github.com/aergoio/aergo@v1.3.1/contract/sqlite3-binding.c (about)

     1  /*
     2  ** This file contains source code of 2 applications:
     3  **
     4  ** 1. SQLite - released as Public Domain
     5  **
     6  ** 2. LiteTree - released under the MIT License
     7  **
     8  ** The content of the last can be verified via making a diff with the sqlite
     9  ** amalgamation version 3.27.2
    10  **
    11  *******************************************************************************
    12   *
    13   *  LiteTree
    14   *
    15   *  Copyright defined in LICENSE.txt
    16   *
    17  *******************************************************************************
    18  ** This file is an amalgamation of many separate C source files from SQLite
    19  ** version 3.27.2.  By combining all the individual C code files into this
    20  ** single large file, the entire code can be compiled as a single translation
    21  ** unit.  This allows many compilers to do optimizations that would not be
    22  ** possible if the files were compiled separately.  Performance improvements
    23  ** of 5% or more are commonly seen when SQLite is compiled as a single
    24  ** translation unit.
    25  **
    26  ** This file is all you need to compile SQLite.  To use SQLite in other
    27  ** programs, you need this file and the "sqlite3.h" header file that defines
    28  ** the programming interface to the SQLite library.  (If you do not have
    29  ** the "sqlite3.h" header file at hand, you will find a copy embedded within
    30  ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
    31  ** of the embedded sqlite3.h header file.) Additional code files may be needed
    32  ** if you want a wrapper to interface SQLite with your choice of programming
    33  ** language. The code for the "sqlite3" command-line shell is also in a
    34  ** separate file. This file contains only code for the core SQLite library.
    35  */
    36  #define SQLITE_CORE 1
    37  #define SQLITE_AMALGAMATION 1
    38  #ifndef SQLITE_PRIVATE
    39  # define SQLITE_PRIVATE static
    40  #endif
    41  
    42  /* defines needed by branching */
    43  #ifndef SQLITE_USE_URI
    44  #define SQLITE_USE_URI  1
    45  #endif
    46  #ifndef SQLITE_ENABLE_JSON1
    47  #define SQLITE_ENABLE_JSON1 1
    48  #endif
    49  #ifndef SQLITE_THREADSAFE
    50  #define SQLITE_THREADSAFE  1
    51  #endif
    52  #ifndef SQLITE_ENABLE_COLUMN_METADATA
    53  #define SQLITE_ENABLE_COLUMN_METADATA 1
    54  #endif
    55  
    56  /************** Begin file ctime.c *******************************************/
    57  /*
    58  ** 2010 February 23
    59  **
    60  ** The author disclaims copyright to this source code.  In place of
    61  ** a legal notice, here is a blessing:
    62  **
    63  **    May you do good and not evil.
    64  **    May you find forgiveness for yourself and forgive others.
    65  **    May you share freely, never taking more than you give.
    66  **
    67  *************************************************************************
    68  **
    69  ** This file implements routines used to report what compile-time options
    70  ** SQLite was built with.
    71  */
    72  
    73  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
    74  
    75  /*
    76  ** Include the configuration header output by 'configure' if we're using the
    77  ** autoconf-based build
    78  */
    79  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
    80  #include "config.h"
    81  #define SQLITECONFIG_H 1
    82  #endif
    83  
    84  /* These macros are provided to "stringify" the value of the define
    85  ** for those options in which the value is meaningful. */
    86  #define CTIMEOPT_VAL_(opt) #opt
    87  #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
    88  
    89  /* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
    90  ** option requires a separate macro because legal values contain a single
    91  ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
    92  #define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
    93  #define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
    94  
    95  /*
    96  ** An array of names of all compile-time options.  This array should 
    97  ** be sorted A-Z.
    98  **
    99  ** This array looks large, but in a typical installation actually uses
   100  ** only a handful of compile-time options, so most times this array is usually
   101  ** rather short and uses little memory space.
   102  */
   103  static const char * const sqlite3azCompileOpt[] = {
   104  
   105  /* 
   106  ** BEGIN CODE GENERATED BY tool/mkctime.tcl 
   107  */
   108  #if SQLITE_32BIT_ROWID
   109    "32BIT_ROWID",
   110  #endif
   111  #if SQLITE_4_BYTE_ALIGNED_MALLOC
   112    "4_BYTE_ALIGNED_MALLOC",
   113  #endif
   114  #if SQLITE_64BIT_STATS
   115    "64BIT_STATS",
   116  #endif
   117  #if SQLITE_ALLOW_COVERING_INDEX_SCAN
   118    "ALLOW_COVERING_INDEX_SCAN",
   119  #endif
   120  #if SQLITE_ALLOW_URI_AUTHORITY
   121    "ALLOW_URI_AUTHORITY",
   122  #endif
   123  #ifdef SQLITE_BITMASK_TYPE
   124    "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
   125  #endif
   126  #if SQLITE_BUG_COMPATIBLE_20160819
   127    "BUG_COMPATIBLE_20160819",
   128  #endif
   129  #if SQLITE_CASE_SENSITIVE_LIKE
   130    "CASE_SENSITIVE_LIKE",
   131  #endif
   132  #if SQLITE_CHECK_PAGES
   133    "CHECK_PAGES",
   134  #endif
   135  #if defined(__clang__) && defined(__clang_major__)
   136    "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
   137                      CTIMEOPT_VAL(__clang_minor__) "."
   138                      CTIMEOPT_VAL(__clang_patchlevel__),
   139  #elif defined(_MSC_VER)
   140    "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
   141  #elif defined(__GNUC__) && defined(__VERSION__)
   142    "COMPILER=gcc-" __VERSION__,
   143  #endif
   144  #if SQLITE_COVERAGE_TEST
   145    "COVERAGE_TEST",
   146  #endif
   147  #if SQLITE_DEBUG
   148    "DEBUG",
   149  #endif
   150  #if SQLITE_DEFAULT_AUTOMATIC_INDEX
   151    "DEFAULT_AUTOMATIC_INDEX",
   152  #endif
   153  #if SQLITE_DEFAULT_AUTOVACUUM
   154    "DEFAULT_AUTOVACUUM",
   155  #endif
   156  #ifdef SQLITE_DEFAULT_CACHE_SIZE
   157    "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
   158  #endif
   159  #if SQLITE_DEFAULT_CKPTFULLFSYNC
   160    "DEFAULT_CKPTFULLFSYNC",
   161  #endif
   162  #ifdef SQLITE_DEFAULT_FILE_FORMAT
   163    "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
   164  #endif
   165  #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
   166    "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
   167  #endif
   168  #if SQLITE_DEFAULT_FOREIGN_KEYS
   169    "DEFAULT_FOREIGN_KEYS",
   170  #endif
   171  #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   172    "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
   173  #endif
   174  #ifdef SQLITE_DEFAULT_LOCKING_MODE
   175    "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
   176  #endif
   177  #ifdef SQLITE_DEFAULT_LOOKASIDE
   178    "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
   179  #endif
   180  #if SQLITE_DEFAULT_MEMSTATUS
   181    "DEFAULT_MEMSTATUS",
   182  #endif
   183  #ifdef SQLITE_DEFAULT_MMAP_SIZE
   184    "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
   185  #endif
   186  #ifdef SQLITE_DEFAULT_PAGE_SIZE
   187    "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
   188  #endif
   189  #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
   190    "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
   191  #endif
   192  #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   193    "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
   194  #endif
   195  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   196    "DEFAULT_RECURSIVE_TRIGGERS",
   197  #endif
   198  #ifdef SQLITE_DEFAULT_ROWEST
   199    "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
   200  #endif
   201  #ifdef SQLITE_DEFAULT_SECTOR_SIZE
   202    "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
   203  #endif
   204  #ifdef SQLITE_DEFAULT_SYNCHRONOUS
   205    "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
   206  #endif
   207  #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
   208    "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
   209  #endif
   210  #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
   211    "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
   212  #endif
   213  #ifdef SQLITE_DEFAULT_WORKER_THREADS
   214    "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
   215  #endif
   216  #if SQLITE_DIRECT_OVERFLOW_READ
   217    "DIRECT_OVERFLOW_READ",
   218  #endif
   219  #if SQLITE_DISABLE_DIRSYNC
   220    "DISABLE_DIRSYNC",
   221  #endif
   222  #if SQLITE_DISABLE_FTS3_UNICODE
   223    "DISABLE_FTS3_UNICODE",
   224  #endif
   225  #if SQLITE_DISABLE_FTS4_DEFERRED
   226    "DISABLE_FTS4_DEFERRED",
   227  #endif
   228  #if SQLITE_DISABLE_INTRINSIC
   229    "DISABLE_INTRINSIC",
   230  #endif
   231  #if SQLITE_DISABLE_LFS
   232    "DISABLE_LFS",
   233  #endif
   234  #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
   235    "DISABLE_PAGECACHE_OVERFLOW_STATS",
   236  #endif
   237  #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
   238    "DISABLE_SKIPAHEAD_DISTINCT",
   239  #endif
   240  #ifdef SQLITE_ENABLE_8_3_NAMES
   241    "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
   242  #endif
   243  #if SQLITE_ENABLE_API_ARMOR
   244    "ENABLE_API_ARMOR",
   245  #endif
   246  #if SQLITE_ENABLE_ATOMIC_WRITE
   247    "ENABLE_ATOMIC_WRITE",
   248  #endif
   249  #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   250    "ENABLE_BATCH_ATOMIC_WRITE",
   251  #endif
   252  #if SQLITE_ENABLE_CEROD
   253    "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
   254  #endif
   255  #if SQLITE_ENABLE_COLUMN_METADATA
   256    "ENABLE_COLUMN_METADATA",
   257  #endif
   258  #if SQLITE_ENABLE_COLUMN_USED_MASK
   259    "ENABLE_COLUMN_USED_MASK",
   260  #endif
   261  #if SQLITE_ENABLE_COSTMULT
   262    "ENABLE_COSTMULT",
   263  #endif
   264  #if SQLITE_ENABLE_CURSOR_HINTS
   265    "ENABLE_CURSOR_HINTS",
   266  #endif
   267  #if SQLITE_ENABLE_DBSTAT_VTAB
   268    "ENABLE_DBSTAT_VTAB",
   269  #endif
   270  #if SQLITE_ENABLE_EXPENSIVE_ASSERT
   271    "ENABLE_EXPENSIVE_ASSERT",
   272  #endif
   273  #if SQLITE_ENABLE_FTS1
   274    "ENABLE_FTS1",
   275  #endif
   276  #if SQLITE_ENABLE_FTS2
   277    "ENABLE_FTS2",
   278  #endif
   279  #if SQLITE_ENABLE_FTS3
   280    "ENABLE_FTS3",
   281  #endif
   282  #if SQLITE_ENABLE_FTS3_PARENTHESIS
   283    "ENABLE_FTS3_PARENTHESIS",
   284  #endif
   285  #if SQLITE_ENABLE_FTS3_TOKENIZER
   286    "ENABLE_FTS3_TOKENIZER",
   287  #endif
   288  #if SQLITE_ENABLE_FTS4
   289    "ENABLE_FTS4",
   290  #endif
   291  #if SQLITE_ENABLE_FTS5
   292    "ENABLE_FTS5",
   293  #endif
   294  #if SQLITE_ENABLE_GEOPOLY
   295    "ENABLE_GEOPOLY",
   296  #endif
   297  #if SQLITE_ENABLE_HIDDEN_COLUMNS
   298    "ENABLE_HIDDEN_COLUMNS",
   299  #endif
   300  #if SQLITE_ENABLE_ICU
   301    "ENABLE_ICU",
   302  #endif
   303  #if SQLITE_ENABLE_IOTRACE
   304    "ENABLE_IOTRACE",
   305  #endif
   306  #if SQLITE_ENABLE_JSON1
   307    "ENABLE_JSON1",
   308  #endif
   309  #if SQLITE_ENABLE_LOAD_EXTENSION
   310    "ENABLE_LOAD_EXTENSION",
   311  #endif
   312  #ifdef SQLITE_ENABLE_LOCKING_STYLE
   313    "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
   314  #endif
   315  #if SQLITE_ENABLE_MEMORY_MANAGEMENT
   316    "ENABLE_MEMORY_MANAGEMENT",
   317  #endif
   318  #if SQLITE_ENABLE_MEMSYS3
   319    "ENABLE_MEMSYS3",
   320  #endif
   321  #if SQLITE_ENABLE_MEMSYS5
   322    "ENABLE_MEMSYS5",
   323  #endif
   324  #if SQLITE_ENABLE_MULTIPLEX
   325    "ENABLE_MULTIPLEX",
   326  #endif
   327  #if SQLITE_ENABLE_NORMALIZE
   328    "ENABLE_NORMALIZE",
   329  #endif
   330  #if SQLITE_ENABLE_NULL_TRIM
   331    "ENABLE_NULL_TRIM",
   332  #endif
   333  #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   334    "ENABLE_OVERSIZE_CELL_CHECK",
   335  #endif
   336  #if SQLITE_ENABLE_PREUPDATE_HOOK
   337    "ENABLE_PREUPDATE_HOOK",
   338  #endif
   339  #if SQLITE_ENABLE_QPSG
   340    "ENABLE_QPSG",
   341  #endif
   342  #if SQLITE_ENABLE_RBU
   343    "ENABLE_RBU",
   344  #endif
   345  #if SQLITE_ENABLE_RTREE
   346    "ENABLE_RTREE",
   347  #endif
   348  #if SQLITE_ENABLE_SELECTTRACE
   349    "ENABLE_SELECTTRACE",
   350  #endif
   351  #if SQLITE_ENABLE_SESSION
   352    "ENABLE_SESSION",
   353  #endif
   354  #if SQLITE_ENABLE_SNAPSHOT
   355    "ENABLE_SNAPSHOT",
   356  #endif
   357  #if SQLITE_ENABLE_SORTER_REFERENCES
   358    "ENABLE_SORTER_REFERENCES",
   359  #endif
   360  #if SQLITE_ENABLE_SQLLOG
   361    "ENABLE_SQLLOG",
   362  #endif
   363  #if defined(SQLITE_ENABLE_STAT4)
   364    "ENABLE_STAT4",
   365  #elif defined(SQLITE_ENABLE_STAT3)
   366    "ENABLE_STAT3",
   367  #endif
   368  #if SQLITE_ENABLE_STMTVTAB
   369    "ENABLE_STMTVTAB",
   370  #endif
   371  #if SQLITE_ENABLE_STMT_SCANSTATUS
   372    "ENABLE_STMT_SCANSTATUS",
   373  #endif
   374  #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
   375    "ENABLE_UNKNOWN_SQL_FUNCTION",
   376  #endif
   377  #if SQLITE_ENABLE_UNLOCK_NOTIFY
   378    "ENABLE_UNLOCK_NOTIFY",
   379  #endif
   380  #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   381    "ENABLE_UPDATE_DELETE_LIMIT",
   382  #endif
   383  #if SQLITE_ENABLE_URI_00_ERROR
   384    "ENABLE_URI_00_ERROR",
   385  #endif
   386  #if SQLITE_ENABLE_VFSTRACE
   387    "ENABLE_VFSTRACE",
   388  #endif
   389  #if SQLITE_ENABLE_WHERETRACE
   390    "ENABLE_WHERETRACE",
   391  #endif
   392  #if SQLITE_ENABLE_ZIPVFS
   393    "ENABLE_ZIPVFS",
   394  #endif
   395  #if SQLITE_EXPLAIN_ESTIMATED_ROWS
   396    "EXPLAIN_ESTIMATED_ROWS",
   397  #endif
   398  #if SQLITE_EXTRA_IFNULLROW
   399    "EXTRA_IFNULLROW",
   400  #endif
   401  #ifdef SQLITE_EXTRA_INIT
   402    "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
   403  #endif
   404  #ifdef SQLITE_EXTRA_SHUTDOWN
   405    "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
   406  #endif
   407  #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
   408    "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
   409  #endif
   410  #if SQLITE_FTS5_ENABLE_TEST_MI
   411    "FTS5_ENABLE_TEST_MI",
   412  #endif
   413  #if SQLITE_FTS5_NO_WITHOUT_ROWID
   414    "FTS5_NO_WITHOUT_ROWID",
   415  #endif
   416  #if SQLITE_HAS_CODEC
   417    "HAS_CODEC",
   418  #endif
   419  #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
   420    "HAVE_ISNAN",
   421  #endif
   422  #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   423    "HOMEGROWN_RECURSIVE_MUTEX",
   424  #endif
   425  #if SQLITE_IGNORE_AFP_LOCK_ERRORS
   426    "IGNORE_AFP_LOCK_ERRORS",
   427  #endif
   428  #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   429    "IGNORE_FLOCK_LOCK_ERRORS",
   430  #endif
   431  #if SQLITE_INLINE_MEMCPY
   432    "INLINE_MEMCPY",
   433  #endif
   434  #if SQLITE_INT64_TYPE
   435    "INT64_TYPE",
   436  #endif
   437  #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   438    "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
   439  #endif
   440  #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
   441    "LIKE_DOESNT_MATCH_BLOBS",
   442  #endif
   443  #if SQLITE_LOCK_TRACE
   444    "LOCK_TRACE",
   445  #endif
   446  #if SQLITE_LOG_CACHE_SPILL
   447    "LOG_CACHE_SPILL",
   448  #endif
   449  #ifdef SQLITE_MALLOC_SOFT_LIMIT
   450    "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
   451  #endif
   452  #ifdef SQLITE_MAX_ATTACHED
   453    "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
   454  #endif
   455  #ifdef SQLITE_MAX_COLUMN
   456    "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
   457  #endif
   458  #ifdef SQLITE_MAX_COMPOUND_SELECT
   459    "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
   460  #endif
   461  #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
   462    "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
   463  #endif
   464  #ifdef SQLITE_MAX_EXPR_DEPTH
   465    "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
   466  #endif
   467  #ifdef SQLITE_MAX_FUNCTION_ARG
   468    "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
   469  #endif
   470  #ifdef SQLITE_MAX_LENGTH
   471    "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
   472  #endif
   473  #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
   474    "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
   475  #endif
   476  #ifdef SQLITE_MAX_MEMORY
   477    "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
   478  #endif
   479  #ifdef SQLITE_MAX_MMAP_SIZE
   480    "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
   481  #endif
   482  #ifdef SQLITE_MAX_MMAP_SIZE_
   483    "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
   484  #endif
   485  #ifdef SQLITE_MAX_PAGE_COUNT
   486    "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
   487  #endif
   488  #ifdef SQLITE_MAX_PAGE_SIZE
   489    "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
   490  #endif
   491  #ifdef SQLITE_MAX_SCHEMA_RETRY
   492    "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
   493  #endif
   494  #ifdef SQLITE_MAX_SQL_LENGTH
   495    "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
   496  #endif
   497  #ifdef SQLITE_MAX_TRIGGER_DEPTH
   498    "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
   499  #endif
   500  #ifdef SQLITE_MAX_VARIABLE_NUMBER
   501    "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
   502  #endif
   503  #ifdef SQLITE_MAX_VDBE_OP
   504    "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
   505  #endif
   506  #ifdef SQLITE_MAX_WORKER_THREADS
   507    "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
   508  #endif
   509  #if SQLITE_MEMDEBUG
   510    "MEMDEBUG",
   511  #endif
   512  #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   513    "MIXED_ENDIAN_64BIT_FLOAT",
   514  #endif
   515  #if SQLITE_MMAP_READWRITE
   516    "MMAP_READWRITE",
   517  #endif
   518  #if SQLITE_MUTEX_NOOP
   519    "MUTEX_NOOP",
   520  #endif
   521  #if SQLITE_MUTEX_NREF
   522    "MUTEX_NREF",
   523  #endif
   524  #if SQLITE_MUTEX_OMIT
   525    "MUTEX_OMIT",
   526  #endif
   527  #if SQLITE_MUTEX_PTHREADS
   528    "MUTEX_PTHREADS",
   529  #endif
   530  #if SQLITE_MUTEX_W32
   531    "MUTEX_W32",
   532  #endif
   533  #if SQLITE_NEED_ERR_NAME
   534    "NEED_ERR_NAME",
   535  #endif
   536  #if SQLITE_NOINLINE
   537    "NOINLINE",
   538  #endif
   539  #if SQLITE_NO_SYNC
   540    "NO_SYNC",
   541  #endif
   542  #if SQLITE_OMIT_ALTERTABLE
   543    "OMIT_ALTERTABLE",
   544  #endif
   545  #if SQLITE_OMIT_ANALYZE
   546    "OMIT_ANALYZE",
   547  #endif
   548  #if SQLITE_OMIT_ATTACH
   549    "OMIT_ATTACH",
   550  #endif
   551  #if SQLITE_OMIT_AUTHORIZATION
   552    "OMIT_AUTHORIZATION",
   553  #endif
   554  #if SQLITE_OMIT_AUTOINCREMENT
   555    "OMIT_AUTOINCREMENT",
   556  #endif
   557  #if SQLITE_OMIT_AUTOINIT
   558    "OMIT_AUTOINIT",
   559  #endif
   560  #if SQLITE_OMIT_AUTOMATIC_INDEX
   561    "OMIT_AUTOMATIC_INDEX",
   562  #endif
   563  #if SQLITE_OMIT_AUTORESET
   564    "OMIT_AUTORESET",
   565  #endif
   566  #if SQLITE_OMIT_AUTOVACUUM
   567    "OMIT_AUTOVACUUM",
   568  #endif
   569  #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
   570    "OMIT_BETWEEN_OPTIMIZATION",
   571  #endif
   572  #if SQLITE_OMIT_BLOB_LITERAL
   573    "OMIT_BLOB_LITERAL",
   574  #endif
   575  #if SQLITE_OMIT_BTREECOUNT
   576    "OMIT_BTREECOUNT",
   577  #endif
   578  #if SQLITE_OMIT_CAST
   579    "OMIT_CAST",
   580  #endif
   581  #if SQLITE_OMIT_CHECK
   582    "OMIT_CHECK",
   583  #endif
   584  #if SQLITE_OMIT_COMPLETE
   585    "OMIT_COMPLETE",
   586  #endif
   587  #if SQLITE_OMIT_COMPOUND_SELECT
   588    "OMIT_COMPOUND_SELECT",
   589  #endif
   590  #if SQLITE_OMIT_CONFLICT_CLAUSE
   591    "OMIT_CONFLICT_CLAUSE",
   592  #endif
   593  #if SQLITE_OMIT_CTE
   594    "OMIT_CTE",
   595  #endif
   596  #if SQLITE_OMIT_DATETIME_FUNCS
   597    "OMIT_DATETIME_FUNCS",
   598  #endif
   599  #if SQLITE_OMIT_DECLTYPE
   600    "OMIT_DECLTYPE",
   601  #endif
   602  #if SQLITE_OMIT_DEPRECATED
   603    "OMIT_DEPRECATED",
   604  #endif
   605  #if SQLITE_OMIT_DISKIO
   606    "OMIT_DISKIO",
   607  #endif
   608  #if SQLITE_OMIT_EXPLAIN
   609    "OMIT_EXPLAIN",
   610  #endif
   611  #if SQLITE_OMIT_FLAG_PRAGMAS
   612    "OMIT_FLAG_PRAGMAS",
   613  #endif
   614  #if SQLITE_OMIT_FLOATING_POINT
   615    "OMIT_FLOATING_POINT",
   616  #endif
   617  #if SQLITE_OMIT_FOREIGN_KEY
   618    "OMIT_FOREIGN_KEY",
   619  #endif
   620  #if SQLITE_OMIT_GET_TABLE
   621    "OMIT_GET_TABLE",
   622  #endif
   623  #if SQLITE_OMIT_HEX_INTEGER
   624    "OMIT_HEX_INTEGER",
   625  #endif
   626  #if SQLITE_OMIT_INCRBLOB
   627    "OMIT_INCRBLOB",
   628  #endif
   629  #if SQLITE_OMIT_INTEGRITY_CHECK
   630    "OMIT_INTEGRITY_CHECK",
   631  #endif
   632  #if SQLITE_OMIT_LIKE_OPTIMIZATION
   633    "OMIT_LIKE_OPTIMIZATION",
   634  #endif
   635  #if SQLITE_OMIT_LOAD_EXTENSION
   636    "OMIT_LOAD_EXTENSION",
   637  #endif
   638  #if SQLITE_OMIT_LOCALTIME
   639    "OMIT_LOCALTIME",
   640  #endif
   641  #if SQLITE_OMIT_LOOKASIDE
   642    "OMIT_LOOKASIDE",
   643  #endif
   644  #if SQLITE_OMIT_MEMORYDB
   645    "OMIT_MEMORYDB",
   646  #endif
   647  #if SQLITE_OMIT_OR_OPTIMIZATION
   648    "OMIT_OR_OPTIMIZATION",
   649  #endif
   650  #if SQLITE_OMIT_PAGER_PRAGMAS
   651    "OMIT_PAGER_PRAGMAS",
   652  #endif
   653  #if SQLITE_OMIT_PARSER_TRACE
   654    "OMIT_PARSER_TRACE",
   655  #endif
   656  #if SQLITE_OMIT_POPEN
   657    "OMIT_POPEN",
   658  #endif
   659  #if SQLITE_OMIT_PRAGMA
   660    "OMIT_PRAGMA",
   661  #endif
   662  #if SQLITE_OMIT_PROGRESS_CALLBACK
   663    "OMIT_PROGRESS_CALLBACK",
   664  #endif
   665  #if SQLITE_OMIT_QUICKBALANCE
   666    "OMIT_QUICKBALANCE",
   667  #endif
   668  #if SQLITE_OMIT_REINDEX
   669    "OMIT_REINDEX",
   670  #endif
   671  #if SQLITE_OMIT_SCHEMA_PRAGMAS
   672    "OMIT_SCHEMA_PRAGMAS",
   673  #endif
   674  #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   675    "OMIT_SCHEMA_VERSION_PRAGMAS",
   676  #endif
   677  #if SQLITE_OMIT_SHARED_CACHE
   678    "OMIT_SHARED_CACHE",
   679  #endif
   680  #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
   681    "OMIT_SHUTDOWN_DIRECTORIES",
   682  #endif
   683  #if SQLITE_OMIT_SUBQUERY
   684    "OMIT_SUBQUERY",
   685  #endif
   686  #if SQLITE_OMIT_TCL_VARIABLE
   687    "OMIT_TCL_VARIABLE",
   688  #endif
   689  #if SQLITE_OMIT_TEMPDB
   690    "OMIT_TEMPDB",
   691  #endif
   692  #if SQLITE_OMIT_TEST_CONTROL
   693    "OMIT_TEST_CONTROL",
   694  #endif
   695  #if SQLITE_OMIT_TRACE
   696    "OMIT_TRACE",
   697  #endif
   698  #if SQLITE_OMIT_TRIGGER
   699    "OMIT_TRIGGER",
   700  #endif
   701  #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   702    "OMIT_TRUNCATE_OPTIMIZATION",
   703  #endif
   704  #if SQLITE_OMIT_UTF16
   705    "OMIT_UTF16",
   706  #endif
   707  #if SQLITE_OMIT_VACUUM
   708    "OMIT_VACUUM",
   709  #endif
   710  #if SQLITE_OMIT_VIEW
   711    "OMIT_VIEW",
   712  #endif
   713  #if SQLITE_OMIT_VIRTUALTABLE
   714    "OMIT_VIRTUALTABLE",
   715  #endif
   716  #if SQLITE_OMIT_WAL
   717    "OMIT_WAL",
   718  #endif
   719  #if SQLITE_OMIT_WSD
   720    "OMIT_WSD",
   721  #endif
   722  #if SQLITE_OMIT_XFER_OPT
   723    "OMIT_XFER_OPT",
   724  #endif
   725  #if SQLITE_PCACHE_SEPARATE_HEADER
   726    "PCACHE_SEPARATE_HEADER",
   727  #endif
   728  #if SQLITE_PERFORMANCE_TRACE
   729    "PERFORMANCE_TRACE",
   730  #endif
   731  #if SQLITE_POWERSAFE_OVERWRITE
   732    "POWERSAFE_OVERWRITE",
   733  #endif
   734  #if SQLITE_PREFER_PROXY_LOCKING
   735    "PREFER_PROXY_LOCKING",
   736  #endif
   737  #if SQLITE_PROXY_DEBUG
   738    "PROXY_DEBUG",
   739  #endif
   740  #if SQLITE_REVERSE_UNORDERED_SELECTS
   741    "REVERSE_UNORDERED_SELECTS",
   742  #endif
   743  #if SQLITE_RTREE_INT_ONLY
   744    "RTREE_INT_ONLY",
   745  #endif
   746  #if SQLITE_SECURE_DELETE
   747    "SECURE_DELETE",
   748  #endif
   749  #if SQLITE_SMALL_STACK
   750    "SMALL_STACK",
   751  #endif
   752  #ifdef SQLITE_SORTER_PMASZ
   753    "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
   754  #endif
   755  #if SQLITE_SOUNDEX
   756    "SOUNDEX",
   757  #endif
   758  #ifdef SQLITE_STAT4_SAMPLES
   759    "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
   760  #endif
   761  #ifdef SQLITE_STMTJRNL_SPILL
   762    "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
   763  #endif
   764  #if SQLITE_SUBSTR_COMPATIBILITY
   765    "SUBSTR_COMPATIBILITY",
   766  #endif
   767  #if SQLITE_SYSTEM_MALLOC
   768    "SYSTEM_MALLOC",
   769  #endif
   770  #if SQLITE_TCL
   771    "TCL",
   772  #endif
   773  #ifdef SQLITE_TEMP_STORE
   774    "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
   775  #endif
   776  #if SQLITE_TEST
   777    "TEST",
   778  #endif
   779  #if defined(SQLITE_THREADSAFE)
   780    "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
   781  #elif defined(THREADSAFE)
   782    "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
   783  #else
   784    "THREADSAFE=1",
   785  #endif
   786  #if SQLITE_UNLINK_AFTER_CLOSE
   787    "UNLINK_AFTER_CLOSE",
   788  #endif
   789  #if SQLITE_UNTESTABLE
   790    "UNTESTABLE",
   791  #endif
   792  #if SQLITE_USER_AUTHENTICATION
   793    "USER_AUTHENTICATION",
   794  #endif
   795  #if SQLITE_USE_ALLOCA
   796    "USE_ALLOCA",
   797  #endif
   798  #if SQLITE_USE_FCNTL_TRACE
   799    "USE_FCNTL_TRACE",
   800  #endif
   801  #if SQLITE_USE_URI
   802    "USE_URI",
   803  #endif
   804  #if SQLITE_VDBE_COVERAGE
   805    "VDBE_COVERAGE",
   806  #endif
   807  #if SQLITE_WIN32_MALLOC
   808    "WIN32_MALLOC",
   809  #endif
   810  #if SQLITE_ZERO_MALLOC
   811    "ZERO_MALLOC",
   812  #endif
   813  /* 
   814  ** END CODE GENERATED BY tool/mkctime.tcl 
   815  */
   816  };
   817  
   818  SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
   819    *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
   820    return (const char**)sqlite3azCompileOpt;
   821  }
   822  
   823  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   824  
   825  /************** End of ctime.c ***********************************************/
   826  /************** Begin file sqliteInt.h ***************************************/
   827  /*
   828  ** 2001 September 15
   829  **
   830  ** The author disclaims copyright to this source code.  In place of
   831  ** a legal notice, here is a blessing:
   832  **
   833  **    May you do good and not evil.
   834  **    May you find forgiveness for yourself and forgive others.
   835  **    May you share freely, never taking more than you give.
   836  **
   837  *************************************************************************
   838  ** Internal interface definitions for SQLite.
   839  **
   840  */
   841  #ifndef SQLITEINT_H
   842  #define SQLITEINT_H
   843  
   844  /* Special Comments:
   845  **
   846  ** Some comments have special meaning to the tools that measure test
   847  ** coverage:
   848  **
   849  **    NO_TEST                     - The branches on this line are not
   850  **                                  measured by branch coverage.  This is
   851  **                                  used on lines of code that actually
   852  **                                  implement parts of coverage testing.
   853  **
   854  **    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
   855  **                                  and the correct answer is still obtained,
   856  **                                  though perhaps more slowly.
   857  **
   858  **    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
   859  **                                  and the correct answer is still obtained,
   860  **                                  though perhaps more slowly.
   861  **
   862  **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
   863  **                                  that would be harmless and undetectable
   864  **                                  if it did occur.  
   865  **
   866  ** In all cases, the special comment must be enclosed in the usual
   867  ** slash-asterisk...asterisk-slash comment marks, with no spaces between the 
   868  ** asterisks and the comment text.
   869  */
   870  
   871  /*
   872  ** Make sure the Tcl calling convention macro is defined.  This macro is
   873  ** only used by test code and Tcl integration code.
   874  */
   875  #ifndef SQLITE_TCLAPI
   876  #  define SQLITE_TCLAPI
   877  #endif
   878  
   879  /*
   880  ** Include the header file used to customize the compiler options for MSVC.
   881  ** This should be done first so that it can successfully prevent spurious
   882  ** compiler warnings due to subsequent content in this file and other files
   883  ** that are included by this file.
   884  */
   885  /************** Include msvc.h in the middle of sqliteInt.h ******************/
   886  /************** Begin file msvc.h ********************************************/
   887  /*
   888  ** 2015 January 12
   889  **
   890  ** The author disclaims copyright to this source code.  In place of
   891  ** a legal notice, here is a blessing:
   892  **
   893  **    May you do good and not evil.
   894  **    May you find forgiveness for yourself and forgive others.
   895  **    May you share freely, never taking more than you give.
   896  **
   897  ******************************************************************************
   898  **
   899  ** This file contains code that is specific to MSVC.
   900  */
   901  #ifndef SQLITE_MSVC_H
   902  #define SQLITE_MSVC_H
   903  
   904  #if defined(_MSC_VER)
   905  #pragma warning(disable : 4054)
   906  #pragma warning(disable : 4055)
   907  #pragma warning(disable : 4100)
   908  #pragma warning(disable : 4127)
   909  #pragma warning(disable : 4130)
   910  #pragma warning(disable : 4152)
   911  #pragma warning(disable : 4189)
   912  #pragma warning(disable : 4206)
   913  #pragma warning(disable : 4210)
   914  #pragma warning(disable : 4232)
   915  #pragma warning(disable : 4244)
   916  #pragma warning(disable : 4305)
   917  #pragma warning(disable : 4306)
   918  #pragma warning(disable : 4702)
   919  #pragma warning(disable : 4706)
   920  #pragma warning(disable : 4996)
   921  #endif /* defined(_MSC_VER) */
   922  
   923  #endif /* SQLITE_MSVC_H */
   924  
   925  /************** End of msvc.h ************************************************/
   926  /************** Continuing where we left off in sqliteInt.h ******************/
   927  
   928  /*
   929  ** Special setup for VxWorks
   930  */
   931  /************** Include vxworks.h in the middle of sqliteInt.h ***************/
   932  /************** Begin file vxworks.h *****************************************/
   933  /*
   934  ** 2015-03-02
   935  **
   936  ** The author disclaims copyright to this source code.  In place of
   937  ** a legal notice, here is a blessing:
   938  **
   939  **    May you do good and not evil.
   940  **    May you find forgiveness for yourself and forgive others.
   941  **    May you share freely, never taking more than you give.
   942  **
   943  ******************************************************************************
   944  **
   945  ** This file contains code that is specific to Wind River's VxWorks
   946  */
   947  #if defined(__RTP__) || defined(_WRS_KERNEL)
   948  /* This is VxWorks.  Set up things specially for that OS
   949  */
   950  #include <vxWorks.h>
   951  #include <pthread.h>  /* amalgamator: dontcache */
   952  #define OS_VXWORKS 1
   953  #define SQLITE_OS_OTHER 0
   954  #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
   955  #define SQLITE_OMIT_LOAD_EXTENSION 1
   956  #define SQLITE_ENABLE_LOCKING_STYLE 0
   957  #define HAVE_UTIME 1
   958  #else
   959  /* This is not VxWorks. */
   960  #define OS_VXWORKS 0
   961  #define HAVE_FCHOWN 1
   962  #define HAVE_READLINK 1
   963  #define HAVE_LSTAT 1
   964  #endif /* defined(_WRS_KERNEL) */
   965  
   966  /************** End of vxworks.h *********************************************/
   967  /************** Continuing where we left off in sqliteInt.h ******************/
   968  
   969  /*
   970  ** These #defines should enable >2GB file support on POSIX if the
   971  ** underlying operating system supports it.  If the OS lacks
   972  ** large file support, or if the OS is windows, these should be no-ops.
   973  **
   974  ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
   975  ** system #includes.  Hence, this block of code must be the very first
   976  ** code in all source files.
   977  **
   978  ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   979  ** on the compiler command line.  This is necessary if you are compiling
   980  ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
   981  ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
   982  ** without this option, LFS is enable.  But LFS does not exist in the kernel
   983  ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
   984  ** portability you should omit LFS.
   985  **
   986  ** The previous paragraph was written in 2005.  (This paragraph is written
   987  ** on 2008-11-28.) These days, all Linux kernels support large files, so
   988  ** you should probably leave LFS enabled.  But some embedded platforms might
   989  ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   990  **
   991  ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
   992  */
   993  #ifndef SQLITE_DISABLE_LFS
   994  # define _LARGE_FILE       1
   995  # ifndef _FILE_OFFSET_BITS
   996  #   define _FILE_OFFSET_BITS 64
   997  # endif
   998  # define _LARGEFILE_SOURCE 1
   999  #endif
  1000  
  1001  /* The GCC_VERSION and MSVC_VERSION macros are used to
  1002  ** conditionally include optimizations for each of these compilers.  A
  1003  ** value of 0 means that compiler is not being used.  The
  1004  ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  1005  ** optimizations, and hence set all compiler macros to 0
  1006  **
  1007  ** There was once also a CLANG_VERSION macro.  However, we learn that the
  1008  ** version numbers in clang are for "marketing" only and are inconsistent
  1009  ** and unreliable.  Fortunately, all versions of clang also recognize the
  1010  ** gcc version numbers and have reasonable settings for gcc version numbers,
  1011  ** so the GCC_VERSION macro will be set to a correct non-zero value even
  1012  ** when compiling with clang.
  1013  */
  1014  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  1015  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  1016  #else
  1017  # define GCC_VERSION 0
  1018  #endif
  1019  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  1020  # define MSVC_VERSION _MSC_VER
  1021  #else
  1022  # define MSVC_VERSION 0
  1023  #endif
  1024  
  1025  /* Needed for various definitions... */
  1026  #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  1027  # define _GNU_SOURCE
  1028  #endif
  1029  
  1030  #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  1031  # define _BSD_SOURCE
  1032  #endif
  1033  
  1034  /*
  1035  ** For MinGW, check to see if we can include the header file containing its
  1036  ** version information, among other things.  Normally, this internal MinGW
  1037  ** header file would [only] be included automatically by other MinGW header
  1038  ** files; however, the contained version information is now required by this
  1039  ** header file to work around binary compatibility issues (see below) and
  1040  ** this is the only known way to reliably obtain it.  This entire #if block
  1041  ** would be completely unnecessary if there was any other way of detecting
  1042  ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  1043  ** some MinGW-specific macros).  When compiling for MinGW, either the
  1044  ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  1045  ** defined; otherwise, detection of conditions specific to MinGW will be
  1046  ** disabled.
  1047  */
  1048  #if defined(_HAVE_MINGW_H)
  1049  # include "mingw.h"
  1050  #elif defined(_HAVE__MINGW_H)
  1051  # include "_mingw.h"
  1052  #endif
  1053  
  1054  /*
  1055  ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1056  ** define is required to maintain binary compatibility with the MSVC runtime
  1057  ** library in use (e.g. for Windows XP).
  1058  */
  1059  #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1060      defined(_WIN32) && !defined(_WIN64) && \
  1061      defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1062      defined(__MSVCRT__)
  1063  # define _USE_32BIT_TIME_T
  1064  #endif
  1065  
  1066  /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
  1067  ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
  1068  ** MinGW.
  1069  */
  1070  /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1071  /************** Begin file sqlite3.h *****************************************/
  1072  /*
  1073  ** 2001-09-15
  1074  **
  1075  ** The author disclaims copyright to this source code.  In place of
  1076  ** a legal notice, here is a blessing:
  1077  **
  1078  **    May you do good and not evil.
  1079  **    May you find forgiveness for yourself and forgive others.
  1080  **    May you share freely, never taking more than you give.
  1081  **
  1082  *************************************************************************
  1083  ** This header file defines the interface that the SQLite library
  1084  ** presents to client programs.  If a C-function, structure, datatype,
  1085  ** or constant definition does not appear in this file, then it is
  1086  ** not a published API of SQLite, is subject to change without
  1087  ** notice, and should not be referenced by programs that use SQLite.
  1088  **
  1089  ** Some of the definitions that are in this file are marked as
  1090  ** "experimental".  Experimental interfaces are normally new
  1091  ** features recently added to SQLite.  We do not anticipate changes
  1092  ** to experimental interfaces but reserve the right to make minor changes
  1093  ** if experience from use "in the wild" suggest such changes are prudent.
  1094  **
  1095  ** The official C-language API documentation for SQLite is derived
  1096  ** from comments in this file.  This file is the authoritative source
  1097  ** on how SQLite interfaces are supposed to operate.
  1098  **
  1099  ** The name of this file under configuration management is "sqlite.h.in".
  1100  ** The makefile makes some minor changes to this file (such as inserting
  1101  ** the version number) and changes its name to "sqlite3.h" as
  1102  ** part of the build process.
  1103  */
  1104  #ifndef SQLITE3_H
  1105  #define SQLITE3_H
  1106  #include <stdarg.h>     /* Needed for the definition of va_list */
  1107  
  1108  /*
  1109  ** Make sure we can call this stuff from C++.
  1110  */
  1111  #if 0
  1112  extern "C" {
  1113  #endif
  1114  
  1115  
  1116  /*
  1117  ** Provide the ability to override linkage features of the interface.
  1118  */
  1119  #ifndef SQLITE_EXTERN
  1120  # define SQLITE_EXTERN extern
  1121  #endif
  1122  #ifndef SQLITE_API
  1123  # define SQLITE_API
  1124  #endif
  1125  #ifndef SQLITE_CDECL
  1126  # define SQLITE_CDECL
  1127  #endif
  1128  #ifndef SQLITE_APICALL
  1129  # define SQLITE_APICALL
  1130  #endif
  1131  #ifndef SQLITE_STDCALL
  1132  # define SQLITE_STDCALL SQLITE_APICALL
  1133  #endif
  1134  #ifndef SQLITE_CALLBACK
  1135  # define SQLITE_CALLBACK
  1136  #endif
  1137  #ifndef SQLITE_SYSAPI
  1138  # define SQLITE_SYSAPI
  1139  #endif
  1140  
  1141  /*
  1142  ** These no-op macros are used in front of interfaces to mark those
  1143  ** interfaces as either deprecated or experimental.  New applications
  1144  ** should not use deprecated interfaces - they are supported for backwards
  1145  ** compatibility only.  Application writers should be aware that
  1146  ** experimental interfaces are subject to change in point releases.
  1147  **
  1148  ** These macros used to resolve to various kinds of compiler magic that
  1149  ** would generate warning messages when they were used.  But that
  1150  ** compiler magic ended up generating such a flurry of bug reports
  1151  ** that we have taken it all out and gone back to using simple
  1152  ** noop macros.
  1153  */
  1154  #define SQLITE_DEPRECATED
  1155  #define SQLITE_EXPERIMENTAL
  1156  
  1157  /*
  1158  ** Ensure these symbols were not defined by some previous header file.
  1159  */
  1160  #ifdef SQLITE_VERSION
  1161  # undef SQLITE_VERSION
  1162  #endif
  1163  #ifdef SQLITE_VERSION_NUMBER
  1164  # undef SQLITE_VERSION_NUMBER
  1165  #endif
  1166  
  1167  /*
  1168  ** CAPI3REF: Compile-Time Library Version Numbers
  1169  **
  1170  ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1171  ** evaluates to a string literal that is the SQLite version in the
  1172  ** format "X.Y.Z" where X is the major version number (always 3 for
  1173  ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1174  ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1175  ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1176  ** numbers used in [SQLITE_VERSION].)^
  1177  ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1178  ** be larger than the release from which it is derived.  Either Y will
  1179  ** be held constant and Z will be incremented or else Y will be incremented
  1180  ** and Z will be reset to zero.
  1181  **
  1182  ** Since [version 3.6.18] ([dateof:3.6.18]), 
  1183  ** SQLite source code has been stored in the
  1184  ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1185  ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
  1186  ** a string which identifies a particular check-in of SQLite
  1187  ** within its configuration management system.  ^The SQLITE_SOURCE_ID
  1188  ** string contains the date and time of the check-in (UTC) and a SHA1
  1189  ** or SHA3-256 hash of the entire source tree.  If the source code has
  1190  ** been edited in any way since it was last checked in, then the last
  1191  ** four hexadecimal digits of the hash may be modified.
  1192  **
  1193  ** See also: [sqlite3_libversion()],
  1194  ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1195  ** [sqlite_version()] and [sqlite_source_id()].
  1196  */
  1197  #define SQLITE_VERSION        "3.27.2"
  1198  #define SQLITE_VERSION_NUMBER 3027002
  1199  #define SQLITE_SOURCE_ID      "2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7"
  1200  
  1201  /*
  1202  ** CAPI3REF: Run-Time Library Version Numbers
  1203  ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1204  **
  1205  ** These interfaces provide the same information as the [SQLITE_VERSION],
  1206  ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1207  ** but are associated with the library instead of the header file.  ^(Cautious
  1208  ** programmers might include assert() statements in their application to
  1209  ** verify that values returned by these interfaces match the macros in
  1210  ** the header, and thus ensure that the application is
  1211  ** compiled with matching library and header files.
  1212  **
  1213  ** <blockquote><pre>
  1214  ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1215  ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1216  ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1217  ** </pre></blockquote>)^
  1218  **
  1219  ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1220  ** macro.  ^The sqlite3_libversion() function returns a pointer to the
  1221  ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
  1222  ** function is provided for use in DLLs since DLL users usually do not have
  1223  ** direct access to string constants within the DLL.  ^The
  1224  ** sqlite3_libversion_number() function returns an integer equal to
  1225  ** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns 
  1226  ** a pointer to a string constant whose value is the same as the 
  1227  ** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
  1228  ** using an edited copy of [the amalgamation], then the last four characters
  1229  ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1230  **
  1231  ** See also: [sqlite_version()] and [sqlite_source_id()].
  1232  */
  1233  SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1234  SQLITE_API const char *sqlite3_libversion(void);
  1235  SQLITE_API const char *sqlite3_sourceid(void);
  1236  SQLITE_API int sqlite3_libversion_number(void);
  1237  
  1238  /*
  1239  ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1240  **
  1241  ** ^The sqlite3_compileoption_used() function returns 0 or 1 
  1242  ** indicating whether the specified option was defined at 
  1243  ** compile time.  ^The SQLITE_ prefix may be omitted from the 
  1244  ** option name passed to sqlite3_compileoption_used().  
  1245  **
  1246  ** ^The sqlite3_compileoption_get() function allows iterating
  1247  ** over the list of options that were defined at compile time by
  1248  ** returning the N-th compile time option string.  ^If N is out of range,
  1249  ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
  1250  ** prefix is omitted from any strings returned by 
  1251  ** sqlite3_compileoption_get().
  1252  **
  1253  ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1254  ** and sqlite3_compileoption_get() may be omitted by specifying the 
  1255  ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1256  **
  1257  ** See also: SQL functions [sqlite_compileoption_used()] and
  1258  ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1259  */
  1260  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1261  SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1262  SQLITE_API const char *sqlite3_compileoption_get(int N);
  1263  #endif
  1264  
  1265  /*
  1266  ** CAPI3REF: Test To See If The Library Is Threadsafe
  1267  **
  1268  ** ^The sqlite3_threadsafe() function returns zero if and only if
  1269  ** SQLite was compiled with mutexing code omitted due to the
  1270  ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1271  **
  1272  ** SQLite can be compiled with or without mutexes.  When
  1273  ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1274  ** are enabled and SQLite is threadsafe.  When the
  1275  ** [SQLITE_THREADSAFE] macro is 0, 
  1276  ** the mutexes are omitted.  Without the mutexes, it is not safe
  1277  ** to use SQLite concurrently from more than one thread.
  1278  **
  1279  ** Enabling mutexes incurs a measurable performance penalty.
  1280  ** So if speed is of utmost importance, it makes sense to disable
  1281  ** the mutexes.  But for maximum safety, mutexes should be enabled.
  1282  ** ^The default behavior is for mutexes to be enabled.
  1283  **
  1284  ** This interface can be used by an application to make sure that the
  1285  ** version of SQLite that it is linking against was compiled with
  1286  ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1287  **
  1288  ** This interface only reports on the compile-time mutex setting
  1289  ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
  1290  ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1291  ** can be fully or partially disabled using a call to [sqlite3_config()]
  1292  ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1293  ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
  1294  ** sqlite3_threadsafe() function shows only the compile-time setting of
  1295  ** thread safety, not any run-time changes to that setting made by
  1296  ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1297  ** is unchanged by calls to sqlite3_config().)^
  1298  **
  1299  ** See the [threading mode] documentation for additional information.
  1300  */
  1301  SQLITE_API int sqlite3_threadsafe(void);
  1302  
  1303  /*
  1304  ** CAPI3REF: Database Connection Handle
  1305  ** KEYWORDS: {database connection} {database connections}
  1306  **
  1307  ** Each open SQLite database is represented by a pointer to an instance of
  1308  ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
  1309  ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
  1310  ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1311  ** and [sqlite3_close_v2()] are its destructors.  There are many other
  1312  ** interfaces (such as
  1313  ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1314  ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1315  ** sqlite3 object.
  1316  */
  1317  typedef struct sqlite3 sqlite3;
  1318  
  1319  /*
  1320  ** CAPI3REF: 64-Bit Integer Types
  1321  ** KEYWORDS: sqlite_int64 sqlite_uint64
  1322  **
  1323  ** Because there is no cross-platform way to specify 64-bit integer types
  1324  ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1325  **
  1326  ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1327  ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1328  ** compatibility only.
  1329  **
  1330  ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1331  ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
  1332  ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
  1333  ** between 0 and +18446744073709551615 inclusive.
  1334  */
  1335  #ifdef SQLITE_INT64_TYPE
  1336    typedef SQLITE_INT64_TYPE sqlite_int64;
  1337  # ifdef SQLITE_UINT64_TYPE
  1338      typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1339  # else  
  1340      typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1341  # endif
  1342  #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1343    typedef __int64 sqlite_int64;
  1344    typedef unsigned __int64 sqlite_uint64;
  1345  #else
  1346    typedef long long int sqlite_int64;
  1347    typedef unsigned long long int sqlite_uint64;
  1348  #endif
  1349  typedef sqlite_int64 sqlite3_int64;
  1350  typedef sqlite_uint64 sqlite3_uint64;
  1351  
  1352  /*
  1353  ** If compiling for a processor that lacks floating point support,
  1354  ** substitute integer for floating-point.
  1355  */
  1356  #ifdef SQLITE_OMIT_FLOATING_POINT
  1357  # define double sqlite3_int64
  1358  #endif
  1359  
  1360  /*
  1361  ** CAPI3REF: Closing A Database Connection
  1362  ** DESTRUCTOR: sqlite3
  1363  **
  1364  ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1365  ** for the [sqlite3] object.
  1366  ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1367  ** the [sqlite3] object is successfully destroyed and all associated
  1368  ** resources are deallocated.
  1369  **
  1370  ** ^If the database connection is associated with unfinalized prepared
  1371  ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1372  ** will leave the database connection open and return [SQLITE_BUSY].
  1373  ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1374  ** and/or unfinished sqlite3_backups, then the database connection becomes
  1375  ** an unusable "zombie" which will automatically be deallocated when the
  1376  ** last prepared statement is finalized or the last sqlite3_backup is
  1377  ** finished.  The sqlite3_close_v2() interface is intended for use with
  1378  ** host languages that are garbage collected, and where the order in which
  1379  ** destructors are called is arbitrary.
  1380  **
  1381  ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1382  ** [sqlite3_blob_close | close] all [BLOB handles], and 
  1383  ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1384  ** with the [sqlite3] object prior to attempting to close the object.  ^If
  1385  ** sqlite3_close_v2() is called on a [database connection] that still has
  1386  ** outstanding [prepared statements], [BLOB handles], and/or
  1387  ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1388  ** of resources is deferred until all [prepared statements], [BLOB handles],
  1389  ** and [sqlite3_backup] objects are also destroyed.
  1390  **
  1391  ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1392  ** the transaction is automatically rolled back.
  1393  **
  1394  ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1395  ** must be either a NULL
  1396  ** pointer or an [sqlite3] object pointer obtained
  1397  ** from [sqlite3_open()], [sqlite3_open16()], or
  1398  ** [sqlite3_open_v2()], and not previously closed.
  1399  ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1400  ** argument is a harmless no-op.
  1401  */
  1402  SQLITE_API int sqlite3_close(sqlite3*);
  1403  SQLITE_API int sqlite3_close_v2(sqlite3*);
  1404  
  1405  /*
  1406  ** The type for a callback function.
  1407  ** This is legacy and deprecated.  It is included for historical
  1408  ** compatibility and is not documented.
  1409  */
  1410  typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1411  
  1412  /*
  1413  ** CAPI3REF: One-Step Query Execution Interface
  1414  ** METHOD: sqlite3
  1415  **
  1416  ** The sqlite3_exec() interface is a convenience wrapper around
  1417  ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1418  ** that allows an application to run multiple statements of SQL
  1419  ** without having to use a lot of C code. 
  1420  **
  1421  ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1422  ** semicolon-separate SQL statements passed into its 2nd argument,
  1423  ** in the context of the [database connection] passed in as its 1st
  1424  ** argument.  ^If the callback function of the 3rd argument to
  1425  ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1426  ** coming out of the evaluated SQL statements.  ^The 4th argument to
  1427  ** sqlite3_exec() is relayed through to the 1st argument of each
  1428  ** callback invocation.  ^If the callback pointer to sqlite3_exec()
  1429  ** is NULL, then no callback is ever invoked and result rows are
  1430  ** ignored.
  1431  **
  1432  ** ^If an error occurs while evaluating the SQL statements passed into
  1433  ** sqlite3_exec(), then execution of the current statement stops and
  1434  ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
  1435  ** is not NULL then any error message is written into memory obtained
  1436  ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1437  ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1438  ** on error message strings returned through the 5th parameter of
  1439  ** sqlite3_exec() after the error message string is no longer needed.
  1440  ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1441  ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1442  ** NULL before returning.
  1443  **
  1444  ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1445  ** routine returns SQLITE_ABORT without invoking the callback again and
  1446  ** without running any subsequent SQL statements.
  1447  **
  1448  ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1449  ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
  1450  ** callback is an array of pointers to strings obtained as if from
  1451  ** [sqlite3_column_text()], one for each column.  ^If an element of a
  1452  ** result row is NULL then the corresponding string pointer for the
  1453  ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
  1454  ** sqlite3_exec() callback is an array of pointers to strings where each
  1455  ** entry represents the name of corresponding result column as obtained
  1456  ** from [sqlite3_column_name()].
  1457  **
  1458  ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1459  ** to an empty string, or a pointer that contains only whitespace and/or 
  1460  ** SQL comments, then no SQL statements are evaluated and the database
  1461  ** is not changed.
  1462  **
  1463  ** Restrictions:
  1464  **
  1465  ** <ul>
  1466  ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1467  **      is a valid and open [database connection].
  1468  ** <li> The application must not close the [database connection] specified by
  1469  **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1470  ** <li> The application must not modify the SQL statement text passed into
  1471  **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1472  ** </ul>
  1473  */
  1474  SQLITE_API int sqlite3_exec(
  1475    sqlite3*,                                  /* An open database */
  1476    const char *sql,                           /* SQL to be evaluated */
  1477    int (*callback)(void*,int,char**,char**),  /* Callback function */
  1478    void *,                                    /* 1st argument to callback */
  1479    char **errmsg                              /* Error msg written here */
  1480  );
  1481  
  1482  /*
  1483  ** CAPI3REF: Result Codes
  1484  ** KEYWORDS: {result code definitions}
  1485  **
  1486  ** Many SQLite functions return an integer result code from the set shown
  1487  ** here in order to indicate success or failure.
  1488  **
  1489  ** New error codes may be added in future versions of SQLite.
  1490  **
  1491  ** See also: [extended result code definitions]
  1492  */
  1493  #define SQLITE_OK           0   /* Successful result */
  1494  /* beginning-of-error-codes */
  1495  #define SQLITE_ERROR        1   /* Generic error */
  1496  #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
  1497  #define SQLITE_PERM         3   /* Access permission denied */
  1498  #define SQLITE_ABORT        4   /* Callback routine requested an abort */
  1499  #define SQLITE_BUSY         5   /* The database file is locked */
  1500  #define SQLITE_LOCKED       6   /* A table in the database is locked */
  1501  #define SQLITE_NOMEM        7   /* A malloc() failed */
  1502  #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
  1503  #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
  1504  #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
  1505  #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
  1506  #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
  1507  #define SQLITE_FULL        13   /* Insertion failed because database is full */
  1508  #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
  1509  #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
  1510  #define SQLITE_EMPTY       16   /* Internal use only */
  1511  #define SQLITE_SCHEMA      17   /* The database schema changed */
  1512  #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
  1513  #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
  1514  #define SQLITE_MISMATCH    20   /* Data type mismatch */
  1515  #define SQLITE_MISUSE      21   /* Library used incorrectly */
  1516  #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
  1517  #define SQLITE_AUTH        23   /* Authorization denied */
  1518  #define SQLITE_FORMAT      24   /* Not used */
  1519  #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
  1520  #define SQLITE_NOTADB      26   /* File opened that is not a database file */
  1521  #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
  1522  #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
  1523  #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
  1524  #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
  1525  /* end-of-error-codes */
  1526  
  1527  /*
  1528  ** CAPI3REF: Extended Result Codes
  1529  ** KEYWORDS: {extended result code definitions}
  1530  **
  1531  ** In its default configuration, SQLite API routines return one of 30 integer
  1532  ** [result codes].  However, experience has shown that many of
  1533  ** these result codes are too coarse-grained.  They do not provide as
  1534  ** much information about problems as programmers might like.  In an effort to
  1535  ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1536  ** and later) include
  1537  ** support for additional result codes that provide more detailed information
  1538  ** about errors. These [extended result codes] are enabled or disabled
  1539  ** on a per database connection basis using the
  1540  ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
  1541  ** the most recent error can be obtained using
  1542  ** [sqlite3_extended_errcode()].
  1543  */
  1544  #define SQLITE_ERROR_MISSING_COLLSEQ   (SQLITE_ERROR | (1<<8))
  1545  #define SQLITE_ERROR_RETRY             (SQLITE_ERROR | (2<<8))
  1546  #define SQLITE_ERROR_SNAPSHOT          (SQLITE_ERROR | (3<<8))
  1547  #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
  1548  #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
  1549  #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
  1550  #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
  1551  #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
  1552  #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
  1553  #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
  1554  #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
  1555  #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
  1556  #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
  1557  #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
  1558  #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
  1559  #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
  1560  #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1561  #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
  1562  #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
  1563  #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
  1564  #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
  1565  #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
  1566  #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
  1567  #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
  1568  #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
  1569  #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
  1570  #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
  1571  #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
  1572  #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
  1573  #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
  1574  #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
  1575  #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
  1576  #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
  1577  #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
  1578  #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
  1579  #define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
  1580  #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
  1581  #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
  1582  #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
  1583  #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
  1584  #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
  1585  #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
  1586  #define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
  1587  #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
  1588  #define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
  1589  #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
  1590  #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
  1591  #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
  1592  #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
  1593  #define SQLITE_READONLY_CANTINIT       (SQLITE_READONLY | (5<<8))
  1594  #define SQLITE_READONLY_DIRECTORY      (SQLITE_READONLY | (6<<8))
  1595  #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
  1596  #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
  1597  #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
  1598  #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
  1599  #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
  1600  #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
  1601  #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
  1602  #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
  1603  #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
  1604  #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
  1605  #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
  1606  #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
  1607  #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1608  #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
  1609  #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
  1610  #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
  1611  
  1612  /*
  1613  ** CAPI3REF: Flags For File Open Operations
  1614  **
  1615  ** These bit values are intended for use in the
  1616  ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1617  ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1618  */
  1619  #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
  1620  #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
  1621  #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
  1622  #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
  1623  #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
  1624  #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
  1625  #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
  1626  #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
  1627  #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
  1628  #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
  1629  #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
  1630  #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
  1631  #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
  1632  #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
  1633  #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
  1634  #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
  1635  #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
  1636  #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
  1637  #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
  1638  #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
  1639  
  1640  /* Reserved:                         0x00F00000 */
  1641  
  1642  /*
  1643  ** CAPI3REF: Device Characteristics
  1644  **
  1645  ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1646  ** object returns an integer which is a vector of these
  1647  ** bit values expressing I/O characteristics of the mass storage
  1648  ** device that holds the file that the [sqlite3_io_methods]
  1649  ** refers to.
  1650  **
  1651  ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1652  ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
  1653  ** mean that writes of blocks that are nnn bytes in size and
  1654  ** are aligned to an address which is an integer multiple of
  1655  ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
  1656  ** that when data is appended to a file, the data is appended
  1657  ** first then the size of the file is extended, never the other
  1658  ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
  1659  ** information is written to disk in the same order as calls
  1660  ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1661  ** after reboot following a crash or power loss, the only bytes in a
  1662  ** file that were written at the application level might have changed
  1663  ** and that adjacent bytes, even bytes within the same sector are
  1664  ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1665  ** flag indicates that a file cannot be deleted when open.  The
  1666  ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1667  ** read-only media and cannot be changed even by processes with
  1668  ** elevated privileges.
  1669  **
  1670  ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1671  ** filesystem supports doing multiple write operations atomically when those
  1672  ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1673  ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1674  */
  1675  #define SQLITE_IOCAP_ATOMIC                 0x00000001
  1676  #define SQLITE_IOCAP_ATOMIC512              0x00000002
  1677  #define SQLITE_IOCAP_ATOMIC1K               0x00000004
  1678  #define SQLITE_IOCAP_ATOMIC2K               0x00000008
  1679  #define SQLITE_IOCAP_ATOMIC4K               0x00000010
  1680  #define SQLITE_IOCAP_ATOMIC8K               0x00000020
  1681  #define SQLITE_IOCAP_ATOMIC16K              0x00000040
  1682  #define SQLITE_IOCAP_ATOMIC32K              0x00000080
  1683  #define SQLITE_IOCAP_ATOMIC64K              0x00000100
  1684  #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
  1685  #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
  1686  #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
  1687  #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
  1688  #define SQLITE_IOCAP_IMMUTABLE              0x00002000
  1689  #define SQLITE_IOCAP_BATCH_ATOMIC           0x00004000
  1690  
  1691  /*
  1692  ** CAPI3REF: File Locking Levels
  1693  **
  1694  ** SQLite uses one of these integer values as the second
  1695  ** argument to calls it makes to the xLock() and xUnlock() methods
  1696  ** of an [sqlite3_io_methods] object.
  1697  */
  1698  #define SQLITE_LOCK_NONE          0
  1699  #define SQLITE_LOCK_SHARED        1
  1700  #define SQLITE_LOCK_RESERVED      2
  1701  #define SQLITE_LOCK_PENDING       3
  1702  #define SQLITE_LOCK_EXCLUSIVE     4
  1703  
  1704  /*
  1705  ** CAPI3REF: Synchronization Type Flags
  1706  **
  1707  ** When SQLite invokes the xSync() method of an
  1708  ** [sqlite3_io_methods] object it uses a combination of
  1709  ** these integer values as the second argument.
  1710  **
  1711  ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1712  ** sync operation only needs to flush data to mass storage.  Inode
  1713  ** information need not be flushed. If the lower four bits of the flag
  1714  ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1715  ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1716  ** to use Mac OS X style fullsync instead of fsync().
  1717  **
  1718  ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1719  ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1720  ** settings.  The [synchronous pragma] determines when calls to the
  1721  ** xSync VFS method occur and applies uniformly across all platforms.
  1722  ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1723  ** energetic or rigorous or forceful the sync operations are and
  1724  ** only make a difference on Mac OSX for the default SQLite code.
  1725  ** (Third-party VFS implementations might also make the distinction
  1726  ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1727  ** operating systems natively supported by SQLite, only Mac OSX
  1728  ** cares about the difference.)
  1729  */
  1730  #define SQLITE_SYNC_NORMAL        0x00002
  1731  #define SQLITE_SYNC_FULL          0x00003
  1732  #define SQLITE_SYNC_DATAONLY      0x00010
  1733  
  1734  /*
  1735  ** CAPI3REF: OS Interface Open File Handle
  1736  **
  1737  ** An [sqlite3_file] object represents an open file in the 
  1738  ** [sqlite3_vfs | OS interface layer].  Individual OS interface
  1739  ** implementations will
  1740  ** want to subclass this object by appending additional fields
  1741  ** for their own use.  The pMethods entry is a pointer to an
  1742  ** [sqlite3_io_methods] object that defines methods for performing
  1743  ** I/O operations on the open file.
  1744  */
  1745  typedef struct sqlite3_file sqlite3_file;
  1746  struct sqlite3_file {
  1747    const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
  1748  };
  1749  
  1750  /*
  1751  ** CAPI3REF: OS Interface File Virtual Methods Object
  1752  **
  1753  ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1754  ** [sqlite3_file] object (or, more commonly, a subclass of the
  1755  ** [sqlite3_file] object) with a pointer to an instance of this object.
  1756  ** This object defines the methods used to perform various operations
  1757  ** against the open file represented by the [sqlite3_file] object.
  1758  **
  1759  ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
  1760  ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1761  ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
  1762  ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1763  ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1764  ** to NULL.
  1765  **
  1766  ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1767  ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
  1768  ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
  1769  ** flag may be ORed in to indicate that only the data of the file
  1770  ** and not its inode needs to be synced.
  1771  **
  1772  ** The integer values to xLock() and xUnlock() are one of
  1773  ** <ul>
  1774  ** <li> [SQLITE_LOCK_NONE],
  1775  ** <li> [SQLITE_LOCK_SHARED],
  1776  ** <li> [SQLITE_LOCK_RESERVED],
  1777  ** <li> [SQLITE_LOCK_PENDING], or
  1778  ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1779  ** </ul>
  1780  ** xLock() increases the lock. xUnlock() decreases the lock.
  1781  ** The xCheckReservedLock() method checks whether any database connection,
  1782  ** either in this process or in some other process, is holding a RESERVED,
  1783  ** PENDING, or EXCLUSIVE lock on the file.  It returns true
  1784  ** if such a lock exists and false otherwise.
  1785  **
  1786  ** The xFileControl() method is a generic interface that allows custom
  1787  ** VFS implementations to directly control an open file using the
  1788  ** [sqlite3_file_control()] interface.  The second "op" argument is an
  1789  ** integer opcode.  The third argument is a generic pointer intended to
  1790  ** point to a structure that may contain arguments or space in which to
  1791  ** write return values.  Potential uses for xFileControl() might be
  1792  ** functions to enable blocking locks with timeouts, to change the
  1793  ** locking strategy (for example to use dot-file locks), to inquire
  1794  ** about the status of a lock, or to break stale locks.  The SQLite
  1795  ** core reserves all opcodes less than 100 for its own use.
  1796  ** A [file control opcodes | list of opcodes] less than 100 is available.
  1797  ** Applications that define a custom xFileControl method should use opcodes
  1798  ** greater than 100 to avoid conflicts.  VFS implementations should
  1799  ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1800  ** recognize.
  1801  **
  1802  ** The xSectorSize() method returns the sector size of the
  1803  ** device that underlies the file.  The sector size is the
  1804  ** minimum write that can be performed without disturbing
  1805  ** other bytes in the file.  The xDeviceCharacteristics()
  1806  ** method returns a bit vector describing behaviors of the
  1807  ** underlying device:
  1808  **
  1809  ** <ul>
  1810  ** <li> [SQLITE_IOCAP_ATOMIC]
  1811  ** <li> [SQLITE_IOCAP_ATOMIC512]
  1812  ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1813  ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1814  ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1815  ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1816  ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1817  ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1818  ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1819  ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1820  ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1821  ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1822  ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1823  ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1824  ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1825  ** </ul>
  1826  **
  1827  ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1828  ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
  1829  ** mean that writes of blocks that are nnn bytes in size and
  1830  ** are aligned to an address which is an integer multiple of
  1831  ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
  1832  ** that when data is appended to a file, the data is appended
  1833  ** first then the size of the file is extended, never the other
  1834  ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
  1835  ** information is written to disk in the same order as calls
  1836  ** to xWrite().
  1837  **
  1838  ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1839  ** in the unread portions of the buffer with zeros.  A VFS that
  1840  ** fails to zero-fill short reads might seem to work.  However,
  1841  ** failure to zero-fill short reads will eventually lead to
  1842  ** database corruption.
  1843  */
  1844  typedef struct sqlite3_io_methods sqlite3_io_methods;
  1845  struct sqlite3_io_methods {
  1846    int iVersion;
  1847    int (*xClose)(sqlite3_file*);
  1848    int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1849    int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1850    int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1851    int (*xSync)(sqlite3_file*, int flags);
  1852    int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1853    int (*xLock)(sqlite3_file*, int);
  1854    int (*xUnlock)(sqlite3_file*, int);
  1855    int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1856    int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1857    int (*xSectorSize)(sqlite3_file*);
  1858    int (*xDeviceCharacteristics)(sqlite3_file*);
  1859    /* Methods above are valid for version 1 */
  1860    int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1861    int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1862    void (*xShmBarrier)(sqlite3_file*);
  1863    int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1864    /* Methods above are valid for version 2 */
  1865    int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1866    int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1867    /* Methods above are valid for version 3 */
  1868    /* Additional methods may be added in future releases */
  1869  };
  1870  
  1871  /*
  1872  ** CAPI3REF: Standard File Control Opcodes
  1873  ** KEYWORDS: {file control opcodes} {file control opcode}
  1874  **
  1875  ** These integer constants are opcodes for the xFileControl method
  1876  ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1877  ** interface.
  1878  **
  1879  ** <ul>
  1880  ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1881  ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
  1882  ** opcode causes the xFileControl method to write the current state of
  1883  ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1884  ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1885  ** into an integer that the pArg argument points to. This capability
  1886  ** is used during testing and is only available when the SQLITE_TEST
  1887  ** compile-time option is used.
  1888  **
  1889  ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1890  ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1891  ** layer a hint of how large the database file will grow to be during the
  1892  ** current transaction.  This hint is not guaranteed to be accurate but it
  1893  ** is often close.  The underlying VFS might choose to preallocate database
  1894  ** file space based on this hint in order to help writes to the database
  1895  ** file run faster.
  1896  **
  1897  ** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
  1898  ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
  1899  ** implements [sqlite3_deserialize()] to set an upper bound on the size
  1900  ** of the in-memory database.  The argument is a pointer to a [sqlite3_int64].
  1901  ** If the integer pointed to is negative, then it is filled in with the
  1902  ** current limit.  Otherwise the limit is set to the larger of the value
  1903  ** of the integer pointed to and the current database size.  The integer
  1904  ** pointed to is set to the new limit.
  1905  **
  1906  ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1907  ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1908  ** extends and truncates the database file in chunks of a size specified
  1909  ** by the user. The fourth argument to [sqlite3_file_control()] should 
  1910  ** point to an integer (type int) containing the new chunk-size to use
  1911  ** for the nominated database. Allocating database file space in large
  1912  ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1913  ** improve performance on some systems.
  1914  **
  1915  ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1916  ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1917  ** to the [sqlite3_file] object associated with a particular database
  1918  ** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1919  **
  1920  ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1921  ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1922  ** to the [sqlite3_file] object associated with the journal file (either
  1923  ** the [rollback journal] or the [write-ahead log]) for a particular database
  1924  ** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
  1925  **
  1926  ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1927  ** No longer in use.
  1928  **
  1929  ** <li>[[SQLITE_FCNTL_SYNC]]
  1930  ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1931  ** sent to the VFS immediately before the xSync method is invoked on a
  1932  ** database file descriptor. Or, if the xSync method is not invoked 
  1933  ** because the user has configured SQLite with 
  1934  ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
  1935  ** of the xSync method. In most cases, the pointer argument passed with
  1936  ** this file-control is NULL. However, if the database file is being synced
  1937  ** as part of a multi-database commit, the argument points to a nul-terminated
  1938  ** string containing the transactions master-journal file name. VFSes that 
  1939  ** do not need this signal should silently ignore this opcode. Applications 
  1940  ** should not call [sqlite3_file_control()] with this opcode as doing so may 
  1941  ** disrupt the operation of the specialized VFSes that do require it.  
  1942  **
  1943  ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1944  ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1945  ** and sent to the VFS after a transaction has been committed immediately
  1946  ** but before the database is unlocked. VFSes that do not need this signal
  1947  ** should silently ignore this opcode. Applications should not call
  1948  ** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
  1949  ** operation of the specialized VFSes that do require it.  
  1950  **
  1951  ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1952  ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1953  ** retry counts and intervals for certain disk I/O operations for the
  1954  ** windows [VFS] in order to provide robustness in the presence of
  1955  ** anti-virus programs.  By default, the windows VFS will retry file read,
  1956  ** file write, and file delete operations up to 10 times, with a delay
  1957  ** of 25 milliseconds before the first retry and with the delay increasing
  1958  ** by an additional 25 milliseconds with each subsequent retry.  This
  1959  ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1960  ** to be adjusted.  The values are changed for all database connections
  1961  ** within the same process.  The argument is a pointer to an array of two
  1962  ** integers where the first integer is the new retry count and the second
  1963  ** integer is the delay.  If either integer is negative, then the setting
  1964  ** is not changed but instead the prior value of that setting is written
  1965  ** into the array entry, allowing the current retry settings to be
  1966  ** interrogated.  The zDbName parameter is ignored.
  1967  **
  1968  ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1969  ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1970  ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
  1971  ** write ahead log ([WAL file]) and shared memory
  1972  ** files used for transaction control
  1973  ** are automatically deleted when the latest connection to the database
  1974  ** closes.  Setting persistent WAL mode causes those files to persist after
  1975  ** close.  Persisting the files is useful when other processes that do not
  1976  ** have write permission on the directory containing the database file want
  1977  ** to read the database file, as the WAL and shared memory files must exist
  1978  ** in order for the database to be readable.  The fourth parameter to
  1979  ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1980  ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1981  ** WAL mode.  If the integer is -1, then it is overwritten with the current
  1982  ** WAL persistence setting.
  1983  **
  1984  ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1985  ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1986  ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
  1987  ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1988  ** xDeviceCharacteristics methods. The fourth parameter to
  1989  ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1990  ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1991  ** mode.  If the integer is -1, then it is overwritten with the current
  1992  ** zero-damage mode setting.
  1993  **
  1994  ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1995  ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1996  ** a write transaction to indicate that, unless it is rolled back for some
  1997  ** reason, the entire database file will be overwritten by the current 
  1998  ** transaction. This is used by VACUUM operations.
  1999  **
  2000  ** <li>[[SQLITE_FCNTL_VFSNAME]]
  2001  ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  2002  ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
  2003  ** final bottom-level VFS are written into memory obtained from 
  2004  ** [sqlite3_malloc()] and the result is stored in the char* variable
  2005  ** that the fourth parameter of [sqlite3_file_control()] points to.
  2006  ** The caller is responsible for freeing the memory when done.  As with
  2007  ** all file-control actions, there is no guarantee that this will actually
  2008  ** do anything.  Callers should initialize the char* variable to a NULL
  2009  ** pointer in case this file-control is not implemented.  This file-control
  2010  ** is intended for diagnostic use only.
  2011  **
  2012  ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  2013  ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  2014  ** [VFSes] currently in use.  ^(The argument X in
  2015  ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  2016  ** of type "[sqlite3_vfs] **".  This opcodes will set *X
  2017  ** to a pointer to the top-level VFS.)^
  2018  ** ^When there are multiple VFS shims in the stack, this opcode finds the
  2019  ** upper-most shim only.
  2020  **
  2021  ** <li>[[SQLITE_FCNTL_PRAGMA]]
  2022  ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
  2023  ** file control is sent to the open [sqlite3_file] object corresponding
  2024  ** to the database file to which the pragma statement refers. ^The argument
  2025  ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  2026  ** pointers to strings (char**) in which the second element of the array
  2027  ** is the name of the pragma and the third element is the argument to the
  2028  ** pragma or NULL if the pragma has no argument.  ^The handler for an
  2029  ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  2030  ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  2031  ** or the equivalent and that string will become the result of the pragma or
  2032  ** the error message if the pragma fails. ^If the
  2033  ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
  2034  ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
  2035  ** file control returns [SQLITE_OK], then the parser assumes that the
  2036  ** VFS has handled the PRAGMA itself and the parser generates a no-op
  2037  ** prepared statement if result string is NULL, or that returns a copy
  2038  ** of the result string if the string is non-NULL.
  2039  ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  2040  ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  2041  ** that the VFS encountered an error while handling the [PRAGMA] and the
  2042  ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
  2043  ** file control occurs at the beginning of pragma statement analysis and so
  2044  ** it is able to override built-in [PRAGMA] statements.
  2045  **
  2046  ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  2047  ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  2048  ** file-control may be invoked by SQLite on the database file handle
  2049  ** shortly after it is opened in order to provide a custom VFS with access
  2050  ** to the connections busy-handler callback. The argument is of type (void **)
  2051  ** - an array of two (void *) values. The first (void *) actually points
  2052  ** to a function of type (int (*)(void *)). In order to invoke the connections
  2053  ** busy-handler, this function should be invoked with the second (void *) in
  2054  ** the array as the only argument. If it returns non-zero, then the operation
  2055  ** should be retried. If it returns zero, the custom VFS should abandon the
  2056  ** current operation.
  2057  **
  2058  ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  2059  ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  2060  ** to have SQLite generate a
  2061  ** temporary filename using the same algorithm that is followed to generate
  2062  ** temporary filenames for TEMP tables and other internal uses.  The
  2063  ** argument should be a char** which will be filled with the filename
  2064  ** written into memory obtained from [sqlite3_malloc()].  The caller should
  2065  ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  2066  **
  2067  ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  2068  ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  2069  ** maximum number of bytes that will be used for memory-mapped I/O.
  2070  ** The argument is a pointer to a value of type sqlite3_int64 that
  2071  ** is an advisory maximum number of bytes in the file to memory map.  The
  2072  ** pointer is overwritten with the old value.  The limit is not changed if
  2073  ** the value originally pointed to is negative, and so the current limit 
  2074  ** can be queried by passing in a pointer to a negative number.  This
  2075  ** file-control is used internally to implement [PRAGMA mmap_size].
  2076  **
  2077  ** <li>[[SQLITE_FCNTL_TRACE]]
  2078  ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  2079  ** to the VFS about what the higher layers of the SQLite stack are doing.
  2080  ** This file control is used by some VFS activity tracing [shims].
  2081  ** The argument is a zero-terminated string.  Higher layers in the
  2082  ** SQLite stack may generate instances of this file control if
  2083  ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  2084  **
  2085  ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  2086  ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  2087  ** pointer to an integer and it writes a boolean into that integer depending
  2088  ** on whether or not the file has been renamed, moved, or deleted since it
  2089  ** was first opened.
  2090  **
  2091  ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2092  ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2093  ** underlying native file handle associated with a file handle.  This file
  2094  ** control interprets its argument as a pointer to a native file handle and
  2095  ** writes the resulting value there.
  2096  **
  2097  ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2098  ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
  2099  ** opcode causes the xFileControl method to swap the file handle with the one
  2100  ** pointed to by the pArg argument.  This capability is used during testing
  2101  ** and only needs to be supported when SQLITE_TEST is defined.
  2102  **
  2103  ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2104  ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2105  ** be advantageous to block on the next WAL lock if the lock is not immediately
  2106  ** available.  The WAL subsystem issues this signal during rare
  2107  ** circumstances in order to fix a problem with priority inversion.
  2108  ** Applications should <em>not</em> use this file-control.
  2109  **
  2110  ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2111  ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2112  ** VFS should return SQLITE_NOTFOUND for this opcode.
  2113  **
  2114  ** <li>[[SQLITE_FCNTL_RBU]]
  2115  ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2116  ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
  2117  ** this opcode.  
  2118  **
  2119  ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2120  ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2121  ** the file descriptor is placed in "batch write mode", which
  2122  ** means all subsequent write operations will be deferred and done
  2123  ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].  Systems
  2124  ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2125  ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2126  ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2127  ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2128  ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2129  ** except for calls to the xWrite method and the xFileControl method
  2130  ** with [SQLITE_FCNTL_SIZE_HINT].
  2131  **
  2132  ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2133  ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2134  ** operations since the previous successful call to 
  2135  ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2136  ** This file control returns [SQLITE_OK] if and only if the writes were
  2137  ** all performed successfully and have been committed to persistent storage.
  2138  ** ^Regardless of whether or not it is successful, this file control takes
  2139  ** the file descriptor out of batch write mode so that all subsequent
  2140  ** write operations are independent.
  2141  ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2142  ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2143  **
  2144  ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2145  ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2146  ** operations since the previous successful call to 
  2147  ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2148  ** ^This file control takes the file descriptor out of batch write mode
  2149  ** so that all subsequent write operations are independent.
  2150  ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2151  ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2152  **
  2153  ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2154  ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2155  ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2156  ** for up to M milliseconds before failing, where M is the single 
  2157  ** unsigned integer parameter.
  2158  **
  2159  ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
  2160  ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
  2161  ** a database file.  The argument is a pointer to a 32-bit unsigned integer.
  2162  ** The "data version" for the pager is written into the pointer.  The
  2163  ** "data version" changes whenever any change occurs to the corresponding
  2164  ** database file, either through SQL statements on the same database
  2165  ** connection or through transactions committed by separate database
  2166  ** connections possibly in other processes. The [sqlite3_total_changes()]
  2167  ** interface can be used to find if any database on the connection has changed,
  2168  ** but that interface responds to changes on TEMP as well as MAIN and does
  2169  ** not provide a mechanism to detect changes to MAIN only.  Also, the
  2170  ** [sqlite3_total_changes()] interface responds to internal changes only and
  2171  ** omits changes made by other database connections.  The
  2172  ** [PRAGMA data_version] command provide a mechanism to detect changes to
  2173  ** a single attached database that occur due to other database connections,
  2174  ** but omits changes implemented by the database connection on which it is
  2175  ** called.  This file control is the only mechanism to detect changes that
  2176  ** happen either internally or externally and that are associated with
  2177  ** a particular attached database.
  2178  ** </ul>
  2179  */
  2180  #define SQLITE_FCNTL_LOCKSTATE               1
  2181  #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
  2182  #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
  2183  #define SQLITE_FCNTL_LAST_ERRNO              4
  2184  #define SQLITE_FCNTL_SIZE_HINT               5
  2185  #define SQLITE_FCNTL_CHUNK_SIZE              6
  2186  #define SQLITE_FCNTL_FILE_POINTER            7
  2187  #define SQLITE_FCNTL_SYNC_OMITTED            8
  2188  #define SQLITE_FCNTL_WIN32_AV_RETRY          9
  2189  #define SQLITE_FCNTL_PERSIST_WAL            10
  2190  #define SQLITE_FCNTL_OVERWRITE              11
  2191  #define SQLITE_FCNTL_VFSNAME                12
  2192  #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
  2193  #define SQLITE_FCNTL_PRAGMA                 14
  2194  #define SQLITE_FCNTL_BUSYHANDLER            15
  2195  #define SQLITE_FCNTL_TEMPFILENAME           16
  2196  #define SQLITE_FCNTL_MMAP_SIZE              18
  2197  #define SQLITE_FCNTL_TRACE                  19
  2198  #define SQLITE_FCNTL_HAS_MOVED              20
  2199  #define SQLITE_FCNTL_SYNC                   21
  2200  #define SQLITE_FCNTL_COMMIT_PHASETWO        22
  2201  #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
  2202  #define SQLITE_FCNTL_WAL_BLOCK              24
  2203  #define SQLITE_FCNTL_ZIPVFS                 25
  2204  #define SQLITE_FCNTL_RBU                    26
  2205  #define SQLITE_FCNTL_VFS_POINTER            27
  2206  #define SQLITE_FCNTL_JOURNAL_POINTER        28
  2207  #define SQLITE_FCNTL_WIN32_GET_HANDLE       29
  2208  #define SQLITE_FCNTL_PDB                    30
  2209  #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE     31
  2210  #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE    32
  2211  #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33
  2212  #define SQLITE_FCNTL_LOCK_TIMEOUT           34
  2213  #define SQLITE_FCNTL_DATA_VERSION           35
  2214  #define SQLITE_FCNTL_SIZE_LIMIT             36
  2215  
  2216  /* deprecated names */
  2217  #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
  2218  #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
  2219  #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
  2220  
  2221  
  2222  /*
  2223  ** CAPI3REF: Mutex Handle
  2224  **
  2225  ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2226  ** abstract type for a mutex object.  The SQLite core never looks
  2227  ** at the internal representation of an [sqlite3_mutex].  It only
  2228  ** deals with pointers to the [sqlite3_mutex] object.
  2229  **
  2230  ** Mutexes are created using [sqlite3_mutex_alloc()].
  2231  */
  2232  typedef struct sqlite3_mutex sqlite3_mutex;
  2233  
  2234  /*
  2235  ** CAPI3REF: Loadable Extension Thunk
  2236  **
  2237  ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2238  ** the third parameter to entry points of [loadable extensions].  This
  2239  ** structure must be typedefed in order to work around compiler warnings
  2240  ** on some platforms.
  2241  */
  2242  typedef struct sqlite3_api_routines sqlite3_api_routines;
  2243  
  2244  /*
  2245  ** CAPI3REF: OS Interface Object
  2246  **
  2247  ** An instance of the sqlite3_vfs object defines the interface between
  2248  ** the SQLite core and the underlying operating system.  The "vfs"
  2249  ** in the name of the object stands for "virtual file system".  See
  2250  ** the [VFS | VFS documentation] for further information.
  2251  **
  2252  ** The VFS interface is sometimes extended by adding new methods onto
  2253  ** the end.  Each time such an extension occurs, the iVersion field
  2254  ** is incremented.  The iVersion value started out as 1 in
  2255  ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2256  ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2257  ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields
  2258  ** may be appended to the sqlite3_vfs object and the iVersion value
  2259  ** may increase again in future versions of SQLite.
  2260  ** Note that the structure
  2261  ** of the sqlite3_vfs object changes in the transition from
  2262  ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2263  ** and yet the iVersion field was not modified.
  2264  **
  2265  ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2266  ** structure used by this VFS.  mxPathname is the maximum length of
  2267  ** a pathname in this VFS.
  2268  **
  2269  ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2270  ** the pNext pointer.  The [sqlite3_vfs_register()]
  2271  ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2272  ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
  2273  ** searches the list.  Neither the application code nor the VFS
  2274  ** implementation should use the pNext pointer.
  2275  **
  2276  ** The pNext field is the only field in the sqlite3_vfs
  2277  ** structure that SQLite will ever modify.  SQLite will only access
  2278  ** or modify this field while holding a particular static mutex.
  2279  ** The application should never modify anything within the sqlite3_vfs
  2280  ** object once the object has been registered.
  2281  **
  2282  ** The zName field holds the name of the VFS module.  The name must
  2283  ** be unique across all VFS modules.
  2284  **
  2285  ** [[sqlite3_vfs.xOpen]]
  2286  ** ^SQLite guarantees that the zFilename parameter to xOpen
  2287  ** is either a NULL pointer or string obtained
  2288  ** from xFullPathname() with an optional suffix added.
  2289  ** ^If a suffix is added to the zFilename parameter, it will
  2290  ** consist of a single "-" character followed by no more than
  2291  ** 11 alphanumeric and/or "-" characters.
  2292  ** ^SQLite further guarantees that
  2293  ** the string will be valid and unchanged until xClose() is
  2294  ** called. Because of the previous sentence,
  2295  ** the [sqlite3_file] can safely store a pointer to the
  2296  ** filename if it needs to remember the filename for some reason.
  2297  ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2298  ** must invent its own temporary name for the file.  ^Whenever the 
  2299  ** xFilename parameter is NULL it will also be the case that the
  2300  ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2301  **
  2302  ** The flags argument to xOpen() includes all bits set in
  2303  ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
  2304  ** or [sqlite3_open16()] is used, then flags includes at least
  2305  ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
  2306  ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2307  ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
  2308  **
  2309  ** ^(SQLite will also add one of the following flags to the xOpen()
  2310  ** call, depending on the object being opened:
  2311  **
  2312  ** <ul>
  2313  ** <li>  [SQLITE_OPEN_MAIN_DB]
  2314  ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
  2315  ** <li>  [SQLITE_OPEN_TEMP_DB]
  2316  ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
  2317  ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
  2318  ** <li>  [SQLITE_OPEN_SUBJOURNAL]
  2319  ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
  2320  ** <li>  [SQLITE_OPEN_WAL]
  2321  ** </ul>)^
  2322  **
  2323  ** The file I/O implementation can use the object type flags to
  2324  ** change the way it deals with files.  For example, an application
  2325  ** that does not care about crash recovery or rollback might make
  2326  ** the open of a journal file a no-op.  Writes to this journal would
  2327  ** also be no-ops, and any attempt to read the journal would return
  2328  ** SQLITE_IOERR.  Or the implementation might recognize that a database
  2329  ** file will be doing page-aligned sector reads and writes in a random
  2330  ** order and set up its I/O subsystem accordingly.
  2331  **
  2332  ** SQLite might also add one of the following flags to the xOpen method:
  2333  **
  2334  ** <ul>
  2335  ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2336  ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2337  ** </ul>
  2338  **
  2339  ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2340  ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
  2341  ** will be set for TEMP databases and their journals, transient
  2342  ** databases, and subjournals.
  2343  **
  2344  ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2345  ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2346  ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2347  ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
  2348  ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2349  ** be created, and that it is an error if it already exists.
  2350  ** It is <i>not</i> used to indicate the file should be opened 
  2351  ** for exclusive access.
  2352  **
  2353  ** ^At least szOsFile bytes of memory are allocated by SQLite
  2354  ** to hold the  [sqlite3_file] structure passed as the third
  2355  ** argument to xOpen.  The xOpen method does not have to
  2356  ** allocate the structure; it should just fill it in.  Note that
  2357  ** the xOpen method must set the sqlite3_file.pMethods to either
  2358  ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
  2359  ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
  2360  ** element will be valid after xOpen returns regardless of the success
  2361  ** or failure of the xOpen call.
  2362  **
  2363  ** [[sqlite3_vfs.xAccess]]
  2364  ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2365  ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2366  ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2367  ** to test whether a file is at least readable.   The file can be a
  2368  ** directory.
  2369  **
  2370  ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2371  ** output buffer xFullPathname.  The exact size of the output buffer
  2372  ** is also passed as a parameter to both  methods. If the output buffer
  2373  ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2374  ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2375  ** to prevent this by setting mxPathname to a sufficiently large value.
  2376  **
  2377  ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2378  ** interfaces are not strictly a part of the filesystem, but they are
  2379  ** included in the VFS structure for completeness.
  2380  ** The xRandomness() function attempts to return nBytes bytes
  2381  ** of good-quality randomness into zOut.  The return value is
  2382  ** the actual number of bytes of randomness obtained.
  2383  ** The xSleep() method causes the calling thread to sleep for at
  2384  ** least the number of microseconds given.  ^The xCurrentTime()
  2385  ** method returns a Julian Day Number for the current date and time as
  2386  ** a floating point value.
  2387  ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2388  ** Day Number multiplied by 86400000 (the number of milliseconds in 
  2389  ** a 24-hour day).  
  2390  ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2391  ** date and time if that method is available (if iVersion is 2 or 
  2392  ** greater and the function pointer is not NULL) and will fall back
  2393  ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2394  **
  2395  ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2396  ** are not used by the SQLite core.  These optional interfaces are provided
  2397  ** by some VFSes to facilitate testing of the VFS code. By overriding 
  2398  ** system calls with functions under its control, a test program can
  2399  ** simulate faults and error conditions that would otherwise be difficult
  2400  ** or impossible to induce.  The set of system calls that can be overridden
  2401  ** varies from one VFS to another, and from one version of the same VFS to the
  2402  ** next.  Applications that use these interfaces must be prepared for any
  2403  ** or all of these interfaces to be NULL or for their behavior to change
  2404  ** from one release to the next.  Applications must not attempt to access
  2405  ** any of these methods if the iVersion of the VFS is less than 3.
  2406  */
  2407  typedef struct sqlite3_vfs sqlite3_vfs;
  2408  typedef void (*sqlite3_syscall_ptr)(void);
  2409  struct sqlite3_vfs {
  2410    int iVersion;            /* Structure version number (currently 3) */
  2411    int szOsFile;            /* Size of subclassed sqlite3_file */
  2412    int mxPathname;          /* Maximum file pathname length */
  2413    sqlite3_vfs *pNext;      /* Next registered VFS */
  2414    const char *zName;       /* Name of this virtual file system */
  2415    void *pAppData;          /* Pointer to application-specific data */
  2416    int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2417                 int flags, int *pOutFlags);
  2418    int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2419    int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2420    int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2421    void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2422    void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2423    void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2424    void (*xDlClose)(sqlite3_vfs*, void*);
  2425    int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2426    int (*xSleep)(sqlite3_vfs*, int microseconds);
  2427    int (*xCurrentTime)(sqlite3_vfs*, double*);
  2428    int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2429    /*
  2430    ** The methods above are in version 1 of the sqlite_vfs object
  2431    ** definition.  Those that follow are added in version 2 or later
  2432    */
  2433    int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2434    /*
  2435    ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2436    ** Those below are for version 3 and greater.
  2437    */
  2438    int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2439    sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2440    const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2441    /*
  2442    ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2443    ** New fields may be appended in future versions.  The iVersion
  2444    ** value will increment whenever this happens. 
  2445    */
  2446  };
  2447  
  2448  /*
  2449  ** CAPI3REF: Flags for the xAccess VFS method
  2450  **
  2451  ** These integer constants can be used as the third parameter to
  2452  ** the xAccess method of an [sqlite3_vfs] object.  They determine
  2453  ** what kind of permissions the xAccess method is looking for.
  2454  ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2455  ** simply checks whether the file exists.
  2456  ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2457  ** checks whether the named directory is both readable and writable
  2458  ** (in other words, if files can be added, removed, and renamed within
  2459  ** the directory).
  2460  ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2461  ** [temp_store_directory pragma], though this could change in a future
  2462  ** release of SQLite.
  2463  ** With SQLITE_ACCESS_READ, the xAccess method
  2464  ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
  2465  ** currently unused, though it might be used in a future release of
  2466  ** SQLite.
  2467  */
  2468  #define SQLITE_ACCESS_EXISTS    0
  2469  #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
  2470  #define SQLITE_ACCESS_READ      2   /* Unused */
  2471  
  2472  /*
  2473  ** CAPI3REF: Flags for the xShmLock VFS method
  2474  **
  2475  ** These integer constants define the various locking operations
  2476  ** allowed by the xShmLock method of [sqlite3_io_methods].  The
  2477  ** following are the only legal combinations of flags to the
  2478  ** xShmLock method:
  2479  **
  2480  ** <ul>
  2481  ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2482  ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2483  ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2484  ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2485  ** </ul>
  2486  **
  2487  ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2488  ** was given on the corresponding lock.  
  2489  **
  2490  ** The xShmLock method can transition between unlocked and SHARED or
  2491  ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
  2492  ** and EXCLUSIVE.
  2493  */
  2494  #define SQLITE_SHM_UNLOCK       1
  2495  #define SQLITE_SHM_LOCK         2
  2496  #define SQLITE_SHM_SHARED       4
  2497  #define SQLITE_SHM_EXCLUSIVE    8
  2498  
  2499  /*
  2500  ** CAPI3REF: Maximum xShmLock index
  2501  **
  2502  ** The xShmLock method on [sqlite3_io_methods] may use values
  2503  ** between 0 and this upper bound as its "offset" argument.
  2504  ** The SQLite core will never attempt to acquire or release a
  2505  ** lock outside of this range
  2506  */
  2507  #define SQLITE_SHM_NLOCK        8
  2508  
  2509  
  2510  /*
  2511  ** CAPI3REF: Initialize The SQLite Library
  2512  **
  2513  ** ^The sqlite3_initialize() routine initializes the
  2514  ** SQLite library.  ^The sqlite3_shutdown() routine
  2515  ** deallocates any resources that were allocated by sqlite3_initialize().
  2516  ** These routines are designed to aid in process initialization and
  2517  ** shutdown on embedded systems.  Workstation applications using
  2518  ** SQLite normally do not need to invoke either of these routines.
  2519  **
  2520  ** A call to sqlite3_initialize() is an "effective" call if it is
  2521  ** the first time sqlite3_initialize() is invoked during the lifetime of
  2522  ** the process, or if it is the first time sqlite3_initialize() is invoked
  2523  ** following a call to sqlite3_shutdown().  ^(Only an effective call
  2524  ** of sqlite3_initialize() does any initialization.  All other calls
  2525  ** are harmless no-ops.)^
  2526  **
  2527  ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2528  ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
  2529  ** an effective call to sqlite3_shutdown() does any deinitialization.
  2530  ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2531  **
  2532  ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2533  ** is not.  The sqlite3_shutdown() interface must only be called from a
  2534  ** single thread.  All open [database connections] must be closed and all
  2535  ** other SQLite resources must be deallocated prior to invoking
  2536  ** sqlite3_shutdown().
  2537  **
  2538  ** Among other things, ^sqlite3_initialize() will invoke
  2539  ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
  2540  ** will invoke sqlite3_os_end().
  2541  **
  2542  ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2543  ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2544  ** the library (perhaps it is unable to allocate a needed resource such
  2545  ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2546  **
  2547  ** ^The sqlite3_initialize() routine is called internally by many other
  2548  ** SQLite interfaces so that an application usually does not need to
  2549  ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
  2550  ** calls sqlite3_initialize() so the SQLite library will be automatically
  2551  ** initialized when [sqlite3_open()] is called if it has not be initialized
  2552  ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2553  ** compile-time option, then the automatic calls to sqlite3_initialize()
  2554  ** are omitted and the application must call sqlite3_initialize() directly
  2555  ** prior to using any other SQLite interface.  For maximum portability,
  2556  ** it is recommended that applications always invoke sqlite3_initialize()
  2557  ** directly prior to using any other SQLite interface.  Future releases
  2558  ** of SQLite may require this.  In other words, the behavior exhibited
  2559  ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2560  ** default behavior in some future release of SQLite.
  2561  **
  2562  ** The sqlite3_os_init() routine does operating-system specific
  2563  ** initialization of the SQLite library.  The sqlite3_os_end()
  2564  ** routine undoes the effect of sqlite3_os_init().  Typical tasks
  2565  ** performed by these routines include allocation or deallocation
  2566  ** of static resources, initialization of global variables,
  2567  ** setting up a default [sqlite3_vfs] module, or setting up
  2568  ** a default configuration using [sqlite3_config()].
  2569  **
  2570  ** The application should never invoke either sqlite3_os_init()
  2571  ** or sqlite3_os_end() directly.  The application should only invoke
  2572  ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
  2573  ** interface is called automatically by sqlite3_initialize() and
  2574  ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
  2575  ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2576  ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2577  ** When [custom builds | built for other platforms]
  2578  ** (using the [SQLITE_OS_OTHER=1] compile-time
  2579  ** option) the application must supply a suitable implementation for
  2580  ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
  2581  ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2582  ** must return [SQLITE_OK] on success and some other [error code] upon
  2583  ** failure.
  2584  */
  2585  SQLITE_API int sqlite3_initialize(void);
  2586  SQLITE_API int sqlite3_shutdown(void);
  2587  SQLITE_API int sqlite3_os_init(void);
  2588  SQLITE_API int sqlite3_os_end(void);
  2589  
  2590  /*
  2591  ** CAPI3REF: Configuring The SQLite Library
  2592  **
  2593  ** The sqlite3_config() interface is used to make global configuration
  2594  ** changes to SQLite in order to tune SQLite to the specific needs of
  2595  ** the application.  The default configuration is recommended for most
  2596  ** applications and so this routine is usually not necessary.  It is
  2597  ** provided to support rare applications with unusual needs.
  2598  **
  2599  ** <b>The sqlite3_config() interface is not threadsafe. The application
  2600  ** must ensure that no other SQLite interfaces are invoked by other
  2601  ** threads while sqlite3_config() is running.</b>
  2602  **
  2603  ** The sqlite3_config() interface
  2604  ** may only be invoked prior to library initialization using
  2605  ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2606  ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2607  ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2608  ** Note, however, that ^sqlite3_config() can be called as part of the
  2609  ** implementation of an application-defined [sqlite3_os_init()].
  2610  **
  2611  ** The first argument to sqlite3_config() is an integer
  2612  ** [configuration option] that determines
  2613  ** what property of SQLite is to be configured.  Subsequent arguments
  2614  ** vary depending on the [configuration option]
  2615  ** in the first argument.
  2616  **
  2617  ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2618  ** ^If the option is unknown or SQLite is unable to set the option
  2619  ** then this routine returns a non-zero [error code].
  2620  */
  2621  SQLITE_API int sqlite3_config(int, ...);
  2622  
  2623  /*
  2624  ** CAPI3REF: Configure database connections
  2625  ** METHOD: sqlite3
  2626  **
  2627  ** The sqlite3_db_config() interface is used to make configuration
  2628  ** changes to a [database connection].  The interface is similar to
  2629  ** [sqlite3_config()] except that the changes apply to a single
  2630  ** [database connection] (specified in the first argument).
  2631  **
  2632  ** The second argument to sqlite3_db_config(D,V,...)  is the
  2633  ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
  2634  ** that indicates what aspect of the [database connection] is being configured.
  2635  ** Subsequent arguments vary depending on the configuration verb.
  2636  **
  2637  ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2638  ** the call is considered successful.
  2639  */
  2640  SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2641  
  2642  /*
  2643  ** CAPI3REF: Memory Allocation Routines
  2644  **
  2645  ** An instance of this object defines the interface between SQLite
  2646  ** and low-level memory allocation routines.
  2647  **
  2648  ** This object is used in only one place in the SQLite interface.
  2649  ** A pointer to an instance of this object is the argument to
  2650  ** [sqlite3_config()] when the configuration option is
  2651  ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
  2652  ** By creating an instance of this object
  2653  ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2654  ** during configuration, an application can specify an alternative
  2655  ** memory allocation subsystem for SQLite to use for all of its
  2656  ** dynamic memory needs.
  2657  **
  2658  ** Note that SQLite comes with several [built-in memory allocators]
  2659  ** that are perfectly adequate for the overwhelming majority of applications
  2660  ** and that this object is only useful to a tiny minority of applications
  2661  ** with specialized memory allocation requirements.  This object is
  2662  ** also used during testing of SQLite in order to specify an alternative
  2663  ** memory allocator that simulates memory out-of-memory conditions in
  2664  ** order to verify that SQLite recovers gracefully from such
  2665  ** conditions.
  2666  **
  2667  ** The xMalloc, xRealloc, and xFree methods must work like the
  2668  ** malloc(), realloc() and free() functions from the standard C library.
  2669  ** ^SQLite guarantees that the second argument to
  2670  ** xRealloc is always a value returned by a prior call to xRoundup.
  2671  **
  2672  ** xSize should return the allocated size of a memory allocation
  2673  ** previously obtained from xMalloc or xRealloc.  The allocated size
  2674  ** is always at least as big as the requested size but may be larger.
  2675  **
  2676  ** The xRoundup method returns what would be the allocated size of
  2677  ** a memory allocation given a particular requested size.  Most memory
  2678  ** allocators round up memory allocations at least to the next multiple
  2679  ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
  2680  ** Every memory allocation request coming in through [sqlite3_malloc()]
  2681  ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
  2682  ** that causes the corresponding memory allocation to fail.
  2683  **
  2684  ** The xInit method initializes the memory allocator.  For example,
  2685  ** it might allocate any require mutexes or initialize internal data
  2686  ** structures.  The xShutdown method is invoked (indirectly) by
  2687  ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2688  ** by xInit.  The pAppData pointer is used as the only parameter to
  2689  ** xInit and xShutdown.
  2690  **
  2691  ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2692  ** the xInit method, so the xInit method need not be threadsafe.  The
  2693  ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2694  ** not need to be threadsafe either.  For all other methods, SQLite
  2695  ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2696  ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2697  ** it is by default) and so the methods are automatically serialized.
  2698  ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2699  ** methods must be threadsafe or else make their own arrangements for
  2700  ** serialization.
  2701  **
  2702  ** SQLite will never invoke xInit() more than once without an intervening
  2703  ** call to xShutdown().
  2704  */
  2705  typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2706  struct sqlite3_mem_methods {
  2707    void *(*xMalloc)(int);         /* Memory allocation function */
  2708    void (*xFree)(void*);          /* Free a prior allocation */
  2709    void *(*xRealloc)(void*,int);  /* Resize an allocation */
  2710    int (*xSize)(void*);           /* Return the size of an allocation */
  2711    int (*xRoundup)(int);          /* Round up request size to allocation size */
  2712    int (*xInit)(void*);           /* Initialize the memory allocator */
  2713    void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  2714    void *pAppData;                /* Argument to xInit() and xShutdown() */
  2715  };
  2716  
  2717  /*
  2718  ** CAPI3REF: Configuration Options
  2719  ** KEYWORDS: {configuration option}
  2720  **
  2721  ** These constants are the available integer configuration options that
  2722  ** can be passed as the first argument to the [sqlite3_config()] interface.
  2723  **
  2724  ** New configuration options may be added in future releases of SQLite.
  2725  ** Existing configuration options might be discontinued.  Applications
  2726  ** should check the return code from [sqlite3_config()] to make sure that
  2727  ** the call worked.  The [sqlite3_config()] interface will return a
  2728  ** non-zero [error code] if a discontinued or unsupported configuration option
  2729  ** is invoked.
  2730  **
  2731  ** <dl>
  2732  ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2733  ** <dd>There are no arguments to this option.  ^This option sets the
  2734  ** [threading mode] to Single-thread.  In other words, it disables
  2735  ** all mutexing and puts SQLite into a mode where it can only be used
  2736  ** by a single thread.   ^If SQLite is compiled with
  2737  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2738  ** it is not possible to change the [threading mode] from its default
  2739  ** value of Single-thread and so [sqlite3_config()] will return 
  2740  ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2741  ** configuration option.</dd>
  2742  **
  2743  ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2744  ** <dd>There are no arguments to this option.  ^This option sets the
  2745  ** [threading mode] to Multi-thread.  In other words, it disables
  2746  ** mutexing on [database connection] and [prepared statement] objects.
  2747  ** The application is responsible for serializing access to
  2748  ** [database connections] and [prepared statements].  But other mutexes
  2749  ** are enabled so that SQLite will be safe to use in a multi-threaded
  2750  ** environment as long as no two threads attempt to use the same
  2751  ** [database connection] at the same time.  ^If SQLite is compiled with
  2752  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2753  ** it is not possible to set the Multi-thread [threading mode] and
  2754  ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2755  ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2756  **
  2757  ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2758  ** <dd>There are no arguments to this option.  ^This option sets the
  2759  ** [threading mode] to Serialized. In other words, this option enables
  2760  ** all mutexes including the recursive
  2761  ** mutexes on [database connection] and [prepared statement] objects.
  2762  ** In this mode (which is the default when SQLite is compiled with
  2763  ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2764  ** to [database connections] and [prepared statements] so that the
  2765  ** application is free to use the same [database connection] or the
  2766  ** same [prepared statement] in different threads at the same time.
  2767  ** ^If SQLite is compiled with
  2768  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2769  ** it is not possible to set the Serialized [threading mode] and
  2770  ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2771  ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2772  **
  2773  ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2774  ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
  2775  ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2776  ** The argument specifies
  2777  ** alternative low-level memory allocation routines to be used in place of
  2778  ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2779  ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2780  ** before the [sqlite3_config()] call returns.</dd>
  2781  **
  2782  ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2783  ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2784  ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2785  ** The [sqlite3_mem_methods]
  2786  ** structure is filled with the currently defined memory allocation routines.)^
  2787  ** This option can be used to overload the default memory allocation
  2788  ** routines with a wrapper that simulations memory allocation failure or
  2789  ** tracks memory usage, for example. </dd>
  2790  **
  2791  ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2792  ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2793  ** type int, interpreted as a boolean, which if true provides a hint to
  2794  ** SQLite that it should avoid large memory allocations if possible.
  2795  ** SQLite will run faster if it is free to make large memory allocations,
  2796  ** but some application might prefer to run slower in exchange for
  2797  ** guarantees about memory fragmentation that are possible if large
  2798  ** allocations are avoided.  This hint is normally off.
  2799  ** </dd>
  2800  **
  2801  ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2802  ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2803  ** interpreted as a boolean, which enables or disables the collection of
  2804  ** memory allocation statistics. ^(When memory allocation statistics are
  2805  ** disabled, the following SQLite interfaces become non-operational:
  2806  **   <ul>
  2807  **   <li> [sqlite3_memory_used()]
  2808  **   <li> [sqlite3_memory_highwater()]
  2809  **   <li> [sqlite3_soft_heap_limit64()]
  2810  **   <li> [sqlite3_status64()]
  2811  **   </ul>)^
  2812  ** ^Memory allocation statistics are enabled by default unless SQLite is
  2813  ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2814  ** allocation statistics are disabled by default.
  2815  ** </dd>
  2816  **
  2817  ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2818  ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2819  ** </dd>
  2820  **
  2821  ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2822  ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2823  ** that SQLite can use for the database page cache with the default page
  2824  ** cache implementation.  
  2825  ** This configuration option is a no-op if an application-define page
  2826  ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2827  ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2828  ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2829  ** and the number of cache lines (N).
  2830  ** The sz argument should be the size of the largest database page
  2831  ** (a power of two between 512 and 65536) plus some extra bytes for each
  2832  ** page header.  ^The number of extra bytes needed by the page header
  2833  ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2834  ** ^It is harmless, apart from the wasted memory,
  2835  ** for the sz parameter to be larger than necessary.  The pMem
  2836  ** argument must be either a NULL pointer or a pointer to an 8-byte
  2837  ** aligned block of memory of at least sz*N bytes, otherwise
  2838  ** subsequent behavior is undefined.
  2839  ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2840  ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2841  ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2842  ** is exhausted.
  2843  ** ^If pMem is NULL and N is non-zero, then each database connection
  2844  ** does an initial bulk allocation for page cache memory
  2845  ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2846  ** of -1024*N bytes if N is negative, . ^If additional
  2847  ** page cache memory is needed beyond what is provided by the initial
  2848  ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2849  ** additional cache line. </dd>
  2850  **
  2851  ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2852  ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
  2853  ** that SQLite will use for all of its dynamic memory allocation needs
  2854  ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2855  ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2856  ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2857  ** [SQLITE_ERROR] if invoked otherwise.
  2858  ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2859  ** An 8-byte aligned pointer to the memory,
  2860  ** the number of bytes in the memory buffer, and the minimum allocation size.
  2861  ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2862  ** to using its default memory allocator (the system malloc() implementation),
  2863  ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
  2864  ** memory pointer is not NULL then the alternative memory
  2865  ** allocator is engaged to handle all of SQLites memory allocation needs.
  2866  ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2867  ** boundary or subsequent behavior of SQLite will be undefined.
  2868  ** The minimum allocation size is capped at 2**12. Reasonable values
  2869  ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2870  **
  2871  ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2872  ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2873  ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2874  ** The argument specifies alternative low-level mutex routines to be used
  2875  ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
  2876  ** the content of the [sqlite3_mutex_methods] structure before the call to
  2877  ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2878  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2879  ** the entire mutexing subsystem is omitted from the build and hence calls to
  2880  ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2881  ** return [SQLITE_ERROR].</dd>
  2882  **
  2883  ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2884  ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2885  ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
  2886  ** [sqlite3_mutex_methods]
  2887  ** structure is filled with the currently defined mutex routines.)^
  2888  ** This option can be used to overload the default mutex allocation
  2889  ** routines with a wrapper used to track mutex usage for performance
  2890  ** profiling or testing, for example.   ^If SQLite is compiled with
  2891  ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2892  ** the entire mutexing subsystem is omitted from the build and hence calls to
  2893  ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2894  ** return [SQLITE_ERROR].</dd>
  2895  **
  2896  ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2897  ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2898  ** the default size of lookaside memory on each [database connection].
  2899  ** The first argument is the
  2900  ** size of each lookaside buffer slot and the second is the number of
  2901  ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
  2902  ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2903  ** option to [sqlite3_db_config()] can be used to change the lookaside
  2904  ** configuration on individual connections.)^ </dd>
  2905  **
  2906  ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2907  ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
  2908  ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
  2909  ** the interface to a custom page cache implementation.)^
  2910  ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2911  **
  2912  ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2913  ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2914  ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
  2915  ** the current page cache implementation into that object.)^ </dd>
  2916  **
  2917  ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2918  ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2919  ** global [error log].
  2920  ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2921  ** function with a call signature of void(*)(void*,int,const char*), 
  2922  ** and a pointer to void. ^If the function pointer is not NULL, it is
  2923  ** invoked by [sqlite3_log()] to process each logging event.  ^If the
  2924  ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2925  ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2926  ** passed through as the first parameter to the application-defined logger
  2927  ** function whenever that function is invoked.  ^The second parameter to
  2928  ** the logger function is a copy of the first parameter to the corresponding
  2929  ** [sqlite3_log()] call and is intended to be a [result code] or an
  2930  ** [extended result code].  ^The third parameter passed to the logger is
  2931  ** log message after formatting via [sqlite3_snprintf()].
  2932  ** The SQLite logging interface is not reentrant; the logger function
  2933  ** supplied by the application must not invoke any SQLite interface.
  2934  ** In a multi-threaded application, the application-defined logger
  2935  ** function must be threadsafe. </dd>
  2936  **
  2937  ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2938  ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2939  ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2940  ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2941  ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2942  ** [sqlite3_open16()] or
  2943  ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2944  ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2945  ** connection is opened. ^If it is globally disabled, filenames are
  2946  ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2947  ** database connection is opened. ^(By default, URI handling is globally
  2948  ** disabled. The default value may be changed by compiling with the
  2949  ** [SQLITE_USE_URI] symbol defined.)^
  2950  **
  2951  ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2952  ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2953  ** argument which is interpreted as a boolean in order to enable or disable
  2954  ** the use of covering indices for full table scans in the query optimizer.
  2955  ** ^The default setting is determined
  2956  ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2957  ** if that compile-time option is omitted.
  2958  ** The ability to disable the use of covering indices for full table scans
  2959  ** is because some incorrectly coded legacy applications might malfunction
  2960  ** when the optimization is enabled.  Providing the ability to
  2961  ** disable the optimization allows the older, buggy application code to work
  2962  ** without change even with newer versions of SQLite.
  2963  **
  2964  ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2965  ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2966  ** <dd> These options are obsolete and should not be used by new code.
  2967  ** They are retained for backwards compatibility but are now no-ops.
  2968  ** </dd>
  2969  **
  2970  ** [[SQLITE_CONFIG_SQLLOG]]
  2971  ** <dt>SQLITE_CONFIG_SQLLOG
  2972  ** <dd>This option is only available if sqlite is compiled with the
  2973  ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2974  ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2975  ** The second should be of type (void*). The callback is invoked by the library
  2976  ** in three separate circumstances, identified by the value passed as the
  2977  ** fourth parameter. If the fourth parameter is 0, then the database connection
  2978  ** passed as the second argument has just been opened. The third argument
  2979  ** points to a buffer containing the name of the main database file. If the
  2980  ** fourth parameter is 1, then the SQL statement that the third parameter
  2981  ** points to has just been executed. Or, if the fourth parameter is 2, then
  2982  ** the connection being passed as the second parameter is being closed. The
  2983  ** third parameter is passed NULL In this case.  An example of using this
  2984  ** configuration option can be seen in the "test_sqllog.c" source file in
  2985  ** the canonical SQLite source tree.</dd>
  2986  **
  2987  ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2988  ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2989  ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2990  ** that are the default mmap size limit (the default setting for
  2991  ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2992  ** ^The default setting can be overridden by each database connection using
  2993  ** either the [PRAGMA mmap_size] command, or by using the
  2994  ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  2995  ** will be silently truncated if necessary so that it does not exceed the
  2996  ** compile-time maximum mmap size set by the
  2997  ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2998  ** ^If either argument to this option is negative, then that argument is
  2999  ** changed to its compile-time default.
  3000  **
  3001  ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  3002  ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  3003  ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  3004  ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  3005  ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  3006  ** that specifies the maximum size of the created heap.
  3007  **
  3008  ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  3009  ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  3010  ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  3011  ** is a pointer to an integer and writes into that integer the number of extra
  3012  ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  3013  ** The amount of extra space required can change depending on the compiler,
  3014  ** target platform, and SQLite version.
  3015  **
  3016  ** [[SQLITE_CONFIG_PMASZ]]
  3017  ** <dt>SQLITE_CONFIG_PMASZ
  3018  ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  3019  ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  3020  ** sorter to that integer.  The default minimum PMA Size is set by the
  3021  ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
  3022  ** to help with sort operations when multithreaded sorting
  3023  ** is enabled (using the [PRAGMA threads] command) and the amount of content
  3024  ** to be sorted exceeds the page size times the minimum of the
  3025  ** [PRAGMA cache_size] setting and this value.
  3026  **
  3027  ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  3028  ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  3029  ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  3030  ** becomes the [statement journal] spill-to-disk threshold.  
  3031  ** [Statement journals] are held in memory until their size (in bytes)
  3032  ** exceeds this threshold, at which point they are written to disk.
  3033  ** Or if the threshold is -1, statement journals are always held
  3034  ** exclusively in memory.
  3035  ** Since many statement journals never become large, setting the spill
  3036  ** threshold to a value such as 64KiB can greatly reduce the amount of
  3037  ** I/O required to support statement rollback.
  3038  ** The default value for this setting is controlled by the
  3039  ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  3040  **
  3041  ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  3042  ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  3043  ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  3044  ** of type (int) - the new value of the sorter-reference size threshold.
  3045  ** Usually, when SQLite uses an external sort to order records according
  3046  ** to an ORDER BY clause, all fields required by the caller are present in the
  3047  ** sorted records. However, if SQLite determines based on the declared type
  3048  ** of a table column that its values are likely to be very large - larger
  3049  ** than the configured sorter-reference size threshold - then a reference
  3050  ** is stored in each sorted record and the required column values loaded
  3051  ** from the database as records are returned in sorted order. The default
  3052  ** value for this option is to never use this optimization. Specifying a 
  3053  ** negative value for this option restores the default behaviour.
  3054  ** This option is only available if SQLite is compiled with the
  3055  ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  3056  **
  3057  ** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
  3058  ** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
  3059  ** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
  3060  ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
  3061  ** database created using [sqlite3_deserialize()].  This default maximum
  3062  ** size can be adjusted up or down for individual databases using the
  3063  ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control].  If this
  3064  ** configuration setting is never used, then the default maximum is determined
  3065  ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option.  If that
  3066  ** compile-time option is not set, then the default maximum is 1073741824.
  3067  ** </dl>
  3068  */
  3069  #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  3070  #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  3071  #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  3072  #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  3073  #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
  3074  #define SQLITE_CONFIG_SCRATCH       6  /* No longer used */
  3075  #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
  3076  #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
  3077  #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
  3078  #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
  3079  #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
  3080  /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
  3081  #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
  3082  #define SQLITE_CONFIG_PCACHE       14  /* no-op */
  3083  #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
  3084  #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
  3085  #define SQLITE_CONFIG_URI          17  /* int */
  3086  #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
  3087  #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  3088  #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
  3089  #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
  3090  #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
  3091  #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
  3092  #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
  3093  #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
  3094  #define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
  3095  #define SQLITE_CONFIG_SMALL_MALLOC        27  /* boolean */
  3096  #define SQLITE_CONFIG_SORTERREF_SIZE      28  /* int nByte */
  3097  #define SQLITE_CONFIG_MEMDB_MAXSIZE       29  /* sqlite3_int64 */
  3098  
  3099  /*
  3100  ** CAPI3REF: Database Connection Configuration Options
  3101  **
  3102  ** These constants are the available integer configuration options that
  3103  ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  3104  **
  3105  ** New configuration options may be added in future releases of SQLite.
  3106  ** Existing configuration options might be discontinued.  Applications
  3107  ** should check the return code from [sqlite3_db_config()] to make sure that
  3108  ** the call worked.  ^The [sqlite3_db_config()] interface will return a
  3109  ** non-zero [error code] if a discontinued or unsupported configuration option
  3110  ** is invoked.
  3111  **
  3112  ** <dl>
  3113  ** [[SQLITE_DBCONFIG_LOOKASIDE]]
  3114  ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  3115  ** <dd> ^This option takes three additional arguments that determine the 
  3116  ** [lookaside memory allocator] configuration for the [database connection].
  3117  ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3118  ** pointer to a memory buffer to use for lookaside memory.
  3119  ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3120  ** may be NULL in which case SQLite will allocate the
  3121  ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  3122  ** size of each lookaside buffer slot.  ^The third argument is the number of
  3123  ** slots.  The size of the buffer in the first argument must be greater than
  3124  ** or equal to the product of the second and third arguments.  The buffer
  3125  ** must be aligned to an 8-byte boundary.  ^If the second argument to
  3126  ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  3127  ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
  3128  ** configuration for a database connection can only be changed when that
  3129  ** connection is not currently using lookaside memory, or in other words
  3130  ** when the "current value" returned by
  3131  ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3132  ** Any attempt to change the lookaside memory configuration when lookaside
  3133  ** memory is in use leaves the configuration unchanged and returns 
  3134  ** [SQLITE_BUSY].)^</dd>
  3135  **
  3136  ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3137  ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3138  ** <dd> ^This option is used to enable or disable the enforcement of
  3139  ** [foreign key constraints].  There should be two additional arguments.
  3140  ** The first argument is an integer which is 0 to disable FK enforcement,
  3141  ** positive to enable FK enforcement or negative to leave FK enforcement
  3142  ** unchanged.  The second parameter is a pointer to an integer into which
  3143  ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3144  ** following this call.  The second parameter may be a NULL pointer, in
  3145  ** which case the FK enforcement setting is not reported back. </dd>
  3146  **
  3147  ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3148  ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3149  ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3150  ** There should be two additional arguments.
  3151  ** The first argument is an integer which is 0 to disable triggers,
  3152  ** positive to enable triggers or negative to leave the setting unchanged.
  3153  ** The second parameter is a pointer to an integer into which
  3154  ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3155  ** following this call.  The second parameter may be a NULL pointer, in
  3156  ** which case the trigger setting is not reported back. </dd>
  3157  **
  3158  ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3159  ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3160  ** <dd> ^This option is used to enable or disable the two-argument
  3161  ** version of the [fts3_tokenizer()] function which is part of the
  3162  ** [FTS3] full-text search engine extension.
  3163  ** There should be two additional arguments.
  3164  ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3165  ** positive to enable fts3_tokenizer() or negative to leave the setting
  3166  ** unchanged.
  3167  ** The second parameter is a pointer to an integer into which
  3168  ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3169  ** following this call.  The second parameter may be a NULL pointer, in
  3170  ** which case the new setting is not reported back. </dd>
  3171  **
  3172  ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3173  ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3174  ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3175  ** interface independently of the [load_extension()] SQL function.
  3176  ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3177  ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3178  ** There should be two additional arguments.
  3179  ** When the first argument to this interface is 1, then only the C-API is
  3180  ** enabled and the SQL function remains disabled.  If the first argument to
  3181  ** this interface is 0, then both the C-API and the SQL function are disabled.
  3182  ** If the first argument is -1, then no changes are made to state of either the
  3183  ** C-API or the SQL function.
  3184  ** The second parameter is a pointer to an integer into which
  3185  ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3186  ** is disabled or enabled following this call.  The second parameter may
  3187  ** be a NULL pointer, in which case the new setting is not reported back.
  3188  ** </dd>
  3189  **
  3190  ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3191  ** <dd> ^This option is used to change the name of the "main" database
  3192  ** schema.  ^The sole argument is a pointer to a constant UTF8 string
  3193  ** which will become the new schema name in place of "main".  ^SQLite
  3194  ** does not make a copy of the new main schema name string, so the application
  3195  ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3196  ** until after the database connection closes.
  3197  ** </dd>
  3198  **
  3199  ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] 
  3200  ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3201  ** <dd> Usually, when a database in wal mode is closed or detached from a 
  3202  ** database handle, SQLite checks if this will mean that there are now no 
  3203  ** connections at all to the database. If so, it performs a checkpoint 
  3204  ** operation before closing the connection. This option may be used to
  3205  ** override this behaviour. The first parameter passed to this operation
  3206  ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3207  ** default) to enable them, and negative to leave the setting unchanged.
  3208  ** The second parameter is a pointer to an integer
  3209  ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3210  ** have been disabled - 0 if they are not disabled, 1 if they are.
  3211  ** </dd>
  3212  **
  3213  ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3214  ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3215  ** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
  3216  ** a single SQL query statement will always use the same algorithm regardless
  3217  ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3218  ** that look at the values of bound parameters, which can make some queries
  3219  ** slower.  But the QPSG has the advantage of more predictable behavior.  With
  3220  ** the QPSG active, SQLite will always use the same query plan in the field as
  3221  ** was used during testing in the lab.
  3222  ** The first argument to this setting is an integer which is 0 to disable 
  3223  ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3224  ** unchanged. The second parameter is a pointer to an integer into which
  3225  ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3226  ** following this call.
  3227  ** </dd>
  3228  **
  3229  ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3230  ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not 
  3231  ** include output for any operations performed by trigger programs. This
  3232  ** option is used to set or clear (the default) a flag that governs this
  3233  ** behavior. The first parameter passed to this operation is an integer -
  3234  ** positive to enable output for trigger programs, or zero to disable it,
  3235  ** or negative to leave the setting unchanged.
  3236  ** The second parameter is a pointer to an integer into which is written 
  3237  ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
  3238  ** it is not disabled, 1 if it is.  
  3239  ** </dd>
  3240  **
  3241  ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3242  ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3243  ** [VACUUM] in order to reset a database back to an empty database
  3244  ** with no schema and no content. The following process works even for
  3245  ** a badly corrupted database file:
  3246  ** <ol>
  3247  ** <li> If the database connection is newly opened, make sure it has read the
  3248  **      database schema by preparing then discarding some query against the
  3249  **      database, or calling sqlite3_table_column_metadata(), ignoring any
  3250  **      errors.  This step is only necessary if the application desires to keep
  3251  **      the database in WAL mode after the reset if it was in WAL mode before
  3252  **      the reset.  
  3253  ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3254  ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3255  ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3256  ** </ol>
  3257  ** Because resetting a database is destructive and irreversible, the
  3258  ** process requires the use of this obscure API and multiple steps to help
  3259  ** ensure that it does not happen by accident.
  3260  **
  3261  ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3262  ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3263  ** "defensive" flag for a database connection.  When the defensive
  3264  ** flag is enabled, language features that allow ordinary SQL to 
  3265  ** deliberately corrupt the database file are disabled.  The disabled
  3266  ** features include but are not limited to the following:
  3267  ** <ul>
  3268  ** <li> The [PRAGMA writable_schema=ON] statement.
  3269  ** <li> Writes to the [sqlite_dbpage] virtual table.
  3270  ** <li> Direct writes to [shadow tables].
  3271  ** </ul>
  3272  ** </dd>
  3273  ** </dl>
  3274  */
  3275  #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
  3276  #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
  3277  #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
  3278  #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
  3279  #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3280  #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3281  #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
  3282  #define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
  3283  #define SQLITE_DBCONFIG_TRIGGER_EQP           1008 /* int int* */
  3284  #define SQLITE_DBCONFIG_RESET_DATABASE        1009 /* int int* */
  3285  #define SQLITE_DBCONFIG_DEFENSIVE             1010 /* int int* */
  3286  #define SQLITE_DBCONFIG_MAX                   1010 /* Largest DBCONFIG */
  3287  
  3288  /*
  3289  ** CAPI3REF: Enable Or Disable Extended Result Codes
  3290  ** METHOD: sqlite3
  3291  **
  3292  ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3293  ** [extended result codes] feature of SQLite. ^The extended result
  3294  ** codes are disabled by default for historical compatibility.
  3295  */
  3296  SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3297  
  3298  /*
  3299  ** CAPI3REF: Last Insert Rowid
  3300  ** METHOD: sqlite3
  3301  **
  3302  ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3303  ** has a unique 64-bit signed
  3304  ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3305  ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3306  ** names are not also used by explicitly declared columns. ^If
  3307  ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3308  ** is another alias for the rowid.
  3309  **
  3310  ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3311  ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3312  ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3313  ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred 
  3314  ** on the database connection D, then sqlite3_last_insert_rowid(D) returns 
  3315  ** zero.
  3316  **
  3317  ** As well as being set automatically as rows are inserted into database
  3318  ** tables, the value returned by this function may be set explicitly by
  3319  ** [sqlite3_set_last_insert_rowid()]
  3320  **
  3321  ** Some virtual table implementations may INSERT rows into rowid tables as
  3322  ** part of committing a transaction (e.g. to flush data accumulated in memory
  3323  ** to disk). In this case subsequent calls to this function return the rowid
  3324  ** associated with these internal INSERT operations, which leads to 
  3325  ** unintuitive results. Virtual table implementations that do write to rowid
  3326  ** tables in this way can avoid this problem by restoring the original 
  3327  ** rowid value using [sqlite3_set_last_insert_rowid()] before returning 
  3328  ** control to the user.
  3329  **
  3330  ** ^(If an [INSERT] occurs within a trigger then this routine will 
  3331  ** return the [rowid] of the inserted row as long as the trigger is 
  3332  ** running. Once the trigger program ends, the value returned 
  3333  ** by this routine reverts to what it was before the trigger was fired.)^
  3334  **
  3335  ** ^An [INSERT] that fails due to a constraint violation is not a
  3336  ** successful [INSERT] and does not change the value returned by this
  3337  ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3338  ** and INSERT OR ABORT make no changes to the return value of this
  3339  ** routine when their insertion fails.  ^(When INSERT OR REPLACE
  3340  ** encounters a constraint violation, it does not fail.  The
  3341  ** INSERT continues to completion after deleting rows that caused
  3342  ** the constraint problem so INSERT OR REPLACE will always change
  3343  ** the return value of this interface.)^
  3344  **
  3345  ** ^For the purposes of this routine, an [INSERT] is considered to
  3346  ** be successful even if it is subsequently rolled back.
  3347  **
  3348  ** This function is accessible to SQL statements via the
  3349  ** [last_insert_rowid() SQL function].
  3350  **
  3351  ** If a separate thread performs a new [INSERT] on the same
  3352  ** database connection while the [sqlite3_last_insert_rowid()]
  3353  ** function is running and thus changes the last insert [rowid],
  3354  ** then the value returned by [sqlite3_last_insert_rowid()] is
  3355  ** unpredictable and might not equal either the old or the new
  3356  ** last insert [rowid].
  3357  */
  3358  SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3359  
  3360  /*
  3361  ** CAPI3REF: Set the Last Insert Rowid value.
  3362  ** METHOD: sqlite3
  3363  **
  3364  ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3365  ** set the value returned by calling sqlite3_last_insert_rowid(D) to R 
  3366  ** without inserting a row into the database.
  3367  */
  3368  SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3369  
  3370  /*
  3371  ** CAPI3REF: Count The Number Of Rows Modified
  3372  ** METHOD: sqlite3
  3373  **
  3374  ** ^This function returns the number of rows modified, inserted or
  3375  ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3376  ** statement on the database connection specified by the only parameter.
  3377  ** ^Executing any other type of SQL statement does not modify the value
  3378  ** returned by this function.
  3379  **
  3380  ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3381  ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
  3382  ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3383  ** 
  3384  ** Changes to a view that are intercepted by 
  3385  ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
  3386  ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
  3387  ** DELETE statement run on a view is always zero. Only changes made to real 
  3388  ** tables are counted.
  3389  **
  3390  ** Things are more complicated if the sqlite3_changes() function is
  3391  ** executed while a trigger program is running. This may happen if the
  3392  ** program uses the [changes() SQL function], or if some other callback
  3393  ** function invokes sqlite3_changes() directly. Essentially:
  3394  ** 
  3395  ** <ul>
  3396  **   <li> ^(Before entering a trigger program the value returned by
  3397  **        sqlite3_changes() function is saved. After the trigger program 
  3398  **        has finished, the original value is restored.)^
  3399  ** 
  3400  **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
  3401  **        statement sets the value returned by sqlite3_changes() 
  3402  **        upon completion as normal. Of course, this value will not include 
  3403  **        any changes performed by sub-triggers, as the sqlite3_changes() 
  3404  **        value will be saved and restored after each sub-trigger has run.)^
  3405  ** </ul>
  3406  ** 
  3407  ** ^This means that if the changes() SQL function (or similar) is used
  3408  ** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
  3409  ** returns the value as set when the calling statement began executing.
  3410  ** ^If it is used by the second or subsequent such statement within a trigger 
  3411  ** program, the value returned reflects the number of rows modified by the 
  3412  ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3413  **
  3414  ** If a separate thread makes changes on the same database connection
  3415  ** while [sqlite3_changes()] is running then the value returned
  3416  ** is unpredictable and not meaningful.
  3417  **
  3418  ** See also:
  3419  ** <ul>
  3420  ** <li> the [sqlite3_total_changes()] interface
  3421  ** <li> the [count_changes pragma]
  3422  ** <li> the [changes() SQL function]
  3423  ** <li> the [data_version pragma]
  3424  ** </ul>
  3425  */
  3426  SQLITE_API int sqlite3_changes(sqlite3*);
  3427  
  3428  /*
  3429  ** CAPI3REF: Total Number Of Rows Modified
  3430  ** METHOD: sqlite3
  3431  **
  3432  ** ^This function returns the total number of rows inserted, modified or
  3433  ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3434  ** since the database connection was opened, including those executed as
  3435  ** part of trigger programs. ^Executing any other type of SQL statement
  3436  ** does not affect the value returned by sqlite3_total_changes().
  3437  ** 
  3438  ** ^Changes made as part of [foreign key actions] are included in the
  3439  ** count, but those made as part of REPLACE constraint resolution are
  3440  ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
  3441  ** are not counted.
  3442  **
  3443  ** The [sqlite3_total_changes(D)] interface only reports the number
  3444  ** of rows that changed due to SQL statement run against database
  3445  ** connection D.  Any changes by other database connections are ignored.
  3446  ** To detect changes against a database file from other database
  3447  ** connections use the [PRAGMA data_version] command or the
  3448  ** [SQLITE_FCNTL_DATA_VERSION] [file control].
  3449  ** 
  3450  ** If a separate thread makes changes on the same database connection
  3451  ** while [sqlite3_total_changes()] is running then the value
  3452  ** returned is unpredictable and not meaningful.
  3453  **
  3454  ** See also:
  3455  ** <ul>
  3456  ** <li> the [sqlite3_changes()] interface
  3457  ** <li> the [count_changes pragma]
  3458  ** <li> the [changes() SQL function]
  3459  ** <li> the [data_version pragma]
  3460  ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
  3461  ** </ul>
  3462  */
  3463  SQLITE_API int sqlite3_total_changes(sqlite3*);
  3464  
  3465  /*
  3466  ** CAPI3REF: Interrupt A Long-Running Query
  3467  ** METHOD: sqlite3
  3468  **
  3469  ** ^This function causes any pending database operation to abort and
  3470  ** return at its earliest opportunity. This routine is typically
  3471  ** called in response to a user action such as pressing "Cancel"
  3472  ** or Ctrl-C where the user wants a long query operation to halt
  3473  ** immediately.
  3474  **
  3475  ** ^It is safe to call this routine from a thread different from the
  3476  ** thread that is currently running the database operation.  But it
  3477  ** is not safe to call this routine with a [database connection] that
  3478  ** is closed or might close before sqlite3_interrupt() returns.
  3479  **
  3480  ** ^If an SQL operation is very nearly finished at the time when
  3481  ** sqlite3_interrupt() is called, then it might not have an opportunity
  3482  ** to be interrupted and might continue to completion.
  3483  **
  3484  ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3485  ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3486  ** that is inside an explicit transaction, then the entire transaction
  3487  ** will be rolled back automatically.
  3488  **
  3489  ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3490  ** SQL statements on [database connection] D complete.  ^Any new SQL statements
  3491  ** that are started after the sqlite3_interrupt() call and before the 
  3492  ** running statements reaches zero are interrupted as if they had been
  3493  ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
  3494  ** that are started after the running statement count reaches zero are
  3495  ** not effected by the sqlite3_interrupt().
  3496  ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3497  ** SQL statements is a no-op and has no effect on SQL statements
  3498  ** that are started after the sqlite3_interrupt() call returns.
  3499  */
  3500  SQLITE_API void sqlite3_interrupt(sqlite3*);
  3501  
  3502  /*
  3503  ** CAPI3REF: Determine If An SQL Statement Is Complete
  3504  **
  3505  ** These routines are useful during command-line input to determine if the
  3506  ** currently entered text seems to form a complete SQL statement or
  3507  ** if additional input is needed before sending the text into
  3508  ** SQLite for parsing.  ^These routines return 1 if the input string
  3509  ** appears to be a complete SQL statement.  ^A statement is judged to be
  3510  ** complete if it ends with a semicolon token and is not a prefix of a
  3511  ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
  3512  ** string literals or quoted identifier names or comments are not
  3513  ** independent tokens (they are part of the token in which they are
  3514  ** embedded) and thus do not count as a statement terminator.  ^Whitespace
  3515  ** and comments that follow the final semicolon are ignored.
  3516  **
  3517  ** ^These routines return 0 if the statement is incomplete.  ^If a
  3518  ** memory allocation fails, then SQLITE_NOMEM is returned.
  3519  **
  3520  ** ^These routines do not parse the SQL statements thus
  3521  ** will not detect syntactically incorrect SQL.
  3522  **
  3523  ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
  3524  ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3525  ** automatically by sqlite3_complete16().  If that initialization fails,
  3526  ** then the return value from sqlite3_complete16() will be non-zero
  3527  ** regardless of whether or not the input SQL is complete.)^
  3528  **
  3529  ** The input to [sqlite3_complete()] must be a zero-terminated
  3530  ** UTF-8 string.
  3531  **
  3532  ** The input to [sqlite3_complete16()] must be a zero-terminated
  3533  ** UTF-16 string in native byte order.
  3534  */
  3535  SQLITE_API int sqlite3_complete(const char *sql);
  3536  SQLITE_API int sqlite3_complete16(const void *sql);
  3537  
  3538  /*
  3539  ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3540  ** KEYWORDS: {busy-handler callback} {busy handler}
  3541  ** METHOD: sqlite3
  3542  **
  3543  ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3544  ** that might be invoked with argument P whenever
  3545  ** an attempt is made to access a database table associated with
  3546  ** [database connection] D when another thread
  3547  ** or process has the table locked.
  3548  ** The sqlite3_busy_handler() interface is used to implement
  3549  ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3550  **
  3551  ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3552  ** is returned immediately upon encountering the lock.  ^If the busy callback
  3553  ** is not NULL, then the callback might be invoked with two arguments.
  3554  **
  3555  ** ^The first argument to the busy handler is a copy of the void* pointer which
  3556  ** is the third argument to sqlite3_busy_handler().  ^The second argument to
  3557  ** the busy handler callback is the number of times that the busy handler has
  3558  ** been invoked previously for the same locking event.  ^If the
  3559  ** busy callback returns 0, then no additional attempts are made to
  3560  ** access the database and [SQLITE_BUSY] is returned
  3561  ** to the application.
  3562  ** ^If the callback returns non-zero, then another attempt
  3563  ** is made to access the database and the cycle repeats.
  3564  **
  3565  ** The presence of a busy handler does not guarantee that it will be invoked
  3566  ** when there is lock contention. ^If SQLite determines that invoking the busy
  3567  ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3568  ** to the application instead of invoking the 
  3569  ** busy handler.
  3570  ** Consider a scenario where one process is holding a read lock that
  3571  ** it is trying to promote to a reserved lock and
  3572  ** a second process is holding a reserved lock that it is trying
  3573  ** to promote to an exclusive lock.  The first process cannot proceed
  3574  ** because it is blocked by the second and the second process cannot
  3575  ** proceed because it is blocked by the first.  If both processes
  3576  ** invoke the busy handlers, neither will make any progress.  Therefore,
  3577  ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3578  ** will induce the first process to release its read lock and allow
  3579  ** the second process to proceed.
  3580  **
  3581  ** ^The default busy callback is NULL.
  3582  **
  3583  ** ^(There can only be a single busy handler defined for each
  3584  ** [database connection].  Setting a new busy handler clears any
  3585  ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
  3586  ** or evaluating [PRAGMA busy_timeout=N] will change the
  3587  ** busy handler and thus clear any previously set busy handler.
  3588  **
  3589  ** The busy callback should not take any actions which modify the
  3590  ** database connection that invoked the busy handler.  In other words,
  3591  ** the busy handler is not reentrant.  Any such actions
  3592  ** result in undefined behavior.
  3593  ** 
  3594  ** A busy handler must not close the database connection
  3595  ** or [prepared statement] that invoked the busy handler.
  3596  */
  3597  SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3598  
  3599  /*
  3600  ** CAPI3REF: Set A Busy Timeout
  3601  ** METHOD: sqlite3
  3602  **
  3603  ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3604  ** for a specified amount of time when a table is locked.  ^The handler
  3605  ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3606  ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
  3607  ** the handler returns 0 which causes [sqlite3_step()] to return
  3608  ** [SQLITE_BUSY].
  3609  **
  3610  ** ^Calling this routine with an argument less than or equal to zero
  3611  ** turns off all busy handlers.
  3612  **
  3613  ** ^(There can only be a single busy handler for a particular
  3614  ** [database connection] at any given moment.  If another busy handler
  3615  ** was defined  (using [sqlite3_busy_handler()]) prior to calling
  3616  ** this routine, that other busy handler is cleared.)^
  3617  **
  3618  ** See also:  [PRAGMA busy_timeout]
  3619  */
  3620  SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3621  
  3622  /*
  3623  ** CAPI3REF: Convenience Routines For Running Queries
  3624  ** METHOD: sqlite3
  3625  **
  3626  ** This is a legacy interface that is preserved for backwards compatibility.
  3627  ** Use of this interface is not recommended.
  3628  **
  3629  ** Definition: A <b>result table</b> is memory data structure created by the
  3630  ** [sqlite3_get_table()] interface.  A result table records the
  3631  ** complete query results from one or more queries.
  3632  **
  3633  ** The table conceptually has a number of rows and columns.  But
  3634  ** these numbers are not part of the result table itself.  These
  3635  ** numbers are obtained separately.  Let N be the number of rows
  3636  ** and M be the number of columns.
  3637  **
  3638  ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3639  ** There are (N+1)*M elements in the array.  The first M pointers point
  3640  ** to zero-terminated strings that  contain the names of the columns.
  3641  ** The remaining entries all point to query results.  NULL values result
  3642  ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
  3643  ** string representation as returned by [sqlite3_column_text()].
  3644  **
  3645  ** A result table might consist of one or more memory allocations.
  3646  ** It is not safe to pass a result table directly to [sqlite3_free()].
  3647  ** A result table should be deallocated using [sqlite3_free_table()].
  3648  **
  3649  ** ^(As an example of the result table format, suppose a query result
  3650  ** is as follows:
  3651  **
  3652  ** <blockquote><pre>
  3653  **        Name        | Age
  3654  **        -----------------------
  3655  **        Alice       | 43
  3656  **        Bob         | 28
  3657  **        Cindy       | 21
  3658  ** </pre></blockquote>
  3659  **
  3660  ** There are two column (M==2) and three rows (N==3).  Thus the
  3661  ** result table has 8 entries.  Suppose the result table is stored
  3662  ** in an array names azResult.  Then azResult holds this content:
  3663  **
  3664  ** <blockquote><pre>
  3665  **        azResult&#91;0] = "Name";
  3666  **        azResult&#91;1] = "Age";
  3667  **        azResult&#91;2] = "Alice";
  3668  **        azResult&#91;3] = "43";
  3669  **        azResult&#91;4] = "Bob";
  3670  **        azResult&#91;5] = "28";
  3671  **        azResult&#91;6] = "Cindy";
  3672  **        azResult&#91;7] = "21";
  3673  ** </pre></blockquote>)^
  3674  **
  3675  ** ^The sqlite3_get_table() function evaluates one or more
  3676  ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3677  ** string of its 2nd parameter and returns a result table to the
  3678  ** pointer given in its 3rd parameter.
  3679  **
  3680  ** After the application has finished with the result from sqlite3_get_table(),
  3681  ** it must pass the result table pointer to sqlite3_free_table() in order to
  3682  ** release the memory that was malloced.  Because of the way the
  3683  ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3684  ** function must not try to call [sqlite3_free()] directly.  Only
  3685  ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3686  **
  3687  ** The sqlite3_get_table() interface is implemented as a wrapper around
  3688  ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
  3689  ** to any internal data structures of SQLite.  It uses only the public
  3690  ** interface defined here.  As a consequence, errors that occur in the
  3691  ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3692  ** reflected in subsequent calls to [sqlite3_errcode()] or
  3693  ** [sqlite3_errmsg()].
  3694  */
  3695  SQLITE_API int sqlite3_get_table(
  3696    sqlite3 *db,          /* An open database */
  3697    const char *zSql,     /* SQL to be evaluated */
  3698    char ***pazResult,    /* Results of the query */
  3699    int *pnRow,           /* Number of result rows written here */
  3700    int *pnColumn,        /* Number of result columns written here */
  3701    char **pzErrmsg       /* Error msg written here */
  3702  );
  3703  SQLITE_API void sqlite3_free_table(char **result);
  3704  
  3705  /*
  3706  ** CAPI3REF: Formatted String Printing Functions
  3707  **
  3708  ** These routines are work-alikes of the "printf()" family of functions
  3709  ** from the standard C library.
  3710  ** These routines understand most of the common formatting options from
  3711  ** the standard library printf() 
  3712  ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3713  ** See the [built-in printf()] documentation for details.
  3714  **
  3715  ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3716  ** results into memory obtained from [sqlite3_malloc64()].
  3717  ** The strings returned by these two routines should be
  3718  ** released by [sqlite3_free()].  ^Both routines return a
  3719  ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3720  ** memory to hold the resulting string.
  3721  **
  3722  ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3723  ** the standard C library.  The result is written into the
  3724  ** buffer supplied as the second parameter whose size is given by
  3725  ** the first parameter. Note that the order of the
  3726  ** first two parameters is reversed from snprintf().)^  This is an
  3727  ** historical accident that cannot be fixed without breaking
  3728  ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
  3729  ** returns a pointer to its buffer instead of the number of
  3730  ** characters actually written into the buffer.)^  We admit that
  3731  ** the number of characters written would be a more useful return
  3732  ** value but we cannot change the implementation of sqlite3_snprintf()
  3733  ** now without breaking compatibility.
  3734  **
  3735  ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3736  ** guarantees that the buffer is always zero-terminated.  ^The first
  3737  ** parameter "n" is the total size of the buffer, including space for
  3738  ** the zero terminator.  So the longest string that can be completely
  3739  ** written will be n-1 characters.
  3740  **
  3741  ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3742  **
  3743  ** See also:  [built-in printf()], [printf() SQL function]
  3744  */
  3745  SQLITE_API char *sqlite3_mprintf(const char*,...);
  3746  SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3747  SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3748  SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3749  
  3750  /*
  3751  ** CAPI3REF: Memory Allocation Subsystem
  3752  **
  3753  ** The SQLite core uses these three routines for all of its own
  3754  ** internal memory allocation needs. "Core" in the previous sentence
  3755  ** does not include operating-system specific VFS implementation.  The
  3756  ** Windows VFS uses native malloc() and free() for some operations.
  3757  **
  3758  ** ^The sqlite3_malloc() routine returns a pointer to a block
  3759  ** of memory at least N bytes in length, where N is the parameter.
  3760  ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3761  ** memory, it returns a NULL pointer.  ^If the parameter N to
  3762  ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3763  ** a NULL pointer.
  3764  **
  3765  ** ^The sqlite3_malloc64(N) routine works just like
  3766  ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3767  ** of a signed 32-bit integer.
  3768  **
  3769  ** ^Calling sqlite3_free() with a pointer previously returned
  3770  ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3771  ** that it might be reused.  ^The sqlite3_free() routine is
  3772  ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
  3773  ** to sqlite3_free() is harmless.  After being freed, memory
  3774  ** should neither be read nor written.  Even reading previously freed
  3775  ** memory might result in a segmentation fault or other severe error.
  3776  ** Memory corruption, a segmentation fault, or other severe error
  3777  ** might result if sqlite3_free() is called with a non-NULL pointer that
  3778  ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3779  **
  3780  ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3781  ** prior memory allocation X to be at least N bytes.
  3782  ** ^If the X parameter to sqlite3_realloc(X,N)
  3783  ** is a NULL pointer then its behavior is identical to calling
  3784  ** sqlite3_malloc(N).
  3785  ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3786  ** negative then the behavior is exactly the same as calling
  3787  ** sqlite3_free(X).
  3788  ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3789  ** of at least N bytes in size or NULL if insufficient memory is available.
  3790  ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3791  ** of the prior allocation are copied into the beginning of buffer returned
  3792  ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3793  ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3794  ** prior allocation is not freed.
  3795  **
  3796  ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3797  ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3798  ** of a 32-bit signed integer.
  3799  **
  3800  ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3801  ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3802  ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3803  ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3804  ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
  3805  ** sqlite3_msize(X) returns zero.  If X points to something that is not
  3806  ** the beginning of memory allocation, or if it points to a formerly
  3807  ** valid memory allocation that has now been freed, then the behavior
  3808  ** of sqlite3_msize(X) is undefined and possibly harmful.
  3809  **
  3810  ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3811  ** sqlite3_malloc64(), and sqlite3_realloc64()
  3812  ** is always aligned to at least an 8 byte boundary, or to a
  3813  ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3814  ** option is used.
  3815  **
  3816  ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3817  ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3818  ** implementation of these routines to be omitted.  That capability
  3819  ** is no longer provided.  Only built-in memory allocators can be used.
  3820  **
  3821  ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3822  ** the system malloc() and free() directly when converting
  3823  ** filenames between the UTF-8 encoding used by SQLite
  3824  ** and whatever filename encoding is used by the particular Windows
  3825  ** installation.  Memory allocation errors were detected, but
  3826  ** they were reported back as [SQLITE_CANTOPEN] or
  3827  ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3828  **
  3829  ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3830  ** must be either NULL or else pointers obtained from a prior
  3831  ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3832  ** not yet been released.
  3833  **
  3834  ** The application must not read or write any part of
  3835  ** a block of memory after it has been released using
  3836  ** [sqlite3_free()] or [sqlite3_realloc()].
  3837  */
  3838  SQLITE_API void *sqlite3_malloc(int);
  3839  SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3840  SQLITE_API void *sqlite3_realloc(void*, int);
  3841  SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3842  SQLITE_API void sqlite3_free(void*);
  3843  SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3844  
  3845  /*
  3846  ** CAPI3REF: Memory Allocator Statistics
  3847  **
  3848  ** SQLite provides these two interfaces for reporting on the status
  3849  ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3850  ** routines, which form the built-in memory allocation subsystem.
  3851  **
  3852  ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3853  ** of memory currently outstanding (malloced but not freed).
  3854  ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3855  ** value of [sqlite3_memory_used()] since the high-water mark
  3856  ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
  3857  ** [sqlite3_memory_highwater()] include any overhead
  3858  ** added by SQLite in its implementation of [sqlite3_malloc()],
  3859  ** but not overhead added by the any underlying system library
  3860  ** routines that [sqlite3_malloc()] may call.
  3861  **
  3862  ** ^The memory high-water mark is reset to the current value of
  3863  ** [sqlite3_memory_used()] if and only if the parameter to
  3864  ** [sqlite3_memory_highwater()] is true.  ^The value returned
  3865  ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3866  ** prior to the reset.
  3867  */
  3868  SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3869  SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3870  
  3871  /*
  3872  ** CAPI3REF: Pseudo-Random Number Generator
  3873  **
  3874  ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3875  ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3876  ** already uses the largest possible [ROWID].  The PRNG is also used for
  3877  ** the build-in random() and randomblob() SQL functions.  This interface allows
  3878  ** applications to access the same PRNG for other purposes.
  3879  **
  3880  ** ^A call to this routine stores N bytes of randomness into buffer P.
  3881  ** ^The P parameter can be a NULL pointer.
  3882  **
  3883  ** ^If this routine has not been previously called or if the previous
  3884  ** call had N less than one or a NULL pointer for P, then the PRNG is
  3885  ** seeded using randomness obtained from the xRandomness method of
  3886  ** the default [sqlite3_vfs] object.
  3887  ** ^If the previous call to this routine had an N of 1 or more and a
  3888  ** non-NULL P then the pseudo-randomness is generated
  3889  ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3890  ** method.
  3891  */
  3892  SQLITE_API void sqlite3_randomness(int N, void *P);
  3893  
  3894  /*
  3895  ** CAPI3REF: Compile-Time Authorization Callbacks
  3896  ** METHOD: sqlite3
  3897  ** KEYWORDS: {authorizer callback}
  3898  **
  3899  ** ^This routine registers an authorizer callback with a particular
  3900  ** [database connection], supplied in the first argument.
  3901  ** ^The authorizer callback is invoked as SQL statements are being compiled
  3902  ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3903  ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3904  ** and [sqlite3_prepare16_v3()].  ^At various
  3905  ** points during the compilation process, as logic is being created
  3906  ** to perform various actions, the authorizer callback is invoked to
  3907  ** see if those actions are allowed.  ^The authorizer callback should
  3908  ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3909  ** specific action but allow the SQL statement to continue to be
  3910  ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3911  ** rejected with an error.  ^If the authorizer callback returns
  3912  ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3913  ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3914  ** the authorizer will fail with an error message.
  3915  **
  3916  ** When the callback returns [SQLITE_OK], that means the operation
  3917  ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
  3918  ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3919  ** authorizer will fail with an error message explaining that
  3920  ** access is denied. 
  3921  **
  3922  ** ^The first parameter to the authorizer callback is a copy of the third
  3923  ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3924  ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3925  ** the particular action to be authorized. ^The third through sixth parameters
  3926  ** to the callback are either NULL pointers or zero-terminated strings
  3927  ** that contain additional details about the action to be authorized.
  3928  ** Applications must always be prepared to encounter a NULL pointer in any
  3929  ** of the third through the sixth parameters of the authorization callback.
  3930  **
  3931  ** ^If the action code is [SQLITE_READ]
  3932  ** and the callback returns [SQLITE_IGNORE] then the
  3933  ** [prepared statement] statement is constructed to substitute
  3934  ** a NULL value in place of the table column that would have
  3935  ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
  3936  ** return can be used to deny an untrusted user access to individual
  3937  ** columns of a table.
  3938  ** ^When a table is referenced by a [SELECT] but no column values are
  3939  ** extracted from that table (for example in a query like
  3940  ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3941  ** is invoked once for that table with a column name that is an empty string.
  3942  ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3943  ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3944  ** [truncate optimization] is disabled and all rows are deleted individually.
  3945  **
  3946  ** An authorizer is used when [sqlite3_prepare | preparing]
  3947  ** SQL statements from an untrusted source, to ensure that the SQL statements
  3948  ** do not try to access data they are not allowed to see, or that they do not
  3949  ** try to execute malicious statements that damage the database.  For
  3950  ** example, an application may allow a user to enter arbitrary
  3951  ** SQL queries for evaluation by a database.  But the application does
  3952  ** not want the user to be able to make arbitrary changes to the
  3953  ** database.  An authorizer could then be put in place while the
  3954  ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3955  ** disallows everything except [SELECT] statements.
  3956  **
  3957  ** Applications that need to process SQL from untrusted sources
  3958  ** might also consider lowering resource limits using [sqlite3_limit()]
  3959  ** and limiting database size using the [max_page_count] [PRAGMA]
  3960  ** in addition to using an authorizer.
  3961  **
  3962  ** ^(Only a single authorizer can be in place on a database connection
  3963  ** at a time.  Each call to sqlite3_set_authorizer overrides the
  3964  ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
  3965  ** The authorizer is disabled by default.
  3966  **
  3967  ** The authorizer callback must not do anything that will modify
  3968  ** the database connection that invoked the authorizer callback.
  3969  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3970  ** database connections for the meaning of "modify" in this paragraph.
  3971  **
  3972  ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3973  ** statement might be re-prepared during [sqlite3_step()] due to a 
  3974  ** schema change.  Hence, the application should ensure that the
  3975  ** correct authorizer callback remains in place during the [sqlite3_step()].
  3976  **
  3977  ** ^Note that the authorizer callback is invoked only during
  3978  ** [sqlite3_prepare()] or its variants.  Authorization is not
  3979  ** performed during statement evaluation in [sqlite3_step()], unless
  3980  ** as stated in the previous paragraph, sqlite3_step() invokes
  3981  ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3982  */
  3983  SQLITE_API int sqlite3_set_authorizer(
  3984    sqlite3*,
  3985    int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3986    void *pUserData
  3987  );
  3988  
  3989  /*
  3990  ** CAPI3REF: Authorizer Return Codes
  3991  **
  3992  ** The [sqlite3_set_authorizer | authorizer callback function] must
  3993  ** return either [SQLITE_OK] or one of these two constants in order
  3994  ** to signal SQLite whether or not the action is permitted.  See the
  3995  ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3996  ** information.
  3997  **
  3998  ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3999  ** returned from the [sqlite3_vtab_on_conflict()] interface.
  4000  */
  4001  #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
  4002  #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
  4003  
  4004  /*
  4005  ** CAPI3REF: Authorizer Action Codes
  4006  **
  4007  ** The [sqlite3_set_authorizer()] interface registers a callback function
  4008  ** that is invoked to authorize certain SQL statement actions.  The
  4009  ** second parameter to the callback is an integer code that specifies
  4010  ** what action is being authorized.  These are the integer action codes that
  4011  ** the authorizer callback may be passed.
  4012  **
  4013  ** These action code values signify what kind of operation is to be
  4014  ** authorized.  The 3rd and 4th parameters to the authorization
  4015  ** callback function will be parameters or NULL depending on which of these
  4016  ** codes is used as the second parameter.  ^(The 5th parameter to the
  4017  ** authorizer callback is the name of the database ("main", "temp",
  4018  ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
  4019  ** is the name of the inner-most trigger or view that is responsible for
  4020  ** the access attempt or NULL if this access attempt is directly from
  4021  ** top-level SQL code.
  4022  */
  4023  /******************************************* 3rd ************ 4th ***********/
  4024  #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
  4025  #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
  4026  #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
  4027  #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
  4028  #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
  4029  #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
  4030  #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
  4031  #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
  4032  #define SQLITE_DELETE                9   /* Table Name      NULL            */
  4033  #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
  4034  #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
  4035  #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
  4036  #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
  4037  #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
  4038  #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
  4039  #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
  4040  #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
  4041  #define SQLITE_INSERT               18   /* Table Name      NULL            */
  4042  #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
  4043  #define SQLITE_READ                 20   /* Table Name      Column Name     */
  4044  #define SQLITE_SELECT               21   /* NULL            NULL            */
  4045  #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
  4046  #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
  4047  #define SQLITE_ATTACH               24   /* Filename        NULL            */
  4048  #define SQLITE_DETACH               25   /* Database Name   NULL            */
  4049  #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
  4050  #define SQLITE_REINDEX              27   /* Index Name      NULL            */
  4051  #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
  4052  #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
  4053  #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
  4054  #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
  4055  #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
  4056  #define SQLITE_COPY                  0   /* No longer used */
  4057  #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
  4058  
  4059  /*
  4060  ** CAPI3REF: Tracing And Profiling Functions
  4061  ** METHOD: sqlite3
  4062  **
  4063  ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  4064  ** instead of the routines described here.
  4065  **
  4066  ** These routines register callback functions that can be used for
  4067  ** tracing and profiling the execution of SQL statements.
  4068  **
  4069  ** ^The callback function registered by sqlite3_trace() is invoked at
  4070  ** various times when an SQL statement is being run by [sqlite3_step()].
  4071  ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  4072  ** SQL statement text as the statement first begins executing.
  4073  ** ^(Additional sqlite3_trace() callbacks might occur
  4074  ** as each triggered subprogram is entered.  The callbacks for triggers
  4075  ** contain a UTF-8 SQL comment that identifies the trigger.)^
  4076  **
  4077  ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  4078  ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  4079  **
  4080  ** ^The callback function registered by sqlite3_profile() is invoked
  4081  ** as each SQL statement finishes.  ^The profile callback contains
  4082  ** the original statement text and an estimate of wall-clock time
  4083  ** of how long that statement took to run.  ^The profile callback
  4084  ** time is in units of nanoseconds, however the current implementation
  4085  ** is only capable of millisecond resolution so the six least significant
  4086  ** digits in the time are meaningless.  Future versions of SQLite
  4087  ** might provide greater resolution on the profiler callback.  Invoking
  4088  ** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
  4089  ** profile callback.
  4090  */
  4091  SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  4092     void(*xTrace)(void*,const char*), void*);
  4093  SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  4094     void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  4095  
  4096  /*
  4097  ** CAPI3REF: SQL Trace Event Codes
  4098  ** KEYWORDS: SQLITE_TRACE
  4099  **
  4100  ** These constants identify classes of events that can be monitored
  4101  ** using the [sqlite3_trace_v2()] tracing logic.  The M argument
  4102  ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  4103  ** the following constants.  ^The first argument to the trace callback
  4104  ** is one of the following constants.
  4105  **
  4106  ** New tracing constants may be added in future releases.
  4107  **
  4108  ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  4109  ** ^The T argument is one of the integer type codes above.
  4110  ** ^The C argument is a copy of the context pointer passed in as the
  4111  ** fourth argument to [sqlite3_trace_v2()].
  4112  ** The P and X arguments are pointers whose meanings depend on T.
  4113  **
  4114  ** <dl>
  4115  ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  4116  ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  4117  ** first begins running and possibly at other times during the
  4118  ** execution of the prepared statement, such as at the start of each
  4119  ** trigger subprogram. ^The P argument is a pointer to the
  4120  ** [prepared statement]. ^The X argument is a pointer to a string which
  4121  ** is the unexpanded SQL text of the prepared statement or an SQL comment 
  4122  ** that indicates the invocation of a trigger.  ^The callback can compute
  4123  ** the same text that would have been returned by the legacy [sqlite3_trace()]
  4124  ** interface by using the X argument when X begins with "--" and invoking
  4125  ** [sqlite3_expanded_sql(P)] otherwise.
  4126  **
  4127  ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  4128  ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  4129  ** information as is provided by the [sqlite3_profile()] callback.
  4130  ** ^The P argument is a pointer to the [prepared statement] and the
  4131  ** X argument points to a 64-bit integer which is the estimated of
  4132  ** the number of nanosecond that the prepared statement took to run.
  4133  ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  4134  **
  4135  ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  4136  ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  4137  ** statement generates a single row of result.  
  4138  ** ^The P argument is a pointer to the [prepared statement] and the
  4139  ** X argument is unused.
  4140  **
  4141  ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4142  ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4143  ** connection closes.
  4144  ** ^The P argument is a pointer to the [database connection] object
  4145  ** and the X argument is unused.
  4146  ** </dl>
  4147  */
  4148  #define SQLITE_TRACE_STMT       0x01
  4149  #define SQLITE_TRACE_PROFILE    0x02
  4150  #define SQLITE_TRACE_ROW        0x04
  4151  #define SQLITE_TRACE_CLOSE      0x08
  4152  
  4153  /*
  4154  ** CAPI3REF: SQL Trace Hook
  4155  ** METHOD: sqlite3
  4156  **
  4157  ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4158  ** function X against [database connection] D, using property mask M
  4159  ** and context pointer P.  ^If the X callback is
  4160  ** NULL or if the M mask is zero, then tracing is disabled.  The
  4161  ** M argument should be the bitwise OR-ed combination of
  4162  ** zero or more [SQLITE_TRACE] constants.
  4163  **
  4164  ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides 
  4165  ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4166  **
  4167  ** ^The X callback is invoked whenever any of the events identified by 
  4168  ** mask M occur.  ^The integer return value from the callback is currently
  4169  ** ignored, though this may change in future releases.  Callback
  4170  ** implementations should return zero to ensure future compatibility.
  4171  **
  4172  ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4173  ** ^The T argument is one of the [SQLITE_TRACE]
  4174  ** constants to indicate why the callback was invoked.
  4175  ** ^The C argument is a copy of the context pointer.
  4176  ** The P and X arguments are pointers whose meanings depend on T.
  4177  **
  4178  ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4179  ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4180  ** are deprecated.
  4181  */
  4182  SQLITE_API int sqlite3_trace_v2(
  4183    sqlite3*,
  4184    unsigned uMask,
  4185    int(*xCallback)(unsigned,void*,void*,void*),
  4186    void *pCtx
  4187  );
  4188  
  4189  /*
  4190  ** CAPI3REF: Query Progress Callbacks
  4191  ** METHOD: sqlite3
  4192  **
  4193  ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4194  ** function X to be invoked periodically during long running calls to
  4195  ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4196  ** database connection D.  An example use for this
  4197  ** interface is to keep a GUI updated during a large query.
  4198  **
  4199  ** ^The parameter P is passed through as the only parameter to the 
  4200  ** callback function X.  ^The parameter N is the approximate number of 
  4201  ** [virtual machine instructions] that are evaluated between successive
  4202  ** invocations of the callback X.  ^If N is less than one then the progress
  4203  ** handler is disabled.
  4204  **
  4205  ** ^Only a single progress handler may be defined at one time per
  4206  ** [database connection]; setting a new progress handler cancels the
  4207  ** old one.  ^Setting parameter X to NULL disables the progress handler.
  4208  ** ^The progress handler is also disabled by setting N to a value less
  4209  ** than 1.
  4210  **
  4211  ** ^If the progress callback returns non-zero, the operation is
  4212  ** interrupted.  This feature can be used to implement a
  4213  ** "Cancel" button on a GUI progress dialog box.
  4214  **
  4215  ** The progress handler callback must not do anything that will modify
  4216  ** the database connection that invoked the progress handler.
  4217  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4218  ** database connections for the meaning of "modify" in this paragraph.
  4219  **
  4220  */
  4221  SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4222  
  4223  /*
  4224  ** CAPI3REF: Opening A New Database Connection
  4225  ** CONSTRUCTOR: sqlite3
  4226  **
  4227  ** ^These routines open an SQLite database file as specified by the 
  4228  ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4229  ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4230  ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4231  ** returned in *ppDb, even if an error occurs.  The only exception is that
  4232  ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4233  ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4234  ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4235  ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
  4236  ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4237  ** an English language description of the error following a failure of any
  4238  ** of the sqlite3_open() routines.
  4239  **
  4240  ** ^The default encoding will be UTF-8 for databases created using
  4241  ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
  4242  ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4243  **
  4244  ** Whether or not an error occurs when it is opened, resources
  4245  ** associated with the [database connection] handle should be released by
  4246  ** passing it to [sqlite3_close()] when it is no longer required.
  4247  **
  4248  ** The sqlite3_open_v2() interface works like sqlite3_open()
  4249  ** except that it accepts two additional parameters for additional control
  4250  ** over the new database connection.  ^(The flags parameter to
  4251  ** sqlite3_open_v2() can take one of
  4252  ** the following three values, optionally combined with the 
  4253  ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4254  ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4255  **
  4256  ** <dl>
  4257  ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4258  ** <dd>The database is opened in read-only mode.  If the database does not
  4259  ** already exist, an error is returned.</dd>)^
  4260  **
  4261  ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4262  ** <dd>The database is opened for reading and writing if possible, or reading
  4263  ** only if the file is write protected by the operating system.  In either
  4264  ** case the database must already exist, otherwise an error is returned.</dd>)^
  4265  **
  4266  ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4267  ** <dd>The database is opened for reading and writing, and is created if
  4268  ** it does not already exist. This is the behavior that is always used for
  4269  ** sqlite3_open() and sqlite3_open16().</dd>)^
  4270  ** </dl>
  4271  **
  4272  ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4273  ** combinations shown above optionally combined with other
  4274  ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4275  ** then the behavior is undefined.
  4276  **
  4277  ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4278  ** opens in the multi-thread [threading mode] as long as the single-thread
  4279  ** mode has not been set at compile-time or start-time.  ^If the
  4280  ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4281  ** in the serialized [threading mode] unless single-thread was
  4282  ** previously selected at compile-time or start-time.
  4283  ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4284  ** eligible to use [shared cache mode], regardless of whether or not shared
  4285  ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
  4286  ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4287  ** participate in [shared cache mode] even if it is enabled.
  4288  **
  4289  ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4290  ** [sqlite3_vfs] object that defines the operating system interface that
  4291  ** the new database connection should use.  ^If the fourth parameter is
  4292  ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4293  **
  4294  ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4295  ** is created for the connection.  ^This in-memory database will vanish when
  4296  ** the database connection is closed.  Future versions of SQLite might
  4297  ** make use of additional special filenames that begin with the ":" character.
  4298  ** It is recommended that when a database filename actually does begin with
  4299  ** a ":" character you should prefix the filename with a pathname such as
  4300  ** "./" to avoid ambiguity.
  4301  **
  4302  ** ^If the filename is an empty string, then a private, temporary
  4303  ** on-disk database will be created.  ^This private database will be
  4304  ** automatically deleted as soon as the database connection is closed.
  4305  **
  4306  ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4307  **
  4308  ** ^If [URI filename] interpretation is enabled, and the filename argument
  4309  ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4310  ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4311  ** set in the third argument to sqlite3_open_v2(), or if it has
  4312  ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4313  ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4314  ** URI filename interpretation is turned off
  4315  ** by default, but future releases of SQLite might enable URI filename
  4316  ** interpretation by default.  See "[URI filenames]" for additional
  4317  ** information.
  4318  **
  4319  ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4320  ** authority, then it must be either an empty string or the string 
  4321  ** "localhost". ^If the authority is not an empty string or "localhost", an 
  4322  ** error is returned to the caller. ^The fragment component of a URI, if 
  4323  ** present, is ignored.
  4324  **
  4325  ** ^SQLite uses the path component of the URI as the name of the disk file
  4326  ** which contains the database. ^If the path begins with a '/' character, 
  4327  ** then it is interpreted as an absolute path. ^If the path does not begin 
  4328  ** with a '/' (meaning that the authority section is omitted from the URI)
  4329  ** then the path is interpreted as a relative path. 
  4330  ** ^(On windows, the first component of an absolute path 
  4331  ** is a drive specification (e.g. "C:").)^
  4332  **
  4333  ** [[core URI query parameters]]
  4334  ** The query component of a URI may contain parameters that are interpreted
  4335  ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4336  ** SQLite and its built-in [VFSes] interpret the
  4337  ** following query parameters:
  4338  **
  4339  ** <ul>
  4340  **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4341  **     a VFS object that provides the operating system interface that should
  4342  **     be used to access the database file on disk. ^If this option is set to
  4343  **     an empty string the default VFS object is used. ^Specifying an unknown
  4344  **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4345  **     present, then the VFS specified by the option takes precedence over
  4346  **     the value passed as the fourth parameter to sqlite3_open_v2().
  4347  **
  4348  **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4349  **     "rwc", or "memory". Attempting to set it to any other value is
  4350  **     an error)^. 
  4351  **     ^If "ro" is specified, then the database is opened for read-only 
  4352  **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
  4353  **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
  4354  **     "rw", then the database is opened for read-write (but not create) 
  4355  **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
  4356  **     been set. ^Value "rwc" is equivalent to setting both 
  4357  **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
  4358  **     set to "memory" then a pure [in-memory database] that never reads
  4359  **     or writes from disk is used. ^It is an error to specify a value for
  4360  **     the mode parameter that is less restrictive than that specified by
  4361  **     the flags passed in the third parameter to sqlite3_open_v2().
  4362  **
  4363  **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4364  **     "private". ^Setting it to "shared" is equivalent to setting the
  4365  **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4366  **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
  4367  **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4368  **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4369  **     a URI filename, its value overrides any behavior requested by setting
  4370  **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4371  **
  4372  **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4373  **     [powersafe overwrite] property does or does not apply to the
  4374  **     storage media on which the database file resides.
  4375  **
  4376  **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4377  **     which if set disables file locking in rollback journal modes.  This
  4378  **     is useful for accessing a database on a filesystem that does not
  4379  **     support locking.  Caution:  Database corruption might result if two
  4380  **     or more processes write to the same database and any one of those
  4381  **     processes uses nolock=1.
  4382  **
  4383  **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4384  **     parameter that indicates that the database file is stored on
  4385  **     read-only media.  ^When immutable is set, SQLite assumes that the
  4386  **     database file cannot be changed, even by a process with higher
  4387  **     privilege, and so the database is opened read-only and all locking
  4388  **     and change detection is disabled.  Caution: Setting the immutable
  4389  **     property on a database file that does in fact change can result
  4390  **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4391  **     See also: [SQLITE_IOCAP_IMMUTABLE].
  4392  **       
  4393  ** </ul>
  4394  **
  4395  ** ^Specifying an unknown parameter in the query component of a URI is not an
  4396  ** error.  Future versions of SQLite might understand additional query
  4397  ** parameters.  See "[query parameters with special meaning to SQLite]" for
  4398  ** additional information.
  4399  **
  4400  ** [[URI filename examples]] <h3>URI filename examples</h3>
  4401  **
  4402  ** <table border="1" align=center cellpadding=5>
  4403  ** <tr><th> URI filenames <th> Results
  4404  ** <tr><td> file:data.db <td> 
  4405  **          Open the file "data.db" in the current directory.
  4406  ** <tr><td> file:/home/fred/data.db<br>
  4407  **          file:///home/fred/data.db <br> 
  4408  **          file://localhost/home/fred/data.db <br> <td> 
  4409  **          Open the database file "/home/fred/data.db".
  4410  ** <tr><td> file://darkstar/home/fred/data.db <td> 
  4411  **          An error. "darkstar" is not a recognized authority.
  4412  ** <tr><td style="white-space:nowrap"> 
  4413  **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4414  **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4415  **          C:. Note that the %20 escaping in this example is not strictly 
  4416  **          necessary - space characters can be used literally
  4417  **          in URI filenames.
  4418  ** <tr><td> file:data.db?mode=ro&cache=private <td> 
  4419  **          Open file "data.db" in the current directory for read-only access.
  4420  **          Regardless of whether or not shared-cache mode is enabled by
  4421  **          default, use a private cache.
  4422  ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4423  **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4424  **          that uses dot-files in place of posix advisory locking.
  4425  ** <tr><td> file:data.db?mode=readonly <td> 
  4426  **          An error. "readonly" is not a valid option for the "mode" parameter.
  4427  ** </table>
  4428  **
  4429  ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4430  ** query components of a URI. A hexadecimal escape sequence consists of a
  4431  ** percent sign - "%" - followed by exactly two hexadecimal digits 
  4432  ** specifying an octet value. ^Before the path or query components of a
  4433  ** URI filename are interpreted, they are encoded using UTF-8 and all 
  4434  ** hexadecimal escape sequences replaced by a single byte containing the
  4435  ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4436  ** the results are undefined.
  4437  **
  4438  ** <b>Note to Windows users:</b>  The encoding used for the filename argument
  4439  ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4440  ** codepage is currently defined.  Filenames containing international
  4441  ** characters must be converted to UTF-8 prior to passing them into
  4442  ** sqlite3_open() or sqlite3_open_v2().
  4443  **
  4444  ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  4445  ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
  4446  ** features that require the use of temporary files may fail.
  4447  **
  4448  ** See also: [sqlite3_temp_directory]
  4449  */
  4450  SQLITE_API int sqlite3_open(
  4451    const char *filename,   /* Database filename (UTF-8) */
  4452    sqlite3 **ppDb          /* OUT: SQLite db handle */
  4453  );
  4454  SQLITE_API int sqlite3_open16(
  4455    const void *filename,   /* Database filename (UTF-16) */
  4456    sqlite3 **ppDb          /* OUT: SQLite db handle */
  4457  );
  4458  SQLITE_API int sqlite3_open_v2(
  4459    const char *filename,   /* Database filename (UTF-8) */
  4460    sqlite3 **ppDb,         /* OUT: SQLite db handle */
  4461    int flags,              /* Flags */
  4462    const char *zVfs        /* Name of VFS module to use */
  4463  );
  4464  
  4465  /*
  4466  ** CAPI3REF: Obtain Values For URI Parameters
  4467  **
  4468  ** These are utility routines, useful to VFS implementations, that check
  4469  ** to see if a database file was a URI that contained a specific query 
  4470  ** parameter, and if so obtains the value of that query parameter.
  4471  **
  4472  ** If F is the database filename pointer passed into the xOpen() method of 
  4473  ** a VFS implementation when the flags parameter to xOpen() has one or 
  4474  ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4475  ** P is the name of the query parameter, then
  4476  ** sqlite3_uri_parameter(F,P) returns the value of the P
  4477  ** parameter if it exists or a NULL pointer if P does not appear as a 
  4478  ** query parameter on F.  If P is a query parameter of F
  4479  ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4480  ** a pointer to an empty string.
  4481  **
  4482  ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4483  ** parameter and returns true (1) or false (0) according to the value
  4484  ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4485  ** value of query parameter P is one of "yes", "true", or "on" in any
  4486  ** case or if the value begins with a non-zero number.  The 
  4487  ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4488  ** query parameter P is one of "no", "false", or "off" in any case or
  4489  ** if the value begins with a numeric zero.  If P is not a query
  4490  ** parameter on F or if the value of P is does not match any of the
  4491  ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4492  **
  4493  ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4494  ** 64-bit signed integer and returns that integer, or D if P does not
  4495  ** exist.  If the value of P is something other than an integer, then
  4496  ** zero is returned.
  4497  ** 
  4498  ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4499  ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
  4500  ** is not a database file pathname pointer that SQLite passed into the xOpen
  4501  ** VFS method, then the behavior of this routine is undefined and probably
  4502  ** undesirable.
  4503  **
  4504  ** See the [URI filename] documentation for additional information.
  4505  */
  4506  SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4507  SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4508  SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4509  
  4510  SQLITE_PRIVATE int process_branch_uri(sqlite3 *db, const char *name, const char *uri);
  4511  
  4512  /*
  4513  ** CAPI3REF: Error Codes And Messages
  4514  ** METHOD: sqlite3
  4515  **
  4516  ** ^If the most recent sqlite3_* API call associated with 
  4517  ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4518  ** returns the numeric [result code] or [extended result code] for that
  4519  ** API call.
  4520  ** ^The sqlite3_extended_errcode()
  4521  ** interface is the same except that it always returns the 
  4522  ** [extended result code] even when extended result codes are
  4523  ** disabled.
  4524  **
  4525  ** The values returned by sqlite3_errcode() and/or
  4526  ** sqlite3_extended_errcode() might change with each API call.
  4527  ** Except, there are some interfaces that are guaranteed to never
  4528  ** change the value of the error code.  The error-code preserving
  4529  ** interfaces are:
  4530  **
  4531  ** <ul>
  4532  ** <li> sqlite3_errcode()
  4533  ** <li> sqlite3_extended_errcode()
  4534  ** <li> sqlite3_errmsg()
  4535  ** <li> sqlite3_errmsg16()
  4536  ** </ul>
  4537  **
  4538  ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4539  ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4540  ** ^(Memory to hold the error message string is managed internally.
  4541  ** The application does not need to worry about freeing the result.
  4542  ** However, the error string might be overwritten or deallocated by
  4543  ** subsequent calls to other SQLite interface functions.)^
  4544  **
  4545  ** ^The sqlite3_errstr() interface returns the English-language text
  4546  ** that describes the [result code], as UTF-8.
  4547  ** ^(Memory to hold the error message string is managed internally
  4548  ** and must not be freed by the application)^.
  4549  **
  4550  ** When the serialized [threading mode] is in use, it might be the
  4551  ** case that a second error occurs on a separate thread in between
  4552  ** the time of the first error and the call to these interfaces.
  4553  ** When that happens, the second error will be reported since these
  4554  ** interfaces always report the most recent result.  To avoid
  4555  ** this, each thread can obtain exclusive use of the [database connection] D
  4556  ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4557  ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4558  ** all calls to the interfaces listed here are completed.
  4559  **
  4560  ** If an interface fails with SQLITE_MISUSE, that means the interface
  4561  ** was invoked incorrectly by the application.  In that case, the
  4562  ** error code and message may or may not be set.
  4563  */
  4564  SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4565  SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4566  SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4567  SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4568  SQLITE_API const char *sqlite3_errstr(int);
  4569  
  4570  /*
  4571  ** CAPI3REF: Prepared Statement Object
  4572  ** KEYWORDS: {prepared statement} {prepared statements}
  4573  **
  4574  ** An instance of this object represents a single SQL statement that
  4575  ** has been compiled into binary form and is ready to be evaluated.
  4576  **
  4577  ** Think of each SQL statement as a separate computer program.  The
  4578  ** original SQL text is source code.  A prepared statement object 
  4579  ** is the compiled object code.  All SQL must be converted into a
  4580  ** prepared statement before it can be run.
  4581  **
  4582  ** The life-cycle of a prepared statement object usually goes like this:
  4583  **
  4584  ** <ol>
  4585  ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4586  ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4587  **      interfaces.
  4588  ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4589  ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4590  **      to step 2.  Do this zero or more times.
  4591  ** <li> Destroy the object using [sqlite3_finalize()].
  4592  ** </ol>
  4593  */
  4594  typedef struct sqlite3_stmt sqlite3_stmt;
  4595  
  4596  /*
  4597  ** CAPI3REF: Run-time Limits
  4598  ** METHOD: sqlite3
  4599  **
  4600  ** ^(This interface allows the size of various constructs to be limited
  4601  ** on a connection by connection basis.  The first parameter is the
  4602  ** [database connection] whose limit is to be set or queried.  The
  4603  ** second parameter is one of the [limit categories] that define a
  4604  ** class of constructs to be size limited.  The third parameter is the
  4605  ** new limit for that construct.)^
  4606  **
  4607  ** ^If the new limit is a negative number, the limit is unchanged.
  4608  ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
  4609  ** [limits | hard upper bound]
  4610  ** set at compile-time by a C preprocessor macro called
  4611  ** [limits | SQLITE_MAX_<i>NAME</i>].
  4612  ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4613  ** ^Attempts to increase a limit above its hard upper bound are
  4614  ** silently truncated to the hard upper bound.
  4615  **
  4616  ** ^Regardless of whether or not the limit was changed, the 
  4617  ** [sqlite3_limit()] interface returns the prior value of the limit.
  4618  ** ^Hence, to find the current value of a limit without changing it,
  4619  ** simply invoke this interface with the third parameter set to -1.
  4620  **
  4621  ** Run-time limits are intended for use in applications that manage
  4622  ** both their own internal database and also databases that are controlled
  4623  ** by untrusted external sources.  An example application might be a
  4624  ** web browser that has its own databases for storing history and
  4625  ** separate databases controlled by JavaScript applications downloaded
  4626  ** off the Internet.  The internal databases can be given the
  4627  ** large, default limits.  Databases managed by external sources can
  4628  ** be given much smaller limits designed to prevent a denial of service
  4629  ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
  4630  ** interface to further control untrusted SQL.  The size of the database
  4631  ** created by an untrusted script can be contained using the
  4632  ** [max_page_count] [PRAGMA].
  4633  **
  4634  ** New run-time limit categories may be added in future releases.
  4635  */
  4636  SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4637  
  4638  /*
  4639  ** CAPI3REF: Run-Time Limit Categories
  4640  ** KEYWORDS: {limit category} {*limit categories}
  4641  **
  4642  ** These constants define various performance limits
  4643  ** that can be lowered at run-time using [sqlite3_limit()].
  4644  ** The synopsis of the meanings of the various limits is shown below.
  4645  ** Additional information is available at [limits | Limits in SQLite].
  4646  **
  4647  ** <dl>
  4648  ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4649  ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4650  **
  4651  ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4652  ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4653  **
  4654  ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4655  ** <dd>The maximum number of columns in a table definition or in the
  4656  ** result set of a [SELECT] or the maximum number of columns in an index
  4657  ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4658  **
  4659  ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4660  ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4661  **
  4662  ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4663  ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4664  **
  4665  ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4666  ** <dd>The maximum number of instructions in a virtual machine program
  4667  ** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
  4668  ** the equivalent tries to allocate space for more than this many opcodes
  4669  ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4670  **
  4671  ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4672  ** <dd>The maximum number of arguments on a function.</dd>)^
  4673  **
  4674  ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4675  ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4676  **
  4677  ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4678  ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4679  ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4680  ** [GLOB] operators.</dd>)^
  4681  **
  4682  ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4683  ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4684  ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4685  **
  4686  ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4687  ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4688  **
  4689  ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4690  ** <dd>The maximum number of auxiliary worker threads that a single
  4691  ** [prepared statement] may start.</dd>)^
  4692  ** </dl>
  4693  */
  4694  #define SQLITE_LIMIT_LENGTH                    0
  4695  #define SQLITE_LIMIT_SQL_LENGTH                1
  4696  #define SQLITE_LIMIT_COLUMN                    2
  4697  #define SQLITE_LIMIT_EXPR_DEPTH                3
  4698  #define SQLITE_LIMIT_COMPOUND_SELECT           4
  4699  #define SQLITE_LIMIT_VDBE_OP                   5
  4700  #define SQLITE_LIMIT_FUNCTION_ARG              6
  4701  #define SQLITE_LIMIT_ATTACHED                  7
  4702  #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
  4703  #define SQLITE_LIMIT_VARIABLE_NUMBER           9
  4704  #define SQLITE_LIMIT_TRIGGER_DEPTH            10
  4705  #define SQLITE_LIMIT_WORKER_THREADS           11
  4706  
  4707  /*
  4708  ** CAPI3REF: Prepare Flags
  4709  **
  4710  ** These constants define various flags that can be passed into
  4711  ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4712  ** [sqlite3_prepare16_v3()] interfaces.
  4713  **
  4714  ** New flags may be added in future releases of SQLite.
  4715  **
  4716  ** <dl>
  4717  ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4718  ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4719  ** that the prepared statement will be retained for a long time and
  4720  ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4721  ** and [sqlite3_prepare16_v3()] assume that the prepared statement will 
  4722  ** be used just once or at most a few times and then destroyed using
  4723  ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4724  ** on this hint by avoiding the use of [lookaside memory] so as not to
  4725  ** deplete the limited store of lookaside memory. Future versions of
  4726  ** SQLite may act on this hint differently.
  4727  **
  4728  ** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
  4729  ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
  4730  ** to be required for any prepared statement that wanted to use the
  4731  ** [sqlite3_normalized_sql()] interface.  However, the
  4732  ** [sqlite3_normalized_sql()] interface is now available to all
  4733  ** prepared statements, regardless of whether or not they use this
  4734  ** flag.
  4735  **
  4736  ** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
  4737  ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
  4738  ** to return an error (error code SQLITE_ERROR) if the statement uses
  4739  ** any virtual tables.
  4740  ** </dl>
  4741  */
  4742  #define SQLITE_PREPARE_PERSISTENT              0x01
  4743  #define SQLITE_PREPARE_NORMALIZE               0x02
  4744  #define SQLITE_PREPARE_NO_VTAB                 0x04
  4745  
  4746  /*
  4747  ** CAPI3REF: Compiling An SQL Statement
  4748  ** KEYWORDS: {SQL statement compiler}
  4749  ** METHOD: sqlite3
  4750  ** CONSTRUCTOR: sqlite3_stmt
  4751  **
  4752  ** To execute an SQL statement, it must first be compiled into a byte-code
  4753  ** program using one of these routines.  Or, in other words, these routines
  4754  ** are constructors for the [prepared statement] object.
  4755  **
  4756  ** The preferred routine to use is [sqlite3_prepare_v2()].  The
  4757  ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4758  ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4759  ** for special purposes.
  4760  **
  4761  ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4762  ** does all parsing using UTF-8.  The UTF-16 interfaces are provided
  4763  ** as a convenience.  The UTF-16 interfaces work by converting the
  4764  ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4765  **
  4766  ** The first argument, "db", is a [database connection] obtained from a
  4767  ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4768  ** [sqlite3_open16()].  The database connection must not have been closed.
  4769  **
  4770  ** The second argument, "zSql", is the statement to be compiled, encoded
  4771  ** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
  4772  ** and sqlite3_prepare_v3()
  4773  ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4774  ** and sqlite3_prepare16_v3() use UTF-16.
  4775  **
  4776  ** ^If the nByte argument is negative, then zSql is read up to the
  4777  ** first zero terminator. ^If nByte is positive, then it is the
  4778  ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
  4779  ** statement is generated.
  4780  ** If the caller knows that the supplied string is nul-terminated, then
  4781  ** there is a small performance advantage to passing an nByte parameter that
  4782  ** is the number of bytes in the input string <i>including</i>
  4783  ** the nul-terminator.
  4784  **
  4785  ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4786  ** past the end of the first SQL statement in zSql.  These routines only
  4787  ** compile the first statement in zSql, so *pzTail is left pointing to
  4788  ** what remains uncompiled.
  4789  **
  4790  ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4791  ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
  4792  ** to NULL.  ^If the input text contains no SQL (if the input is an empty
  4793  ** string or a comment) then *ppStmt is set to NULL.
  4794  ** The calling procedure is responsible for deleting the compiled
  4795  ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4796  ** ppStmt may not be NULL.
  4797  **
  4798  ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4799  ** otherwise an [error code] is returned.
  4800  **
  4801  ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4802  ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4803  ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4804  ** are retained for backwards compatibility, but their use is discouraged.
  4805  ** ^In the "vX" interfaces, the prepared statement
  4806  ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4807  ** original SQL text. This causes the [sqlite3_step()] interface to
  4808  ** behave differently in three ways:
  4809  **
  4810  ** <ol>
  4811  ** <li>
  4812  ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4813  ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4814  ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4815  ** retries will occur before sqlite3_step() gives up and returns an error.
  4816  ** </li>
  4817  **
  4818  ** <li>
  4819  ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4820  ** [error codes] or [extended error codes].  ^The legacy behavior was that
  4821  ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4822  ** and the application would have to make a second call to [sqlite3_reset()]
  4823  ** in order to find the underlying cause of the problem. With the "v2" prepare
  4824  ** interfaces, the underlying reason for the error is returned immediately.
  4825  ** </li>
  4826  **
  4827  ** <li>
  4828  ** ^If the specific value bound to [parameter | host parameter] in the 
  4829  ** WHERE clause might influence the choice of query plan for a statement,
  4830  ** then the statement will be automatically recompiled, as if there had been 
  4831  ** a schema change, on the first  [sqlite3_step()] call following any change
  4832  ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
  4833  ** ^The specific value of WHERE-clause [parameter] might influence the 
  4834  ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4835  ** or [GLOB] operator or if the parameter is compared to an indexed column
  4836  ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4837  ** </li>
  4838  ** </ol>
  4839  **
  4840  ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4841  ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4842  ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The
  4843  ** sqlite3_prepare_v2() interface works exactly the same as
  4844  ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4845  */
  4846  SQLITE_API int sqlite3_prepare(
  4847    sqlite3 *db,            /* Database handle */
  4848    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4849    int nByte,              /* Maximum length of zSql in bytes. */
  4850    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4851    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4852  );
  4853  SQLITE_API int sqlite3_prepare_v2(
  4854    sqlite3 *db,            /* Database handle */
  4855    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4856    int nByte,              /* Maximum length of zSql in bytes. */
  4857    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4858    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4859  );
  4860  SQLITE_API int sqlite3_prepare_v3(
  4861    sqlite3 *db,            /* Database handle */
  4862    const char *zSql,       /* SQL statement, UTF-8 encoded */
  4863    int nByte,              /* Maximum length of zSql in bytes. */
  4864    unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4865    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4866    const char **pzTail     /* OUT: Pointer to unused portion of zSql */
  4867  );
  4868  SQLITE_API int sqlite3_prepare16(
  4869    sqlite3 *db,            /* Database handle */
  4870    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4871    int nByte,              /* Maximum length of zSql in bytes. */
  4872    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4873    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4874  );
  4875  SQLITE_API int sqlite3_prepare16_v2(
  4876    sqlite3 *db,            /* Database handle */
  4877    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4878    int nByte,              /* Maximum length of zSql in bytes. */
  4879    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4880    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4881  );
  4882  SQLITE_API int sqlite3_prepare16_v3(
  4883    sqlite3 *db,            /* Database handle */
  4884    const void *zSql,       /* SQL statement, UTF-16 encoded */
  4885    int nByte,              /* Maximum length of zSql in bytes. */
  4886    unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4887    sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  4888    const void **pzTail     /* OUT: Pointer to unused portion of zSql */
  4889  );
  4890  
  4891  /*
  4892  ** CAPI3REF: Retrieving Statement SQL
  4893  ** METHOD: sqlite3_stmt
  4894  **
  4895  ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4896  ** SQL text used to create [prepared statement] P if P was
  4897  ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4898  ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4899  ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4900  ** string containing the SQL text of prepared statement P with
  4901  ** [bound parameters] expanded.
  4902  ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  4903  ** string containing the normalized SQL text of prepared statement P.  The
  4904  ** semantics used to normalize a SQL statement are unspecified and subject
  4905  ** to change.  At a minimum, literal values will be replaced with suitable
  4906  ** placeholders.
  4907  **
  4908  ** ^(For example, if a prepared statement is created using the SQL
  4909  ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4910  ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4911  ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4912  ** will return "SELECT 2345,NULL".)^
  4913  **
  4914  ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4915  ** is available to hold the result, or if the result would exceed the
  4916  ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4917  **
  4918  ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4919  ** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
  4920  ** option causes sqlite3_expanded_sql() to always return NULL.
  4921  **
  4922  ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  4923  ** are managed by SQLite and are automatically freed when the prepared
  4924  ** statement is finalized.
  4925  ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4926  ** is obtained from [sqlite3_malloc()] and must be free by the application
  4927  ** by passing it to [sqlite3_free()].
  4928  */
  4929  SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4930  SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4931  SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  4932  
  4933  /*
  4934  ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4935  ** METHOD: sqlite3_stmt
  4936  **
  4937  ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4938  ** and only if the [prepared statement] X makes no direct changes to
  4939  ** the content of the database file.
  4940  **
  4941  ** Note that [application-defined SQL functions] or
  4942  ** [virtual tables] might change the database indirectly as a side effect.  
  4943  ** ^(For example, if an application defines a function "eval()" that 
  4944  ** calls [sqlite3_exec()], then the following SQL statement would
  4945  ** change the database file through side-effects:
  4946  **
  4947  ** <blockquote><pre>
  4948  **    SELECT eval('DELETE FROM t1') FROM t2;
  4949  ** </pre></blockquote>
  4950  **
  4951  ** But because the [SELECT] statement does not change the database file
  4952  ** directly, sqlite3_stmt_readonly() would still return true.)^
  4953  **
  4954  ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4955  ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4956  ** since the statements themselves do not actually modify the database but
  4957  ** rather they control the timing of when other statements modify the 
  4958  ** database.  ^The [ATTACH] and [DETACH] statements also cause
  4959  ** sqlite3_stmt_readonly() to return true since, while those statements
  4960  ** change the configuration of a database connection, they do not make 
  4961  ** changes to the content of the database files on disk.
  4962  ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4963  ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4964  ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4965  ** sqlite3_stmt_readonly() returns false for those commands.
  4966  */
  4967  SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4968  
  4969  /*
  4970  ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4971  ** METHOD: sqlite3_stmt
  4972  **
  4973  ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4974  ** [prepared statement] S has been stepped at least once using 
  4975  ** [sqlite3_step(S)] but has neither run to completion (returned
  4976  ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4977  ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
  4978  ** interface returns false if S is a NULL pointer.  If S is not a 
  4979  ** NULL pointer and is not a pointer to a valid [prepared statement]
  4980  ** object, then the behavior is undefined and probably undesirable.
  4981  **
  4982  ** This interface can be used in combination [sqlite3_next_stmt()]
  4983  ** to locate all prepared statements associated with a database 
  4984  ** connection that are in need of being reset.  This can be used,
  4985  ** for example, in diagnostic routines to search for prepared 
  4986  ** statements that are holding a transaction open.
  4987  */
  4988  SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4989  
  4990  /*
  4991  ** CAPI3REF: Dynamically Typed Value Object
  4992  ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4993  **
  4994  ** SQLite uses the sqlite3_value object to represent all values
  4995  ** that can be stored in a database table. SQLite uses dynamic typing
  4996  ** for the values it stores.  ^Values stored in sqlite3_value objects
  4997  ** can be integers, floating point values, strings, BLOBs, or NULL.
  4998  **
  4999  ** An sqlite3_value object may be either "protected" or "unprotected".
  5000  ** Some interfaces require a protected sqlite3_value.  Other interfaces
  5001  ** will accept either a protected or an unprotected sqlite3_value.
  5002  ** Every interface that accepts sqlite3_value arguments specifies
  5003  ** whether or not it requires a protected sqlite3_value.  The
  5004  ** [sqlite3_value_dup()] interface can be used to construct a new 
  5005  ** protected sqlite3_value from an unprotected sqlite3_value.
  5006  **
  5007  ** The terms "protected" and "unprotected" refer to whether or not
  5008  ** a mutex is held.  An internal mutex is held for a protected
  5009  ** sqlite3_value object but no mutex is held for an unprotected
  5010  ** sqlite3_value object.  If SQLite is compiled to be single-threaded
  5011  ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  5012  ** or if SQLite is run in one of reduced mutex modes 
  5013  ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  5014  ** then there is no distinction between protected and unprotected
  5015  ** sqlite3_value objects and they can be used interchangeably.  However,
  5016  ** for maximum code portability it is recommended that applications
  5017  ** still make the distinction between protected and unprotected
  5018  ** sqlite3_value objects even when not strictly required.
  5019  **
  5020  ** ^The sqlite3_value objects that are passed as parameters into the
  5021  ** implementation of [application-defined SQL functions] are protected.
  5022  ** ^The sqlite3_value object returned by
  5023  ** [sqlite3_column_value()] is unprotected.
  5024  ** Unprotected sqlite3_value objects may only be used as arguments
  5025  ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  5026  ** [sqlite3_value_dup()].
  5027  ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  5028  ** interfaces require protected sqlite3_value objects.
  5029  */
  5030  typedef struct sqlite3_value sqlite3_value;
  5031  
  5032  /*
  5033  ** CAPI3REF: SQL Function Context Object
  5034  **
  5035  ** The context in which an SQL function executes is stored in an
  5036  ** sqlite3_context object.  ^A pointer to an sqlite3_context object
  5037  ** is always first parameter to [application-defined SQL functions].
  5038  ** The application-defined SQL function implementation will pass this
  5039  ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  5040  ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  5041  ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  5042  ** and/or [sqlite3_set_auxdata()].
  5043  */
  5044  typedef struct sqlite3_context sqlite3_context;
  5045  
  5046  /*
  5047  ** CAPI3REF: Binding Values To Prepared Statements
  5048  ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  5049  ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  5050  ** METHOD: sqlite3_stmt
  5051  **
  5052  ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  5053  ** literals may be replaced by a [parameter] that matches one of following
  5054  ** templates:
  5055  **
  5056  ** <ul>
  5057  ** <li>  ?
  5058  ** <li>  ?NNN
  5059  ** <li>  :VVV
  5060  ** <li>  @VVV
  5061  ** <li>  $VVV
  5062  ** </ul>
  5063  **
  5064  ** In the templates above, NNN represents an integer literal,
  5065  ** and VVV represents an alphanumeric identifier.)^  ^The values of these
  5066  ** parameters (also called "host parameter names" or "SQL parameters")
  5067  ** can be set using the sqlite3_bind_*() routines defined here.
  5068  **
  5069  ** ^The first argument to the sqlite3_bind_*() routines is always
  5070  ** a pointer to the [sqlite3_stmt] object returned from
  5071  ** [sqlite3_prepare_v2()] or its variants.
  5072  **
  5073  ** ^The second argument is the index of the SQL parameter to be set.
  5074  ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
  5075  ** SQL parameter is used more than once, second and subsequent
  5076  ** occurrences have the same index as the first occurrence.
  5077  ** ^The index for named parameters can be looked up using the
  5078  ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
  5079  ** for "?NNN" parameters is the value of NNN.
  5080  ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  5081  ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  5082  **
  5083  ** ^The third argument is the value to bind to the parameter.
  5084  ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5085  ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  5086  ** is ignored and the end result is the same as sqlite3_bind_null().
  5087  **
  5088  ** ^(In those routines that have a fourth argument, its value is the
  5089  ** number of bytes in the parameter.  To be clear: the value is the
  5090  ** number of <u>bytes</u> in the value, not the number of characters.)^
  5091  ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5092  ** is negative, then the length of the string is
  5093  ** the number of bytes up to the first zero terminator.
  5094  ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  5095  ** the behavior is undefined.
  5096  ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  5097  ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  5098  ** that parameter must be the byte offset
  5099  ** where the NUL terminator would occur assuming the string were NUL
  5100  ** terminated.  If any NUL characters occur at byte offsets less than 
  5101  ** the value of the fourth parameter then the resulting string value will
  5102  ** contain embedded NULs.  The result of expressions involving strings
  5103  ** with embedded NULs is undefined.
  5104  **
  5105  ** ^The fifth argument to the BLOB and string binding interfaces
  5106  ** is a destructor used to dispose of the BLOB or
  5107  ** string after SQLite has finished with it.  ^The destructor is called
  5108  ** to dispose of the BLOB or string even if the call to bind API fails.
  5109  ** ^If the fifth argument is
  5110  ** the special value [SQLITE_STATIC], then SQLite assumes that the
  5111  ** information is in static, unmanaged space and does not need to be freed.
  5112  ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  5113  ** SQLite makes its own private copy of the data immediately, before
  5114  ** the sqlite3_bind_*() routine returns.
  5115  **
  5116  ** ^The sixth argument to sqlite3_bind_text64() must be one of
  5117  ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  5118  ** to specify the encoding of the text in the third parameter.  If
  5119  ** the sixth argument to sqlite3_bind_text64() is not one of the
  5120  ** allowed values shown above, or if the text encoding is different
  5121  ** from the encoding specified by the sixth parameter, then the behavior
  5122  ** is undefined.
  5123  **
  5124  ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  5125  ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
  5126  ** (just an integer to hold its size) while it is being processed.
  5127  ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  5128  ** content is later written using
  5129  ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  5130  ** ^A negative value for the zeroblob results in a zero-length BLOB.
  5131  **
  5132  ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  5133  ** [prepared statement] S to have an SQL value of NULL, but to also be
  5134  ** associated with the pointer P of type T.  ^D is either a NULL pointer or
  5135  ** a pointer to a destructor function for P. ^SQLite will invoke the
  5136  ** destructor D with a single argument of P when it is finished using
  5137  ** P.  The T parameter should be a static string, preferably a string
  5138  ** literal. The sqlite3_bind_pointer() routine is part of the
  5139  ** [pointer passing interface] added for SQLite 3.20.0.
  5140  **
  5141  ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  5142  ** for the [prepared statement] or with a prepared statement for which
  5143  ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  5144  ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
  5145  ** routine is passed a [prepared statement] that has been finalized, the
  5146  ** result is undefined and probably harmful.
  5147  **
  5148  ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  5149  ** ^Unbound parameters are interpreted as NULL.
  5150  **
  5151  ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  5152  ** [error code] if anything goes wrong.
  5153  ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  5154  ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  5155  ** [SQLITE_MAX_LENGTH].
  5156  ** ^[SQLITE_RANGE] is returned if the parameter
  5157  ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
  5158  **
  5159  ** See also: [sqlite3_bind_parameter_count()],
  5160  ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  5161  */
  5162  SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  5163  SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  5164                          void(*)(void*));
  5165  SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  5166  SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  5167  SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  5168  SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  5169  SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  5170  SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  5171  SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  5172                           void(*)(void*), unsigned char encoding);
  5173  SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  5174  SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  5175  SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  5176  SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5177  
  5178  /*
  5179  ** CAPI3REF: Number Of SQL Parameters
  5180  ** METHOD: sqlite3_stmt
  5181  **
  5182  ** ^This routine can be used to find the number of [SQL parameters]
  5183  ** in a [prepared statement].  SQL parameters are tokens of the
  5184  ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5185  ** placeholders for values that are [sqlite3_bind_blob | bound]
  5186  ** to the parameters at a later time.
  5187  **
  5188  ** ^(This routine actually returns the index of the largest (rightmost)
  5189  ** parameter. For all forms except ?NNN, this will correspond to the
  5190  ** number of unique parameters.  If parameters of the ?NNN form are used,
  5191  ** there may be gaps in the list.)^
  5192  **
  5193  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5194  ** [sqlite3_bind_parameter_name()], and
  5195  ** [sqlite3_bind_parameter_index()].
  5196  */
  5197  SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5198  
  5199  /*
  5200  ** CAPI3REF: Name Of A Host Parameter
  5201  ** METHOD: sqlite3_stmt
  5202  **
  5203  ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5204  ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5205  ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5206  ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5207  ** respectively.
  5208  ** In other words, the initial ":" or "$" or "@" or "?"
  5209  ** is included as part of the name.)^
  5210  ** ^Parameters of the form "?" without a following integer have no name
  5211  ** and are referred to as "nameless" or "anonymous parameters".
  5212  **
  5213  ** ^The first host parameter has an index of 1, not 0.
  5214  **
  5215  ** ^If the value N is out of range or if the N-th parameter is
  5216  ** nameless, then NULL is returned.  ^The returned string is
  5217  ** always in UTF-8 encoding even if the named parameter was
  5218  ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5219  ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5220  **
  5221  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5222  ** [sqlite3_bind_parameter_count()], and
  5223  ** [sqlite3_bind_parameter_index()].
  5224  */
  5225  SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5226  
  5227  /*
  5228  ** CAPI3REF: Index Of A Parameter With A Given Name
  5229  ** METHOD: sqlite3_stmt
  5230  **
  5231  ** ^Return the index of an SQL parameter given its name.  ^The
  5232  ** index value returned is suitable for use as the second
  5233  ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
  5234  ** is returned if no matching parameter is found.  ^The parameter
  5235  ** name must be given in UTF-8 even if the original statement
  5236  ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5237  ** [sqlite3_prepare16_v3()].
  5238  **
  5239  ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5240  ** [sqlite3_bind_parameter_count()], and
  5241  ** [sqlite3_bind_parameter_name()].
  5242  */
  5243  SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5244  
  5245  /*
  5246  ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5247  ** METHOD: sqlite3_stmt
  5248  **
  5249  ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5250  ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5251  ** ^Use this routine to reset all host parameters to NULL.
  5252  */
  5253  SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5254  
  5255  /*
  5256  ** CAPI3REF: Number Of Columns In A Result Set
  5257  ** METHOD: sqlite3_stmt
  5258  **
  5259  ** ^Return the number of columns in the result set returned by the
  5260  ** [prepared statement]. ^If this routine returns 0, that means the 
  5261  ** [prepared statement] returns no data (for example an [UPDATE]).
  5262  ** ^However, just because this routine returns a positive number does not
  5263  ** mean that one or more rows of data will be returned.  ^A SELECT statement
  5264  ** will always have a positive sqlite3_column_count() but depending on the
  5265  ** WHERE clause constraints and the table content, it might return no rows.
  5266  **
  5267  ** See also: [sqlite3_data_count()]
  5268  */
  5269  SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5270  
  5271  /*
  5272  ** CAPI3REF: Column Names In A Result Set
  5273  ** METHOD: sqlite3_stmt
  5274  **
  5275  ** ^These routines return the name assigned to a particular column
  5276  ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
  5277  ** interface returns a pointer to a zero-terminated UTF-8 string
  5278  ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5279  ** UTF-16 string.  ^The first parameter is the [prepared statement]
  5280  ** that implements the [SELECT] statement. ^The second parameter is the
  5281  ** column number.  ^The leftmost column is number 0.
  5282  **
  5283  ** ^The returned string pointer is valid until either the [prepared statement]
  5284  ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5285  ** reprepared by the first call to [sqlite3_step()] for a particular run
  5286  ** or until the next call to
  5287  ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5288  **
  5289  ** ^If sqlite3_malloc() fails during the processing of either routine
  5290  ** (for example during a conversion from UTF-8 to UTF-16) then a
  5291  ** NULL pointer is returned.
  5292  **
  5293  ** ^The name of a result column is the value of the "AS" clause for
  5294  ** that column, if there is an AS clause.  If there is no AS clause
  5295  ** then the name of the column is unspecified and may change from
  5296  ** one release of SQLite to the next.
  5297  */
  5298  SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5299  SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5300  
  5301  /*
  5302  ** CAPI3REF: Source Of Data In A Query Result
  5303  ** METHOD: sqlite3_stmt
  5304  **
  5305  ** ^These routines provide a means to determine the database, table, and
  5306  ** table column that is the origin of a particular result column in
  5307  ** [SELECT] statement.
  5308  ** ^The name of the database or table or column can be returned as
  5309  ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
  5310  ** the database name, the _table_ routines return the table name, and
  5311  ** the origin_ routines return the column name.
  5312  ** ^The returned string is valid until the [prepared statement] is destroyed
  5313  ** using [sqlite3_finalize()] or until the statement is automatically
  5314  ** reprepared by the first call to [sqlite3_step()] for a particular run
  5315  ** or until the same information is requested
  5316  ** again in a different encoding.
  5317  **
  5318  ** ^The names returned are the original un-aliased names of the
  5319  ** database, table, and column.
  5320  **
  5321  ** ^The first argument to these interfaces is a [prepared statement].
  5322  ** ^These functions return information about the Nth result column returned by
  5323  ** the statement, where N is the second function argument.
  5324  ** ^The left-most column is column 0 for these routines.
  5325  **
  5326  ** ^If the Nth column returned by the statement is an expression or
  5327  ** subquery and is not a column value, then all of these functions return
  5328  ** NULL.  ^These routine might also return NULL if a memory allocation error
  5329  ** occurs.  ^Otherwise, they return the name of the attached database, table,
  5330  ** or column that query result column was extracted from.
  5331  **
  5332  ** ^As with all other SQLite APIs, those whose names end with "16" return
  5333  ** UTF-16 encoded strings and the other functions return UTF-8.
  5334  **
  5335  ** ^These APIs are only available if the library was compiled with the
  5336  ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5337  **
  5338  ** If two or more threads call one or more of these routines against the same
  5339  ** prepared statement and column at the same time then the results are
  5340  ** undefined.
  5341  **
  5342  ** If two or more threads call one or more
  5343  ** [sqlite3_column_database_name | column metadata interfaces]
  5344  ** for the same [prepared statement] and result column
  5345  ** at the same time then the results are undefined.
  5346  */
  5347  SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5348  SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5349  SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5350  SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5351  SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5352  SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5353  
  5354  /*
  5355  ** CAPI3REF: Declared Datatype Of A Query Result
  5356  ** METHOD: sqlite3_stmt
  5357  **
  5358  ** ^(The first parameter is a [prepared statement].
  5359  ** If this statement is a [SELECT] statement and the Nth column of the
  5360  ** returned result set of that [SELECT] is a table column (not an
  5361  ** expression or subquery) then the declared type of the table
  5362  ** column is returned.)^  ^If the Nth column of the result set is an
  5363  ** expression or subquery, then a NULL pointer is returned.
  5364  ** ^The returned string is always UTF-8 encoded.
  5365  **
  5366  ** ^(For example, given the database schema:
  5367  **
  5368  ** CREATE TABLE t1(c1 VARIANT);
  5369  **
  5370  ** and the following statement to be compiled:
  5371  **
  5372  ** SELECT c1 + 1, c1 FROM t1;
  5373  **
  5374  ** this routine would return the string "VARIANT" for the second result
  5375  ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5376  **
  5377  ** ^SQLite uses dynamic run-time typing.  ^So just because a column
  5378  ** is declared to contain a particular type does not mean that the
  5379  ** data stored in that column is of the declared type.  SQLite is
  5380  ** strongly typed, but the typing is dynamic not static.  ^Type
  5381  ** is associated with individual values, not with the containers
  5382  ** used to hold those values.
  5383  */
  5384  SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5385  SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5386  
  5387  /*
  5388  ** CAPI3REF: Evaluate An SQL Statement
  5389  ** METHOD: sqlite3_stmt
  5390  **
  5391  ** After a [prepared statement] has been prepared using any of
  5392  ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5393  ** or [sqlite3_prepare16_v3()] or one of the legacy
  5394  ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5395  ** must be called one or more times to evaluate the statement.
  5396  **
  5397  ** The details of the behavior of the sqlite3_step() interface depend
  5398  ** on whether the statement was prepared using the newer "vX" interfaces
  5399  ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5400  ** [sqlite3_prepare16_v2()] or the older legacy
  5401  ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
  5402  ** new "vX" interface is recommended for new applications but the legacy
  5403  ** interface will continue to be supported.
  5404  **
  5405  ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5406  ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5407  ** ^With the "v2" interface, any of the other [result codes] or
  5408  ** [extended result codes] might be returned as well.
  5409  **
  5410  ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5411  ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
  5412  ** or occurs outside of an explicit transaction, then you can retry the
  5413  ** statement.  If the statement is not a [COMMIT] and occurs within an
  5414  ** explicit transaction then you should rollback the transaction before
  5415  ** continuing.
  5416  **
  5417  ** ^[SQLITE_DONE] means that the statement has finished executing
  5418  ** successfully.  sqlite3_step() should not be called again on this virtual
  5419  ** machine without first calling [sqlite3_reset()] to reset the virtual
  5420  ** machine back to its initial state.
  5421  **
  5422  ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5423  ** is returned each time a new row of data is ready for processing by the
  5424  ** caller. The values may be accessed using the [column access functions].
  5425  ** sqlite3_step() is called again to retrieve the next row of data.
  5426  **
  5427  ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5428  ** violation) has occurred.  sqlite3_step() should not be called again on
  5429  ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5430  ** ^With the legacy interface, a more specific error code (for example,
  5431  ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5432  ** can be obtained by calling [sqlite3_reset()] on the
  5433  ** [prepared statement].  ^In the "v2" interface,
  5434  ** the more specific error code is returned directly by sqlite3_step().
  5435  **
  5436  ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5437  ** Perhaps it was called on a [prepared statement] that has
  5438  ** already been [sqlite3_finalize | finalized] or on one that had
  5439  ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
  5440  ** be the case that the same database connection is being used by two or
  5441  ** more threads at the same moment in time.
  5442  **
  5443  ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5444  ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5445  ** other than [SQLITE_ROW] before any subsequent invocation of
  5446  ** sqlite3_step().  Failure to reset the prepared statement using 
  5447  ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5448  ** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5449  ** sqlite3_step() began
  5450  ** calling [sqlite3_reset()] automatically in this circumstance rather
  5451  ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
  5452  ** break because any application that ever receives an SQLITE_MISUSE error
  5453  ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
  5454  ** can be used to restore the legacy behavior.
  5455  **
  5456  ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5457  ** API always returns a generic error code, [SQLITE_ERROR], following any
  5458  ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
  5459  ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5460  ** specific [error codes] that better describes the error.
  5461  ** We admit that this is a goofy design.  The problem has been fixed
  5462  ** with the "v2" interface.  If you prepare all of your SQL statements
  5463  ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5464  ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5465  ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5466  ** then the more specific [error codes] are returned directly
  5467  ** by sqlite3_step().  The use of the "vX" interfaces is recommended.
  5468  */
  5469  SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5470  
  5471  /*
  5472  ** CAPI3REF: Number of columns in a result set
  5473  ** METHOD: sqlite3_stmt
  5474  **
  5475  ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5476  ** current row of the result set of [prepared statement] P.
  5477  ** ^If prepared statement P does not have results ready to return
  5478  ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5479  ** interfaces) then sqlite3_data_count(P) returns 0.
  5480  ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5481  ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5482  ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
  5483  ** will return non-zero if previous call to [sqlite3_step](P) returned
  5484  ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5485  ** where it always returns zero since each step of that multi-step
  5486  ** pragma returns 0 columns of data.
  5487  **
  5488  ** See also: [sqlite3_column_count()]
  5489  */
  5490  SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5491  
  5492  /*
  5493  ** CAPI3REF: Fundamental Datatypes
  5494  ** KEYWORDS: SQLITE_TEXT
  5495  **
  5496  ** ^(Every value in SQLite has one of five fundamental datatypes:
  5497  **
  5498  ** <ul>
  5499  ** <li> 64-bit signed integer
  5500  ** <li> 64-bit IEEE floating point number
  5501  ** <li> string
  5502  ** <li> BLOB
  5503  ** <li> NULL
  5504  ** </ul>)^
  5505  **
  5506  ** These constants are codes for each of those types.
  5507  **
  5508  ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5509  ** for a completely different meaning.  Software that links against both
  5510  ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5511  ** SQLITE_TEXT.
  5512  */
  5513  #define SQLITE_INTEGER  1
  5514  #define SQLITE_FLOAT    2
  5515  #define SQLITE_BLOB     4
  5516  #define SQLITE_NULL     5
  5517  #ifdef SQLITE_TEXT
  5518  # undef SQLITE_TEXT
  5519  #else
  5520  # define SQLITE_TEXT     3
  5521  #endif
  5522  #define SQLITE3_TEXT     3
  5523  
  5524  /*
  5525  ** CAPI3REF: Result Values From A Query
  5526  ** KEYWORDS: {column access functions}
  5527  ** METHOD: sqlite3_stmt
  5528  **
  5529  ** <b>Summary:</b>
  5530  ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5531  ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5532  ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5533  ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5534  ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5535  ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5536  ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5537  ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an 
  5538  ** [sqlite3_value|unprotected sqlite3_value] object.
  5539  ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5540  ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5541  ** or a UTF-8 TEXT result in bytes
  5542  ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5543  ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5544  ** TEXT in bytes
  5545  ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5546  ** datatype of the result
  5547  ** </table></blockquote>
  5548  **
  5549  ** <b>Details:</b>
  5550  **
  5551  ** ^These routines return information about a single column of the current
  5552  ** result row of a query.  ^In every case the first argument is a pointer
  5553  ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5554  ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5555  ** and the second argument is the index of the column for which information
  5556  ** should be returned. ^The leftmost column of the result set has the index 0.
  5557  ** ^The number of columns in the result can be determined using
  5558  ** [sqlite3_column_count()].
  5559  **
  5560  ** If the SQL statement does not currently point to a valid row, or if the
  5561  ** column index is out of range, the result is undefined.
  5562  ** These routines may only be called when the most recent call to
  5563  ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5564  ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5565  ** If any of these routines are called after [sqlite3_reset()] or
  5566  ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5567  ** something other than [SQLITE_ROW], the results are undefined.
  5568  ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5569  ** are called from a different thread while any of these routines
  5570  ** are pending, then the results are undefined.
  5571  **
  5572  ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5573  ** each return the value of a result column in a specific data format.  If
  5574  ** the result column is not initially in the requested format (for example,
  5575  ** if the query returns an integer but the sqlite3_column_text() interface
  5576  ** is used to extract the value) then an automatic type conversion is performed.
  5577  **
  5578  ** ^The sqlite3_column_type() routine returns the
  5579  ** [SQLITE_INTEGER | datatype code] for the initial data type
  5580  ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
  5581  ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5582  ** The return value of sqlite3_column_type() can be used to decide which
  5583  ** of the first six interface should be used to extract the column value.
  5584  ** The value returned by sqlite3_column_type() is only meaningful if no
  5585  ** automatic type conversions have occurred for the value in question.  
  5586  ** After a type conversion, the result of calling sqlite3_column_type()
  5587  ** is undefined, though harmless.  Future
  5588  ** versions of SQLite may change the behavior of sqlite3_column_type()
  5589  ** following a type conversion.
  5590  **
  5591  ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5592  ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5593  ** of that BLOB or string.
  5594  **
  5595  ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5596  ** routine returns the number of bytes in that BLOB or string.
  5597  ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5598  ** the string to UTF-8 and then returns the number of bytes.
  5599  ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5600  ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5601  ** the number of bytes in that string.
  5602  ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5603  **
  5604  ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5605  ** routine returns the number of bytes in that BLOB or string.
  5606  ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5607  ** the string to UTF-16 and then returns the number of bytes.
  5608  ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5609  ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5610  ** the number of bytes in that string.
  5611  ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5612  **
  5613  ** ^The values returned by [sqlite3_column_bytes()] and 
  5614  ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5615  ** of the string.  ^For clarity: the values returned by
  5616  ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5617  ** bytes in the string, not the number of characters.
  5618  **
  5619  ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5620  ** even empty strings, are always zero-terminated.  ^The return
  5621  ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5622  **
  5623  ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5624  ** [unprotected sqlite3_value] object.  In a multithreaded environment,
  5625  ** an unprotected sqlite3_value object may only be used safely with
  5626  ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5627  ** If the [unprotected sqlite3_value] object returned by
  5628  ** [sqlite3_column_value()] is used in any other way, including calls
  5629  ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5630  ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5631  ** Hence, the sqlite3_column_value() interface
  5632  ** is normally only useful within the implementation of 
  5633  ** [application-defined SQL functions] or [virtual tables], not within
  5634  ** top-level application code.
  5635  **
  5636  ** The these routines may attempt to convert the datatype of the result.
  5637  ** ^For example, if the internal representation is FLOAT and a text result
  5638  ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5639  ** conversion automatically.  ^(The following table details the conversions
  5640  ** that are applied:
  5641  **
  5642  ** <blockquote>
  5643  ** <table border="1">
  5644  ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
  5645  **
  5646  ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
  5647  ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
  5648  ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
  5649  ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
  5650  ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
  5651  ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
  5652  ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
  5653  ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
  5654  ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
  5655  ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
  5656  ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
  5657  ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
  5658  ** <tr><td>  TEXT    <td>   BLOB    <td> No change
  5659  ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
  5660  ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
  5661  ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
  5662  ** </table>
  5663  ** </blockquote>)^
  5664  **
  5665  ** Note that when type conversions occur, pointers returned by prior
  5666  ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5667  ** sqlite3_column_text16() may be invalidated.
  5668  ** Type conversions and pointer invalidations might occur
  5669  ** in the following cases:
  5670  **
  5671  ** <ul>
  5672  ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5673  **      sqlite3_column_text16() is called.  A zero-terminator might
  5674  **      need to be added to the string.</li>
  5675  ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5676  **      sqlite3_column_text16() is called.  The content must be converted
  5677  **      to UTF-16.</li>
  5678  ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5679  **      sqlite3_column_text() is called.  The content must be converted
  5680  **      to UTF-8.</li>
  5681  ** </ul>
  5682  **
  5683  ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5684  ** not invalidate a prior pointer, though of course the content of the buffer
  5685  ** that the prior pointer references will have been modified.  Other kinds
  5686  ** of conversion are done in place when it is possible, but sometimes they
  5687  ** are not possible and in those cases prior pointers are invalidated.
  5688  **
  5689  ** The safest policy is to invoke these routines
  5690  ** in one of the following ways:
  5691  **
  5692  ** <ul>
  5693  **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5694  **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5695  **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5696  ** </ul>
  5697  **
  5698  ** In other words, you should call sqlite3_column_text(),
  5699  ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5700  ** into the desired format, then invoke sqlite3_column_bytes() or
  5701  ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
  5702  ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5703  ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5704  ** with calls to sqlite3_column_bytes().
  5705  **
  5706  ** ^The pointers returned are valid until a type conversion occurs as
  5707  ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5708  ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
  5709  ** and BLOBs is freed automatically.  Do not pass the pointers returned
  5710  ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5711  ** [sqlite3_free()].
  5712  **
  5713  ** As long as the input parameters are correct, these routines will only
  5714  ** fail if an out-of-memory error occurs during a format conversion.
  5715  ** Only the following subset of interfaces are subject to out-of-memory
  5716  ** errors:
  5717  **
  5718  ** <ul>
  5719  ** <li> sqlite3_column_blob()
  5720  ** <li> sqlite3_column_text()
  5721  ** <li> sqlite3_column_text16()
  5722  ** <li> sqlite3_column_bytes()
  5723  ** <li> sqlite3_column_bytes16()
  5724  ** </ul>
  5725  **
  5726  ** If an out-of-memory error occurs, then the return value from these
  5727  ** routines is the same as if the column had contained an SQL NULL value.
  5728  ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5729  ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5730  ** return value is obtained and before any
  5731  ** other SQLite interface is called on the same [database connection].
  5732  */
  5733  SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5734  SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5735  SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5736  SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5737  SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5738  SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5739  SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5740  SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5741  SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5742  SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5743  
  5744  /*
  5745  ** CAPI3REF: Destroy A Prepared Statement Object
  5746  ** DESTRUCTOR: sqlite3_stmt
  5747  **
  5748  ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5749  ** ^If the most recent evaluation of the statement encountered no errors
  5750  ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5751  ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
  5752  ** sqlite3_finalize(S) returns the appropriate [error code] or
  5753  ** [extended error code].
  5754  **
  5755  ** ^The sqlite3_finalize(S) routine can be called at any point during
  5756  ** the life cycle of [prepared statement] S:
  5757  ** before statement S is ever evaluated, after
  5758  ** one or more calls to [sqlite3_reset()], or after any call
  5759  ** to [sqlite3_step()] regardless of whether or not the statement has
  5760  ** completed execution.
  5761  **
  5762  ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5763  **
  5764  ** The application must finalize every [prepared statement] in order to avoid
  5765  ** resource leaks.  It is a grievous error for the application to try to use
  5766  ** a prepared statement after it has been finalized.  Any use of a prepared
  5767  ** statement after it has been finalized can result in undefined and
  5768  ** undesirable behavior such as segfaults and heap corruption.
  5769  */
  5770  SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5771  
  5772  /*
  5773  ** CAPI3REF: Reset A Prepared Statement Object
  5774  ** METHOD: sqlite3_stmt
  5775  **
  5776  ** The sqlite3_reset() function is called to reset a [prepared statement]
  5777  ** object back to its initial state, ready to be re-executed.
  5778  ** ^Any SQL statement variables that had values bound to them using
  5779  ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5780  ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5781  **
  5782  ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5783  ** back to the beginning of its program.
  5784  **
  5785  ** ^If the most recent call to [sqlite3_step(S)] for the
  5786  ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5787  ** or if [sqlite3_step(S)] has never before been called on S,
  5788  ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5789  **
  5790  ** ^If the most recent call to [sqlite3_step(S)] for the
  5791  ** [prepared statement] S indicated an error, then
  5792  ** [sqlite3_reset(S)] returns an appropriate [error code].
  5793  **
  5794  ** ^The [sqlite3_reset(S)] interface does not change the values
  5795  ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5796  */
  5797  SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5798  
  5799  /*
  5800  ** CAPI3REF: Create Or Redefine SQL Functions
  5801  ** KEYWORDS: {function creation routines}
  5802  ** KEYWORDS: {application-defined SQL function}
  5803  ** KEYWORDS: {application-defined SQL functions}
  5804  ** METHOD: sqlite3
  5805  **
  5806  ** ^These functions (collectively known as "function creation routines")
  5807  ** are used to add SQL functions or aggregates or to redefine the behavior
  5808  ** of existing SQL functions or aggregates. The only differences between
  5809  ** the three "sqlite3_create_function*" routines are the text encoding 
  5810  ** expected for the second parameter (the name of the function being 
  5811  ** created) and the presence or absence of a destructor callback for
  5812  ** the application data pointer. Function sqlite3_create_window_function()
  5813  ** is similar, but allows the user to supply the extra callback functions
  5814  ** needed by [aggregate window functions].
  5815  **
  5816  ** ^The first parameter is the [database connection] to which the SQL
  5817  ** function is to be added.  ^If an application uses more than one database
  5818  ** connection then application-defined SQL functions must be added
  5819  ** to each database connection separately.
  5820  **
  5821  ** ^The second parameter is the name of the SQL function to be created or
  5822  ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
  5823  ** representation, exclusive of the zero-terminator.  ^Note that the name
  5824  ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
  5825  ** ^Any attempt to create a function with a longer name
  5826  ** will result in [SQLITE_MISUSE] being returned.
  5827  **
  5828  ** ^The third parameter (nArg)
  5829  ** is the number of arguments that the SQL function or
  5830  ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5831  ** aggregate may take any number of arguments between 0 and the limit
  5832  ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
  5833  ** parameter is less than -1 or greater than 127 then the behavior is
  5834  ** undefined.
  5835  **
  5836  ** ^The fourth parameter, eTextRep, specifies what
  5837  ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5838  ** its parameters.  The application should set this parameter to
  5839  ** [SQLITE_UTF16LE] if the function implementation invokes 
  5840  ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5841  ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5842  ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5843  ** otherwise.  ^The same SQL function may be registered multiple times using
  5844  ** different preferred text encodings, with different implementations for
  5845  ** each encoding.
  5846  ** ^When multiple implementations of the same function are available, SQLite
  5847  ** will pick the one that involves the least amount of data conversion.
  5848  **
  5849  ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5850  ** to signal that the function will always return the same result given
  5851  ** the same inputs within a single SQL statement.  Most SQL functions are
  5852  ** deterministic.  The built-in [random()] SQL function is an example of a
  5853  ** function that is not deterministic.  The SQLite query planner is able to
  5854  ** perform additional optimizations on deterministic functions, so use
  5855  ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5856  **
  5857  ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
  5858  ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5859  **
  5860  ** ^The sixth, seventh and eighth parameters passed to the three
  5861  ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
  5862  ** pointers to C-language functions that implement the SQL function or
  5863  ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5864  ** callback only; NULL pointers must be passed as the xStep and xFinal
  5865  ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5866  ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5867  ** SQL function or aggregate, pass NULL pointers for all three function
  5868  ** callbacks.
  5869  **
  5870  ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue 
  5871  ** and xInverse) passed to sqlite3_create_window_function are pointers to
  5872  ** C-language callbacks that implement the new function. xStep and xFinal
  5873  ** must both be non-NULL. xValue and xInverse may either both be NULL, in
  5874  ** which case a regular aggregate function is created, or must both be 
  5875  ** non-NULL, in which case the new function may be used as either an aggregate
  5876  ** or aggregate window function. More details regarding the implementation
  5877  ** of aggregate window functions are 
  5878  ** [user-defined window functions|available here].
  5879  **
  5880  ** ^(If the final parameter to sqlite3_create_function_v2() or
  5881  ** sqlite3_create_window_function() is not NULL, then it is destructor for
  5882  ** the application data pointer. The destructor is invoked when the function 
  5883  ** is deleted, either by being overloaded or when the database connection 
  5884  ** closes.)^ ^The destructor is also invoked if the call to 
  5885  ** sqlite3_create_function_v2() fails.  ^When the destructor callback is
  5886  ** invoked, it is passed a single argument which is a copy of the application
  5887  ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
  5888  **
  5889  ** ^It is permitted to register multiple implementations of the same
  5890  ** functions with the same name but with either differing numbers of
  5891  ** arguments or differing preferred text encodings.  ^SQLite will use
  5892  ** the implementation that most closely matches the way in which the
  5893  ** SQL function is used.  ^A function implementation with a non-negative
  5894  ** nArg parameter is a better match than a function implementation with
  5895  ** a negative nArg.  ^A function where the preferred text encoding
  5896  ** matches the database encoding is a better
  5897  ** match than a function where the encoding is different.  
  5898  ** ^A function where the encoding difference is between UTF16le and UTF16be
  5899  ** is a closer match than a function where the encoding difference is
  5900  ** between UTF8 and UTF16.
  5901  **
  5902  ** ^Built-in functions may be overloaded by new application-defined functions.
  5903  **
  5904  ** ^An application-defined function is permitted to call other
  5905  ** SQLite interfaces.  However, such calls must not
  5906  ** close the database connection nor finalize or reset the prepared
  5907  ** statement in which the function is running.
  5908  */
  5909  SQLITE_API int sqlite3_create_function(
  5910    sqlite3 *db,
  5911    const char *zFunctionName,
  5912    int nArg,
  5913    int eTextRep,
  5914    void *pApp,
  5915    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5916    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5917    void (*xFinal)(sqlite3_context*)
  5918  );
  5919  SQLITE_API int sqlite3_create_function16(
  5920    sqlite3 *db,
  5921    const void *zFunctionName,
  5922    int nArg,
  5923    int eTextRep,
  5924    void *pApp,
  5925    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5926    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5927    void (*xFinal)(sqlite3_context*)
  5928  );
  5929  SQLITE_API int sqlite3_create_function_v2(
  5930    sqlite3 *db,
  5931    const char *zFunctionName,
  5932    int nArg,
  5933    int eTextRep,
  5934    void *pApp,
  5935    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5936    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5937    void (*xFinal)(sqlite3_context*),
  5938    void(*xDestroy)(void*)
  5939  );
  5940  SQLITE_API int sqlite3_create_window_function(
  5941    sqlite3 *db,
  5942    const char *zFunctionName,
  5943    int nArg,
  5944    int eTextRep,
  5945    void *pApp,
  5946    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5947    void (*xFinal)(sqlite3_context*),
  5948    void (*xValue)(sqlite3_context*),
  5949    void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  5950    void(*xDestroy)(void*)
  5951  );
  5952  
  5953  /*
  5954  ** CAPI3REF: Text Encodings
  5955  **
  5956  ** These constant define integer codes that represent the various
  5957  ** text encodings supported by SQLite.
  5958  */
  5959  #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
  5960  #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
  5961  #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
  5962  #define SQLITE_UTF16          4    /* Use native byte order */
  5963  #define SQLITE_ANY            5    /* Deprecated */
  5964  #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
  5965  
  5966  /*
  5967  ** CAPI3REF: Function Flags
  5968  **
  5969  ** These constants may be ORed together with the 
  5970  ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5971  ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5972  ** [sqlite3_create_function_v2()].
  5973  */
  5974  #define SQLITE_DETERMINISTIC    0x800
  5975  
  5976  /*
  5977  ** CAPI3REF: Deprecated Functions
  5978  ** DEPRECATED
  5979  **
  5980  ** These functions are [deprecated].  In order to maintain
  5981  ** backwards compatibility with older code, these functions continue 
  5982  ** to be supported.  However, new applications should avoid
  5983  ** the use of these functions.  To encourage programmers to avoid
  5984  ** these functions, we will not explain what they do.
  5985  */
  5986  #ifndef SQLITE_OMIT_DEPRECATED
  5987  SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5988  SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5989  SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5990  SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5991  SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5992  SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5993                        void*,sqlite3_int64);
  5994  #endif
  5995  
  5996  /*
  5997  ** CAPI3REF: Obtaining SQL Values
  5998  ** METHOD: sqlite3_value
  5999  **
  6000  ** <b>Summary:</b>
  6001  ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  6002  ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  6003  ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  6004  ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  6005  ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  6006  ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  6007  ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  6008  ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  6009  ** the native byteorder
  6010  ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  6011  ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  6012  ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  6013  ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  6014  ** or a UTF-8 TEXT in bytes
  6015  ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  6016  ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  6017  ** TEXT in bytes
  6018  ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  6019  ** datatype of the value
  6020  ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  6021  ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  6022  ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  6023  ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  6024  ** against a virtual table.
  6025  ** </table></blockquote>
  6026  **
  6027  ** <b>Details:</b>
  6028  **
  6029  ** These routines extract type, size, and content information from
  6030  ** [protected sqlite3_value] objects.  Protected sqlite3_value objects
  6031  ** are used to pass parameter information into implementation of
  6032  ** [application-defined SQL functions] and [virtual tables].
  6033  **
  6034  ** These routines work only with [protected sqlite3_value] objects.
  6035  ** Any attempt to use these routines on an [unprotected sqlite3_value]
  6036  ** is not threadsafe.
  6037  **
  6038  ** ^These routines work just like the corresponding [column access functions]
  6039  ** except that these routines take a single [protected sqlite3_value] object
  6040  ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  6041  **
  6042  ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  6043  ** in the native byte-order of the host machine.  ^The
  6044  ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  6045  ** extract UTF-16 strings as big-endian and little-endian respectively.
  6046  **
  6047  ** ^If [sqlite3_value] object V was initialized 
  6048  ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  6049  ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  6050  ** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
  6051  ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() 
  6052  ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6053  **
  6054  ** ^(The sqlite3_value_type(V) interface returns the
  6055  ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  6056  ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  6057  ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  6058  ** Other interfaces might change the datatype for an sqlite3_value object.
  6059  ** For example, if the datatype is initially SQLITE_INTEGER and
  6060  ** sqlite3_value_text(V) is called to extract a text value for that
  6061  ** integer, then subsequent calls to sqlite3_value_type(V) might return
  6062  ** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion
  6063  ** occurs is undefined and may change from one release of SQLite to the next.
  6064  **
  6065  ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  6066  ** numeric affinity to the value.  This means that an attempt is
  6067  ** made to convert the value to an integer or floating point.  If
  6068  ** such a conversion is possible without loss of information (in other
  6069  ** words, if the value is a string that looks like a number)
  6070  ** then the conversion is performed.  Otherwise no conversion occurs.
  6071  ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  6072  **
  6073  ** ^Within the [xUpdate] method of a [virtual table], the
  6074  ** sqlite3_value_nochange(X) interface returns true if and only if
  6075  ** the column corresponding to X is unchanged by the UPDATE operation
  6076  ** that the xUpdate method call was invoked to implement and if
  6077  ** and the prior [xColumn] method call that was invoked to extracted
  6078  ** the value for that column returned without setting a result (probably
  6079  ** because it queried [sqlite3_vtab_nochange()] and found that the column
  6080  ** was unchanging).  ^Within an [xUpdate] method, any value for which
  6081  ** sqlite3_value_nochange(X) is true will in all other respects appear
  6082  ** to be a NULL value.  If sqlite3_value_nochange(X) is invoked anywhere other
  6083  ** than within an [xUpdate] method call for an UPDATE statement, then
  6084  ** the return value is arbitrary and meaningless.
  6085  **
  6086  ** Please pay particular attention to the fact that the pointer returned
  6087  ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  6088  ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  6089  ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  6090  ** or [sqlite3_value_text16()].
  6091  **
  6092  ** These routines must be called from the same thread as
  6093  ** the SQL function that supplied the [sqlite3_value*] parameters.
  6094  **
  6095  ** As long as the input parameter is correct, these routines can only
  6096  ** fail if an out-of-memory error occurs during a format conversion.
  6097  ** Only the following subset of interfaces are subject to out-of-memory
  6098  ** errors:
  6099  **
  6100  ** <ul>
  6101  ** <li> sqlite3_value_blob()
  6102  ** <li> sqlite3_value_text()
  6103  ** <li> sqlite3_value_text16()
  6104  ** <li> sqlite3_value_text16le()
  6105  ** <li> sqlite3_value_text16be()
  6106  ** <li> sqlite3_value_bytes()
  6107  ** <li> sqlite3_value_bytes16()
  6108  ** </ul>
  6109  **
  6110  ** If an out-of-memory error occurs, then the return value from these
  6111  ** routines is the same as if the column had contained an SQL NULL value.
  6112  ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  6113  ** by invoking the [sqlite3_errcode()] immediately after the suspect
  6114  ** return value is obtained and before any
  6115  ** other SQLite interface is called on the same [database connection].
  6116  */
  6117  SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  6118  SQLITE_API double sqlite3_value_double(sqlite3_value*);
  6119  SQLITE_API int sqlite3_value_int(sqlite3_value*);
  6120  SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  6121  SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  6122  SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  6123  SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  6124  SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  6125  SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  6126  SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  6127  SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  6128  SQLITE_API int sqlite3_value_type(sqlite3_value*);
  6129  SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  6130  SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  6131  
  6132  /*
  6133  ** CAPI3REF: Finding The Subtype Of SQL Values
  6134  ** METHOD: sqlite3_value
  6135  **
  6136  ** The sqlite3_value_subtype(V) function returns the subtype for
  6137  ** an [application-defined SQL function] argument V.  The subtype
  6138  ** information can be used to pass a limited amount of context from
  6139  ** one SQL function to another.  Use the [sqlite3_result_subtype()]
  6140  ** routine to set the subtype for the return value of an SQL function.
  6141  */
  6142  SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  6143  
  6144  /*
  6145  ** CAPI3REF: Copy And Free SQL Values
  6146  ** METHOD: sqlite3_value
  6147  **
  6148  ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  6149  ** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
  6150  ** is a [protected sqlite3_value] object even if the input is not.
  6151  ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  6152  ** memory allocation fails.
  6153  **
  6154  ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  6155  ** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
  6156  ** then sqlite3_value_free(V) is a harmless no-op.
  6157  */
  6158  SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  6159  SQLITE_API void sqlite3_value_free(sqlite3_value*);
  6160  
  6161  /*
  6162  ** CAPI3REF: Obtain Aggregate Function Context
  6163  ** METHOD: sqlite3_context
  6164  **
  6165  ** Implementations of aggregate SQL functions use this
  6166  ** routine to allocate memory for storing their state.
  6167  **
  6168  ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
  6169  ** for a particular aggregate function, SQLite
  6170  ** allocates N of memory, zeroes out that memory, and returns a pointer
  6171  ** to the new memory. ^On second and subsequent calls to
  6172  ** sqlite3_aggregate_context() for the same aggregate function instance,
  6173  ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
  6174  ** called once for each invocation of the xStep callback and then one
  6175  ** last time when the xFinal callback is invoked.  ^(When no rows match
  6176  ** an aggregate query, the xStep() callback of the aggregate function
  6177  ** implementation is never called and xFinal() is called exactly once.
  6178  ** In those cases, sqlite3_aggregate_context() might be called for the
  6179  ** first time from within xFinal().)^
  6180  **
  6181  ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
  6182  ** when first called if N is less than or equal to zero or if a memory
  6183  ** allocate error occurs.
  6184  **
  6185  ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  6186  ** determined by the N parameter on first successful call.  Changing the
  6187  ** value of N in subsequent call to sqlite3_aggregate_context() within
  6188  ** the same aggregate function instance will not resize the memory
  6189  ** allocation.)^  Within the xFinal callback, it is customary to set
  6190  ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
  6191  ** pointless memory allocations occur.
  6192  **
  6193  ** ^SQLite automatically frees the memory allocated by 
  6194  ** sqlite3_aggregate_context() when the aggregate query concludes.
  6195  **
  6196  ** The first parameter must be a copy of the
  6197  ** [sqlite3_context | SQL function context] that is the first parameter
  6198  ** to the xStep or xFinal callback routine that implements the aggregate
  6199  ** function.
  6200  **
  6201  ** This routine must be called from the same thread in which
  6202  ** the aggregate SQL function is running.
  6203  */
  6204  SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  6205  
  6206  /*
  6207  ** CAPI3REF: User Data For Functions
  6208  ** METHOD: sqlite3_context
  6209  **
  6210  ** ^The sqlite3_user_data() interface returns a copy of
  6211  ** the pointer that was the pUserData parameter (the 5th parameter)
  6212  ** of the [sqlite3_create_function()]
  6213  ** and [sqlite3_create_function16()] routines that originally
  6214  ** registered the application defined function.
  6215  **
  6216  ** This routine must be called from the same thread in which
  6217  ** the application-defined function is running.
  6218  */
  6219  SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  6220  
  6221  /*
  6222  ** CAPI3REF: Database Connection For Functions
  6223  ** METHOD: sqlite3_context
  6224  **
  6225  ** ^The sqlite3_context_db_handle() interface returns a copy of
  6226  ** the pointer to the [database connection] (the 1st parameter)
  6227  ** of the [sqlite3_create_function()]
  6228  ** and [sqlite3_create_function16()] routines that originally
  6229  ** registered the application defined function.
  6230  */
  6231  SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  6232  
  6233  /*
  6234  ** CAPI3REF: Function Auxiliary Data
  6235  ** METHOD: sqlite3_context
  6236  **
  6237  ** These functions may be used by (non-aggregate) SQL functions to
  6238  ** associate metadata with argument values. If the same value is passed to
  6239  ** multiple invocations of the same SQL function during query execution, under
  6240  ** some circumstances the associated metadata may be preserved.  An example
  6241  ** of where this might be useful is in a regular-expression matching
  6242  ** function. The compiled version of the regular expression can be stored as
  6243  ** metadata associated with the pattern string.  
  6244  ** Then as long as the pattern string remains the same,
  6245  ** the compiled regular expression can be reused on multiple
  6246  ** invocations of the same function.
  6247  **
  6248  ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  6249  ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  6250  ** value to the application-defined function.  ^N is zero for the left-most
  6251  ** function argument.  ^If there is no metadata
  6252  ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  6253  ** returns a NULL pointer.
  6254  **
  6255  ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6256  ** argument of the application-defined function.  ^Subsequent
  6257  ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6258  ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6259  ** NULL if the metadata has been discarded.
  6260  ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6261  ** SQLite will invoke the destructor function X with parameter P exactly
  6262  ** once, when the metadata is discarded.
  6263  ** SQLite is free to discard the metadata at any time, including: <ul>
  6264  ** <li> ^(when the corresponding function parameter changes)^, or
  6265  ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6266  **      SQL statement)^, or
  6267  ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6268  **       parameter)^, or
  6269  ** <li> ^(during the original sqlite3_set_auxdata() call when a memory 
  6270  **      allocation error occurs.)^ </ul>
  6271  **
  6272  ** Note the last bullet in particular.  The destructor X in 
  6273  ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6274  ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
  6275  ** should be called near the end of the function implementation and the
  6276  ** function implementation should not make any use of P after
  6277  ** sqlite3_set_auxdata() has been called.
  6278  **
  6279  ** ^(In practice, metadata is preserved between function calls for
  6280  ** function parameters that are compile-time constants, including literal
  6281  ** values and [parameters] and expressions composed from the same.)^
  6282  **
  6283  ** The value of the N parameter to these interfaces should be non-negative.
  6284  ** Future enhancements may make use of negative N values to define new
  6285  ** kinds of function caching behavior.
  6286  **
  6287  ** These routines must be called from the same thread in which
  6288  ** the SQL function is running.
  6289  */
  6290  SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6291  SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6292  
  6293  
  6294  /*
  6295  ** CAPI3REF: Constants Defining Special Destructor Behavior
  6296  **
  6297  ** These are special values for the destructor that is passed in as the
  6298  ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
  6299  ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6300  ** and will never change.  It does not need to be destroyed.  ^The
  6301  ** SQLITE_TRANSIENT value means that the content will likely change in
  6302  ** the near future and that SQLite should make its own private copy of
  6303  ** the content before returning.
  6304  **
  6305  ** The typedef is necessary to work around problems in certain
  6306  ** C++ compilers.
  6307  */
  6308  typedef void (*sqlite3_destructor_type)(void*);
  6309  #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
  6310  #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
  6311  
  6312  /*
  6313  ** CAPI3REF: Setting The Result Of An SQL Function
  6314  ** METHOD: sqlite3_context
  6315  **
  6316  ** These routines are used by the xFunc or xFinal callbacks that
  6317  ** implement SQL functions and aggregates.  See
  6318  ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6319  ** for additional information.
  6320  **
  6321  ** These functions work very much like the [parameter binding] family of
  6322  ** functions used to bind values to host parameters in prepared statements.
  6323  ** Refer to the [SQL parameter] documentation for additional information.
  6324  **
  6325  ** ^The sqlite3_result_blob() interface sets the result from
  6326  ** an application-defined function to be the BLOB whose content is pointed
  6327  ** to by the second parameter and which is N bytes long where N is the
  6328  ** third parameter.
  6329  **
  6330  ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6331  ** interfaces set the result of the application-defined function to be
  6332  ** a BLOB containing all zero bytes and N bytes in size.
  6333  **
  6334  ** ^The sqlite3_result_double() interface sets the result from
  6335  ** an application-defined function to be a floating point value specified
  6336  ** by its 2nd argument.
  6337  **
  6338  ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6339  ** cause the implemented SQL function to throw an exception.
  6340  ** ^SQLite uses the string pointed to by the
  6341  ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6342  ** as the text of an error message.  ^SQLite interprets the error
  6343  ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6344  ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  6345  ** byte order.  ^If the third parameter to sqlite3_result_error()
  6346  ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6347  ** message all text up through the first zero character.
  6348  ** ^If the third parameter to sqlite3_result_error() or
  6349  ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6350  ** bytes (not characters) from the 2nd parameter as the error message.
  6351  ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6352  ** routines make a private copy of the error message text before
  6353  ** they return.  Hence, the calling function can deallocate or
  6354  ** modify the text after they return without harm.
  6355  ** ^The sqlite3_result_error_code() function changes the error code
  6356  ** returned by SQLite as a result of an error in a function.  ^By default,
  6357  ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
  6358  ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6359  **
  6360  ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6361  ** error indicating that a string or BLOB is too long to represent.
  6362  **
  6363  ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6364  ** error indicating that a memory allocation failed.
  6365  **
  6366  ** ^The sqlite3_result_int() interface sets the return value
  6367  ** of the application-defined function to be the 32-bit signed integer
  6368  ** value given in the 2nd argument.
  6369  ** ^The sqlite3_result_int64() interface sets the return value
  6370  ** of the application-defined function to be the 64-bit signed integer
  6371  ** value given in the 2nd argument.
  6372  **
  6373  ** ^The sqlite3_result_null() interface sets the return value
  6374  ** of the application-defined function to be NULL.
  6375  **
  6376  ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6377  ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6378  ** set the return value of the application-defined function to be
  6379  ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6380  ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6381  ** ^The sqlite3_result_text64() interface sets the return value of an
  6382  ** application-defined function to be a text string in an encoding
  6383  ** specified by the fifth (and last) parameter, which must be one
  6384  ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6385  ** ^SQLite takes the text result from the application from
  6386  ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6387  ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6388  ** is negative, then SQLite takes result text from the 2nd parameter
  6389  ** through the first zero character.
  6390  ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6391  ** is non-negative, then as many bytes (not characters) of the text
  6392  ** pointed to by the 2nd parameter are taken as the application-defined
  6393  ** function result.  If the 3rd parameter is non-negative, then it
  6394  ** must be the byte offset into the string where the NUL terminator would
  6395  ** appear if the string where NUL terminated.  If any NUL characters occur
  6396  ** in the string at a byte offset that is less than the value of the 3rd
  6397  ** parameter, then the resulting string will contain embedded NULs and the
  6398  ** result of expressions operating on strings with embedded NULs is undefined.
  6399  ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6400  ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6401  ** function as the destructor on the text or BLOB result when it has
  6402  ** finished using that result.
  6403  ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6404  ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6405  ** assumes that the text or BLOB result is in constant space and does not
  6406  ** copy the content of the parameter nor call a destructor on the content
  6407  ** when it has finished using that result.
  6408  ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6409  ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6410  ** then SQLite makes a copy of the result into space obtained
  6411  ** from [sqlite3_malloc()] before it returns.
  6412  **
  6413  ** ^The sqlite3_result_value() interface sets the result of
  6414  ** the application-defined function to be a copy of the
  6415  ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
  6416  ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6417  ** so that the [sqlite3_value] specified in the parameter may change or
  6418  ** be deallocated after sqlite3_result_value() returns without harm.
  6419  ** ^A [protected sqlite3_value] object may always be used where an
  6420  ** [unprotected sqlite3_value] object is required, so either
  6421  ** kind of [sqlite3_value] object can be used with this interface.
  6422  **
  6423  ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6424  ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6425  ** also associates the host-language pointer P or type T with that 
  6426  ** NULL value such that the pointer can be retrieved within an
  6427  ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6428  ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6429  ** for the P parameter.  ^SQLite invokes D with P as its only argument
  6430  ** when SQLite is finished with P.  The T parameter should be a static
  6431  ** string and preferably a string literal. The sqlite3_result_pointer()
  6432  ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6433  **
  6434  ** If these routines are called from within the different thread
  6435  ** than the one containing the application-defined function that received
  6436  ** the [sqlite3_context] pointer, the results are undefined.
  6437  */
  6438  SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6439  SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6440                             sqlite3_uint64,void(*)(void*));
  6441  SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6442  SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6443  SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6444  SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6445  SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6446  SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6447  SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6448  SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6449  SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6450  SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6451  SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6452                             void(*)(void*), unsigned char encoding);
  6453  SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6454  SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6455  SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6456  SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6457  SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6458  SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6459  SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6460  
  6461  
  6462  /*
  6463  ** CAPI3REF: Setting The Subtype Of An SQL Function
  6464  ** METHOD: sqlite3_context
  6465  **
  6466  ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6467  ** the result from the [application-defined SQL function] with 
  6468  ** [sqlite3_context] C to be the value T.  Only the lower 8 bits 
  6469  ** of the subtype T are preserved in current versions of SQLite;
  6470  ** higher order bits are discarded.
  6471  ** The number of subtype bytes preserved by SQLite might increase
  6472  ** in future releases of SQLite.
  6473  */
  6474  SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6475  
  6476  /*
  6477  ** CAPI3REF: Define New Collating Sequences
  6478  ** METHOD: sqlite3
  6479  **
  6480  ** ^These functions add, remove, or modify a [collation] associated
  6481  ** with the [database connection] specified as the first argument.
  6482  **
  6483  ** ^The name of the collation is a UTF-8 string
  6484  ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6485  ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6486  ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6487  ** considered to be the same name.
  6488  **
  6489  ** ^(The third argument (eTextRep) must be one of the constants:
  6490  ** <ul>
  6491  ** <li> [SQLITE_UTF8],
  6492  ** <li> [SQLITE_UTF16LE],
  6493  ** <li> [SQLITE_UTF16BE],
  6494  ** <li> [SQLITE_UTF16], or
  6495  ** <li> [SQLITE_UTF16_ALIGNED].
  6496  ** </ul>)^
  6497  ** ^The eTextRep argument determines the encoding of strings passed
  6498  ** to the collating function callback, xCallback.
  6499  ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6500  ** force strings to be UTF16 with native byte order.
  6501  ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6502  ** on an even byte address.
  6503  **
  6504  ** ^The fourth argument, pArg, is an application data pointer that is passed
  6505  ** through as the first argument to the collating function callback.
  6506  **
  6507  ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6508  ** ^Multiple collating functions can be registered using the same name but
  6509  ** with different eTextRep parameters and SQLite will use whichever
  6510  ** function requires the least amount of data transformation.
  6511  ** ^If the xCallback argument is NULL then the collating function is
  6512  ** deleted.  ^When all collating functions having the same name are deleted,
  6513  ** that collation is no longer usable.
  6514  **
  6515  ** ^The collating function callback is invoked with a copy of the pArg 
  6516  ** application data pointer and with two strings in the encoding specified
  6517  ** by the eTextRep argument.  The collating function must return an
  6518  ** integer that is negative, zero, or positive
  6519  ** if the first string is less than, equal to, or greater than the second,
  6520  ** respectively.  A collating function must always return the same answer
  6521  ** given the same inputs.  If two or more collating functions are registered
  6522  ** to the same collation name (using different eTextRep values) then all
  6523  ** must give an equivalent answer when invoked with equivalent strings.
  6524  ** The collating function must obey the following properties for all
  6525  ** strings A, B, and C:
  6526  **
  6527  ** <ol>
  6528  ** <li> If A==B then B==A.
  6529  ** <li> If A==B and B==C then A==C.
  6530  ** <li> If A&lt;B THEN B&gt;A.
  6531  ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6532  ** </ol>
  6533  **
  6534  ** If a collating function fails any of the above constraints and that
  6535  ** collating function is  registered and used, then the behavior of SQLite
  6536  ** is undefined.
  6537  **
  6538  ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6539  ** with the addition that the xDestroy callback is invoked on pArg when
  6540  ** the collating function is deleted.
  6541  ** ^Collating functions are deleted when they are overridden by later
  6542  ** calls to the collation creation functions or when the
  6543  ** [database connection] is closed using [sqlite3_close()].
  6544  **
  6545  ** ^The xDestroy callback is <u>not</u> called if the 
  6546  ** sqlite3_create_collation_v2() function fails.  Applications that invoke
  6547  ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
  6548  ** check the return code and dispose of the application data pointer
  6549  ** themselves rather than expecting SQLite to deal with it for them.
  6550  ** This is different from every other SQLite interface.  The inconsistency 
  6551  ** is unfortunate but cannot be changed without breaking backwards 
  6552  ** compatibility.
  6553  **
  6554  ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6555  */
  6556  SQLITE_API int sqlite3_create_collation(
  6557    sqlite3*, 
  6558    const char *zName, 
  6559    int eTextRep, 
  6560    void *pArg,
  6561    int(*xCompare)(void*,int,const void*,int,const void*)
  6562  );
  6563  SQLITE_API int sqlite3_create_collation_v2(
  6564    sqlite3*, 
  6565    const char *zName, 
  6566    int eTextRep, 
  6567    void *pArg,
  6568    int(*xCompare)(void*,int,const void*,int,const void*),
  6569    void(*xDestroy)(void*)
  6570  );
  6571  SQLITE_API int sqlite3_create_collation16(
  6572    sqlite3*, 
  6573    const void *zName,
  6574    int eTextRep, 
  6575    void *pArg,
  6576    int(*xCompare)(void*,int,const void*,int,const void*)
  6577  );
  6578  
  6579  /*
  6580  ** CAPI3REF: Collation Needed Callbacks
  6581  ** METHOD: sqlite3
  6582  **
  6583  ** ^To avoid having to register all collation sequences before a database
  6584  ** can be used, a single callback function may be registered with the
  6585  ** [database connection] to be invoked whenever an undefined collation
  6586  ** sequence is required.
  6587  **
  6588  ** ^If the function is registered using the sqlite3_collation_needed() API,
  6589  ** then it is passed the names of undefined collation sequences as strings
  6590  ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6591  ** the names are passed as UTF-16 in machine native byte order.
  6592  ** ^A call to either function replaces the existing collation-needed callback.
  6593  **
  6594  ** ^(When the callback is invoked, the first argument passed is a copy
  6595  ** of the second argument to sqlite3_collation_needed() or
  6596  ** sqlite3_collation_needed16().  The second argument is the database
  6597  ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6598  ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6599  ** sequence function required.  The fourth parameter is the name of the
  6600  ** required collation sequence.)^
  6601  **
  6602  ** The callback function should register the desired collation using
  6603  ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6604  ** [sqlite3_create_collation_v2()].
  6605  */
  6606  SQLITE_API int sqlite3_collation_needed(
  6607    sqlite3*, 
  6608    void*, 
  6609    void(*)(void*,sqlite3*,int eTextRep,const char*)
  6610  );
  6611  SQLITE_API int sqlite3_collation_needed16(
  6612    sqlite3*, 
  6613    void*,
  6614    void(*)(void*,sqlite3*,int eTextRep,const void*)
  6615  );
  6616  
  6617  #ifdef SQLITE_HAS_CODEC
  6618  /*
  6619  ** Specify the key for an encrypted database.  This routine should be
  6620  ** called right after sqlite3_open().
  6621  **
  6622  ** The code to implement this API is not available in the public release
  6623  ** of SQLite.
  6624  */
  6625  SQLITE_API int sqlite3_key(
  6626    sqlite3 *db,                   /* Database to be rekeyed */
  6627    const void *pKey, int nKey     /* The key */
  6628  );
  6629  SQLITE_API int sqlite3_key_v2(
  6630    sqlite3 *db,                   /* Database to be rekeyed */
  6631    const char *zDbName,           /* Name of the database */
  6632    const void *pKey, int nKey     /* The key */
  6633  );
  6634  
  6635  /*
  6636  ** Change the key on an open database.  If the current database is not
  6637  ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
  6638  ** database is decrypted.
  6639  **
  6640  ** The code to implement this API is not available in the public release
  6641  ** of SQLite.
  6642  */
  6643  SQLITE_API int sqlite3_rekey(
  6644    sqlite3 *db,                   /* Database to be rekeyed */
  6645    const void *pKey, int nKey     /* The new key */
  6646  );
  6647  SQLITE_API int sqlite3_rekey_v2(
  6648    sqlite3 *db,                   /* Database to be rekeyed */
  6649    const char *zDbName,           /* Name of the database */
  6650    const void *pKey, int nKey     /* The new key */
  6651  );
  6652  
  6653  /*
  6654  ** Specify the activation key for a SEE database.  Unless 
  6655  ** activated, none of the SEE routines will work.
  6656  */
  6657  SQLITE_API void sqlite3_activate_see(
  6658    const char *zPassPhrase        /* Activation phrase */
  6659  );
  6660  #endif
  6661  
  6662  #ifdef SQLITE_ENABLE_CEROD
  6663  /*
  6664  ** Specify the activation key for a CEROD database.  Unless 
  6665  ** activated, none of the CEROD routines will work.
  6666  */
  6667  SQLITE_API void sqlite3_activate_cerod(
  6668    const char *zPassPhrase        /* Activation phrase */
  6669  );
  6670  #endif
  6671  
  6672  /*
  6673  ** CAPI3REF: Suspend Execution For A Short Time
  6674  **
  6675  ** The sqlite3_sleep() function causes the current thread to suspend execution
  6676  ** for at least a number of milliseconds specified in its parameter.
  6677  **
  6678  ** If the operating system does not support sleep requests with
  6679  ** millisecond time resolution, then the time will be rounded up to
  6680  ** the nearest second. The number of milliseconds of sleep actually
  6681  ** requested from the operating system is returned.
  6682  **
  6683  ** ^SQLite implements this interface by calling the xSleep()
  6684  ** method of the default [sqlite3_vfs] object.  If the xSleep() method
  6685  ** of the default VFS is not implemented correctly, or not implemented at
  6686  ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6687  ** in the previous paragraphs.
  6688  */
  6689  SQLITE_API int sqlite3_sleep(int);
  6690  
  6691  /*
  6692  ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6693  **
  6694  ** ^(If this global variable is made to point to a string which is
  6695  ** the name of a folder (a.k.a. directory), then all temporary files
  6696  ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6697  ** will be placed in that directory.)^  ^If this variable
  6698  ** is a NULL pointer, then SQLite performs a search for an appropriate
  6699  ** temporary file directory.
  6700  **
  6701  ** Applications are strongly discouraged from using this global variable.
  6702  ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6703  ** But for all other platforms, it is highly recommended that applications
  6704  ** neither read nor write this variable.  This global variable is a relic
  6705  ** that exists for backwards compatibility of legacy applications and should
  6706  ** be avoided in new projects.
  6707  **
  6708  ** It is not safe to read or modify this variable in more than one
  6709  ** thread at a time.  It is not safe to read or modify this variable
  6710  ** if a [database connection] is being used at the same time in a separate
  6711  ** thread.
  6712  ** It is intended that this variable be set once
  6713  ** as part of process initialization and before any SQLite interface
  6714  ** routines have been called and that this variable remain unchanged
  6715  ** thereafter.
  6716  **
  6717  ** ^The [temp_store_directory pragma] may modify this variable and cause
  6718  ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  6719  ** the [temp_store_directory pragma] always assumes that any string
  6720  ** that this variable points to is held in memory obtained from 
  6721  ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6722  ** using [sqlite3_free].
  6723  ** Hence, if this variable is modified directly, either it should be
  6724  ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6725  ** or else the use of the [temp_store_directory pragma] should be avoided.
  6726  ** Except when requested by the [temp_store_directory pragma], SQLite
  6727  ** does not free the memory that sqlite3_temp_directory points to.  If
  6728  ** the application wants that memory to be freed, it must do
  6729  ** so itself, taking care to only do so after all [database connection]
  6730  ** objects have been destroyed.
  6731  **
  6732  ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
  6733  ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
  6734  ** features that require the use of temporary files may fail.  Here is an
  6735  ** example of how to do this using C++ with the Windows Runtime:
  6736  **
  6737  ** <blockquote><pre>
  6738  ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6739  ** &nbsp;     TemporaryFolder->Path->Data();
  6740  ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6741  ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6742  ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6743  ** &nbsp;     NULL, NULL);
  6744  ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6745  ** </pre></blockquote>
  6746  */
  6747  SQLITE_API char *sqlite3_temp_directory;
  6748  
  6749  /*
  6750  ** CAPI3REF: Name Of The Folder Holding Database Files
  6751  **
  6752  ** ^(If this global variable is made to point to a string which is
  6753  ** the name of a folder (a.k.a. directory), then all database files
  6754  ** specified with a relative pathname and created or accessed by
  6755  ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6756  ** to be relative to that directory.)^ ^If this variable is a NULL
  6757  ** pointer, then SQLite assumes that all database files specified
  6758  ** with a relative pathname are relative to the current directory
  6759  ** for the process.  Only the windows VFS makes use of this global
  6760  ** variable; it is ignored by the unix VFS.
  6761  **
  6762  ** Changing the value of this variable while a database connection is
  6763  ** open can result in a corrupt database.
  6764  **
  6765  ** It is not safe to read or modify this variable in more than one
  6766  ** thread at a time.  It is not safe to read or modify this variable
  6767  ** if a [database connection] is being used at the same time in a separate
  6768  ** thread.
  6769  ** It is intended that this variable be set once
  6770  ** as part of process initialization and before any SQLite interface
  6771  ** routines have been called and that this variable remain unchanged
  6772  ** thereafter.
  6773  **
  6774  ** ^The [data_store_directory pragma] may modify this variable and cause
  6775  ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
  6776  ** the [data_store_directory pragma] always assumes that any string
  6777  ** that this variable points to is held in memory obtained from 
  6778  ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6779  ** using [sqlite3_free].
  6780  ** Hence, if this variable is modified directly, either it should be
  6781  ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6782  ** or else the use of the [data_store_directory pragma] should be avoided.
  6783  */
  6784  SQLITE_API char *sqlite3_data_directory;
  6785  
  6786  /*
  6787  ** CAPI3REF: Win32 Specific Interface
  6788  **
  6789  ** These interfaces are available only on Windows.  The
  6790  ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6791  ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6792  ** zValue, depending on the value of the type parameter.  The zValue parameter
  6793  ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6794  ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6795  ** prior to being used.  The [sqlite3_win32_set_directory] interface returns
  6796  ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6797  ** or [SQLITE_NOMEM] if memory could not be allocated.  The value of the
  6798  ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6799  ** the current directory on the sub-platforms of Win32 where that concept is
  6800  ** not present, e.g. WinRT and UWP.  The [sqlite3_win32_set_directory8] and
  6801  ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6802  ** sqlite3_win32_set_directory interface except the string parameter must be
  6803  ** UTF-8 or UTF-16, respectively.
  6804  */
  6805  SQLITE_API int sqlite3_win32_set_directory(
  6806    unsigned long type, /* Identifier for directory being set or reset */
  6807    void *zValue        /* New value for directory being set or reset */
  6808  );
  6809  SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6810  SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6811  
  6812  /*
  6813  ** CAPI3REF: Win32 Directory Types
  6814  **
  6815  ** These macros are only available on Windows.  They define the allowed values
  6816  ** for the type argument to the [sqlite3_win32_set_directory] interface.
  6817  */
  6818  #define SQLITE_WIN32_DATA_DIRECTORY_TYPE  1
  6819  #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE  2
  6820  
  6821  /*
  6822  ** CAPI3REF: Test For Auto-Commit Mode
  6823  ** KEYWORDS: {autocommit mode}
  6824  ** METHOD: sqlite3
  6825  **
  6826  ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6827  ** zero if the given database connection is or is not in autocommit mode,
  6828  ** respectively.  ^Autocommit mode is on by default.
  6829  ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6830  ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6831  **
  6832  ** If certain kinds of errors occur on a statement within a multi-statement
  6833  ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6834  ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6835  ** transaction might be rolled back automatically.  The only way to
  6836  ** find out whether SQLite automatically rolled back the transaction after
  6837  ** an error is to use this function.
  6838  **
  6839  ** If another thread changes the autocommit status of the database
  6840  ** connection while this routine is running, then the return value
  6841  ** is undefined.
  6842  */
  6843  SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6844  
  6845  /*
  6846  ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6847  ** METHOD: sqlite3_stmt
  6848  **
  6849  ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6850  ** to which a [prepared statement] belongs.  ^The [database connection]
  6851  ** returned by sqlite3_db_handle is the same [database connection]
  6852  ** that was the first argument
  6853  ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6854  ** create the statement in the first place.
  6855  */
  6856  SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6857  
  6858  /*
  6859  ** CAPI3REF: Return The Filename For A Database Connection
  6860  ** METHOD: sqlite3
  6861  **
  6862  ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6863  ** associated with database N of connection D.  ^The main database file
  6864  ** has the name "main".  If there is no attached database N on the database
  6865  ** connection D, or if database N is a temporary or in-memory database, then
  6866  ** a NULL pointer is returned.
  6867  **
  6868  ** ^The filename returned by this function is the output of the
  6869  ** xFullPathname method of the [VFS].  ^In other words, the filename
  6870  ** will be an absolute pathname, even if the filename used
  6871  ** to open the database originally was a URI or relative pathname.
  6872  */
  6873  SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6874  
  6875  /*
  6876  ** CAPI3REF: Determine if a database is read-only
  6877  ** METHOD: sqlite3
  6878  **
  6879  ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6880  ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6881  ** the name of a database on connection D.
  6882  */
  6883  SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6884  
  6885  /*
  6886  ** CAPI3REF: Find the next prepared statement
  6887  ** METHOD: sqlite3
  6888  **
  6889  ** ^This interface returns a pointer to the next [prepared statement] after
  6890  ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
  6891  ** then this interface returns a pointer to the first prepared statement
  6892  ** associated with the database connection pDb.  ^If no prepared statement
  6893  ** satisfies the conditions of this routine, it returns NULL.
  6894  **
  6895  ** The [database connection] pointer D in a call to
  6896  ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6897  ** connection and in particular must not be a NULL pointer.
  6898  */
  6899  SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6900  
  6901  /*
  6902  ** CAPI3REF: Commit And Rollback Notification Callbacks
  6903  ** METHOD: sqlite3
  6904  **
  6905  ** ^The sqlite3_commit_hook() interface registers a callback
  6906  ** function to be invoked whenever a transaction is [COMMIT | committed].
  6907  ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6908  ** for the same database connection is overridden.
  6909  ** ^The sqlite3_rollback_hook() interface registers a callback
  6910  ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6911  ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6912  ** for the same database connection is overridden.
  6913  ** ^The pArg argument is passed through to the callback.
  6914  ** ^If the callback on a commit hook function returns non-zero,
  6915  ** then the commit is converted into a rollback.
  6916  **
  6917  ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6918  ** return the P argument from the previous call of the same function
  6919  ** on the same [database connection] D, or NULL for
  6920  ** the first call for each function on D.
  6921  **
  6922  ** The commit and rollback hook callbacks are not reentrant.
  6923  ** The callback implementation must not do anything that will modify
  6924  ** the database connection that invoked the callback.  Any actions
  6925  ** to modify the database connection must be deferred until after the
  6926  ** completion of the [sqlite3_step()] call that triggered the commit
  6927  ** or rollback hook in the first place.
  6928  ** Note that running any other SQL statements, including SELECT statements,
  6929  ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6930  ** the database connections for the meaning of "modify" in this paragraph.
  6931  **
  6932  ** ^Registering a NULL function disables the callback.
  6933  **
  6934  ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6935  ** operation is allowed to continue normally.  ^If the commit hook
  6936  ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6937  ** ^The rollback hook is invoked on a rollback that results from a commit
  6938  ** hook returning non-zero, just as it would be with any other rollback.
  6939  **
  6940  ** ^For the purposes of this API, a transaction is said to have been
  6941  ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6942  ** an error or constraint causes an implicit rollback to occur.
  6943  ** ^The rollback callback is not invoked if a transaction is
  6944  ** automatically rolled back because the database connection is closed.
  6945  **
  6946  ** See also the [sqlite3_update_hook()] interface.
  6947  */
  6948  SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6949  SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6950  
  6951  /*
  6952  ** CAPI3REF: Data Change Notification Callbacks
  6953  ** METHOD: sqlite3
  6954  **
  6955  ** ^The sqlite3_update_hook() interface registers a callback function
  6956  ** with the [database connection] identified by the first argument
  6957  ** to be invoked whenever a row is updated, inserted or deleted in
  6958  ** a [rowid table].
  6959  ** ^Any callback set by a previous call to this function
  6960  ** for the same database connection is overridden.
  6961  **
  6962  ** ^The second argument is a pointer to the function to invoke when a
  6963  ** row is updated, inserted or deleted in a rowid table.
  6964  ** ^The first argument to the callback is a copy of the third argument
  6965  ** to sqlite3_update_hook().
  6966  ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6967  ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6968  ** to be invoked.
  6969  ** ^The third and fourth arguments to the callback contain pointers to the
  6970  ** database and table name containing the affected row.
  6971  ** ^The final callback parameter is the [rowid] of the row.
  6972  ** ^In the case of an update, this is the [rowid] after the update takes place.
  6973  **
  6974  ** ^(The update hook is not invoked when internal system tables are
  6975  ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6976  ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6977  **
  6978  ** ^In the current implementation, the update hook
  6979  ** is not invoked when conflicting rows are deleted because of an
  6980  ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
  6981  ** invoked when rows are deleted using the [truncate optimization].
  6982  ** The exceptions defined in this paragraph might change in a future
  6983  ** release of SQLite.
  6984  **
  6985  ** The update hook implementation must not do anything that will modify
  6986  ** the database connection that invoked the update hook.  Any actions
  6987  ** to modify the database connection must be deferred until after the
  6988  ** completion of the [sqlite3_step()] call that triggered the update hook.
  6989  ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6990  ** database connections for the meaning of "modify" in this paragraph.
  6991  **
  6992  ** ^The sqlite3_update_hook(D,C,P) function
  6993  ** returns the P argument from the previous call
  6994  ** on the same [database connection] D, or NULL for
  6995  ** the first call on D.
  6996  **
  6997  ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6998  ** and [sqlite3_preupdate_hook()] interfaces.
  6999  */
  7000  SQLITE_API void *sqlite3_update_hook(
  7001    sqlite3*, 
  7002    void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  7003    void*
  7004  );
  7005  
  7006  /*
  7007  ** CAPI3REF: Enable Or Disable Shared Pager Cache
  7008  **
  7009  ** ^(This routine enables or disables the sharing of the database cache
  7010  ** and schema data structures between [database connection | connections]
  7011  ** to the same database. Sharing is enabled if the argument is true
  7012  ** and disabled if the argument is false.)^
  7013  **
  7014  ** ^Cache sharing is enabled and disabled for an entire process.
  7015  ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). 
  7016  ** In prior versions of SQLite,
  7017  ** sharing was enabled or disabled for each thread separately.
  7018  **
  7019  ** ^(The cache sharing mode set by this interface effects all subsequent
  7020  ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  7021  ** Existing database connections continue use the sharing mode
  7022  ** that was in effect at the time they were opened.)^
  7023  **
  7024  ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  7025  ** successfully.  An [error code] is returned otherwise.)^
  7026  **
  7027  ** ^Shared cache is disabled by default. But this might change in
  7028  ** future releases of SQLite.  Applications that care about shared
  7029  ** cache setting should set it explicitly.
  7030  **
  7031  ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  7032  ** and will always return SQLITE_MISUSE. On those systems, 
  7033  ** shared cache mode should be enabled per-database connection via 
  7034  ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  7035  **
  7036  ** This interface is threadsafe on processors where writing a
  7037  ** 32-bit integer is atomic.
  7038  **
  7039  ** See Also:  [SQLite Shared-Cache Mode]
  7040  */
  7041  SQLITE_API int sqlite3_enable_shared_cache(int);
  7042  
  7043  /*
  7044  ** CAPI3REF: Attempt To Free Heap Memory
  7045  **
  7046  ** ^The sqlite3_release_memory() interface attempts to free N bytes
  7047  ** of heap memory by deallocating non-essential memory allocations
  7048  ** held by the database library.   Memory used to cache database
  7049  ** pages to improve performance is an example of non-essential memory.
  7050  ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  7051  ** which might be more or less than the amount requested.
  7052  ** ^The sqlite3_release_memory() routine is a no-op returning zero
  7053  ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  7054  **
  7055  ** See also: [sqlite3_db_release_memory()]
  7056  */
  7057  SQLITE_API int sqlite3_release_memory(int);
  7058  
  7059  /*
  7060  ** CAPI3REF: Free Memory Used By A Database Connection
  7061  ** METHOD: sqlite3
  7062  **
  7063  ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  7064  ** memory as possible from database connection D. Unlike the
  7065  ** [sqlite3_release_memory()] interface, this interface is in effect even
  7066  ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  7067  ** omitted.
  7068  **
  7069  ** See also: [sqlite3_release_memory()]
  7070  */
  7071  SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  7072  
  7073  /*
  7074  ** CAPI3REF: Impose A Limit On Heap Size
  7075  **
  7076  ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  7077  ** soft limit on the amount of heap memory that may be allocated by SQLite.
  7078  ** ^SQLite strives to keep heap memory utilization below the soft heap
  7079  ** limit by reducing the number of pages held in the page cache
  7080  ** as heap memory usages approaches the limit.
  7081  ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  7082  ** below the limit, it will exceed the limit rather than generate
  7083  ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
  7084  ** is advisory only.
  7085  **
  7086  ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  7087  ** the soft heap limit prior to the call, or negative in the case of an
  7088  ** error.  ^If the argument N is negative
  7089  ** then no change is made to the soft heap limit.  Hence, the current
  7090  ** size of the soft heap limit can be determined by invoking
  7091  ** sqlite3_soft_heap_limit64() with a negative argument.
  7092  **
  7093  ** ^If the argument N is zero then the soft heap limit is disabled.
  7094  **
  7095  ** ^(The soft heap limit is not enforced in the current implementation
  7096  ** if one or more of following conditions are true:
  7097  **
  7098  ** <ul>
  7099  ** <li> The soft heap limit is set to zero.
  7100  ** <li> Memory accounting is disabled using a combination of the
  7101  **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  7102  **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  7103  ** <li> An alternative page cache implementation is specified using
  7104  **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  7105  ** <li> The page cache allocates from its own memory pool supplied
  7106  **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  7107  **      from the heap.
  7108  ** </ul>)^
  7109  **
  7110  ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), 
  7111  ** the soft heap limit is enforced
  7112  ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  7113  ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  7114  ** the soft heap limit is enforced on every memory allocation.  Without
  7115  ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  7116  ** when memory is allocated by the page cache.  Testing suggests that because
  7117  ** the page cache is the predominate memory user in SQLite, most
  7118  ** applications will achieve adequate soft heap limit enforcement without
  7119  ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  7120  **
  7121  ** The circumstances under which SQLite will enforce the soft heap limit may
  7122  ** changes in future releases of SQLite.
  7123  */
  7124  SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  7125  
  7126  /*
  7127  ** CAPI3REF: Deprecated Soft Heap Limit Interface
  7128  ** DEPRECATED
  7129  **
  7130  ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  7131  ** interface.  This routine is provided for historical compatibility
  7132  ** only.  All new applications should use the
  7133  ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  7134  */
  7135  SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  7136  
  7137  
  7138  /*
  7139  ** CAPI3REF: Extract Metadata About A Column Of A Table
  7140  ** METHOD: sqlite3
  7141  **
  7142  ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  7143  ** information about column C of table T in database D
  7144  ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
  7145  ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  7146  ** the final five arguments with appropriate values if the specified
  7147  ** column exists.  ^The sqlite3_table_column_metadata() interface returns
  7148  ** SQLITE_ERROR and if the specified column does not exist.
  7149  ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  7150  ** NULL pointer, then this routine simply checks for the existence of the
  7151  ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  7152  ** does not.  If the table name parameter T in a call to
  7153  ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  7154  ** undefined behavior.
  7155  **
  7156  ** ^The column is identified by the second, third and fourth parameters to
  7157  ** this function. ^(The second parameter is either the name of the database
  7158  ** (i.e. "main", "temp", or an attached database) containing the specified
  7159  ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  7160  ** for the table using the same algorithm used by the database engine to
  7161  ** resolve unqualified table references.
  7162  **
  7163  ** ^The third and fourth parameters to this function are the table and column
  7164  ** name of the desired column, respectively.
  7165  **
  7166  ** ^Metadata is returned by writing to the memory locations passed as the 5th
  7167  ** and subsequent parameters to this function. ^Any of these arguments may be
  7168  ** NULL, in which case the corresponding element of metadata is omitted.
  7169  **
  7170  ** ^(<blockquote>
  7171  ** <table border="1">
  7172  ** <tr><th> Parameter <th> Output<br>Type <th>  Description
  7173  **
  7174  ** <tr><td> 5th <td> const char* <td> Data type
  7175  ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  7176  ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
  7177  ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
  7178  ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
  7179  ** </table>
  7180  ** </blockquote>)^
  7181  **
  7182  ** ^The memory pointed to by the character pointers returned for the
  7183  ** declaration type and collation sequence is valid until the next
  7184  ** call to any SQLite API function.
  7185  **
  7186  ** ^If the specified table is actually a view, an [error code] is returned.
  7187  **
  7188  ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
  7189  ** is not a [WITHOUT ROWID] table and an
  7190  ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  7191  ** parameters are set for the explicitly declared column. ^(If there is no
  7192  ** [INTEGER PRIMARY KEY] column, then the outputs
  7193  ** for the [rowid] are set as follows:
  7194  **
  7195  ** <pre>
  7196  **     data type: "INTEGER"
  7197  **     collation sequence: "BINARY"
  7198  **     not null: 0
  7199  **     primary key: 1
  7200  **     auto increment: 0
  7201  ** </pre>)^
  7202  **
  7203  ** ^This function causes all database schemas to be read from disk and
  7204  ** parsed, if that has not already been done, and returns an error if
  7205  ** any errors are encountered while loading the schema.
  7206  */
  7207  SQLITE_API int sqlite3_table_column_metadata(
  7208    sqlite3 *db,                /* Connection handle */
  7209    const char *zDbName,        /* Database name or NULL */
  7210    const char *zTableName,     /* Table name */
  7211    const char *zColumnName,    /* Column name */
  7212    char const **pzDataType,    /* OUTPUT: Declared data type */
  7213    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
  7214    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
  7215    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
  7216    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
  7217  );
  7218  
  7219  /*
  7220  ** CAPI3REF: Load An Extension
  7221  ** METHOD: sqlite3
  7222  **
  7223  ** ^This interface loads an SQLite extension library from the named file.
  7224  **
  7225  ** ^The sqlite3_load_extension() interface attempts to load an
  7226  ** [SQLite extension] library contained in the file zFile.  If
  7227  ** the file cannot be loaded directly, attempts are made to load
  7228  ** with various operating-system specific extensions added.
  7229  ** So for example, if "samplelib" cannot be loaded, then names like
  7230  ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  7231  ** be tried also.
  7232  **
  7233  ** ^The entry point is zProc.
  7234  ** ^(zProc may be 0, in which case SQLite will try to come up with an
  7235  ** entry point name on its own.  It first tries "sqlite3_extension_init".
  7236  ** If that does not work, it constructs a name "sqlite3_X_init" where the
  7237  ** X is consists of the lower-case equivalent of all ASCII alphabetic
  7238  ** characters in the filename from the last "/" to the first following
  7239  ** "." and omitting any initial "lib".)^
  7240  ** ^The sqlite3_load_extension() interface returns
  7241  ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  7242  ** ^If an error occurs and pzErrMsg is not 0, then the
  7243  ** [sqlite3_load_extension()] interface shall attempt to
  7244  ** fill *pzErrMsg with error message text stored in memory
  7245  ** obtained from [sqlite3_malloc()]. The calling function
  7246  ** should free this memory by calling [sqlite3_free()].
  7247  **
  7248  ** ^Extension loading must be enabled using
  7249  ** [sqlite3_enable_load_extension()] or
  7250  ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  7251  ** prior to calling this API,
  7252  ** otherwise an error will be returned.
  7253  **
  7254  ** <b>Security warning:</b> It is recommended that the 
  7255  ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  7256  ** interface.  The use of the [sqlite3_enable_load_extension()] interface
  7257  ** should be avoided.  This will keep the SQL function [load_extension()]
  7258  ** disabled and prevent SQL injections from giving attackers
  7259  ** access to extension loading capabilities.
  7260  **
  7261  ** See also the [load_extension() SQL function].
  7262  */
  7263  SQLITE_API int sqlite3_load_extension(
  7264    sqlite3 *db,          /* Load the extension into this database connection */
  7265    const char *zFile,    /* Name of the shared library containing extension */
  7266    const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  7267    char **pzErrMsg       /* Put error message here if not 0 */
  7268  );
  7269  
  7270  /*
  7271  ** CAPI3REF: Enable Or Disable Extension Loading
  7272  ** METHOD: sqlite3
  7273  **
  7274  ** ^So as not to open security holes in older applications that are
  7275  ** unprepared to deal with [extension loading], and as a means of disabling
  7276  ** [extension loading] while evaluating user-entered SQL, the following API
  7277  ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  7278  **
  7279  ** ^Extension loading is off by default.
  7280  ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  7281  ** to turn extension loading on and call it with onoff==0 to turn
  7282  ** it back off again.
  7283  **
  7284  ** ^This interface enables or disables both the C-API
  7285  ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  7286  ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  7287  ** to enable or disable only the C-API.)^
  7288  **
  7289  ** <b>Security warning:</b> It is recommended that extension loading
  7290  ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7291  ** rather than this interface, so the [load_extension()] SQL function
  7292  ** remains disabled. This will prevent SQL injections from giving attackers
  7293  ** access to extension loading capabilities.
  7294  */
  7295  SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7296  
  7297  /*
  7298  ** CAPI3REF: Automatically Load Statically Linked Extensions
  7299  **
  7300  ** ^This interface causes the xEntryPoint() function to be invoked for
  7301  ** each new [database connection] that is created.  The idea here is that
  7302  ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7303  ** that is to be automatically loaded into all new database connections.
  7304  **
  7305  ** ^(Even though the function prototype shows that xEntryPoint() takes
  7306  ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7307  ** arguments and expects an integer result as if the signature of the
  7308  ** entry point where as follows:
  7309  **
  7310  ** <blockquote><pre>
  7311  ** &nbsp;  int xEntryPoint(
  7312  ** &nbsp;    sqlite3 *db,
  7313  ** &nbsp;    const char **pzErrMsg,
  7314  ** &nbsp;    const struct sqlite3_api_routines *pThunk
  7315  ** &nbsp;  );
  7316  ** </pre></blockquote>)^
  7317  **
  7318  ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7319  ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7320  ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
  7321  ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
  7322  ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
  7323  ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7324  ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7325  **
  7326  ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7327  ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7328  ** will be called more than once for each database connection that is opened.
  7329  **
  7330  ** See also: [sqlite3_reset_auto_extension()]
  7331  ** and [sqlite3_cancel_auto_extension()]
  7332  */
  7333  SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7334  
  7335  /*
  7336  ** CAPI3REF: Cancel Automatic Extension Loading
  7337  **
  7338  ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7339  ** initialization routine X that was registered using a prior call to
  7340  ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
  7341  ** routine returns 1 if initialization routine X was successfully 
  7342  ** unregistered and it returns 0 if X was not on the list of initialization
  7343  ** routines.
  7344  */
  7345  SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7346  
  7347  /*
  7348  ** CAPI3REF: Reset Automatic Extension Loading
  7349  **
  7350  ** ^This interface disables all automatic extensions previously
  7351  ** registered using [sqlite3_auto_extension()].
  7352  */
  7353  SQLITE_API void sqlite3_reset_auto_extension(void);
  7354  
  7355  /*
  7356  ** The interface to the virtual-table mechanism is currently considered
  7357  ** to be experimental.  The interface might change in incompatible ways.
  7358  ** If this is a problem for you, do not use the interface at this time.
  7359  **
  7360  ** When the virtual-table mechanism stabilizes, we will declare the
  7361  ** interface fixed, support it indefinitely, and remove this comment.
  7362  */
  7363  
  7364  /*
  7365  ** Structures used by the virtual table interface
  7366  */
  7367  typedef struct sqlite3_vtab sqlite3_vtab;
  7368  typedef struct sqlite3_index_info sqlite3_index_info;
  7369  typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7370  typedef struct sqlite3_module sqlite3_module;
  7371  
  7372  /*
  7373  ** CAPI3REF: Virtual Table Object
  7374  ** KEYWORDS: sqlite3_module {virtual table module}
  7375  **
  7376  ** This structure, sometimes called a "virtual table module", 
  7377  ** defines the implementation of a [virtual tables].  
  7378  ** This structure consists mostly of methods for the module.
  7379  **
  7380  ** ^A virtual table module is created by filling in a persistent
  7381  ** instance of this structure and passing a pointer to that instance
  7382  ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7383  ** ^The registration remains valid until it is replaced by a different
  7384  ** module or until the [database connection] closes.  The content
  7385  ** of this structure must not change while it is registered with
  7386  ** any database connection.
  7387  */
  7388  struct sqlite3_module {
  7389    int iVersion;
  7390    int (*xCreate)(sqlite3*, void *pAux,
  7391                 int argc, const char *const*argv,
  7392                 sqlite3_vtab **ppVTab, char**);
  7393    int (*xConnect)(sqlite3*, void *pAux,
  7394                 int argc, const char *const*argv,
  7395                 sqlite3_vtab **ppVTab, char**);
  7396    int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7397    int (*xDisconnect)(sqlite3_vtab *pVTab);
  7398    int (*xDestroy)(sqlite3_vtab *pVTab);
  7399    int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7400    int (*xClose)(sqlite3_vtab_cursor*);
  7401    int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7402                  int argc, sqlite3_value **argv);
  7403    int (*xNext)(sqlite3_vtab_cursor*);
  7404    int (*xEof)(sqlite3_vtab_cursor*);
  7405    int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7406    int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7407    int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7408    int (*xBegin)(sqlite3_vtab *pVTab);
  7409    int (*xSync)(sqlite3_vtab *pVTab);
  7410    int (*xCommit)(sqlite3_vtab *pVTab);
  7411    int (*xRollback)(sqlite3_vtab *pVTab);
  7412    int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7413                         void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7414                         void **ppArg);
  7415    int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7416    /* The methods above are in version 1 of the sqlite_module object. Those 
  7417    ** below are for version 2 and greater. */
  7418    int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7419    int (*xRelease)(sqlite3_vtab *pVTab, int);
  7420    int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7421    /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7422    ** Those below are for version 3 and greater. */
  7423    int (*xShadowName)(const char*);
  7424  };
  7425  
  7426  /*
  7427  ** CAPI3REF: Virtual Table Indexing Information
  7428  ** KEYWORDS: sqlite3_index_info
  7429  **
  7430  ** The sqlite3_index_info structure and its substructures is used as part
  7431  ** of the [virtual table] interface to
  7432  ** pass information into and receive the reply from the [xBestIndex]
  7433  ** method of a [virtual table module].  The fields under **Inputs** are the
  7434  ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
  7435  ** results into the **Outputs** fields.
  7436  **
  7437  ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7438  **
  7439  ** <blockquote>column OP expr</blockquote>
  7440  **
  7441  ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
  7442  ** stored in aConstraint[].op using one of the
  7443  ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7444  ** ^(The index of the column is stored in
  7445  ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
  7446  ** expr on the right-hand side can be evaluated (and thus the constraint
  7447  ** is usable) and false if it cannot.)^
  7448  **
  7449  ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7450  ** and makes other simplifications to the WHERE clause in an attempt to
  7451  ** get as many WHERE clause terms into the form shown above as possible.
  7452  ** ^The aConstraint[] array only reports WHERE clause terms that are
  7453  ** relevant to the particular virtual table being queried.
  7454  **
  7455  ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7456  ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7457  **
  7458  ** The colUsed field indicates which columns of the virtual table may be
  7459  ** required by the current scan. Virtual table columns are numbered from
  7460  ** zero in the order in which they appear within the CREATE TABLE statement
  7461  ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7462  ** the corresponding bit is set within the colUsed mask if the column may be
  7463  ** required by SQLite. If the table has at least 64 columns and any column
  7464  ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7465  ** set. In other words, column iCol may be required if the expression
  7466  ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to 
  7467  ** non-zero.
  7468  **
  7469  ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7470  ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
  7471  ** the right-hand side of the corresponding aConstraint[] is evaluated
  7472  ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
  7473  ** is true, then the constraint is assumed to be fully handled by the
  7474  ** virtual table and is not checked again by SQLite.)^
  7475  **
  7476  ** ^The idxNum and idxPtr values are recorded and passed into the
  7477  ** [xFilter] method.
  7478  ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7479  ** needToFreeIdxPtr is true.
  7480  **
  7481  ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7482  ** the correct order to satisfy the ORDER BY clause so that no separate
  7483  ** sorting step is required.
  7484  **
  7485  ** ^The estimatedCost value is an estimate of the cost of a particular
  7486  ** strategy. A cost of N indicates that the cost of the strategy is similar
  7487  ** to a linear scan of an SQLite table with N rows. A cost of log(N) 
  7488  ** indicates that the expense of the operation is similar to that of a
  7489  ** binary search on a unique indexed field of an SQLite table with N rows.
  7490  **
  7491  ** ^The estimatedRows value is an estimate of the number of rows that
  7492  ** will be returned by the strategy.
  7493  **
  7494  ** The xBestIndex method may optionally populate the idxFlags field with a 
  7495  ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7496  ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7497  ** assumes that the strategy may visit at most one row. 
  7498  **
  7499  ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7500  ** SQLite also assumes that if a call to the xUpdate() method is made as
  7501  ** part of the same statement to delete or update a virtual table row and the
  7502  ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7503  ** any database changes. In other words, if the xUpdate() returns
  7504  ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7505  ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7506  ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7507  ** the xUpdate method are automatically rolled back by SQLite.
  7508  **
  7509  ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7510  ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). 
  7511  ** If a virtual table extension is
  7512  ** used with an SQLite version earlier than 3.8.2, the results of attempting 
  7513  ** to read or write the estimatedRows field are undefined (but are likely 
  7514  ** to included crashing the application). The estimatedRows field should
  7515  ** therefore only be used if [sqlite3_libversion_number()] returns a
  7516  ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7517  ** was added for [version 3.9.0] ([dateof:3.9.0]). 
  7518  ** It may therefore only be used if
  7519  ** sqlite3_libversion_number() returns a value greater than or equal to
  7520  ** 3009000.
  7521  */
  7522  struct sqlite3_index_info {
  7523    /* Inputs */
  7524    int nConstraint;           /* Number of entries in aConstraint */
  7525    struct sqlite3_index_constraint {
  7526       int iColumn;              /* Column constrained.  -1 for ROWID */
  7527       unsigned char op;         /* Constraint operator */
  7528       unsigned char usable;     /* True if this constraint is usable */
  7529       int iTermOffset;          /* Used internally - xBestIndex should ignore */
  7530    } *aConstraint;            /* Table of WHERE clause constraints */
  7531    int nOrderBy;              /* Number of terms in the ORDER BY clause */
  7532    struct sqlite3_index_orderby {
  7533       int iColumn;              /* Column number */
  7534       unsigned char desc;       /* True for DESC.  False for ASC. */
  7535    } *aOrderBy;               /* The ORDER BY clause */
  7536    /* Outputs */
  7537    struct sqlite3_index_constraint_usage {
  7538      int argvIndex;           /* if >0, constraint is part of argv to xFilter */
  7539      unsigned char omit;      /* Do not code a test for this constraint */
  7540    } *aConstraintUsage;
  7541    int idxNum;                /* Number used to identify the index */
  7542    char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
  7543    int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
  7544    int orderByConsumed;       /* True if output is already ordered */
  7545    double estimatedCost;           /* Estimated cost of using this index */
  7546    /* Fields below are only available in SQLite 3.8.2 and later */
  7547    sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
  7548    /* Fields below are only available in SQLite 3.9.0 and later */
  7549    int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
  7550    /* Fields below are only available in SQLite 3.10.0 and later */
  7551    sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
  7552  };
  7553  
  7554  /*
  7555  ** CAPI3REF: Virtual Table Scan Flags
  7556  **
  7557  ** Virtual table implementations are allowed to set the 
  7558  ** [sqlite3_index_info].idxFlags field to some combination of
  7559  ** these bits.
  7560  */
  7561  #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
  7562  
  7563  /*
  7564  ** CAPI3REF: Virtual Table Constraint Operator Codes
  7565  **
  7566  ** These macros defined the allowed values for the
  7567  ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
  7568  ** an operator that is part of a constraint term in the wHERE clause of
  7569  ** a query that uses a [virtual table].
  7570  */
  7571  #define SQLITE_INDEX_CONSTRAINT_EQ         2
  7572  #define SQLITE_INDEX_CONSTRAINT_GT         4
  7573  #define SQLITE_INDEX_CONSTRAINT_LE         8
  7574  #define SQLITE_INDEX_CONSTRAINT_LT        16
  7575  #define SQLITE_INDEX_CONSTRAINT_GE        32
  7576  #define SQLITE_INDEX_CONSTRAINT_MATCH     64
  7577  #define SQLITE_INDEX_CONSTRAINT_LIKE      65
  7578  #define SQLITE_INDEX_CONSTRAINT_GLOB      66
  7579  #define SQLITE_INDEX_CONSTRAINT_REGEXP    67
  7580  #define SQLITE_INDEX_CONSTRAINT_NE        68
  7581  #define SQLITE_INDEX_CONSTRAINT_ISNOT     69
  7582  #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7583  #define SQLITE_INDEX_CONSTRAINT_ISNULL    71
  7584  #define SQLITE_INDEX_CONSTRAINT_IS        72
  7585  #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
  7586  
  7587  /*
  7588  ** CAPI3REF: Register A Virtual Table Implementation
  7589  ** METHOD: sqlite3
  7590  **
  7591  ** ^These routines are used to register a new [virtual table module] name.
  7592  ** ^Module names must be registered before
  7593  ** creating a new [virtual table] using the module and before using a
  7594  ** preexisting [virtual table] for the module.
  7595  **
  7596  ** ^The module name is registered on the [database connection] specified
  7597  ** by the first parameter.  ^The name of the module is given by the 
  7598  ** second parameter.  ^The third parameter is a pointer to
  7599  ** the implementation of the [virtual table module].   ^The fourth
  7600  ** parameter is an arbitrary client data pointer that is passed through
  7601  ** into the [xCreate] and [xConnect] methods of the virtual table module
  7602  ** when a new virtual table is be being created or reinitialized.
  7603  **
  7604  ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7605  ** is a pointer to a destructor for the pClientData.  ^SQLite will
  7606  ** invoke the destructor function (if it is not NULL) when SQLite
  7607  ** no longer needs the pClientData pointer.  ^The destructor will also
  7608  ** be invoked if the call to sqlite3_create_module_v2() fails.
  7609  ** ^The sqlite3_create_module()
  7610  ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7611  ** destructor.
  7612  */
  7613  SQLITE_API int sqlite3_create_module(
  7614    sqlite3 *db,               /* SQLite connection to register module with */
  7615    const char *zName,         /* Name of the module */
  7616    const sqlite3_module *p,   /* Methods for the module */
  7617    void *pClientData          /* Client data for xCreate/xConnect */
  7618  );
  7619  SQLITE_API int sqlite3_create_module_v2(
  7620    sqlite3 *db,               /* SQLite connection to register module with */
  7621    const char *zName,         /* Name of the module */
  7622    const sqlite3_module *p,   /* Methods for the module */
  7623    void *pClientData,         /* Client data for xCreate/xConnect */
  7624    void(*xDestroy)(void*)     /* Module destructor function */
  7625  );
  7626  
  7627  /*
  7628  ** CAPI3REF: Virtual Table Instance Object
  7629  ** KEYWORDS: sqlite3_vtab
  7630  **
  7631  ** Every [virtual table module] implementation uses a subclass
  7632  ** of this object to describe a particular instance
  7633  ** of the [virtual table].  Each subclass will
  7634  ** be tailored to the specific needs of the module implementation.
  7635  ** The purpose of this superclass is to define certain fields that are
  7636  ** common to all module implementations.
  7637  **
  7638  ** ^Virtual tables methods can set an error message by assigning a
  7639  ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
  7640  ** take care that any prior string is freed by a call to [sqlite3_free()]
  7641  ** prior to assigning a new string to zErrMsg.  ^After the error message
  7642  ** is delivered up to the client application, the string will be automatically
  7643  ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7644  */
  7645  struct sqlite3_vtab {
  7646    const sqlite3_module *pModule;  /* The module for this virtual table */
  7647    int nRef;                       /* Number of open cursors */
  7648    char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
  7649    /* Virtual table implementations will typically add additional fields */
  7650  };
  7651  
  7652  /*
  7653  ** CAPI3REF: Virtual Table Cursor Object
  7654  ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7655  **
  7656  ** Every [virtual table module] implementation uses a subclass of the
  7657  ** following structure to describe cursors that point into the
  7658  ** [virtual table] and are used
  7659  ** to loop through the virtual table.  Cursors are created using the
  7660  ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7661  ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
  7662  ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7663  ** of the module.  Each module implementation will define
  7664  ** the content of a cursor structure to suit its own needs.
  7665  **
  7666  ** This superclass exists in order to define fields of the cursor that
  7667  ** are common to all implementations.
  7668  */
  7669  struct sqlite3_vtab_cursor {
  7670    sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
  7671    /* Virtual table implementations will typically add additional fields */
  7672  };
  7673  
  7674  /*
  7675  ** CAPI3REF: Declare The Schema Of A Virtual Table
  7676  **
  7677  ** ^The [xCreate] and [xConnect] methods of a
  7678  ** [virtual table module] call this interface
  7679  ** to declare the format (the names and datatypes of the columns) of
  7680  ** the virtual tables they implement.
  7681  */
  7682  SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7683  
  7684  /*
  7685  ** CAPI3REF: Overload A Function For A Virtual Table
  7686  ** METHOD: sqlite3
  7687  **
  7688  ** ^(Virtual tables can provide alternative implementations of functions
  7689  ** using the [xFindFunction] method of the [virtual table module].  
  7690  ** But global versions of those functions
  7691  ** must exist in order to be overloaded.)^
  7692  **
  7693  ** ^(This API makes sure a global version of a function with a particular
  7694  ** name and number of parameters exists.  If no such function exists
  7695  ** before this API is called, a new function is created.)^  ^The implementation
  7696  ** of the new function always causes an exception to be thrown.  So
  7697  ** the new function is not good for anything by itself.  Its only
  7698  ** purpose is to be a placeholder function that can be overloaded
  7699  ** by a [virtual table].
  7700  */
  7701  SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7702  
  7703  /*
  7704  ** The interface to the virtual-table mechanism defined above (back up
  7705  ** to a comment remarkably similar to this one) is currently considered
  7706  ** to be experimental.  The interface might change in incompatible ways.
  7707  ** If this is a problem for you, do not use the interface at this time.
  7708  **
  7709  ** When the virtual-table mechanism stabilizes, we will declare the
  7710  ** interface fixed, support it indefinitely, and remove this comment.
  7711  */
  7712  
  7713  /*
  7714  ** CAPI3REF: A Handle To An Open BLOB
  7715  ** KEYWORDS: {BLOB handle} {BLOB handles}
  7716  **
  7717  ** An instance of this object represents an open BLOB on which
  7718  ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7719  ** ^Objects of this type are created by [sqlite3_blob_open()]
  7720  ** and destroyed by [sqlite3_blob_close()].
  7721  ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7722  ** can be used to read or write small subsections of the BLOB.
  7723  ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7724  */
  7725  typedef struct sqlite3_blob sqlite3_blob;
  7726  
  7727  /*
  7728  ** CAPI3REF: Open A BLOB For Incremental I/O
  7729  ** METHOD: sqlite3
  7730  ** CONSTRUCTOR: sqlite3_blob
  7731  **
  7732  ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7733  ** in row iRow, column zColumn, table zTable in database zDb;
  7734  ** in other words, the same BLOB that would be selected by:
  7735  **
  7736  ** <pre>
  7737  **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7738  ** </pre>)^
  7739  **
  7740  ** ^(Parameter zDb is not the filename that contains the database, but 
  7741  ** rather the symbolic name of the database. For attached databases, this is
  7742  ** the name that appears after the AS keyword in the [ATTACH] statement.
  7743  ** For the main database file, the database name is "main". For TEMP
  7744  ** tables, the database name is "temp".)^
  7745  **
  7746  ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7747  ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7748  ** read-only access.
  7749  **
  7750  ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7751  ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7752  ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7753  ** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
  7754  ** on *ppBlob after this function it returns.
  7755  **
  7756  ** This function fails with SQLITE_ERROR if any of the following are true:
  7757  ** <ul>
  7758  **   <li> ^(Database zDb does not exist)^, 
  7759  **   <li> ^(Table zTable does not exist within database zDb)^, 
  7760  **   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
  7761  **   <li> ^(Column zColumn does not exist)^,
  7762  **   <li> ^(Row iRow is not present in the table)^,
  7763  **   <li> ^(The specified column of row iRow contains a value that is not
  7764  **         a TEXT or BLOB value)^,
  7765  **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
  7766  **         constraint and the blob is being opened for read/write access)^,
  7767  **   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
  7768  **         column zColumn is part of a [child key] definition and the blob is
  7769  **         being opened for read/write access)^.
  7770  ** </ul>
  7771  **
  7772  ** ^Unless it returns SQLITE_MISUSE, this function sets the 
  7773  ** [database connection] error code and message accessible via 
  7774  ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
  7775  **
  7776  ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7777  ** [sqlite3_blob_read()] interface and modified by using
  7778  ** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
  7779  ** different row of the same table using the [sqlite3_blob_reopen()]
  7780  ** interface.  However, the column, table, or database of a [BLOB handle]
  7781  ** cannot be changed after the [BLOB handle] is opened.
  7782  **
  7783  ** ^(If the row that a BLOB handle points to is modified by an
  7784  ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7785  ** then the BLOB handle is marked as "expired".
  7786  ** This is true if any column of the row is changed, even a column
  7787  ** other than the one the BLOB handle is open on.)^
  7788  ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7789  ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7790  ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7791  ** rolled back by the expiration of the BLOB.  Such changes will eventually
  7792  ** commit if the transaction continues to completion.)^
  7793  **
  7794  ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7795  ** the opened blob.  ^The size of a blob may not be changed by this
  7796  ** interface.  Use the [UPDATE] SQL command to change the size of a
  7797  ** blob.
  7798  **
  7799  ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7800  ** and the built-in [zeroblob] SQL function may be used to create a 
  7801  ** zero-filled blob to read or write using the incremental-blob interface.
  7802  **
  7803  ** To avoid a resource leak, every open [BLOB handle] should eventually
  7804  ** be released by a call to [sqlite3_blob_close()].
  7805  **
  7806  ** See also: [sqlite3_blob_close()],
  7807  ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7808  ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7809  */
  7810  SQLITE_API int sqlite3_blob_open(
  7811    sqlite3*,
  7812    const char *zDb,
  7813    const char *zTable,
  7814    const char *zColumn,
  7815    sqlite3_int64 iRow,
  7816    int flags,
  7817    sqlite3_blob **ppBlob
  7818  );
  7819  
  7820  /*
  7821  ** CAPI3REF: Move a BLOB Handle to a New Row
  7822  ** METHOD: sqlite3_blob
  7823  **
  7824  ** ^This function is used to move an existing [BLOB handle] so that it points
  7825  ** to a different row of the same database table. ^The new row is identified
  7826  ** by the rowid value passed as the second argument. Only the row can be
  7827  ** changed. ^The database, table and column on which the blob handle is open
  7828  ** remain the same. Moving an existing [BLOB handle] to a new row is
  7829  ** faster than closing the existing handle and opening a new one.
  7830  **
  7831  ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7832  ** it must exist and there must be either a blob or text value stored in
  7833  ** the nominated column.)^ ^If the new row is not present in the table, or if
  7834  ** it does not contain a blob or text value, or if another error occurs, an
  7835  ** SQLite error code is returned and the blob handle is considered aborted.
  7836  ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7837  ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7838  ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7839  ** always returns zero.
  7840  **
  7841  ** ^This function sets the database handle error code and message.
  7842  */
  7843  SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7844  
  7845  /*
  7846  ** CAPI3REF: Close A BLOB Handle
  7847  ** DESTRUCTOR: sqlite3_blob
  7848  **
  7849  ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7850  ** unconditionally.  Even if this routine returns an error code, the 
  7851  ** handle is still closed.)^
  7852  **
  7853  ** ^If the blob handle being closed was opened for read-write access, and if
  7854  ** the database is in auto-commit mode and there are no other open read-write
  7855  ** blob handles or active write statements, the current transaction is
  7856  ** committed. ^If an error occurs while committing the transaction, an error
  7857  ** code is returned and the transaction rolled back.
  7858  **
  7859  ** Calling this function with an argument that is not a NULL pointer or an
  7860  ** open blob handle results in undefined behaviour. ^Calling this routine 
  7861  ** with a null pointer (such as would be returned by a failed call to 
  7862  ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7863  ** is passed a valid open blob handle, the values returned by the 
  7864  ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7865  */
  7866  SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7867  
  7868  /*
  7869  ** CAPI3REF: Return The Size Of An Open BLOB
  7870  ** METHOD: sqlite3_blob
  7871  **
  7872  ** ^Returns the size in bytes of the BLOB accessible via the 
  7873  ** successfully opened [BLOB handle] in its only argument.  ^The
  7874  ** incremental blob I/O routines can only read or overwriting existing
  7875  ** blob content; they cannot change the size of a blob.
  7876  **
  7877  ** This routine only works on a [BLOB handle] which has been created
  7878  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7879  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7880  ** to this routine results in undefined and probably undesirable behavior.
  7881  */
  7882  SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7883  
  7884  /*
  7885  ** CAPI3REF: Read Data From A BLOB Incrementally
  7886  ** METHOD: sqlite3_blob
  7887  **
  7888  ** ^(This function is used to read data from an open [BLOB handle] into a
  7889  ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7890  ** from the open BLOB, starting at offset iOffset.)^
  7891  **
  7892  ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7893  ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
  7894  ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7895  ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7896  ** can be determined using the [sqlite3_blob_bytes()] interface.
  7897  **
  7898  ** ^An attempt to read from an expired [BLOB handle] fails with an
  7899  ** error code of [SQLITE_ABORT].
  7900  **
  7901  ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7902  ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7903  **
  7904  ** This routine only works on a [BLOB handle] which has been created
  7905  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7906  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7907  ** to this routine results in undefined and probably undesirable behavior.
  7908  **
  7909  ** See also: [sqlite3_blob_write()].
  7910  */
  7911  SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7912  
  7913  /*
  7914  ** CAPI3REF: Write Data Into A BLOB Incrementally
  7915  ** METHOD: sqlite3_blob
  7916  **
  7917  ** ^(This function is used to write data into an open [BLOB handle] from a
  7918  ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7919  ** into the open BLOB, starting at offset iOffset.)^
  7920  **
  7921  ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7922  ** Otherwise, an  [error code] or an [extended error code] is returned.)^
  7923  ** ^Unless SQLITE_MISUSE is returned, this function sets the 
  7924  ** [database connection] error code and message accessible via 
  7925  ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
  7926  **
  7927  ** ^If the [BLOB handle] passed as the first argument was not opened for
  7928  ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7929  ** this function returns [SQLITE_READONLY].
  7930  **
  7931  ** This function may only modify the contents of the BLOB; it is
  7932  ** not possible to increase the size of a BLOB using this API.
  7933  ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7934  ** [SQLITE_ERROR] is returned and no data is written. The size of the 
  7935  ** BLOB (and hence the maximum value of N+iOffset) can be determined 
  7936  ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
  7937  ** than zero [SQLITE_ERROR] is returned and no data is written.
  7938  **
  7939  ** ^An attempt to write to an expired [BLOB handle] fails with an
  7940  ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
  7941  ** before the [BLOB handle] expired are not rolled back by the
  7942  ** expiration of the handle, though of course those changes might
  7943  ** have been overwritten by the statement that expired the BLOB handle
  7944  ** or by other independent statements.
  7945  **
  7946  ** This routine only works on a [BLOB handle] which has been created
  7947  ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7948  ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
  7949  ** to this routine results in undefined and probably undesirable behavior.
  7950  **
  7951  ** See also: [sqlite3_blob_read()].
  7952  */
  7953  SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7954  
  7955  /*
  7956  ** CAPI3REF: Virtual File System Objects
  7957  **
  7958  ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7959  ** that SQLite uses to interact
  7960  ** with the underlying operating system.  Most SQLite builds come with a
  7961  ** single default VFS that is appropriate for the host computer.
  7962  ** New VFSes can be registered and existing VFSes can be unregistered.
  7963  ** The following interfaces are provided.
  7964  **
  7965  ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7966  ** ^Names are case sensitive.
  7967  ** ^Names are zero-terminated UTF-8 strings.
  7968  ** ^If there is no match, a NULL pointer is returned.
  7969  ** ^If zVfsName is NULL then the default VFS is returned.
  7970  **
  7971  ** ^New VFSes are registered with sqlite3_vfs_register().
  7972  ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7973  ** ^The same VFS can be registered multiple times without injury.
  7974  ** ^To make an existing VFS into the default VFS, register it again
  7975  ** with the makeDflt flag set.  If two different VFSes with the
  7976  ** same name are registered, the behavior is undefined.  If a
  7977  ** VFS is registered with a name that is NULL or an empty string,
  7978  ** then the behavior is undefined.
  7979  **
  7980  ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7981  ** ^(If the default VFS is unregistered, another VFS is chosen as
  7982  ** the default.  The choice for the new VFS is arbitrary.)^
  7983  */
  7984  SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7985  SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7986  SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7987  
  7988  /*
  7989  ** CAPI3REF: Mutexes
  7990  **
  7991  ** The SQLite core uses these routines for thread
  7992  ** synchronization. Though they are intended for internal
  7993  ** use by SQLite, code that links against SQLite is
  7994  ** permitted to use any of these routines.
  7995  **
  7996  ** The SQLite source code contains multiple implementations
  7997  ** of these mutex routines.  An appropriate implementation
  7998  ** is selected automatically at compile-time.  The following
  7999  ** implementations are available in the SQLite core:
  8000  **
  8001  ** <ul>
  8002  ** <li>   SQLITE_MUTEX_PTHREADS
  8003  ** <li>   SQLITE_MUTEX_W32
  8004  ** <li>   SQLITE_MUTEX_NOOP
  8005  ** </ul>
  8006  **
  8007  ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  8008  ** that does no real locking and is appropriate for use in
  8009  ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
  8010  ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  8011  ** and Windows.
  8012  **
  8013  ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  8014  ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  8015  ** implementation is included with the library. In this case the
  8016  ** application must supply a custom mutex implementation using the
  8017  ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  8018  ** before calling sqlite3_initialize() or any other public sqlite3_
  8019  ** function that calls sqlite3_initialize().
  8020  **
  8021  ** ^The sqlite3_mutex_alloc() routine allocates a new
  8022  ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  8023  ** routine returns NULL if it is unable to allocate the requested
  8024  ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
  8025  ** integer constants:
  8026  **
  8027  ** <ul>
  8028  ** <li>  SQLITE_MUTEX_FAST
  8029  ** <li>  SQLITE_MUTEX_RECURSIVE
  8030  ** <li>  SQLITE_MUTEX_STATIC_MASTER
  8031  ** <li>  SQLITE_MUTEX_STATIC_MEM
  8032  ** <li>  SQLITE_MUTEX_STATIC_OPEN
  8033  ** <li>  SQLITE_MUTEX_STATIC_PRNG
  8034  ** <li>  SQLITE_MUTEX_STATIC_LRU
  8035  ** <li>  SQLITE_MUTEX_STATIC_PMEM
  8036  ** <li>  SQLITE_MUTEX_STATIC_APP1
  8037  ** <li>  SQLITE_MUTEX_STATIC_APP2
  8038  ** <li>  SQLITE_MUTEX_STATIC_APP3
  8039  ** <li>  SQLITE_MUTEX_STATIC_VFS1
  8040  ** <li>  SQLITE_MUTEX_STATIC_VFS2
  8041  ** <li>  SQLITE_MUTEX_STATIC_VFS3
  8042  ** </ul>
  8043  **
  8044  ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  8045  ** cause sqlite3_mutex_alloc() to create
  8046  ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  8047  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  8048  ** The mutex implementation does not need to make a distinction
  8049  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  8050  ** not want to.  SQLite will only request a recursive mutex in
  8051  ** cases where it really needs one.  If a faster non-recursive mutex
  8052  ** implementation is available on the host platform, the mutex subsystem
  8053  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  8054  **
  8055  ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  8056  ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  8057  ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
  8058  ** used by the current version of SQLite.  Future versions of SQLite
  8059  ** may add additional static mutexes.  Static mutexes are for internal
  8060  ** use by SQLite only.  Applications that use SQLite mutexes should
  8061  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  8062  ** SQLITE_MUTEX_RECURSIVE.
  8063  **
  8064  ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  8065  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  8066  ** returns a different mutex on every call.  ^For the static
  8067  ** mutex types, the same mutex is returned on every call that has
  8068  ** the same type number.
  8069  **
  8070  ** ^The sqlite3_mutex_free() routine deallocates a previously
  8071  ** allocated dynamic mutex.  Attempting to deallocate a static
  8072  ** mutex results in undefined behavior.
  8073  **
  8074  ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  8075  ** to enter a mutex.  ^If another thread is already within the mutex,
  8076  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  8077  ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  8078  ** upon successful entry.  ^(Mutexes created using
  8079  ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  8080  ** In such cases, the
  8081  ** mutex must be exited an equal number of times before another thread
  8082  ** can enter.)^  If the same thread tries to enter any mutex other
  8083  ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  8084  **
  8085  ** ^(Some systems (for example, Windows 95) do not support the operation
  8086  ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
  8087  ** will always return SQLITE_BUSY. The SQLite core only ever uses
  8088  ** sqlite3_mutex_try() as an optimization so this is acceptable 
  8089  ** behavior.)^
  8090  **
  8091  ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  8092  ** previously entered by the same thread.   The behavior
  8093  ** is undefined if the mutex is not currently entered by the
  8094  ** calling thread or is not currently allocated.
  8095  **
  8096  ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  8097  ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  8098  ** behave as no-ops.
  8099  **
  8100  ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  8101  */
  8102  SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  8103  SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  8104  SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  8105  SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  8106  SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  8107  
  8108  /*
  8109  ** CAPI3REF: Mutex Methods Object
  8110  **
  8111  ** An instance of this structure defines the low-level routines
  8112  ** used to allocate and use mutexes.
  8113  **
  8114  ** Usually, the default mutex implementations provided by SQLite are
  8115  ** sufficient, however the application has the option of substituting a custom
  8116  ** implementation for specialized deployments or systems for which SQLite
  8117  ** does not provide a suitable implementation. In this case, the application
  8118  ** creates and populates an instance of this structure to pass
  8119  ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  8120  ** Additionally, an instance of this structure can be used as an
  8121  ** output variable when querying the system for the current mutex
  8122  ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  8123  **
  8124  ** ^The xMutexInit method defined by this structure is invoked as
  8125  ** part of system initialization by the sqlite3_initialize() function.
  8126  ** ^The xMutexInit routine is called by SQLite exactly once for each
  8127  ** effective call to [sqlite3_initialize()].
  8128  **
  8129  ** ^The xMutexEnd method defined by this structure is invoked as
  8130  ** part of system shutdown by the sqlite3_shutdown() function. The
  8131  ** implementation of this method is expected to release all outstanding
  8132  ** resources obtained by the mutex methods implementation, especially
  8133  ** those obtained by the xMutexInit method.  ^The xMutexEnd()
  8134  ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  8135  **
  8136  ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  8137  ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  8138  ** xMutexNotheld) implement the following interfaces (respectively):
  8139  **
  8140  ** <ul>
  8141  **   <li>  [sqlite3_mutex_alloc()] </li>
  8142  **   <li>  [sqlite3_mutex_free()] </li>
  8143  **   <li>  [sqlite3_mutex_enter()] </li>
  8144  **   <li>  [sqlite3_mutex_try()] </li>
  8145  **   <li>  [sqlite3_mutex_leave()] </li>
  8146  **   <li>  [sqlite3_mutex_held()] </li>
  8147  **   <li>  [sqlite3_mutex_notheld()] </li>
  8148  ** </ul>)^
  8149  **
  8150  ** The only difference is that the public sqlite3_XXX functions enumerated
  8151  ** above silently ignore any invocations that pass a NULL pointer instead
  8152  ** of a valid mutex handle. The implementations of the methods defined
  8153  ** by this structure are not required to handle this case, the results
  8154  ** of passing a NULL pointer instead of a valid mutex handle are undefined
  8155  ** (i.e. it is acceptable to provide an implementation that segfaults if
  8156  ** it is passed a NULL pointer).
  8157  **
  8158  ** The xMutexInit() method must be threadsafe.  It must be harmless to
  8159  ** invoke xMutexInit() multiple times within the same process and without
  8160  ** intervening calls to xMutexEnd().  Second and subsequent calls to
  8161  ** xMutexInit() must be no-ops.
  8162  **
  8163  ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  8164  ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
  8165  ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
  8166  ** memory allocation for a fast or recursive mutex.
  8167  **
  8168  ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  8169  ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  8170  ** If xMutexInit fails in any way, it is expected to clean up after itself
  8171  ** prior to returning.
  8172  */
  8173  typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  8174  struct sqlite3_mutex_methods {
  8175    int (*xMutexInit)(void);
  8176    int (*xMutexEnd)(void);
  8177    sqlite3_mutex *(*xMutexAlloc)(int);
  8178    void (*xMutexFree)(sqlite3_mutex *);
  8179    void (*xMutexEnter)(sqlite3_mutex *);
  8180    int (*xMutexTry)(sqlite3_mutex *);
  8181    void (*xMutexLeave)(sqlite3_mutex *);
  8182    int (*xMutexHeld)(sqlite3_mutex *);
  8183    int (*xMutexNotheld)(sqlite3_mutex *);
  8184  };
  8185  
  8186  /*
  8187  ** CAPI3REF: Mutex Verification Routines
  8188  **
  8189  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  8190  ** are intended for use inside assert() statements.  The SQLite core
  8191  ** never uses these routines except inside an assert() and applications
  8192  ** are advised to follow the lead of the core.  The SQLite core only
  8193  ** provides implementations for these routines when it is compiled
  8194  ** with the SQLITE_DEBUG flag.  External mutex implementations
  8195  ** are only required to provide these routines if SQLITE_DEBUG is
  8196  ** defined and if NDEBUG is not defined.
  8197  **
  8198  ** These routines should return true if the mutex in their argument
  8199  ** is held or not held, respectively, by the calling thread.
  8200  **
  8201  ** The implementation is not required to provide versions of these
  8202  ** routines that actually work. If the implementation does not provide working
  8203  ** versions of these routines, it should at least provide stubs that always
  8204  ** return true so that one does not get spurious assertion failures.
  8205  **
  8206  ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  8207  ** the routine should return 1.   This seems counter-intuitive since
  8208  ** clearly the mutex cannot be held if it does not exist.  But
  8209  ** the reason the mutex does not exist is because the build is not
  8210  ** using mutexes.  And we do not want the assert() containing the
  8211  ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  8212  ** the appropriate thing to do.  The sqlite3_mutex_notheld()
  8213  ** interface should also return 1 when given a NULL pointer.
  8214  */
  8215  #ifndef NDEBUG
  8216  SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  8217  SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  8218  #endif
  8219  
  8220  /*
  8221  ** CAPI3REF: Mutex Types
  8222  **
  8223  ** The [sqlite3_mutex_alloc()] interface takes a single argument
  8224  ** which is one of these integer constants.
  8225  **
  8226  ** The set of static mutexes may change from one SQLite release to the
  8227  ** next.  Applications that override the built-in mutex logic must be
  8228  ** prepared to accommodate additional static mutexes.
  8229  */
  8230  #define SQLITE_MUTEX_FAST             0
  8231  #define SQLITE_MUTEX_RECURSIVE        1
  8232  #define SQLITE_MUTEX_STATIC_MASTER    2
  8233  #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
  8234  #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
  8235  #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
  8236  #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
  8237  #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
  8238  #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
  8239  #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
  8240  #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
  8241  #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
  8242  #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
  8243  #define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
  8244  #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
  8245  #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
  8246  
  8247  /*
  8248  ** CAPI3REF: Retrieve the mutex for a database connection
  8249  ** METHOD: sqlite3
  8250  **
  8251  ** ^This interface returns a pointer the [sqlite3_mutex] object that 
  8252  ** serializes access to the [database connection] given in the argument
  8253  ** when the [threading mode] is Serialized.
  8254  ** ^If the [threading mode] is Single-thread or Multi-thread then this
  8255  ** routine returns a NULL pointer.
  8256  */
  8257  SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  8258  
  8259  /*
  8260  ** CAPI3REF: Low-Level Control Of Database Files
  8261  ** METHOD: sqlite3
  8262  ** KEYWORDS: {file control}
  8263  **
  8264  ** ^The [sqlite3_file_control()] interface makes a direct call to the
  8265  ** xFileControl method for the [sqlite3_io_methods] object associated
  8266  ** with a particular database identified by the second argument. ^The
  8267  ** name of the database is "main" for the main database or "temp" for the
  8268  ** TEMP database, or the name that appears after the AS keyword for
  8269  ** databases that are added using the [ATTACH] SQL command.
  8270  ** ^A NULL pointer can be used in place of "main" to refer to the
  8271  ** main database file.
  8272  ** ^The third and fourth parameters to this routine
  8273  ** are passed directly through to the second and third parameters of
  8274  ** the xFileControl method.  ^The return value of the xFileControl
  8275  ** method becomes the return value of this routine.
  8276  **
  8277  ** A few opcodes for [sqlite3_file_control()] are handled directly
  8278  ** by the SQLite core and never invoke the 
  8279  ** sqlite3_io_methods.xFileControl method.
  8280  ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  8281  ** a pointer to the underlying [sqlite3_file] object to be written into
  8282  ** the space pointed to by the 4th parameter.  The
  8283  ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
  8284  ** the [sqlite3_file] object associated with the journal file instead of
  8285  ** the main database.  The [SQLITE_FCNTL_VFS_POINTER] opcode returns
  8286  ** a pointer to the underlying [sqlite3_vfs] object for the file.
  8287  ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
  8288  ** from the pager.
  8289  **
  8290  ** ^If the second parameter (zDbName) does not match the name of any
  8291  ** open database file, then SQLITE_ERROR is returned.  ^This error
  8292  ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  8293  ** or [sqlite3_errmsg()].  The underlying xFileControl method might
  8294  ** also return SQLITE_ERROR.  There is no way to distinguish between
  8295  ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  8296  ** xFileControl method.
  8297  **
  8298  ** See also: [file control opcodes]
  8299  */
  8300  SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  8301  
  8302  /*
  8303  ** CAPI3REF: Testing Interface
  8304  **
  8305  ** ^The sqlite3_test_control() interface is used to read out internal
  8306  ** state of SQLite and to inject faults into SQLite for testing
  8307  ** purposes.  ^The first parameter is an operation code that determines
  8308  ** the number, meaning, and operation of all subsequent parameters.
  8309  **
  8310  ** This interface is not for use by applications.  It exists solely
  8311  ** for verifying the correct operation of the SQLite library.  Depending
  8312  ** on how the SQLite library is compiled, this interface might not exist.
  8313  **
  8314  ** The details of the operation codes, their meanings, the parameters
  8315  ** they take, and what they do are all subject to change without notice.
  8316  ** Unlike most of the SQLite API, this function is not guaranteed to
  8317  ** operate consistently from one release to the next.
  8318  */
  8319  SQLITE_API int sqlite3_test_control(int op, ...);
  8320  
  8321  /*
  8322  ** CAPI3REF: Testing Interface Operation Codes
  8323  **
  8324  ** These constants are the valid operation code parameters used
  8325  ** as the first argument to [sqlite3_test_control()].
  8326  **
  8327  ** These parameters and their meanings are subject to change
  8328  ** without notice.  These values are for testing purposes only.
  8329  ** Applications should not use any of these parameters or the
  8330  ** [sqlite3_test_control()] interface.
  8331  */
  8332  #define SQLITE_TESTCTRL_FIRST                    5
  8333  #define SQLITE_TESTCTRL_PRNG_SAVE                5
  8334  #define SQLITE_TESTCTRL_PRNG_RESTORE             6
  8335  #define SQLITE_TESTCTRL_PRNG_RESET               7
  8336  #define SQLITE_TESTCTRL_BITVEC_TEST              8
  8337  #define SQLITE_TESTCTRL_FAULT_INSTALL            9
  8338  #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
  8339  #define SQLITE_TESTCTRL_PENDING_BYTE            11
  8340  #define SQLITE_TESTCTRL_ASSERT                  12
  8341  #define SQLITE_TESTCTRL_ALWAYS                  13
  8342  #define SQLITE_TESTCTRL_RESERVE                 14
  8343  #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  8344  #define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */
  8345  #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
  8346  #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS      17
  8347  #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
  8348  #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
  8349  #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
  8350  #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
  8351  #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
  8352  #define SQLITE_TESTCTRL_BYTEORDER               22
  8353  #define SQLITE_TESTCTRL_ISINIT                  23
  8354  #define SQLITE_TESTCTRL_SORTER_MMAP             24
  8355  #define SQLITE_TESTCTRL_IMPOSTER                25
  8356  #define SQLITE_TESTCTRL_PARSER_COVERAGE         26
  8357  #define SQLITE_TESTCTRL_LAST                    26  /* Largest TESTCTRL */
  8358  
  8359  /*
  8360  ** CAPI3REF: SQL Keyword Checking
  8361  **
  8362  ** These routines provide access to the set of SQL language keywords 
  8363  ** recognized by SQLite.  Applications can uses these routines to determine
  8364  ** whether or not a specific identifier needs to be escaped (for example,
  8365  ** by enclosing in double-quotes) so as not to confuse the parser.
  8366  **
  8367  ** The sqlite3_keyword_count() interface returns the number of distinct
  8368  ** keywords understood by SQLite.
  8369  **
  8370  ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  8371  ** makes *Z point to that keyword expressed as UTF8 and writes the number
  8372  ** of bytes in the keyword into *L.  The string that *Z points to is not
  8373  ** zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns
  8374  ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  8375  ** or L are NULL or invalid pointers then calls to
  8376  ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  8377  **
  8378  ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  8379  ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  8380  ** if it is and zero if not.
  8381  **
  8382  ** The parser used by SQLite is forgiving.  It is often possible to use
  8383  ** a keyword as an identifier as long as such use does not result in a
  8384  ** parsing ambiguity.  For example, the statement
  8385  ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8386  ** creates a new table named "BEGIN" with three columns named
  8387  ** "REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid
  8388  ** using keywords as identifiers.  Common techniques used to avoid keyword
  8389  ** name collisions include:
  8390  ** <ul>
  8391  ** <li> Put all identifier names inside double-quotes.  This is the official
  8392  **      SQL way to escape identifier names.
  8393  ** <li> Put identifier names inside &#91;...&#93;.  This is not standard SQL,
  8394  **      but it is what SQL Server does and so lots of programmers use this
  8395  **      technique.
  8396  ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8397  **      with "Z".
  8398  ** <li> Include a digit somewhere in every identifier name.
  8399  ** </ul>
  8400  **
  8401  ** Note that the number of keywords understood by SQLite can depend on
  8402  ** compile-time options.  For example, "VACUUM" is not a keyword if
  8403  ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option.  Also,
  8404  ** new keywords may be added to future releases of SQLite.
  8405  */
  8406  SQLITE_API int sqlite3_keyword_count(void);
  8407  SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8408  SQLITE_API int sqlite3_keyword_check(const char*,int);
  8409  
  8410  /*
  8411  ** CAPI3REF: Dynamic String Object
  8412  ** KEYWORDS: {dynamic string}
  8413  **
  8414  ** An instance of the sqlite3_str object contains a dynamically-sized
  8415  ** string under construction.
  8416  **
  8417  ** The lifecycle of an sqlite3_str object is as follows:
  8418  ** <ol>
  8419  ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8420  ** <li> ^Text is appended to the sqlite3_str object using various
  8421  ** methods, such as [sqlite3_str_appendf()].
  8422  ** <li> ^The sqlite3_str object is destroyed and the string it created
  8423  ** is returned using the [sqlite3_str_finish()] interface.
  8424  ** </ol>
  8425  */
  8426  typedef struct sqlite3_str sqlite3_str;
  8427  
  8428  /*
  8429  ** CAPI3REF: Create A New Dynamic String Object
  8430  ** CONSTRUCTOR: sqlite3_str
  8431  **
  8432  ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8433  ** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
  8434  ** [sqlite3_str_new()] must be freed by a subsequent call to 
  8435  ** [sqlite3_str_finish(X)].
  8436  **
  8437  ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8438  ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8439  ** error the returned object might be a special singleton that will
  8440  ** silently reject new text, always return SQLITE_NOMEM from 
  8441  ** [sqlite3_str_errcode()], always return 0 for 
  8442  ** [sqlite3_str_length()], and always return NULL from
  8443  ** [sqlite3_str_finish(X)].  It is always safe to use the value
  8444  ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8445  ** to any of the other [sqlite3_str] methods.
  8446  **
  8447  ** The D parameter to [sqlite3_str_new(D)] may be NULL.  If the
  8448  ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8449  ** length of the string contained in the [sqlite3_str] object will be
  8450  ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8451  ** of [SQLITE_MAX_LENGTH].
  8452  */
  8453  SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8454  
  8455  /*
  8456  ** CAPI3REF: Finalize A Dynamic String
  8457  ** DESTRUCTOR: sqlite3_str
  8458  **
  8459  ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8460  ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8461  ** that contains the constructed string.  The calling application should
  8462  ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8463  ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8464  ** errors were encountered during construction of the string.  ^The
  8465  ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8466  ** string in [sqlite3_str] object X is zero bytes long.
  8467  */
  8468  SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8469  
  8470  /*
  8471  ** CAPI3REF: Add Content To A Dynamic String
  8472  ** METHOD: sqlite3_str
  8473  **
  8474  ** These interfaces add content to an sqlite3_str object previously obtained
  8475  ** from [sqlite3_str_new()].
  8476  **
  8477  ** ^The [sqlite3_str_appendf(X,F,...)] and 
  8478  ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8479  ** functionality of SQLite to append formatted text onto the end of 
  8480  ** [sqlite3_str] object X.
  8481  **
  8482  ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8483  ** onto the end of the [sqlite3_str] object X.  N must be non-negative.
  8484  ** S must contain at least N non-zero bytes of content.  To append a
  8485  ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8486  ** method instead.
  8487  **
  8488  ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8489  ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8490  **
  8491  ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8492  ** single-byte character C onto the end of [sqlite3_str] object X.
  8493  ** ^This method can be used, for example, to add whitespace indentation.
  8494  **
  8495  ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8496  ** inside [sqlite3_str] object X back to zero bytes in length.  
  8497  **
  8498  ** These methods do not return a result code.  ^If an error occurs, that fact
  8499  ** is recorded in the [sqlite3_str] object and can be recovered by a
  8500  ** subsequent call to [sqlite3_str_errcode(X)].
  8501  */
  8502  SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8503  SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8504  SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8505  SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8506  SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8507  SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8508  
  8509  /*
  8510  ** CAPI3REF: Status Of A Dynamic String
  8511  ** METHOD: sqlite3_str
  8512  **
  8513  ** These interfaces return the current status of an [sqlite3_str] object.
  8514  **
  8515  ** ^If any prior errors have occurred while constructing the dynamic string
  8516  ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8517  ** an appropriate error code.  ^The [sqlite3_str_errcode(X)] method returns
  8518  ** [SQLITE_NOMEM] following any out-of-memory error, or
  8519  ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8520  ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8521  **
  8522  ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8523  ** of the dynamic string under construction in [sqlite3_str] object X.
  8524  ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8525  ** zero-termination byte.
  8526  **
  8527  ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8528  ** content of the dynamic string under construction in X.  The value
  8529  ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8530  ** and might be freed or altered by any subsequent method on the same
  8531  ** [sqlite3_str] object.  Applications must not used the pointer returned
  8532  ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8533  ** object.  ^Applications may change the content of the string returned
  8534  ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8535  ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8536  ** write any byte after any subsequent sqlite3_str method call.
  8537  */
  8538  SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8539  SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8540  SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8541  
  8542  /*
  8543  ** CAPI3REF: SQLite Runtime Status
  8544  **
  8545  ** ^These interfaces are used to retrieve runtime status information
  8546  ** about the performance of SQLite, and optionally to reset various
  8547  ** highwater marks.  ^The first argument is an integer code for
  8548  ** the specific parameter to measure.  ^(Recognized integer codes
  8549  ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8550  ** ^The current value of the parameter is returned into *pCurrent.
  8551  ** ^The highest recorded value is returned in *pHighwater.  ^If the
  8552  ** resetFlag is true, then the highest record value is reset after
  8553  ** *pHighwater is written.  ^(Some parameters do not record the highest
  8554  ** value.  For those parameters
  8555  ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8556  ** ^(Other parameters record only the highwater mark and not the current
  8557  ** value.  For these latter parameters nothing is written into *pCurrent.)^
  8558  **
  8559  ** ^The sqlite3_status() and sqlite3_status64() routines return
  8560  ** SQLITE_OK on success and a non-zero [error code] on failure.
  8561  **
  8562  ** If either the current value or the highwater mark is too large to
  8563  ** be represented by a 32-bit integer, then the values returned by
  8564  ** sqlite3_status() are undefined.
  8565  **
  8566  ** See also: [sqlite3_db_status()]
  8567  */
  8568  SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8569  SQLITE_API int sqlite3_status64(
  8570    int op,
  8571    sqlite3_int64 *pCurrent,
  8572    sqlite3_int64 *pHighwater,
  8573    int resetFlag
  8574  );
  8575  
  8576  
  8577  /*
  8578  ** CAPI3REF: Status Parameters
  8579  ** KEYWORDS: {status parameters}
  8580  **
  8581  ** These integer constants designate various run-time status parameters
  8582  ** that can be returned by [sqlite3_status()].
  8583  **
  8584  ** <dl>
  8585  ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8586  ** <dd>This parameter is the current amount of memory checked out
  8587  ** using [sqlite3_malloc()], either directly or indirectly.  The
  8588  ** figure includes calls made to [sqlite3_malloc()] by the application
  8589  ** and internal memory usage by the SQLite library.  Auxiliary page-cache
  8590  ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8591  ** this parameter.  The amount returned is the sum of the allocation
  8592  ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8593  **
  8594  ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8595  ** <dd>This parameter records the largest memory allocation request
  8596  ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8597  ** internal equivalents).  Only the value returned in the
  8598  ** *pHighwater parameter to [sqlite3_status()] is of interest.  
  8599  ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8600  **
  8601  ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8602  ** <dd>This parameter records the number of separate memory allocations
  8603  ** currently checked out.</dd>)^
  8604  **
  8605  ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8606  ** <dd>This parameter returns the number of pages used out of the
  8607  ** [pagecache memory allocator] that was configured using 
  8608  ** [SQLITE_CONFIG_PAGECACHE].  The
  8609  ** value returned is in pages, not in bytes.</dd>)^
  8610  **
  8611  ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
  8612  ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8613  ** <dd>This parameter returns the number of bytes of page cache
  8614  ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8615  ** buffer and where forced to overflow to [sqlite3_malloc()].  The
  8616  ** returned value includes allocations that overflowed because they
  8617  ** where too large (they were larger than the "sz" parameter to
  8618  ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8619  ** no space was left in the page cache.</dd>)^
  8620  **
  8621  ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8622  ** <dd>This parameter records the largest memory allocation request
  8623  ** handed to [pagecache memory allocator].  Only the value returned in the
  8624  ** *pHighwater parameter to [sqlite3_status()] is of interest.  
  8625  ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8626  **
  8627  ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8628  ** <dd>No longer used.</dd>
  8629  **
  8630  ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8631  ** <dd>No longer used.</dd>
  8632  **
  8633  ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8634  ** <dd>No longer used.</dd>
  8635  **
  8636  ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8637  ** <dd>The *pHighwater parameter records the deepest parser stack. 
  8638  ** The *pCurrent value is undefined.  The *pHighwater value is only
  8639  ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8640  ** </dl>
  8641  **
  8642  ** New status parameters may be added from time to time.
  8643  */
  8644  #define SQLITE_STATUS_MEMORY_USED          0
  8645  #define SQLITE_STATUS_PAGECACHE_USED       1
  8646  #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
  8647  #define SQLITE_STATUS_SCRATCH_USED         3  /* NOT USED */
  8648  #define SQLITE_STATUS_SCRATCH_OVERFLOW     4  /* NOT USED */
  8649  #define SQLITE_STATUS_MALLOC_SIZE          5
  8650  #define SQLITE_STATUS_PARSER_STACK         6
  8651  #define SQLITE_STATUS_PAGECACHE_SIZE       7
  8652  #define SQLITE_STATUS_SCRATCH_SIZE         8  /* NOT USED */
  8653  #define SQLITE_STATUS_MALLOC_COUNT         9
  8654  
  8655  /*
  8656  ** CAPI3REF: Database Connection Status
  8657  ** METHOD: sqlite3
  8658  **
  8659  ** ^This interface is used to retrieve runtime status information 
  8660  ** about a single [database connection].  ^The first argument is the
  8661  ** database connection object to be interrogated.  ^The second argument
  8662  ** is an integer constant, taken from the set of
  8663  ** [SQLITE_DBSTATUS options], that
  8664  ** determines the parameter to interrogate.  The set of 
  8665  ** [SQLITE_DBSTATUS options] is likely
  8666  ** to grow in future releases of SQLite.
  8667  **
  8668  ** ^The current value of the requested parameter is written into *pCur
  8669  ** and the highest instantaneous value is written into *pHiwtr.  ^If
  8670  ** the resetFlg is true, then the highest instantaneous value is
  8671  ** reset back down to the current value.
  8672  **
  8673  ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8674  ** non-zero [error code] on failure.
  8675  **
  8676  ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8677  */
  8678  SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8679  
  8680  /*
  8681  ** CAPI3REF: Status Parameters for database connections
  8682  ** KEYWORDS: {SQLITE_DBSTATUS options}
  8683  **
  8684  ** These constants are the available integer "verbs" that can be passed as
  8685  ** the second argument to the [sqlite3_db_status()] interface.
  8686  **
  8687  ** New verbs may be added in future releases of SQLite. Existing verbs
  8688  ** might be discontinued. Applications should check the return code from
  8689  ** [sqlite3_db_status()] to make sure that the call worked.
  8690  ** The [sqlite3_db_status()] interface will return a non-zero error code
  8691  ** if a discontinued or unsupported verb is invoked.
  8692  **
  8693  ** <dl>
  8694  ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8695  ** <dd>This parameter returns the number of lookaside memory slots currently
  8696  ** checked out.</dd>)^
  8697  **
  8698  ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8699  ** <dd>This parameter returns the number malloc attempts that were 
  8700  ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8701  ** the current value is always zero.)^
  8702  **
  8703  ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8704  ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8705  ** <dd>This parameter returns the number malloc attempts that might have
  8706  ** been satisfied using lookaside memory but failed due to the amount of
  8707  ** memory requested being larger than the lookaside slot size.
  8708  ** Only the high-water value is meaningful;
  8709  ** the current value is always zero.)^
  8710  **
  8711  ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8712  ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8713  ** <dd>This parameter returns the number malloc attempts that might have
  8714  ** been satisfied using lookaside memory but failed due to all lookaside
  8715  ** memory already being in use.
  8716  ** Only the high-water value is meaningful;
  8717  ** the current value is always zero.)^
  8718  **
  8719  ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8720  ** <dd>This parameter returns the approximate number of bytes of heap
  8721  ** memory used by all pager caches associated with the database connection.)^
  8722  ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8723  **
  8724  ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] 
  8725  ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8726  ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8727  ** pager cache is shared between two or more connections the bytes of heap
  8728  ** memory used by that pager cache is divided evenly between the attached
  8729  ** connections.)^  In other words, if none of the pager caches associated
  8730  ** with the database connection are shared, this request returns the same
  8731  ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8732  ** shared, the value returned by this call will be smaller than that returned
  8733  ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8734  ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8735  **
  8736  ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8737  ** <dd>This parameter returns the approximate number of bytes of heap
  8738  ** memory used to store the schema for all databases associated
  8739  ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
  8740  ** ^The full amount of memory used by the schemas is reported, even if the
  8741  ** schema memory is shared with other database connections due to
  8742  ** [shared cache mode] being enabled.
  8743  ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8744  **
  8745  ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8746  ** <dd>This parameter returns the approximate number of bytes of heap
  8747  ** and lookaside memory used by all prepared statements associated with
  8748  ** the database connection.)^
  8749  ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8750  ** </dd>
  8751  **
  8752  ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8753  ** <dd>This parameter returns the number of pager cache hits that have
  8754  ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
  8755  ** is always 0.
  8756  ** </dd>
  8757  **
  8758  ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8759  ** <dd>This parameter returns the number of pager cache misses that have
  8760  ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
  8761  ** is always 0.
  8762  ** </dd>
  8763  **
  8764  ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8765  ** <dd>This parameter returns the number of dirty cache entries that have
  8766  ** been written to disk. Specifically, the number of pages written to the
  8767  ** wal file in wal mode databases, or the number of pages written to the
  8768  ** database file in rollback mode databases. Any pages written as part of
  8769  ** transaction rollback or database recovery operations are not included.
  8770  ** If an IO or other error occurs while writing a page to disk, the effect
  8771  ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8772  ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8773  ** </dd>
  8774  **
  8775  ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8776  ** <dd>This parameter returns the number of dirty cache entries that have
  8777  ** been written to disk in the middle of a transaction due to the page
  8778  ** cache overflowing. Transactions are more efficient if they are written
  8779  ** to disk all at once. When pages spill mid-transaction, that introduces
  8780  ** additional overhead. This parameter can be used help identify
  8781  ** inefficiencies that can be resolve by increasing the cache size.
  8782  ** </dd>
  8783  **
  8784  ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8785  ** <dd>This parameter returns zero for the current value if and only if
  8786  ** all foreign key constraints (deferred or immediate) have been
  8787  ** resolved.)^  ^The highwater mark is always 0.
  8788  ** </dd>
  8789  ** </dl>
  8790  */
  8791  #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
  8792  #define SQLITE_DBSTATUS_CACHE_USED           1
  8793  #define SQLITE_DBSTATUS_SCHEMA_USED          2
  8794  #define SQLITE_DBSTATUS_STMT_USED            3
  8795  #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
  8796  #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
  8797  #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
  8798  #define SQLITE_DBSTATUS_CACHE_HIT            7
  8799  #define SQLITE_DBSTATUS_CACHE_MISS           8
  8800  #define SQLITE_DBSTATUS_CACHE_WRITE          9
  8801  #define SQLITE_DBSTATUS_DEFERRED_FKS        10
  8802  #define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
  8803  #define SQLITE_DBSTATUS_CACHE_SPILL         12
  8804  #define SQLITE_DBSTATUS_MAX                 12   /* Largest defined DBSTATUS */
  8805  
  8806  
  8807  /*
  8808  ** CAPI3REF: Prepared Statement Status
  8809  ** METHOD: sqlite3_stmt
  8810  **
  8811  ** ^(Each prepared statement maintains various
  8812  ** [SQLITE_STMTSTATUS counters] that measure the number
  8813  ** of times it has performed specific operations.)^  These counters can
  8814  ** be used to monitor the performance characteristics of the prepared
  8815  ** statements.  For example, if the number of table steps greatly exceeds
  8816  ** the number of table searches or result rows, that would tend to indicate
  8817  ** that the prepared statement is using a full table scan rather than
  8818  ** an index.  
  8819  **
  8820  ** ^(This interface is used to retrieve and reset counter values from
  8821  ** a [prepared statement].  The first argument is the prepared statement
  8822  ** object to be interrogated.  The second argument
  8823  ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8824  ** to be interrogated.)^
  8825  ** ^The current value of the requested counter is returned.
  8826  ** ^If the resetFlg is true, then the counter is reset to zero after this
  8827  ** interface call returns.
  8828  **
  8829  ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8830  */
  8831  SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8832  
  8833  /*
  8834  ** CAPI3REF: Status Parameters for prepared statements
  8835  ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8836  **
  8837  ** These preprocessor macros define integer codes that name counter
  8838  ** values associated with the [sqlite3_stmt_status()] interface.
  8839  ** The meanings of the various counters are as follows:
  8840  **
  8841  ** <dl>
  8842  ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8843  ** <dd>^This is the number of times that SQLite has stepped forward in
  8844  ** a table as part of a full table scan.  Large numbers for this counter
  8845  ** may indicate opportunities for performance improvement through 
  8846  ** careful use of indices.</dd>
  8847  **
  8848  ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8849  ** <dd>^This is the number of sort operations that have occurred.
  8850  ** A non-zero value in this counter may indicate an opportunity to
  8851  ** improvement performance through careful use of indices.</dd>
  8852  **
  8853  ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8854  ** <dd>^This is the number of rows inserted into transient indices that
  8855  ** were created automatically in order to help joins run faster.
  8856  ** A non-zero value in this counter may indicate an opportunity to
  8857  ** improvement performance by adding permanent indices that do not
  8858  ** need to be reinitialized each time the statement is run.</dd>
  8859  **
  8860  ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8861  ** <dd>^This is the number of virtual machine operations executed
  8862  ** by the prepared statement if that number is less than or equal
  8863  ** to 2147483647.  The number of virtual machine operations can be 
  8864  ** used as a proxy for the total work done by the prepared statement.
  8865  ** If the number of virtual machine operations exceeds 2147483647
  8866  ** then the value returned by this statement status code is undefined.
  8867  **
  8868  ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8869  ** <dd>^This is the number of times that the prepare statement has been
  8870  ** automatically regenerated due to schema changes or change to 
  8871  ** [bound parameters] that might affect the query plan.
  8872  **
  8873  ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8874  ** <dd>^This is the number of times that the prepared statement has
  8875  ** been run.  A single "run" for the purposes of this counter is one
  8876  ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8877  ** The counter is incremented on the first [sqlite3_step()] call of each
  8878  ** cycle.
  8879  **
  8880  ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8881  ** <dd>^This is the approximate number of bytes of heap memory
  8882  ** used to store the prepared statement.  ^This value is not actually
  8883  ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8884  ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8885  ** </dd>
  8886  ** </dl>
  8887  */
  8888  #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
  8889  #define SQLITE_STMTSTATUS_SORT              2
  8890  #define SQLITE_STMTSTATUS_AUTOINDEX         3
  8891  #define SQLITE_STMTSTATUS_VM_STEP           4
  8892  #define SQLITE_STMTSTATUS_REPREPARE         5
  8893  #define SQLITE_STMTSTATUS_RUN               6
  8894  #define SQLITE_STMTSTATUS_MEMUSED           99
  8895  
  8896  /*
  8897  ** CAPI3REF: Custom Page Cache Object
  8898  **
  8899  ** The sqlite3_pcache type is opaque.  It is implemented by
  8900  ** the pluggable module.  The SQLite core has no knowledge of
  8901  ** its size or internal structure and never deals with the
  8902  ** sqlite3_pcache object except by holding and passing pointers
  8903  ** to the object.
  8904  **
  8905  ** See [sqlite3_pcache_methods2] for additional information.
  8906  */
  8907  typedef struct sqlite3_pcache sqlite3_pcache;
  8908  
  8909  /*
  8910  ** CAPI3REF: Custom Page Cache Object
  8911  **
  8912  ** The sqlite3_pcache_page object represents a single page in the
  8913  ** page cache.  The page cache will allocate instances of this
  8914  ** object.  Various methods of the page cache use pointers to instances
  8915  ** of this object as parameters or as their return value.
  8916  **
  8917  ** See [sqlite3_pcache_methods2] for additional information.
  8918  */
  8919  typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8920  struct sqlite3_pcache_page {
  8921    void *pBuf;        /* The content of the page */
  8922    void *pExtra;      /* Extra information associated with the page */
  8923  };
  8924  
  8925  /*
  8926  ** CAPI3REF: Application Defined Page Cache.
  8927  ** KEYWORDS: {page cache}
  8928  **
  8929  ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8930  ** register an alternative page cache implementation by passing in an 
  8931  ** instance of the sqlite3_pcache_methods2 structure.)^
  8932  ** In many applications, most of the heap memory allocated by 
  8933  ** SQLite is used for the page cache.
  8934  ** By implementing a 
  8935  ** custom page cache using this API, an application can better control
  8936  ** the amount of memory consumed by SQLite, the way in which 
  8937  ** that memory is allocated and released, and the policies used to 
  8938  ** determine exactly which parts of a database file are cached and for 
  8939  ** how long.
  8940  **
  8941  ** The alternative page cache mechanism is an
  8942  ** extreme measure that is only needed by the most demanding applications.
  8943  ** The built-in page cache is recommended for most uses.
  8944  **
  8945  ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8946  ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
  8947  ** the application may discard the parameter after the call to
  8948  ** [sqlite3_config()] returns.)^
  8949  **
  8950  ** [[the xInit() page cache method]]
  8951  ** ^(The xInit() method is called once for each effective 
  8952  ** call to [sqlite3_initialize()])^
  8953  ** (usually only once during the lifetime of the process). ^(The xInit()
  8954  ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8955  ** The intent of the xInit() method is to set up global data structures 
  8956  ** required by the custom page cache implementation. 
  8957  ** ^(If the xInit() method is NULL, then the 
  8958  ** built-in default page cache is used instead of the application defined
  8959  ** page cache.)^
  8960  **
  8961  ** [[the xShutdown() page cache method]]
  8962  ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8963  ** It can be used to clean up 
  8964  ** any outstanding resources before process shutdown, if required.
  8965  ** ^The xShutdown() method may be NULL.
  8966  **
  8967  ** ^SQLite automatically serializes calls to the xInit method,
  8968  ** so the xInit method need not be threadsafe.  ^The
  8969  ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8970  ** not need to be threadsafe either.  All other methods must be threadsafe
  8971  ** in multithreaded applications.
  8972  **
  8973  ** ^SQLite will never invoke xInit() more than once without an intervening
  8974  ** call to xShutdown().
  8975  **
  8976  ** [[the xCreate() page cache methods]]
  8977  ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8978  ** SQLite will typically create one cache instance for each open database file,
  8979  ** though this is not guaranteed. ^The
  8980  ** first parameter, szPage, is the size in bytes of the pages that must
  8981  ** be allocated by the cache.  ^szPage will always a power of two.  ^The
  8982  ** second parameter szExtra is a number of bytes of extra storage 
  8983  ** associated with each page cache entry.  ^The szExtra parameter will
  8984  ** a number less than 250.  SQLite will use the
  8985  ** extra szExtra bytes on each page to store metadata about the underlying
  8986  ** database page on disk.  The value passed into szExtra depends
  8987  ** on the SQLite version, the target platform, and how SQLite was compiled.
  8988  ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8989  ** created will be used to cache database pages of a file stored on disk, or
  8990  ** false if it is used for an in-memory database. The cache implementation
  8991  ** does not have to do anything special based with the value of bPurgeable;
  8992  ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
  8993  ** never invoke xUnpin() except to deliberately delete a page.
  8994  ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8995  ** false will always have the "discard" flag set to true.  
  8996  ** ^Hence, a cache created with bPurgeable false will
  8997  ** never contain any unpinned pages.
  8998  **
  8999  ** [[the xCachesize() page cache method]]
  9000  ** ^(The xCachesize() method may be called at any time by SQLite to set the
  9001  ** suggested maximum cache-size (number of pages stored by) the cache
  9002  ** instance passed as the first argument. This is the value configured using
  9003  ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
  9004  ** parameter, the implementation is not required to do anything with this
  9005  ** value; it is advisory only.
  9006  **
  9007  ** [[the xPagecount() page cache methods]]
  9008  ** The xPagecount() method must return the number of pages currently
  9009  ** stored in the cache, both pinned and unpinned.
  9010  ** 
  9011  ** [[the xFetch() page cache methods]]
  9012  ** The xFetch() method locates a page in the cache and returns a pointer to 
  9013  ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  9014  ** The pBuf element of the returned sqlite3_pcache_page object will be a
  9015  ** pointer to a buffer of szPage bytes used to store the content of a 
  9016  ** single database page.  The pExtra element of sqlite3_pcache_page will be
  9017  ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  9018  ** for each entry in the page cache.
  9019  **
  9020  ** The page to be fetched is determined by the key. ^The minimum key value
  9021  ** is 1.  After it has been retrieved using xFetch, the page is considered
  9022  ** to be "pinned".
  9023  **
  9024  ** If the requested page is already in the page cache, then the page cache
  9025  ** implementation must return a pointer to the page buffer with its content
  9026  ** intact.  If the requested page is not already in the cache, then the
  9027  ** cache implementation should use the value of the createFlag
  9028  ** parameter to help it determined what action to take:
  9029  **
  9030  ** <table border=1 width=85% align=center>
  9031  ** <tr><th> createFlag <th> Behavior when page is not already in cache
  9032  ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
  9033  ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  9034  **                 Otherwise return NULL.
  9035  ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
  9036  **                 NULL if allocating a new page is effectively impossible.
  9037  ** </table>
  9038  **
  9039  ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
  9040  ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  9041  ** failed.)^  In between the to xFetch() calls, SQLite may
  9042  ** attempt to unpin one or more cache pages by spilling the content of
  9043  ** pinned pages to disk and synching the operating system disk cache.
  9044  **
  9045  ** [[the xUnpin() page cache method]]
  9046  ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  9047  ** as its second argument.  If the third parameter, discard, is non-zero,
  9048  ** then the page must be evicted from the cache.
  9049  ** ^If the discard parameter is
  9050  ** zero, then the page may be discarded or retained at the discretion of
  9051  ** page cache implementation. ^The page cache implementation
  9052  ** may choose to evict unpinned pages at any time.
  9053  **
  9054  ** The cache must not perform any reference counting. A single 
  9055  ** call to xUnpin() unpins the page regardless of the number of prior calls 
  9056  ** to xFetch().
  9057  **
  9058  ** [[the xRekey() page cache methods]]
  9059  ** The xRekey() method is used to change the key value associated with the
  9060  ** page passed as the second argument. If the cache
  9061  ** previously contains an entry associated with newKey, it must be
  9062  ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  9063  ** to be pinned.
  9064  **
  9065  ** When SQLite calls the xTruncate() method, the cache must discard all
  9066  ** existing cache entries with page numbers (keys) greater than or equal
  9067  ** to the value of the iLimit parameter passed to xTruncate(). If any
  9068  ** of these pages are pinned, they are implicitly unpinned, meaning that
  9069  ** they can be safely discarded.
  9070  **
  9071  ** [[the xDestroy() page cache method]]
  9072  ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  9073  ** All resources associated with the specified cache should be freed. ^After
  9074  ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  9075  ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  9076  ** functions.
  9077  **
  9078  ** [[the xShrink() page cache method]]
  9079  ** ^SQLite invokes the xShrink() method when it wants the page cache to
  9080  ** free up as much of heap memory as possible.  The page cache implementation
  9081  ** is not obligated to free any memory, but well-behaved implementations should
  9082  ** do their best.
  9083  */
  9084  typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  9085  struct sqlite3_pcache_methods2 {
  9086    int iVersion;
  9087    void *pArg;
  9088    int (*xInit)(void*);
  9089    void (*xShutdown)(void*);
  9090    sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  9091    void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  9092    int (*xPagecount)(sqlite3_pcache*);
  9093    sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  9094    void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  9095    void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
  9096        unsigned oldKey, unsigned newKey);
  9097    void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  9098    void (*xDestroy)(sqlite3_pcache*);
  9099    void (*xShrink)(sqlite3_pcache*);
  9100  };
  9101  
  9102  /*
  9103  ** This is the obsolete pcache_methods object that has now been replaced
  9104  ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
  9105  ** retained in the header file for backwards compatibility only.
  9106  */
  9107  typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  9108  struct sqlite3_pcache_methods {
  9109    void *pArg;
  9110    int (*xInit)(void*);
  9111    void (*xShutdown)(void*);
  9112    sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  9113    void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  9114    int (*xPagecount)(sqlite3_pcache*);
  9115    void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  9116    void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  9117    void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  9118    void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  9119    void (*xDestroy)(sqlite3_pcache*);
  9120  };
  9121  
  9122  
  9123  /*
  9124  ** CAPI3REF: Online Backup Object
  9125  **
  9126  ** The sqlite3_backup object records state information about an ongoing
  9127  ** online backup operation.  ^The sqlite3_backup object is created by
  9128  ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  9129  ** [sqlite3_backup_finish()].
  9130  **
  9131  ** See Also: [Using the SQLite Online Backup API]
  9132  */
  9133  typedef struct sqlite3_backup sqlite3_backup;
  9134  
  9135  /*
  9136  ** CAPI3REF: Online Backup API.
  9137  **
  9138  ** The backup API copies the content of one database into another.
  9139  ** It is useful either for creating backups of databases or
  9140  ** for copying in-memory databases to or from persistent files. 
  9141  **
  9142  ** See Also: [Using the SQLite Online Backup API]
  9143  **
  9144  ** ^SQLite holds a write transaction open on the destination database file
  9145  ** for the duration of the backup operation.
  9146  ** ^The source database is read-locked only while it is being read;
  9147  ** it is not locked continuously for the entire backup operation.
  9148  ** ^Thus, the backup may be performed on a live source database without
  9149  ** preventing other database connections from
  9150  ** reading or writing to the source database while the backup is underway.
  9151  ** 
  9152  ** ^(To perform a backup operation: 
  9153  **   <ol>
  9154  **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
  9155  **         backup, 
  9156  **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
  9157  **         the data between the two databases, and finally
  9158  **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
  9159  **         associated with the backup operation. 
  9160  **   </ol>)^
  9161  ** There should be exactly one call to sqlite3_backup_finish() for each
  9162  ** successful call to sqlite3_backup_init().
  9163  **
  9164  ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  9165  **
  9166  ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
  9167  ** [database connection] associated with the destination database 
  9168  ** and the database name, respectively.
  9169  ** ^The database name is "main" for the main database, "temp" for the
  9170  ** temporary database, or the name specified after the AS keyword in
  9171  ** an [ATTACH] statement for an attached database.
  9172  ** ^The S and M arguments passed to 
  9173  ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  9174  ** and database name of the source database, respectively.
  9175  ** ^The source and destination [database connections] (parameters S and D)
  9176  ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  9177  ** an error.
  9178  **
  9179  ** ^A call to sqlite3_backup_init() will fail, returning NULL, if 
  9180  ** there is already a read or read-write transaction open on the 
  9181  ** destination database.
  9182  **
  9183  ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  9184  ** returned and an error code and error message are stored in the
  9185  ** destination [database connection] D.
  9186  ** ^The error code and message for the failed call to sqlite3_backup_init()
  9187  ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  9188  ** [sqlite3_errmsg16()] functions.
  9189  ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  9190  ** [sqlite3_backup] object.
  9191  ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  9192  ** sqlite3_backup_finish() functions to perform the specified backup 
  9193  ** operation.
  9194  **
  9195  ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  9196  **
  9197  ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
  9198  ** the source and destination databases specified by [sqlite3_backup] object B.
  9199  ** ^If N is negative, all remaining source pages are copied. 
  9200  ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  9201  ** are still more pages to be copied, then the function returns [SQLITE_OK].
  9202  ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  9203  ** from source to destination, then it returns [SQLITE_DONE].
  9204  ** ^If an error occurs while running sqlite3_backup_step(B,N),
  9205  ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  9206  ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  9207  ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  9208  ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  9209  **
  9210  ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  9211  ** <ol>
  9212  ** <li> the destination database was opened read-only, or
  9213  ** <li> the destination database is using write-ahead-log journaling
  9214  ** and the destination and source page sizes differ, or
  9215  ** <li> the destination database is an in-memory database and the
  9216  ** destination and source page sizes differ.
  9217  ** </ol>)^
  9218  **
  9219  ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  9220  ** the [sqlite3_busy_handler | busy-handler function]
  9221  ** is invoked (if one is specified). ^If the 
  9222  ** busy-handler returns non-zero before the lock is available, then 
  9223  ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  9224  ** sqlite3_backup_step() can be retried later. ^If the source
  9225  ** [database connection]
  9226  ** is being used to write to the source database when sqlite3_backup_step()
  9227  ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  9228  ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  9229  ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  9230  ** [SQLITE_READONLY] is returned, then 
  9231  ** there is no point in retrying the call to sqlite3_backup_step(). These 
  9232  ** errors are considered fatal.)^  The application must accept 
  9233  ** that the backup operation has failed and pass the backup operation handle 
  9234  ** to the sqlite3_backup_finish() to release associated resources.
  9235  **
  9236  ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  9237  ** on the destination file. ^The exclusive lock is not released until either 
  9238  ** sqlite3_backup_finish() is called or the backup operation is complete 
  9239  ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
  9240  ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  9241  ** lasts for the duration of the sqlite3_backup_step() call.
  9242  ** ^Because the source database is not locked between calls to
  9243  ** sqlite3_backup_step(), the source database may be modified mid-way
  9244  ** through the backup process.  ^If the source database is modified by an
  9245  ** external process or via a database connection other than the one being
  9246  ** used by the backup operation, then the backup will be automatically
  9247  ** restarted by the next call to sqlite3_backup_step(). ^If the source 
  9248  ** database is modified by the using the same database connection as is used
  9249  ** by the backup operation, then the backup database is automatically
  9250  ** updated at the same time.
  9251  **
  9252  ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  9253  **
  9254  ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
  9255  ** application wishes to abandon the backup operation, the application
  9256  ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  9257  ** ^The sqlite3_backup_finish() interfaces releases all
  9258  ** resources associated with the [sqlite3_backup] object. 
  9259  ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  9260  ** active write-transaction on the destination database is rolled back.
  9261  ** The [sqlite3_backup] object is invalid
  9262  ** and may not be used following a call to sqlite3_backup_finish().
  9263  **
  9264  ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  9265  ** sqlite3_backup_step() errors occurred, regardless or whether or not
  9266  ** sqlite3_backup_step() completed.
  9267  ** ^If an out-of-memory condition or IO error occurred during any prior
  9268  ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  9269  ** sqlite3_backup_finish() returns the corresponding [error code].
  9270  **
  9271  ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  9272  ** is not a permanent error and does not affect the return value of
  9273  ** sqlite3_backup_finish().
  9274  **
  9275  ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  9276  ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  9277  **
  9278  ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  9279  ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  9280  ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  9281  ** in the source database at the conclusion of the most recent
  9282  ** sqlite3_backup_step().
  9283  ** ^(The values returned by these functions are only updated by
  9284  ** sqlite3_backup_step(). If the source database is modified in a way that
  9285  ** changes the size of the source database or the number of pages remaining,
  9286  ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  9287  ** and sqlite3_backup_remaining() until after the next
  9288  ** sqlite3_backup_step().)^
  9289  **
  9290  ** <b>Concurrent Usage of Database Handles</b>
  9291  **
  9292  ** ^The source [database connection] may be used by the application for other
  9293  ** purposes while a backup operation is underway or being initialized.
  9294  ** ^If SQLite is compiled and configured to support threadsafe database
  9295  ** connections, then the source database connection may be used concurrently
  9296  ** from within other threads.
  9297  **
  9298  ** However, the application must guarantee that the destination 
  9299  ** [database connection] is not passed to any other API (by any thread) after 
  9300  ** sqlite3_backup_init() is called and before the corresponding call to
  9301  ** sqlite3_backup_finish().  SQLite does not currently check to see
  9302  ** if the application incorrectly accesses the destination [database connection]
  9303  ** and so no error code is reported, but the operations may malfunction
  9304  ** nevertheless.  Use of the destination database connection while a
  9305  ** backup is in progress might also also cause a mutex deadlock.
  9306  **
  9307  ** If running in [shared cache mode], the application must
  9308  ** guarantee that the shared cache used by the destination database
  9309  ** is not accessed while the backup is running. In practice this means
  9310  ** that the application must guarantee that the disk file being 
  9311  ** backed up to is not accessed by any connection within the process,
  9312  ** not just the specific connection that was passed to sqlite3_backup_init().
  9313  **
  9314  ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
  9315  ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  9316  ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  9317  ** APIs are not strictly speaking threadsafe. If they are invoked at the
  9318  ** same time as another thread is invoking sqlite3_backup_step() it is
  9319  ** possible that they return invalid values.
  9320  */
  9321  SQLITE_API sqlite3_backup *sqlite3_backup_init(
  9322    sqlite3 *pDest,                        /* Destination database handle */
  9323    const char *zDestName,                 /* Destination database name */
  9324    sqlite3 *pSource,                      /* Source database handle */
  9325    const char *zSourceName                /* Source database name */
  9326  );
  9327  SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  9328  SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  9329  SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  9330  SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  9331  
  9332  /*
  9333  ** CAPI3REF: Unlock Notification
  9334  ** METHOD: sqlite3
  9335  **
  9336  ** ^When running in shared-cache mode, a database operation may fail with
  9337  ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  9338  ** individual tables within the shared-cache cannot be obtained. See
  9339  ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
  9340  ** ^This API may be used to register a callback that SQLite will invoke 
  9341  ** when the connection currently holding the required lock relinquishes it.
  9342  ** ^This API is only available if the library was compiled with the
  9343  ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  9344  **
  9345  ** See Also: [Using the SQLite Unlock Notification Feature].
  9346  **
  9347  ** ^Shared-cache locks are released when a database connection concludes
  9348  ** its current transaction, either by committing it or rolling it back. 
  9349  **
  9350  ** ^When a connection (known as the blocked connection) fails to obtain a
  9351  ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  9352  ** identity of the database connection (the blocking connection) that
  9353  ** has locked the required resource is stored internally. ^After an 
  9354  ** application receives an SQLITE_LOCKED error, it may call the
  9355  ** sqlite3_unlock_notify() method with the blocked connection handle as 
  9356  ** the first argument to register for a callback that will be invoked
  9357  ** when the blocking connections current transaction is concluded. ^The
  9358  ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  9359  ** call that concludes the blocking connections transaction.
  9360  **
  9361  ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  9362  ** there is a chance that the blocking connection will have already
  9363  ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  9364  ** If this happens, then the specified callback is invoked immediately,
  9365  ** from within the call to sqlite3_unlock_notify().)^
  9366  **
  9367  ** ^If the blocked connection is attempting to obtain a write-lock on a
  9368  ** shared-cache table, and more than one other connection currently holds
  9369  ** a read-lock on the same table, then SQLite arbitrarily selects one of 
  9370  ** the other connections to use as the blocking connection.
  9371  **
  9372  ** ^(There may be at most one unlock-notify callback registered by a 
  9373  ** blocked connection. If sqlite3_unlock_notify() is called when the
  9374  ** blocked connection already has a registered unlock-notify callback,
  9375  ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  9376  ** called with a NULL pointer as its second argument, then any existing
  9377  ** unlock-notify callback is canceled. ^The blocked connections 
  9378  ** unlock-notify callback may also be canceled by closing the blocked
  9379  ** connection using [sqlite3_close()].
  9380  **
  9381  ** The unlock-notify callback is not reentrant. If an application invokes
  9382  ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  9383  ** crash or deadlock may be the result.
  9384  **
  9385  ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  9386  ** returns SQLITE_OK.
  9387  **
  9388  ** <b>Callback Invocation Details</b>
  9389  **
  9390  ** When an unlock-notify callback is registered, the application provides a 
  9391  ** single void* pointer that is passed to the callback when it is invoked.
  9392  ** However, the signature of the callback function allows SQLite to pass
  9393  ** it an array of void* context pointers. The first argument passed to
  9394  ** an unlock-notify callback is a pointer to an array of void* pointers,
  9395  ** and the second is the number of entries in the array.
  9396  **
  9397  ** When a blocking connections transaction is concluded, there may be
  9398  ** more than one blocked connection that has registered for an unlock-notify
  9399  ** callback. ^If two or more such blocked connections have specified the
  9400  ** same callback function, then instead of invoking the callback function
  9401  ** multiple times, it is invoked once with the set of void* context pointers
  9402  ** specified by the blocked connections bundled together into an array.
  9403  ** This gives the application an opportunity to prioritize any actions 
  9404  ** related to the set of unblocked database connections.
  9405  **
  9406  ** <b>Deadlock Detection</b>
  9407  **
  9408  ** Assuming that after registering for an unlock-notify callback a 
  9409  ** database waits for the callback to be issued before taking any further
  9410  ** action (a reasonable assumption), then using this API may cause the
  9411  ** application to deadlock. For example, if connection X is waiting for
  9412  ** connection Y's transaction to be concluded, and similarly connection
  9413  ** Y is waiting on connection X's transaction, then neither connection
  9414  ** will proceed and the system may remain deadlocked indefinitely.
  9415  **
  9416  ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  9417  ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  9418  ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  9419  ** unlock-notify callback is registered. The system is said to be in
  9420  ** a deadlocked state if connection A has registered for an unlock-notify
  9421  ** callback on the conclusion of connection B's transaction, and connection
  9422  ** B has itself registered for an unlock-notify callback when connection
  9423  ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  9424  ** the system is also considered to be deadlocked if connection B has
  9425  ** registered for an unlock-notify callback on the conclusion of connection
  9426  ** C's transaction, where connection C is waiting on connection A. ^Any
  9427  ** number of levels of indirection are allowed.
  9428  **
  9429  ** <b>The "DROP TABLE" Exception</b>
  9430  **
  9431  ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
  9432  ** always appropriate to call sqlite3_unlock_notify(). There is however,
  9433  ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  9434  ** SQLite checks if there are any currently executing SELECT statements
  9435  ** that belong to the same connection. If there are, SQLITE_LOCKED is
  9436  ** returned. In this case there is no "blocking connection", so invoking
  9437  ** sqlite3_unlock_notify() results in the unlock-notify callback being
  9438  ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  9439  ** or "DROP INDEX" query, an infinite loop might be the result.
  9440  **
  9441  ** One way around this problem is to check the extended error code returned
  9442  ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  9443  ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  9444  ** the special "DROP TABLE/INDEX" case, the extended error code is just 
  9445  ** SQLITE_LOCKED.)^
  9446  */
  9447  SQLITE_API int sqlite3_unlock_notify(
  9448    sqlite3 *pBlocked,                          /* Waiting connection */
  9449    void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
  9450    void *pNotifyArg                            /* Argument to pass to xNotify */
  9451  );
  9452  
  9453  
  9454  /*
  9455  ** CAPI3REF: String Comparison
  9456  **
  9457  ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9458  ** and extensions to compare the contents of two buffers containing UTF-8
  9459  ** strings in a case-independent fashion, using the same definition of "case
  9460  ** independence" that SQLite uses internally when comparing identifiers.
  9461  */
  9462  SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9463  SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9464  
  9465  /*
  9466  ** CAPI3REF: String Globbing
  9467  *
  9468  ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9469  ** string X matches the [GLOB] pattern P.
  9470  ** ^The definition of [GLOB] pattern matching used in
  9471  ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9472  ** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
  9473  ** is case sensitive.
  9474  **
  9475  ** Note that this routine returns zero on a match and non-zero if the strings
  9476  ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9477  **
  9478  ** See also: [sqlite3_strlike()].
  9479  */
  9480  SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9481  
  9482  /*
  9483  ** CAPI3REF: String LIKE Matching
  9484  *
  9485  ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9486  ** string X matches the [LIKE] pattern P with escape character E.
  9487  ** ^The definition of [LIKE] pattern matching used in
  9488  ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9489  ** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
  9490  ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9491  ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9492  ** insensitive - equivalent upper and lower case ASCII characters match
  9493  ** one another.
  9494  **
  9495  ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9496  ** only ASCII characters are case folded.
  9497  **
  9498  ** Note that this routine returns zero on a match and non-zero if the strings
  9499  ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9500  **
  9501  ** See also: [sqlite3_strglob()].
  9502  */
  9503  SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9504  
  9505  /*
  9506  ** CAPI3REF: Error Logging Interface
  9507  **
  9508  ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9509  ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9510  ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9511  ** used with [sqlite3_snprintf()] to generate the final output string.
  9512  **
  9513  ** The sqlite3_log() interface is intended for use by extensions such as
  9514  ** virtual tables, collating functions, and SQL functions.  While there is
  9515  ** nothing to prevent an application from calling sqlite3_log(), doing so
  9516  ** is considered bad form.
  9517  **
  9518  ** The zFormat string must not be NULL.
  9519  **
  9520  ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9521  ** will not use dynamically allocated memory.  The log message is stored in
  9522  ** a fixed-length buffer on the stack.  If the log message is longer than
  9523  ** a few hundred characters, it will be truncated to the length of the
  9524  ** buffer.
  9525  */
  9526  SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9527  
  9528  /*
  9529  ** CAPI3REF: Write-Ahead Log Commit Hook
  9530  ** METHOD: sqlite3
  9531  **
  9532  ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9533  ** is invoked each time data is committed to a database in wal mode.
  9534  **
  9535  ** ^(The callback is invoked by SQLite after the commit has taken place and 
  9536  ** the associated write-lock on the database released)^, so the implementation 
  9537  ** may read, write or [checkpoint] the database as required.
  9538  **
  9539  ** ^The first parameter passed to the callback function when it is invoked
  9540  ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9541  ** registering the callback. ^The second is a copy of the database handle.
  9542  ** ^The third parameter is the name of the database that was written to -
  9543  ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9544  ** is the number of pages currently in the write-ahead log file,
  9545  ** including those that were just committed.
  9546  **
  9547  ** The callback function should normally return [SQLITE_OK].  ^If an error
  9548  ** code is returned, that error will propagate back up through the
  9549  ** SQLite code base to cause the statement that provoked the callback
  9550  ** to report an error, though the commit will have still occurred. If the
  9551  ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9552  ** that does not correspond to any valid SQLite error code, the results
  9553  ** are undefined.
  9554  **
  9555  ** A single database handle may have at most a single write-ahead log callback 
  9556  ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9557  ** previously registered write-ahead log callback. ^Note that the
  9558  ** [sqlite3_wal_autocheckpoint()] interface and the
  9559  ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9560  ** overwrite any prior [sqlite3_wal_hook()] settings.
  9561  */
  9562  SQLITE_API void *sqlite3_wal_hook(
  9563    sqlite3*, 
  9564    int(*)(void *,sqlite3*,const char*,int),
  9565    void*
  9566  );
  9567  
  9568  /*
  9569  ** CAPI3REF: Configure an auto-checkpoint
  9570  ** METHOD: sqlite3
  9571  **
  9572  ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9573  ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9574  ** to automatically [checkpoint]
  9575  ** after committing a transaction if there are N or
  9576  ** more frames in the [write-ahead log] file.  ^Passing zero or 
  9577  ** a negative value as the nFrame parameter disables automatic
  9578  ** checkpoints entirely.
  9579  **
  9580  ** ^The callback registered by this function replaces any existing callback
  9581  ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
  9582  ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9583  ** configured by this function.
  9584  **
  9585  ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9586  ** from SQL.
  9587  **
  9588  ** ^Checkpoints initiated by this mechanism are
  9589  ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9590  **
  9591  ** ^Every new [database connection] defaults to having the auto-checkpoint
  9592  ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9593  ** pages.  The use of this interface
  9594  ** is only necessary if the default setting is found to be suboptimal
  9595  ** for a particular application.
  9596  */
  9597  SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9598  
  9599  /*
  9600  ** CAPI3REF: Checkpoint a database
  9601  ** METHOD: sqlite3
  9602  **
  9603  ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9604  ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9605  **
  9606  ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
  9607  ** [write-ahead log] for database X on [database connection] D to be
  9608  ** transferred into the database file and for the write-ahead log to
  9609  ** be reset.  See the [checkpointing] documentation for addition
  9610  ** information.
  9611  **
  9612  ** This interface used to be the only way to cause a checkpoint to
  9613  ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9614  ** interface was added.  This interface is retained for backwards
  9615  ** compatibility and as a convenience for applications that need to manually
  9616  ** start a callback but which do not need the full power (and corresponding
  9617  ** complication) of [sqlite3_wal_checkpoint_v2()].
  9618  */
  9619  SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9620  
  9621  /*
  9622  ** CAPI3REF: Checkpoint a database
  9623  ** METHOD: sqlite3
  9624  **
  9625  ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9626  ** operation on database X of [database connection] D in mode M.  Status
  9627  ** information is written back into integers pointed to by L and C.)^
  9628  ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9629  **
  9630  ** <dl>
  9631  ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9632  **   ^Checkpoint as many frames as possible without waiting for any database 
  9633  **   readers or writers to finish, then sync the database file if all frames 
  9634  **   in the log were checkpointed. ^The [busy-handler callback]
  9635  **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
  9636  **   ^On the other hand, passive mode might leave the checkpoint unfinished
  9637  **   if there are concurrent readers or writers.
  9638  **
  9639  ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9640  **   ^This mode blocks (it invokes the
  9641  **   [sqlite3_busy_handler|busy-handler callback]) until there is no
  9642  **   database writer and all readers are reading from the most recent database
  9643  **   snapshot. ^It then checkpoints all frames in the log file and syncs the
  9644  **   database file. ^This mode blocks new database writers while it is pending,
  9645  **   but new database readers are allowed to continue unimpeded.
  9646  **
  9647  ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9648  **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9649  **   that after checkpointing the log file it blocks (calls the 
  9650  **   [busy-handler callback])
  9651  **   until all readers are reading from the database file only. ^This ensures 
  9652  **   that the next writer will restart the log file from the beginning.
  9653  **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9654  **   database writer attempts while it is pending, but does not impede readers.
  9655  **
  9656  ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9657  **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9658  **   addition that it also truncates the log file to zero bytes just prior
  9659  **   to a successful return.
  9660  ** </dl>
  9661  **
  9662  ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9663  ** the log file or to -1 if the checkpoint could not run because
  9664  ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9665  ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9666  ** log file (including any that were already checkpointed before the function
  9667  ** was called) or to -1 if the checkpoint could not run due to an error or
  9668  ** because the database is not in WAL mode. ^Note that upon successful
  9669  ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9670  ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9671  **
  9672  ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9673  ** any other process is running a checkpoint operation at the same time, the 
  9674  ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
  9675  ** busy-handler configured, it will not be invoked in this case.
  9676  **
  9677  ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
  9678  ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9679  ** obtained immediately, and a busy-handler is configured, it is invoked and
  9680  ** the writer lock retried until either the busy-handler returns 0 or the lock
  9681  ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9682  ** database readers as described above. ^If the busy-handler returns 0 before
  9683  ** the writer lock is obtained or while waiting for database readers, the
  9684  ** checkpoint operation proceeds from that point in the same way as 
  9685  ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
  9686  ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9687  **
  9688  ** ^If parameter zDb is NULL or points to a zero length string, then the
  9689  ** specified operation is attempted on all WAL databases [attached] to 
  9690  ** [database connection] db.  In this case the
  9691  ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
  9692  ** an SQLITE_BUSY error is encountered when processing one or more of the 
  9693  ** attached WAL databases, the operation is still attempted on any remaining 
  9694  ** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
  9695  ** error occurs while processing an attached database, processing is abandoned 
  9696  ** and the error code is returned to the caller immediately. ^If no error 
  9697  ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
  9698  ** databases, SQLITE_OK is returned.
  9699  **
  9700  ** ^If database zDb is the name of an attached database that is not in WAL
  9701  ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9702  ** zDb is not NULL (or a zero length string) and is not the name of any
  9703  ** attached database, SQLITE_ERROR is returned to the caller.
  9704  **
  9705  ** ^Unless it returns SQLITE_MISUSE,
  9706  ** the sqlite3_wal_checkpoint_v2() interface
  9707  ** sets the error information that is queried by
  9708  ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9709  **
  9710  ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9711  ** from SQL.
  9712  */
  9713  SQLITE_API int sqlite3_wal_checkpoint_v2(
  9714    sqlite3 *db,                    /* Database handle */
  9715    const char *zDb,                /* Name of attached database (or NULL) */
  9716    int eMode,                      /* SQLITE_CHECKPOINT_* value */
  9717    int *pnLog,                     /* OUT: Size of WAL log in frames */
  9718    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
  9719  );
  9720  
  9721  /*
  9722  ** CAPI3REF: Checkpoint Mode Values
  9723  ** KEYWORDS: {checkpoint mode}
  9724  **
  9725  ** These constants define all valid values for the "checkpoint mode" passed
  9726  ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9727  ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9728  ** meaning of each of these checkpoint modes.
  9729  */
  9730  #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
  9731  #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
  9732  #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
  9733  #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
  9734  
  9735  /*
  9736  ** CAPI3REF: Virtual Table Interface Configuration
  9737  **
  9738  ** This function may be called by either the [xConnect] or [xCreate] method
  9739  ** of a [virtual table] implementation to configure
  9740  ** various facets of the virtual table interface.
  9741  **
  9742  ** If this interface is invoked outside the context of an xConnect or
  9743  ** xCreate virtual table method then the behavior is undefined.
  9744  **
  9745  ** At present, there is only one option that may be configured using
  9746  ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
  9747  ** may be added in the future.
  9748  */
  9749  SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9750  
  9751  /*
  9752  ** CAPI3REF: Virtual Table Configuration Options
  9753  **
  9754  ** These macros define the various options to the
  9755  ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9756  ** can use to customize and optimize their behavior.
  9757  **
  9758  ** <dl>
  9759  ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9760  ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9761  ** <dd>Calls of the form
  9762  ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9763  ** where X is an integer.  If X is zero, then the [virtual table] whose
  9764  ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9765  ** support constraints.  In this configuration (which is the default) if
  9766  ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9767  ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9768  ** specified as part of the users SQL statement, regardless of the actual
  9769  ** ON CONFLICT mode specified.
  9770  **
  9771  ** If X is non-zero, then the virtual table implementation guarantees
  9772  ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9773  ** any modifications to internal or persistent data structures have been made.
  9774  ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
  9775  ** is able to roll back a statement or database transaction, and abandon
  9776  ** or continue processing the current SQL statement as appropriate. 
  9777  ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9778  ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9779  ** had been ABORT.
  9780  **
  9781  ** Virtual table implementations that are required to handle OR REPLACE
  9782  ** must do so within the [xUpdate] method. If a call to the 
  9783  ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
  9784  ** CONFLICT policy is REPLACE, the virtual table implementation should 
  9785  ** silently replace the appropriate rows within the xUpdate callback and
  9786  ** return SQLITE_OK. Or, if this is not possible, it may return
  9787  ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
  9788  ** constraint handling.
  9789  ** </dl>
  9790  */
  9791  #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9792  
  9793  /*
  9794  ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9795  **
  9796  ** This function may only be called from within a call to the [xUpdate] method
  9797  ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9798  ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9799  ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9800  ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9801  ** [virtual table].
  9802  */
  9803  SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9804  
  9805  /*
  9806  ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9807  **
  9808  ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9809  ** method of a [virtual table], then it returns true if and only if the
  9810  ** column is being fetched as part of an UPDATE operation during which the
  9811  ** column value will not change.  Applications might use this to substitute
  9812  ** a return value that is less expensive to compute and that the corresponding
  9813  ** [xUpdate] method understands as a "no-change" value.
  9814  **
  9815  ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9816  ** the column is not changed by the UPDATE statement, then the xColumn
  9817  ** method can optionally return without setting a result, without calling
  9818  ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9819  ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9820  ** same column in the [xUpdate] method.
  9821  */
  9822  SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9823  
  9824  /*
  9825  ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9826  **
  9827  ** This function may only be called from within a call to the [xBestIndex]
  9828  ** method of a [virtual table]. 
  9829  **
  9830  ** The first argument must be the sqlite3_index_info object that is the
  9831  ** first parameter to the xBestIndex() method. The second argument must be
  9832  ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9833  ** structure passed to xBestIndex. This function returns a pointer to a buffer 
  9834  ** containing the name of the collation sequence for the corresponding
  9835  ** constraint.
  9836  */
  9837  SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9838  
  9839  /*
  9840  ** CAPI3REF: Conflict resolution modes
  9841  ** KEYWORDS: {conflict resolution mode}
  9842  **
  9843  ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9844  ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9845  ** is for the SQL statement being evaluated.
  9846  **
  9847  ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9848  ** return value from the [sqlite3_set_authorizer()] callback and that
  9849  ** [SQLITE_ABORT] is also a [result code].
  9850  */
  9851  #define SQLITE_ROLLBACK 1
  9852  /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9853  #define SQLITE_FAIL     3
  9854  /* #define SQLITE_ABORT 4  // Also an error code */
  9855  #define SQLITE_REPLACE  5
  9856  
  9857  /*
  9858  ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9859  ** KEYWORDS: {scanstatus options}
  9860  **
  9861  ** The following constants can be used for the T parameter to the
  9862  ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
  9863  ** different metric for sqlite3_stmt_scanstatus() to return.
  9864  **
  9865  ** When the value returned to V is a string, space to hold that string is
  9866  ** managed by the prepared statement S and will be automatically freed when
  9867  ** S is finalized.
  9868  **
  9869  ** <dl>
  9870  ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9871  ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9872  ** set to the total number of times that the X-th loop has run.</dd>
  9873  **
  9874  ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9875  ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9876  ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9877  **
  9878  ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9879  ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9880  ** query planner's estimate for the average number of rows output from each
  9881  ** iteration of the X-th loop.  If the query planner's estimates was accurate,
  9882  ** then this value will approximate the quotient NVISIT/NLOOP and the
  9883  ** product of this value for all prior loops with the same SELECTID will
  9884  ** be the NLOOP value for the current loop.
  9885  **
  9886  ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9887  ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9888  ** to a zero-terminated UTF-8 string containing the name of the index or table
  9889  ** used for the X-th loop.
  9890  **
  9891  ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9892  ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9893  ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9894  ** description for the X-th loop.
  9895  **
  9896  ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9897  ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9898  ** "select-id" for the X-th loop.  The select-id identifies which query or
  9899  ** subquery the loop is part of.  The main query has a select-id of zero.
  9900  ** The select-id is the same value as is output in the first column
  9901  ** of an [EXPLAIN QUERY PLAN] query.
  9902  ** </dl>
  9903  */
  9904  #define SQLITE_SCANSTAT_NLOOP    0
  9905  #define SQLITE_SCANSTAT_NVISIT   1
  9906  #define SQLITE_SCANSTAT_EST      2
  9907  #define SQLITE_SCANSTAT_NAME     3
  9908  #define SQLITE_SCANSTAT_EXPLAIN  4
  9909  #define SQLITE_SCANSTAT_SELECTID 5
  9910  
  9911  /*
  9912  ** CAPI3REF: Prepared Statement Scan Status
  9913  ** METHOD: sqlite3_stmt
  9914  **
  9915  ** This interface returns information about the predicted and measured
  9916  ** performance for pStmt.  Advanced applications can use this
  9917  ** interface to compare the predicted and the measured performance and
  9918  ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9919  **
  9920  ** Since this interface is expected to be rarely used, it is only
  9921  ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9922  ** compile-time option.
  9923  **
  9924  ** The "iScanStatusOp" parameter determines which status information to return.
  9925  ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9926  ** of this interface is undefined.
  9927  ** ^The requested measurement is written into a variable pointed to by
  9928  ** the "pOut" parameter.
  9929  ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9930  ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9931  ** zero or greater than or equal to the total number of loops used to implement
  9932  ** the statement - a non-zero value is returned and the variable that pOut
  9933  ** points to is unchanged.
  9934  **
  9935  ** ^Statistics might not be available for all loops in all statements. ^In cases
  9936  ** where there exist loops with no available statistics, this function behaves
  9937  ** as if the loop did not exist - it returns non-zero and leave the variable
  9938  ** that pOut points to unchanged.
  9939  **
  9940  ** See also: [sqlite3_stmt_scanstatus_reset()]
  9941  */
  9942  SQLITE_API int sqlite3_stmt_scanstatus(
  9943    sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
  9944    int idx,                  /* Index of loop to report on */
  9945    int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
  9946    void *pOut                /* Result written here */
  9947  );     
  9948  
  9949  /*
  9950  ** CAPI3REF: Zero Scan-Status Counters
  9951  ** METHOD: sqlite3_stmt
  9952  **
  9953  ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9954  **
  9955  ** This API is only available if the library is built with pre-processor
  9956  ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9957  */
  9958  SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9959  
  9960  /*
  9961  ** CAPI3REF: Flush caches to disk mid-transaction
  9962  **
  9963  ** ^If a write-transaction is open on [database connection] D when the
  9964  ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9965  ** pages in the pager-cache that are not currently in use are written out 
  9966  ** to disk. A dirty page may be in use if a database cursor created by an
  9967  ** active SQL statement is reading from it, or if it is page 1 of a database
  9968  ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
  9969  ** interface flushes caches for all schemas - "main", "temp", and
  9970  ** any [attached] databases.
  9971  **
  9972  ** ^If this function needs to obtain extra database locks before dirty pages 
  9973  ** can be flushed to disk, it does so. ^If those locks cannot be obtained 
  9974  ** immediately and there is a busy-handler callback configured, it is invoked
  9975  ** in the usual manner. ^If the required lock still cannot be obtained, then
  9976  ** the database is skipped and an attempt made to flush any dirty pages
  9977  ** belonging to the next (if any) database. ^If any databases are skipped
  9978  ** because locks cannot be obtained, but no other error occurs, this
  9979  ** function returns SQLITE_BUSY.
  9980  **
  9981  ** ^If any other error occurs while flushing dirty pages to disk (for
  9982  ** example an IO error or out-of-memory condition), then processing is
  9983  ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9984  **
  9985  ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9986  **
  9987  ** ^This function does not set the database handle error code or message
  9988  ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9989  */
  9990  SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9991  
  9992  /*
  9993  ** CAPI3REF: The pre-update hook.
  9994  **
  9995  ** ^These interfaces are only available if SQLite is compiled using the
  9996  ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9997  **
  9998  ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9999  ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
 10000  ** on a database table.
 10001  ** ^At most one preupdate hook may be registered at a time on a single
 10002  ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
 10003  ** the previous setting.
 10004  ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
 10005  ** with a NULL pointer as the second parameter.
 10006  ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
 10007  ** the first parameter to callbacks.
 10008  **
 10009  ** ^The preupdate hook only fires for changes to real database tables; the
 10010  ** preupdate hook is not invoked for changes to [virtual tables] or to
 10011  ** system tables like sqlite_master or sqlite_stat1.
 10012  **
 10013  ** ^The second parameter to the preupdate callback is a pointer to
 10014  ** the [database connection] that registered the preupdate hook.
 10015  ** ^The third parameter to the preupdate callback is one of the constants
 10016  ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
 10017  ** kind of update operation that is about to occur.
 10018  ** ^(The fourth parameter to the preupdate callback is the name of the
 10019  ** database within the database connection that is being modified.  This
 10020  ** will be "main" for the main database or "temp" for TEMP tables or 
 10021  ** the name given after the AS keyword in the [ATTACH] statement for attached
 10022  ** databases.)^
 10023  ** ^The fifth parameter to the preupdate callback is the name of the
 10024  ** table that is being modified.
 10025  **
 10026  ** For an UPDATE or DELETE operation on a [rowid table], the sixth
 10027  ** parameter passed to the preupdate callback is the initial [rowid] of the 
 10028  ** row being modified or deleted. For an INSERT operation on a rowid table,
 10029  ** or any operation on a WITHOUT ROWID table, the value of the sixth 
 10030  ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
 10031  ** seventh parameter is the final rowid value of the row being inserted
 10032  ** or updated. The value of the seventh parameter passed to the callback
 10033  ** function is not defined for operations on WITHOUT ROWID tables, or for
 10034  ** INSERT operations on rowid tables.
 10035  **
 10036  ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
 10037  ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
 10038  ** provide additional information about a preupdate event. These routines
 10039  ** may only be called from within a preupdate callback.  Invoking any of
 10040  ** these routines from outside of a preupdate callback or with a
 10041  ** [database connection] pointer that is different from the one supplied
 10042  ** to the preupdate callback results in undefined and probably undesirable
 10043  ** behavior.
 10044  **
 10045  ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
 10046  ** in the row that is being inserted, updated, or deleted.
 10047  **
 10048  ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
 10049  ** a [protected sqlite3_value] that contains the value of the Nth column of
 10050  ** the table row before it is updated.  The N parameter must be between 0
 10051  ** and one less than the number of columns or the behavior will be
 10052  ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
 10053  ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
 10054  ** behavior is undefined.  The [sqlite3_value] that P points to
 10055  ** will be destroyed when the preupdate callback returns.
 10056  **
 10057  ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
 10058  ** a [protected sqlite3_value] that contains the value of the Nth column of
 10059  ** the table row after it is updated.  The N parameter must be between 0
 10060  ** and one less than the number of columns or the behavior will be
 10061  ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
 10062  ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
 10063  ** behavior is undefined.  The [sqlite3_value] that P points to
 10064  ** will be destroyed when the preupdate callback returns.
 10065  **
 10066  ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
 10067  ** callback was invoked as a result of a direct insert, update, or delete
 10068  ** operation; or 1 for inserts, updates, or deletes invoked by top-level 
 10069  ** triggers; or 2 for changes resulting from triggers called by top-level
 10070  ** triggers; and so forth.
 10071  **
 10072  ** See also:  [sqlite3_update_hook()]
 10073  */
 10074  #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
 10075  SQLITE_API void *sqlite3_preupdate_hook(
 10076    sqlite3 *db,
 10077    void(*xPreUpdate)(
 10078      void *pCtx,                   /* Copy of third arg to preupdate_hook() */
 10079      sqlite3 *db,                  /* Database handle */
 10080      int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
 10081      char const *zDb,              /* Database name */
 10082      char const *zName,            /* Table name */
 10083      sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
 10084      sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
 10085    ),
 10086    void*
 10087  );
 10088  SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
 10089  SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
 10090  SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
 10091  SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
 10092  #endif
 10093  
 10094  /*
 10095  ** CAPI3REF: Low-level system error code
 10096  **
 10097  ** ^Attempt to return the underlying operating system error code or error
 10098  ** number that caused the most recent I/O error or failure to open a file.
 10099  ** The return value is OS-dependent.  For example, on unix systems, after
 10100  ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
 10101  ** called to get back the underlying "errno" that caused the problem, such
 10102  ** as ENOSPC, EAUTH, EISDIR, and so forth.  
 10103  */
 10104  SQLITE_API int sqlite3_system_errno(sqlite3*);
 10105  
 10106  /*
 10107  ** CAPI3REF: Database Snapshot
 10108  ** KEYWORDS: {snapshot} {sqlite3_snapshot}
 10109  **
 10110  ** An instance of the snapshot object records the state of a [WAL mode]
 10111  ** database for some specific point in history.
 10112  **
 10113  ** In [WAL mode], multiple [database connections] that are open on the
 10114  ** same database file can each be reading a different historical version
 10115  ** of the database file.  When a [database connection] begins a read
 10116  ** transaction, that connection sees an unchanging copy of the database
 10117  ** as it existed for the point in time when the transaction first started.
 10118  ** Subsequent changes to the database from other connections are not seen
 10119  ** by the reader until a new read transaction is started.
 10120  **
 10121  ** The sqlite3_snapshot object records state information about an historical
 10122  ** version of the database file so that it is possible to later open a new read
 10123  ** transaction that sees that historical version of the database rather than
 10124  ** the most recent version.
 10125  */
 10126  typedef struct sqlite3_snapshot {
 10127    unsigned char hidden[48];
 10128  } sqlite3_snapshot;
 10129  
 10130  /*
 10131  ** CAPI3REF: Record A Database Snapshot
 10132  ** CONSTRUCTOR: sqlite3_snapshot
 10133  **
 10134  ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
 10135  ** new [sqlite3_snapshot] object that records the current state of
 10136  ** schema S in database connection D.  ^On success, the
 10137  ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
 10138  ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
 10139  ** If there is not already a read-transaction open on schema S when
 10140  ** this function is called, one is opened automatically. 
 10141  **
 10142  ** The following must be true for this function to succeed. If any of
 10143  ** the following statements are false when sqlite3_snapshot_get() is
 10144  ** called, SQLITE_ERROR is returned. The final value of *P is undefined
 10145  ** in this case. 
 10146  **
 10147  ** <ul>
 10148  **   <li> The database handle must not be in [autocommit mode].
 10149  **
 10150  **   <li> Schema S of [database connection] D must be a [WAL mode] database.
 10151  **
 10152  **   <li> There must not be a write transaction open on schema S of database
 10153  **        connection D.
 10154  **
 10155  **   <li> One or more transactions must have been written to the current wal
 10156  **        file since it was created on disk (by any connection). This means
 10157  **        that a snapshot cannot be taken on a wal mode database with no wal 
 10158  **        file immediately after it is first opened. At least one transaction
 10159  **        must be written to it first.
 10160  ** </ul>
 10161  **
 10162  ** This function may also return SQLITE_NOMEM.  If it is called with the
 10163  ** database handle in autocommit mode but fails for some other reason, 
 10164  ** whether or not a read transaction is opened on schema S is undefined.
 10165  **
 10166  ** The [sqlite3_snapshot] object returned from a successful call to
 10167  ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
 10168  ** to avoid a memory leak.
 10169  **
 10170  ** The [sqlite3_snapshot_get()] interface is only available when the
 10171  ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
 10172  */
 10173  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
 10174    sqlite3 *db,
 10175    const char *zSchema,
 10176    sqlite3_snapshot **ppSnapshot
 10177  );
 10178  
 10179  /*
 10180  ** CAPI3REF: Start a read transaction on an historical snapshot
 10181  ** METHOD: sqlite3_snapshot
 10182  **
 10183  ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read 
 10184  ** transaction or upgrades an existing one for schema S of 
 10185  ** [database connection] D such that the read transaction refers to 
 10186  ** historical [snapshot] P, rather than the most recent change to the 
 10187  ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK 
 10188  ** on success or an appropriate [error code] if it fails.
 10189  **
 10190  ** ^In order to succeed, the database connection must not be in 
 10191  ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
 10192  ** is already a read transaction open on schema S, then the database handle
 10193  ** must have no active statements (SELECT statements that have been passed
 10194  ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). 
 10195  ** SQLITE_ERROR is returned if either of these conditions is violated, or
 10196  ** if schema S does not exist, or if the snapshot object is invalid.
 10197  **
 10198  ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
 10199  ** snapshot has been overwritten by a [checkpoint]. In this case 
 10200  ** SQLITE_ERROR_SNAPSHOT is returned.
 10201  **
 10202  ** If there is already a read transaction open when this function is 
 10203  ** invoked, then the same read transaction remains open (on the same
 10204  ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
 10205  ** is returned. If another error code - for example SQLITE_PROTOCOL or an
 10206  ** SQLITE_IOERR error code - is returned, then the final state of the
 10207  ** read transaction is undefined. If SQLITE_OK is returned, then the 
 10208  ** read transaction is now open on database snapshot P.
 10209  **
 10210  ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
 10211  ** database connection D does not know that the database file for
 10212  ** schema S is in [WAL mode].  A database connection might not know
 10213  ** that the database file is in [WAL mode] if there has been no prior
 10214  ** I/O on that database connection, or if the database entered [WAL mode] 
 10215  ** after the most recent I/O on the database connection.)^
 10216  ** (Hint: Run "[PRAGMA application_id]" against a newly opened
 10217  ** database connection in order to make it ready to use snapshots.)
 10218  **
 10219  ** The [sqlite3_snapshot_open()] interface is only available when the
 10220  ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
 10221  */
 10222  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
 10223    sqlite3 *db,
 10224    const char *zSchema,
 10225    sqlite3_snapshot *pSnapshot
 10226  );
 10227  
 10228  /*
 10229  ** CAPI3REF: Destroy a snapshot
 10230  ** DESTRUCTOR: sqlite3_snapshot
 10231  **
 10232  ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
 10233  ** The application must eventually free every [sqlite3_snapshot] object
 10234  ** using this routine to avoid a memory leak.
 10235  **
 10236  ** The [sqlite3_snapshot_free()] interface is only available when the
 10237  ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
 10238  */
 10239  SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
 10240  
 10241  /*
 10242  ** CAPI3REF: Compare the ages of two snapshot handles.
 10243  ** METHOD: sqlite3_snapshot
 10244  **
 10245  ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
 10246  ** of two valid snapshot handles. 
 10247  **
 10248  ** If the two snapshot handles are not associated with the same database 
 10249  ** file, the result of the comparison is undefined. 
 10250  **
 10251  ** Additionally, the result of the comparison is only valid if both of the
 10252  ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
 10253  ** last time the wal file was deleted. The wal file is deleted when the
 10254  ** database is changed back to rollback mode or when the number of database
 10255  ** clients drops to zero. If either snapshot handle was obtained before the 
 10256  ** wal file was last deleted, the value returned by this function 
 10257  ** is undefined.
 10258  **
 10259  ** Otherwise, this API returns a negative value if P1 refers to an older
 10260  ** snapshot than P2, zero if the two handles refer to the same database
 10261  ** snapshot, and a positive value if P1 is a newer snapshot than P2.
 10262  **
 10263  ** This interface is only available if SQLite is compiled with the
 10264  ** [SQLITE_ENABLE_SNAPSHOT] option.
 10265  */
 10266  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
 10267    sqlite3_snapshot *p1,
 10268    sqlite3_snapshot *p2
 10269  );
 10270  
 10271  /*
 10272  ** CAPI3REF: Recover snapshots from a wal file
 10273  ** METHOD: sqlite3_snapshot
 10274  **
 10275  ** If a [WAL file] remains on disk after all database connections close
 10276  ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
 10277  ** or because the last process to have the database opened exited without
 10278  ** calling [sqlite3_close()]) and a new connection is subsequently opened
 10279  ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
 10280  ** will only be able to open the last transaction added to the WAL file
 10281  ** even though the WAL file contains other valid transactions.
 10282  **
 10283  ** This function attempts to scan the WAL file associated with database zDb
 10284  ** of database handle db and make all valid snapshots available to
 10285  ** sqlite3_snapshot_open(). It is an error if there is already a read
 10286  ** transaction open on the database, or if the database is not a WAL mode
 10287  ** database.
 10288  **
 10289  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 10290  **
 10291  ** This interface is only available if SQLite is compiled with the
 10292  ** [SQLITE_ENABLE_SNAPSHOT] option.
 10293  */
 10294  SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
 10295  
 10296  /*
 10297  ** CAPI3REF: Serialize a database
 10298  **
 10299  ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
 10300  ** that is a serialization of the S database on [database connection] D.
 10301  ** If P is not a NULL pointer, then the size of the database in bytes
 10302  ** is written into *P.
 10303  **
 10304  ** For an ordinary on-disk database file, the serialization is just a
 10305  ** copy of the disk file.  For an in-memory database or a "TEMP" database,
 10306  ** the serialization is the same sequence of bytes which would be written
 10307  ** to disk if that database where backed up to disk.
 10308  **
 10309  ** The usual case is that sqlite3_serialize() copies the serialization of
 10310  ** the database into memory obtained from [sqlite3_malloc64()] and returns
 10311  ** a pointer to that memory.  The caller is responsible for freeing the
 10312  ** returned value to avoid a memory leak.  However, if the F argument
 10313  ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
 10314  ** are made, and the sqlite3_serialize() function will return a pointer
 10315  ** to the contiguous memory representation of the database that SQLite
 10316  ** is currently using for that database, or NULL if the no such contiguous
 10317  ** memory representation of the database exists.  A contiguous memory
 10318  ** representation of the database will usually only exist if there has
 10319  ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
 10320  ** values of D and S.
 10321  ** The size of the database is written into *P even if the 
 10322  ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
 10323  ** of the database exists.
 10324  **
 10325  ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
 10326  ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
 10327  ** allocation error occurs.
 10328  **
 10329  ** This interface is only available if SQLite is compiled with the
 10330  ** [SQLITE_ENABLE_DESERIALIZE] option.
 10331  */
 10332  SQLITE_API unsigned char *sqlite3_serialize(
 10333    sqlite3 *db,           /* The database connection */
 10334    const char *zSchema,   /* Which DB to serialize. ex: "main", "temp", ... */
 10335    sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
 10336    unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */
 10337  );
 10338  
 10339  /*
 10340  ** CAPI3REF: Flags for sqlite3_serialize
 10341  **
 10342  ** Zero or more of the following constants can be OR-ed together for
 10343  ** the F argument to [sqlite3_serialize(D,S,P,F)].
 10344  **
 10345  ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
 10346  ** a pointer to contiguous in-memory database that it is currently using,
 10347  ** without making a copy of the database.  If SQLite is not currently using
 10348  ** a contiguous in-memory database, then this option causes
 10349  ** [sqlite3_serialize()] to return a NULL pointer.  SQLite will only be
 10350  ** using a contiguous in-memory database if it has been initialized by a
 10351  ** prior call to [sqlite3_deserialize()].
 10352  */
 10353  #define SQLITE_SERIALIZE_NOCOPY 0x001   /* Do no memory allocations */
 10354  
 10355  /*
 10356  ** CAPI3REF: Deserialize a database
 10357  **
 10358  ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the 
 10359  ** [database connection] D to disconnect from database S and then
 10360  ** reopen S as an in-memory database based on the serialization contained
 10361  ** in P.  The serialized database P is N bytes in size.  M is the size of
 10362  ** the buffer P, which might be larger than N.  If M is larger than N, and
 10363  ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
 10364  ** permitted to add content to the in-memory database as long as the total
 10365  ** size does not exceed M bytes.
 10366  **
 10367  ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
 10368  ** invoke sqlite3_free() on the serialization buffer when the database
 10369  ** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
 10370  ** SQLite will try to increase the buffer size using sqlite3_realloc64()
 10371  ** if writes on the database cause it to grow larger than M bytes.
 10372  **
 10373  ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
 10374  ** database is currently in a read transaction or is involved in a backup
 10375  ** operation.
 10376  **
 10377  ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the 
 10378  ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
 10379  ** [sqlite3_free()] is invoked on argument P prior to returning.
 10380  **
 10381  ** This interface is only available if SQLite is compiled with the
 10382  ** [SQLITE_ENABLE_DESERIALIZE] option.
 10383  */
 10384  SQLITE_API int sqlite3_deserialize(
 10385    sqlite3 *db,            /* The database connection */
 10386    const char *zSchema,    /* Which DB to reopen with the deserialization */
 10387    unsigned char *pData,   /* The serialized database content */
 10388    sqlite3_int64 szDb,     /* Number bytes in the deserialization */
 10389    sqlite3_int64 szBuf,    /* Total size of buffer pData[] */
 10390    unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */
 10391  );
 10392  
 10393  /*
 10394  ** CAPI3REF: Flags for sqlite3_deserialize()
 10395  **
 10396  ** The following are allowed values for 6th argument (the F argument) to
 10397  ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
 10398  **
 10399  ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
 10400  ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
 10401  ** and that SQLite should take ownership of this memory and automatically
 10402  ** free it when it has finished using it.  Without this flag, the caller
 10403  ** is responsible for freeing any dynamically allocated memory.
 10404  **
 10405  ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
 10406  ** grow the size of the database using calls to [sqlite3_realloc64()].  This
 10407  ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
 10408  ** Without this flag, the deserialized database cannot increase in size beyond
 10409  ** the number of bytes specified by the M parameter.
 10410  **
 10411  ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
 10412  ** should be treated as read-only.
 10413  */
 10414  #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
 10415  #define SQLITE_DESERIALIZE_RESIZEABLE  2 /* Resize using sqlite3_realloc64() */
 10416  #define SQLITE_DESERIALIZE_READONLY    4 /* Database is read-only */
 10417  
 10418  /*
 10419  ** Undo the hack that converts floating point types to integer for
 10420  ** builds on processors without floating point support.
 10421  */
 10422  #ifdef SQLITE_OMIT_FLOATING_POINT
 10423  # undef double
 10424  #endif
 10425  
 10426  #if 0
 10427  }  /* End of the 'extern "C"' block */
 10428  #endif
 10429  #endif /* SQLITE3_H */
 10430  
 10431  /******** Begin file sqlite3rtree.h *********/
 10432  /*
 10433  ** 2010 August 30
 10434  **
 10435  ** The author disclaims copyright to this source code.  In place of
 10436  ** a legal notice, here is a blessing:
 10437  **
 10438  **    May you do good and not evil.
 10439  **    May you find forgiveness for yourself and forgive others.
 10440  **    May you share freely, never taking more than you give.
 10441  **
 10442  *************************************************************************
 10443  */
 10444  
 10445  #ifndef _SQLITE3RTREE_H_
 10446  #define _SQLITE3RTREE_H_
 10447  
 10448  
 10449  #if 0
 10450  extern "C" {
 10451  #endif
 10452  
 10453  typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
 10454  typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
 10455  
 10456  /* The double-precision datatype used by RTree depends on the
 10457  ** SQLITE_RTREE_INT_ONLY compile-time option.
 10458  */
 10459  #ifdef SQLITE_RTREE_INT_ONLY
 10460    typedef sqlite3_int64 sqlite3_rtree_dbl;
 10461  #else
 10462    typedef double sqlite3_rtree_dbl;
 10463  #endif
 10464  
 10465  /*
 10466  ** Register a geometry callback named zGeom that can be used as part of an
 10467  ** R-Tree geometry query as follows:
 10468  **
 10469  **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
 10470  */
 10471  SQLITE_API int sqlite3_rtree_geometry_callback(
 10472    sqlite3 *db,
 10473    const char *zGeom,
 10474    int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
 10475    void *pContext
 10476  );
 10477  
 10478  
 10479  /*
 10480  ** A pointer to a structure of the following type is passed as the first
 10481  ** argument to callbacks registered using rtree_geometry_callback().
 10482  */
 10483  struct sqlite3_rtree_geometry {
 10484    void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
 10485    int nParam;                     /* Size of array aParam[] */
 10486    sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
 10487    void *pUser;                    /* Callback implementation user data */
 10488    void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
 10489  };
 10490  
 10491  /*
 10492  ** Register a 2nd-generation geometry callback named zScore that can be 
 10493  ** used as part of an R-Tree geometry query as follows:
 10494  **
 10495  **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
 10496  */
 10497  SQLITE_API int sqlite3_rtree_query_callback(
 10498    sqlite3 *db,
 10499    const char *zQueryFunc,
 10500    int (*xQueryFunc)(sqlite3_rtree_query_info*),
 10501    void *pContext,
 10502    void (*xDestructor)(void*)
 10503  );
 10504  
 10505  
 10506  /*
 10507  ** A pointer to a structure of the following type is passed as the 
 10508  ** argument to scored geometry callback registered using
 10509  ** sqlite3_rtree_query_callback().
 10510  **
 10511  ** Note that the first 5 fields of this structure are identical to
 10512  ** sqlite3_rtree_geometry.  This structure is a subclass of
 10513  ** sqlite3_rtree_geometry.
 10514  */
 10515  struct sqlite3_rtree_query_info {
 10516    void *pContext;                   /* pContext from when function registered */
 10517    int nParam;                       /* Number of function parameters */
 10518    sqlite3_rtree_dbl *aParam;        /* value of function parameters */
 10519    void *pUser;                      /* callback can use this, if desired */
 10520    void (*xDelUser)(void*);          /* function to free pUser */
 10521    sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
 10522    unsigned int *anQueue;            /* Number of pending entries in the queue */
 10523    int nCoord;                       /* Number of coordinates */
 10524    int iLevel;                       /* Level of current node or entry */
 10525    int mxLevel;                      /* The largest iLevel value in the tree */
 10526    sqlite3_int64 iRowid;             /* Rowid for current entry */
 10527    sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
 10528    int eParentWithin;                /* Visibility of parent node */
 10529    int eWithin;                      /* OUT: Visibility */
 10530    sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
 10531    /* The following fields are only available in 3.8.11 and later */
 10532    sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
 10533  };
 10534  
 10535  /*
 10536  ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
 10537  */
 10538  #define NOT_WITHIN       0   /* Object completely outside of query region */
 10539  #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
 10540  #define FULLY_WITHIN     2   /* Object fully contained within query region */
 10541  
 10542  
 10543  #if 0
 10544  }  /* end of the 'extern "C"' block */
 10545  #endif
 10546  
 10547  #endif  /* ifndef _SQLITE3RTREE_H_ */
 10548  
 10549  /******** End of sqlite3rtree.h *********/
 10550  /******** Begin file sqlite3session.h *********/
 10551  
 10552  #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
 10553  #define __SQLITESESSION_H_ 1
 10554  
 10555  /*
 10556  ** Make sure we can call this stuff from C++.
 10557  */
 10558  #if 0
 10559  extern "C" {
 10560  #endif
 10561  
 10562  
 10563  /*
 10564  ** CAPI3REF: Session Object Handle
 10565  **
 10566  ** An instance of this object is a [session] that can be used to
 10567  ** record changes to a database.
 10568  */
 10569  typedef struct sqlite3_session sqlite3_session;
 10570  
 10571  /*
 10572  ** CAPI3REF: Changeset Iterator Handle
 10573  **
 10574  ** An instance of this object acts as a cursor for iterating
 10575  ** over the elements of a [changeset] or [patchset].
 10576  */
 10577  typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
 10578  
 10579  /*
 10580  ** CAPI3REF: Create A New Session Object
 10581  ** CONSTRUCTOR: sqlite3_session
 10582  **
 10583  ** Create a new session object attached to database handle db. If successful,
 10584  ** a pointer to the new object is written to *ppSession and SQLITE_OK is
 10585  ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
 10586  ** error code (e.g. SQLITE_NOMEM) is returned.
 10587  **
 10588  ** It is possible to create multiple session objects attached to a single
 10589  ** database handle.
 10590  **
 10591  ** Session objects created using this function should be deleted using the
 10592  ** [sqlite3session_delete()] function before the database handle that they
 10593  ** are attached to is itself closed. If the database handle is closed before
 10594  ** the session object is deleted, then the results of calling any session
 10595  ** module function, including [sqlite3session_delete()] on the session object
 10596  ** are undefined.
 10597  **
 10598  ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
 10599  ** is not possible for an application to register a pre-update hook on a
 10600  ** database handle that has one or more session objects attached. Nor is
 10601  ** it possible to create a session object attached to a database handle for
 10602  ** which a pre-update hook is already defined. The results of attempting 
 10603  ** either of these things are undefined.
 10604  **
 10605  ** The session object will be used to create changesets for tables in
 10606  ** database zDb, where zDb is either "main", or "temp", or the name of an
 10607  ** attached database. It is not an error if database zDb is not attached
 10608  ** to the database when the session object is created.
 10609  */
 10610  SQLITE_API int sqlite3session_create(
 10611    sqlite3 *db,                    /* Database handle */
 10612    const char *zDb,                /* Name of db (e.g. "main") */
 10613    sqlite3_session **ppSession     /* OUT: New session object */
 10614  );
 10615  
 10616  /*
 10617  ** CAPI3REF: Delete A Session Object
 10618  ** DESTRUCTOR: sqlite3_session
 10619  **
 10620  ** Delete a session object previously allocated using 
 10621  ** [sqlite3session_create()]. Once a session object has been deleted, the
 10622  ** results of attempting to use pSession with any other session module
 10623  ** function are undefined.
 10624  **
 10625  ** Session objects must be deleted before the database handle to which they
 10626  ** are attached is closed. Refer to the documentation for 
 10627  ** [sqlite3session_create()] for details.
 10628  */
 10629  SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
 10630  
 10631  
 10632  /*
 10633  ** CAPI3REF: Enable Or Disable A Session Object
 10634  ** METHOD: sqlite3_session
 10635  **
 10636  ** Enable or disable the recording of changes by a session object. When
 10637  ** enabled, a session object records changes made to the database. When
 10638  ** disabled - it does not. A newly created session object is enabled.
 10639  ** Refer to the documentation for [sqlite3session_changeset()] for further
 10640  ** details regarding how enabling and disabling a session object affects
 10641  ** the eventual changesets.
 10642  **
 10643  ** Passing zero to this function disables the session. Passing a value
 10644  ** greater than zero enables it. Passing a value less than zero is a 
 10645  ** no-op, and may be used to query the current state of the session.
 10646  **
 10647  ** The return value indicates the final state of the session object: 0 if 
 10648  ** the session is disabled, or 1 if it is enabled.
 10649  */
 10650  SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 10651  
 10652  /*
 10653  ** CAPI3REF: Set Or Clear the Indirect Change Flag
 10654  ** METHOD: sqlite3_session
 10655  **
 10656  ** Each change recorded by a session object is marked as either direct or
 10657  ** indirect. A change is marked as indirect if either:
 10658  **
 10659  ** <ul>
 10660  **   <li> The session object "indirect" flag is set when the change is
 10661  **        made, or
 10662  **   <li> The change is made by an SQL trigger or foreign key action 
 10663  **        instead of directly as a result of a users SQL statement.
 10664  ** </ul>
 10665  **
 10666  ** If a single row is affected by more than one operation within a session,
 10667  ** then the change is considered indirect if all operations meet the criteria
 10668  ** for an indirect change above, or direct otherwise.
 10669  **
 10670  ** This function is used to set, clear or query the session object indirect
 10671  ** flag.  If the second argument passed to this function is zero, then the
 10672  ** indirect flag is cleared. If it is greater than zero, the indirect flag
 10673  ** is set. Passing a value less than zero does not modify the current value
 10674  ** of the indirect flag, and may be used to query the current state of the 
 10675  ** indirect flag for the specified session object.
 10676  **
 10677  ** The return value indicates the final state of the indirect flag: 0 if 
 10678  ** it is clear, or 1 if it is set.
 10679  */
 10680  SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
 10681  
 10682  /*
 10683  ** CAPI3REF: Attach A Table To A Session Object
 10684  ** METHOD: sqlite3_session
 10685  **
 10686  ** If argument zTab is not NULL, then it is the name of a table to attach
 10687  ** to the session object passed as the first argument. All subsequent changes 
 10688  ** made to the table while the session object is enabled will be recorded. See 
 10689  ** documentation for [sqlite3session_changeset()] for further details.
 10690  **
 10691  ** Or, if argument zTab is NULL, then changes are recorded for all tables
 10692  ** in the database. If additional tables are added to the database (by 
 10693  ** executing "CREATE TABLE" statements) after this call is made, changes for 
 10694  ** the new tables are also recorded.
 10695  **
 10696  ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
 10697  ** defined as part of their CREATE TABLE statement. It does not matter if the 
 10698  ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
 10699  ** KEY may consist of a single column, or may be a composite key.
 10700  ** 
 10701  ** It is not an error if the named table does not exist in the database. Nor
 10702  ** is it an error if the named table does not have a PRIMARY KEY. However,
 10703  ** no changes will be recorded in either of these scenarios.
 10704  **
 10705  ** Changes are not recorded for individual rows that have NULL values stored
 10706  ** in one or more of their PRIMARY KEY columns.
 10707  **
 10708  ** SQLITE_OK is returned if the call completes without error. Or, if an error 
 10709  ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
 10710  **
 10711  ** <h3>Special sqlite_stat1 Handling</h3>
 10712  **
 10713  ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to 
 10714  ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
 10715  **  <pre>
 10716  **  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)  
 10717  **  </pre>
 10718  **
 10719  ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are 
 10720  ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes 
 10721  ** are recorded for rows for which (idx IS NULL) is true. However, for such
 10722  ** rows a zero-length blob (SQL value X'') is stored in the changeset or
 10723  ** patchset instead of a NULL value. This allows such changesets to be
 10724  ** manipulated by legacy implementations of sqlite3changeset_invert(),
 10725  ** concat() and similar.
 10726  **
 10727  ** The sqlite3changeset_apply() function automatically converts the 
 10728  ** zero-length blob back to a NULL value when updating the sqlite_stat1
 10729  ** table. However, if the application calls sqlite3changeset_new(),
 10730  ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset 
 10731  ** iterator directly (including on a changeset iterator passed to a
 10732  ** conflict-handler callback) then the X'' value is returned. The application
 10733  ** must translate X'' to NULL itself if required.
 10734  **
 10735  ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
 10736  ** changes made to the sqlite_stat1 table. Legacy versions of the
 10737  ** sqlite3changeset_apply() function silently ignore any modifications to the
 10738  ** sqlite_stat1 table that are part of a changeset or patchset.
 10739  */
 10740  SQLITE_API int sqlite3session_attach(
 10741    sqlite3_session *pSession,      /* Session object */
 10742    const char *zTab                /* Table name */
 10743  );
 10744  
 10745  /*
 10746  ** CAPI3REF: Set a table filter on a Session Object.
 10747  ** METHOD: sqlite3_session
 10748  **
 10749  ** The second argument (xFilter) is the "filter callback". For changes to rows 
 10750  ** in tables that are not attached to the Session object, the filter is called
 10751  ** to determine whether changes to the table's rows should be tracked or not. 
 10752  ** If xFilter returns 0, changes is not tracked. Note that once a table is 
 10753  ** attached, xFilter will not be called again.
 10754  */
 10755  SQLITE_API void sqlite3session_table_filter(
 10756    sqlite3_session *pSession,      /* Session object */
 10757    int(*xFilter)(
 10758      void *pCtx,                   /* Copy of third arg to _filter_table() */
 10759      const char *zTab              /* Table name */
 10760    ),
 10761    void *pCtx                      /* First argument passed to xFilter */
 10762  );
 10763  
 10764  /*
 10765  ** CAPI3REF: Generate A Changeset From A Session Object
 10766  ** METHOD: sqlite3_session
 10767  **
 10768  ** Obtain a changeset containing changes to the tables attached to the 
 10769  ** session object passed as the first argument. If successful, 
 10770  ** set *ppChangeset to point to a buffer containing the changeset 
 10771  ** and *pnChangeset to the size of the changeset in bytes before returning
 10772  ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
 10773  ** zero and return an SQLite error code.
 10774  **
 10775  ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
 10776  ** each representing a change to a single row of an attached table. An INSERT
 10777  ** change contains the values of each field of a new database row. A DELETE
 10778  ** contains the original values of each field of a deleted database row. An
 10779  ** UPDATE change contains the original values of each field of an updated
 10780  ** database row along with the updated values for each updated non-primary-key
 10781  ** column. It is not possible for an UPDATE change to represent a change that
 10782  ** modifies the values of primary key columns. If such a change is made, it
 10783  ** is represented in a changeset as a DELETE followed by an INSERT.
 10784  **
 10785  ** Changes are not recorded for rows that have NULL values stored in one or 
 10786  ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
 10787  ** no corresponding change is present in the changesets returned by this
 10788  ** function. If an existing row with one or more NULL values stored in
 10789  ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
 10790  ** only an INSERT is appears in the changeset. Similarly, if an existing row
 10791  ** with non-NULL PRIMARY KEY values is updated so that one or more of its
 10792  ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
 10793  ** DELETE change only.
 10794  **
 10795  ** The contents of a changeset may be traversed using an iterator created
 10796  ** using the [sqlite3changeset_start()] API. A changeset may be applied to
 10797  ** a database with a compatible schema using the [sqlite3changeset_apply()]
 10798  ** API.
 10799  **
 10800  ** Within a changeset generated by this function, all changes related to a
 10801  ** single table are grouped together. In other words, when iterating through
 10802  ** a changeset or when applying a changeset to a database, all changes related
 10803  ** to a single table are processed before moving on to the next table. Tables
 10804  ** are sorted in the same order in which they were attached (or auto-attached)
 10805  ** to the sqlite3_session object. The order in which the changes related to
 10806  ** a single table are stored is undefined.
 10807  **
 10808  ** Following a successful call to this function, it is the responsibility of
 10809  ** the caller to eventually free the buffer that *ppChangeset points to using
 10810  ** [sqlite3_free()].
 10811  **
 10812  ** <h3>Changeset Generation</h3>
 10813  **
 10814  ** Once a table has been attached to a session object, the session object
 10815  ** records the primary key values of all new rows inserted into the table.
 10816  ** It also records the original primary key and other column values of any
 10817  ** deleted or updated rows. For each unique primary key value, data is only
 10818  ** recorded once - the first time a row with said primary key is inserted,
 10819  ** updated or deleted in the lifetime of the session.
 10820  **
 10821  ** There is one exception to the previous paragraph: when a row is inserted,
 10822  ** updated or deleted, if one or more of its primary key columns contain a
 10823  ** NULL value, no record of the change is made.
 10824  **
 10825  ** The session object therefore accumulates two types of records - those
 10826  ** that consist of primary key values only (created when the user inserts
 10827  ** a new record) and those that consist of the primary key values and the
 10828  ** original values of other table columns (created when the users deletes
 10829  ** or updates a record).
 10830  **
 10831  ** When this function is called, the requested changeset is created using
 10832  ** both the accumulated records and the current contents of the database
 10833  ** file. Specifically:
 10834  **
 10835  ** <ul>
 10836  **   <li> For each record generated by an insert, the database is queried
 10837  **        for a row with a matching primary key. If one is found, an INSERT
 10838  **        change is added to the changeset. If no such row is found, no change 
 10839  **        is added to the changeset.
 10840  **
 10841  **   <li> For each record generated by an update or delete, the database is 
 10842  **        queried for a row with a matching primary key. If such a row is
 10843  **        found and one or more of the non-primary key fields have been
 10844  **        modified from their original values, an UPDATE change is added to 
 10845  **        the changeset. Or, if no such row is found in the table, a DELETE 
 10846  **        change is added to the changeset. If there is a row with a matching
 10847  **        primary key in the database, but all fields contain their original
 10848  **        values, no change is added to the changeset.
 10849  ** </ul>
 10850  **
 10851  ** This means, amongst other things, that if a row is inserted and then later
 10852  ** deleted while a session object is active, neither the insert nor the delete
 10853  ** will be present in the changeset. Or if a row is deleted and then later a 
 10854  ** row with the same primary key values inserted while a session object is
 10855  ** active, the resulting changeset will contain an UPDATE change instead of
 10856  ** a DELETE and an INSERT.
 10857  **
 10858  ** When a session object is disabled (see the [sqlite3session_enable()] API),
 10859  ** it does not accumulate records when rows are inserted, updated or deleted.
 10860  ** This may appear to have some counter-intuitive effects if a single row
 10861  ** is written to more than once during a session. For example, if a row
 10862  ** is inserted while a session object is enabled, then later deleted while 
 10863  ** the same session object is disabled, no INSERT record will appear in the
 10864  ** changeset, even though the delete took place while the session was disabled.
 10865  ** Or, if one field of a row is updated while a session is disabled, and 
 10866  ** another field of the same row is updated while the session is enabled, the
 10867  ** resulting changeset will contain an UPDATE change that updates both fields.
 10868  */
 10869  SQLITE_API int sqlite3session_changeset(
 10870    sqlite3_session *pSession,      /* Session object */
 10871    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
 10872    void **ppChangeset              /* OUT: Buffer containing changeset */
 10873  );
 10874  
 10875  /*
 10876  ** CAPI3REF: Load The Difference Between Tables Into A Session
 10877  ** METHOD: sqlite3_session
 10878  **
 10879  ** If it is not already attached to the session object passed as the first
 10880  ** argument, this function attaches table zTbl in the same manner as the
 10881  ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
 10882  ** does not have a primary key, this function is a no-op (but does not return
 10883  ** an error).
 10884  **
 10885  ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
 10886  ** attached to the same database handle as the session object that contains 
 10887  ** a table compatible with the table attached to the session by this function.
 10888  ** A table is considered compatible if it:
 10889  **
 10890  ** <ul>
 10891  **   <li> Has the same name,
 10892  **   <li> Has the same set of columns declared in the same order, and
 10893  **   <li> Has the same PRIMARY KEY definition.
 10894  ** </ul>
 10895  **
 10896  ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
 10897  ** are compatible but do not have any PRIMARY KEY columns, it is not an error
 10898  ** but no changes are added to the session object. As with other session
 10899  ** APIs, tables without PRIMARY KEYs are simply ignored.
 10900  **
 10901  ** This function adds a set of changes to the session object that could be
 10902  ** used to update the table in database zFrom (call this the "from-table") 
 10903  ** so that its content is the same as the table attached to the session 
 10904  ** object (call this the "to-table"). Specifically:
 10905  **
 10906  ** <ul>
 10907  **   <li> For each row (primary key) that exists in the to-table but not in 
 10908  **     the from-table, an INSERT record is added to the session object.
 10909  **
 10910  **   <li> For each row (primary key) that exists in the to-table but not in 
 10911  **     the from-table, a DELETE record is added to the session object.
 10912  **
 10913  **   <li> For each row (primary key) that exists in both tables, but features 
 10914  **     different non-PK values in each, an UPDATE record is added to the
 10915  **     session.  
 10916  ** </ul>
 10917  **
 10918  ** To clarify, if this function is called and then a changeset constructed
 10919  ** using [sqlite3session_changeset()], then after applying that changeset to 
 10920  ** database zFrom the contents of the two compatible tables would be 
 10921  ** identical.
 10922  **
 10923  ** It an error if database zFrom does not exist or does not contain the
 10924  ** required compatible table.
 10925  **
 10926  ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
 10927  ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
 10928  ** may be set to point to a buffer containing an English language error 
 10929  ** message. It is the responsibility of the caller to free this buffer using
 10930  ** sqlite3_free().
 10931  */
 10932  SQLITE_API int sqlite3session_diff(
 10933    sqlite3_session *pSession,
 10934    const char *zFromDb,
 10935    const char *zTbl,
 10936    char **pzErrMsg
 10937  );
 10938  
 10939  
 10940  /*
 10941  ** CAPI3REF: Generate A Patchset From A Session Object
 10942  ** METHOD: sqlite3_session
 10943  **
 10944  ** The differences between a patchset and a changeset are that:
 10945  **
 10946  ** <ul>
 10947  **   <li> DELETE records consist of the primary key fields only. The 
 10948  **        original values of other fields are omitted.
 10949  **   <li> The original values of any modified fields are omitted from 
 10950  **        UPDATE records.
 10951  ** </ul>
 10952  **
 10953  ** A patchset blob may be used with up to date versions of all 
 10954  ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), 
 10955  ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
 10956  ** attempting to use a patchset blob with old versions of the
 10957  ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. 
 10958  **
 10959  ** Because the non-primary key "old.*" fields are omitted, no 
 10960  ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
 10961  ** is passed to the sqlite3changeset_apply() API. Other conflict types work
 10962  ** in the same way as for changesets.
 10963  **
 10964  ** Changes within a patchset are ordered in the same way as for changesets
 10965  ** generated by the sqlite3session_changeset() function (i.e. all changes for
 10966  ** a single table are grouped together, tables appear in the order in which
 10967  ** they were attached to the session object).
 10968  */
 10969  SQLITE_API int sqlite3session_patchset(
 10970    sqlite3_session *pSession,      /* Session object */
 10971    int *pnPatchset,                /* OUT: Size of buffer at *ppPatchset */
 10972    void **ppPatchset               /* OUT: Buffer containing patchset */
 10973  );
 10974  
 10975  /*
 10976  ** CAPI3REF: Test if a changeset has recorded any changes.
 10977  **
 10978  ** Return non-zero if no changes to attached tables have been recorded by 
 10979  ** the session object passed as the first argument. Otherwise, if one or 
 10980  ** more changes have been recorded, return zero.
 10981  **
 10982  ** Even if this function returns zero, it is possible that calling
 10983  ** [sqlite3session_changeset()] on the session handle may still return a
 10984  ** changeset that contains no changes. This can happen when a row in 
 10985  ** an attached table is modified and then later on the original values 
 10986  ** are restored. However, if this function returns non-zero, then it is
 10987  ** guaranteed that a call to sqlite3session_changeset() will return a 
 10988  ** changeset containing zero changes.
 10989  */
 10990  SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 10991  
 10992  /*
 10993  ** CAPI3REF: Create An Iterator To Traverse A Changeset 
 10994  ** CONSTRUCTOR: sqlite3_changeset_iter
 10995  **
 10996  ** Create an iterator used to iterate through the contents of a changeset.
 10997  ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
 10998  ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
 10999  ** SQLite error code is returned.
 11000  **
 11001  ** The following functions can be used to advance and query a changeset 
 11002  ** iterator created by this function:
 11003  **
 11004  ** <ul>
 11005  **   <li> [sqlite3changeset_next()]
 11006  **   <li> [sqlite3changeset_op()]
 11007  **   <li> [sqlite3changeset_new()]
 11008  **   <li> [sqlite3changeset_old()]
 11009  ** </ul>
 11010  **
 11011  ** It is the responsibility of the caller to eventually destroy the iterator
 11012  ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
 11013  ** changeset (pChangeset) must remain valid until after the iterator is
 11014  ** destroyed.
 11015  **
 11016  ** Assuming the changeset blob was created by one of the
 11017  ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
 11018  ** [sqlite3changeset_invert()] functions, all changes within the changeset 
 11019  ** that apply to a single table are grouped together. This means that when 
 11020  ** an application iterates through a changeset using an iterator created by 
 11021  ** this function, all changes that relate to a single table are visited 
 11022  ** consecutively. There is no chance that the iterator will visit a change 
 11023  ** the applies to table X, then one for table Y, and then later on visit 
 11024  ** another change for table X.
 11025  **
 11026  ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
 11027  ** may be modified by passing a combination of
 11028  ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
 11029  **
 11030  ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
 11031  ** and therefore subject to change.
 11032  */
 11033  SQLITE_API int sqlite3changeset_start(
 11034    sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 11035    int nChangeset,                 /* Size of changeset blob in bytes */
 11036    void *pChangeset                /* Pointer to blob containing changeset */
 11037  );
 11038  SQLITE_API int sqlite3changeset_start_v2(
 11039    sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 11040    int nChangeset,                 /* Size of changeset blob in bytes */
 11041    void *pChangeset,               /* Pointer to blob containing changeset */
 11042    int flags                       /* SESSION_CHANGESETSTART_* flags */
 11043  );
 11044  
 11045  /*
 11046  ** CAPI3REF: Flags for sqlite3changeset_start_v2
 11047  **
 11048  ** The following flags may passed via the 4th parameter to
 11049  ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
 11050  **
 11051  ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
 11052  **   Invert the changeset while iterating through it. This is equivalent to
 11053  **   inverting a changeset using sqlite3changeset_invert() before applying it.
 11054  **   It is an error to specify this flag with a patchset.
 11055  */
 11056  #define SQLITE_CHANGESETSTART_INVERT        0x0002
 11057  
 11058  
 11059  /*
 11060  ** CAPI3REF: Advance A Changeset Iterator
 11061  ** METHOD: sqlite3_changeset_iter
 11062  **
 11063  ** This function may only be used with iterators created by function
 11064  ** [sqlite3changeset_start()]. If it is called on an iterator passed to
 11065  ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
 11066  ** is returned and the call has no effect.
 11067  **
 11068  ** Immediately after an iterator is created by sqlite3changeset_start(), it
 11069  ** does not point to any change in the changeset. Assuming the changeset
 11070  ** is not empty, the first call to this function advances the iterator to
 11071  ** point to the first change in the changeset. Each subsequent call advances
 11072  ** the iterator to point to the next change in the changeset (if any). If
 11073  ** no error occurs and the iterator points to a valid change after a call
 11074  ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. 
 11075  ** Otherwise, if all changes in the changeset have already been visited,
 11076  ** SQLITE_DONE is returned.
 11077  **
 11078  ** If an error occurs, an SQLite error code is returned. Possible error 
 11079  ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or 
 11080  ** SQLITE_NOMEM.
 11081  */
 11082  SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
 11083  
 11084  /*
 11085  ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
 11086  ** METHOD: sqlite3_changeset_iter
 11087  **
 11088  ** The pIter argument passed to this function may either be an iterator
 11089  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 11090  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 11091  ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
 11092  ** is not the case, this function returns [SQLITE_MISUSE].
 11093  **
 11094  ** If argument pzTab is not NULL, then *pzTab is set to point to a
 11095  ** nul-terminated utf-8 encoded string containing the name of the table
 11096  ** affected by the current change. The buffer remains valid until either
 11097  ** sqlite3changeset_next() is called on the iterator or until the 
 11098  ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is 
 11099  ** set to the number of columns in the table affected by the change. If
 11100  ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
 11101  ** is an indirect change, or false (0) otherwise. See the documentation for
 11102  ** [sqlite3session_indirect()] for a description of direct and indirect
 11103  ** changes. Finally, if pOp is not NULL, then *pOp is set to one of 
 11104  ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the 
 11105  ** type of change that the iterator currently points to.
 11106  **
 11107  ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
 11108  ** SQLite error code is returned. The values of the output variables may not
 11109  ** be trusted in this case.
 11110  */
 11111  SQLITE_API int sqlite3changeset_op(
 11112    sqlite3_changeset_iter *pIter,  /* Iterator object */
 11113    const char **pzTab,             /* OUT: Pointer to table name */
 11114    int *pnCol,                     /* OUT: Number of columns in table */
 11115    int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
 11116    int *pbIndirect                 /* OUT: True for an 'indirect' change */
 11117  );
 11118  
 11119  /*
 11120  ** CAPI3REF: Obtain The Primary Key Definition Of A Table
 11121  ** METHOD: sqlite3_changeset_iter
 11122  **
 11123  ** For each modified table, a changeset includes the following:
 11124  **
 11125  ** <ul>
 11126  **   <li> The number of columns in the table, and
 11127  **   <li> Which of those columns make up the tables PRIMARY KEY.
 11128  ** </ul>
 11129  **
 11130  ** This function is used to find which columns comprise the PRIMARY KEY of
 11131  ** the table modified by the change that iterator pIter currently points to.
 11132  ** If successful, *pabPK is set to point to an array of nCol entries, where
 11133  ** nCol is the number of columns in the table. Elements of *pabPK are set to
 11134  ** 0x01 if the corresponding column is part of the tables primary key, or
 11135  ** 0x00 if it is not.
 11136  **
 11137  ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
 11138  ** in the table.
 11139  **
 11140  ** If this function is called when the iterator does not point to a valid
 11141  ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
 11142  ** SQLITE_OK is returned and the output variables populated as described
 11143  ** above.
 11144  */
 11145  SQLITE_API int sqlite3changeset_pk(
 11146    sqlite3_changeset_iter *pIter,  /* Iterator object */
 11147    unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
 11148    int *pnCol                      /* OUT: Number of entries in output array */
 11149  );
 11150  
 11151  /*
 11152  ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
 11153  ** METHOD: sqlite3_changeset_iter
 11154  **
 11155  ** The pIter argument passed to this function may either be an iterator
 11156  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 11157  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 11158  ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 11159  ** Furthermore, it may only be called if the type of change that the iterator
 11160  ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
 11161  ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 11162  **
 11163  ** Argument iVal must be greater than or equal to 0, and less than the number
 11164  ** of columns in the table affected by the current change. Otherwise,
 11165  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 11166  **
 11167  ** If successful, this function sets *ppValue to point to a protected
 11168  ** sqlite3_value object containing the iVal'th value from the vector of 
 11169  ** original row values stored as part of the UPDATE or DELETE change and
 11170  ** returns SQLITE_OK. The name of the function comes from the fact that this 
 11171  ** is similar to the "old.*" columns available to update or delete triggers.
 11172  **
 11173  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 11174  ** is returned and *ppValue is set to NULL.
 11175  */
 11176  SQLITE_API int sqlite3changeset_old(
 11177    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 11178    int iVal,                       /* Column number */
 11179    sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
 11180  );
 11181  
 11182  /*
 11183  ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
 11184  ** METHOD: sqlite3_changeset_iter
 11185  **
 11186  ** The pIter argument passed to this function may either be an iterator
 11187  ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 11188  ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 11189  ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 11190  ** Furthermore, it may only be called if the type of change that the iterator
 11191  ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
 11192  ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 11193  **
 11194  ** Argument iVal must be greater than or equal to 0, and less than the number
 11195  ** of columns in the table affected by the current change. Otherwise,
 11196  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 11197  **
 11198  ** If successful, this function sets *ppValue to point to a protected
 11199  ** sqlite3_value object containing the iVal'th value from the vector of 
 11200  ** new row values stored as part of the UPDATE or INSERT change and
 11201  ** returns SQLITE_OK. If the change is an UPDATE and does not include
 11202  ** a new value for the requested column, *ppValue is set to NULL and 
 11203  ** SQLITE_OK returned. The name of the function comes from the fact that 
 11204  ** this is similar to the "new.*" columns available to update or delete 
 11205  ** triggers.
 11206  **
 11207  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 11208  ** is returned and *ppValue is set to NULL.
 11209  */
 11210  SQLITE_API int sqlite3changeset_new(
 11211    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 11212    int iVal,                       /* Column number */
 11213    sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
 11214  );
 11215  
 11216  /*
 11217  ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
 11218  ** METHOD: sqlite3_changeset_iter
 11219  **
 11220  ** This function should only be used with iterator objects passed to a
 11221  ** conflict-handler callback by [sqlite3changeset_apply()] with either
 11222  ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
 11223  ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
 11224  ** is set to NULL.
 11225  **
 11226  ** Argument iVal must be greater than or equal to 0, and less than the number
 11227  ** of columns in the table affected by the current change. Otherwise,
 11228  ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 11229  **
 11230  ** If successful, this function sets *ppValue to point to a protected
 11231  ** sqlite3_value object containing the iVal'th value from the 
 11232  ** "conflicting row" associated with the current conflict-handler callback
 11233  ** and returns SQLITE_OK.
 11234  **
 11235  ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 11236  ** is returned and *ppValue is set to NULL.
 11237  */
 11238  SQLITE_API int sqlite3changeset_conflict(
 11239    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 11240    int iVal,                       /* Column number */
 11241    sqlite3_value **ppValue         /* OUT: Value from conflicting row */
 11242  );
 11243  
 11244  /*
 11245  ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
 11246  ** METHOD: sqlite3_changeset_iter
 11247  **
 11248  ** This function may only be called with an iterator passed to an
 11249  ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
 11250  ** it sets the output variable to the total number of known foreign key
 11251  ** violations in the destination database and returns SQLITE_OK.
 11252  **
 11253  ** In all other cases this function returns SQLITE_MISUSE.
 11254  */
 11255  SQLITE_API int sqlite3changeset_fk_conflicts(
 11256    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 11257    int *pnOut                      /* OUT: Number of FK violations */
 11258  );
 11259  
 11260  
 11261  /*
 11262  ** CAPI3REF: Finalize A Changeset Iterator
 11263  ** METHOD: sqlite3_changeset_iter
 11264  **
 11265  ** This function is used to finalize an iterator allocated with
 11266  ** [sqlite3changeset_start()].
 11267  **
 11268  ** This function should only be called on iterators created using the
 11269  ** [sqlite3changeset_start()] function. If an application calls this
 11270  ** function with an iterator passed to a conflict-handler by
 11271  ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
 11272  ** call has no effect.
 11273  **
 11274  ** If an error was encountered within a call to an sqlite3changeset_xxx()
 11275  ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an 
 11276  ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
 11277  ** to that error is returned by this function. Otherwise, SQLITE_OK is
 11278  ** returned. This is to allow the following pattern (pseudo-code):
 11279  **
 11280  ** <pre>
 11281  **   sqlite3changeset_start();
 11282  **   while( SQLITE_ROW==sqlite3changeset_next() ){
 11283  **     // Do something with change.
 11284  **   }
 11285  **   rc = sqlite3changeset_finalize();
 11286  **   if( rc!=SQLITE_OK ){
 11287  **     // An error has occurred 
 11288  **   }
 11289  ** </pre>
 11290  */
 11291  SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
 11292  
 11293  /*
 11294  ** CAPI3REF: Invert A Changeset
 11295  **
 11296  ** This function is used to "invert" a changeset object. Applying an inverted
 11297  ** changeset to a database reverses the effects of applying the uninverted
 11298  ** changeset. Specifically:
 11299  **
 11300  ** <ul>
 11301  **   <li> Each DELETE change is changed to an INSERT, and
 11302  **   <li> Each INSERT change is changed to a DELETE, and
 11303  **   <li> For each UPDATE change, the old.* and new.* values are exchanged.
 11304  ** </ul>
 11305  **
 11306  ** This function does not change the order in which changes appear within
 11307  ** the changeset. It merely reverses the sense of each individual change.
 11308  **
 11309  ** If successful, a pointer to a buffer containing the inverted changeset
 11310  ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
 11311  ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
 11312  ** zeroed and an SQLite error code returned.
 11313  **
 11314  ** It is the responsibility of the caller to eventually call sqlite3_free()
 11315  ** on the *ppOut pointer to free the buffer allocation following a successful 
 11316  ** call to this function.
 11317  **
 11318  ** WARNING/TODO: This function currently assumes that the input is a valid
 11319  ** changeset. If it is not, the results are undefined.
 11320  */
 11321  SQLITE_API int sqlite3changeset_invert(
 11322    int nIn, const void *pIn,       /* Input changeset */
 11323    int *pnOut, void **ppOut        /* OUT: Inverse of input */
 11324  );
 11325  
 11326  /*
 11327  ** CAPI3REF: Concatenate Two Changeset Objects
 11328  **
 11329  ** This function is used to concatenate two changesets, A and B, into a 
 11330  ** single changeset. The result is a changeset equivalent to applying
 11331  ** changeset A followed by changeset B. 
 11332  **
 11333  ** This function combines the two input changesets using an 
 11334  ** sqlite3_changegroup object. Calling it produces similar results as the
 11335  ** following code fragment:
 11336  **
 11337  ** <pre>
 11338  **   sqlite3_changegroup *pGrp;
 11339  **   rc = sqlite3_changegroup_new(&pGrp);
 11340  **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
 11341  **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
 11342  **   if( rc==SQLITE_OK ){
 11343  **     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
 11344  **   }else{
 11345  **     *ppOut = 0;
 11346  **     *pnOut = 0;
 11347  **   }
 11348  ** </pre>
 11349  **
 11350  ** Refer to the sqlite3_changegroup documentation below for details.
 11351  */
 11352  SQLITE_API int sqlite3changeset_concat(
 11353    int nA,                         /* Number of bytes in buffer pA */
 11354    void *pA,                       /* Pointer to buffer containing changeset A */
 11355    int nB,                         /* Number of bytes in buffer pB */
 11356    void *pB,                       /* Pointer to buffer containing changeset B */
 11357    int *pnOut,                     /* OUT: Number of bytes in output changeset */
 11358    void **ppOut                    /* OUT: Buffer containing output changeset */
 11359  );
 11360  
 11361  
 11362  /*
 11363  ** CAPI3REF: Changegroup Handle
 11364  **
 11365  ** A changegroup is an object used to combine two or more 
 11366  ** [changesets] or [patchsets]
 11367  */
 11368  typedef struct sqlite3_changegroup sqlite3_changegroup;
 11369  
 11370  /*
 11371  ** CAPI3REF: Create A New Changegroup Object
 11372  ** CONSTRUCTOR: sqlite3_changegroup
 11373  **
 11374  ** An sqlite3_changegroup object is used to combine two or more changesets
 11375  ** (or patchsets) into a single changeset (or patchset). A single changegroup
 11376  ** object may combine changesets or patchsets, but not both. The output is
 11377  ** always in the same format as the input.
 11378  **
 11379  ** If successful, this function returns SQLITE_OK and populates (*pp) with
 11380  ** a pointer to a new sqlite3_changegroup object before returning. The caller
 11381  ** should eventually free the returned object using a call to 
 11382  ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
 11383  ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
 11384  **
 11385  ** The usual usage pattern for an sqlite3_changegroup object is as follows:
 11386  **
 11387  ** <ul>
 11388  **   <li> It is created using a call to sqlite3changegroup_new().
 11389  **
 11390  **   <li> Zero or more changesets (or patchsets) are added to the object
 11391  **        by calling sqlite3changegroup_add().
 11392  **
 11393  **   <li> The result of combining all input changesets together is obtained 
 11394  **        by the application via a call to sqlite3changegroup_output().
 11395  **
 11396  **   <li> The object is deleted using a call to sqlite3changegroup_delete().
 11397  ** </ul>
 11398  **
 11399  ** Any number of calls to add() and output() may be made between the calls to
 11400  ** new() and delete(), and in any order.
 11401  **
 11402  ** As well as the regular sqlite3changegroup_add() and 
 11403  ** sqlite3changegroup_output() functions, also available are the streaming
 11404  ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
 11405  */
 11406  SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 11407  
 11408  /*
 11409  ** CAPI3REF: Add A Changeset To A Changegroup
 11410  ** METHOD: sqlite3_changegroup
 11411  **
 11412  ** Add all changes within the changeset (or patchset) in buffer pData (size
 11413  ** nData bytes) to the changegroup. 
 11414  **
 11415  ** If the buffer contains a patchset, then all prior calls to this function
 11416  ** on the same changegroup object must also have specified patchsets. Or, if
 11417  ** the buffer contains a changeset, so must have the earlier calls to this
 11418  ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
 11419  ** to the changegroup.
 11420  **
 11421  ** Rows within the changeset and changegroup are identified by the values in
 11422  ** their PRIMARY KEY columns. A change in the changeset is considered to
 11423  ** apply to the same row as a change already present in the changegroup if
 11424  ** the two rows have the same primary key.
 11425  **
 11426  ** Changes to rows that do not already appear in the changegroup are
 11427  ** simply copied into it. Or, if both the new changeset and the changegroup
 11428  ** contain changes that apply to a single row, the final contents of the
 11429  ** changegroup depends on the type of each change, as follows:
 11430  **
 11431  ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 11432  **   <tr><th style="white-space:pre">Existing Change  </th>
 11433  **       <th style="white-space:pre">New Change       </th>
 11434  **       <th>Output Change
 11435  **   <tr><td>INSERT <td>INSERT <td>
 11436  **       The new change is ignored. This case does not occur if the new
 11437  **       changeset was recorded immediately after the changesets already
 11438  **       added to the changegroup.
 11439  **   <tr><td>INSERT <td>UPDATE <td>
 11440  **       The INSERT change remains in the changegroup. The values in the 
 11441  **       INSERT change are modified as if the row was inserted by the
 11442  **       existing change and then updated according to the new change.
 11443  **   <tr><td>INSERT <td>DELETE <td>
 11444  **       The existing INSERT is removed from the changegroup. The DELETE is
 11445  **       not added.
 11446  **   <tr><td>UPDATE <td>INSERT <td>
 11447  **       The new change is ignored. This case does not occur if the new
 11448  **       changeset was recorded immediately after the changesets already
 11449  **       added to the changegroup.
 11450  **   <tr><td>UPDATE <td>UPDATE <td>
 11451  **       The existing UPDATE remains within the changegroup. It is amended 
 11452  **       so that the accompanying values are as if the row was updated once 
 11453  **       by the existing change and then again by the new change.
 11454  **   <tr><td>UPDATE <td>DELETE <td>
 11455  **       The existing UPDATE is replaced by the new DELETE within the
 11456  **       changegroup.
 11457  **   <tr><td>DELETE <td>INSERT <td>
 11458  **       If one or more of the column values in the row inserted by the
 11459  **       new change differ from those in the row deleted by the existing 
 11460  **       change, the existing DELETE is replaced by an UPDATE within the
 11461  **       changegroup. Otherwise, if the inserted row is exactly the same 
 11462  **       as the deleted row, the existing DELETE is simply discarded.
 11463  **   <tr><td>DELETE <td>UPDATE <td>
 11464  **       The new change is ignored. This case does not occur if the new
 11465  **       changeset was recorded immediately after the changesets already
 11466  **       added to the changegroup.
 11467  **   <tr><td>DELETE <td>DELETE <td>
 11468  **       The new change is ignored. This case does not occur if the new
 11469  **       changeset was recorded immediately after the changesets already
 11470  **       added to the changegroup.
 11471  ** </table>
 11472  **
 11473  ** If the new changeset contains changes to a table that is already present
 11474  ** in the changegroup, then the number of columns and the position of the
 11475  ** primary key columns for the table must be consistent. If this is not the
 11476  ** case, this function fails with SQLITE_SCHEMA. If the input changeset
 11477  ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
 11478  ** returned. Or, if an out-of-memory condition occurs during processing, this
 11479  ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
 11480  ** final contents of the changegroup is undefined.
 11481  **
 11482  ** If no error occurs, SQLITE_OK is returned.
 11483  */
 11484  SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
 11485  
 11486  /*
 11487  ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
 11488  ** METHOD: sqlite3_changegroup
 11489  **
 11490  ** Obtain a buffer containing a changeset (or patchset) representing the
 11491  ** current contents of the changegroup. If the inputs to the changegroup
 11492  ** were themselves changesets, the output is a changeset. Or, if the
 11493  ** inputs were patchsets, the output is also a patchset.
 11494  **
 11495  ** As with the output of the sqlite3session_changeset() and
 11496  ** sqlite3session_patchset() functions, all changes related to a single
 11497  ** table are grouped together in the output of this function. Tables appear
 11498  ** in the same order as for the very first changeset added to the changegroup.
 11499  ** If the second or subsequent changesets added to the changegroup contain
 11500  ** changes for tables that do not appear in the first changeset, they are
 11501  ** appended onto the end of the output changeset, again in the order in
 11502  ** which they are first encountered.
 11503  **
 11504  ** If an error occurs, an SQLite error code is returned and the output
 11505  ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
 11506  ** is returned and the output variables are set to the size of and a 
 11507  ** pointer to the output buffer, respectively. In this case it is the
 11508  ** responsibility of the caller to eventually free the buffer using a
 11509  ** call to sqlite3_free().
 11510  */
 11511  SQLITE_API int sqlite3changegroup_output(
 11512    sqlite3_changegroup*,
 11513    int *pnData,                    /* OUT: Size of output buffer in bytes */
 11514    void **ppData                   /* OUT: Pointer to output buffer */
 11515  );
 11516  
 11517  /*
 11518  ** CAPI3REF: Delete A Changegroup Object
 11519  ** DESTRUCTOR: sqlite3_changegroup
 11520  */
 11521  SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 11522  
 11523  /*
 11524  ** CAPI3REF: Apply A Changeset To A Database
 11525  **
 11526  ** Apply a changeset or patchset to a database. These functions attempt to
 11527  ** update the "main" database attached to handle db with the changes found in
 11528  ** the changeset passed via the second and third arguments. 
 11529  **
 11530  ** The fourth argument (xFilter) passed to these functions is the "filter
 11531  ** callback". If it is not NULL, then for each table affected by at least one
 11532  ** change in the changeset, the filter callback is invoked with
 11533  ** the table name as the second argument, and a copy of the context pointer
 11534  ** passed as the sixth argument as the first. If the "filter callback"
 11535  ** returns zero, then no attempt is made to apply any changes to the table.
 11536  ** Otherwise, if the return value is non-zero or the xFilter argument to
 11537  ** is NULL, all changes related to the table are attempted.
 11538  **
 11539  ** For each table that is not excluded by the filter callback, this function 
 11540  ** tests that the target database contains a compatible table. A table is 
 11541  ** considered compatible if all of the following are true:
 11542  **
 11543  ** <ul>
 11544  **   <li> The table has the same name as the name recorded in the 
 11545  **        changeset, and
 11546  **   <li> The table has at least as many columns as recorded in the 
 11547  **        changeset, and
 11548  **   <li> The table has primary key columns in the same position as 
 11549  **        recorded in the changeset.
 11550  ** </ul>
 11551  **
 11552  ** If there is no compatible table, it is not an error, but none of the
 11553  ** changes associated with the table are applied. A warning message is issued
 11554  ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
 11555  ** one such warning is issued for each table in the changeset.
 11556  **
 11557  ** For each change for which there is a compatible table, an attempt is made 
 11558  ** to modify the table contents according to the UPDATE, INSERT or DELETE 
 11559  ** change. If a change cannot be applied cleanly, the conflict handler 
 11560  ** function passed as the fifth argument to sqlite3changeset_apply() may be 
 11561  ** invoked. A description of exactly when the conflict handler is invoked for 
 11562  ** each type of change is below.
 11563  **
 11564  ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
 11565  ** of passing anything other than a valid function pointer as the xConflict
 11566  ** argument are undefined.
 11567  **
 11568  ** Each time the conflict handler function is invoked, it must return one
 11569  ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or 
 11570  ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
 11571  ** if the second argument passed to the conflict handler is either
 11572  ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
 11573  ** returns an illegal value, any changes already made are rolled back and
 11574  ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different 
 11575  ** actions are taken by sqlite3changeset_apply() depending on the value
 11576  ** returned by each invocation of the conflict-handler function. Refer to
 11577  ** the documentation for the three 
 11578  ** [SQLITE_CHANGESET_OMIT|available return values] for details.
 11579  **
 11580  ** <dl>
 11581  ** <dt>DELETE Changes<dd>
 11582  **   For each DELETE change, the function checks if the target database 
 11583  **   contains a row with the same primary key value (or values) as the 
 11584  **   original row values stored in the changeset. If it does, and the values 
 11585  **   stored in all non-primary key columns also match the values stored in 
 11586  **   the changeset the row is deleted from the target database.
 11587  **
 11588  **   If a row with matching primary key values is found, but one or more of
 11589  **   the non-primary key fields contains a value different from the original
 11590  **   row value stored in the changeset, the conflict-handler function is
 11591  **   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
 11592  **   database table has more columns than are recorded in the changeset,
 11593  **   only the values of those non-primary key fields are compared against
 11594  **   the current database contents - any trailing database table columns
 11595  **   are ignored.
 11596  **
 11597  **   If no row with matching primary key values is found in the database,
 11598  **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 11599  **   passed as the second argument.
 11600  **
 11601  **   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
 11602  **   (which can only happen if a foreign key constraint is violated), the
 11603  **   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
 11604  **   passed as the second argument. This includes the case where the DELETE
 11605  **   operation is attempted because an earlier call to the conflict handler
 11606  **   function returned [SQLITE_CHANGESET_REPLACE].
 11607  **
 11608  ** <dt>INSERT Changes<dd>
 11609  **   For each INSERT change, an attempt is made to insert the new row into
 11610  **   the database. If the changeset row contains fewer fields than the
 11611  **   database table, the trailing fields are populated with their default
 11612  **   values.
 11613  **
 11614  **   If the attempt to insert the row fails because the database already 
 11615  **   contains a row with the same primary key values, the conflict handler
 11616  **   function is invoked with the second argument set to 
 11617  **   [SQLITE_CHANGESET_CONFLICT].
 11618  **
 11619  **   If the attempt to insert the row fails because of some other constraint
 11620  **   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is 
 11621  **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
 11622  **   This includes the case where the INSERT operation is re-attempted because 
 11623  **   an earlier call to the conflict handler function returned 
 11624  **   [SQLITE_CHANGESET_REPLACE].
 11625  **
 11626  ** <dt>UPDATE Changes<dd>
 11627  **   For each UPDATE change, the function checks if the target database 
 11628  **   contains a row with the same primary key value (or values) as the 
 11629  **   original row values stored in the changeset. If it does, and the values 
 11630  **   stored in all modified non-primary key columns also match the values
 11631  **   stored in the changeset the row is updated within the target database.
 11632  **
 11633  **   If a row with matching primary key values is found, but one or more of
 11634  **   the modified non-primary key fields contains a value different from an
 11635  **   original row value stored in the changeset, the conflict-handler function
 11636  **   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
 11637  **   UPDATE changes only contain values for non-primary key fields that are
 11638  **   to be modified, only those fields need to match the original values to
 11639  **   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
 11640  **
 11641  **   If no row with matching primary key values is found in the database,
 11642  **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 11643  **   passed as the second argument.
 11644  **
 11645  **   If the UPDATE operation is attempted, but SQLite returns 
 11646  **   SQLITE_CONSTRAINT, the conflict-handler function is invoked with 
 11647  **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
 11648  **   This includes the case where the UPDATE operation is attempted after 
 11649  **   an earlier call to the conflict handler function returned
 11650  **   [SQLITE_CHANGESET_REPLACE].  
 11651  ** </dl>
 11652  **
 11653  ** It is safe to execute SQL statements, including those that write to the
 11654  ** table that the callback related to, from within the xConflict callback.
 11655  ** This can be used to further customize the applications conflict
 11656  ** resolution strategy.
 11657  **
 11658  ** All changes made by these functions are enclosed in a savepoint transaction.
 11659  ** If any other error (aside from a constraint failure when attempting to
 11660  ** write to the target database) occurs, then the savepoint transaction is
 11661  ** rolled back, restoring the target database to its original state, and an 
 11662  ** SQLite error code returned.
 11663  **
 11664  ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
 11665  ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
 11666  ** may set (*ppRebase) to point to a "rebase" that may be used with the 
 11667  ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
 11668  ** is set to the size of the buffer in bytes. It is the responsibility of the
 11669  ** caller to eventually free any such buffer using sqlite3_free(). The buffer
 11670  ** is only allocated and populated if one or more conflicts were encountered
 11671  ** while applying the patchset. See comments surrounding the sqlite3_rebaser
 11672  ** APIs for further details.
 11673  **
 11674  ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
 11675  ** may be modified by passing a combination of
 11676  ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
 11677  **
 11678  ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
 11679  ** and therefore subject to change.
 11680  */
 11681  SQLITE_API int sqlite3changeset_apply(
 11682    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 11683    int nChangeset,                 /* Size of changeset in bytes */
 11684    void *pChangeset,               /* Changeset blob */
 11685    int(*xFilter)(
 11686      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11687      const char *zTab              /* Table name */
 11688    ),
 11689    int(*xConflict)(
 11690      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11691      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 11692      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 11693    ),
 11694    void *pCtx                      /* First argument passed to xConflict */
 11695  );
 11696  SQLITE_API int sqlite3changeset_apply_v2(
 11697    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 11698    int nChangeset,                 /* Size of changeset in bytes */
 11699    void *pChangeset,               /* Changeset blob */
 11700    int(*xFilter)(
 11701      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11702      const char *zTab              /* Table name */
 11703    ),
 11704    int(*xConflict)(
 11705      void *pCtx,                   /* Copy of sixth arg to _apply() */
 11706      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 11707      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 11708    ),
 11709    void *pCtx,                     /* First argument passed to xConflict */
 11710    void **ppRebase, int *pnRebase, /* OUT: Rebase data */
 11711    int flags                       /* SESSION_CHANGESETAPPLY_* flags */
 11712  );
 11713  
 11714  /*
 11715  ** CAPI3REF: Flags for sqlite3changeset_apply_v2
 11716  **
 11717  ** The following flags may passed via the 9th parameter to
 11718  ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
 11719  **
 11720  ** <dl>
 11721  ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
 11722  **   Usually, the sessions module encloses all operations performed by
 11723  **   a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
 11724  **   SAVEPOINT is committed if the changeset or patchset is successfully
 11725  **   applied, or rolled back if an error occurs. Specifying this flag
 11726  **   causes the sessions module to omit this savepoint. In this case, if the
 11727  **   caller has an open transaction or savepoint when apply_v2() is called, 
 11728  **   it may revert the partially applied changeset by rolling it back.
 11729  **
 11730  ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
 11731  **   Invert the changeset before applying it. This is equivalent to inverting
 11732  **   a changeset using sqlite3changeset_invert() before applying it. It is
 11733  **   an error to specify this flag with a patchset.
 11734  */
 11735  #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
 11736  #define SQLITE_CHANGESETAPPLY_INVERT        0x0002
 11737  
 11738  /* 
 11739  ** CAPI3REF: Constants Passed To The Conflict Handler
 11740  **
 11741  ** Values that may be passed as the second argument to a conflict-handler.
 11742  **
 11743  ** <dl>
 11744  ** <dt>SQLITE_CHANGESET_DATA<dd>
 11745  **   The conflict handler is invoked with CHANGESET_DATA as the second argument
 11746  **   when processing a DELETE or UPDATE change if a row with the required
 11747  **   PRIMARY KEY fields is present in the database, but one or more other 
 11748  **   (non primary-key) fields modified by the update do not contain the 
 11749  **   expected "before" values.
 11750  ** 
 11751  **   The conflicting row, in this case, is the database row with the matching
 11752  **   primary key.
 11753  ** 
 11754  ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
 11755  **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
 11756  **   argument when processing a DELETE or UPDATE change if a row with the
 11757  **   required PRIMARY KEY fields is not present in the database.
 11758  ** 
 11759  **   There is no conflicting row in this case. The results of invoking the
 11760  **   sqlite3changeset_conflict() API are undefined.
 11761  ** 
 11762  ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
 11763  **   CHANGESET_CONFLICT is passed as the second argument to the conflict
 11764  **   handler while processing an INSERT change if the operation would result 
 11765  **   in duplicate primary key values.
 11766  ** 
 11767  **   The conflicting row in this case is the database row with the matching
 11768  **   primary key.
 11769  **
 11770  ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
 11771  **   If foreign key handling is enabled, and applying a changeset leaves the
 11772  **   database in a state containing foreign key violations, the conflict 
 11773  **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
 11774  **   exactly once before the changeset is committed. If the conflict handler
 11775  **   returns CHANGESET_OMIT, the changes, including those that caused the
 11776  **   foreign key constraint violation, are committed. Or, if it returns
 11777  **   CHANGESET_ABORT, the changeset is rolled back.
 11778  **
 11779  **   No current or conflicting row information is provided. The only function
 11780  **   it is possible to call on the supplied sqlite3_changeset_iter handle
 11781  **   is sqlite3changeset_fk_conflicts().
 11782  ** 
 11783  ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
 11784  **   If any other constraint violation occurs while applying a change (i.e. 
 11785  **   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is 
 11786  **   invoked with CHANGESET_CONSTRAINT as the second argument.
 11787  ** 
 11788  **   There is no conflicting row in this case. The results of invoking the
 11789  **   sqlite3changeset_conflict() API are undefined.
 11790  **
 11791  ** </dl>
 11792  */
 11793  #define SQLITE_CHANGESET_DATA        1
 11794  #define SQLITE_CHANGESET_NOTFOUND    2
 11795  #define SQLITE_CHANGESET_CONFLICT    3
 11796  #define SQLITE_CHANGESET_CONSTRAINT  4
 11797  #define SQLITE_CHANGESET_FOREIGN_KEY 5
 11798  
 11799  /* 
 11800  ** CAPI3REF: Constants Returned By The Conflict Handler
 11801  **
 11802  ** A conflict handler callback must return one of the following three values.
 11803  **
 11804  ** <dl>
 11805  ** <dt>SQLITE_CHANGESET_OMIT<dd>
 11806  **   If a conflict handler returns this value no special action is taken. The
 11807  **   change that caused the conflict is not applied. The session module 
 11808  **   continues to the next change in the changeset.
 11809  **
 11810  ** <dt>SQLITE_CHANGESET_REPLACE<dd>
 11811  **   This value may only be returned if the second argument to the conflict
 11812  **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
 11813  **   is not the case, any changes applied so far are rolled back and the 
 11814  **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
 11815  **
 11816  **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
 11817  **   handler, then the conflicting row is either updated or deleted, depending
 11818  **   on the type of change.
 11819  **
 11820  **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
 11821  **   handler, then the conflicting row is removed from the database and a
 11822  **   second attempt to apply the change is made. If this second attempt fails,
 11823  **   the original row is restored to the database before continuing.
 11824  **
 11825  ** <dt>SQLITE_CHANGESET_ABORT<dd>
 11826  **   If this value is returned, any changes applied so far are rolled back 
 11827  **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
 11828  ** </dl>
 11829  */
 11830  #define SQLITE_CHANGESET_OMIT       0
 11831  #define SQLITE_CHANGESET_REPLACE    1
 11832  #define SQLITE_CHANGESET_ABORT      2
 11833  
 11834  /* 
 11835  ** CAPI3REF: Rebasing changesets
 11836  ** EXPERIMENTAL
 11837  **
 11838  ** Suppose there is a site hosting a database in state S0. And that
 11839  ** modifications are made that move that database to state S1 and a
 11840  ** changeset recorded (the "local" changeset). Then, a changeset based
 11841  ** on S0 is received from another site (the "remote" changeset) and 
 11842  ** applied to the database. The database is then in state 
 11843  ** (S1+"remote"), where the exact state depends on any conflict
 11844  ** resolution decisions (OMIT or REPLACE) made while applying "remote".
 11845  ** Rebasing a changeset is to update it to take those conflict 
 11846  ** resolution decisions into account, so that the same conflicts
 11847  ** do not have to be resolved elsewhere in the network. 
 11848  **
 11849  ** For example, if both the local and remote changesets contain an
 11850  ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
 11851  **
 11852  **   local:  INSERT INTO t1 VALUES(1, 'v1');
 11853  **   remote: INSERT INTO t1 VALUES(1, 'v2');
 11854  **
 11855  ** and the conflict resolution is REPLACE, then the INSERT change is
 11856  ** removed from the local changeset (it was overridden). Or, if the
 11857  ** conflict resolution was "OMIT", then the local changeset is modified
 11858  ** to instead contain:
 11859  **
 11860  **           UPDATE t1 SET b = 'v2' WHERE a=1;
 11861  **
 11862  ** Changes within the local changeset are rebased as follows:
 11863  **
 11864  ** <dl>
 11865  ** <dt>Local INSERT<dd>
 11866  **   This may only conflict with a remote INSERT. If the conflict 
 11867  **   resolution was OMIT, then add an UPDATE change to the rebased
 11868  **   changeset. Or, if the conflict resolution was REPLACE, add
 11869  **   nothing to the rebased changeset.
 11870  **
 11871  ** <dt>Local DELETE<dd>
 11872  **   This may conflict with a remote UPDATE or DELETE. In both cases the
 11873  **   only possible resolution is OMIT. If the remote operation was a
 11874  **   DELETE, then add no change to the rebased changeset. If the remote
 11875  **   operation was an UPDATE, then the old.* fields of change are updated
 11876  **   to reflect the new.* values in the UPDATE.
 11877  **
 11878  ** <dt>Local UPDATE<dd>
 11879  **   This may conflict with a remote UPDATE or DELETE. If it conflicts
 11880  **   with a DELETE, and the conflict resolution was OMIT, then the update
 11881  **   is changed into an INSERT. Any undefined values in the new.* record
 11882  **   from the update change are filled in using the old.* values from
 11883  **   the conflicting DELETE. Or, if the conflict resolution was REPLACE,
 11884  **   the UPDATE change is simply omitted from the rebased changeset.
 11885  **
 11886  **   If conflict is with a remote UPDATE and the resolution is OMIT, then
 11887  **   the old.* values are rebased using the new.* values in the remote
 11888  **   change. Or, if the resolution is REPLACE, then the change is copied
 11889  **   into the rebased changeset with updates to columns also updated by
 11890  **   the conflicting remote UPDATE removed. If this means no columns would 
 11891  **   be updated, the change is omitted.
 11892  ** </dl>
 11893  **
 11894  ** A local change may be rebased against multiple remote changes 
 11895  ** simultaneously. If a single key is modified by multiple remote 
 11896  ** changesets, they are combined as follows before the local changeset
 11897  ** is rebased:
 11898  **
 11899  ** <ul>
 11900  **    <li> If there has been one or more REPLACE resolutions on a
 11901  **         key, it is rebased according to a REPLACE.
 11902  **
 11903  **    <li> If there have been no REPLACE resolutions on a key, then
 11904  **         the local changeset is rebased according to the most recent
 11905  **         of the OMIT resolutions.
 11906  ** </ul>
 11907  **
 11908  ** Note that conflict resolutions from multiple remote changesets are 
 11909  ** combined on a per-field basis, not per-row. This means that in the 
 11910  ** case of multiple remote UPDATE operations, some fields of a single 
 11911  ** local change may be rebased for REPLACE while others are rebased for 
 11912  ** OMIT.
 11913  **
 11914  ** In order to rebase a local changeset, the remote changeset must first
 11915  ** be applied to the local database using sqlite3changeset_apply_v2() and
 11916  ** the buffer of rebase information captured. Then:
 11917  **
 11918  ** <ol>
 11919  **   <li> An sqlite3_rebaser object is created by calling 
 11920  **        sqlite3rebaser_create().
 11921  **   <li> The new object is configured with the rebase buffer obtained from
 11922  **        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
 11923  **        If the local changeset is to be rebased against multiple remote
 11924  **        changesets, then sqlite3rebaser_configure() should be called
 11925  **        multiple times, in the same order that the multiple
 11926  **        sqlite3changeset_apply_v2() calls were made.
 11927  **   <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
 11928  **   <li> The sqlite3_rebaser object is deleted by calling
 11929  **        sqlite3rebaser_delete().
 11930  ** </ol>
 11931  */
 11932  typedef struct sqlite3_rebaser sqlite3_rebaser;
 11933  
 11934  /*
 11935  ** CAPI3REF: Create a changeset rebaser object.
 11936  ** EXPERIMENTAL
 11937  **
 11938  ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
 11939  ** point to the new object and return SQLITE_OK. Otherwise, if an error
 11940  ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) 
 11941  ** to NULL. 
 11942  */
 11943  SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
 11944  
 11945  /*
 11946  ** CAPI3REF: Configure a changeset rebaser object.
 11947  ** EXPERIMENTAL
 11948  **
 11949  ** Configure the changeset rebaser object to rebase changesets according
 11950  ** to the conflict resolutions described by buffer pRebase (size nRebase
 11951  ** bytes), which must have been obtained from a previous call to
 11952  ** sqlite3changeset_apply_v2().
 11953  */
 11954  SQLITE_API int sqlite3rebaser_configure(
 11955    sqlite3_rebaser*, 
 11956    int nRebase, const void *pRebase
 11957  ); 
 11958  
 11959  /*
 11960  ** CAPI3REF: Rebase a changeset
 11961  ** EXPERIMENTAL
 11962  **
 11963  ** Argument pIn must point to a buffer containing a changeset nIn bytes
 11964  ** in size. This function allocates and populates a buffer with a copy
 11965  ** of the changeset rebased rebased according to the configuration of the
 11966  ** rebaser object passed as the first argument. If successful, (*ppOut)
 11967  ** is set to point to the new buffer containing the rebased changset and 
 11968  ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
 11969  ** responsibility of the caller to eventually free the new buffer using
 11970  ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
 11971  ** are set to zero and an SQLite error code returned.
 11972  */
 11973  SQLITE_API int sqlite3rebaser_rebase(
 11974    sqlite3_rebaser*,
 11975    int nIn, const void *pIn, 
 11976    int *pnOut, void **ppOut 
 11977  );
 11978  
 11979  /*
 11980  ** CAPI3REF: Delete a changeset rebaser object.
 11981  ** EXPERIMENTAL
 11982  **
 11983  ** Delete the changeset rebaser object and all associated resources. There
 11984  ** should be one call to this function for each successful invocation
 11985  ** of sqlite3rebaser_create().
 11986  */
 11987  SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); 
 11988  
 11989  /*
 11990  ** CAPI3REF: Streaming Versions of API functions.
 11991  **
 11992  ** The six streaming API xxx_strm() functions serve similar purposes to the 
 11993  ** corresponding non-streaming API functions:
 11994  **
 11995  ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 11996  **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
 11997  **   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] 
 11998  **   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] 
 11999  **   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] 
 12000  **   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] 
 12001  **   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] 
 12002  **   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] 
 12003  **   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] 
 12004  ** </table>
 12005  **
 12006  ** Non-streaming functions that accept changesets (or patchsets) as input
 12007  ** require that the entire changeset be stored in a single buffer in memory. 
 12008  ** Similarly, those that return a changeset or patchset do so by returning 
 12009  ** a pointer to a single large buffer allocated using sqlite3_malloc(). 
 12010  ** Normally this is convenient. However, if an application running in a 
 12011  ** low-memory environment is required to handle very large changesets, the
 12012  ** large contiguous memory allocations required can become onerous.
 12013  **
 12014  ** In order to avoid this problem, instead of a single large buffer, input
 12015  ** is passed to a streaming API functions by way of a callback function that
 12016  ** the sessions module invokes to incrementally request input data as it is
 12017  ** required. In all cases, a pair of API function parameters such as
 12018  **
 12019  **  <pre>
 12020  **  &nbsp;     int nChangeset,
 12021  **  &nbsp;     void *pChangeset,
 12022  **  </pre>
 12023  **
 12024  ** Is replaced by:
 12025  **
 12026  **  <pre>
 12027  **  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
 12028  **  &nbsp;     void *pIn,
 12029  **  </pre>
 12030  **
 12031  ** Each time the xInput callback is invoked by the sessions module, the first
 12032  ** argument passed is a copy of the supplied pIn context pointer. The second 
 12033  ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no 
 12034  ** error occurs the xInput method should copy up to (*pnData) bytes of data 
 12035  ** into the buffer and set (*pnData) to the actual number of bytes copied 
 12036  ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) 
 12037  ** should be set to zero to indicate this. Or, if an error occurs, an SQLite 
 12038  ** error code should be returned. In all cases, if an xInput callback returns
 12039  ** an error, all processing is abandoned and the streaming API function
 12040  ** returns a copy of the error code to the caller.
 12041  **
 12042  ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
 12043  ** invoked by the sessions module at any point during the lifetime of the
 12044  ** iterator. If such an xInput callback returns an error, the iterator enters
 12045  ** an error state, whereby all subsequent calls to iterator functions 
 12046  ** immediately fail with the same error code as returned by xInput.
 12047  **
 12048  ** Similarly, streaming API functions that return changesets (or patchsets)
 12049  ** return them in chunks by way of a callback function instead of via a
 12050  ** pointer to a single large buffer. In this case, a pair of parameters such
 12051  ** as:
 12052  **
 12053  **  <pre>
 12054  **  &nbsp;     int *pnChangeset,
 12055  **  &nbsp;     void **ppChangeset,
 12056  **  </pre>
 12057  **
 12058  ** Is replaced by:
 12059  **
 12060  **  <pre>
 12061  **  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
 12062  **  &nbsp;     void *pOut
 12063  **  </pre>
 12064  **
 12065  ** The xOutput callback is invoked zero or more times to return data to
 12066  ** the application. The first parameter passed to each call is a copy of the
 12067  ** pOut pointer supplied by the application. The second parameter, pData,
 12068  ** points to a buffer nData bytes in size containing the chunk of output
 12069  ** data being returned. If the xOutput callback successfully processes the
 12070  ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
 12071  ** it should return some other SQLite error code. In this case processing
 12072  ** is immediately abandoned and the streaming API function returns a copy
 12073  ** of the xOutput error code to the application.
 12074  **
 12075  ** The sessions module never invokes an xOutput callback with the third 
 12076  ** parameter set to a value less than or equal to zero. Other than this,
 12077  ** no guarantees are made as to the size of the chunks of data returned.
 12078  */
 12079  SQLITE_API int sqlite3changeset_apply_strm(
 12080    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 12081    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
 12082    void *pIn,                                          /* First arg for xInput */
 12083    int(*xFilter)(
 12084      void *pCtx,                   /* Copy of sixth arg to _apply() */
 12085      const char *zTab              /* Table name */
 12086    ),
 12087    int(*xConflict)(
 12088      void *pCtx,                   /* Copy of sixth arg to _apply() */
 12089      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 12090      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 12091    ),
 12092    void *pCtx                      /* First argument passed to xConflict */
 12093  );
 12094  SQLITE_API int sqlite3changeset_apply_v2_strm(
 12095    sqlite3 *db,                    /* Apply change to "main" db of this handle */
 12096    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
 12097    void *pIn,                                          /* First arg for xInput */
 12098    int(*xFilter)(
 12099      void *pCtx,                   /* Copy of sixth arg to _apply() */
 12100      const char *zTab              /* Table name */
 12101    ),
 12102    int(*xConflict)(
 12103      void *pCtx,                   /* Copy of sixth arg to _apply() */
 12104      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 12105      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 12106    ),
 12107    void *pCtx,                     /* First argument passed to xConflict */
 12108    void **ppRebase, int *pnRebase,
 12109    int flags
 12110  );
 12111  SQLITE_API int sqlite3changeset_concat_strm(
 12112    int (*xInputA)(void *pIn, void *pData, int *pnData),
 12113    void *pInA,
 12114    int (*xInputB)(void *pIn, void *pData, int *pnData),
 12115    void *pInB,
 12116    int (*xOutput)(void *pOut, const void *pData, int nData),
 12117    void *pOut
 12118  );
 12119  SQLITE_API int sqlite3changeset_invert_strm(
 12120    int (*xInput)(void *pIn, void *pData, int *pnData),
 12121    void *pIn,
 12122    int (*xOutput)(void *pOut, const void *pData, int nData),
 12123    void *pOut
 12124  );
 12125  SQLITE_API int sqlite3changeset_start_strm(
 12126    sqlite3_changeset_iter **pp,
 12127    int (*xInput)(void *pIn, void *pData, int *pnData),
 12128    void *pIn
 12129  );
 12130  SQLITE_API int sqlite3changeset_start_v2_strm(
 12131    sqlite3_changeset_iter **pp,
 12132    int (*xInput)(void *pIn, void *pData, int *pnData),
 12133    void *pIn,
 12134    int flags
 12135  );
 12136  SQLITE_API int sqlite3session_changeset_strm(
 12137    sqlite3_session *pSession,
 12138    int (*xOutput)(void *pOut, const void *pData, int nData),
 12139    void *pOut
 12140  );
 12141  SQLITE_API int sqlite3session_patchset_strm(
 12142    sqlite3_session *pSession,
 12143    int (*xOutput)(void *pOut, const void *pData, int nData),
 12144    void *pOut
 12145  );
 12146  SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, 
 12147      int (*xInput)(void *pIn, void *pData, int *pnData),
 12148      void *pIn
 12149  );
 12150  SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
 12151      int (*xOutput)(void *pOut, const void *pData, int nData), 
 12152      void *pOut
 12153  );
 12154  SQLITE_API int sqlite3rebaser_rebase_strm(
 12155    sqlite3_rebaser *pRebaser,
 12156    int (*xInput)(void *pIn, void *pData, int *pnData),
 12157    void *pIn,
 12158    int (*xOutput)(void *pOut, const void *pData, int nData),
 12159    void *pOut
 12160  );
 12161  
 12162  /*
 12163  ** CAPI3REF: Configure global parameters
 12164  **
 12165  ** The sqlite3session_config() interface is used to make global configuration
 12166  ** changes to the sessions module in order to tune it to the specific needs 
 12167  ** of the application.
 12168  **
 12169  ** The sqlite3session_config() interface is not threadsafe. If it is invoked
 12170  ** while any other thread is inside any other sessions method then the
 12171  ** results are undefined. Furthermore, if it is invoked after any sessions
 12172  ** related objects have been created, the results are also undefined. 
 12173  **
 12174  ** The first argument to the sqlite3session_config() function must be one
 12175  ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The 
 12176  ** interpretation of the (void*) value passed as the second parameter and
 12177  ** the effect of calling this function depends on the value of the first
 12178  ** parameter.
 12179  **
 12180  ** <dl>
 12181  ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
 12182  **    By default, the sessions module streaming interfaces attempt to input
 12183  **    and output data in approximately 1 KiB chunks. This operand may be used
 12184  **    to set and query the value of this configuration setting. The pointer
 12185  **    passed as the second argument must point to a value of type (int).
 12186  **    If this value is greater than 0, it is used as the new streaming data
 12187  **    chunk size for both input and output. Before returning, the (int) value
 12188  **    pointed to by pArg is set to the final value of the streaming interface
 12189  **    chunk size.
 12190  ** </dl>
 12191  **
 12192  ** This function returns SQLITE_OK if successful, or an SQLite error code
 12193  ** otherwise.
 12194  */
 12195  SQLITE_API int sqlite3session_config(int op, void *pArg);
 12196  
 12197  /*
 12198  ** CAPI3REF: Values for sqlite3session_config().
 12199  */
 12200  #define SQLITE_SESSION_CONFIG_STRMSIZE 1
 12201  
 12202  /*
 12203  ** Make sure we can call this stuff from C++.
 12204  */
 12205  #if 0
 12206  }
 12207  #endif
 12208  
 12209  #endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
 12210  
 12211  /******** End of sqlite3session.h *********/
 12212  /******** Begin file fts5.h *********/
 12213  /*
 12214  ** 2014 May 31
 12215  **
 12216  ** The author disclaims copyright to this source code.  In place of
 12217  ** a legal notice, here is a blessing:
 12218  **
 12219  **    May you do good and not evil.
 12220  **    May you find forgiveness for yourself and forgive others.
 12221  **    May you share freely, never taking more than you give.
 12222  **
 12223  ******************************************************************************
 12224  **
 12225  ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
 12226  ** FTS5 may be extended with:
 12227  **
 12228  **     * custom tokenizers, and
 12229  **     * custom auxiliary functions.
 12230  */
 12231  
 12232  
 12233  #ifndef _FTS5_H
 12234  #define _FTS5_H
 12235  
 12236  
 12237  #if 0
 12238  extern "C" {
 12239  #endif
 12240  
 12241  /*************************************************************************
 12242  ** CUSTOM AUXILIARY FUNCTIONS
 12243  **
 12244  ** Virtual table implementations may overload SQL functions by implementing
 12245  ** the sqlite3_module.xFindFunction() method.
 12246  */
 12247  
 12248  typedef struct Fts5ExtensionApi Fts5ExtensionApi;
 12249  typedef struct Fts5Context Fts5Context;
 12250  typedef struct Fts5PhraseIter Fts5PhraseIter;
 12251  
 12252  typedef void (*fts5_extension_function)(
 12253    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
 12254    Fts5Context *pFts,              /* First arg to pass to pApi functions */
 12255    sqlite3_context *pCtx,          /* Context for returning result/error */
 12256    int nVal,                       /* Number of values in apVal[] array */
 12257    sqlite3_value **apVal           /* Array of trailing arguments */
 12258  );
 12259  
 12260  struct Fts5PhraseIter {
 12261    const unsigned char *a;
 12262    const unsigned char *b;
 12263  };
 12264  
 12265  /*
 12266  ** EXTENSION API FUNCTIONS
 12267  **
 12268  ** xUserData(pFts):
 12269  **   Return a copy of the context pointer the extension function was 
 12270  **   registered with.
 12271  **
 12272  ** xColumnTotalSize(pFts, iCol, pnToken):
 12273  **   If parameter iCol is less than zero, set output variable *pnToken
 12274  **   to the total number of tokens in the FTS5 table. Or, if iCol is
 12275  **   non-negative but less than the number of columns in the table, return
 12276  **   the total number of tokens in column iCol, considering all rows in 
 12277  **   the FTS5 table.
 12278  **
 12279  **   If parameter iCol is greater than or equal to the number of columns
 12280  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
 12281  **   an OOM condition or IO error), an appropriate SQLite error code is 
 12282  **   returned.
 12283  **
 12284  ** xColumnCount(pFts):
 12285  **   Return the number of columns in the table.
 12286  **
 12287  ** xColumnSize(pFts, iCol, pnToken):
 12288  **   If parameter iCol is less than zero, set output variable *pnToken
 12289  **   to the total number of tokens in the current row. Or, if iCol is
 12290  **   non-negative but less than the number of columns in the table, set
 12291  **   *pnToken to the number of tokens in column iCol of the current row.
 12292  **
 12293  **   If parameter iCol is greater than or equal to the number of columns
 12294  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
 12295  **   an OOM condition or IO error), an appropriate SQLite error code is 
 12296  **   returned.
 12297  **
 12298  **   This function may be quite inefficient if used with an FTS5 table
 12299  **   created with the "columnsize=0" option.
 12300  **
 12301  ** xColumnText:
 12302  **   This function attempts to retrieve the text of column iCol of the
 12303  **   current document. If successful, (*pz) is set to point to a buffer
 12304  **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
 12305  **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
 12306  **   if an error occurs, an SQLite error code is returned and the final values
 12307  **   of (*pz) and (*pn) are undefined.
 12308  **
 12309  ** xPhraseCount:
 12310  **   Returns the number of phrases in the current query expression.
 12311  **
 12312  ** xPhraseSize:
 12313  **   Returns the number of tokens in phrase iPhrase of the query. Phrases
 12314  **   are numbered starting from zero.
 12315  **
 12316  ** xInstCount:
 12317  **   Set *pnInst to the total number of occurrences of all phrases within
 12318  **   the query within the current row. Return SQLITE_OK if successful, or
 12319  **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
 12320  **
 12321  **   This API can be quite slow if used with an FTS5 table created with the
 12322  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
 12323  **   with either "detail=none" or "detail=column" and "content=" option 
 12324  **   (i.e. if it is a contentless table), then this API always returns 0.
 12325  **
 12326  ** xInst:
 12327  **   Query for the details of phrase match iIdx within the current row.
 12328  **   Phrase matches are numbered starting from zero, so the iIdx argument
 12329  **   should be greater than or equal to zero and smaller than the value
 12330  **   output by xInstCount().
 12331  **
 12332  **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
 12333  **   to the column in which it occurs and *piOff the token offset of the
 12334  **   first token of the phrase. Returns SQLITE_OK if successful, or an error
 12335  **   code (i.e. SQLITE_NOMEM) if an error occurs.
 12336  **
 12337  **   This API can be quite slow if used with an FTS5 table created with the
 12338  **   "detail=none" or "detail=column" option. 
 12339  **
 12340  ** xRowid:
 12341  **   Returns the rowid of the current row.
 12342  **
 12343  ** xTokenize:
 12344  **   Tokenize text using the tokenizer belonging to the FTS5 table.
 12345  **
 12346  ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
 12347  **   This API function is used to query the FTS table for phrase iPhrase
 12348  **   of the current query. Specifically, a query equivalent to:
 12349  **
 12350  **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
 12351  **
 12352  **   with $p set to a phrase equivalent to the phrase iPhrase of the
 12353  **   current query is executed. Any column filter that applies to
 12354  **   phrase iPhrase of the current query is included in $p. For each 
 12355  **   row visited, the callback function passed as the fourth argument 
 12356  **   is invoked. The context and API objects passed to the callback 
 12357  **   function may be used to access the properties of each matched row.
 12358  **   Invoking Api.xUserData() returns a copy of the pointer passed as 
 12359  **   the third argument to pUserData.
 12360  **
 12361  **   If the callback function returns any value other than SQLITE_OK, the
 12362  **   query is abandoned and the xQueryPhrase function returns immediately.
 12363  **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
 12364  **   Otherwise, the error code is propagated upwards.
 12365  **
 12366  **   If the query runs to completion without incident, SQLITE_OK is returned.
 12367  **   Or, if some error occurs before the query completes or is aborted by
 12368  **   the callback, an SQLite error code is returned.
 12369  **
 12370  **
 12371  ** xSetAuxdata(pFts5, pAux, xDelete)
 12372  **
 12373  **   Save the pointer passed as the second argument as the extension functions 
 12374  **   "auxiliary data". The pointer may then be retrieved by the current or any
 12375  **   future invocation of the same fts5 extension function made as part of
 12376  **   of the same MATCH query using the xGetAuxdata() API.
 12377  **
 12378  **   Each extension function is allocated a single auxiliary data slot for
 12379  **   each FTS query (MATCH expression). If the extension function is invoked 
 12380  **   more than once for a single FTS query, then all invocations share a 
 12381  **   single auxiliary data context.
 12382  **
 12383  **   If there is already an auxiliary data pointer when this function is
 12384  **   invoked, then it is replaced by the new pointer. If an xDelete callback
 12385  **   was specified along with the original pointer, it is invoked at this
 12386  **   point.
 12387  **
 12388  **   The xDelete callback, if one is specified, is also invoked on the
 12389  **   auxiliary data pointer after the FTS5 query has finished.
 12390  **
 12391  **   If an error (e.g. an OOM condition) occurs within this function, an
 12392  **   the auxiliary data is set to NULL and an error code returned. If the
 12393  **   xDelete parameter was not NULL, it is invoked on the auxiliary data
 12394  **   pointer before returning.
 12395  **
 12396  **
 12397  ** xGetAuxdata(pFts5, bClear)
 12398  **
 12399  **   Returns the current auxiliary data pointer for the fts5 extension 
 12400  **   function. See the xSetAuxdata() method for details.
 12401  **
 12402  **   If the bClear argument is non-zero, then the auxiliary data is cleared
 12403  **   (set to NULL) before this function returns. In this case the xDelete,
 12404  **   if any, is not invoked.
 12405  **
 12406  **
 12407  ** xRowCount(pFts5, pnRow)
 12408  **
 12409  **   This function is used to retrieve the total number of rows in the table.
 12410  **   In other words, the same value that would be returned by:
 12411  **
 12412  **        SELECT count(*) FROM ftstable;
 12413  **
 12414  ** xPhraseFirst()
 12415  **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
 12416  **   method, to iterate through all instances of a single query phrase within
 12417  **   the current row. This is the same information as is accessible via the
 12418  **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
 12419  **   to use, this API may be faster under some circumstances. To iterate 
 12420  **   through instances of phrase iPhrase, use the following code:
 12421  **
 12422  **       Fts5PhraseIter iter;
 12423  **       int iCol, iOff;
 12424  **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
 12425  **           iCol>=0;
 12426  **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
 12427  **       ){
 12428  **         // An instance of phrase iPhrase at offset iOff of column iCol
 12429  **       }
 12430  **
 12431  **   The Fts5PhraseIter structure is defined above. Applications should not
 12432  **   modify this structure directly - it should only be used as shown above
 12433  **   with the xPhraseFirst() and xPhraseNext() API methods (and by
 12434  **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
 12435  **
 12436  **   This API can be quite slow if used with an FTS5 table created with the
 12437  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
 12438  **   with either "detail=none" or "detail=column" and "content=" option 
 12439  **   (i.e. if it is a contentless table), then this API always iterates
 12440  **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
 12441  **
 12442  ** xPhraseNext()
 12443  **   See xPhraseFirst above.
 12444  **
 12445  ** xPhraseFirstColumn()
 12446  **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
 12447  **   and xPhraseNext() APIs described above. The difference is that instead
 12448  **   of iterating through all instances of a phrase in the current row, these
 12449  **   APIs are used to iterate through the set of columns in the current row
 12450  **   that contain one or more instances of a specified phrase. For example:
 12451  **
 12452  **       Fts5PhraseIter iter;
 12453  **       int iCol;
 12454  **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
 12455  **           iCol>=0;
 12456  **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
 12457  **       ){
 12458  **         // Column iCol contains at least one instance of phrase iPhrase
 12459  **       }
 12460  **
 12461  **   This API can be quite slow if used with an FTS5 table created with the
 12462  **   "detail=none" option. If the FTS5 table is created with either 
 12463  **   "detail=none" "content=" option (i.e. if it is a contentless table), 
 12464  **   then this API always iterates through an empty set (all calls to 
 12465  **   xPhraseFirstColumn() set iCol to -1).
 12466  **
 12467  **   The information accessed using this API and its companion
 12468  **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
 12469  **   (or xInst/xInstCount). The chief advantage of this API is that it is
 12470  **   significantly more efficient than those alternatives when used with
 12471  **   "detail=column" tables.  
 12472  **
 12473  ** xPhraseNextColumn()
 12474  **   See xPhraseFirstColumn above.
 12475  */
 12476  struct Fts5ExtensionApi {
 12477    int iVersion;                   /* Currently always set to 3 */
 12478  
 12479    void *(*xUserData)(Fts5Context*);
 12480  
 12481    int (*xColumnCount)(Fts5Context*);
 12482    int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
 12483    int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
 12484  
 12485    int (*xTokenize)(Fts5Context*, 
 12486      const char *pText, int nText, /* Text to tokenize */
 12487      void *pCtx,                   /* Context passed to xToken() */
 12488      int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
 12489    );
 12490  
 12491    int (*xPhraseCount)(Fts5Context*);
 12492    int (*xPhraseSize)(Fts5Context*, int iPhrase);
 12493  
 12494    int (*xInstCount)(Fts5Context*, int *pnInst);
 12495    int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
 12496  
 12497    sqlite3_int64 (*xRowid)(Fts5Context*);
 12498    int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
 12499    int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
 12500  
 12501    int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
 12502      int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
 12503    );
 12504    int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
 12505    void *(*xGetAuxdata)(Fts5Context*, int bClear);
 12506  
 12507    int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
 12508    void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
 12509  
 12510    int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
 12511    void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
 12512  };
 12513  
 12514  /* 
 12515  ** CUSTOM AUXILIARY FUNCTIONS
 12516  *************************************************************************/
 12517  
 12518  /*************************************************************************
 12519  ** CUSTOM TOKENIZERS
 12520  **
 12521  ** Applications may also register custom tokenizer types. A tokenizer 
 12522  ** is registered by providing fts5 with a populated instance of the 
 12523  ** following structure. All structure methods must be defined, setting
 12524  ** any member of the fts5_tokenizer struct to NULL leads to undefined
 12525  ** behaviour. The structure methods are expected to function as follows:
 12526  **
 12527  ** xCreate:
 12528  **   This function is used to allocate and initialize a tokenizer instance.
 12529  **   A tokenizer instance is required to actually tokenize text.
 12530  **
 12531  **   The first argument passed to this function is a copy of the (void*)
 12532  **   pointer provided by the application when the fts5_tokenizer object
 12533  **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
 12534  **   The second and third arguments are an array of nul-terminated strings
 12535  **   containing the tokenizer arguments, if any, specified following the
 12536  **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
 12537  **   to create the FTS5 table.
 12538  **
 12539  **   The final argument is an output variable. If successful, (*ppOut) 
 12540  **   should be set to point to the new tokenizer handle and SQLITE_OK
 12541  **   returned. If an error occurs, some value other than SQLITE_OK should
 12542  **   be returned. In this case, fts5 assumes that the final value of *ppOut 
 12543  **   is undefined.
 12544  **
 12545  ** xDelete:
 12546  **   This function is invoked to delete a tokenizer handle previously
 12547  **   allocated using xCreate(). Fts5 guarantees that this function will
 12548  **   be invoked exactly once for each successful call to xCreate().
 12549  **
 12550  ** xTokenize:
 12551  **   This function is expected to tokenize the nText byte string indicated 
 12552  **   by argument pText. pText may or may not be nul-terminated. The first
 12553  **   argument passed to this function is a pointer to an Fts5Tokenizer object
 12554  **   returned by an earlier call to xCreate().
 12555  **
 12556  **   The second argument indicates the reason that FTS5 is requesting
 12557  **   tokenization of the supplied text. This is always one of the following
 12558  **   four values:
 12559  **
 12560  **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
 12561  **            or removed from the FTS table. The tokenizer is being invoked to
 12562  **            determine the set of tokens to add to (or delete from) the
 12563  **            FTS index.
 12564  **
 12565  **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
 12566  **            against the FTS index. The tokenizer is being called to tokenize 
 12567  **            a bareword or quoted string specified as part of the query.
 12568  **
 12569  **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
 12570  **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
 12571  **            followed by a "*" character, indicating that the last token
 12572  **            returned by the tokenizer will be treated as a token prefix.
 12573  **
 12574  **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
 12575  **            satisfy an fts5_api.xTokenize() request made by an auxiliary
 12576  **            function. Or an fts5_api.xColumnSize() request made by the same
 12577  **            on a columnsize=0 database.  
 12578  **   </ul>
 12579  **
 12580  **   For each token in the input string, the supplied callback xToken() must
 12581  **   be invoked. The first argument to it should be a copy of the pointer
 12582  **   passed as the second argument to xTokenize(). The third and fourth
 12583  **   arguments are a pointer to a buffer containing the token text, and the
 12584  **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
 12585  **   of the first byte of and first byte immediately following the text from
 12586  **   which the token is derived within the input.
 12587  **
 12588  **   The second argument passed to the xToken() callback ("tflags") should
 12589  **   normally be set to 0. The exception is if the tokenizer supports 
 12590  **   synonyms. In this case see the discussion below for details.
 12591  **
 12592  **   FTS5 assumes the xToken() callback is invoked for each token in the 
 12593  **   order that they occur within the input text.
 12594  **
 12595  **   If an xToken() callback returns any value other than SQLITE_OK, then
 12596  **   the tokenization should be abandoned and the xTokenize() method should
 12597  **   immediately return a copy of the xToken() return value. Or, if the
 12598  **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
 12599  **   if an error occurs with the xTokenize() implementation itself, it
 12600  **   may abandon the tokenization and return any error code other than
 12601  **   SQLITE_OK or SQLITE_DONE.
 12602  **
 12603  ** SYNONYM SUPPORT
 12604  **
 12605  **   Custom tokenizers may also support synonyms. Consider a case in which a
 12606  **   user wishes to query for a phrase such as "first place". Using the 
 12607  **   built-in tokenizers, the FTS5 query 'first + place' will match instances
 12608  **   of "first place" within the document set, but not alternative forms
 12609  **   such as "1st place". In some applications, it would be better to match
 12610  **   all instances of "first place" or "1st place" regardless of which form
 12611  **   the user specified in the MATCH query text.
 12612  **
 12613  **   There are several ways to approach this in FTS5:
 12614  **
 12615  **   <ol><li> By mapping all synonyms to a single token. In this case, the 
 12616  **            In the above example, this means that the tokenizer returns the
 12617  **            same token for inputs "first" and "1st". Say that token is in
 12618  **            fact "first", so that when the user inserts the document "I won
 12619  **            1st place" entries are added to the index for tokens "i", "won",
 12620  **            "first" and "place". If the user then queries for '1st + place',
 12621  **            the tokenizer substitutes "first" for "1st" and the query works
 12622  **            as expected.
 12623  **
 12624  **       <li> By querying the index for all synonyms of each query term
 12625  **            separately. In this case, when tokenizing query text, the
 12626  **            tokenizer may provide multiple synonyms for a single term 
 12627  **            within the document. FTS5 then queries the index for each 
 12628  **            synonym individually. For example, faced with the query:
 12629  **
 12630  **   <codeblock>
 12631  **     ... MATCH 'first place'</codeblock>
 12632  **
 12633  **            the tokenizer offers both "1st" and "first" as synonyms for the
 12634  **            first token in the MATCH query and FTS5 effectively runs a query 
 12635  **            similar to:
 12636  **
 12637  **   <codeblock>
 12638  **     ... MATCH '(first OR 1st) place'</codeblock>
 12639  **
 12640  **            except that, for the purposes of auxiliary functions, the query
 12641  **            still appears to contain just two phrases - "(first OR 1st)" 
 12642  **            being treated as a single phrase.
 12643  **
 12644  **       <li> By adding multiple synonyms for a single term to the FTS index.
 12645  **            Using this method, when tokenizing document text, the tokenizer
 12646  **            provides multiple synonyms for each token. So that when a 
 12647  **            document such as "I won first place" is tokenized, entries are
 12648  **            added to the FTS index for "i", "won", "first", "1st" and
 12649  **            "place".
 12650  **
 12651  **            This way, even if the tokenizer does not provide synonyms
 12652  **            when tokenizing query text (it should not - to do so would be
 12653  **            inefficient), it doesn't matter if the user queries for 
 12654  **            'first + place' or '1st + place', as there are entries in the
 12655  **            FTS index corresponding to both forms of the first token.
 12656  **   </ol>
 12657  **
 12658  **   Whether it is parsing document or query text, any call to xToken that
 12659  **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
 12660  **   is considered to supply a synonym for the previous token. For example,
 12661  **   when parsing the document "I won first place", a tokenizer that supports
 12662  **   synonyms would call xToken() 5 times, as follows:
 12663  **
 12664  **   <codeblock>
 12665  **       xToken(pCtx, 0, "i",                      1,  0,  1);
 12666  **       xToken(pCtx, 0, "won",                    3,  2,  5);
 12667  **       xToken(pCtx, 0, "first",                  5,  6, 11);
 12668  **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
 12669  **       xToken(pCtx, 0, "place",                  5, 12, 17);
 12670  **</codeblock>
 12671  **
 12672  **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
 12673  **   xToken() is called. Multiple synonyms may be specified for a single token
 12674  **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
 12675  **   There is no limit to the number of synonyms that may be provided for a
 12676  **   single token.
 12677  **
 12678  **   In many cases, method (1) above is the best approach. It does not add 
 12679  **   extra data to the FTS index or require FTS5 to query for multiple terms,
 12680  **   so it is efficient in terms of disk space and query speed. However, it
 12681  **   does not support prefix queries very well. If, as suggested above, the
 12682  **   token "first" is substituted for "1st" by the tokenizer, then the query:
 12683  **
 12684  **   <codeblock>
 12685  **     ... MATCH '1s*'</codeblock>
 12686  **
 12687  **   will not match documents that contain the token "1st" (as the tokenizer
 12688  **   will probably not map "1s" to any prefix of "first").
 12689  **
 12690  **   For full prefix support, method (3) may be preferred. In this case, 
 12691  **   because the index contains entries for both "first" and "1st", prefix
 12692  **   queries such as 'fi*' or '1s*' will match correctly. However, because
 12693  **   extra entries are added to the FTS index, this method uses more space
 12694  **   within the database.
 12695  **
 12696  **   Method (2) offers a midpoint between (1) and (3). Using this method,
 12697  **   a query such as '1s*' will match documents that contain the literal 
 12698  **   token "1st", but not "first" (assuming the tokenizer is not able to
 12699  **   provide synonyms for prefixes). However, a non-prefix query like '1st'
 12700  **   will match against "1st" and "first". This method does not require
 12701  **   extra disk space, as no extra entries are added to the FTS index. 
 12702  **   On the other hand, it may require more CPU cycles to run MATCH queries,
 12703  **   as separate queries of the FTS index are required for each synonym.
 12704  **
 12705  **   When using methods (2) or (3), it is important that the tokenizer only
 12706  **   provide synonyms when tokenizing document text (method (2)) or query
 12707  **   text (method (3)), not both. Doing so will not cause any errors, but is
 12708  **   inefficient.
 12709  */
 12710  typedef struct Fts5Tokenizer Fts5Tokenizer;
 12711  typedef struct fts5_tokenizer fts5_tokenizer;
 12712  struct fts5_tokenizer {
 12713    int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
 12714    void (*xDelete)(Fts5Tokenizer*);
 12715    int (*xTokenize)(Fts5Tokenizer*, 
 12716        void *pCtx,
 12717        int flags,            /* Mask of FTS5_TOKENIZE_* flags */
 12718        const char *pText, int nText, 
 12719        int (*xToken)(
 12720          void *pCtx,         /* Copy of 2nd argument to xTokenize() */
 12721          int tflags,         /* Mask of FTS5_TOKEN_* flags */
 12722          const char *pToken, /* Pointer to buffer containing token */
 12723          int nToken,         /* Size of token in bytes */
 12724          int iStart,         /* Byte offset of token within input text */
 12725          int iEnd            /* Byte offset of end of token within input text */
 12726        )
 12727    );
 12728  };
 12729  
 12730  /* Flags that may be passed as the third argument to xTokenize() */
 12731  #define FTS5_TOKENIZE_QUERY     0x0001
 12732  #define FTS5_TOKENIZE_PREFIX    0x0002
 12733  #define FTS5_TOKENIZE_DOCUMENT  0x0004
 12734  #define FTS5_TOKENIZE_AUX       0x0008
 12735  
 12736  /* Flags that may be passed by the tokenizer implementation back to FTS5
 12737  ** as the third argument to the supplied xToken callback. */
 12738  #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
 12739  
 12740  /*
 12741  ** END OF CUSTOM TOKENIZERS
 12742  *************************************************************************/
 12743  
 12744  /*************************************************************************
 12745  ** FTS5 EXTENSION REGISTRATION API
 12746  */
 12747  typedef struct fts5_api fts5_api;
 12748  struct fts5_api {
 12749    int iVersion;                   /* Currently always set to 2 */
 12750  
 12751    /* Create a new tokenizer */
 12752    int (*xCreateTokenizer)(
 12753      fts5_api *pApi,
 12754      const char *zName,
 12755      void *pContext,
 12756      fts5_tokenizer *pTokenizer,
 12757      void (*xDestroy)(void*)
 12758    );
 12759  
 12760    /* Find an existing tokenizer */
 12761    int (*xFindTokenizer)(
 12762      fts5_api *pApi,
 12763      const char *zName,
 12764      void **ppContext,
 12765      fts5_tokenizer *pTokenizer
 12766    );
 12767  
 12768    /* Create a new auxiliary function */
 12769    int (*xCreateFunction)(
 12770      fts5_api *pApi,
 12771      const char *zName,
 12772      void *pContext,
 12773      fts5_extension_function xFunction,
 12774      void (*xDestroy)(void*)
 12775    );
 12776  };
 12777  
 12778  /*
 12779  ** END OF REGISTRATION API
 12780  *************************************************************************/
 12781  
 12782  #if 0
 12783  }  /* end of the 'extern "C"' block */
 12784  #endif
 12785  
 12786  #endif /* _FTS5_H */
 12787  
 12788  /******** End of fts5.h *********/
 12789  
 12790  /************** End of sqlite3.h *********************************************/
 12791  /************** Continuing where we left off in sqliteInt.h ******************/
 12792  
 12793  /*
 12794  ** Include the configuration header output by 'configure' if we're using the
 12795  ** autoconf-based build
 12796  */
 12797  #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
 12798  /* #include "config.h" */
 12799  #define SQLITECONFIG_H 1
 12800  #endif
 12801  
 12802  /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
 12803  /************** Begin file sqliteLimit.h *************************************/
 12804  /*
 12805  ** 2007 May 7
 12806  **
 12807  ** The author disclaims copyright to this source code.  In place of
 12808  ** a legal notice, here is a blessing:
 12809  **
 12810  **    May you do good and not evil.
 12811  **    May you find forgiveness for yourself and forgive others.
 12812  **    May you share freely, never taking more than you give.
 12813  **
 12814  *************************************************************************
 12815  ** 
 12816  ** This file defines various limits of what SQLite can process.
 12817  */
 12818  
 12819  /*
 12820  ** The maximum length of a TEXT or BLOB in bytes.   This also
 12821  ** limits the size of a row in a table or index.
 12822  **
 12823  ** The hard limit is the ability of a 32-bit signed integer
 12824  ** to count the size: 2^31-1 or 2147483647.
 12825  */
 12826  #ifndef SQLITE_MAX_LENGTH
 12827  # define SQLITE_MAX_LENGTH 1000000000
 12828  #endif
 12829  
 12830  /*
 12831  ** This is the maximum number of
 12832  **
 12833  **    * Columns in a table
 12834  **    * Columns in an index
 12835  **    * Columns in a view
 12836  **    * Terms in the SET clause of an UPDATE statement
 12837  **    * Terms in the result set of a SELECT statement
 12838  **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
 12839  **    * Terms in the VALUES clause of an INSERT statement
 12840  **
 12841  ** The hard upper limit here is 32676.  Most database people will
 12842  ** tell you that in a well-normalized database, you usually should
 12843  ** not have more than a dozen or so columns in any table.  And if
 12844  ** that is the case, there is no point in having more than a few
 12845  ** dozen values in any of the other situations described above.
 12846  */
 12847  #ifndef SQLITE_MAX_COLUMN
 12848  # define SQLITE_MAX_COLUMN 2000
 12849  #endif
 12850  
 12851  /*
 12852  ** The maximum length of a single SQL statement in bytes.
 12853  **
 12854  ** It used to be the case that setting this value to zero would
 12855  ** turn the limit off.  That is no longer true.  It is not possible
 12856  ** to turn this limit off.
 12857  */
 12858  #ifndef SQLITE_MAX_SQL_LENGTH
 12859  # define SQLITE_MAX_SQL_LENGTH 1000000000
 12860  #endif
 12861  
 12862  /*
 12863  ** The maximum depth of an expression tree. This is limited to 
 12864  ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
 12865  ** want to place more severe limits on the complexity of an 
 12866  ** expression.
 12867  **
 12868  ** A value of 0 used to mean that the limit was not enforced.
 12869  ** But that is no longer true.  The limit is now strictly enforced
 12870  ** at all times.
 12871  */
 12872  #ifndef SQLITE_MAX_EXPR_DEPTH
 12873  # define SQLITE_MAX_EXPR_DEPTH 1000
 12874  #endif
 12875  
 12876  /*
 12877  ** The maximum number of terms in a compound SELECT statement.
 12878  ** The code generator for compound SELECT statements does one
 12879  ** level of recursion for each term.  A stack overflow can result
 12880  ** if the number of terms is too large.  In practice, most SQL
 12881  ** never has more than 3 or 4 terms.  Use a value of 0 to disable
 12882  ** any limit on the number of terms in a compount SELECT.
 12883  */
 12884  #ifndef SQLITE_MAX_COMPOUND_SELECT
 12885  # define SQLITE_MAX_COMPOUND_SELECT 500
 12886  #endif
 12887  
 12888  /*
 12889  ** The maximum number of opcodes in a VDBE program.
 12890  ** Not currently enforced.
 12891  */
 12892  #ifndef SQLITE_MAX_VDBE_OP
 12893  # define SQLITE_MAX_VDBE_OP 250000000
 12894  #endif
 12895  
 12896  /*
 12897  ** The maximum number of arguments to an SQL function.
 12898  */
 12899  #ifndef SQLITE_MAX_FUNCTION_ARG
 12900  # define SQLITE_MAX_FUNCTION_ARG 127
 12901  #endif
 12902  
 12903  /*
 12904  ** The suggested maximum number of in-memory pages to use for
 12905  ** the main database table and for temporary tables.
 12906  **
 12907  ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
 12908  ** which means the cache size is limited to 2048000 bytes of memory.
 12909  ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
 12910  ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
 12911  */
 12912  #ifndef SQLITE_DEFAULT_CACHE_SIZE
 12913  # define SQLITE_DEFAULT_CACHE_SIZE  -2000
 12914  #endif
 12915  
 12916  /*
 12917  ** The default number of frames to accumulate in the log file before
 12918  ** checkpointing the database in WAL mode.
 12919  */
 12920  #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
 12921  # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
 12922  #endif
 12923  
 12924  /*
 12925  ** The maximum number of attached databases.  This must be between 0
 12926  ** and 125.  The upper bound of 125 is because the attached databases are
 12927  ** counted using a signed 8-bit integer which has a maximum value of 127
 12928  ** and we have to allow 2 extra counts for the "main" and "temp" databases.
 12929  */
 12930  #ifndef SQLITE_MAX_ATTACHED
 12931  # define SQLITE_MAX_ATTACHED 10
 12932  #endif
 12933  
 12934  
 12935  /*
 12936  ** The maximum value of a ?nnn wildcard that the parser will accept.
 12937  */
 12938  #ifndef SQLITE_MAX_VARIABLE_NUMBER
 12939  # define SQLITE_MAX_VARIABLE_NUMBER 999
 12940  #endif
 12941  
 12942  /* Maximum page size.  The upper bound on this value is 65536.  This a limit
 12943  ** imposed by the use of 16-bit offsets within each page.
 12944  **
 12945  ** Earlier versions of SQLite allowed the user to change this value at
 12946  ** compile time. This is no longer permitted, on the grounds that it creates
 12947  ** a library that is technically incompatible with an SQLite library 
 12948  ** compiled with a different limit. If a process operating on a database 
 12949  ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
 12950  ** compiled with the default page-size limit will not be able to rollback 
 12951  ** the aborted transaction. This could lead to database corruption.
 12952  */
 12953  #ifdef SQLITE_MAX_PAGE_SIZE
 12954  # undef SQLITE_MAX_PAGE_SIZE
 12955  #endif
 12956  #define SQLITE_MAX_PAGE_SIZE 65536
 12957  
 12958  
 12959  /*
 12960  ** The default size of a database page.
 12961  */
 12962  #ifndef SQLITE_DEFAULT_PAGE_SIZE
 12963  # define SQLITE_DEFAULT_PAGE_SIZE 4096
 12964  #endif
 12965  #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 12966  # undef SQLITE_DEFAULT_PAGE_SIZE
 12967  # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 12968  #endif
 12969  
 12970  /*
 12971  ** Ordinarily, if no value is explicitly provided, SQLite creates databases
 12972  ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
 12973  ** device characteristics (sector-size and atomic write() support),
 12974  ** SQLite may choose a larger value. This constant is the maximum value
 12975  ** SQLite will choose on its own.
 12976  */
 12977  #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
 12978  # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
 12979  #endif
 12980  #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
 12981  # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
 12982  # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
 12983  #endif
 12984  
 12985  
 12986  /*
 12987  ** Maximum number of pages in one database file.
 12988  **
 12989  ** This is really just the default value for the max_page_count pragma.
 12990  ** This value can be lowered (or raised) at run-time using that the
 12991  ** max_page_count macro.
 12992  */
 12993  #ifndef SQLITE_MAX_PAGE_COUNT
 12994  # define SQLITE_MAX_PAGE_COUNT 1073741823
 12995  #endif
 12996  
 12997  /*
 12998  ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
 12999  ** operator.
 13000  */
 13001  #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
 13002  # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
 13003  #endif
 13004  
 13005  /*
 13006  ** Maximum depth of recursion for triggers.
 13007  **
 13008  ** A value of 1 means that a trigger program will not be able to itself
 13009  ** fire any triggers. A value of 0 means that no trigger programs at all 
 13010  ** may be executed.
 13011  */
 13012  #ifndef SQLITE_MAX_TRIGGER_DEPTH
 13013  # define SQLITE_MAX_TRIGGER_DEPTH 1000
 13014  #endif
 13015  
 13016  /************** End of sqliteLimit.h *****************************************/
 13017  /************** Continuing where we left off in sqliteInt.h ******************/
 13018  
 13019  /* Disable nuisance warnings on Borland compilers */
 13020  #if defined(__BORLANDC__)
 13021  #pragma warn -rch /* unreachable code */
 13022  #pragma warn -ccc /* Condition is always true or false */
 13023  #pragma warn -aus /* Assigned value is never used */
 13024  #pragma warn -csu /* Comparing signed and unsigned */
 13025  #pragma warn -spa /* Suspicious pointer arithmetic */
 13026  #endif
 13027  
 13028  /*
 13029  ** Include standard header files as necessary
 13030  */
 13031  #ifdef HAVE_STDINT_H
 13032  #include <stdint.h>
 13033  #endif
 13034  #ifdef HAVE_INTTYPES_H
 13035  #include <inttypes.h>
 13036  #endif
 13037  
 13038  /*
 13039  ** The following macros are used to cast pointers to integers and
 13040  ** integers to pointers.  The way you do this varies from one compiler
 13041  ** to the next, so we have developed the following set of #if statements
 13042  ** to generate appropriate macros for a wide range of compilers.
 13043  **
 13044  ** The correct "ANSI" way to do this is to use the intptr_t type.
 13045  ** Unfortunately, that typedef is not available on all compilers, or
 13046  ** if it is available, it requires an #include of specific headers
 13047  ** that vary from one machine to the next.
 13048  **
 13049  ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
 13050  ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
 13051  ** So we have to define the macros in different ways depending on the
 13052  ** compiler.
 13053  */
 13054  #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
 13055  # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
 13056  # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
 13057  #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
 13058  # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
 13059  # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
 13060  #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
 13061  # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
 13062  # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
 13063  #else                          /* Generates a warning - but it always works */
 13064  # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
 13065  # define SQLITE_PTR_TO_INT(X)  ((int)(X))
 13066  #endif
 13067  
 13068  /*
 13069  ** A macro to hint to the compiler that a function should not be
 13070  ** inlined.
 13071  */
 13072  #if defined(__GNUC__)
 13073  #  define SQLITE_NOINLINE  __attribute__((noinline))
 13074  #elif defined(_MSC_VER) && _MSC_VER>=1310
 13075  #  define SQLITE_NOINLINE  __declspec(noinline)
 13076  #else
 13077  #  define SQLITE_NOINLINE
 13078  #endif
 13079  
 13080  /*
 13081  ** Make sure that the compiler intrinsics we desire are enabled when
 13082  ** compiling with an appropriate version of MSVC unless prevented by
 13083  ** the SQLITE_DISABLE_INTRINSIC define.
 13084  */
 13085  #if !defined(SQLITE_DISABLE_INTRINSIC)
 13086  #  if defined(_MSC_VER) && _MSC_VER>=1400
 13087  #    if !defined(_WIN32_WCE)
 13088  #      include <intrin.h>
 13089  #      pragma intrinsic(_byteswap_ushort)
 13090  #      pragma intrinsic(_byteswap_ulong)
 13091  #      pragma intrinsic(_byteswap_uint64)
 13092  #      pragma intrinsic(_ReadWriteBarrier)
 13093  #    else
 13094  #      include <cmnintrin.h>
 13095  #    endif
 13096  #  endif
 13097  #endif
 13098  
 13099  /*
 13100  ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
 13101  ** 0 means mutexes are permanently disable and the library is never
 13102  ** threadsafe.  1 means the library is serialized which is the highest
 13103  ** level of threadsafety.  2 means the library is multithreaded - multiple
 13104  ** threads can use SQLite as long as no two threads try to use the same
 13105  ** database connection at the same time.
 13106  **
 13107  ** Older versions of SQLite used an optional THREADSAFE macro.
 13108  ** We support that for legacy.
 13109  **
 13110  ** To ensure that the correct value of "THREADSAFE" is reported when querying
 13111  ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
 13112  ** logic is partially replicated in ctime.c. If it is updated here, it should
 13113  ** also be updated there.
 13114  */
 13115  #if !defined(SQLITE_THREADSAFE)
 13116  # if defined(THREADSAFE)
 13117  #   define SQLITE_THREADSAFE THREADSAFE
 13118  # else
 13119  #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
 13120  # endif
 13121  #endif
 13122  
 13123  /*
 13124  ** Powersafe overwrite is on by default.  But can be turned off using
 13125  ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
 13126  */
 13127  #ifndef SQLITE_POWERSAFE_OVERWRITE
 13128  # define SQLITE_POWERSAFE_OVERWRITE 1
 13129  #endif
 13130  
 13131  /*
 13132  ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
 13133  ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
 13134  ** which case memory allocation statistics are disabled by default.
 13135  */
 13136  #if !defined(SQLITE_DEFAULT_MEMSTATUS)
 13137  # define SQLITE_DEFAULT_MEMSTATUS 1
 13138  #endif
 13139  
 13140  /*
 13141  ** Exactly one of the following macros must be defined in order to
 13142  ** specify which memory allocation subsystem to use.
 13143  **
 13144  **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
 13145  **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
 13146  **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
 13147  **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
 13148  **
 13149  ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
 13150  ** assert() macro is enabled, each call into the Win32 native heap subsystem
 13151  ** will cause HeapValidate to be called.  If heap validation should fail, an
 13152  ** assertion will be triggered.
 13153  **
 13154  ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
 13155  ** the default.
 13156  */
 13157  #if defined(SQLITE_SYSTEM_MALLOC) \
 13158    + defined(SQLITE_WIN32_MALLOC) \
 13159    + defined(SQLITE_ZERO_MALLOC) \
 13160    + defined(SQLITE_MEMDEBUG)>1
 13161  # error "Two or more of the following compile-time configuration options\
 13162   are defined but at most one is allowed:\
 13163   SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
 13164   SQLITE_ZERO_MALLOC"
 13165  #endif
 13166  #if defined(SQLITE_SYSTEM_MALLOC) \
 13167    + defined(SQLITE_WIN32_MALLOC) \
 13168    + defined(SQLITE_ZERO_MALLOC) \
 13169    + defined(SQLITE_MEMDEBUG)==0
 13170  # define SQLITE_SYSTEM_MALLOC 1
 13171  #endif
 13172  
 13173  /*
 13174  ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
 13175  ** sizes of memory allocations below this value where possible.
 13176  */
 13177  #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
 13178  # define SQLITE_MALLOC_SOFT_LIMIT 1024
 13179  #endif
 13180  
 13181  /*
 13182  ** We need to define _XOPEN_SOURCE as follows in order to enable
 13183  ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
 13184  ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
 13185  ** it.
 13186  */
 13187  #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
 13188  #  define _XOPEN_SOURCE 600
 13189  #endif
 13190  
 13191  /*
 13192  ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
 13193  ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
 13194  ** make it true by defining or undefining NDEBUG.
 13195  **
 13196  ** Setting NDEBUG makes the code smaller and faster by disabling the
 13197  ** assert() statements in the code.  So we want the default action
 13198  ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
 13199  ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
 13200  ** feature.
 13201  */
 13202  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 13203  # define NDEBUG 1
 13204  #endif
 13205  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
 13206  # undef NDEBUG
 13207  #endif
 13208  
 13209  /*
 13210  ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
 13211  */
 13212  #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
 13213  # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
 13214  #endif
 13215  
 13216  /*
 13217  ** The testcase() macro is used to aid in coverage testing.  When
 13218  ** doing coverage testing, the condition inside the argument to
 13219  ** testcase() must be evaluated both true and false in order to
 13220  ** get full branch coverage.  The testcase() macro is inserted
 13221  ** to help ensure adequate test coverage in places where simple
 13222  ** condition/decision coverage is inadequate.  For example, testcase()
 13223  ** can be used to make sure boundary values are tested.  For
 13224  ** bitmask tests, testcase() can be used to make sure each bit
 13225  ** is significant and used at least once.  On switch statements
 13226  ** where multiple cases go to the same block of code, testcase()
 13227  ** can insure that all cases are evaluated.
 13228  **
 13229  */
 13230  #ifdef SQLITE_COVERAGE_TEST
 13231  SQLITE_PRIVATE   void sqlite3Coverage(int);
 13232  # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
 13233  #else
 13234  # define testcase(X)
 13235  #endif
 13236  
 13237  /*
 13238  ** The TESTONLY macro is used to enclose variable declarations or
 13239  ** other bits of code that are needed to support the arguments
 13240  ** within testcase() and assert() macros.
 13241  */
 13242  #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
 13243  # define TESTONLY(X)  X
 13244  #else
 13245  # define TESTONLY(X)
 13246  #endif
 13247  
 13248  /*
 13249  ** Sometimes we need a small amount of code such as a variable initialization
 13250  ** to setup for a later assert() statement.  We do not want this code to
 13251  ** appear when assert() is disabled.  The following macro is therefore
 13252  ** used to contain that setup code.  The "VVA" acronym stands for
 13253  ** "Verification, Validation, and Accreditation".  In other words, the
 13254  ** code within VVA_ONLY() will only run during verification processes.
 13255  */
 13256  #ifndef NDEBUG
 13257  # define VVA_ONLY(X)  X
 13258  #else
 13259  # define VVA_ONLY(X)
 13260  #endif
 13261  
 13262  /*
 13263  ** The ALWAYS and NEVER macros surround boolean expressions which
 13264  ** are intended to always be true or false, respectively.  Such
 13265  ** expressions could be omitted from the code completely.  But they
 13266  ** are included in a few cases in order to enhance the resilience
 13267  ** of SQLite to unexpected behavior - to make the code "self-healing"
 13268  ** or "ductile" rather than being "brittle" and crashing at the first
 13269  ** hint of unplanned behavior.
 13270  **
 13271  ** In other words, ALWAYS and NEVER are added for defensive code.
 13272  **
 13273  ** When doing coverage testing ALWAYS and NEVER are hard-coded to
 13274  ** be true and false so that the unreachable code they specify will
 13275  ** not be counted as untested code.
 13276  */
 13277  #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
 13278  # define ALWAYS(X)      (1)
 13279  # define NEVER(X)       (0)
 13280  #elif !defined(NDEBUG)
 13281  # define ALWAYS(X)      ((X)?1:(assert(0),0))
 13282  # define NEVER(X)       ((X)?(assert(0),1):0)
 13283  #else
 13284  # define ALWAYS(X)      (X)
 13285  # define NEVER(X)       (X)
 13286  #endif
 13287  
 13288  /*
 13289  ** Some conditionals are optimizations only.  In other words, if the
 13290  ** conditionals are replaced with a constant 1 (true) or 0 (false) then
 13291  ** the correct answer is still obtained, though perhaps not as quickly.
 13292  **
 13293  ** The following macros mark these optimizations conditionals.
 13294  */
 13295  #if defined(SQLITE_MUTATION_TEST)
 13296  # define OK_IF_ALWAYS_TRUE(X)  (1)
 13297  # define OK_IF_ALWAYS_FALSE(X) (0)
 13298  #else
 13299  # define OK_IF_ALWAYS_TRUE(X)  (X)
 13300  # define OK_IF_ALWAYS_FALSE(X) (X)
 13301  #endif
 13302  
 13303  /*
 13304  ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
 13305  ** defined.  We need to defend against those failures when testing with
 13306  ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
 13307  ** during a normal build.  The following macro can be used to disable tests
 13308  ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
 13309  */
 13310  #if defined(SQLITE_TEST_REALLOC_STRESS)
 13311  # define ONLY_IF_REALLOC_STRESS(X)  (X)
 13312  #elif !defined(NDEBUG)
 13313  # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
 13314  #else
 13315  # define ONLY_IF_REALLOC_STRESS(X)  (0)
 13316  #endif
 13317  
 13318  /*
 13319  ** Declarations used for tracing the operating system interfaces.
 13320  */
 13321  #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
 13322      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
 13323    extern int sqlite3OSTrace;
 13324  # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
 13325  # define SQLITE_HAVE_OS_TRACE
 13326  #else
 13327  # define OSTRACE(X)
 13328  # undef  SQLITE_HAVE_OS_TRACE
 13329  #endif
 13330  
 13331  /*
 13332  ** Is the sqlite3ErrName() function needed in the build?  Currently,
 13333  ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
 13334  ** OSTRACE is enabled), and by several "test*.c" files (which are
 13335  ** compiled using SQLITE_TEST).
 13336  */
 13337  #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
 13338      (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
 13339  # define SQLITE_NEED_ERR_NAME
 13340  #else
 13341  # undef  SQLITE_NEED_ERR_NAME
 13342  #endif
 13343  
 13344  /*
 13345  ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
 13346  */
 13347  #ifdef SQLITE_OMIT_EXPLAIN
 13348  # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
 13349  #endif
 13350  
 13351  /*
 13352  ** Return true (non-zero) if the input is an integer that is too large
 13353  ** to fit in 32-bits.  This macro is used inside of various testcase()
 13354  ** macros to verify that we have tested SQLite for large-file support.
 13355  */
 13356  #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
 13357  
 13358  /*
 13359  ** The macro unlikely() is a hint that surrounds a boolean
 13360  ** expression that is usually false.  Macro likely() surrounds
 13361  ** a boolean expression that is usually true.  These hints could,
 13362  ** in theory, be used by the compiler to generate better code, but
 13363  ** currently they are just comments for human readers.
 13364  */
 13365  #define likely(X)    (X)
 13366  #define unlikely(X)  (X)
 13367  
 13368  /************** Include hash.h in the middle of sqliteInt.h ******************/
 13369  /************** Begin file hash.h ********************************************/
 13370  /*
 13371  ** 2001 September 22
 13372  **
 13373  ** The author disclaims copyright to this source code.  In place of
 13374  ** a legal notice, here is a blessing:
 13375  **
 13376  **    May you do good and not evil.
 13377  **    May you find forgiveness for yourself and forgive others.
 13378  **    May you share freely, never taking more than you give.
 13379  **
 13380  *************************************************************************
 13381  ** This is the header file for the generic hash-table implementation
 13382  ** used in SQLite.
 13383  */
 13384  #ifndef SQLITE_HASH_H
 13385  #define SQLITE_HASH_H
 13386  
 13387  /* Forward declarations of structures. */
 13388  typedef struct Hash Hash;
 13389  typedef struct HashElem HashElem;
 13390  
 13391  /* A complete hash table is an instance of the following structure.
 13392  ** The internals of this structure are intended to be opaque -- client
 13393  ** code should not attempt to access or modify the fields of this structure
 13394  ** directly.  Change this structure only by using the routines below.
 13395  ** However, some of the "procedures" and "functions" for modifying and
 13396  ** accessing this structure are really macros, so we can't really make
 13397  ** this structure opaque.
 13398  **
 13399  ** All elements of the hash table are on a single doubly-linked list.
 13400  ** Hash.first points to the head of this list.
 13401  **
 13402  ** There are Hash.htsize buckets.  Each bucket points to a spot in
 13403  ** the global doubly-linked list.  The contents of the bucket are the
 13404  ** element pointed to plus the next _ht.count-1 elements in the list.
 13405  **
 13406  ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
 13407  ** by a linear search of the global list.  For small tables, the 
 13408  ** Hash.ht table is never allocated because if there are few elements
 13409  ** in the table, it is faster to do a linear search than to manage
 13410  ** the hash table.
 13411  */
 13412  struct Hash {
 13413    unsigned int htsize;      /* Number of buckets in the hash table */
 13414    unsigned int count;       /* Number of entries in this table */
 13415    HashElem *first;          /* The first element of the array */
 13416    struct _ht {              /* the hash table */
 13417      int count;                 /* Number of entries with this hash */
 13418      HashElem *chain;           /* Pointer to first entry with this hash */
 13419    } *ht;
 13420  };
 13421  
 13422  /* Each element in the hash table is an instance of the following 
 13423  ** structure.  All elements are stored on a single doubly-linked list.
 13424  **
 13425  ** Again, this structure is intended to be opaque, but it can't really
 13426  ** be opaque because it is used by macros.
 13427  */
 13428  struct HashElem {
 13429    HashElem *next, *prev;       /* Next and previous elements in the table */
 13430    void *data;                  /* Data associated with this element */
 13431    const char *pKey;            /* Key associated with this element */
 13432  };
 13433  
 13434  /*
 13435  ** Access routines.  To delete, insert a NULL pointer.
 13436  */
 13437  SQLITE_PRIVATE void sqlite3HashInit(Hash*);
 13438  SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
 13439  SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
 13440  SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 13441  
 13442  /*
 13443  ** Macros for looping over all elements of a hash table.  The idiom is
 13444  ** like this:
 13445  **
 13446  **   Hash h;
 13447  **   HashElem *p;
 13448  **   ...
 13449  **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
 13450  **     SomeStructure *pData = sqliteHashData(p);
 13451  **     // do something with pData
 13452  **   }
 13453  */
 13454  #define sqliteHashFirst(H)  ((H)->first)
 13455  #define sqliteHashNext(E)   ((E)->next)
 13456  #define sqliteHashData(E)   ((E)->data)
 13457  /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
 13458  /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
 13459  
 13460  /*
 13461  ** Number of entries in a hash table
 13462  */
 13463  /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
 13464  
 13465  #endif /* SQLITE_HASH_H */
 13466  
 13467  /************** End of hash.h ************************************************/
 13468  /************** Continuing where we left off in sqliteInt.h ******************/
 13469  /************** Include parse.h in the middle of sqliteInt.h *****************/
 13470  /************** Begin file parse.h *******************************************/
 13471  #define TK_SEMI                             1
 13472  #define TK_EXPLAIN                          2
 13473  #define TK_QUERY                            3
 13474  #define TK_PLAN                             4
 13475  #define TK_BEGIN                            5
 13476  #define TK_TRANSACTION                      6
 13477  #define TK_DEFERRED                         7
 13478  #define TK_IMMEDIATE                        8
 13479  #define TK_EXCLUSIVE                        9
 13480  #define TK_COMMIT                          10
 13481  #define TK_END                             11
 13482  #define TK_ROLLBACK                        12
 13483  #define TK_SAVEPOINT                       13
 13484  #define TK_RELEASE                         14
 13485  #define TK_TO                              15
 13486  #define TK_TABLE                           16
 13487  #define TK_CREATE                          17
 13488  #define TK_IF                              18
 13489  #define TK_NOT                             19
 13490  #define TK_EXISTS                          20
 13491  #define TK_TEMP                            21
 13492  #define TK_LP                              22
 13493  #define TK_RP                              23
 13494  #define TK_AS                              24
 13495  #define TK_WITHOUT                         25
 13496  #define TK_COMMA                           26
 13497  #define TK_ABORT                           27
 13498  #define TK_ACTION                          28
 13499  #define TK_AFTER                           29
 13500  #define TK_ANALYZE                         30
 13501  #define TK_ASC                             31
 13502  #define TK_ATTACH                          32
 13503  #define TK_BEFORE                          33
 13504  #define TK_BY                              34
 13505  #define TK_CASCADE                         35
 13506  #define TK_CAST                            36
 13507  #define TK_CONFLICT                        37
 13508  #define TK_DATABASE                        38
 13509  #define TK_DESC                            39
 13510  #define TK_DETACH                          40
 13511  #define TK_EACH                            41
 13512  #define TK_FAIL                            42
 13513  #define TK_OR                              43
 13514  #define TK_AND                             44
 13515  #define TK_IS                              45
 13516  #define TK_MATCH                           46
 13517  #define TK_LIKE_KW                         47
 13518  #define TK_BETWEEN                         48
 13519  #define TK_IN                              49
 13520  #define TK_ISNULL                          50
 13521  #define TK_NOTNULL                         51
 13522  #define TK_NE                              52
 13523  #define TK_EQ                              53
 13524  #define TK_GT                              54
 13525  #define TK_LE                              55
 13526  #define TK_LT                              56
 13527  #define TK_GE                              57
 13528  #define TK_ESCAPE                          58
 13529  #define TK_ID                              59
 13530  #define TK_COLUMNKW                        60
 13531  #define TK_DO                              61
 13532  #define TK_FOR                             62
 13533  #define TK_IGNORE                          63
 13534  #define TK_INITIALLY                       64
 13535  #define TK_INSTEAD                         65
 13536  #define TK_NO                              66
 13537  #define TK_KEY                             67
 13538  #define TK_OF                              68
 13539  #define TK_OFFSET                          69
 13540  #define TK_PRAGMA                          70
 13541  #define TK_RAISE                           71
 13542  #define TK_RECURSIVE                       72
 13543  #define TK_REPLACE                         73
 13544  #define TK_RESTRICT                        74
 13545  #define TK_ROW                             75
 13546  #define TK_ROWS                            76
 13547  #define TK_TRIGGER                         77
 13548  #define TK_VACUUM                          78
 13549  #define TK_VIEW                            79
 13550  #define TK_VIRTUAL                         80
 13551  #define TK_WITH                            81
 13552  #define TK_CURRENT                         82
 13553  #define TK_FOLLOWING                       83
 13554  #define TK_PARTITION                       84
 13555  #define TK_PRECEDING                       85
 13556  #define TK_RANGE                           86
 13557  #define TK_UNBOUNDED                       87
 13558  #define TK_REINDEX                         88
 13559  #define TK_RENAME                          89
 13560  #define TK_CTIME_KW                        90
 13561  #define TK_ANY                             91
 13562  #define TK_BITAND                          92
 13563  #define TK_BITOR                           93
 13564  #define TK_LSHIFT                          94
 13565  #define TK_RSHIFT                          95
 13566  #define TK_PLUS                            96
 13567  #define TK_MINUS                           97
 13568  #define TK_STAR                            98
 13569  #define TK_SLASH                           99
 13570  #define TK_REM                            100
 13571  #define TK_CONCAT                         101
 13572  #define TK_COLLATE                        102
 13573  #define TK_BITNOT                         103
 13574  #define TK_ON                             104
 13575  #define TK_INDEXED                        105
 13576  #define TK_STRING                         106
 13577  #define TK_JOIN_KW                        107
 13578  #define TK_CONSTRAINT                     108
 13579  #define TK_DEFAULT                        109
 13580  #define TK_NULL                           110
 13581  #define TK_PRIMARY                        111
 13582  #define TK_UNIQUE                         112
 13583  #define TK_CHECK                          113
 13584  #define TK_REFERENCES                     114
 13585  #define TK_AUTOINCR                       115
 13586  #define TK_INSERT                         116
 13587  #define TK_DELETE                         117
 13588  #define TK_UPDATE                         118
 13589  #define TK_SET                            119
 13590  #define TK_DEFERRABLE                     120
 13591  #define TK_FOREIGN                        121
 13592  #define TK_DROP                           122
 13593  #define TK_UNION                          123
 13594  #define TK_ALL                            124
 13595  #define TK_EXCEPT                         125
 13596  #define TK_INTERSECT                      126
 13597  #define TK_SELECT                         127
 13598  #define TK_VALUES                         128
 13599  #define TK_DISTINCT                       129
 13600  #define TK_DOT                            130
 13601  #define TK_FROM                           131
 13602  #define TK_JOIN                           132
 13603  #define TK_USING                          133
 13604  #define TK_ORDER                          134
 13605  #define TK_GROUP                          135
 13606  #define TK_HAVING                         136
 13607  #define TK_LIMIT                          137
 13608  #define TK_WHERE                          138
 13609  #define TK_INTO                           139
 13610  #define TK_NOTHING                        140
 13611  #define TK_FLOAT                          141
 13612  #define TK_BLOB                           142
 13613  #define TK_INTEGER                        143
 13614  #define TK_VARIABLE                       144
 13615  #define TK_CASE                           145
 13616  #define TK_WHEN                           146
 13617  #define TK_THEN                           147
 13618  #define TK_ELSE                           148
 13619  #define TK_INDEX                          149
 13620  #define TK_ALTER                          150
 13621  #define TK_ADD                            151
 13622  #define TK_WINDOW                         152
 13623  #define TK_OVER                           153
 13624  #define TK_FILTER                         154
 13625  #define TK_TRUEFALSE                      155
 13626  #define TK_ISNOT                          156
 13627  #define TK_FUNCTION                       157
 13628  #define TK_COLUMN                         158
 13629  #define TK_AGG_FUNCTION                   159
 13630  #define TK_AGG_COLUMN                     160
 13631  #define TK_UMINUS                         161
 13632  #define TK_UPLUS                          162
 13633  #define TK_TRUTH                          163
 13634  #define TK_REGISTER                       164
 13635  #define TK_VECTOR                         165
 13636  #define TK_SELECT_COLUMN                  166
 13637  #define TK_IF_NULL_ROW                    167
 13638  #define TK_ASTERISK                       168
 13639  #define TK_SPAN                           169
 13640  #define TK_END_OF_FILE                    170
 13641  #define TK_UNCLOSED_STRING                171
 13642  #define TK_SPACE                          172
 13643  #define TK_ILLEGAL                        173
 13644  
 13645  /* The token codes above must all fit in 8 bits */
 13646  #define TKFLG_MASK           0xff  
 13647  
 13648  /* Flags that can be added to a token code when it is not
 13649  ** being stored in a u8: */
 13650  #define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
 13651  
 13652  /************** End of parse.h ***********************************************/
 13653  /************** Continuing where we left off in sqliteInt.h ******************/
 13654  #include <stdio.h>
 13655  #include <stdlib.h>
 13656  #include <string.h>
 13657  #include <assert.h>
 13658  #include <stddef.h>
 13659  
 13660  /*
 13661  ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
 13662  ** This allows better measurements of where memcpy() is used when running
 13663  ** cachegrind.  But this macro version of memcpy() is very slow so it
 13664  ** should not be used in production.  This is a performance measurement
 13665  ** hack only.
 13666  */
 13667  #ifdef SQLITE_INLINE_MEMCPY
 13668  # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
 13669                          int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
 13670  #endif
 13671  
 13672  /*
 13673  ** If compiling for a processor that lacks floating point support,
 13674  ** substitute integer for floating-point
 13675  */
 13676  #ifdef SQLITE_OMIT_FLOATING_POINT
 13677  # define double sqlite_int64
 13678  # define float sqlite_int64
 13679  # define LONGDOUBLE_TYPE sqlite_int64
 13680  # ifndef SQLITE_BIG_DBL
 13681  #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
 13682  # endif
 13683  # define SQLITE_OMIT_DATETIME_FUNCS 1
 13684  # define SQLITE_OMIT_TRACE 1
 13685  # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 13686  # undef SQLITE_HAVE_ISNAN
 13687  #endif
 13688  #ifndef SQLITE_BIG_DBL
 13689  # define SQLITE_BIG_DBL (1e99)
 13690  #endif
 13691  
 13692  /*
 13693  ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
 13694  ** afterward. Having this macro allows us to cause the C compiler
 13695  ** to omit code used by TEMP tables without messy #ifndef statements.
 13696  */
 13697  #ifdef SQLITE_OMIT_TEMPDB
 13698  #define OMIT_TEMPDB 1
 13699  #else
 13700  #define OMIT_TEMPDB 0
 13701  #endif
 13702  
 13703  /*
 13704  ** The "file format" number is an integer that is incremented whenever
 13705  ** the VDBE-level file format changes.  The following macros define the
 13706  ** the default file format for new databases and the maximum file format
 13707  ** that the library can read.
 13708  */
 13709  #define SQLITE_MAX_FILE_FORMAT 4
 13710  #ifndef SQLITE_DEFAULT_FILE_FORMAT
 13711  # define SQLITE_DEFAULT_FILE_FORMAT 4
 13712  #endif
 13713  
 13714  /*
 13715  ** Determine whether triggers are recursive by default.  This can be
 13716  ** changed at run-time using a pragma.
 13717  */
 13718  #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
 13719  # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
 13720  #endif
 13721  
 13722  /*
 13723  ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
 13724  ** on the command-line
 13725  */
 13726  #ifndef SQLITE_TEMP_STORE
 13727  # define SQLITE_TEMP_STORE 1
 13728  #endif
 13729  
 13730  /*
 13731  ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
 13732  ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
 13733  ** to zero.
 13734  */
 13735  #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
 13736  # undef SQLITE_MAX_WORKER_THREADS
 13737  # define SQLITE_MAX_WORKER_THREADS 0
 13738  #endif
 13739  #ifndef SQLITE_MAX_WORKER_THREADS
 13740  # define SQLITE_MAX_WORKER_THREADS 8
 13741  #endif
 13742  #ifndef SQLITE_DEFAULT_WORKER_THREADS
 13743  # define SQLITE_DEFAULT_WORKER_THREADS 0
 13744  #endif
 13745  #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
 13746  # undef SQLITE_MAX_WORKER_THREADS
 13747  # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
 13748  #endif
 13749  
 13750  /*
 13751  ** The default initial allocation for the pagecache when using separate
 13752  ** pagecaches for each database connection.  A positive number is the
 13753  ** number of pages.  A negative number N translations means that a buffer
 13754  ** of -1024*N bytes is allocated and used for as many pages as it will hold.
 13755  **
 13756  ** The default value of "20" was choosen to minimize the run-time of the
 13757  ** speedtest1 test program with options: --shrink-memory --reprepare
 13758  */
 13759  #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
 13760  # define SQLITE_DEFAULT_PCACHE_INITSZ 20
 13761  #endif
 13762  
 13763  /*
 13764  ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
 13765  */
 13766  #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
 13767  # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
 13768  #endif
 13769  
 13770  /*
 13771  ** The compile-time options SQLITE_MMAP_READWRITE and 
 13772  ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
 13773  ** You must choose one or the other (or neither) but not both.
 13774  */
 13775  #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 13776  #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 13777  #endif
 13778  
 13779  /*
 13780  ** GCC does not define the offsetof() macro so we'll have to do it
 13781  ** ourselves.
 13782  */
 13783  #ifndef offsetof
 13784  #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
 13785  #endif
 13786  
 13787  /*
 13788  ** Macros to compute minimum and maximum of two numbers.
 13789  */
 13790  #ifndef MIN
 13791  # define MIN(A,B) ((A)<(B)?(A):(B))
 13792  #endif
 13793  #ifndef MAX
 13794  # define MAX(A,B) ((A)>(B)?(A):(B))
 13795  #endif
 13796  
 13797  /*
 13798  ** Swap two objects of type TYPE.
 13799  */
 13800  #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
 13801  
 13802  /*
 13803  ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
 13804  ** not, there are still machines out there that use EBCDIC.)
 13805  */
 13806  #if 'A' == '\301'
 13807  # define SQLITE_EBCDIC 1
 13808  #else
 13809  # define SQLITE_ASCII 1
 13810  #endif
 13811  
 13812  /*
 13813  ** Integers of known sizes.  These typedefs might change for architectures
 13814  ** where the sizes very.  Preprocessor macros are available so that the
 13815  ** types can be conveniently redefined at compile-type.  Like this:
 13816  **
 13817  **         cc '-DUINTPTR_TYPE=long long int' ...
 13818  */
 13819  #ifndef UINT32_TYPE
 13820  # ifdef HAVE_UINT32_T
 13821  #  define UINT32_TYPE uint32_t
 13822  # else
 13823  #  define UINT32_TYPE unsigned int
 13824  # endif
 13825  #endif
 13826  #ifndef UINT16_TYPE
 13827  # ifdef HAVE_UINT16_T
 13828  #  define UINT16_TYPE uint16_t
 13829  # else
 13830  #  define UINT16_TYPE unsigned short int
 13831  # endif
 13832  #endif
 13833  #ifndef INT16_TYPE
 13834  # ifdef HAVE_INT16_T
 13835  #  define INT16_TYPE int16_t
 13836  # else
 13837  #  define INT16_TYPE short int
 13838  # endif
 13839  #endif
 13840  #ifndef UINT8_TYPE
 13841  # ifdef HAVE_UINT8_T
 13842  #  define UINT8_TYPE uint8_t
 13843  # else
 13844  #  define UINT8_TYPE unsigned char
 13845  # endif
 13846  #endif
 13847  #ifndef INT8_TYPE
 13848  # ifdef HAVE_INT8_T
 13849  #  define INT8_TYPE int8_t
 13850  # else
 13851  #  define INT8_TYPE signed char
 13852  # endif
 13853  #endif
 13854  #ifndef LONGDOUBLE_TYPE
 13855  # define LONGDOUBLE_TYPE long double
 13856  #endif
 13857  typedef sqlite_int64 i64;          /* 8-byte signed integer */
 13858  typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
 13859  typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
 13860  typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
 13861  typedef INT16_TYPE i16;            /* 2-byte signed integer */
 13862  typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
 13863  typedef INT8_TYPE i8;              /* 1-byte signed integer */
 13864  
 13865  /*
 13866  ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
 13867  ** that can be stored in a u32 without loss of data.  The value
 13868  ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
 13869  ** have to specify the value in the less intuitive manner shown:
 13870  */
 13871  #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
 13872  
 13873  /*
 13874  ** The datatype used to store estimates of the number of rows in a
 13875  ** table or index.  This is an unsigned integer type.  For 99.9% of
 13876  ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
 13877  ** can be used at compile-time if desired.
 13878  */
 13879  #ifdef SQLITE_64BIT_STATS
 13880   typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
 13881  #else
 13882   typedef u32 tRowcnt;    /* 32-bit is the default */
 13883  #endif
 13884  
 13885  /*
 13886  ** Estimated quantities used for query planning are stored as 16-bit
 13887  ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
 13888  ** gives a possible range of values of approximately 1.0e986 to 1e-986.
 13889  ** But the allowed values are "grainy".  Not every value is representable.
 13890  ** For example, quantities 16 and 17 are both represented by a LogEst
 13891  ** of 40.  However, since LogEst quantities are suppose to be estimates,
 13892  ** not exact values, this imprecision is not a problem.
 13893  **
 13894  ** "LogEst" is short for "Logarithmic Estimate".
 13895  **
 13896  ** Examples:
 13897  **      1 -> 0              20 -> 43          10000 -> 132
 13898  **      2 -> 10             25 -> 46          25000 -> 146
 13899  **      3 -> 16            100 -> 66        1000000 -> 199
 13900  **      4 -> 20           1000 -> 99        1048576 -> 200
 13901  **     10 -> 33           1024 -> 100    4294967296 -> 320
 13902  **
 13903  ** The LogEst can be negative to indicate fractional values.
 13904  ** Examples:
 13905  **
 13906  **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
 13907  */
 13908  typedef INT16_TYPE LogEst;
 13909  
 13910  /*
 13911  ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
 13912  */
 13913  #ifndef SQLITE_PTRSIZE
 13914  # if defined(__SIZEOF_POINTER__)
 13915  #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
 13916  # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
 13917         defined(_M_ARM)   || defined(__arm__)    || defined(__x86)   ||    \
 13918        (defined(__TOS_AIX__) && !defined(__64BIT__))
 13919  #   define SQLITE_PTRSIZE 4
 13920  # else
 13921  #   define SQLITE_PTRSIZE 8
 13922  # endif
 13923  #endif
 13924  
 13925  /* The uptr type is an unsigned integer large enough to hold a pointer
 13926  */
 13927  #if defined(HAVE_STDINT_H)
 13928    typedef uintptr_t uptr;
 13929  #elif SQLITE_PTRSIZE==4
 13930    typedef u32 uptr;
 13931  #else
 13932    typedef u64 uptr;
 13933  #endif
 13934  
 13935  /*
 13936  ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
 13937  ** something between S (inclusive) and E (exclusive).
 13938  **
 13939  ** In other words, S is a buffer and E is a pointer to the first byte after
 13940  ** the end of buffer S.  This macro returns true if P points to something
 13941  ** contained within the buffer S.
 13942  */
 13943  #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
 13944  
 13945  
 13946  /*
 13947  ** Macros to determine whether the machine is big or little endian,
 13948  ** and whether or not that determination is run-time or compile-time.
 13949  **
 13950  ** For best performance, an attempt is made to guess at the byte-order
 13951  ** using C-preprocessor macros.  If that is unsuccessful, or if
 13952  ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
 13953  ** at run-time.
 13954  */
 13955  #ifndef SQLITE_BYTEORDER
 13956  # if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
 13957       defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
 13958       defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
 13959       defined(__arm__)  || defined(_M_ARM64)
 13960  #   define SQLITE_BYTEORDER    1234
 13961  # elif defined(sparc)    || defined(__ppc__)
 13962  #   define SQLITE_BYTEORDER    4321
 13963  # else
 13964  #   define SQLITE_BYTEORDER 0
 13965  # endif
 13966  #endif
 13967  #if SQLITE_BYTEORDER==4321
 13968  # define SQLITE_BIGENDIAN    1
 13969  # define SQLITE_LITTLEENDIAN 0
 13970  # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
 13971  #elif SQLITE_BYTEORDER==1234
 13972  # define SQLITE_BIGENDIAN    0
 13973  # define SQLITE_LITTLEENDIAN 1
 13974  # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
 13975  #else
 13976  # ifdef SQLITE_AMALGAMATION
 13977    const int sqlite3one = 1;
 13978  # else
 13979    extern const int sqlite3one;
 13980  # endif
 13981  # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
 13982  # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
 13983  # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
 13984  #endif
 13985  
 13986  /*
 13987  ** Constants for the largest and smallest possible 64-bit signed integers.
 13988  ** These macros are designed to work correctly on both 32-bit and 64-bit
 13989  ** compilers.
 13990  */
 13991  #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
 13992  #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
 13993  
 13994  /*
 13995  ** Round up a number to the next larger multiple of 8.  This is used
 13996  ** to force 8-byte alignment on 64-bit architectures.
 13997  */
 13998  #define ROUND8(x)     (((x)+7)&~7)
 13999  
 14000  /*
 14001  ** Round down to the nearest multiple of 8
 14002  */
 14003  #define ROUNDDOWN8(x) ((x)&~7)
 14004  
 14005  /*
 14006  ** Assert that the pointer X is aligned to an 8-byte boundary.  This
 14007  ** macro is used only within assert() to verify that the code gets
 14008  ** all alignment restrictions correct.
 14009  **
 14010  ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
 14011  ** underlying malloc() implementation might return us 4-byte aligned
 14012  ** pointers.  In that case, only verify 4-byte alignment.
 14013  */
 14014  #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
 14015  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
 14016  #else
 14017  # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
 14018  #endif
 14019  
 14020  /*
 14021  ** Disable MMAP on platforms where it is known to not work
 14022  */
 14023  #if defined(__OpenBSD__) || defined(__QNXNTO__)
 14024  # undef SQLITE_MAX_MMAP_SIZE
 14025  # define SQLITE_MAX_MMAP_SIZE 0
 14026  #endif
 14027  
 14028  /*
 14029  ** Default maximum size of memory used by memory-mapped I/O in the VFS
 14030  */
 14031  #ifdef __APPLE__
 14032  # include <TargetConditionals.h>
 14033  #endif
 14034  #ifndef SQLITE_MAX_MMAP_SIZE
 14035  # if defined(__linux__) \
 14036    || defined(_WIN32) \
 14037    || (defined(__APPLE__) && defined(__MACH__)) \
 14038    || defined(__sun) \
 14039    || defined(__FreeBSD__) \
 14040    || defined(__DragonFly__)
 14041  #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
 14042  # else
 14043  #   define SQLITE_MAX_MMAP_SIZE 0
 14044  # endif
 14045  #endif
 14046  
 14047  /*
 14048  ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
 14049  ** default MMAP_SIZE is specified at compile-time, make sure that it does
 14050  ** not exceed the maximum mmap size.
 14051  */
 14052  #ifndef SQLITE_DEFAULT_MMAP_SIZE
 14053  # define SQLITE_DEFAULT_MMAP_SIZE 0
 14054  #endif
 14055  #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
 14056  # undef SQLITE_DEFAULT_MMAP_SIZE
 14057  # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
 14058  #endif
 14059  
 14060  /*
 14061  ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
 14062  ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
 14063  ** define SQLITE_ENABLE_STAT3_OR_STAT4
 14064  */
 14065  #ifdef SQLITE_ENABLE_STAT4
 14066  # undef SQLITE_ENABLE_STAT3
 14067  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
 14068  #elif SQLITE_ENABLE_STAT3
 14069  # define SQLITE_ENABLE_STAT3_OR_STAT4 1
 14070  #elif SQLITE_ENABLE_STAT3_OR_STAT4
 14071  # undef SQLITE_ENABLE_STAT3_OR_STAT4
 14072  #endif
 14073  
 14074  /*
 14075  ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
 14076  ** the Select query generator tracing logic is turned on.
 14077  */
 14078  #if defined(SQLITE_ENABLE_SELECTTRACE)
 14079  # define SELECTTRACE_ENABLED 1
 14080  #else
 14081  # define SELECTTRACE_ENABLED 0
 14082  #endif
 14083  
 14084  /*
 14085  ** An instance of the following structure is used to store the busy-handler
 14086  ** callback for a given sqlite handle.
 14087  **
 14088  ** The sqlite.busyHandler member of the sqlite struct contains the busy
 14089  ** callback for the database handle. Each pager opened via the sqlite
 14090  ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
 14091  ** callback is currently invoked only from within pager.c.
 14092  */
 14093  typedef struct BusyHandler BusyHandler;
 14094  struct BusyHandler {
 14095    int (*xBusyHandler)(void *,int);  /* The busy callback */
 14096    void *pBusyArg;                   /* First arg to busy callback */
 14097    int nBusy;                        /* Incremented with each busy call */
 14098    u8 bExtraFileArg;                 /* Include sqlite3_file as callback arg */
 14099  };
 14100  
 14101  /*
 14102  ** Name of the master database table.  The master database table
 14103  ** is a special table that holds the names and attributes of all
 14104  ** user tables and indices.
 14105  */
 14106  #define MASTER_NAME       "sqlite_master"
 14107  #define TEMP_MASTER_NAME  "sqlite_temp_master"
 14108  
 14109  /*
 14110  ** The root-page of the master database table.
 14111  */
 14112  #define MASTER_ROOT       1
 14113  
 14114  /*
 14115  ** The name of the schema table.
 14116  */
 14117  #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
 14118  
 14119  /*
 14120  ** A convenience macro that returns the number of elements in
 14121  ** an array.
 14122  */
 14123  #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
 14124  
 14125  /*
 14126  ** Determine if the argument is a power of two
 14127  */
 14128  #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
 14129  
 14130  /*
 14131  ** The following value as a destructor means to use sqlite3DbFree().
 14132  ** The sqlite3DbFree() routine requires two parameters instead of the
 14133  ** one parameter that destructors normally want.  So we have to introduce
 14134  ** this magic value that the code knows to handle differently.  Any
 14135  ** pointer will work here as long as it is distinct from SQLITE_STATIC
 14136  ** and SQLITE_TRANSIENT.
 14137  */
 14138  #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
 14139  
 14140  /*
 14141  ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
 14142  ** not support Writable Static Data (WSD) such as global and static variables.
 14143  ** All variables must either be on the stack or dynamically allocated from
 14144  ** the heap.  When WSD is unsupported, the variable declarations scattered
 14145  ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
 14146  ** macro is used for this purpose.  And instead of referencing the variable
 14147  ** directly, we use its constant as a key to lookup the run-time allocated
 14148  ** buffer that holds real variable.  The constant is also the initializer
 14149  ** for the run-time allocated buffer.
 14150  **
 14151  ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
 14152  ** macros become no-ops and have zero performance impact.
 14153  */
 14154  #ifdef SQLITE_OMIT_WSD
 14155    #define SQLITE_WSD const
 14156    #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
 14157    #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
 14158  SQLITE_API int sqlite3_wsd_init(int N, int J);
 14159  SQLITE_API void *sqlite3_wsd_find(void *K, int L);
 14160  #else
 14161    #define SQLITE_WSD
 14162    #define GLOBAL(t,v) v
 14163    #define sqlite3GlobalConfig sqlite3Config
 14164  #endif
 14165  
 14166  /*
 14167  ** The following macros are used to suppress compiler warnings and to
 14168  ** make it clear to human readers when a function parameter is deliberately
 14169  ** left unused within the body of a function. This usually happens when
 14170  ** a function is called via a function pointer. For example the
 14171  ** implementation of an SQL aggregate step callback may not use the
 14172  ** parameter indicating the number of arguments passed to the aggregate,
 14173  ** if it knows that this is enforced elsewhere.
 14174  **
 14175  ** When a function parameter is not used at all within the body of a function,
 14176  ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
 14177  ** However, these macros may also be used to suppress warnings related to
 14178  ** parameters that may or may not be used depending on compilation options.
 14179  ** For example those parameters only used in assert() statements. In these
 14180  ** cases the parameters are named as per the usual conventions.
 14181  */
 14182  #define UNUSED_PARAMETER(x) (void)(x)
 14183  #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
 14184  
 14185  /*
 14186  ** Forward references to structures
 14187  */
 14188  typedef struct AggInfo AggInfo;
 14189  typedef struct AuthContext AuthContext;
 14190  typedef struct AutoincInfo AutoincInfo;
 14191  typedef struct Bitvec Bitvec;
 14192  typedef struct CollSeq CollSeq;
 14193  typedef struct Column Column;
 14194  typedef struct Db Db;
 14195  typedef struct Schema Schema;
 14196  typedef struct Expr Expr;
 14197  typedef struct ExprList ExprList;
 14198  typedef struct FKey FKey;
 14199  typedef struct FuncDestructor FuncDestructor;
 14200  typedef struct FuncDef FuncDef;
 14201  typedef struct FuncDefHash FuncDefHash;
 14202  typedef struct IdList IdList;
 14203  typedef struct Index Index;
 14204  typedef struct IndexSample IndexSample;
 14205  typedef struct KeyClass KeyClass;
 14206  typedef struct KeyInfo KeyInfo;
 14207  typedef struct Lookaside Lookaside;
 14208  typedef struct LookasideSlot LookasideSlot;
 14209  typedef struct Module Module;
 14210  typedef struct NameContext NameContext;
 14211  typedef struct Parse Parse;
 14212  typedef struct PreUpdate PreUpdate;
 14213  typedef struct PrintfArguments PrintfArguments;
 14214  typedef struct RenameToken RenameToken;
 14215  typedef struct RowSet RowSet;
 14216  typedef struct Savepoint Savepoint;
 14217  typedef struct Select Select;
 14218  typedef struct SQLiteThread SQLiteThread;
 14219  typedef struct SelectDest SelectDest;
 14220  typedef struct SrcList SrcList;
 14221  typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
 14222  typedef struct Table Table;
 14223  typedef struct TableLock TableLock;
 14224  typedef struct Token Token;
 14225  typedef struct TreeView TreeView;
 14226  typedef struct Trigger Trigger;
 14227  typedef struct TriggerPrg TriggerPrg;
 14228  typedef struct TriggerStep TriggerStep;
 14229  typedef struct UnpackedRecord UnpackedRecord;
 14230  typedef struct Upsert Upsert;
 14231  typedef struct VTable VTable;
 14232  typedef struct VtabCtx VtabCtx;
 14233  typedef struct Walker Walker;
 14234  typedef struct WhereInfo WhereInfo;
 14235  typedef struct Window Window;
 14236  typedef struct With With;
 14237  
 14238  
 14239  /*
 14240  ** The bitmask datatype defined below is used for various optimizations.
 14241  **
 14242  ** Changing this from a 64-bit to a 32-bit type limits the number of
 14243  ** tables in a join to 32 instead of 64.  But it also reduces the size
 14244  ** of the library by 738 bytes on ix86.
 14245  */
 14246  #ifdef SQLITE_BITMASK_TYPE
 14247    typedef SQLITE_BITMASK_TYPE Bitmask;
 14248  #else
 14249    typedef u64 Bitmask;
 14250  #endif
 14251  
 14252  /*
 14253  ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
 14254  */
 14255  #define BMS  ((int)(sizeof(Bitmask)*8))
 14256  
 14257  /*
 14258  ** A bit in a Bitmask
 14259  */
 14260  #define MASKBIT(n)   (((Bitmask)1)<<(n))
 14261  #define MASKBIT32(n) (((unsigned int)1)<<(n))
 14262  #define ALLBITS      ((Bitmask)-1)
 14263  
 14264  /* A VList object records a mapping between parameters/variables/wildcards
 14265  ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
 14266  ** variable number associated with that parameter.  See the format description
 14267  ** on the sqlite3VListAdd() routine for more information.  A VList is really
 14268  ** just an array of integers.
 14269  */
 14270  typedef int VList;
 14271  
 14272  /*
 14273  ** Defer sourcing vdbe.h and btree.h until after the "u8" and
 14274  ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
 14275  ** pointer types (i.e. FuncDef) defined above.
 14276  */
 14277  /************** Include btree.h in the middle of sqliteInt.h *****************/
 14278  /************** Begin file btree.h *******************************************/
 14279  /*
 14280  ** 2001 September 15
 14281  **
 14282  ** The author disclaims copyright to this source code.  In place of
 14283  ** a legal notice, here is a blessing:
 14284  **
 14285  **    May you do good and not evil.
 14286  **    May you find forgiveness for yourself and forgive others.
 14287  **    May you share freely, never taking more than you give.
 14288  **
 14289  *************************************************************************
 14290  ** This header file defines the interface that the sqlite B-Tree file
 14291  ** subsystem.  See comments in the source code for a detailed description
 14292  ** of what each interface routine does.
 14293  */
 14294  #ifndef SQLITE_BTREE_H
 14295  #define SQLITE_BTREE_H
 14296  
 14297  /* TODO: This definition is just included so other modules compile. It
 14298  ** needs to be revisited.
 14299  */
 14300  #define SQLITE_N_BTREE_META 16
 14301  
 14302  /*
 14303  ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
 14304  ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
 14305  */
 14306  #ifndef SQLITE_DEFAULT_AUTOVACUUM
 14307    #define SQLITE_DEFAULT_AUTOVACUUM 0
 14308  #endif
 14309  
 14310  #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
 14311  #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
 14312  #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
 14313  
 14314  /*
 14315  ** Forward declarations of structure
 14316  */
 14317  typedef struct Btree Btree;
 14318  typedef struct BtCursor BtCursor;
 14319  typedef struct BtShared BtShared;
 14320  typedef struct BtreePayload BtreePayload;
 14321  
 14322  
 14323  SQLITE_PRIVATE int sqlite3BtreeOpen(
 14324    sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
 14325    const char *zFilename,   /* Name of database file to open */
 14326    sqlite3 *db,             /* Associated database connection */
 14327    Btree **ppBtree,         /* Return open Btree* here */
 14328    int flags,               /* Flags */
 14329    int vfsFlags             /* Flags passed through to VFS open */
 14330  );
 14331  
 14332  /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
 14333  ** following values.
 14334  **
 14335  ** NOTE:  These values must match the corresponding PAGER_ values in
 14336  ** pager.h.
 14337  */
 14338  #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
 14339  #define BTREE_MEMORY        2  /* This is an in-memory DB */
 14340  #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
 14341  #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
 14342  
 14343  SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
 14344  SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
 14345  SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
 14346  #if SQLITE_MAX_MMAP_SIZE>0
 14347  SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
 14348  #endif
 14349  SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
 14350  SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
 14351  SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
 14352  SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
 14353  SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
 14354  SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
 14355  SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
 14356  SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
 14357  SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
 14358  SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
 14359  SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
 14360  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
 14361  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
 14362  SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
 14363  SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
 14364  SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
 14365  SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
 14366  SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
 14367  SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
 14368  SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
 14369  SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
 14370  SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
 14371  #ifndef SQLITE_OMIT_SHARED_CACHE
 14372  SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
 14373  #endif
 14374  SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
 14375  
 14376  SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
 14377  SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
 14378  SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
 14379  
 14380  SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
 14381  
 14382  /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
 14383  ** of the flags shown below.
 14384  **
 14385  ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
 14386  ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
 14387  ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
 14388  ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
 14389  ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
 14390  ** indices.)
 14391  */
 14392  #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
 14393  #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
 14394  
 14395  SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
 14396  SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
 14397  SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
 14398  SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
 14399  
 14400  SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
 14401  SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
 14402  
 14403  SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
 14404  
 14405  /*
 14406  ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
 14407  ** should be one of the following values. The integer values are assigned 
 14408  ** to constants so that the offset of the corresponding field in an
 14409  ** SQLite database header may be found using the following formula:
 14410  **
 14411  **   offset = 36 + (idx * 4)
 14412  **
 14413  ** For example, the free-page-count field is located at byte offset 36 of
 14414  ** the database file header. The incr-vacuum-flag field is located at
 14415  ** byte offset 64 (== 36+4*7).
 14416  **
 14417  ** The BTREE_DATA_VERSION value is not really a value stored in the header.
 14418  ** It is a read-only number computed by the pager.  But we merge it with
 14419  ** the header value access routines since its access pattern is the same.
 14420  ** Call it a "virtual meta value".
 14421  */
 14422  #define BTREE_FREE_PAGE_COUNT     0
 14423  #define BTREE_SCHEMA_VERSION      1
 14424  #define BTREE_FILE_FORMAT         2
 14425  #define BTREE_DEFAULT_CACHE_SIZE  3
 14426  #define BTREE_LARGEST_ROOT_PAGE   4
 14427  #define BTREE_TEXT_ENCODING       5
 14428  #define BTREE_USER_VERSION        6
 14429  #define BTREE_INCR_VACUUM         7
 14430  #define BTREE_APPLICATION_ID      8
 14431  #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
 14432  
 14433  /*
 14434  ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
 14435  ** interface.
 14436  **
 14437  ** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
 14438  **
 14439  **     The first argument is an Expr* (which is guaranteed to be constant for
 14440  **     the lifetime of the cursor) that defines constraints on which rows
 14441  **     might be fetched with this cursor.  The Expr* tree may contain
 14442  **     TK_REGISTER nodes that refer to values stored in the array of registers
 14443  **     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
 14444  **     then the value of the node is the value in Mem[pExpr.iTable].  Any
 14445  **     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
 14446  **     column of the b-tree of the cursor.  The Expr tree will not contain
 14447  **     any function calls nor subqueries nor references to b-trees other than
 14448  **     the cursor being hinted.
 14449  **
 14450  **     The design of the _RANGE hint is aid b-tree implementations that try
 14451  **     to prefetch content from remote machines - to provide those
 14452  **     implementations with limits on what needs to be prefetched and thereby
 14453  **     reduce network bandwidth.
 14454  **
 14455  ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
 14456  ** standard SQLite.  The other hints are provided for extentions that use
 14457  ** the SQLite parser and code generator but substitute their own storage
 14458  ** engine.
 14459  */
 14460  #define BTREE_HINT_RANGE 0       /* Range constraints on queries */
 14461  
 14462  /*
 14463  ** Values that may be OR'd together to form the argument to the
 14464  ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
 14465  **
 14466  ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
 14467  ** to be filled with content that is already in sorted order.
 14468  **
 14469  ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
 14470  ** OP_SeekLE opcodes for a range search, but where the range of entries
 14471  ** selected will all have the same key.  In other words, the cursor will
 14472  ** be used only for equality key searches.
 14473  **
 14474  */
 14475  #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
 14476  #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
 14477  
 14478  /* 
 14479  ** Flags passed as the third argument to sqlite3BtreeCursor().
 14480  **
 14481  ** For read-only cursors the wrFlag argument is always zero. For read-write
 14482  ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
 14483  ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
 14484  ** only be used by SQLite for the following:
 14485  **
 14486  **   * to seek to and then delete specific entries, and/or
 14487  **
 14488  **   * to read values that will be used to create keys that other
 14489  **     BTREE_FORDELETE cursors will seek to and delete.
 14490  **
 14491  ** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
 14492  ** by this, the native b-tree engine of SQLite, but it is available to
 14493  ** alternative storage engines that might be substituted in place of this
 14494  ** b-tree system.  For alternative storage engines in which a delete of
 14495  ** the main table row automatically deletes corresponding index rows,
 14496  ** the FORDELETE flag hint allows those alternative storage engines to
 14497  ** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
 14498  ** and DELETE operations as no-ops, and any READ operation against a
 14499  ** FORDELETE cursor may return a null row: 0x01 0x00.
 14500  */
 14501  #define BTREE_WRCSR     0x00000004     /* read-write cursor */
 14502  #define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
 14503  
 14504  SQLITE_PRIVATE int sqlite3BtreeCursor(
 14505    Btree*,                              /* BTree containing table to open */
 14506    int iTable,                          /* Index of root page */
 14507    int wrFlag,                          /* 1 for writing.  0 for read-only */
 14508    struct KeyInfo*,                     /* First argument to compare function */
 14509    BtCursor *pCursor                    /* Space to write cursor structure */
 14510  );
 14511  SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
 14512  SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
 14513  SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
 14514  SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
 14515  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 14516  SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
 14517  #endif
 14518  
 14519  SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
 14520  SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
 14521    BtCursor*,
 14522    UnpackedRecord *pUnKey,
 14523    i64 intKey,
 14524    int bias,
 14525    int *pRes
 14526  );
 14527  SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
 14528  SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
 14529  SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
 14530  
 14531  /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
 14532  #define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
 14533  #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
 14534  #define BTREE_APPEND       0x08  /* Insert is likely an append */
 14535  
 14536  /* An instance of the BtreePayload object describes the content of a single
 14537  ** entry in either an index or table btree.
 14538  **
 14539  ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
 14540  ** an arbitrary key and no data.  These btrees have pKey,nKey set to the
 14541  ** key and the pData,nData,nZero fields are uninitialized.  The aMem,nMem
 14542  ** fields give an array of Mem objects that are a decomposition of the key.
 14543  ** The nMem field might be zero, indicating that no decomposition is available.
 14544  **
 14545  ** Table btrees (used for rowid tables) contain an integer rowid used as
 14546  ** the key and passed in the nKey field.  The pKey field is zero.  
 14547  ** pData,nData hold the content of the new entry.  nZero extra zero bytes
 14548  ** are appended to the end of the content when constructing the entry.
 14549  ** The aMem,nMem fields are uninitialized for table btrees.
 14550  **
 14551  ** Field usage summary:
 14552  **
 14553  **               Table BTrees                   Index Btrees
 14554  **
 14555  **   pKey        always NULL                    encoded key
 14556  **   nKey        the ROWID                      length of pKey
 14557  **   pData       data                           not used
 14558  **   aMem        not used                       decomposed key value
 14559  **   nMem        not used                       entries in aMem
 14560  **   nData       length of pData                not used
 14561  **   nZero       extra zeros after pData        not used
 14562  **
 14563  ** This object is used to pass information into sqlite3BtreeInsert().  The
 14564  ** same information used to be passed as five separate parameters.  But placing
 14565  ** the information into this object helps to keep the interface more 
 14566  ** organized and understandable, and it also helps the resulting code to
 14567  ** run a little faster by using fewer registers for parameter passing.
 14568  */
 14569  struct BtreePayload {
 14570    const void *pKey;       /* Key content for indexes.  NULL for tables */
 14571    sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
 14572    const void *pData;      /* Data for tables. */
 14573    sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
 14574    u16 nMem;               /* Number of aMem[] value.  Might be zero */
 14575    int nData;              /* Size of pData.  0 if none. */
 14576    int nZero;              /* Extra zero data appended after pData,nData */
 14577  };
 14578  
 14579  SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
 14580                         int flags, int seekResult);
 14581  SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
 14582  #ifndef SQLITE_OMIT_WINDOWFUNC
 14583  SQLITE_PRIVATE void sqlite3BtreeSkipNext(BtCursor*);
 14584  #endif
 14585  SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
 14586  SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
 14587  SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
 14588  SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
 14589  SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
 14590  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
 14591  SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
 14592  #endif
 14593  SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
 14594  SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
 14595  SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
 14596  SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
 14597  
 14598  SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
 14599  SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
 14600  SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
 14601  
 14602  #ifndef SQLITE_OMIT_INCRBLOB
 14603  SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
 14604  SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
 14605  SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
 14606  #endif
 14607  SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
 14608  SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
 14609  SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
 14610  SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
 14611  SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
 14612  
 14613  #ifndef NDEBUG
 14614  SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
 14615  #endif
 14616  SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
 14617  
 14618  #ifndef SQLITE_OMIT_BTREECOUNT
 14619  SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
 14620  #endif
 14621  
 14622  #ifdef SQLITE_TEST
 14623  SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
 14624  SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
 14625  #endif
 14626  
 14627  #ifndef SQLITE_OMIT_WAL
 14628  SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
 14629  #endif
 14630  
 14631  /*
 14632  ** If we are not using shared cache, then there is no need to
 14633  ** use mutexes to access the BtShared structures.  So make the
 14634  ** Enter and Leave procedures no-ops.
 14635  */
 14636  #ifndef SQLITE_OMIT_SHARED_CACHE
 14637  SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
 14638  SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
 14639  SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
 14640  SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
 14641  SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
 14642  #else
 14643  # define sqlite3BtreeEnter(X) 
 14644  # define sqlite3BtreeEnterAll(X)
 14645  # define sqlite3BtreeSharable(X) 0
 14646  # define sqlite3BtreeEnterCursor(X)
 14647  # define sqlite3BtreeConnectionCount(X) 1
 14648  #endif
 14649  
 14650  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
 14651  SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
 14652  SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
 14653  SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
 14654  #ifndef NDEBUG
 14655    /* These routines are used inside assert() statements only. */
 14656  SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
 14657  SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
 14658  SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
 14659  #endif
 14660  #else
 14661  
 14662  # define sqlite3BtreeLeave(X)
 14663  # define sqlite3BtreeLeaveCursor(X)
 14664  # define sqlite3BtreeLeaveAll(X)
 14665  
 14666  # define sqlite3BtreeHoldsMutex(X) 1
 14667  # define sqlite3BtreeHoldsAllMutexes(X) 1
 14668  # define sqlite3SchemaMutexHeld(X,Y,Z) 1
 14669  #endif
 14670  
 14671  
 14672  #endif /* SQLITE_BTREE_H */
 14673  
 14674  /************** End of btree.h ***********************************************/
 14675  /************** Continuing where we left off in sqliteInt.h ******************/
 14676  /************** Include vdbe.h in the middle of sqliteInt.h ******************/
 14677  /************** Begin file vdbe.h ********************************************/
 14678  /*
 14679  ** 2001 September 15
 14680  **
 14681  ** The author disclaims copyright to this source code.  In place of
 14682  ** a legal notice, here is a blessing:
 14683  **
 14684  **    May you do good and not evil.
 14685  **    May you find forgiveness for yourself and forgive others.
 14686  **    May you share freely, never taking more than you give.
 14687  **
 14688  *************************************************************************
 14689  ** Header file for the Virtual DataBase Engine (VDBE)
 14690  **
 14691  ** This header defines the interface to the virtual database engine
 14692  ** or VDBE.  The VDBE implements an abstract machine that runs a
 14693  ** simple program to access and modify the underlying database.
 14694  */
 14695  #ifndef SQLITE_VDBE_H
 14696  #define SQLITE_VDBE_H
 14697  /* #include <stdio.h> */
 14698  
 14699  /*
 14700  ** A single VDBE is an opaque structure named "Vdbe".  Only routines
 14701  ** in the source file sqliteVdbe.c are allowed to see the insides
 14702  ** of this structure.
 14703  */
 14704  typedef struct Vdbe Vdbe;
 14705  
 14706  /*
 14707  ** The names of the following types declared in vdbeInt.h are required
 14708  ** for the VdbeOp definition.
 14709  */
 14710  typedef struct sqlite3_value Mem;
 14711  typedef struct SubProgram SubProgram;
 14712  
 14713  /*
 14714  ** A single instruction of the virtual machine has an opcode
 14715  ** and as many as three operands.  The instruction is recorded
 14716  ** as an instance of the following structure:
 14717  */
 14718  struct VdbeOp {
 14719    u8 opcode;          /* What operation to perform */
 14720    signed char p4type; /* One of the P4_xxx constants for p4 */
 14721    u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
 14722    int p1;             /* First operand */
 14723    int p2;             /* Second parameter (often the jump destination) */
 14724    int p3;             /* The third parameter */
 14725    union p4union {     /* fourth parameter */
 14726      int i;                 /* Integer value if p4type==P4_INT32 */
 14727      void *p;               /* Generic pointer */
 14728      char *z;               /* Pointer to data for string (char array) types */
 14729      i64 *pI64;             /* Used when p4type is P4_INT64 */
 14730      double *pReal;         /* Used when p4type is P4_REAL */
 14731      FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
 14732      sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
 14733      CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
 14734      Mem *pMem;             /* Used when p4type is P4_MEM */
 14735      VTable *pVtab;         /* Used when p4type is P4_VTAB */
 14736      KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
 14737      int *ai;               /* Used when p4type is P4_INTARRAY */
 14738      SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
 14739      Table *pTab;           /* Used when p4type is P4_TABLE */
 14740  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 14741      Expr *pExpr;           /* Used when p4type is P4_EXPR */
 14742  #endif
 14743      int (*xAdvance)(BtCursor *, int);
 14744    } p4;
 14745  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 14746    char *zComment;          /* Comment to improve readability */
 14747  #endif
 14748  #ifdef VDBE_PROFILE
 14749    u32 cnt;                 /* Number of times this instruction was executed */
 14750    u64 cycles;              /* Total time spent executing this instruction */
 14751  #endif
 14752  #ifdef SQLITE_VDBE_COVERAGE
 14753    u32 iSrcLine;            /* Source-code line that generated this opcode
 14754                             ** with flags in the upper 8 bits */
 14755  #endif
 14756  };
 14757  typedef struct VdbeOp VdbeOp;
 14758  
 14759  
 14760  /*
 14761  ** A sub-routine used to implement a trigger program.
 14762  */
 14763  struct SubProgram {
 14764    VdbeOp *aOp;                  /* Array of opcodes for sub-program */
 14765    int nOp;                      /* Elements in aOp[] */
 14766    int nMem;                     /* Number of memory cells required */
 14767    int nCsr;                     /* Number of cursors required */
 14768    u8 *aOnce;                    /* Array of OP_Once flags */
 14769    void *token;                  /* id that may be used to recursive triggers */
 14770    SubProgram *pNext;            /* Next sub-program already visited */
 14771  };
 14772  
 14773  /*
 14774  ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
 14775  ** it takes up less space.
 14776  */
 14777  struct VdbeOpList {
 14778    u8 opcode;          /* What operation to perform */
 14779    signed char p1;     /* First operand */
 14780    signed char p2;     /* Second parameter (often the jump destination) */
 14781    signed char p3;     /* Third parameter */
 14782  };
 14783  typedef struct VdbeOpList VdbeOpList;
 14784  
 14785  /*
 14786  ** Allowed values of VdbeOp.p4type
 14787  */
 14788  #define P4_NOTUSED      0   /* The P4 parameter is not used */
 14789  #define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */
 14790  #define P4_STATIC     (-1)  /* Pointer to a static string */
 14791  #define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */
 14792  #define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */
 14793  #define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */
 14794  #define P4_ADVANCE    (-5)  /* P4 is a pointer to BtreeNext() or BtreePrev() */
 14795  #define P4_TABLE      (-6)  /* P4 is a pointer to a Table structure */
 14796  /* Above do not own any resources.  Must free those below */
 14797  #define P4_FREE_IF_LE (-7)
 14798  #define P4_DYNAMIC    (-7)  /* Pointer to memory from sqliteMalloc() */
 14799  #define P4_FUNCDEF    (-8)  /* P4 is a pointer to a FuncDef structure */
 14800  #define P4_KEYINFO    (-9)  /* P4 is a pointer to a KeyInfo structure */
 14801  #define P4_EXPR       (-10) /* P4 is a pointer to an Expr tree */
 14802  #define P4_MEM        (-11) /* P4 is a pointer to a Mem*    structure */
 14803  #define P4_VTAB       (-12) /* P4 is a pointer to an sqlite3_vtab structure */
 14804  #define P4_REAL       (-13) /* P4 is a 64-bit floating point value */
 14805  #define P4_INT64      (-14) /* P4 is a 64-bit signed integer */
 14806  #define P4_INTARRAY   (-15) /* P4 is a vector of 32-bit integers */
 14807  #define P4_FUNCCTX    (-16) /* P4 is a pointer to an sqlite3_context object */
 14808  #define P4_DYNBLOB    (-17) /* Pointer to memory from sqliteMalloc() */
 14809  
 14810  /* Error message codes for OP_Halt */
 14811  #define P5_ConstraintNotNull 1
 14812  #define P5_ConstraintUnique  2
 14813  #define P5_ConstraintCheck   3
 14814  #define P5_ConstraintFK      4
 14815  
 14816  /*
 14817  ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
 14818  ** number of columns of data returned by the statement.
 14819  */
 14820  #define COLNAME_NAME     0
 14821  #define COLNAME_DECLTYPE 1
 14822  #define COLNAME_DATABASE 2
 14823  #define COLNAME_TABLE    3
 14824  #define COLNAME_COLUMN   4
 14825  #ifdef SQLITE_ENABLE_COLUMN_METADATA
 14826  # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
 14827  #else
 14828  # ifdef SQLITE_OMIT_DECLTYPE
 14829  #   define COLNAME_N      1      /* Store only the name */
 14830  # else
 14831  #   define COLNAME_N      2      /* Store the name and decltype */
 14832  # endif
 14833  #endif
 14834  
 14835  /*
 14836  ** The following macro converts a label returned by sqlite3VdbeMakeLabel()
 14837  ** into an index into the Parse.aLabel[] array that contains the resolved
 14838  ** address of that label.
 14839  */
 14840  #define ADDR(X)  (~(X))
 14841  
 14842  /*
 14843  ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
 14844  ** header file that defines a number for each opcode used by the VDBE.
 14845  */
 14846  /************** Include opcodes.h in the middle of vdbe.h ********************/
 14847  /************** Begin file opcodes.h *****************************************/
 14848  /* Automatically generated.  Do not edit */
 14849  /* See the tool/mkopcodeh.tcl script for details */
 14850  #define OP_Savepoint       0
 14851  #define OP_AutoCommit      1
 14852  #define OP_Transaction     2
 14853  #define OP_SorterNext      3 /* jump                                       */
 14854  #define OP_Prev            4 /* jump                                       */
 14855  #define OP_Next            5 /* jump                                       */
 14856  #define OP_Checkpoint      6
 14857  #define OP_JournalMode     7
 14858  #define OP_Vacuum          8
 14859  #define OP_VFilter         9 /* jump, synopsis: iplan=r[P3] zplan='P4'     */
 14860  #define OP_VUpdate        10 /* synopsis: data=r[P3@P2]                    */
 14861  #define OP_Goto           11 /* jump                                       */
 14862  #define OP_Gosub          12 /* jump                                       */
 14863  #define OP_InitCoroutine  13 /* jump                                       */
 14864  #define OP_Yield          14 /* jump                                       */
 14865  #define OP_MustBeInt      15 /* jump                                       */
 14866  #define OP_Jump           16 /* jump                                       */
 14867  #define OP_Once           17 /* jump                                       */
 14868  #define OP_If             18 /* jump                                       */
 14869  #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
 14870  #define OP_IfNot          20 /* jump                                       */
 14871  #define OP_IfNullRow      21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
 14872  #define OP_SeekLT         22 /* jump, synopsis: key=r[P3@P4]               */
 14873  #define OP_SeekLE         23 /* jump, synopsis: key=r[P3@P4]               */
 14874  #define OP_SeekGE         24 /* jump, synopsis: key=r[P3@P4]               */
 14875  #define OP_SeekGT         25 /* jump, synopsis: key=r[P3@P4]               */
 14876  #define OP_IfNoHope       26 /* jump, synopsis: key=r[P3@P4]               */
 14877  #define OP_NoConflict     27 /* jump, synopsis: key=r[P3@P4]               */
 14878  #define OP_NotFound       28 /* jump, synopsis: key=r[P3@P4]               */
 14879  #define OP_Found          29 /* jump, synopsis: key=r[P3@P4]               */
 14880  #define OP_SeekRowid      30 /* jump, synopsis: intkey=r[P3]               */
 14881  #define OP_NotExists      31 /* jump, synopsis: intkey=r[P3]               */
 14882  #define OP_Last           32 /* jump                                       */
 14883  #define OP_IfSmaller      33 /* jump                                       */
 14884  #define OP_SorterSort     34 /* jump                                       */
 14885  #define OP_Sort           35 /* jump                                       */
 14886  #define OP_Rewind         36 /* jump                                       */
 14887  #define OP_IdxLE          37 /* jump, synopsis: key=r[P3@P4]               */
 14888  #define OP_IdxGT          38 /* jump, synopsis: key=r[P3@P4]               */
 14889  #define OP_IdxLT          39 /* jump, synopsis: key=r[P3@P4]               */
 14890  #define OP_IdxGE          40 /* jump, synopsis: key=r[P3@P4]               */
 14891  #define OP_RowSetRead     41 /* jump, synopsis: r[P3]=rowset(P1)           */
 14892  #define OP_RowSetTest     42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
 14893  #define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
 14894  #define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
 14895  #define OP_Program        45 /* jump                                       */
 14896  #define OP_FkIfZero       46 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
 14897  #define OP_IfPos          47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
 14898  #define OP_IfNotZero      48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
 14899  #define OP_DecrJumpZero   49 /* jump, synopsis: if (--r[P1])==0 goto P2    */
 14900  #define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
 14901  #define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
 14902  #define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
 14903  #define OP_Eq             53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
 14904  #define OP_Gt             54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
 14905  #define OP_Le             55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
 14906  #define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
 14907  #define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
 14908  #define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */
 14909  #define OP_IncrVacuum     59 /* jump                                       */
 14910  #define OP_VNext          60 /* jump                                       */
 14911  #define OP_Init           61 /* jump, synopsis: Start at P2                */
 14912  #define OP_PureFunc0      62
 14913  #define OP_Function0      63 /* synopsis: r[P3]=func(r[P2@P5])             */
 14914  #define OP_PureFunc       64
 14915  #define OP_Function       65 /* synopsis: r[P3]=func(r[P2@P5])             */
 14916  #define OP_Return         66
 14917  #define OP_EndCoroutine   67
 14918  #define OP_HaltIfNull     68 /* synopsis: if r[P3]=null halt               */
 14919  #define OP_Halt           69
 14920  #define OP_Integer        70 /* synopsis: r[P2]=P1                         */
 14921  #define OP_Int64          71 /* synopsis: r[P2]=P4                         */
 14922  #define OP_String         72 /* synopsis: r[P2]='P4' (len=P1)              */
 14923  #define OP_Null           73 /* synopsis: r[P2..P3]=NULL                   */
 14924  #define OP_SoftNull       74 /* synopsis: r[P1]=NULL                       */
 14925  #define OP_Blob           75 /* synopsis: r[P2]=P4 (len=P1)                */
 14926  #define OP_Variable       76 /* synopsis: r[P2]=parameter(P1,P4)           */
 14927  #define OP_Move           77 /* synopsis: r[P2@P3]=r[P1@P3]                */
 14928  #define OP_Copy           78 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
 14929  #define OP_SCopy          79 /* synopsis: r[P2]=r[P1]                      */
 14930  #define OP_IntCopy        80 /* synopsis: r[P2]=r[P1]                      */
 14931  #define OP_ResultRow      81 /* synopsis: output=r[P1@P2]                  */
 14932  #define OP_CollSeq        82
 14933  #define OP_AddImm         83 /* synopsis: r[P1]=r[P1]+P2                   */
 14934  #define OP_RealAffinity   84
 14935  #define OP_Cast           85 /* synopsis: affinity(r[P1])                  */
 14936  #define OP_Permutation    86
 14937  #define OP_Compare        87 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
 14938  #define OP_IsTrue         88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
 14939  #define OP_Offset         89 /* synopsis: r[P3] = sqlite_offset(P1)        */
 14940  #define OP_Column         90 /* synopsis: r[P3]=PX                         */
 14941  #define OP_Affinity       91 /* synopsis: affinity(r[P1@P2])               */
 14942  #define OP_BitAnd         92 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
 14943  #define OP_BitOr          93 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
 14944  #define OP_ShiftLeft      94 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
 14945  #define OP_ShiftRight     95 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
 14946  #define OP_Add            96 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
 14947  #define OP_Subtract       97 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
 14948  #define OP_Multiply       98 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
 14949  #define OP_Divide         99 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
 14950  #define OP_Remainder     100 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
 14951  #define OP_Concat        101 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
 14952  #define OP_MakeRecord    102 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
 14953  #define OP_BitNot        103 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
 14954  #define OP_Count         104 /* synopsis: r[P2]=count()                    */
 14955  #define OP_ReadCookie    105
 14956  #define OP_String8       106 /* same as TK_STRING, synopsis: r[P2]='P4'    */
 14957  #define OP_SetCookie     107
 14958  #define OP_ReopenIdx     108 /* synopsis: root=P2 iDb=P3                   */
 14959  #define OP_OpenRead      109 /* synopsis: root=P2 iDb=P3                   */
 14960  #define OP_OpenWrite     110 /* synopsis: root=P2 iDb=P3                   */
 14961  #define OP_OpenDup       111
 14962  #define OP_OpenAutoindex 112 /* synopsis: nColumn=P2                       */
 14963  #define OP_OpenEphemeral 113 /* synopsis: nColumn=P2                       */
 14964  #define OP_SorterOpen    114
 14965  #define OP_SequenceTest  115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
 14966  #define OP_OpenPseudo    116 /* synopsis: P3 columns in r[P2]              */
 14967  #define OP_Close         117
 14968  #define OP_ColumnsUsed   118
 14969  #define OP_SeekHit       119 /* synopsis: seekHit=P2                       */
 14970  #define OP_Sequence      120 /* synopsis: r[P2]=cursor[P1].ctr++           */
 14971  #define OP_NewRowid      121 /* synopsis: r[P2]=rowid                      */
 14972  #define OP_Insert        122 /* synopsis: intkey=r[P3] data=r[P2]          */
 14973  #define OP_Delete        123
 14974  #define OP_ResetCount    124
 14975  #define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
 14976  #define OP_SorterData    126 /* synopsis: r[P2]=data                       */
 14977  #define OP_RowData       127 /* synopsis: r[P2]=data                       */
 14978  #define OP_Rowid         128 /* synopsis: r[P2]=rowid                      */
 14979  #define OP_NullRow       129
 14980  #define OP_SeekEnd       130
 14981  #define OP_SorterInsert  131 /* synopsis: key=r[P2]                        */
 14982  #define OP_IdxInsert     132 /* synopsis: key=r[P2]                        */
 14983  #define OP_IdxDelete     133 /* synopsis: key=r[P2@P3]                     */
 14984  #define OP_DeferredSeek  134 /* synopsis: Move P3 to P1.rowid if needed    */
 14985  #define OP_IdxRowid      135 /* synopsis: r[P2]=rowid                      */
 14986  #define OP_Destroy       136
 14987  #define OP_Clear         137
 14988  #define OP_ResetSorter   138
 14989  #define OP_CreateBtree   139 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
 14990  #define OP_SqlExec       140
 14991  #define OP_Real          141 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
 14992  #define OP_ParseSchema   142
 14993  #define OP_LoadAnalysis  143
 14994  #define OP_DropTable     144
 14995  #define OP_DropIndex     145
 14996  #define OP_DropTrigger   146
 14997  #define OP_IntegrityCk   147
 14998  #define OP_RowSetAdd     148 /* synopsis: rowset(P1)=r[P2]                 */
 14999  #define OP_Param         149
 15000  #define OP_FkCounter     150 /* synopsis: fkctr[P1]+=P2                    */
 15001  #define OP_MemMax        151 /* synopsis: r[P1]=max(r[P1],r[P2])           */
 15002  #define OP_OffsetLimit   152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
 15003  #define OP_AggInverse    153 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
 15004  #define OP_AggStep       154 /* synopsis: accum=r[P3] step(r[P2@P5])       */
 15005  #define OP_AggStep1      155 /* synopsis: accum=r[P3] step(r[P2@P5])       */
 15006  #define OP_AggValue      156 /* synopsis: r[P3]=value N=P2                 */
 15007  #define OP_AggFinal      157 /* synopsis: accum=r[P1] N=P2                 */
 15008  #define OP_Expire        158
 15009  #define OP_TableLock     159 /* synopsis: iDb=P1 root=P2 write=P3          */
 15010  #define OP_VBegin        160
 15011  #define OP_VCreate       161
 15012  #define OP_VDestroy      162
 15013  #define OP_VOpen         163
 15014  #define OP_VColumn       164 /* synopsis: r[P3]=vcolumn(P2)                */
 15015  #define OP_VRename       165
 15016  #define OP_Pagecount     166
 15017  #define OP_MaxPgcnt      167
 15018  #define OP_Trace         168
 15019  #define OP_CursorHint    169
 15020  #define OP_Noop          170
 15021  #define OP_Explain       171
 15022  #define OP_Abortable     172
 15023  
 15024  /* Properties such as "out2" or "jump" that are specified in
 15025  ** comments following the "case" for each opcode in the vdbe.c
 15026  ** are encoded into bitvectors as follows:
 15027  */
 15028  #define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
 15029  #define OPFLG_IN1         0x02  /* in1:   P1 is an input */
 15030  #define OPFLG_IN2         0x04  /* in2:   P2 is an input */
 15031  #define OPFLG_IN3         0x08  /* in3:   P3 is an input */
 15032  #define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
 15033  #define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
 15034  #define OPFLG_INITIALIZER {\
 15035  /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
 15036  /*   8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
 15037  /*  16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
 15038  /*  24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
 15039  /*  32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
 15040  /*  40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
 15041  /*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
 15042  /*  56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
 15043  /*  64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
 15044  /*  72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
 15045  /*  80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
 15046  /*  88 */ 0x12, 0x20, 0x00, 0x00, 0x26, 0x26, 0x26, 0x26,\
 15047  /*  96 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
 15048  /* 104 */ 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
 15049  /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 15050  /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 15051  /* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
 15052  /* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00,\
 15053  /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
 15054  /* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 15055  /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
 15056  /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00,}
 15057  
 15058  /* The sqlite3P2Values() routine is able to run faster if it knows
 15059  ** the value of the largest JUMP opcode.  The smaller the maximum
 15060  ** JUMP opcode the better, so the mkopcodeh.tcl script that
 15061  ** generated this include file strives to group all JUMP opcodes
 15062  ** together near the beginning of the list.
 15063  */
 15064  #define SQLITE_MX_JUMP_OPCODE  61  /* Maximum JUMP opcode */
 15065  
 15066  /************** End of opcodes.h *********************************************/
 15067  /************** Continuing where we left off in vdbe.h ***********************/
 15068  
 15069  /*
 15070  ** Additional non-public SQLITE_PREPARE_* flags
 15071  */
 15072  #define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */
 15073  #define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */
 15074  
 15075  /*
 15076  ** Prototypes for the VDBE interface.  See comments on the implementation
 15077  ** for a description of what each of these routines does.
 15078  */
 15079  SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
 15080  SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
 15081  SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
 15082  SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
 15083  SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
 15084  SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
 15085  SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
 15086  SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
 15087  SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
 15088  SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
 15089  SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
 15090  SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
 15091  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 15092  SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
 15093  SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
 15094  #else
 15095  # define sqlite3VdbeVerifyNoMallocRequired(A,B)
 15096  # define sqlite3VdbeVerifyNoResultRow(A)
 15097  #endif
 15098  #if defined(SQLITE_DEBUG)
 15099  SQLITE_PRIVATE   void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
 15100  #else
 15101  # define sqlite3VdbeVerifyAbortable(A,B)
 15102  #endif
 15103  SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
 15104  #ifndef SQLITE_OMIT_EXPLAIN
 15105  SQLITE_PRIVATE   void sqlite3VdbeExplain(Parse*,u8,const char*,...);
 15106  SQLITE_PRIVATE   void sqlite3VdbeExplainPop(Parse*);
 15107  SQLITE_PRIVATE   int sqlite3VdbeExplainParent(Parse*);
 15108  # define ExplainQueryPlan(P)        sqlite3VdbeExplain P
 15109  # define ExplainQueryPlanPop(P)     sqlite3VdbeExplainPop(P)
 15110  # define ExplainQueryPlanParent(P)  sqlite3VdbeExplainParent(P)
 15111  #else
 15112  # define ExplainQueryPlan(P)
 15113  # define ExplainQueryPlanPop(P)
 15114  # define ExplainQueryPlanParent(P) 0
 15115  # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
 15116  #endif
 15117  #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
 15118  SQLITE_PRIVATE   void sqlite3ExplainBreakpoint(const char*,const char*);
 15119  #else
 15120  # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
 15121  #endif
 15122  SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
 15123  SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
 15124  SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
 15125  SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
 15126  SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
 15127  SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
 15128  SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
 15129  SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
 15130  SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
 15131  SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
 15132  SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
 15133  SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
 15134  SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
 15135  SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
 15136  SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
 15137  SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
 15138  SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
 15139  SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
 15140  SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
 15141  SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
 15142  SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
 15143  SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
 15144  SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
 15145  #ifdef SQLITE_DEBUG
 15146  SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
 15147  #endif
 15148  SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
 15149  SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
 15150  SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
 15151  SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
 15152  SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
 15153  SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
 15154  SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
 15155  SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
 15156  SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
 15157  #ifdef SQLITE_ENABLE_NORMALIZE
 15158  SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
 15159  SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
 15160  #endif
 15161  SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
 15162  SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
 15163  SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
 15164  SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
 15165  #ifndef SQLITE_OMIT_TRACE
 15166  SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
 15167  #endif
 15168  SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
 15169  SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
 15170  
 15171  SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
 15172  SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
 15173  SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
 15174  SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
 15175  
 15176  typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
 15177  SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
 15178  
 15179  #ifndef SQLITE_OMIT_TRIGGER
 15180  SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
 15181  #endif
 15182  
 15183  SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
 15184  
 15185  /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
 15186  ** each VDBE opcode.
 15187  **
 15188  ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
 15189  ** comments in VDBE programs that show key decision points in the code
 15190  ** generator.
 15191  */
 15192  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 15193  SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
 15194  # define VdbeComment(X)  sqlite3VdbeComment X
 15195  SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
 15196  # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
 15197  # ifdef SQLITE_ENABLE_MODULE_COMMENTS
 15198  #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
 15199  # else
 15200  #   define VdbeModuleComment(X)
 15201  # endif
 15202  #else
 15203  # define VdbeComment(X)
 15204  # define VdbeNoopComment(X)
 15205  # define VdbeModuleComment(X)
 15206  #endif
 15207  
 15208  /*
 15209  ** The VdbeCoverage macros are used to set a coverage testing point
 15210  ** for VDBE branch instructions.  The coverage testing points are line
 15211  ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
 15212  ** only works with an amalagmation build.  That's ok since a VDBE branch
 15213  ** coverage build designed for testing the test suite only.  No application
 15214  ** should ever ship with VDBE branch coverage measuring turned on.
 15215  **
 15216  **    VdbeCoverage(v)                  // Mark the previously coded instruction
 15217  **                                     // as a branch
 15218  **
 15219  **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
 15220  **
 15221  **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
 15222  **
 15223  **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
 15224  **
 15225  **    VdbeCoverageNeverNull(v)         // Previous three-way branch is only
 15226  **                                     // taken on the first two ways.  The
 15227  **                                     // NULL option is not possible
 15228  **
 15229  **    VdbeCoverageEqNe(v)              // Previous OP_Jump is only interested
 15230  **                                     // in distingishing equal and not-equal.
 15231  **
 15232  ** Every VDBE branch operation must be tagged with one of the macros above.
 15233  ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
 15234  ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
 15235  ** routine in vdbe.c, alerting the developer to the missed tag.
 15236  **
 15237  ** During testing, the test application will invoke
 15238  ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
 15239  ** routine that is invoked as each bytecode branch is taken.  The callback
 15240  ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
 15241  ** flags to indicate whether or not the branch was taken.  The test application
 15242  ** is responsible for keeping track of this and reporting byte-code branches
 15243  ** that are never taken.
 15244  **
 15245  ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
 15246  ** vdbe.c source file for additional information.
 15247  */
 15248  #ifdef SQLITE_VDBE_COVERAGE
 15249  SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
 15250  # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
 15251  # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
 15252  # define VdbeCoverageAlwaysTaken(v) \
 15253           sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
 15254  # define VdbeCoverageNeverTaken(v) \
 15255           sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
 15256  # define VdbeCoverageNeverNull(v) \
 15257           sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
 15258  # define VdbeCoverageNeverNullIf(v,x) \
 15259           if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
 15260  # define VdbeCoverageEqNe(v) \
 15261           sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
 15262  # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
 15263  #else
 15264  # define VdbeCoverage(v)
 15265  # define VdbeCoverageIf(v,x)
 15266  # define VdbeCoverageAlwaysTaken(v)
 15267  # define VdbeCoverageNeverTaken(v)
 15268  # define VdbeCoverageNeverNull(v)
 15269  # define VdbeCoverageNeverNullIf(v,x)
 15270  # define VdbeCoverageEqNe(v)
 15271  # define VDBE_OFFSET_LINENO(x) 0
 15272  #endif
 15273  
 15274  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 15275  SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
 15276  #else
 15277  # define sqlite3VdbeScanStatus(a,b,c,d,e)
 15278  #endif
 15279  
 15280  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 15281  SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
 15282  #endif
 15283  
 15284  #endif /* SQLITE_VDBE_H */
 15285  
 15286  /************** End of vdbe.h ************************************************/
 15287  /************** Continuing where we left off in sqliteInt.h ******************/
 15288  /************** Include pager.h in the middle of sqliteInt.h *****************/
 15289  /************** Begin file pager.h *******************************************/
 15290  /*
 15291  ** 2001 September 15
 15292  **
 15293  ** The author disclaims copyright to this source code.  In place of
 15294  ** a legal notice, here is a blessing:
 15295  **
 15296  **    May you do good and not evil.
 15297  **    May you find forgiveness for yourself and forgive others.
 15298  **    May you share freely, never taking more than you give.
 15299  **
 15300  *************************************************************************
 15301  ** This header file defines the interface that the sqlite page cache
 15302  ** subsystem.  The page cache subsystem reads and writes a file a page
 15303  ** at a time and provides a journal for rollback.
 15304  */
 15305  
 15306  #ifndef SQLITE_PAGER_H
 15307  #define SQLITE_PAGER_H
 15308  
 15309  /*
 15310  ** Default maximum size for persistent journal files. A negative 
 15311  ** value means no limit. This value may be overridden using the 
 15312  ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
 15313  */
 15314  #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
 15315    #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
 15316  #endif
 15317  
 15318  /*
 15319  ** The type used to represent a page number.  The first page in a file
 15320  ** is called page 1.  0 is used to represent "not a page".
 15321  */
 15322  typedef u32 Pgno;
 15323  
 15324  /*
 15325  ** Each open file is managed by a separate instance of the "Pager" structure.
 15326  */
 15327  typedef struct Pager Pager;
 15328  
 15329  /*
 15330  ** Handle type for pages.
 15331  */
 15332  typedef struct PgHdr DbPage;
 15333  
 15334  /*
 15335  ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
 15336  ** reserved for working around a windows/posix incompatibility). It is
 15337  ** used in the journal to signify that the remainder of the journal file 
 15338  ** is devoted to storing a master journal name - there are no more pages to
 15339  ** roll back. See comments for function writeMasterJournal() in pager.c 
 15340  ** for details.
 15341  */
 15342  #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
 15343  
 15344  /*
 15345  ** Allowed values for the flags parameter to sqlite3PagerOpen().
 15346  **
 15347  ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
 15348  */
 15349  #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
 15350  #define PAGER_MEMORY        0x0002    /* In-memory database */
 15351  
 15352  /*
 15353  ** Valid values for the second argument to sqlite3PagerLockingMode().
 15354  */
 15355  #define PAGER_LOCKINGMODE_QUERY      -1
 15356  #define PAGER_LOCKINGMODE_NORMAL      0
 15357  #define PAGER_LOCKINGMODE_EXCLUSIVE   1
 15358  
 15359  /*
 15360  ** Numeric constants that encode the journalmode.
 15361  **
 15362  ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
 15363  ** are exposed in the API via the "PRAGMA journal_mode" command and
 15364  ** therefore cannot be changed without a compatibility break.
 15365  */
 15366  #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
 15367  #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
 15368  #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
 15369  #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
 15370  #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
 15371  #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
 15372  #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
 15373  #define PAGER_JOURNALMODE_BRANCHES    6   /* Use branches */
 15374  
 15375  /*
 15376  ** Flags that make up the mask passed to sqlite3PagerGet().
 15377  */
 15378  #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
 15379  #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
 15380  
 15381  /*
 15382  ** Flags for sqlite3PagerSetFlags()
 15383  **
 15384  ** Value constraints (enforced via assert()):
 15385  **    PAGER_FULLFSYNC      == SQLITE_FullFSync
 15386  **    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
 15387  **    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
 15388  */
 15389  #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
 15390  #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
 15391  #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
 15392  #define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
 15393  #define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
 15394  #define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
 15395  #define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
 15396  #define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
 15397  #define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
 15398  
 15399  /*
 15400  ** The remainder of this file contains the declarations of the functions
 15401  ** that make up the Pager sub-system API. See source code comments for 
 15402  ** a detailed description of each routine.
 15403  */
 15404  
 15405  /* Open and close a Pager connection. */ 
 15406  SQLITE_PRIVATE int sqlite3PagerOpen(
 15407    sqlite3_vfs*,
 15408    Pager **ppPager,
 15409    const char*,
 15410    int,
 15411    int,
 15412    int,
 15413    void(*)(DbPage*)
 15414  );
 15415  SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
 15416  SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
 15417  
 15418  /* Functions used to configure a Pager object. */
 15419  SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
 15420  SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
 15421  #ifdef SQLITE_HAS_CODEC
 15422  SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
 15423  #endif
 15424  SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
 15425  SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
 15426  SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
 15427  SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
 15428  SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
 15429  SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
 15430  SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
 15431  SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
 15432  SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
 15433  SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
 15434  SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
 15435  SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
 15436  SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
 15437  
 15438  /* Functions used to obtain and release page references. */ 
 15439  SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
 15440  SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
 15441  SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
 15442  SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
 15443  SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
 15444  SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
 15445  
 15446  /* Operations on page references. */
 15447  SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
 15448  SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
 15449  SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
 15450  SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
 15451  SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
 15452  SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
 15453  
 15454  /* Functions used to manage pager transactions and savepoints. */
 15455  SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
 15456  SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
 15457  SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
 15458  SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
 15459  SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
 15460  SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
 15461  SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
 15462  SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
 15463  SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
 15464  SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
 15465  
 15466  #ifndef SQLITE_OMIT_WAL
 15467  SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
 15468  SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
 15469  SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
 15470  SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
 15471  SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
 15472  # ifdef SQLITE_ENABLE_SNAPSHOT
 15473  SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
 15474  SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
 15475  SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
 15476  SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
 15477  SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);
 15478  # endif
 15479  #endif
 15480  
 15481  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 15482  SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
 15483  #endif
 15484  
 15485  #ifdef SQLITE_ENABLE_ZIPVFS
 15486  SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
 15487  #endif
 15488  
 15489  /* Functions used to query pager state and configuration. */
 15490  SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
 15491  SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
 15492  #ifdef SQLITE_DEBUG
 15493  SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
 15494  #endif
 15495  SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
 15496  SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
 15497  SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
 15498  SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
 15499  SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
 15500  SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
 15501  SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
 15502  SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
 15503  SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
 15504  SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
 15505  SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
 15506  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
 15507  SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
 15508  #else
 15509  # define sqlite3PagerResetLockTimeout(X)
 15510  #endif
 15511  
 15512  /* Functions used to truncate the database file. */
 15513  SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
 15514  
 15515  SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
 15516  
 15517  #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
 15518  SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
 15519  #endif
 15520  
 15521  /* Functions to support testing and debugging. */
 15522  #if !defined(NDEBUG) || defined(SQLITE_TEST)
 15523  SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
 15524  SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
 15525  #endif
 15526  #ifdef SQLITE_TEST
 15527  SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
 15528  SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
 15529    void disable_simulated_io_errors(void);
 15530    void enable_simulated_io_errors(void);
 15531  #else
 15532  # define disable_simulated_io_errors()
 15533  # define enable_simulated_io_errors()
 15534  #endif
 15535  
 15536  #endif /* SQLITE_PAGER_H */
 15537  
 15538  /************** End of pager.h ***********************************************/
 15539  /************** Continuing where we left off in sqliteInt.h ******************/
 15540  /************** Include pcache.h in the middle of sqliteInt.h ****************/
 15541  /************** Begin file pcache.h ******************************************/
 15542  /*
 15543  ** 2008 August 05
 15544  **
 15545  ** The author disclaims copyright to this source code.  In place of
 15546  ** a legal notice, here is a blessing:
 15547  **
 15548  **    May you do good and not evil.
 15549  **    May you find forgiveness for yourself and forgive others.
 15550  **    May you share freely, never taking more than you give.
 15551  **
 15552  *************************************************************************
 15553  ** This header file defines the interface that the sqlite page cache
 15554  ** subsystem. 
 15555  */
 15556  
 15557  #ifndef _PCACHE_H_
 15558  
 15559  typedef struct PgHdr PgHdr;
 15560  typedef struct PCache PCache;
 15561  
 15562  /*
 15563  ** Every page in the cache is controlled by an instance of the following
 15564  ** structure.
 15565  */
 15566  struct PgHdr {
 15567    sqlite3_pcache_page *pPage;    /* Pcache object page handle */
 15568    void *pData;                   /* Page data */
 15569    void *pExtra;                  /* Extra content */
 15570    PCache *pCache;                /* PRIVATE: Cache that owns this page */
 15571    PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
 15572    Pager *pPager;                 /* The pager this page is part of */
 15573    Pgno pgno;                     /* Page number for this page */
 15574  #ifdef SQLITE_CHECK_PAGES
 15575    u32 pageHash;                  /* Hash of page content */
 15576  #endif
 15577    u16 flags;                     /* PGHDR flags defined below */
 15578  
 15579    /**********************************************************************
 15580    ** Elements above, except pCache, are public.  All that follow are 
 15581    ** private to pcache.c and should not be accessed by other modules.
 15582    ** pCache is grouped with the public elements for efficiency.
 15583    */
 15584    i16 nRef;                      /* Number of users of this page */
 15585    PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
 15586    PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
 15587                            /* NB: pDirtyNext and pDirtyPrev are undefined if the
 15588                            ** PgHdr object is not dirty */
 15589  };
 15590  
 15591  /* Bit values for PgHdr.flags */
 15592  #define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
 15593  #define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
 15594  #define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
 15595  #define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
 15596                                       ** writing this page to the database */
 15597  #define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
 15598  #define PGHDR_MMAP            0x020  /* This is an mmap page object */
 15599  
 15600  #define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
 15601  
 15602  /* Initialize and shutdown the page cache subsystem */
 15603  SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
 15604  SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
 15605  
 15606  /* Page cache buffer management:
 15607  ** These routines implement SQLITE_CONFIG_PAGECACHE.
 15608  */
 15609  SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
 15610  
 15611  /* Create a new pager cache.
 15612  ** Under memory stress, invoke xStress to try to make pages clean.
 15613  ** Only clean and unpinned pages can be reclaimed.
 15614  */
 15615  SQLITE_PRIVATE int sqlite3PcacheOpen(
 15616    int szPage,                    /* Size of every page */
 15617    int szExtra,                   /* Extra space associated with each page */
 15618    int bPurgeable,                /* True if pages are on backing store */
 15619    int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
 15620    void *pStress,                 /* Argument to xStress */
 15621    PCache *pToInit                /* Preallocated space for the PCache */
 15622  );
 15623  
 15624  /* Modify the page-size after the cache has been created. */
 15625  SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
 15626  
 15627  /* Return the size in bytes of a PCache object.  Used to preallocate
 15628  ** storage space.
 15629  */
 15630  SQLITE_PRIVATE int sqlite3PcacheSize(void);
 15631  
 15632  /* One release per successful fetch.  Page is pinned until released.
 15633  ** Reference counted. 
 15634  */
 15635  SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
 15636  SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
 15637  SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
 15638  SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
 15639  
 15640  SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
 15641  SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
 15642  SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
 15643  SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
 15644  SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
 15645  
 15646  /* Change a page number.  Used by incr-vacuum. */
 15647  SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
 15648  
 15649  /* Remove all pages with pgno>x.  Reset the cache if x==0 */
 15650  SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
 15651  
 15652  /* Get a list of all dirty pages in the cache, sorted by page number */
 15653  SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
 15654  
 15655  /* Reset and close the cache object */
 15656  SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
 15657  
 15658  /* Clear flags from pages of the page cache */
 15659  SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
 15660  
 15661  /* Discard the contents of the cache */
 15662  SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
 15663  
 15664  /* Return the total number of outstanding page references */
 15665  SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
 15666  
 15667  /* Increment the reference count of an existing page */
 15668  SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
 15669  
 15670  SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
 15671  
 15672  /* Return the total number of pages stored in the cache */
 15673  SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
 15674  
 15675  #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 15676  /* Iterate through all dirty pages currently stored in the cache. This
 15677  ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
 15678  ** library is built.
 15679  */
 15680  SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
 15681  #endif
 15682  
 15683  #if defined(SQLITE_DEBUG)
 15684  /* Check invariants on a PgHdr object */
 15685  SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
 15686  #endif
 15687  
 15688  /* Set and get the suggested cache-size for the specified pager-cache.
 15689  **
 15690  ** If no global maximum is configured, then the system attempts to limit
 15691  ** the total number of pages cached by purgeable pager-caches to the sum
 15692  ** of the suggested cache-sizes.
 15693  */
 15694  SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
 15695  #ifdef SQLITE_TEST
 15696  SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
 15697  #endif
 15698  
 15699  /* Set or get the suggested spill-size for the specified pager-cache.
 15700  **
 15701  ** The spill-size is the minimum number of pages in cache before the cache
 15702  ** will attempt to spill dirty pages by calling xStress.
 15703  */
 15704  SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
 15705  
 15706  /* Free up as much memory as possible from the page cache */
 15707  SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
 15708  
 15709  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 15710  /* Try to return memory used by the pcache module to the main memory heap */
 15711  SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
 15712  #endif
 15713  
 15714  #ifdef SQLITE_TEST
 15715  SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
 15716  #endif
 15717  
 15718  SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
 15719  
 15720  /* Return the header size */
 15721  SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
 15722  SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
 15723  
 15724  /* Number of dirty pages as a percentage of the configured cache size */
 15725  SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
 15726  
 15727  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 15728  SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 15729  #endif
 15730  
 15731  #endif /* _PCACHE_H_ */
 15732  
 15733  /************** End of pcache.h **********************************************/
 15734  /************** Begin file branches.h ****************************************/
 15735  
 15736  #include "lmdb.h"
 15737  
 15738  /* global LMDB environment handle shared between connections from the same process */
 15739  struct global_lmdb {
 15740    struct global_lmdb *next;
 15741    MDB_env *env;         /* LMDB environment handle */
 15742    int      refcount;    /* reference counter */
 15743  };
 15744  
 15745  struct global_lmdb *global_lmdb=NULL;
 15746  
 15747  struct branch_info {
 15748    int id;               /* if ==0, the branch is deleted and no more in use */
 15749    int visible;          /* = not deleted */
 15750    char name[128];       /* the branch name */
 15751    int source_branch;    /* where this branch starts from */
 15752    u64 source_commit;    /* the commit on the source branch where this branch starts at. this_branch.first_commit = source_commit + 1 */
 15753    u64 last_commit;      /* num_commits = last_commit - source_commit */
 15754    u64 max_commit;       /* selected by the user or 0 if none was specified */
 15755    u32 commit_max_page;  /* the maximum page number up to this commit */
 15756    u32 max_page;         /* the maximum page number on this branch */
 15757    u32 txn_max_page;     /* The max pgno on the current transaction */
 15758    MDB_dbi pages_db;     /* the LMDB database storing the SQLite pages for this branch */
 15759    MDB_dbi maxpg_db;     /* the LMDB database storing the max page number for each commit */
 15760    u8 temp_db_handle;    /* if the db handle was not 'commited' yet */
 15761    u8 is_new;            /* if this branch was not saved yet */
 15762  };
 15763  
 15764  struct data_chunk {
 15765    struct data_chunk *next;
 15766    int total;            /* total size of the buffer bellow */
 15767    int used;             /* used size */
 15768    unsigned char buf[];
 15769  };
 15770  
 15771  struct lmdb {
 15772    struct global_lmdb *global;
 15773    MDB_env *env;
 15774    MDB_txn *txn;
 15775    MDB_dbi main_db;             /* the main LMDB database */
 15776    MDB_dbi logs_db;             /* sub-database to store sql logs */
 15777    MDB_dbi meta_db;             /* sub-database to store metadata */
 15778    u8 inReadTxn;                /* True if in a read transaction */
 15779    u8 inWriteTxn;               /* True if in a write transaction */
 15780    u32 pageSize;                /* Database page size */
 15781    u8 useJson;                  /* use JSON format in pragma command results */
 15782    u8 singleConnection;         /* this db is used by a single connection */
 15783  
 15784    int db_change_counter;              /* if the db was modified since the last time this struct was loaded */
 15785    int num_branches;                   /* the number of items in the branches array */
 15786    struct branch_info* branches;       /* array */
 15787    struct branch_info* current_branch; /* pointer to an array item */
 15788  
 15789    char current_branch_name[128];      /* if reloading the array this keeps the selected branch name */  // -- MAYBE NOT NEEDED !!
 15790    u64  current_branch_commit;         /* same as above */
 15791  #ifndef OMIT_BRANCH_LOG
 15792    char *sql;                   /* The SQL command being executed */
 15793    char *log;                   /* The list of SQL commands for this transaction */
 15794  #endif
 15795  };
 15796  
 15797  typedef struct lmdb lmdb;
 15798  typedef struct branch_info branch_info;
 15799  
 15800  SQLITE_PRIVATE int  sqlite3BranchInit(Pager *pPager);
 15801  SQLITE_PRIVATE void sqlite3BranchClose(Pager *pPager);
 15802  
 15803  SQLITE_PRIVATE int  sqlite3BranchLoadArray(lmdb *lmdb);
 15804  SQLITE_PRIVATE int  sqlite3BranchFind(lmdb *lmdb, char *name);
 15805  
 15806  SQLITE_PRIVATE int  sqlite3BranchOpen(lmdb *lmdb, int branch_id, int open_txn);
 15807  SQLITE_PRIVATE int  sqlite3BranchGetMaxPage(lmdb *lmdb, branch_info *branch);
 15808  SQLITE_PRIVATE int  sqlite3BranchGetCommitMaxPage(lmdb *lmdb, branch_info *branch, u64 commit_id, Pgno *pMaxPgno);
 15809  
 15810  SQLITE_PRIVATE int  sqlite3BranchBeginReadTransaction(lmdb *lmdb, int check_for_updates, int *pChanged);
 15811  SQLITE_PRIVATE void sqlite3BranchEndReadTransaction(lmdb *lmdb);
 15812  SQLITE_PRIVATE int  sqlite3BranchBeginWriteTransaction(lmdb *lmdb);
 15813  SQLITE_PRIVATE int  sqlite3BranchEndWriteTransaction(lmdb *lmdb, int reopen_read_txn);
 15814  SQLITE_PRIVATE int  sqlite3BranchUndoChanges(lmdb *lmdb);
 15815  SQLITE_PRIVATE int  sqlite3BranchCommitTransaction(lmdb *lmdb, int reopen_read_txn);
 15816  SQLITE_PRIVATE int  sqlite3BranchGetPage(lmdb *lmdb, Pgno pgno, u8 **ppData);
 15817  SQLITE_PRIVATE int  sqlite3BranchReadPage(lmdb *lmdb, Pgno pgno, int nOut, u8 *pOut);
 15818  SQLITE_PRIVATE int  sqlite3BranchWritePages(lmdb *lmdb, PgHdr *pList, Pgno nTruncate, int isCommit);
 15819  
 15820  SQLITE_PRIVATE void sqlite3BranchSavepoint(lmdb *lmdb, u32 *aWalData);
 15821  SQLITE_PRIVATE int  sqlite3BranchSavepointUndo(lmdb *lmdb, u32 *aWalData);
 15822  
 15823  #ifndef OMIT_BRANCH_LOG
 15824  SQLITE_PRIVATE int  sqlite3BranchStoreLastCommand(lmdb *lmdb);
 15825  SQLITE_PRIVATE int  sqlite3BranchSaveSqlLog(lmdb *lmdb, int branch_id, u64 commit_id);
 15826  SQLITE_PRIVATE void sqlite3BranchDiscardSqlLog(lmdb *lmdb);
 15827  #endif
 15828  
 15829  SQLITE_PRIVATE int  is_commit_accessible(lmdb *lmdb, int branch_id, u64 commit, int *paccessible);
 15830  
 15831  #define LMDB_PAGE_RESERVED_SPACE 16
 15832  
 15833  SQLITE_PRIVATE char * pragma_get_branch_list(lmdb *lmdb);
 15834  #if 0
 15835  SQLITE_PRIVATE int    pragma_set_current_branch(sqlite3 *db, int iDb, char *zBranch, u64 iCommit);
 15836  SQLITE_PRIVATE char * pragma_get_current_branch(sqlite3 *db, int iDb, Parse *pParse);
 15837  SQLITE_PRIVATE int    pragma_new_branch(sqlite3 *db, int iDb, char *zBranchName, char *zSourceBranch, char *zSourceCommit);
 15838  SQLITE_PRIVATE int    pragma_rename_branch(sqlite3 *db, int iDb, char *old_name, char *new_name);
 15839  SQLITE_PRIVATE int    pragma_truncate_branch(sqlite3 *db, int iDb, char *name, u64 to_commit);
 15840  SQLITE_PRIVATE int    pragma_delete_branch(sqlite3 *db, int iDb, char *name);
 15841  #endif
 15842  SQLITE_PRIVATE char * pragma_get_branch_info(sqlite3 *db, int iDb, char *name);
 15843  #ifndef OMIT_BRANCH_LOG
 15844  SQLITE_PRIVATE int    pragma_get_branch_log(sqlite3 *db, int iDb, char *params, Parse *pParse);
 15845  #endif
 15846  
 15847  /************** End of branches.h ********************************************/
 15848  /************** Continuing where we left off in sqliteInt.h ******************/
 15849  /************** Include os.h in the middle of sqliteInt.h ********************/
 15850  /************** Begin file os.h **********************************************/
 15851  /*
 15852  ** 2001 September 16
 15853  **
 15854  ** The author disclaims copyright to this source code.  In place of
 15855  ** a legal notice, here is a blessing:
 15856  **
 15857  **    May you do good and not evil.
 15858  **    May you find forgiveness for yourself and forgive others.
 15859  **    May you share freely, never taking more than you give.
 15860  **
 15861  ******************************************************************************
 15862  **
 15863  ** This header file (together with is companion C source-code file
 15864  ** "os.c") attempt to abstract the underlying operating system so that
 15865  ** the SQLite library will work on both POSIX and windows systems.
 15866  **
 15867  ** This header file is #include-ed by sqliteInt.h and thus ends up
 15868  ** being included by every source file.
 15869  */
 15870  #ifndef _SQLITE_OS_H_
 15871  #define _SQLITE_OS_H_
 15872  
 15873  /*
 15874  ** Attempt to automatically detect the operating system and setup the
 15875  ** necessary pre-processor macros for it.
 15876  */
 15877  /************** Include os_setup.h in the middle of os.h *********************/
 15878  /************** Begin file os_setup.h ****************************************/
 15879  /*
 15880  ** 2013 November 25
 15881  **
 15882  ** The author disclaims copyright to this source code.  In place of
 15883  ** a legal notice, here is a blessing:
 15884  **
 15885  **    May you do good and not evil.
 15886  **    May you find forgiveness for yourself and forgive others.
 15887  **    May you share freely, never taking more than you give.
 15888  **
 15889  ******************************************************************************
 15890  **
 15891  ** This file contains pre-processor directives related to operating system
 15892  ** detection and/or setup.
 15893  */
 15894  #ifndef SQLITE_OS_SETUP_H
 15895  #define SQLITE_OS_SETUP_H
 15896  
 15897  /*
 15898  ** Figure out if we are dealing with Unix, Windows, or some other operating
 15899  ** system.
 15900  **
 15901  ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
 15902  ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
 15903  ** the three will be 1.  The other two will be 0.
 15904  */
 15905  #if defined(SQLITE_OS_OTHER)
 15906  #  if SQLITE_OS_OTHER==1
 15907  #    undef SQLITE_OS_UNIX
 15908  #    define SQLITE_OS_UNIX 0
 15909  #    undef SQLITE_OS_WIN
 15910  #    define SQLITE_OS_WIN 0
 15911  #  else
 15912  #    undef SQLITE_OS_OTHER
 15913  #  endif
 15914  #endif
 15915  #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
 15916  #  define SQLITE_OS_OTHER 0
 15917  #  ifndef SQLITE_OS_WIN
 15918  #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
 15919          defined(__MINGW32__) || defined(__BORLANDC__)
 15920  #      define SQLITE_OS_WIN 1
 15921  #      define SQLITE_OS_UNIX 0
 15922  #    else
 15923  #      define SQLITE_OS_WIN 0
 15924  #      define SQLITE_OS_UNIX 1
 15925  #    endif
 15926  #  else
 15927  #    define SQLITE_OS_UNIX 0
 15928  #  endif
 15929  #else
 15930  #  ifndef SQLITE_OS_WIN
 15931  #    define SQLITE_OS_WIN 0
 15932  #  endif
 15933  #endif
 15934  
 15935  #endif /* SQLITE_OS_SETUP_H */
 15936  
 15937  /************** End of os_setup.h ********************************************/
 15938  /************** Continuing where we left off in os.h *************************/
 15939  
 15940  /* If the SET_FULLSYNC macro is not defined above, then make it
 15941  ** a no-op
 15942  */
 15943  #ifndef SET_FULLSYNC
 15944  # define SET_FULLSYNC(x,y)
 15945  #endif
 15946  
 15947  /*
 15948  ** The default size of a disk sector
 15949  */
 15950  #ifndef SQLITE_DEFAULT_SECTOR_SIZE
 15951  # define SQLITE_DEFAULT_SECTOR_SIZE 4096
 15952  #endif
 15953  
 15954  /*
 15955  ** Temporary files are named starting with this prefix followed by 16 random
 15956  ** alphanumeric characters, and no file extension. They are stored in the
 15957  ** OS's standard temporary file directory, and are deleted prior to exit.
 15958  ** If sqlite is being embedded in another program, you may wish to change the
 15959  ** prefix to reflect your program's name, so that if your program exits
 15960  ** prematurely, old temporary files can be easily identified. This can be done
 15961  ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
 15962  **
 15963  ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
 15964  ** Mcafee started using SQLite in their anti-virus product and it
 15965  ** started putting files with the "sqlite" name in the c:/temp folder.
 15966  ** This annoyed many windows users.  Those users would then do a 
 15967  ** Google search for "sqlite", find the telephone numbers of the
 15968  ** developers and call to wake them up at night and complain.
 15969  ** For this reason, the default name prefix is changed to be "sqlite" 
 15970  ** spelled backwards.  So the temp files are still identified, but
 15971  ** anybody smart enough to figure out the code is also likely smart
 15972  ** enough to know that calling the developer will not help get rid
 15973  ** of the file.
 15974  */
 15975  #ifndef SQLITE_TEMP_FILE_PREFIX
 15976  # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
 15977  #endif
 15978  
 15979  /*
 15980  ** The following values may be passed as the second argument to
 15981  ** sqlite3OsLock(). The various locks exhibit the following semantics:
 15982  **
 15983  ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
 15984  ** RESERVED:  A single process may hold a RESERVED lock on a file at
 15985  **            any time. Other processes may hold and obtain new SHARED locks.
 15986  ** PENDING:   A single process may hold a PENDING lock on a file at
 15987  **            any one time. Existing SHARED locks may persist, but no new
 15988  **            SHARED locks may be obtained by other processes.
 15989  ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
 15990  **
 15991  ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
 15992  ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
 15993  ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
 15994  ** sqlite3OsLock().
 15995  */
 15996  #define NO_LOCK         0
 15997  #define SHARED_LOCK     1
 15998  #define RESERVED_LOCK   2
 15999  #define PENDING_LOCK    3
 16000  #define EXCLUSIVE_LOCK  4
 16001  
 16002  /*
 16003  ** File Locking Notes:  (Mostly about windows but also some info for Unix)
 16004  **
 16005  ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
 16006  ** those functions are not available.  So we use only LockFile() and
 16007  ** UnlockFile().
 16008  **
 16009  ** LockFile() prevents not just writing but also reading by other processes.
 16010  ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
 16011  ** byte out of a specific range of bytes. The lock byte is obtained at 
 16012  ** random so two separate readers can probably access the file at the 
 16013  ** same time, unless they are unlucky and choose the same lock byte.
 16014  ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
 16015  ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
 16016  ** a single byte of the file that is designated as the reserved lock byte.
 16017  ** A PENDING_LOCK is obtained by locking a designated byte different from
 16018  ** the RESERVED_LOCK byte.
 16019  **
 16020  ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
 16021  ** which means we can use reader/writer locks.  When reader/writer locks
 16022  ** are used, the lock is placed on the same range of bytes that is used
 16023  ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
 16024  ** will support two or more Win95 readers or two or more WinNT readers.
 16025  ** But a single Win95 reader will lock out all WinNT readers and a single
 16026  ** WinNT reader will lock out all other Win95 readers.
 16027  **
 16028  ** The following #defines specify the range of bytes used for locking.
 16029  ** SHARED_SIZE is the number of bytes available in the pool from which
 16030  ** a random byte is selected for a shared lock.  The pool of bytes for
 16031  ** shared locks begins at SHARED_FIRST. 
 16032  **
 16033  ** The same locking strategy and
 16034  ** byte ranges are used for Unix.  This leaves open the possibility of having
 16035  ** clients on win95, winNT, and unix all talking to the same shared file
 16036  ** and all locking correctly.  To do so would require that samba (or whatever
 16037  ** tool is being used for file sharing) implements locks correctly between
 16038  ** windows and unix.  I'm guessing that isn't likely to happen, but by
 16039  ** using the same locking range we are at least open to the possibility.
 16040  **
 16041  ** Locking in windows is manditory.  For this reason, we cannot store
 16042  ** actual data in the bytes used for locking.  The pager never allocates
 16043  ** the pages involved in locking therefore.  SHARED_SIZE is selected so
 16044  ** that all locks will fit on a single page even at the minimum page size.
 16045  ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
 16046  ** is set high so that we don't have to allocate an unused page except
 16047  ** for very large databases.  But one should test the page skipping logic 
 16048  ** by setting PENDING_BYTE low and running the entire regression suite.
 16049  **
 16050  ** Changing the value of PENDING_BYTE results in a subtly incompatible
 16051  ** file format.  Depending on how it is changed, you might not notice
 16052  ** the incompatibility right away, even running a full regression test.
 16053  ** The default location of PENDING_BYTE is the first byte past the
 16054  ** 1GB boundary.
 16055  **
 16056  */
 16057  #ifdef SQLITE_OMIT_WSD
 16058  # define PENDING_BYTE     (0x40000000)
 16059  #else
 16060  # define PENDING_BYTE      sqlite3PendingByte
 16061  #endif
 16062  #define RESERVED_BYTE     (PENDING_BYTE+1)
 16063  #define SHARED_FIRST      (PENDING_BYTE+2)
 16064  #define SHARED_SIZE       510
 16065  
 16066  /*
 16067  ** Wrapper around OS specific sqlite3_os_init() function.
 16068  */
 16069  SQLITE_PRIVATE int sqlite3OsInit(void);
 16070  
 16071  /* 
 16072  ** Functions for accessing sqlite3_file methods 
 16073  */
 16074  SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
 16075  SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
 16076  SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
 16077  SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
 16078  SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
 16079  SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
 16080  SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
 16081  SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
 16082  SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
 16083  SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
 16084  SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
 16085  #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
 16086  SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
 16087  SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
 16088  #ifndef SQLITE_OMIT_WAL
 16089  SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
 16090  SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
 16091  SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
 16092  SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
 16093  #endif /* SQLITE_OMIT_WAL */
 16094  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
 16095  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
 16096  
 16097  
 16098  /* 
 16099  ** Functions for accessing sqlite3_vfs methods 
 16100  */
 16101  SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
 16102  SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
 16103  SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
 16104  SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
 16105  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 16106  SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
 16107  SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
 16108  SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
 16109  SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
 16110  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 16111  SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
 16112  SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
 16113  SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
 16114  SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
 16115  
 16116  /*
 16117  ** Convenience functions for opening and closing files using 
 16118  ** sqlite3_malloc() to obtain space for the file-handle structure.
 16119  */
 16120  SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
 16121  SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
 16122  
 16123  #endif /* _SQLITE_OS_H_ */
 16124  
 16125  /************** End of os.h **************************************************/
 16126  /************** Continuing where we left off in sqliteInt.h ******************/
 16127  /************** Include mutex.h in the middle of sqliteInt.h *****************/
 16128  /************** Begin file mutex.h *******************************************/
 16129  /*
 16130  ** 2007 August 28
 16131  **
 16132  ** The author disclaims copyright to this source code.  In place of
 16133  ** a legal notice, here is a blessing:
 16134  **
 16135  **    May you do good and not evil.
 16136  **    May you find forgiveness for yourself and forgive others.
 16137  **    May you share freely, never taking more than you give.
 16138  **
 16139  *************************************************************************
 16140  **
 16141  ** This file contains the common header for all mutex implementations.
 16142  ** The sqliteInt.h header #includes this file so that it is available
 16143  ** to all source files.  We break it out in an effort to keep the code
 16144  ** better organized.
 16145  **
 16146  ** NOTE:  source files should *not* #include this header file directly.
 16147  ** Source files should #include the sqliteInt.h file and let that file
 16148  ** include this one indirectly.
 16149  */
 16150  
 16151  
 16152  /*
 16153  ** Figure out what version of the code to use.  The choices are
 16154  **
 16155  **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
 16156  **                             mutexes implementation cannot be overridden
 16157  **                             at start-time.
 16158  **
 16159  **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
 16160  **                             mutual exclusion is provided.  But this
 16161  **                             implementation can be overridden at
 16162  **                             start-time.
 16163  **
 16164  **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
 16165  **
 16166  **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
 16167  */
 16168  #if !SQLITE_THREADSAFE
 16169  # define SQLITE_MUTEX_OMIT
 16170  #endif
 16171  #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
 16172  #  if SQLITE_OS_UNIX
 16173  #    define SQLITE_MUTEX_PTHREADS
 16174  #  elif SQLITE_OS_WIN
 16175  #    define SQLITE_MUTEX_W32
 16176  #  else
 16177  #    define SQLITE_MUTEX_NOOP
 16178  #  endif
 16179  #endif
 16180  
 16181  #ifdef SQLITE_MUTEX_OMIT
 16182  /*
 16183  ** If this is a no-op implementation, implement everything as macros.
 16184  */
 16185  #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
 16186  #define sqlite3_mutex_free(X)
 16187  #define sqlite3_mutex_enter(X)    
 16188  #define sqlite3_mutex_try(X)      SQLITE_OK
 16189  #define sqlite3_mutex_leave(X)    
 16190  #define sqlite3_mutex_held(X)     ((void)(X),1)
 16191  #define sqlite3_mutex_notheld(X)  ((void)(X),1)
 16192  #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
 16193  #define sqlite3MutexInit()        SQLITE_OK
 16194  #define sqlite3MutexEnd()
 16195  #define MUTEX_LOGIC(X)
 16196  #else
 16197  #define MUTEX_LOGIC(X)            X
 16198  #endif /* defined(SQLITE_MUTEX_OMIT) */
 16199  
 16200  /************** End of mutex.h ***********************************************/
 16201  /************** Continuing where we left off in sqliteInt.h ******************/
 16202  
 16203  /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
 16204  ** synchronous setting to EXTRA.  It is no longer supported.
 16205  */
 16206  #ifdef SQLITE_EXTRA_DURABLE
 16207  # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
 16208  # define SQLITE_DEFAULT_SYNCHRONOUS 3
 16209  #endif
 16210  
 16211  /*
 16212  ** Default synchronous levels.
 16213  **
 16214  ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
 16215  ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
 16216  **
 16217  **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
 16218  **   OFF           1                         0
 16219  **   NORMAL        2                         1
 16220  **   FULL          3                         2
 16221  **   EXTRA         4                         3
 16222  **
 16223  ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
 16224  ** In other words, the zero-based numbers are used for all external interfaces
 16225  ** and the one-based values are used internally.
 16226  */
 16227  #ifndef SQLITE_DEFAULT_SYNCHRONOUS
 16228  # define SQLITE_DEFAULT_SYNCHRONOUS 2
 16229  #endif
 16230  #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
 16231  # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
 16232  #endif
 16233  
 16234  /*
 16235  ** Each database file to be accessed by the system is an instance
 16236  ** of the following structure.  There are normally two of these structures
 16237  ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
 16238  ** aDb[1] is the database file used to hold temporary tables.  Additional
 16239  ** databases may be attached.
 16240  */
 16241  struct Db {
 16242    char *zDbSName;      /* Name of this database. (schema name, not filename) */
 16243    Btree *pBt;          /* The B*Tree structure for this database file */
 16244    u8 safety_level;     /* How aggressive at syncing data to disk */
 16245    u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
 16246    Schema *pSchema;     /* Pointer to database schema (possibly shared) */
 16247  };
 16248  
 16249  /*
 16250  ** An instance of the following structure stores a database schema.
 16251  **
 16252  ** Most Schema objects are associated with a Btree.  The exception is
 16253  ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
 16254  ** In shared cache mode, a single Schema object can be shared by multiple
 16255  ** Btrees that refer to the same underlying BtShared object.
 16256  **
 16257  ** Schema objects are automatically deallocated when the last Btree that
 16258  ** references them is destroyed.   The TEMP Schema is manually freed by
 16259  ** sqlite3_close().
 16260  *
 16261  ** A thread must be holding a mutex on the corresponding Btree in order
 16262  ** to access Schema content.  This implies that the thread must also be
 16263  ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
 16264  ** For a TEMP Schema, only the connection mutex is required.
 16265  */
 16266  struct Schema {
 16267    int schema_cookie;   /* Database schema version number for this file */
 16268    int iGeneration;     /* Generation counter.  Incremented with each change */
 16269    Hash tblHash;        /* All tables indexed by name */
 16270    Hash idxHash;        /* All (named) indices indexed by name */
 16271    Hash trigHash;       /* All triggers indexed by name */
 16272    Hash fkeyHash;       /* All foreign keys by referenced table name */
 16273    Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
 16274    u8 file_format;      /* Schema format version for this file */
 16275    u8 enc;              /* Text encoding used by this database */
 16276    u16 schemaFlags;     /* Flags associated with this schema */
 16277    int cache_size;      /* Number of pages to use in the cache */
 16278  };
 16279  
 16280  /*
 16281  ** These macros can be used to test, set, or clear bits in the
 16282  ** Db.pSchema->flags field.
 16283  */
 16284  #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
 16285  #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
 16286  #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
 16287  #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
 16288  
 16289  /*
 16290  ** Allowed values for the DB.pSchema->flags field.
 16291  **
 16292  ** The DB_SchemaLoaded flag is set after the database schema has been
 16293  ** read into internal hash tables.
 16294  **
 16295  ** DB_UnresetViews means that one or more views have column names that
 16296  ** have been filled out.  If the schema changes, these column names might
 16297  ** changes and so the view will need to be reset.
 16298  */
 16299  #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
 16300  #define DB_UnresetViews    0x0002  /* Some views have defined column names */
 16301  #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
 16302  #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
 16303  
 16304  /*
 16305  ** The number of different kinds of things that can be limited
 16306  ** using the sqlite3_limit() interface.
 16307  */
 16308  #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
 16309  
 16310  /*
 16311  ** Lookaside malloc is a set of fixed-size buffers that can be used
 16312  ** to satisfy small transient memory allocation requests for objects
 16313  ** associated with a particular database connection.  The use of
 16314  ** lookaside malloc provides a significant performance enhancement
 16315  ** (approx 10%) by avoiding numerous malloc/free requests while parsing
 16316  ** SQL statements.
 16317  **
 16318  ** The Lookaside structure holds configuration information about the
 16319  ** lookaside malloc subsystem.  Each available memory allocation in
 16320  ** the lookaside subsystem is stored on a linked list of LookasideSlot
 16321  ** objects.
 16322  **
 16323  ** Lookaside allocations are only allowed for objects that are associated
 16324  ** with a particular database connection.  Hence, schema information cannot
 16325  ** be stored in lookaside because in shared cache mode the schema information
 16326  ** is shared by multiple database connections.  Therefore, while parsing
 16327  ** schema information, the Lookaside.bEnabled flag is cleared so that
 16328  ** lookaside allocations are not used to construct the schema objects.
 16329  */
 16330  struct Lookaside {
 16331    u32 bDisable;           /* Only operate the lookaside when zero */
 16332    u16 sz;                 /* Size of each buffer in bytes */
 16333    u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
 16334    u32 nSlot;              /* Number of lookaside slots allocated */
 16335    u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
 16336    LookasideSlot *pInit;   /* List of buffers not previously used */
 16337    LookasideSlot *pFree;   /* List of available buffers */
 16338    void *pStart;           /* First byte of available memory space */
 16339    void *pEnd;             /* First byte past end of available space */
 16340  };
 16341  struct LookasideSlot {
 16342    LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
 16343  };
 16344  
 16345  /*
 16346  ** A hash table for built-in function definitions.  (Application-defined
 16347  ** functions use a regular table table from hash.h.)
 16348  **
 16349  ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
 16350  ** Collisions are on the FuncDef.u.pHash chain.  Use the SQLITE_FUNC_HASH()
 16351  ** macro to compute a hash on the function name.
 16352  */
 16353  #define SQLITE_FUNC_HASH_SZ 23
 16354  struct FuncDefHash {
 16355    FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
 16356  };
 16357  #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
 16358  
 16359  #ifdef SQLITE_USER_AUTHENTICATION
 16360  /*
 16361  ** Information held in the "sqlite3" database connection object and used
 16362  ** to manage user authentication.
 16363  */
 16364  typedef struct sqlite3_userauth sqlite3_userauth;
 16365  struct sqlite3_userauth {
 16366    u8 authLevel;                 /* Current authentication level */
 16367    int nAuthPW;                  /* Size of the zAuthPW in bytes */
 16368    char *zAuthPW;                /* Password used to authenticate */
 16369    char *zAuthUser;              /* User name used to authenticate */
 16370  };
 16371  
 16372  /* Allowed values for sqlite3_userauth.authLevel */
 16373  #define UAUTH_Unknown     0     /* Authentication not yet checked */
 16374  #define UAUTH_Fail        1     /* User authentication failed */
 16375  #define UAUTH_User        2     /* Authenticated as a normal user */
 16376  #define UAUTH_Admin       3     /* Authenticated as an administrator */
 16377  
 16378  /* Functions used only by user authorization logic */
 16379  SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
 16380  SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
 16381  SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
 16382  SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
 16383  
 16384  #endif /* SQLITE_USER_AUTHENTICATION */
 16385  
 16386  /*
 16387  ** typedef for the authorization callback function.
 16388  */
 16389  #ifdef SQLITE_USER_AUTHENTICATION
 16390    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
 16391                                 const char*, const char*);
 16392  #else
 16393    typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
 16394                                 const char*);
 16395  #endif
 16396  
 16397  #ifndef SQLITE_OMIT_DEPRECATED
 16398  /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
 16399  ** in the style of sqlite3_trace()
 16400  */
 16401  #define SQLITE_TRACE_LEGACY          0x40     /* Use the legacy xTrace */
 16402  #define SQLITE_TRACE_XPROFILE        0x80     /* Use the legacy xProfile */
 16403  #else
 16404  #define SQLITE_TRACE_LEGACY          0
 16405  #define SQLITE_TRACE_XPROFILE        0
 16406  #endif /* SQLITE_OMIT_DEPRECATED */
 16407  #define SQLITE_TRACE_NONLEGACY_MASK  0x0f     /* Normal flags */
 16408  
 16409  
 16410  /*
 16411  ** Each database connection is an instance of the following structure.
 16412  */
 16413  struct sqlite3 {
 16414    sqlite3_vfs *pVfs;            /* OS Interface */
 16415    struct Vdbe *pVdbe;           /* List of active virtual machines */
 16416    CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
 16417    sqlite3_mutex *mutex;         /* Connection mutex */
 16418    Db *aDb;                      /* All backends */
 16419    int nDb;                      /* Number of backends currently in use */
 16420    u32 mDbFlags;                 /* flags recording internal state */
 16421    u64 flags;                    /* flags settable by pragmas. See below */
 16422    i64 lastRowid;                /* ROWID of most recent insert (see above) */
 16423    i64 szMmap;                   /* Default mmap_size setting */
 16424    u32 nSchemaLock;              /* Do not reset the schema when non-zero */
 16425    unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
 16426    int errCode;                  /* Most recent error code (SQLITE_*) */
 16427    int errMask;                  /* & result codes with this before returning */
 16428    int iSysErrno;                /* Errno value from last system error */
 16429    u16 dbOptFlags;               /* Flags to enable/disable optimizations */
 16430    u8 enc;                       /* Text encoding */
 16431    u8 autoCommit;                /* The auto-commit flag. */
 16432    u8 temp_store;                /* 1: file 2: memory 0: default */
 16433    u8 mallocFailed;              /* True if we have seen a malloc failure */
 16434    u8 bBenignMalloc;             /* Do not require OOMs if true */
 16435    u8 dfltLockMode;              /* Default locking-mode for attached dbs */
 16436    signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
 16437    u8 suppressErr;               /* Do not issue error messages if true */
 16438    u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
 16439    u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
 16440    u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
 16441    u8 noSharedCache;             /* True if no shared-cache backends */
 16442    u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
 16443    int nextPagesize;             /* Pagesize after VACUUM if >0 */
 16444    u32 magic;                    /* Magic number for detect library misuse */
 16445    int nChange;                  /* Value returned by sqlite3_changes() */
 16446    int nTotalChange;             /* Value returned by sqlite3_total_changes() */
 16447    int aLimit[SQLITE_N_LIMIT];   /* Limits */
 16448    int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
 16449    struct sqlite3InitInfo {      /* Information used during initialization */
 16450      int newTnum;                /* Rootpage of table being initialized */
 16451      u8 iDb;                     /* Which db file is being initialized */
 16452      u8 busy;                    /* TRUE if currently initializing */
 16453      unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
 16454      unsigned imposterTable : 1; /* Building an imposter table */
 16455      unsigned reopenMemdb : 1;   /* ATTACH is really a reopen using MemDB */
 16456    } init;
 16457    int nVdbeActive;              /* Number of VDBEs currently running */
 16458    int nVdbeRead;                /* Number of active VDBEs that read or write */
 16459    int nVdbeWrite;               /* Number of active VDBEs that read and write */
 16460    int nVdbeExec;                /* Number of nested calls to VdbeExec() */
 16461    int nVDestroy;                /* Number of active OP_VDestroy operations */
 16462    int nExtension;               /* Number of loaded extensions */
 16463    void **aExtension;            /* Array of shared library handles */
 16464    int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
 16465    void *pTraceArg;                          /* Argument to the trace function */
 16466  #ifndef SQLITE_OMIT_DEPRECATED
 16467    void (*xProfile)(void*,const char*,u64);  /* Profiling function */
 16468    void *pProfileArg;                        /* Argument to profile function */
 16469  #endif
 16470    void *pCommitArg;                 /* Argument to xCommitCallback() */
 16471    int (*xCommitCallback)(void*);    /* Invoked at every commit. */
 16472    void *pRollbackArg;               /* Argument to xRollbackCallback() */
 16473    void (*xRollbackCallback)(void*); /* Invoked at every commit. */
 16474    void *pUpdateArg;
 16475    void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
 16476  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 16477    void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
 16478    void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
 16479      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
 16480    );
 16481    PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
 16482  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 16483  #ifndef SQLITE_OMIT_WAL
 16484    int (*xWalCallback)(void *, sqlite3 *, const char *, int);
 16485    void *pWalArg;
 16486  #endif
 16487    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
 16488    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
 16489    void *pCollNeededArg;
 16490    sqlite3_value *pErr;          /* Most recent error message */
 16491    union {
 16492      volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
 16493      double notUsed1;            /* Spacer */
 16494    } u1;
 16495    Lookaside lookaside;          /* Lookaside malloc configuration */
 16496  #ifndef SQLITE_OMIT_AUTHORIZATION
 16497    sqlite3_xauth xAuth;          /* Access authorization function */
 16498    void *pAuthArg;               /* 1st argument to the access auth function */
 16499  #endif
 16500  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 16501    int (*xProgress)(void *);     /* The progress callback */
 16502    void *pProgressArg;           /* Argument to the progress callback */
 16503    unsigned nProgressOps;        /* Number of opcodes for progress callback */
 16504  #endif
 16505  #ifndef SQLITE_OMIT_VIRTUALTABLE
 16506    int nVTrans;                  /* Allocated size of aVTrans */
 16507    Hash aModule;                 /* populated by sqlite3_create_module() */
 16508    VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
 16509    VTable **aVTrans;             /* Virtual tables with open transactions */
 16510    VTable *pDisconnect;          /* Disconnect these in next sqlite3_prepare() */
 16511  #endif
 16512    Hash aFunc;                   /* Hash table of connection functions */
 16513    Hash aCollSeq;                /* All collating sequences */
 16514    BusyHandler busyHandler;      /* Busy callback */
 16515    Db aDbStatic[2];              /* Static space for the 2 default backends */
 16516    Savepoint *pSavepoint;        /* List of active savepoints */
 16517    int busyTimeout;              /* Busy handler timeout, in msec */
 16518    int nSavepoint;               /* Number of non-transaction savepoints */
 16519    int nStatement;               /* Number of nested statement-transactions  */
 16520    i64 nDeferredCons;            /* Net deferred constraints this transaction. */
 16521    i64 nDeferredImmCons;         /* Net deferred immediate constraints */
 16522    int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
 16523  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 16524    /* The following variables are all protected by the STATIC_MASTER
 16525    ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
 16526    **
 16527    ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
 16528    ** unlock so that it can proceed.
 16529    **
 16530    ** When X.pBlockingConnection==Y, that means that something that X tried
 16531    ** tried to do recently failed with an SQLITE_LOCKED error due to locks
 16532    ** held by Y.
 16533    */
 16534    sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
 16535    sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
 16536    void *pUnlockArg;                     /* Argument to xUnlockNotify */
 16537    void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
 16538    sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
 16539  #endif
 16540  #ifdef SQLITE_USER_AUTHENTICATION
 16541    sqlite3_userauth auth;        /* User authentication information */
 16542  #endif
 16543  };
 16544  
 16545  /*
 16546  ** A macro to discover the encoding of a database.
 16547  */
 16548  #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
 16549  #define ENC(db)        ((db)->enc)
 16550  
 16551  /*
 16552  ** Possible values for the sqlite3.flags.
 16553  **
 16554  ** Value constraints (enforced via assert()):
 16555  **      SQLITE_FullFSync     == PAGER_FULLFSYNC
 16556  **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
 16557  **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
 16558  */
 16559  #define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
 16560  #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
 16561  #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
 16562  #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
 16563  #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
 16564  #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
 16565  #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
 16566  #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
 16567                                            /*   DELETE, or UPDATE and return */
 16568                                            /*   the count using a callback. */
 16569  #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
 16570                                            /*   result set is empty */
 16571  #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
 16572  #define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
 16573  #define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
 16574  #define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
 16575  #define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
 16576  #define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
 16577  #define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
 16578  #define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
 16579  #define SQLITE_LoadExtFunc    0x00020000  /* Enable load_extension() SQL func */
 16580  #define SQLITE_EnableTrigger  0x00040000  /* True to enable triggers */
 16581  #define SQLITE_DeferFKs       0x00080000  /* Defer all FK constraints */
 16582  #define SQLITE_QueryOnly      0x00100000  /* Disable database changes */
 16583  #define SQLITE_CellSizeCk     0x00200000  /* Check btree cell sizes on load */
 16584  #define SQLITE_Fts3Tokenizer  0x00400000  /* Enable fts3_tokenizer(2) */
 16585  #define SQLITE_EnableQPSG     0x00800000  /* Query Planner Stability Guarantee*/
 16586  #define SQLITE_TriggerEQP     0x01000000  /* Show trigger EXPLAIN QUERY PLAN */
 16587  #define SQLITE_ResetDatabase  0x02000000  /* Reset the database */
 16588  #define SQLITE_LegacyAlter    0x04000000  /* Legacy ALTER TABLE behaviour */
 16589  #define SQLITE_NoSchemaError  0x08000000  /* Do not report schema parse errors*/
 16590  #define SQLITE_Defensive      0x10000000  /* Input SQL is likely hostile */
 16591  
 16592  /* Flags used only if debugging */
 16593  #define HI(X)  ((u64)(X)<<32)
 16594  #ifdef SQLITE_DEBUG
 16595  #define SQLITE_SqlTrace       HI(0x0001)  /* Debug print SQL as it executes */
 16596  #define SQLITE_VdbeListing    HI(0x0002)  /* Debug listings of VDBE progs */
 16597  #define SQLITE_VdbeTrace      HI(0x0004)  /* True to trace VDBE execution */
 16598  #define SQLITE_VdbeAddopTrace HI(0x0008)  /* Trace sqlite3VdbeAddOp() calls */
 16599  #define SQLITE_VdbeEQP        HI(0x0010)  /* Debug EXPLAIN QUERY PLAN */
 16600  #define SQLITE_ParserTrace    HI(0x0020)  /* PRAGMA parser_trace=ON */
 16601  #endif
 16602  
 16603  /*
 16604  ** Allowed values for sqlite3.mDbFlags
 16605  */
 16606  #define DBFLAG_SchemaChange   0x0001  /* Uncommitted Hash table changes */
 16607  #define DBFLAG_PreferBuiltin  0x0002  /* Preference to built-in funcs */
 16608  #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
 16609  #define DBFLAG_SchemaKnownOk  0x0008  /* Schema is known to be valid */
 16610  
 16611  /*
 16612  ** Bits of the sqlite3.dbOptFlags field that are used by the
 16613  ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
 16614  ** selectively disable various optimizations.
 16615  */
 16616  #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
 16617                            /*  0x0002   available for reuse */
 16618  #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
 16619  #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
 16620  #define SQLITE_DistinctOpt    0x0010   /* DISTINCT using indexes */
 16621  #define SQLITE_CoverIdxScan   0x0020   /* Covering index scans */
 16622  #define SQLITE_OrderByIdxJoin 0x0040   /* ORDER BY of joins via index */
 16623  #define SQLITE_Transitive     0x0080   /* Transitive constraints */
 16624  #define SQLITE_OmitNoopJoin   0x0100   /* Omit unused tables in joins */
 16625  #define SQLITE_CountOfView    0x0200   /* The count-of-view optimization */
 16626  #define SQLITE_CursorHints    0x0400   /* Add OP_CursorHint opcodes */
 16627  #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
 16628     /* TH3 expects the Stat34  ^^^^^^ value to be 0x0800.  Don't change it */
 16629  #define SQLITE_PushDown       0x1000   /* The push-down optimization */
 16630  #define SQLITE_SimplifyJoin   0x2000   /* Convert LEFT JOIN to JOIN */
 16631  #define SQLITE_SkipScan       0x4000   /* Skip-scans */
 16632  #define SQLITE_PropagateConst 0x8000   /* The constant propagation opt */
 16633  #define SQLITE_AllOpts        0xffff   /* All optimizations */
 16634  
 16635  /*
 16636  ** Macros for testing whether or not optimizations are enabled or disabled.
 16637  */
 16638  #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
 16639  #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
 16640  
 16641  /*
 16642  ** Return true if it OK to factor constant expressions into the initialization
 16643  ** code. The argument is a Parse object for the code generator.
 16644  */
 16645  #define ConstFactorOk(P) ((P)->okConstFactor)
 16646  
 16647  /*
 16648  ** Possible values for the sqlite.magic field.
 16649  ** The numbers are obtained at random and have no special meaning, other
 16650  ** than being distinct from one another.
 16651  */
 16652  #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
 16653  #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
 16654  #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
 16655  #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
 16656  #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
 16657  #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
 16658  
 16659  /*
 16660  ** Each SQL function is defined by an instance of the following
 16661  ** structure.  For global built-in functions (ex: substr(), max(), count())
 16662  ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
 16663  ** For per-connection application-defined functions, a pointer to this
 16664  ** structure is held in the db->aHash hash table.
 16665  **
 16666  ** The u.pHash field is used by the global built-ins.  The u.pDestructor
 16667  ** field is used by per-connection app-def functions.
 16668  */
 16669  struct FuncDef {
 16670    i8 nArg;             /* Number of arguments.  -1 means unlimited */
 16671    u32 funcFlags;       /* Some combination of SQLITE_FUNC_* */
 16672    void *pUserData;     /* User data parameter */
 16673    FuncDef *pNext;      /* Next function with same name */
 16674    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
 16675    void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
 16676    void (*xValue)(sqlite3_context*);                     /* Current agg value */
 16677    void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
 16678    const char *zName;   /* SQL name of the function. */
 16679    union {
 16680      FuncDef *pHash;      /* Next with a different name but the same hash */
 16681      FuncDestructor *pDestructor;   /* Reference counted destructor function */
 16682    } u;
 16683  };
 16684  
 16685  /*
 16686  ** This structure encapsulates a user-function destructor callback (as
 16687  ** configured using create_function_v2()) and a reference counter. When
 16688  ** create_function_v2() is called to create a function with a destructor,
 16689  ** a single object of this type is allocated. FuncDestructor.nRef is set to
 16690  ** the number of FuncDef objects created (either 1 or 3, depending on whether
 16691  ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
 16692  ** member of each of the new FuncDef objects is set to point to the allocated
 16693  ** FuncDestructor.
 16694  **
 16695  ** Thereafter, when one of the FuncDef objects is deleted, the reference
 16696  ** count on this object is decremented. When it reaches 0, the destructor
 16697  ** is invoked and the FuncDestructor structure freed.
 16698  */
 16699  struct FuncDestructor {
 16700    int nRef;
 16701    void (*xDestroy)(void *);
 16702    void *pUserData;
 16703  };
 16704  
 16705  /*
 16706  ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
 16707  ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
 16708  ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
 16709  ** are assert() statements in the code to verify this.
 16710  **
 16711  ** Value constraints (enforced via assert()):
 16712  **     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
 16713  **     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
 16714  **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
 16715  **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
 16716  **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
 16717  */
 16718  #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
 16719  #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
 16720  #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
 16721  #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
 16722  #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
 16723  #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
 16724  #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
 16725  #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
 16726  #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
 16727  #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
 16728  #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
 16729  #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
 16730  #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
 16731                                      ** single query - might change over time */
 16732  #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
 16733  #define SQLITE_FUNC_OFFSET   0x8000 /* Built-in sqlite_offset() function */
 16734  #define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
 16735  #define SQLITE_FUNC_WINDOW_SIZE 0x20000 /* Requires partition size as arg. */
 16736  #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
 16737  
 16738  /*
 16739  ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
 16740  ** used to create the initializers for the FuncDef structures.
 16741  **
 16742  **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
 16743  **     Used to create a scalar function definition of a function zName
 16744  **     implemented by C function xFunc that accepts nArg arguments. The
 16745  **     value passed as iArg is cast to a (void*) and made available
 16746  **     as the user-data (sqlite3_user_data()) for the function. If
 16747  **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
 16748  **
 16749  **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
 16750  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
 16751  **
 16752  **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
 16753  **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
 16754  **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
 16755  **     and functions like sqlite_version() that can change, but not during
 16756  **     a single query.  The iArg is ignored.  The user-data is always set
 16757  **     to a NULL pointer.  The bNC parameter is not used.
 16758  **
 16759  **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
 16760  **     Used for "pure" date/time functions, this macro is like DFUNCTION
 16761  **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
 16762  **     ignored and the user-data for these functions is set to an 
 16763  **     arbitrary non-NULL pointer.  The bNC parameter is not used.
 16764  **
 16765  **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
 16766  **     Used to create an aggregate function definition implemented by
 16767  **     the C functions xStep and xFinal. The first four parameters
 16768  **     are interpreted in the same way as the first 4 parameters to
 16769  **     FUNCTION().
 16770  **
 16771  **   WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
 16772  **     Used to create an aggregate function definition implemented by
 16773  **     the C functions xStep and xFinal. The first four parameters
 16774  **     are interpreted in the same way as the first 4 parameters to
 16775  **     FUNCTION().
 16776  **
 16777  **   LIKEFUNC(zName, nArg, pArg, flags)
 16778  **     Used to create a scalar function definition of a function zName
 16779  **     that accepts nArg arguments and is implemented by a call to C
 16780  **     function likeFunc. Argument pArg is cast to a (void *) and made
 16781  **     available as the function user-data (sqlite3_user_data()). The
 16782  **     FuncDef.flags variable is set to the value passed as the flags
 16783  **     parameter.
 16784  */
 16785  #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
 16786    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 16787     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 16788  #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 16789    {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 16790     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 16791  #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
 16792    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
 16793     0, 0, xFunc, 0, 0, 0, #zName, {0} }
 16794  #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
 16795    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
 16796     (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
 16797  #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
 16798    {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
 16799     SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
 16800  #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
 16801    {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
 16802     pArg, 0, xFunc, 0, 0, 0, #zName, }
 16803  #define LIKEFUNC(zName, nArg, arg, flags) \
 16804    {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
 16805     (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
 16806  #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
 16807    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
 16808     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
 16809  #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
 16810    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
 16811     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
 16812  #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
 16813    {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
 16814     SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
 16815  #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
 16816    {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
 16817     0, 0, xFunc, 0, 0, 0, #zName, {0} }
 16818  
 16819  
 16820  /*
 16821  ** All current savepoints are stored in a linked list starting at
 16822  ** sqlite3.pSavepoint. The first element in the list is the most recently
 16823  ** opened savepoint. Savepoints are added to the list by the vdbe
 16824  ** OP_Savepoint instruction.
 16825  */
 16826  struct Savepoint {
 16827    char *zName;                        /* Savepoint name (nul-terminated) */
 16828    i64 nDeferredCons;                  /* Number of deferred fk violations */
 16829    i64 nDeferredImmCons;               /* Number of deferred imm fk. */
 16830    Savepoint *pNext;                   /* Parent savepoint (if any) */
 16831  };
 16832  
 16833  /*
 16834  ** The following are used as the second parameter to sqlite3Savepoint(),
 16835  ** and as the P1 argument to the OP_Savepoint instruction.
 16836  */
 16837  #define SAVEPOINT_BEGIN      0
 16838  #define SAVEPOINT_RELEASE    1
 16839  #define SAVEPOINT_ROLLBACK   2
 16840  
 16841  
 16842  /*
 16843  ** Each SQLite module (virtual table definition) is defined by an
 16844  ** instance of the following structure, stored in the sqlite3.aModule
 16845  ** hash table.
 16846  */
 16847  struct Module {
 16848    const sqlite3_module *pModule;       /* Callback pointers */
 16849    const char *zName;                   /* Name passed to create_module() */
 16850    void *pAux;                          /* pAux passed to create_module() */
 16851    void (*xDestroy)(void *);            /* Module destructor function */
 16852    Table *pEpoTab;                      /* Eponymous table for this module */
 16853  };
 16854  
 16855  /*
 16856  ** information about each column of an SQL table is held in an instance
 16857  ** of this structure.
 16858  */
 16859  struct Column {
 16860    char *zName;     /* Name of this column, \000, then the type */
 16861    Expr *pDflt;     /* Default value of this column */
 16862    char *zColl;     /* Collating sequence.  If NULL, use the default */
 16863    u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
 16864    char affinity;   /* One of the SQLITE_AFF_... values */
 16865    u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
 16866    u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
 16867  };
 16868  
 16869  /* Allowed values for Column.colFlags:
 16870  */
 16871  #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
 16872  #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
 16873  #define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
 16874  #define COLFLAG_UNIQUE   0x0008    /* Column def contains "UNIQUE" or "PK" */
 16875  #define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */
 16876  
 16877  /*
 16878  ** A "Collating Sequence" is defined by an instance of the following
 16879  ** structure. Conceptually, a collating sequence consists of a name and
 16880  ** a comparison routine that defines the order of that sequence.
 16881  **
 16882  ** If CollSeq.xCmp is NULL, it means that the
 16883  ** collating sequence is undefined.  Indices built on an undefined
 16884  ** collating sequence may not be read or written.
 16885  */
 16886  struct CollSeq {
 16887    char *zName;          /* Name of the collating sequence, UTF-8 encoded */
 16888    u8 enc;               /* Text encoding handled by xCmp() */
 16889    void *pUser;          /* First argument to xCmp() */
 16890    int (*xCmp)(void*,int, const void*, int, const void*);
 16891    void (*xDel)(void*);  /* Destructor for pUser */
 16892  };
 16893  
 16894  /*
 16895  ** A sort order can be either ASC or DESC.
 16896  */
 16897  #define SQLITE_SO_ASC       0  /* Sort in ascending order */
 16898  #define SQLITE_SO_DESC      1  /* Sort in ascending order */
 16899  #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
 16900  
 16901  /*
 16902  ** Column affinity types.
 16903  **
 16904  ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
 16905  ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
 16906  ** the speed a little by numbering the values consecutively.
 16907  **
 16908  ** But rather than start with 0 or 1, we begin with 'A'.  That way,
 16909  ** when multiple affinity types are concatenated into a string and
 16910  ** used as the P4 operand, they will be more readable.
 16911  **
 16912  ** Note also that the numeric types are grouped together so that testing
 16913  ** for a numeric type is a single comparison.  And the BLOB type is first.
 16914  */
 16915  #define SQLITE_AFF_BLOB     'A'
 16916  #define SQLITE_AFF_TEXT     'B'
 16917  #define SQLITE_AFF_NUMERIC  'C'
 16918  #define SQLITE_AFF_INTEGER  'D'
 16919  #define SQLITE_AFF_REAL     'E'
 16920  
 16921  #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
 16922  
 16923  /*
 16924  ** The SQLITE_AFF_MASK values masks off the significant bits of an
 16925  ** affinity value.
 16926  */
 16927  #define SQLITE_AFF_MASK     0x47
 16928  
 16929  /*
 16930  ** Additional bit values that can be ORed with an affinity without
 16931  ** changing the affinity.
 16932  **
 16933  ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
 16934  ** It causes an assert() to fire if either operand to a comparison
 16935  ** operator is NULL.  It is added to certain comparison operators to
 16936  ** prove that the operands are always NOT NULL.
 16937  */
 16938  #define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
 16939  #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
 16940  #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
 16941  #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
 16942  #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
 16943  
 16944  /*
 16945  ** An object of this type is created for each virtual table present in
 16946  ** the database schema.
 16947  **
 16948  ** If the database schema is shared, then there is one instance of this
 16949  ** structure for each database connection (sqlite3*) that uses the shared
 16950  ** schema. This is because each database connection requires its own unique
 16951  ** instance of the sqlite3_vtab* handle used to access the virtual table
 16952  ** implementation. sqlite3_vtab* handles can not be shared between
 16953  ** database connections, even when the rest of the in-memory database
 16954  ** schema is shared, as the implementation often stores the database
 16955  ** connection handle passed to it via the xConnect() or xCreate() method
 16956  ** during initialization internally. This database connection handle may
 16957  ** then be used by the virtual table implementation to access real tables
 16958  ** within the database. So that they appear as part of the callers
 16959  ** transaction, these accesses need to be made via the same database
 16960  ** connection as that used to execute SQL operations on the virtual table.
 16961  **
 16962  ** All VTable objects that correspond to a single table in a shared
 16963  ** database schema are initially stored in a linked-list pointed to by
 16964  ** the Table.pVTable member variable of the corresponding Table object.
 16965  ** When an sqlite3_prepare() operation is required to access the virtual
 16966  ** table, it searches the list for the VTable that corresponds to the
 16967  ** database connection doing the preparing so as to use the correct
 16968  ** sqlite3_vtab* handle in the compiled query.
 16969  **
 16970  ** When an in-memory Table object is deleted (for example when the
 16971  ** schema is being reloaded for some reason), the VTable objects are not
 16972  ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
 16973  ** immediately. Instead, they are moved from the Table.pVTable list to
 16974  ** another linked list headed by the sqlite3.pDisconnect member of the
 16975  ** corresponding sqlite3 structure. They are then deleted/xDisconnected
 16976  ** next time a statement is prepared using said sqlite3*. This is done
 16977  ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
 16978  ** Refer to comments above function sqlite3VtabUnlockList() for an
 16979  ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
 16980  ** list without holding the corresponding sqlite3.mutex mutex.
 16981  **
 16982  ** The memory for objects of this type is always allocated by
 16983  ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
 16984  ** the first argument.
 16985  */
 16986  struct VTable {
 16987    sqlite3 *db;              /* Database connection associated with this table */
 16988    Module *pMod;             /* Pointer to module implementation */
 16989    sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
 16990    int nRef;                 /* Number of pointers to this structure */
 16991    u8 bConstraint;           /* True if constraints are supported */
 16992    int iSavepoint;           /* Depth of the SAVEPOINT stack */
 16993    VTable *pNext;            /* Next in linked list (see above) */
 16994  };
 16995  
 16996  /*
 16997  ** The schema for each SQL table and view is represented in memory
 16998  ** by an instance of the following structure.
 16999  */
 17000  struct Table {
 17001    char *zName;         /* Name of the table or view */
 17002    Column *aCol;        /* Information about each column */
 17003    Index *pIndex;       /* List of SQL indexes on this table. */
 17004    Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
 17005    FKey *pFKey;         /* Linked list of all foreign keys in this table */
 17006    char *zColAff;       /* String defining the affinity of each column */
 17007    ExprList *pCheck;    /* All CHECK constraints */
 17008                         /*   ... also used as column name list in a VIEW */
 17009    int tnum;            /* Root BTree page for this table */
 17010    u32 nTabRef;         /* Number of pointers to this Table */
 17011    u32 tabFlags;        /* Mask of TF_* values */
 17012    i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
 17013    i16 nCol;            /* Number of columns in this table */
 17014    LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
 17015    LogEst szTabRow;     /* Estimated size of each table row in bytes */
 17016  #ifdef SQLITE_ENABLE_COSTMULT
 17017    LogEst costMult;     /* Cost multiplier for using this table */
 17018  #endif
 17019    u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
 17020  #ifndef SQLITE_OMIT_ALTERTABLE
 17021    int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
 17022  #endif
 17023  #ifndef SQLITE_OMIT_VIRTUALTABLE
 17024    int nModuleArg;      /* Number of arguments to the module */
 17025    char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
 17026    VTable *pVTable;     /* List of VTable objects. */
 17027  #endif
 17028    Trigger *pTrigger;   /* List of triggers stored in pSchema */
 17029    Schema *pSchema;     /* Schema that contains this table */
 17030    Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
 17031  };
 17032  
 17033  /*
 17034  ** Allowed values for Table.tabFlags.
 17035  **
 17036  ** TF_OOOHidden applies to tables or view that have hidden columns that are
 17037  ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
 17038  ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
 17039  ** the TF_OOOHidden attribute would apply in this case.  Such tables require
 17040  ** special handling during INSERT processing.
 17041  */
 17042  #define TF_Readonly        0x0001    /* Read-only system table */
 17043  #define TF_Ephemeral       0x0002    /* An ephemeral table */
 17044  #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
 17045  #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
 17046  #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
 17047  #define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
 17048  #define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
 17049  #define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
 17050  #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
 17051                                       ** Index.aiRowLogEst[] values */
 17052  #define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
 17053  #define TF_Shadow          0x0400    /* True for a shadow table */
 17054  
 17055  /*
 17056  ** Test to see whether or not a table is a virtual table.  This is
 17057  ** done as a macro so that it will be optimized out when virtual
 17058  ** table support is omitted from the build.
 17059  */
 17060  #ifndef SQLITE_OMIT_VIRTUALTABLE
 17061  #  define IsVirtual(X)      ((X)->nModuleArg)
 17062  #else
 17063  #  define IsVirtual(X)      0
 17064  #endif
 17065  
 17066  /*
 17067  ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
 17068  ** only works for non-virtual tables (ordinary tables and views) and is
 17069  ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
 17070  ** IsHiddenColumn() macro is general purpose.
 17071  */
 17072  #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
 17073  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 17074  #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 17075  #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
 17076  #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
 17077  #  define IsOrdinaryHiddenColumn(X) 0
 17078  #else
 17079  #  define IsHiddenColumn(X)         0
 17080  #  define IsOrdinaryHiddenColumn(X) 0
 17081  #endif
 17082  
 17083  
 17084  /* Does the table have a rowid */
 17085  #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
 17086  #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
 17087  
 17088  /*
 17089  ** Each foreign key constraint is an instance of the following structure.
 17090  **
 17091  ** A foreign key is associated with two tables.  The "from" table is
 17092  ** the table that contains the REFERENCES clause that creates the foreign
 17093  ** key.  The "to" table is the table that is named in the REFERENCES clause.
 17094  ** Consider this example:
 17095  **
 17096  **     CREATE TABLE ex1(
 17097  **       a INTEGER PRIMARY KEY,
 17098  **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
 17099  **     );
 17100  **
 17101  ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
 17102  ** Equivalent names:
 17103  **
 17104  **     from-table == child-table
 17105  **       to-table == parent-table
 17106  **
 17107  ** Each REFERENCES clause generates an instance of the following structure
 17108  ** which is attached to the from-table.  The to-table need not exist when
 17109  ** the from-table is created.  The existence of the to-table is not checked.
 17110  **
 17111  ** The list of all parents for child Table X is held at X.pFKey.
 17112  **
 17113  ** A list of all children for a table named Z (which might not even exist)
 17114  ** is held in Schema.fkeyHash with a hash key of Z.
 17115  */
 17116  struct FKey {
 17117    Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
 17118    FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
 17119    char *zTo;        /* Name of table that the key points to (aka: Parent) */
 17120    FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
 17121    FKey *pPrevTo;    /* Previous with the same zTo */
 17122    int nCol;         /* Number of columns in this key */
 17123    /* EV: R-30323-21917 */
 17124    u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
 17125    u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
 17126    Trigger *apTrigger[2];/* Triggers for aAction[] actions */
 17127    struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
 17128      int iFrom;            /* Index of column in pFrom */
 17129      char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
 17130    } aCol[1];            /* One entry for each of nCol columns */
 17131  };
 17132  
 17133  /*
 17134  ** SQLite supports many different ways to resolve a constraint
 17135  ** error.  ROLLBACK processing means that a constraint violation
 17136  ** causes the operation in process to fail and for the current transaction
 17137  ** to be rolled back.  ABORT processing means the operation in process
 17138  ** fails and any prior changes from that one operation are backed out,
 17139  ** but the transaction is not rolled back.  FAIL processing means that
 17140  ** the operation in progress stops and returns an error code.  But prior
 17141  ** changes due to the same operation are not backed out and no rollback
 17142  ** occurs.  IGNORE means that the particular row that caused the constraint
 17143  ** error is not inserted or updated.  Processing continues and no error
 17144  ** is returned.  REPLACE means that preexisting database rows that caused
 17145  ** a UNIQUE constraint violation are removed so that the new insert or
 17146  ** update can proceed.  Processing continues and no error is reported.
 17147  **
 17148  ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
 17149  ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
 17150  ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
 17151  ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
 17152  ** referenced table row is propagated into the row that holds the
 17153  ** foreign key.
 17154  **
 17155  ** The following symbolic values are used to record which type
 17156  ** of action to take.
 17157  */
 17158  #define OE_None     0   /* There is no constraint to check */
 17159  #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
 17160  #define OE_Abort    2   /* Back out changes but do no rollback transaction */
 17161  #define OE_Fail     3   /* Stop the operation but leave all prior changes */
 17162  #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
 17163  #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
 17164  #define OE_Update   6   /* Process as a DO UPDATE in an upsert */
 17165  #define OE_Restrict 7   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
 17166  #define OE_SetNull  8   /* Set the foreign key value to NULL */
 17167  #define OE_SetDflt  9   /* Set the foreign key value to its default */
 17168  #define OE_Cascade  10  /* Cascade the changes */
 17169  #define OE_Default  11  /* Do whatever the default action is */
 17170  
 17171  
 17172  /*
 17173  ** An instance of the following structure is passed as the first
 17174  ** argument to sqlite3VdbeKeyCompare and is used to control the
 17175  ** comparison of the two index keys.
 17176  **
 17177  ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
 17178  ** are nField slots for the columns of an index then one extra slot
 17179  ** for the rowid at the end.
 17180  */
 17181  struct KeyInfo {
 17182    u32 nRef;           /* Number of references to this KeyInfo object */
 17183    u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
 17184    u16 nKeyField;      /* Number of key columns in the index */
 17185    u16 nAllField;      /* Total columns, including key plus others */
 17186    sqlite3 *db;        /* The database connection */
 17187    u8 *aSortOrder;     /* Sort order for each column. */
 17188    CollSeq *aColl[1];  /* Collating sequence for each term of the key */
 17189  };
 17190  
 17191  /*
 17192  ** This object holds a record which has been parsed out into individual
 17193  ** fields, for the purposes of doing a comparison.
 17194  **
 17195  ** A record is an object that contains one or more fields of data.
 17196  ** Records are used to store the content of a table row and to store
 17197  ** the key of an index.  A blob encoding of a record is created by
 17198  ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
 17199  ** OP_Column opcode.
 17200  **
 17201  ** An instance of this object serves as a "key" for doing a search on
 17202  ** an index b+tree. The goal of the search is to find the entry that
 17203  ** is closed to the key described by this object.  This object might hold
 17204  ** just a prefix of the key.  The number of fields is given by
 17205  ** pKeyInfo->nField.
 17206  **
 17207  ** The r1 and r2 fields are the values to return if this key is less than
 17208  ** or greater than a key in the btree, respectively.  These are normally
 17209  ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
 17210  ** is in DESC order.
 17211  **
 17212  ** The key comparison functions actually return default_rc when they find
 17213  ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
 17214  ** multiple entries in the b-tree with the same key (when only looking
 17215  ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
 17216  ** cause the search to find the last match, or +1 to cause the search to
 17217  ** find the first match.
 17218  **
 17219  ** The key comparison functions will set eqSeen to true if they ever
 17220  ** get and equal results when comparing this structure to a b-tree record.
 17221  ** When default_rc!=0, the search might end up on the record immediately
 17222  ** before the first match or immediately after the last match.  The
 17223  ** eqSeen field will indicate whether or not an exact match exists in the
 17224  ** b-tree.
 17225  */
 17226  struct UnpackedRecord {
 17227    KeyInfo *pKeyInfo;  /* Collation and sort-order information */
 17228    Mem *aMem;          /* Values */
 17229    u16 nField;         /* Number of entries in apMem[] */
 17230    i8 default_rc;      /* Comparison result if keys are equal */
 17231    u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
 17232    i8 r1;              /* Value to return if (lhs < rhs) */
 17233    i8 r2;              /* Value to return if (lhs > rhs) */
 17234    u8 eqSeen;          /* True if an equality comparison has been seen */
 17235  };
 17236  
 17237  
 17238  /*
 17239  ** Each SQL index is represented in memory by an
 17240  ** instance of the following structure.
 17241  **
 17242  ** The columns of the table that are to be indexed are described
 17243  ** by the aiColumn[] field of this structure.  For example, suppose
 17244  ** we have the following table and index:
 17245  **
 17246  **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
 17247  **     CREATE INDEX Ex2 ON Ex1(c3,c1);
 17248  **
 17249  ** In the Table structure describing Ex1, nCol==3 because there are
 17250  ** three columns in the table.  In the Index structure describing
 17251  ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
 17252  ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
 17253  ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
 17254  ** The second column to be indexed (c1) has an index of 0 in
 17255  ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
 17256  **
 17257  ** The Index.onError field determines whether or not the indexed columns
 17258  ** must be unique and what to do if they are not.  When Index.onError=OE_None,
 17259  ** it means this is not a unique index.  Otherwise it is a unique index
 17260  ** and the value of Index.onError indicate the which conflict resolution
 17261  ** algorithm to employ whenever an attempt is made to insert a non-unique
 17262  ** element.
 17263  **
 17264  ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
 17265  ** generate VDBE code (as opposed to parsing one read from an sqlite_master
 17266  ** table as part of parsing an existing database schema), transient instances
 17267  ** of this structure may be created. In this case the Index.tnum variable is
 17268  ** used to store the address of a VDBE instruction, not a database page
 17269  ** number (it cannot - the database page is not allocated until the VDBE
 17270  ** program is executed). See convertToWithoutRowidTable() for details.
 17271  */
 17272  struct Index {
 17273    char *zName;             /* Name of this index */
 17274    i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
 17275    LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
 17276    Table *pTable;           /* The SQL table being indexed */
 17277    char *zColAff;           /* String defining the affinity of each column */
 17278    Index *pNext;            /* The next index associated with the same table */
 17279    Schema *pSchema;         /* Schema containing this index */
 17280    u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
 17281    const char **azColl;     /* Array of collation sequence names for index */
 17282    Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
 17283    ExprList *aColExpr;      /* Column expressions */
 17284    int tnum;                /* DB Page containing root of this index */
 17285    LogEst szIdxRow;         /* Estimated average row size in bytes */
 17286    u16 nKeyCol;             /* Number of columns forming the key */
 17287    u16 nColumn;             /* Number of columns stored in the index */
 17288    u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
 17289    unsigned idxType:2;      /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
 17290    unsigned bUnordered:1;   /* Use this index for == or IN queries only */
 17291    unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
 17292    unsigned isResized:1;    /* True if resizeIndexObject() has been called */
 17293    unsigned isCovering:1;   /* True if this is a covering index */
 17294    unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
 17295    unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
 17296    unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
 17297  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 17298    int nSample;             /* Number of elements in aSample[] */
 17299    int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
 17300    tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
 17301    IndexSample *aSample;    /* Samples of the left-most key */
 17302    tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
 17303    tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
 17304  #endif
 17305    Bitmask colNotIdxed;     /* 0 for unindexed columns in pTab */
 17306  };
 17307  
 17308  /*
 17309  ** Allowed values for Index.idxType
 17310  */
 17311  #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
 17312  #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
 17313  #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
 17314  #define SQLITE_IDXTYPE_IPK         3   /* INTEGER PRIMARY KEY index */
 17315  
 17316  /* Return true if index X is a PRIMARY KEY index */
 17317  #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
 17318  
 17319  /* Return true if index X is a UNIQUE index */
 17320  #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
 17321  
 17322  /* The Index.aiColumn[] values are normally positive integer.  But
 17323  ** there are some negative values that have special meaning:
 17324  */
 17325  #define XN_ROWID     (-1)     /* Indexed column is the rowid */
 17326  #define XN_EXPR      (-2)     /* Indexed column is an expression */
 17327  
 17328  /*
 17329  ** Each sample stored in the sqlite_stat3 table is represented in memory
 17330  ** using a structure of this type.  See documentation at the top of the
 17331  ** analyze.c source file for additional information.
 17332  */
 17333  struct IndexSample {
 17334    void *p;          /* Pointer to sampled record */
 17335    int n;            /* Size of record in bytes */
 17336    tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
 17337    tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
 17338    tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
 17339  };
 17340  
 17341  /*
 17342  ** Possible values to use within the flags argument to sqlite3GetToken().
 17343  */
 17344  #define SQLITE_TOKEN_QUOTED    0x1 /* Token is a quoted identifier. */
 17345  #define SQLITE_TOKEN_KEYWORD   0x2 /* Token is a keyword. */
 17346  
 17347  /*
 17348  ** Each token coming out of the lexer is an instance of
 17349  ** this structure.  Tokens are also used as part of an expression.
 17350  **
 17351  ** The memory that "z" points to is owned by other objects.  Take care
 17352  ** that the owner of the "z" string does not deallocate the string before
 17353  ** the Token goes out of scope!  Very often, the "z" points to some place
 17354  ** in the middle of the Parse.zSql text.  But it might also point to a
 17355  ** static string.
 17356  */
 17357  struct Token {
 17358    const char *z;     /* Text of the token.  Not NULL-terminated! */
 17359    unsigned int n;    /* Number of characters in this token */
 17360  };
 17361  
 17362  /*
 17363  ** An instance of this structure contains information needed to generate
 17364  ** code for a SELECT that contains aggregate functions.
 17365  **
 17366  ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
 17367  ** pointer to this structure.  The Expr.iColumn field is the index in
 17368  ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
 17369  ** code for that node.
 17370  **
 17371  ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
 17372  ** original Select structure that describes the SELECT statement.  These
 17373  ** fields do not need to be freed when deallocating the AggInfo structure.
 17374  */
 17375  struct AggInfo {
 17376    u8 directMode;          /* Direct rendering mode means take data directly
 17377                            ** from source tables rather than from accumulators */
 17378    u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
 17379                            ** than the source table */
 17380    int sortingIdx;         /* Cursor number of the sorting index */
 17381    int sortingIdxPTab;     /* Cursor number of pseudo-table */
 17382    int nSortingColumn;     /* Number of columns in the sorting index */
 17383    int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
 17384    ExprList *pGroupBy;     /* The group by clause */
 17385    struct AggInfo_col {    /* For each column used in source tables */
 17386      Table *pTab;             /* Source table */
 17387      int iTable;              /* Cursor number of the source table */
 17388      int iColumn;             /* Column number within the source table */
 17389      int iSorterColumn;       /* Column number in the sorting index */
 17390      int iMem;                /* Memory location that acts as accumulator */
 17391      Expr *pExpr;             /* The original expression */
 17392    } *aCol;
 17393    int nColumn;            /* Number of used entries in aCol[] */
 17394    int nAccumulator;       /* Number of columns that show through to the output.
 17395                            ** Additional columns are used only as parameters to
 17396                            ** aggregate functions */
 17397    struct AggInfo_func {   /* For each aggregate function */
 17398      Expr *pExpr;             /* Expression encoding the function */
 17399      FuncDef *pFunc;          /* The aggregate function implementation */
 17400      int iMem;                /* Memory location that acts as accumulator */
 17401      int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
 17402    } *aFunc;
 17403    int nFunc;              /* Number of entries in aFunc[] */
 17404  };
 17405  
 17406  /*
 17407  ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
 17408  ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
 17409  ** than 32767 we have to make it 32-bit.  16-bit is preferred because
 17410  ** it uses less memory in the Expr object, which is a big memory user
 17411  ** in systems with lots of prepared statements.  And few applications
 17412  ** need more than about 10 or 20 variables.  But some extreme users want
 17413  ** to have prepared statements with over 32767 variables, and for them
 17414  ** the option is available (at compile-time).
 17415  */
 17416  #if SQLITE_MAX_VARIABLE_NUMBER<=32767
 17417  typedef i16 ynVar;
 17418  #else
 17419  typedef int ynVar;
 17420  #endif
 17421  
 17422  /*
 17423  ** Each node of an expression in the parse tree is an instance
 17424  ** of this structure.
 17425  **
 17426  ** Expr.op is the opcode. The integer parser token codes are reused
 17427  ** as opcodes here. For example, the parser defines TK_GE to be an integer
 17428  ** code representing the ">=" operator. This same integer code is reused
 17429  ** to represent the greater-than-or-equal-to operator in the expression
 17430  ** tree.
 17431  **
 17432  ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
 17433  ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
 17434  ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
 17435  ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
 17436  ** then Expr.token contains the name of the function.
 17437  **
 17438  ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
 17439  ** binary operator. Either or both may be NULL.
 17440  **
 17441  ** Expr.x.pList is a list of arguments if the expression is an SQL function,
 17442  ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
 17443  ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
 17444  ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
 17445  ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
 17446  ** valid.
 17447  **
 17448  ** An expression of the form ID or ID.ID refers to a column in a table.
 17449  ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
 17450  ** the integer cursor number of a VDBE cursor pointing to that table and
 17451  ** Expr.iColumn is the column number for the specific column.  If the
 17452  ** expression is used as a result in an aggregate SELECT, then the
 17453  ** value is also stored in the Expr.iAgg column in the aggregate so that
 17454  ** it can be accessed after all aggregates are computed.
 17455  **
 17456  ** If the expression is an unbound variable marker (a question mark
 17457  ** character '?' in the original SQL) then the Expr.iTable holds the index
 17458  ** number for that variable.
 17459  **
 17460  ** If the expression is a subquery then Expr.iColumn holds an integer
 17461  ** register number containing the result of the subquery.  If the
 17462  ** subquery gives a constant result, then iTable is -1.  If the subquery
 17463  ** gives a different answer at different times during statement processing
 17464  ** then iTable is the address of a subroutine that computes the subquery.
 17465  **
 17466  ** If the Expr is of type OP_Column, and the table it is selecting from
 17467  ** is a disk table or the "old.*" pseudo-table, then pTab points to the
 17468  ** corresponding table definition.
 17469  **
 17470  ** ALLOCATION NOTES:
 17471  **
 17472  ** Expr objects can use a lot of memory space in database schema.  To
 17473  ** help reduce memory requirements, sometimes an Expr object will be
 17474  ** truncated.  And to reduce the number of memory allocations, sometimes
 17475  ** two or more Expr objects will be stored in a single memory allocation,
 17476  ** together with Expr.zToken strings.
 17477  **
 17478  ** If the EP_Reduced and EP_TokenOnly flags are set when
 17479  ** an Expr object is truncated.  When EP_Reduced is set, then all
 17480  ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
 17481  ** are contained within the same memory allocation.  Note, however, that
 17482  ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
 17483  ** allocated, regardless of whether or not EP_Reduced is set.
 17484  */
 17485  struct Expr {
 17486    u8 op;                 /* Operation performed by this node */
 17487    char affinity;         /* The affinity of the column or 0 if not a column */
 17488    u32 flags;             /* Various flags.  EP_* See below */
 17489    union {
 17490      char *zToken;          /* Token value. Zero terminated and dequoted */
 17491      int iValue;            /* Non-negative integer value if EP_IntValue */
 17492    } u;
 17493  
 17494    /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
 17495    ** space is allocated for the fields below this point. An attempt to
 17496    ** access them will result in a segfault or malfunction.
 17497    *********************************************************************/
 17498  
 17499    Expr *pLeft;           /* Left subnode */
 17500    Expr *pRight;          /* Right subnode */
 17501    union {
 17502      ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
 17503      Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
 17504    } x;
 17505  
 17506    /* If the EP_Reduced flag is set in the Expr.flags mask, then no
 17507    ** space is allocated for the fields below this point. An attempt to
 17508    ** access them will result in a segfault or malfunction.
 17509    *********************************************************************/
 17510  
 17511  #if SQLITE_MAX_EXPR_DEPTH>0
 17512    int nHeight;           /* Height of the tree headed by this node */
 17513  #endif
 17514    int iTable;            /* TK_COLUMN: cursor number of table holding column
 17515                           ** TK_REGISTER: register number
 17516                           ** TK_TRIGGER: 1 -> new, 0 -> old
 17517                           ** EP_Unlikely:  134217728 times likelihood
 17518                           ** TK_SELECT: 1st register of result vector */
 17519    ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
 17520                           ** TK_VARIABLE: variable number (always >= 1).
 17521                           ** TK_SELECT_COLUMN: column of the result vector */
 17522    i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
 17523    i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
 17524    u8 op2;                /* TK_REGISTER: original value of Expr.op
 17525                           ** TK_COLUMN: the value of p5 for OP_Column
 17526                           ** TK_AGG_FUNCTION: nesting depth */
 17527    AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
 17528    union {
 17529      Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
 17530                             ** for a column of an index on an expression */
 17531      Window *pWin;          /* TK_FUNCTION: Window definition for the func */
 17532      struct {               /* TK_IN, TK_SELECT, and TK_EXISTS */
 17533        int iAddr;             /* Subroutine entry address */
 17534        int regReturn;         /* Register used to hold return address */
 17535      } sub;
 17536    } y;
 17537  };
 17538  
 17539  /*
 17540  ** The following are the meanings of bits in the Expr.flags field.
 17541  */
 17542  #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
 17543  #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
 17544  #define EP_HasFunc   0x000004 /* Contains one or more functions of any kind */
 17545  #define EP_FixedCol  0x000008 /* TK_Column with a known fixed value */
 17546  #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
 17547  #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
 17548  #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
 17549  #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
 17550  #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
 17551  #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
 17552  #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
 17553  #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
 17554  #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
 17555  #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
 17556  #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
 17557  #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
 17558  #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
 17559  #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
 17560  #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
 17561  #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
 17562  #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
 17563  #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
 17564  #define EP_Alias     0x400000 /* Is an alias for a result set column */
 17565  #define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
 17566  #define EP_WinFunc  0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
 17567  #define EP_Subrtn   0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
 17568  #define EP_Quoted   0x4000000 /* TK_ID was originally quoted */
 17569  
 17570  /*
 17571  ** The EP_Propagate mask is a set of properties that automatically propagate
 17572  ** upwards into parent nodes.
 17573  */
 17574  #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
 17575  
 17576  /*
 17577  ** These macros can be used to test, set, or clear bits in the
 17578  ** Expr.flags field.
 17579  */
 17580  #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
 17581  #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
 17582  #define ExprSetProperty(E,P)     (E)->flags|=(P)
 17583  #define ExprClearProperty(E,P)   (E)->flags&=~(P)
 17584  
 17585  /* The ExprSetVVAProperty() macro is used for Verification, Validation,
 17586  ** and Accreditation only.  It works like ExprSetProperty() during VVA
 17587  ** processes but is a no-op for delivery.
 17588  */
 17589  #ifdef SQLITE_DEBUG
 17590  # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
 17591  #else
 17592  # define ExprSetVVAProperty(E,P)
 17593  #endif
 17594  
 17595  /*
 17596  ** Macros to determine the number of bytes required by a normal Expr
 17597  ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
 17598  ** and an Expr struct with the EP_TokenOnly flag set.
 17599  */
 17600  #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
 17601  #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
 17602  #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
 17603  
 17604  /*
 17605  ** Flags passed to the sqlite3ExprDup() function. See the header comment
 17606  ** above sqlite3ExprDup() for details.
 17607  */
 17608  #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
 17609  
 17610  /*
 17611  ** A list of expressions.  Each expression may optionally have a
 17612  ** name.  An expr/name combination can be used in several ways, such
 17613  ** as the list of "expr AS ID" fields following a "SELECT" or in the
 17614  ** list of "ID = expr" items in an UPDATE.  A list of expressions can
 17615  ** also be used as the argument to a function, in which case the a.zName
 17616  ** field is not used.
 17617  **
 17618  ** By default the Expr.zSpan field holds a human-readable description of
 17619  ** the expression that is used in the generation of error messages and
 17620  ** column labels.  In this case, Expr.zSpan is typically the text of a
 17621  ** column expression as it exists in a SELECT statement.  However, if
 17622  ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
 17623  ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
 17624  ** form is used for name resolution with nested FROM clauses.
 17625  */
 17626  struct ExprList {
 17627    int nExpr;             /* Number of expressions on the list */
 17628    struct ExprList_item { /* For each expression in the list */
 17629      Expr *pExpr;            /* The parse tree for this expression */
 17630      char *zName;            /* Token associated with this expression */
 17631      char *zSpan;            /* Original text of the expression */
 17632      u8 sortOrder;           /* 1 for DESC or 0 for ASC */
 17633      unsigned done :1;       /* A flag to indicate when processing is finished */
 17634      unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
 17635      unsigned reusable :1;   /* Constant expression is reusable */
 17636      unsigned bSorterRef :1; /* Defer evaluation until after sorting */
 17637      union {
 17638        struct {
 17639          u16 iOrderByCol;      /* For ORDER BY, column number in result set */
 17640          u16 iAlias;           /* Index into Parse.aAlias[] for zName */
 17641        } x;
 17642        int iConstExprReg;      /* Register in which Expr value is cached */
 17643      } u;
 17644    } a[1];                  /* One slot for each expression in the list */
 17645  };
 17646  
 17647  /*
 17648  ** An instance of this structure can hold a simple list of identifiers,
 17649  ** such as the list "a,b,c" in the following statements:
 17650  **
 17651  **      INSERT INTO t(a,b,c) VALUES ...;
 17652  **      CREATE INDEX idx ON t(a,b,c);
 17653  **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
 17654  **
 17655  ** The IdList.a.idx field is used when the IdList represents the list of
 17656  ** column names after a table name in an INSERT statement.  In the statement
 17657  **
 17658  **     INSERT INTO t(a,b,c) ...
 17659  **
 17660  ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
 17661  */
 17662  struct IdList {
 17663    struct IdList_item {
 17664      char *zName;      /* Name of the identifier */
 17665      int idx;          /* Index in some Table.aCol[] of a column named zName */
 17666    } *a;
 17667    int nId;         /* Number of identifiers on the list */
 17668  };
 17669  
 17670  /*
 17671  ** The following structure describes the FROM clause of a SELECT statement.
 17672  ** Each table or subquery in the FROM clause is a separate element of
 17673  ** the SrcList.a[] array.
 17674  **
 17675  ** With the addition of multiple database support, the following structure
 17676  ** can also be used to describe a particular table such as the table that
 17677  ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
 17678  ** such a table must be a simple name: ID.  But in SQLite, the table can
 17679  ** now be identified by a database name, a dot, then the table name: ID.ID.
 17680  **
 17681  ** The jointype starts out showing the join type between the current table
 17682  ** and the next table on the list.  The parser builds the list this way.
 17683  ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
 17684  ** jointype expresses the join between the table and the previous table.
 17685  **
 17686  ** In the colUsed field, the high-order bit (bit 63) is set if the table
 17687  ** contains more than 63 columns and the 64-th or later column is used.
 17688  */
 17689  struct SrcList {
 17690    int nSrc;        /* Number of tables or subqueries in the FROM clause */
 17691    u32 nAlloc;      /* Number of entries allocated in a[] below */
 17692    struct SrcList_item {
 17693      Schema *pSchema;  /* Schema to which this item is fixed */
 17694      char *zDatabase;  /* Name of database holding this table */
 17695      char *zName;      /* Name of the table */
 17696      char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
 17697      Table *pTab;      /* An SQL table corresponding to zName */
 17698      Select *pSelect;  /* A SELECT statement used in place of a table name */
 17699      int addrFillSub;  /* Address of subroutine to manifest a subquery */
 17700      int regReturn;    /* Register holding return address of addrFillSub */
 17701      int regResult;    /* Registers holding results of a co-routine */
 17702      struct {
 17703        u8 jointype;      /* Type of join between this table and the previous */
 17704        unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
 17705        unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
 17706        unsigned isTabFunc :1;     /* True if table-valued-function syntax */
 17707        unsigned isCorrelated :1;  /* True if sub-query is correlated */
 17708        unsigned viaCoroutine :1;  /* Implemented as a co-routine */
 17709        unsigned isRecursive :1;   /* True for recursive reference in WITH */
 17710      } fg;
 17711      int iCursor;      /* The VDBE cursor number used to access this table */
 17712      Expr *pOn;        /* The ON clause of a join */
 17713      IdList *pUsing;   /* The USING clause of a join */
 17714      Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
 17715      union {
 17716        char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
 17717        ExprList *pFuncArg;  /* Arguments to table-valued-function */
 17718      } u1;
 17719      Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
 17720    } a[1];             /* One entry for each identifier on the list */
 17721  };
 17722  
 17723  /*
 17724  ** Permitted values of the SrcList.a.jointype field
 17725  */
 17726  #define JT_INNER     0x0001    /* Any kind of inner or cross join */
 17727  #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
 17728  #define JT_NATURAL   0x0004    /* True for a "natural" join */
 17729  #define JT_LEFT      0x0008    /* Left outer join */
 17730  #define JT_RIGHT     0x0010    /* Right outer join */
 17731  #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
 17732  #define JT_ERROR     0x0040    /* unknown or unsupported join type */
 17733  
 17734  
 17735  /*
 17736  ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
 17737  ** and the WhereInfo.wctrlFlags member.
 17738  **
 17739  ** Value constraints (enforced via assert()):
 17740  **     WHERE_USE_LIMIT  == SF_FixedLimit
 17741  */
 17742  #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
 17743  #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
 17744  #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
 17745  #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
 17746  #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
 17747  #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
 17748  #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
 17749                                        ** the OR optimization  */
 17750  #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
 17751  #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
 17752  #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
 17753  #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
 17754  #define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
 17755  #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
 17756  #define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
 17757                          /*     0x2000    not currently used */
 17758  #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
 17759                          /*     0x8000    not currently used */
 17760  
 17761  /* Allowed return values from sqlite3WhereIsDistinct()
 17762  */
 17763  #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
 17764  #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
 17765  #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
 17766  #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
 17767  
 17768  /*
 17769  ** A NameContext defines a context in which to resolve table and column
 17770  ** names.  The context consists of a list of tables (the pSrcList) field and
 17771  ** a list of named expression (pEList).  The named expression list may
 17772  ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
 17773  ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
 17774  ** pEList corresponds to the result set of a SELECT and is NULL for
 17775  ** other statements.
 17776  **
 17777  ** NameContexts can be nested.  When resolving names, the inner-most
 17778  ** context is searched first.  If no match is found, the next outer
 17779  ** context is checked.  If there is still no match, the next context
 17780  ** is checked.  This process continues until either a match is found
 17781  ** or all contexts are check.  When a match is found, the nRef member of
 17782  ** the context containing the match is incremented.
 17783  **
 17784  ** Each subquery gets a new NameContext.  The pNext field points to the
 17785  ** NameContext in the parent query.  Thus the process of scanning the
 17786  ** NameContext list corresponds to searching through successively outer
 17787  ** subqueries looking for a match.
 17788  */
 17789  struct NameContext {
 17790    Parse *pParse;       /* The parser */
 17791    SrcList *pSrcList;   /* One or more tables used to resolve names */
 17792    union {
 17793      ExprList *pEList;    /* Optional list of result-set columns */
 17794      AggInfo *pAggInfo;   /* Information about aggregates at this level */
 17795      Upsert *pUpsert;     /* ON CONFLICT clause information from an upsert */
 17796    } uNC;
 17797    NameContext *pNext;  /* Next outer name context.  NULL for outermost */
 17798    int nRef;            /* Number of names resolved by this context */
 17799    int nErr;            /* Number of errors encountered while resolving names */
 17800    u16 ncFlags;         /* Zero or more NC_* flags defined below */
 17801    Select *pWinSelect;  /* SELECT statement for any window functions */
 17802  };
 17803  
 17804  /*
 17805  ** Allowed values for the NameContext, ncFlags field.
 17806  **
 17807  ** Value constraints (all checked via assert()):
 17808  **    NC_HasAgg    == SF_HasAgg
 17809  **    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
 17810  **
 17811  */
 17812  #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
 17813  #define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
 17814  #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
 17815  #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
 17816  #define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
 17817  #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
 17818  #define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
 17819  #define NC_UEList    0x0080  /* True if uNC.pEList is used */
 17820  #define NC_UAggInfo  0x0100  /* True if uNC.pAggInfo is used */
 17821  #define NC_UUpsert   0x0200  /* True if uNC.pUpsert is used */
 17822  #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
 17823  #define NC_Complex   0x2000  /* True if a function or subquery seen */
 17824  #define NC_AllowWin  0x4000  /* Window functions are allowed here */
 17825  
 17826  /*
 17827  ** An instance of the following object describes a single ON CONFLICT
 17828  ** clause in an upsert.
 17829  **
 17830  ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
 17831  ** conflict-target clause.  (In "ON CONFLICT(a,b)" the "(a,b)" is the
 17832  ** conflict-target clause.)  The pUpsertTargetWhere is the optional
 17833  ** WHERE clause used to identify partial unique indexes.
 17834  **
 17835  ** pUpsertSet is the list of column=expr terms of the UPDATE statement. 
 17836  ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The
 17837  ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
 17838  ** WHERE clause is omitted.
 17839  */
 17840  struct Upsert {
 17841    ExprList *pUpsertTarget;  /* Optional description of conflicting index */
 17842    Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
 17843    ExprList *pUpsertSet;     /* The SET clause from an ON CONFLICT UPDATE */
 17844    Expr *pUpsertWhere;       /* WHERE clause for the ON CONFLICT UPDATE */
 17845    /* The fields above comprise the parse tree for the upsert clause.
 17846    ** The fields below are used to transfer information from the INSERT
 17847    ** processing down into the UPDATE processing while generating code.
 17848    ** Upsert owns the memory allocated above, but not the memory below. */
 17849    Index *pUpsertIdx;        /* Constraint that pUpsertTarget identifies */
 17850    SrcList *pUpsertSrc;      /* Table to be updated */
 17851    int regData;              /* First register holding array of VALUES */
 17852    int iDataCur;             /* Index of the data cursor */
 17853    int iIdxCur;              /* Index of the first index cursor */
 17854  };
 17855  
 17856  /*
 17857  ** An instance of the following structure contains all information
 17858  ** needed to generate code for a single SELECT statement.
 17859  **
 17860  ** See the header comment on the computeLimitRegisters() routine for a
 17861  ** detailed description of the meaning of the iLimit and iOffset fields.
 17862  **
 17863  ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
 17864  ** These addresses must be stored so that we can go back and fill in
 17865  ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
 17866  ** the number of columns in P2 can be computed at the same time
 17867  ** as the OP_OpenEphm instruction is coded because not
 17868  ** enough information about the compound query is known at that point.
 17869  ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
 17870  ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
 17871  ** sequences for the ORDER BY clause.
 17872  */
 17873  struct Select {
 17874    ExprList *pEList;      /* The fields of the result */
 17875    u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
 17876    LogEst nSelectRow;     /* Estimated number of result rows */
 17877    u32 selFlags;          /* Various SF_* values */
 17878    int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
 17879    u32 selId;             /* Unique identifier number for this SELECT */
 17880    int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
 17881    SrcList *pSrc;         /* The FROM clause */
 17882    Expr *pWhere;          /* The WHERE clause */
 17883    ExprList *pGroupBy;    /* The GROUP BY clause */
 17884    Expr *pHaving;         /* The HAVING clause */
 17885    ExprList *pOrderBy;    /* The ORDER BY clause */
 17886    Select *pPrior;        /* Prior select in a compound select statement */
 17887    Select *pNext;         /* Next select to the left in a compound */
 17888    Expr *pLimit;          /* LIMIT expression. NULL means not used. */
 17889    With *pWith;           /* WITH clause attached to this select. Or NULL. */
 17890  #ifndef SQLITE_OMIT_WINDOWFUNC
 17891    Window *pWin;          /* List of window functions */
 17892    Window *pWinDefn;      /* List of named window definitions */
 17893  #endif
 17894  };
 17895  
 17896  /*
 17897  ** Allowed values for Select.selFlags.  The "SF" prefix stands for
 17898  ** "Select Flag".
 17899  **
 17900  ** Value constraints (all checked via assert())
 17901  **     SF_HasAgg     == NC_HasAgg
 17902  **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
 17903  **     SF_FixedLimit == WHERE_USE_LIMIT
 17904  */
 17905  #define SF_Distinct       0x00001  /* Output should be DISTINCT */
 17906  #define SF_All            0x00002  /* Includes the ALL keyword */
 17907  #define SF_Resolved       0x00004  /* Identifiers have been resolved */
 17908  #define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
 17909  #define SF_HasAgg         0x00010  /* Contains aggregate functions */
 17910  #define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
 17911  #define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
 17912  #define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
 17913  #define SF_Compound       0x00100  /* Part of a compound query */
 17914  #define SF_Values         0x00200  /* Synthesized from VALUES clause */
 17915  #define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
 17916  #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
 17917  #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
 17918  #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
 17919  #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
 17920  #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
 17921  #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
 17922  #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
 17923  #define SF_ComplexResult  0x40000  /* Result contains subquery or function */
 17924  
 17925  /*
 17926  ** The results of a SELECT can be distributed in several ways, as defined
 17927  ** by one of the following macros.  The "SRT" prefix means "SELECT Result
 17928  ** Type".
 17929  **
 17930  **     SRT_Union       Store results as a key in a temporary index
 17931  **                     identified by pDest->iSDParm.
 17932  **
 17933  **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
 17934  **
 17935  **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
 17936  **                     set is not empty.
 17937  **
 17938  **     SRT_Discard     Throw the results away.  This is used by SELECT
 17939  **                     statements within triggers whose only purpose is
 17940  **                     the side-effects of functions.
 17941  **
 17942  ** All of the above are free to ignore their ORDER BY clause. Those that
 17943  ** follow must honor the ORDER BY clause.
 17944  **
 17945  **     SRT_Output      Generate a row of output (using the OP_ResultRow
 17946  **                     opcode) for each row in the result set.
 17947  **
 17948  **     SRT_Mem         Only valid if the result is a single column.
 17949  **                     Store the first column of the first result row
 17950  **                     in register pDest->iSDParm then abandon the rest
 17951  **                     of the query.  This destination implies "LIMIT 1".
 17952  **
 17953  **     SRT_Set         The result must be a single column.  Store each
 17954  **                     row of result as the key in table pDest->iSDParm.
 17955  **                     Apply the affinity pDest->affSdst before storing
 17956  **                     results.  Used to implement "IN (SELECT ...)".
 17957  **
 17958  **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
 17959  **                     the result there. The cursor is left open after
 17960  **                     returning.  This is like SRT_Table except that
 17961  **                     this destination uses OP_OpenEphemeral to create
 17962  **                     the table first.
 17963  **
 17964  **     SRT_Coroutine   Generate a co-routine that returns a new row of
 17965  **                     results each time it is invoked.  The entry point
 17966  **                     of the co-routine is stored in register pDest->iSDParm
 17967  **                     and the result row is stored in pDest->nDest registers
 17968  **                     starting with pDest->iSdst.
 17969  **
 17970  **     SRT_Table       Store results in temporary table pDest->iSDParm.
 17971  **     SRT_Fifo        This is like SRT_EphemTab except that the table
 17972  **                     is assumed to already be open.  SRT_Fifo has
 17973  **                     the additional property of being able to ignore
 17974  **                     the ORDER BY clause.
 17975  **
 17976  **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
 17977  **                     But also use temporary table pDest->iSDParm+1 as
 17978  **                     a record of all prior results and ignore any duplicate
 17979  **                     rows.  Name means:  "Distinct Fifo".
 17980  **
 17981  **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
 17982  **                     an index).  Append a sequence number so that all entries
 17983  **                     are distinct.
 17984  **
 17985  **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
 17986  **                     the same record has never been stored before.  The
 17987  **                     index at pDest->iSDParm+1 hold all prior stores.
 17988  */
 17989  #define SRT_Union        1  /* Store result as keys in an index */
 17990  #define SRT_Except       2  /* Remove result from a UNION index */
 17991  #define SRT_Exists       3  /* Store 1 if the result is not empty */
 17992  #define SRT_Discard      4  /* Do not save the results anywhere */
 17993  #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
 17994  #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
 17995  #define SRT_Queue        7  /* Store result in an queue */
 17996  #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
 17997  
 17998  /* The ORDER BY clause is ignored for all of the above */
 17999  #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
 18000  
 18001  #define SRT_Output       9  /* Output each row of result */
 18002  #define SRT_Mem         10  /* Store result in a memory cell */
 18003  #define SRT_Set         11  /* Store results as keys in an index */
 18004  #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
 18005  #define SRT_Coroutine   13  /* Generate a single row of result */
 18006  #define SRT_Table       14  /* Store result as data with an automatic rowid */
 18007  
 18008  /*
 18009  ** An instance of this object describes where to put of the results of
 18010  ** a SELECT statement.
 18011  */
 18012  struct SelectDest {
 18013    u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
 18014    int iSDParm;         /* A parameter used by the eDest disposal method */
 18015    int iSdst;           /* Base register where results are written */
 18016    int nSdst;           /* Number of registers allocated */
 18017    char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
 18018    ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
 18019  };
 18020  
 18021  /*
 18022  ** During code generation of statements that do inserts into AUTOINCREMENT
 18023  ** tables, the following information is attached to the Table.u.autoInc.p
 18024  ** pointer of each autoincrement table to record some side information that
 18025  ** the code generator needs.  We have to keep per-table autoincrement
 18026  ** information in case inserts are done within triggers.  Triggers do not
 18027  ** normally coordinate their activities, but we do need to coordinate the
 18028  ** loading and saving of autoincrement information.
 18029  */
 18030  struct AutoincInfo {
 18031    AutoincInfo *pNext;   /* Next info block in a list of them all */
 18032    Table *pTab;          /* Table this info block refers to */
 18033    int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
 18034    int regCtr;           /* Memory register holding the rowid counter */
 18035  };
 18036  
 18037  /*
 18038  ** At least one instance of the following structure is created for each
 18039  ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
 18040  ** statement. All such objects are stored in the linked list headed at
 18041  ** Parse.pTriggerPrg and deleted once statement compilation has been
 18042  ** completed.
 18043  **
 18044  ** A Vdbe sub-program that implements the body and WHEN clause of trigger
 18045  ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
 18046  ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
 18047  ** The Parse.pTriggerPrg list never contains two entries with the same
 18048  ** values for both pTrigger and orconf.
 18049  **
 18050  ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
 18051  ** accessed (or set to 0 for triggers fired as a result of INSERT
 18052  ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
 18053  ** a mask of new.* columns used by the program.
 18054  */
 18055  struct TriggerPrg {
 18056    Trigger *pTrigger;      /* Trigger this program was coded from */
 18057    TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
 18058    SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
 18059    int orconf;             /* Default ON CONFLICT policy */
 18060    u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
 18061  };
 18062  
 18063  /*
 18064  ** The yDbMask datatype for the bitmask of all attached databases.
 18065  */
 18066  #if SQLITE_MAX_ATTACHED>30
 18067    typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
 18068  # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
 18069  # define DbMaskZero(M)      memset((M),0,sizeof(M))
 18070  # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
 18071  # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
 18072  # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
 18073  #else
 18074    typedef unsigned int yDbMask;
 18075  # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
 18076  # define DbMaskZero(M)      (M)=0
 18077  # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
 18078  # define DbMaskAllZero(M)   (M)==0
 18079  # define DbMaskNonZero(M)   (M)!=0
 18080  #endif
 18081  
 18082  /*
 18083  ** An SQL parser context.  A copy of this structure is passed through
 18084  ** the parser and down into all the parser action routine in order to
 18085  ** carry around information that is global to the entire parse.
 18086  **
 18087  ** The structure is divided into two parts.  When the parser and code
 18088  ** generate call themselves recursively, the first part of the structure
 18089  ** is constant but the second part is reset at the beginning and end of
 18090  ** each recursion.
 18091  **
 18092  ** The nTableLock and aTableLock variables are only used if the shared-cache
 18093  ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
 18094  ** used to store the set of table-locks required by the statement being
 18095  ** compiled. Function sqlite3TableLock() is used to add entries to the
 18096  ** list.
 18097  */
 18098  struct Parse {
 18099    sqlite3 *db;         /* The main database structure */
 18100    char *zErrMsg;       /* An error message */
 18101    Vdbe *pVdbe;         /* An engine for executing database bytecode */
 18102    int rc;              /* Return code from execution */
 18103    u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
 18104    u8 checkSchema;      /* Causes schema cookie check after an error */
 18105    u8 nested;           /* Number of nested calls to the parser/code generator */
 18106    u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
 18107    u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
 18108    u8 mayAbort;         /* True if statement may throw an ABORT exception */
 18109    u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
 18110    u8 okConstFactor;    /* OK to factor out constants */
 18111    u8 disableLookaside; /* Number of times lookaside has been disabled */
 18112    u8 disableVtab;      /* Disable all virtual tables for this parse */
 18113    int nRangeReg;       /* Size of the temporary register block */
 18114    int iRangeReg;       /* First register in temporary register block */
 18115    int nErr;            /* Number of errors seen */
 18116    int nTab;            /* Number of previously allocated VDBE cursors */
 18117    int nMem;            /* Number of memory cells used so far */
 18118    int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
 18119    int iSelfTab;        /* Table associated with an index on expr, or negative
 18120                         ** of the base register during check-constraint eval */
 18121    int nLabel;          /* The *negative* of the number of labels used */
 18122    int nLabelAlloc;     /* Number of slots in aLabel */
 18123    int *aLabel;         /* Space to hold the labels */
 18124    ExprList *pConstExpr;/* Constant expressions */
 18125    Token constraintName;/* Name of the constraint currently being parsed */
 18126    yDbMask writeMask;   /* Start a write transaction on these databases */
 18127    yDbMask cookieMask;  /* Bitmask of schema verified databases */
 18128    int regRowid;        /* Register holding rowid of CREATE TABLE entry */
 18129    int regRoot;         /* Register holding root page number for new objects */
 18130    int nMaxArg;         /* Max args passed to user function by sub-program */
 18131    int nSelect;         /* Number of SELECT stmts. Counter for Select.selId */
 18132  #ifndef SQLITE_OMIT_SHARED_CACHE
 18133    int nTableLock;        /* Number of locks in aTableLock */
 18134    TableLock *aTableLock; /* Required table locks for shared-cache mode */
 18135  #endif
 18136    AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
 18137    Parse *pToplevel;    /* Parse structure for main program (or NULL) */
 18138    Table *pTriggerTab;  /* Table triggers are being coded for */
 18139    int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
 18140    u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
 18141    u32 oldmask;         /* Mask of old.* columns referenced */
 18142    u32 newmask;         /* Mask of new.* columns referenced */
 18143    u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
 18144    u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
 18145    u8 disableTriggers;  /* True to disable triggers */
 18146  
 18147    /**************************************************************************
 18148    ** Fields above must be initialized to zero.  The fields that follow,
 18149    ** down to the beginning of the recursive section, do not need to be
 18150    ** initialized as they will be set before being used.  The boundary is
 18151    ** determined by offsetof(Parse,aTempReg).
 18152    **************************************************************************/
 18153  
 18154    int aTempReg[8];        /* Holding area for temporary registers */
 18155    Token sNameToken;       /* Token with unqualified schema object name */
 18156  
 18157    /************************************************************************
 18158    ** Above is constant between recursions.  Below is reset before and after
 18159    ** each recursion.  The boundary between these two regions is determined
 18160    ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
 18161    ** first field in the recursive region.
 18162    ************************************************************************/
 18163  
 18164    Token sLastToken;       /* The last token parsed */
 18165    ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
 18166    u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
 18167    u8 explain;               /* True if the EXPLAIN flag is found on the query */
 18168  #if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
 18169    u8 eParseMode;            /* PARSE_MODE_XXX constant */
 18170  #endif
 18171  #ifndef SQLITE_OMIT_VIRTUALTABLE
 18172    int nVtabLock;            /* Number of virtual tables to lock */
 18173  #endif
 18174    int nHeight;              /* Expression tree height of current sub-select */
 18175  #ifndef SQLITE_OMIT_EXPLAIN
 18176    int addrExplain;          /* Address of current OP_Explain opcode */
 18177  #endif
 18178    VList *pVList;            /* Mapping between variable names and numbers */
 18179    Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
 18180    const char *zTail;        /* All SQL text past the last semicolon parsed */
 18181    Table *pNewTable;         /* A table being constructed by CREATE TABLE */
 18182    Index *pNewIndex;         /* An index being constructed by CREATE INDEX.
 18183                              ** Also used to hold redundant UNIQUE constraints
 18184                              ** during a RENAME COLUMN */
 18185    Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
 18186    const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
 18187  #ifndef SQLITE_OMIT_VIRTUALTABLE
 18188    Token sArg;               /* Complete text of a module argument */
 18189    Table **apVtabLock;       /* Pointer to virtual tables needing locking */
 18190  #endif
 18191    Table *pZombieTab;        /* List of Table objects to delete after code gen */
 18192    TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
 18193    With *pWith;              /* Current WITH clause, or NULL */
 18194    With *pWithToFree;        /* Free this WITH object at the end of the parse */
 18195  #ifndef SQLITE_OMIT_ALTERTABLE
 18196    RenameToken *pRename;     /* Tokens subject to renaming by ALTER TABLE */
 18197  #endif
 18198  };
 18199  
 18200  #define PARSE_MODE_NORMAL        0
 18201  #define PARSE_MODE_DECLARE_VTAB  1
 18202  #define PARSE_MODE_RENAME_COLUMN 2
 18203  #define PARSE_MODE_RENAME_TABLE  3
 18204  
 18205  /*
 18206  ** Sizes and pointers of various parts of the Parse object.
 18207  */
 18208  #define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
 18209  #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
 18210  #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
 18211  #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
 18212  
 18213  /*
 18214  ** Return true if currently inside an sqlite3_declare_vtab() call.
 18215  */
 18216  #ifdef SQLITE_OMIT_VIRTUALTABLE
 18217    #define IN_DECLARE_VTAB 0
 18218  #else
 18219    #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
 18220  #endif
 18221  
 18222  #if defined(SQLITE_OMIT_ALTERTABLE)
 18223    #define IN_RENAME_OBJECT 0
 18224  #else
 18225    #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
 18226  #endif
 18227  
 18228  #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
 18229    #define IN_SPECIAL_PARSE 0
 18230  #else
 18231    #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
 18232  #endif
 18233  
 18234  /*
 18235  ** An instance of the following structure can be declared on a stack and used
 18236  ** to save the Parse.zAuthContext value so that it can be restored later.
 18237  */
 18238  struct AuthContext {
 18239    const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
 18240    Parse *pParse;              /* The Parse structure */
 18241  };
 18242  
 18243  /*
 18244  ** Bitfield flags for P5 value in various opcodes.
 18245  **
 18246  ** Value constraints (enforced via assert()):
 18247  **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
 18248  **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
 18249  **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
 18250  **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
 18251  **    OPFLAG_FORDELETE    == BTREE_FORDELETE
 18252  **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
 18253  **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
 18254  */
 18255  #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
 18256                                       /* Also used in P2 (not P5) of OP_Delete */
 18257  #define OPFLAG_NOCHNG        0x01    /* OP_VColumn nochange for UPDATE */
 18258  #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
 18259  #define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
 18260  #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
 18261  #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
 18262  #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
 18263  #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
 18264  #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
 18265  #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
 18266  #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
 18267  #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
 18268  #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
 18269  #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
 18270  #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
 18271  #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
 18272  #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
 18273  #define OPFLAG_NOCHNG_MAGIC  0x6d    /* OP_MakeRecord: serialtype 10 is ok */
 18274  
 18275  /*
 18276   * Each trigger present in the database schema is stored as an instance of
 18277   * struct Trigger.
 18278   *
 18279   * Pointers to instances of struct Trigger are stored in two ways.
 18280   * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
 18281   *    database). This allows Trigger structures to be retrieved by name.
 18282   * 2. All triggers associated with a single table form a linked list, using the
 18283   *    pNext member of struct Trigger. A pointer to the first element of the
 18284   *    linked list is stored as the "pTrigger" member of the associated
 18285   *    struct Table.
 18286   *
 18287   * The "step_list" member points to the first element of a linked list
 18288   * containing the SQL statements specified as the trigger program.
 18289   */
 18290  struct Trigger {
 18291    char *zName;            /* The name of the trigger                        */
 18292    char *table;            /* The table or view to which the trigger applies */
 18293    u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
 18294    u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
 18295    Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
 18296    IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
 18297                               the <column-list> is stored here */
 18298    Schema *pSchema;        /* Schema containing the trigger */
 18299    Schema *pTabSchema;     /* Schema containing the table */
 18300    TriggerStep *step_list; /* Link list of trigger program steps             */
 18301    Trigger *pNext;         /* Next trigger associated with the table */
 18302  };
 18303  
 18304  /*
 18305  ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
 18306  ** determine which.
 18307  **
 18308  ** If there are multiple triggers, you might of some BEFORE and some AFTER.
 18309  ** In that cases, the constants below can be ORed together.
 18310  */
 18311  #define TRIGGER_BEFORE  1
 18312  #define TRIGGER_AFTER   2
 18313  
 18314  /*
 18315   * An instance of struct TriggerStep is used to store a single SQL statement
 18316   * that is a part of a trigger-program.
 18317   *
 18318   * Instances of struct TriggerStep are stored in a singly linked list (linked
 18319   * using the "pNext" member) referenced by the "step_list" member of the
 18320   * associated struct Trigger instance. The first element of the linked list is
 18321   * the first step of the trigger-program.
 18322   *
 18323   * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
 18324   * "SELECT" statement. The meanings of the other members is determined by the
 18325   * value of "op" as follows:
 18326   *
 18327   * (op == TK_INSERT)
 18328   * orconf    -> stores the ON CONFLICT algorithm
 18329   * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
 18330   *              this stores a pointer to the SELECT statement. Otherwise NULL.
 18331   * zTarget   -> Dequoted name of the table to insert into.
 18332   * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
 18333   *              this stores values to be inserted. Otherwise NULL.
 18334   * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
 18335   *              statement, then this stores the column-names to be
 18336   *              inserted into.
 18337   *
 18338   * (op == TK_DELETE)
 18339   * zTarget   -> Dequoted name of the table to delete from.
 18340   * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
 18341   *              Otherwise NULL.
 18342   *
 18343   * (op == TK_UPDATE)
 18344   * zTarget   -> Dequoted name of the table to update.
 18345   * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
 18346   *              Otherwise NULL.
 18347   * pExprList -> A list of the columns to update and the expressions to update
 18348   *              them to. See sqlite3Update() documentation of "pChanges"
 18349   *              argument.
 18350   *
 18351   */
 18352  struct TriggerStep {
 18353    u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
 18354    u8 orconf;           /* OE_Rollback etc. */
 18355    Trigger *pTrig;      /* The trigger that this step is a part of */
 18356    Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
 18357    char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
 18358    Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
 18359    ExprList *pExprList; /* SET clause for UPDATE */
 18360    IdList *pIdList;     /* Column names for INSERT */
 18361    Upsert *pUpsert;     /* Upsert clauses on an INSERT */
 18362    char *zSpan;         /* Original SQL text of this command */
 18363    TriggerStep *pNext;  /* Next in the link-list */
 18364    TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
 18365  };
 18366  
 18367  /*
 18368  ** The following structure contains information used by the sqliteFix...
 18369  ** routines as they walk the parse tree to make database references
 18370  ** explicit.
 18371  */
 18372  typedef struct DbFixer DbFixer;
 18373  struct DbFixer {
 18374    Parse *pParse;      /* The parsing context.  Error messages written here */
 18375    Schema *pSchema;    /* Fix items to this schema */
 18376    int bVarOnly;       /* Check for variable references only */
 18377    const char *zDb;    /* Make sure all objects are contained in this database */
 18378    const char *zType;  /* Type of the container - used for error messages */
 18379    const Token *pName; /* Name of the container - used for error messages */
 18380  };
 18381  
 18382  /*
 18383  ** An objected used to accumulate the text of a string where we
 18384  ** do not necessarily know how big the string will be in the end.
 18385  */
 18386  struct sqlite3_str {
 18387    sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
 18388    char *zText;         /* The string collected so far */
 18389    u32  nAlloc;         /* Amount of space allocated in zText */
 18390    u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
 18391    u32  nChar;          /* Length of the string so far */
 18392    u8   accError;       /* SQLITE_NOMEM or SQLITE_TOOBIG */
 18393    u8   printfFlags;    /* SQLITE_PRINTF flags below */
 18394  };
 18395  #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
 18396  #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
 18397  #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
 18398  
 18399  #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
 18400  
 18401  
 18402  /*
 18403  ** A pointer to this structure is used to communicate information
 18404  ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
 18405  */
 18406  typedef struct {
 18407    sqlite3 *db;        /* The database being initialized */
 18408    char **pzErrMsg;    /* Error message stored here */
 18409    int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
 18410    int rc;             /* Result code stored here */
 18411    u32 mInitFlags;     /* Flags controlling error messages */
 18412    u32 nInitRow;       /* Number of rows processed */
 18413  } InitData;
 18414  
 18415  /*
 18416  ** Allowed values for mInitFlags
 18417  */
 18418  #define INITFLAG_AlterTable   0x0001  /* This is a reparse after ALTER TABLE */
 18419  
 18420  /*
 18421  ** Structure containing global configuration data for the SQLite library.
 18422  **
 18423  ** This structure also contains some state information.
 18424  */
 18425  struct Sqlite3Config {
 18426    int bMemstat;                     /* True to enable memory status */
 18427    int bCoreMutex;                   /* True to enable core mutexing */
 18428    int bFullMutex;                   /* True to enable full mutexing */
 18429    int bOpenUri;                     /* True to interpret filenames as URIs */
 18430    int bUseCis;                      /* Use covering indices for full-scans */
 18431    int bSmallMalloc;                 /* Avoid large memory allocations if true */
 18432    int mxStrlen;                     /* Maximum string length */
 18433    int neverCorrupt;                 /* Database is always well-formed */
 18434    int szLookaside;                  /* Default lookaside buffer size */
 18435    int nLookaside;                   /* Default lookaside buffer count */
 18436    int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
 18437    sqlite3_mem_methods m;            /* Low-level memory allocation interface */
 18438    sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
 18439    sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
 18440    void *pHeap;                      /* Heap storage space */
 18441    int nHeap;                        /* Size of pHeap[] */
 18442    int mnReq, mxReq;                 /* Min and max heap requests sizes */
 18443    sqlite3_int64 szMmap;             /* mmap() space per open file */
 18444    sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
 18445    void *pPage;                      /* Page cache memory */
 18446    int szPage;                       /* Size of each page in pPage[] */
 18447    int nPage;                        /* Number of pages in pPage[] */
 18448    int mxParserStack;                /* maximum depth of the parser stack */
 18449    int sharedCacheEnabled;           /* true if shared-cache mode enabled */
 18450    u32 szPma;                        /* Maximum Sorter PMA size */
 18451    /* The above might be initialized to non-zero.  The following need to always
 18452    ** initially be zero, however. */
 18453    int isInit;                       /* True after initialization has finished */
 18454    int inProgress;                   /* True while initialization in progress */
 18455    int isMutexInit;                  /* True after mutexes are initialized */
 18456    int isMallocInit;                 /* True after malloc is initialized */
 18457    int isPCacheInit;                 /* True after malloc is initialized */
 18458    int nRefInitMutex;                /* Number of users of pInitMutex */
 18459    sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
 18460    void (*xLog)(void*,int,const char*); /* Function for logging */
 18461    void *pLogArg;                       /* First argument to xLog() */
 18462  #ifdef SQLITE_ENABLE_SQLLOG
 18463    void(*xSqllog)(void*,sqlite3*,const char*, int);
 18464    void *pSqllogArg;
 18465  #endif
 18466  #ifdef SQLITE_VDBE_COVERAGE
 18467    /* The following callback (if not NULL) is invoked on every VDBE branch
 18468    ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
 18469    */
 18470    void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx);  /* Callback */
 18471    void *pVdbeBranchArg;                                     /* 1st argument */
 18472  #endif
 18473  #ifdef SQLITE_ENABLE_DESERIALIZE
 18474    sqlite3_int64 mxMemdbSize;        /* Default max memdb size */
 18475  #endif
 18476  #ifndef SQLITE_UNTESTABLE
 18477    int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
 18478  #endif
 18479    int bLocaltimeFault;              /* True to fail localtime() calls */
 18480    int bInternalFunctions;           /* Internal SQL functions are visible */
 18481    int iOnceResetThreshold;          /* When to reset OP_Once counters */
 18482    u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
 18483  };
 18484  
 18485  /*
 18486  ** This macro is used inside of assert() statements to indicate that
 18487  ** the assert is only valid on a well-formed database.  Instead of:
 18488  **
 18489  **     assert( X );
 18490  **
 18491  ** One writes:
 18492  **
 18493  **     assert( X || CORRUPT_DB );
 18494  **
 18495  ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
 18496  ** that the database is definitely corrupt, only that it might be corrupt.
 18497  ** For most test cases, CORRUPT_DB is set to false using a special
 18498  ** sqlite3_test_control().  This enables assert() statements to prove
 18499  ** things that are always true for well-formed databases.
 18500  */
 18501  #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
 18502  
 18503  /*
 18504  ** Context pointer passed down through the tree-walk.
 18505  */
 18506  struct Walker {
 18507    Parse *pParse;                            /* Parser context.  */
 18508    int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
 18509    int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
 18510    void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
 18511    int walkerDepth;                          /* Number of subqueries */
 18512    u8 eCode;                                 /* A small processing code */
 18513    union {                                   /* Extra data for callback */
 18514      NameContext *pNC;                         /* Naming context */
 18515      int n;                                    /* A counter */
 18516      int iCur;                                 /* A cursor number */
 18517      SrcList *pSrcList;                        /* FROM clause */
 18518      struct SrcCount *pSrcCount;               /* Counting column references */
 18519      struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
 18520      int *aiCol;                               /* array of column indexes */
 18521      struct IdxCover *pIdxCover;               /* Check for index coverage */
 18522      struct IdxExprTrans *pIdxTrans;           /* Convert idxed expr to column */
 18523      ExprList *pGroupBy;                       /* GROUP BY clause */
 18524      Select *pSelect;                          /* HAVING to WHERE clause ctx */
 18525      struct WindowRewrite *pRewrite;           /* Window rewrite context */
 18526      struct WhereConst *pConst;                /* WHERE clause constants */
 18527      struct RenameCtx *pRename;                /* RENAME COLUMN context */
 18528    } u;
 18529  };
 18530  
 18531  /* Forward declarations */
 18532  SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
 18533  SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
 18534  SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
 18535  SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
 18536  SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
 18537  SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
 18538  SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
 18539  SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
 18540  #ifdef SQLITE_DEBUG
 18541  SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
 18542  #endif
 18543  
 18544  /*
 18545  ** Return code from the parse-tree walking primitives and their
 18546  ** callbacks.
 18547  */
 18548  #define WRC_Continue    0   /* Continue down into children */
 18549  #define WRC_Prune       1   /* Omit children but continue walking siblings */
 18550  #define WRC_Abort       2   /* Abandon the tree walk */
 18551  
 18552  /*
 18553  ** An instance of this structure represents a set of one or more CTEs
 18554  ** (common table expressions) created by a single WITH clause.
 18555  */
 18556  struct With {
 18557    int nCte;                       /* Number of CTEs in the WITH clause */
 18558    With *pOuter;                   /* Containing WITH clause, or NULL */
 18559    struct Cte {                    /* For each CTE in the WITH clause.... */
 18560      char *zName;                    /* Name of this CTE */
 18561      ExprList *pCols;                /* List of explicit column names, or NULL */
 18562      Select *pSelect;                /* The definition of this CTE */
 18563      const char *zCteErr;            /* Error message for circular references */
 18564    } a[1];
 18565  };
 18566  
 18567  #ifdef SQLITE_DEBUG
 18568  /*
 18569  ** An instance of the TreeView object is used for printing the content of
 18570  ** data structures on sqlite3DebugPrintf() using a tree-like view.
 18571  */
 18572  struct TreeView {
 18573    int iLevel;             /* Which level of the tree we are on */
 18574    u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
 18575  };
 18576  #endif /* SQLITE_DEBUG */
 18577  
 18578  /*
 18579  ** This object is used in varioius ways, all related to window functions
 18580  **
 18581  **   (1) A single instance of this structure is attached to the
 18582  **       the Expr.pWin field for each window function in an expression tree.
 18583  **       This object holds the information contained in the OVER clause,
 18584  **       plus additional fields used during code generation.
 18585  **
 18586  **   (2) All window functions in a single SELECT form a linked-list
 18587  **       attached to Select.pWin.  The Window.pFunc and Window.pExpr
 18588  **       fields point back to the expression that is the window function.
 18589  **
 18590  **   (3) The terms of the WINDOW clause of a SELECT are instances of this
 18591  **       object on a linked list attached to Select.pWinDefn.
 18592  **
 18593  ** The uses (1) and (2) are really the same Window object that just happens
 18594  ** to be accessible in two different ways.  Use (3) is are separate objects.
 18595  */
 18596  struct Window {
 18597    char *zName;            /* Name of window (may be NULL) */
 18598    ExprList *pPartition;   /* PARTITION BY clause */
 18599    ExprList *pOrderBy;     /* ORDER BY clause */
 18600    u8 eType;               /* TK_RANGE or TK_ROWS */
 18601    u8 eStart;              /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
 18602    u8 eEnd;                /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
 18603    Expr *pStart;           /* Expression for "<expr> PRECEDING" */
 18604    Expr *pEnd;             /* Expression for "<expr> FOLLOWING" */
 18605    Window *pNextWin;       /* Next window function belonging to this SELECT */
 18606    Expr *pFilter;          /* The FILTER expression */
 18607    FuncDef *pFunc;         /* The function */
 18608    int iEphCsr;            /* Partition buffer or Peer buffer */
 18609    int regAccum;
 18610    int regResult;
 18611    int csrApp;             /* Function cursor (used by min/max) */
 18612    int regApp;             /* Function register (also used by min/max) */
 18613    int regPart;            /* First in a set of registers holding PARTITION BY
 18614                            ** and ORDER BY values for the window */
 18615    Expr *pOwner;           /* Expression object this window is attached to */
 18616    int nBufferCol;         /* Number of columns in buffer table */
 18617    int iArgCol;            /* Offset of first argument for this function */
 18618  };
 18619  
 18620  #ifndef SQLITE_OMIT_WINDOWFUNC
 18621  SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
 18622  SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
 18623  SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*);
 18624  SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
 18625  SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*);
 18626  SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
 18627  SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
 18628  SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
 18629  SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
 18630  SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
 18631  SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
 18632  SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
 18633  SQLITE_PRIVATE void sqlite3WindowFunctions(void);
 18634  #else
 18635  # define sqlite3WindowDelete(a,b)
 18636  # define sqlite3WindowFunctions()
 18637  # define sqlite3WindowAttach(a,b,c)
 18638  #endif
 18639  
 18640  /*
 18641  ** Assuming zIn points to the first byte of a UTF-8 character,
 18642  ** advance zIn to point to the first byte of the next UTF-8 character.
 18643  */
 18644  #define SQLITE_SKIP_UTF8(zIn) {                        \
 18645    if( (*(zIn++))>=0xc0 ){                              \
 18646      while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
 18647    }                                                    \
 18648  }
 18649  
 18650  /*
 18651  ** The SQLITE_*_BKPT macros are substitutes for the error codes with
 18652  ** the same name but without the _BKPT suffix.  These macros invoke
 18653  ** routines that report the line-number on which the error originated
 18654  ** using sqlite3_log().  The routines also provide a convenient place
 18655  ** to set a debugger breakpoint.
 18656  */
 18657  SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
 18658  SQLITE_PRIVATE int sqlite3CorruptError(int);
 18659  SQLITE_PRIVATE int sqlite3MisuseError(int);
 18660  SQLITE_PRIVATE int sqlite3CantopenError(int);
 18661  #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
 18662  #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
 18663  #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
 18664  #ifdef SQLITE_DEBUG
 18665  SQLITE_PRIVATE   int sqlite3NomemError(int);
 18666  SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
 18667  SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
 18668  # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
 18669  # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
 18670  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
 18671  #else
 18672  # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
 18673  # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
 18674  # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
 18675  #endif
 18676  
 18677  /*
 18678  ** FTS3 and FTS4 both require virtual table support
 18679  */
 18680  #if defined(SQLITE_OMIT_VIRTUALTABLE)
 18681  # undef SQLITE_ENABLE_FTS3
 18682  # undef SQLITE_ENABLE_FTS4
 18683  #endif
 18684  
 18685  /*
 18686  ** FTS4 is really an extension for FTS3.  It is enabled using the
 18687  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
 18688  ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
 18689  */
 18690  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
 18691  # define SQLITE_ENABLE_FTS3 1
 18692  #endif
 18693  
 18694  /*
 18695  ** The ctype.h header is needed for non-ASCII systems.  It is also
 18696  ** needed by FTS3 when FTS3 is included in the amalgamation.
 18697  */
 18698  #if !defined(SQLITE_ASCII) || \
 18699      (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
 18700  # include <ctype.h>
 18701  #endif
 18702  
 18703  /*
 18704  ** The following macros mimic the standard library functions toupper(),
 18705  ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
 18706  ** sqlite versions only work for ASCII characters, regardless of locale.
 18707  */
 18708  #ifdef SQLITE_ASCII
 18709  # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
 18710  # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
 18711  # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
 18712  # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
 18713  # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
 18714  # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
 18715  # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
 18716  # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
 18717  #else
 18718  # define sqlite3Toupper(x)   toupper((unsigned char)(x))
 18719  # define sqlite3Isspace(x)   isspace((unsigned char)(x))
 18720  # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
 18721  # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
 18722  # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
 18723  # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
 18724  # define sqlite3Tolower(x)   tolower((unsigned char)(x))
 18725  # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
 18726  #endif
 18727  SQLITE_PRIVATE int sqlite3IsIdChar(u8);
 18728  
 18729  /*
 18730  ** Internal function prototypes
 18731  */
 18732  SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
 18733  SQLITE_PRIVATE int sqlite3Strlen30(const char*);
 18734  #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
 18735  SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
 18736  #define sqlite3StrNICmp sqlite3_strnicmp
 18737  
 18738  SQLITE_PRIVATE int sqlite3MallocInit(void);
 18739  SQLITE_PRIVATE void sqlite3MallocEnd(void);
 18740  SQLITE_PRIVATE void *sqlite3Malloc(u64);
 18741  SQLITE_PRIVATE void *sqlite3MallocZero(u64);
 18742  SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
 18743  SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
 18744  SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
 18745  SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
 18746  SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
 18747  SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
 18748  SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
 18749  SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
 18750  SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
 18751  SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
 18752  SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
 18753  SQLITE_PRIVATE int sqlite3MallocSize(void*);
 18754  SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
 18755  SQLITE_PRIVATE void *sqlite3PageMalloc(int);
 18756  SQLITE_PRIVATE void sqlite3PageFree(void*);
 18757  SQLITE_PRIVATE void sqlite3MemSetDefault(void);
 18758  #ifndef SQLITE_UNTESTABLE
 18759  SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
 18760  #endif
 18761  SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
 18762  
 18763  /*
 18764  ** On systems with ample stack space and that support alloca(), make
 18765  ** use of alloca() to obtain space for large automatic objects.  By default,
 18766  ** obtain space from malloc().
 18767  **
 18768  ** The alloca() routine never returns NULL.  This will cause code paths
 18769  ** that deal with sqlite3StackAlloc() failures to be unreachable.
 18770  */
 18771  #ifdef SQLITE_USE_ALLOCA
 18772  # define sqlite3StackAllocRaw(D,N)   alloca(N)
 18773  # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
 18774  # define sqlite3StackFree(D,P)
 18775  #else
 18776  # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
 18777  # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
 18778  # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
 18779  #endif
 18780  
 18781  /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
 18782  ** are, disable MEMSYS3
 18783  */
 18784  #ifdef SQLITE_ENABLE_MEMSYS5
 18785  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
 18786  #undef SQLITE_ENABLE_MEMSYS3
 18787  #endif
 18788  #ifdef SQLITE_ENABLE_MEMSYS3
 18789  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
 18790  #endif
 18791  
 18792  
 18793  #ifndef SQLITE_MUTEX_OMIT
 18794  SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
 18795  SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
 18796  SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
 18797  SQLITE_PRIVATE   int sqlite3MutexInit(void);
 18798  SQLITE_PRIVATE   int sqlite3MutexEnd(void);
 18799  #endif
 18800  #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
 18801  SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
 18802  #else
 18803  # define sqlite3MemoryBarrier()
 18804  #endif
 18805  
 18806  SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
 18807  SQLITE_PRIVATE void sqlite3StatusUp(int, int);
 18808  SQLITE_PRIVATE void sqlite3StatusDown(int, int);
 18809  SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
 18810  SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
 18811  
 18812  /* Access to mutexes used by sqlite3_status() */
 18813  SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
 18814  SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
 18815  
 18816  #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
 18817  SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
 18818  #else
 18819  # define sqlite3MutexWarnOnContention(x)
 18820  #endif
 18821  
 18822  #ifndef SQLITE_OMIT_FLOATING_POINT
 18823  SQLITE_PRIVATE   int sqlite3IsNaN(double);
 18824  #else
 18825  # define sqlite3IsNaN(X)  0
 18826  #endif
 18827  
 18828  /*
 18829  ** An instance of the following structure holds information about SQL
 18830  ** functions arguments that are the parameters to the printf() function.
 18831  */
 18832  struct PrintfArguments {
 18833    int nArg;                /* Total number of arguments */
 18834    int nUsed;               /* Number of arguments used so far */
 18835    sqlite3_value **apArg;   /* The argument values */
 18836  };
 18837  
 18838  SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
 18839  SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
 18840  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 18841  SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
 18842  #endif
 18843  #if defined(SQLITE_TEST)
 18844  SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
 18845  #endif
 18846  
 18847  #if defined(SQLITE_DEBUG)
 18848  SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
 18849  SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
 18850  SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
 18851  SQLITE_PRIVATE   void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
 18852  SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
 18853  SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
 18854  #ifndef SQLITE_OMIT_WINDOWFUNC
 18855  SQLITE_PRIVATE   void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
 18856  SQLITE_PRIVATE   void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
 18857  #endif
 18858  #endif
 18859  
 18860  
 18861  SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
 18862  SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
 18863  SQLITE_PRIVATE void sqlite3Dequote(char*);
 18864  SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
 18865  SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
 18866  SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
 18867  SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
 18868  SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
 18869  SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
 18870  SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
 18871  SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
 18872  SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
 18873  SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
 18874  #ifdef SQLITE_DEBUG
 18875  SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
 18876  #endif
 18877  SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
 18878  SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
 18879  SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
 18880  SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
 18881  SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
 18882  SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
 18883  SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
 18884  SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
 18885  SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
 18886  SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
 18887  SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
 18888  SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
 18889  SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
 18890  SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
 18891  SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
 18892  SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
 18893  SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
 18894  SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
 18895  SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
 18896  SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
 18897  SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
 18898  #ifndef SQLITE_OMIT_VIRTUALTABLE
 18899  SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
 18900  #endif
 18901  SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
 18902  SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
 18903  SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
 18904  SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
 18905  SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
 18906  SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
 18907  SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
 18908  SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
 18909  SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
 18910  SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
 18911  SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
 18912  SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 18913  #if SQLITE_ENABLE_HIDDEN_COLUMNS
 18914  SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
 18915  #else
 18916  # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
 18917  #endif
 18918  SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
 18919  SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 18920  SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
 18921  SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
 18922  SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
 18923  SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
 18924  SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
 18925  SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
 18926                      sqlite3_vfs**,char**,char **);
 18927  #ifdef SQLITE_HAS_CODEC
 18928  SQLITE_PRIVATE   int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
 18929  #else
 18930  # define sqlite3CodecQueryParameters(A,B,C) 0
 18931  #endif
 18932  SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
 18933  
 18934  #ifdef SQLITE_UNTESTABLE
 18935  # define sqlite3FaultSim(X) SQLITE_OK
 18936  #else
 18937  SQLITE_PRIVATE   int sqlite3FaultSim(int);
 18938  #endif
 18939  
 18940  SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
 18941  SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
 18942  SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
 18943  SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
 18944  SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
 18945  SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
 18946  SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
 18947  #ifndef SQLITE_UNTESTABLE
 18948  SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
 18949  #endif
 18950  
 18951  SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
 18952  SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
 18953  SQLITE_PRIVATE void sqlite3RowSetClear(void*);
 18954  SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
 18955  SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
 18956  SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
 18957  
 18958  SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
 18959  
 18960  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
 18961  SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
 18962  #else
 18963  # define sqlite3ViewGetColumnNames(A,B) 0
 18964  #endif
 18965  
 18966  #if SQLITE_MAX_ATTACHED>30
 18967  SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
 18968  #endif
 18969  SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
 18970  SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
 18971  SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
 18972  SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
 18973  #ifndef SQLITE_OMIT_AUTOINCREMENT
 18974  SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
 18975  SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
 18976  #else
 18977  # define sqlite3AutoincrementBegin(X)
 18978  # define sqlite3AutoincrementEnd(X)
 18979  #endif
 18980  SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
 18981  SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
 18982  SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
 18983  SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
 18984  SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
 18985  SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
 18986  SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
 18987                                        Token*, Select*, Expr*, IdList*);
 18988  SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
 18989  SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
 18990  SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
 18991  SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
 18992  SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
 18993  SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
 18994  SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
 18995  SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
 18996  SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
 18997                            Expr*, int, int, u8);
 18998  SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
 18999  SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
 19000  SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
 19001                           Expr*,ExprList*,u32,Expr*);
 19002  SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
 19003  SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
 19004  SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
 19005  SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
 19006  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
 19007  SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
 19008  #endif
 19009  SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
 19010  SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
 19011                     Upsert*);
 19012  SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
 19013  SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 19014  SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
 19015  SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
 19016  SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
 19017  SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
 19018  SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
 19019  SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
 19020  SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
 19021  SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
 19022  #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
 19023  #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
 19024  #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
 19025  SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
 19026  SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
 19027  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
 19028  SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
 19029  SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
 19030  SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
 19031  SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
 19032  SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
 19033  SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
 19034  SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
 19035  SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
 19036  SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
 19037  #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
 19038  #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
 19039  #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
 19040  #define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
 19041  SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
 19042  SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
 19043  SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
 19044  SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
 19045  #define LOCATE_VIEW    0x01
 19046  #define LOCATE_NOERR   0x02
 19047  SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
 19048  SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
 19049  SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
 19050  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
 19051  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
 19052  SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
 19053  SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
 19054  SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
 19055  SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
 19056  SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
 19057  SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
 19058  SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
 19059  SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
 19060  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
 19061  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
 19062  SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
 19063  SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
 19064  SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
 19065  #ifndef SQLITE_UNTESTABLE
 19066  SQLITE_PRIVATE void sqlite3PrngSaveState(void);
 19067  SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
 19068  #endif
 19069  SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
 19070  SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
 19071  SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
 19072  SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
 19073  SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
 19074  SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
 19075  SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
 19076  SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
 19077  SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
 19078  SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
 19079  SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
 19080  SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
 19081  SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
 19082  SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
 19083  SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
 19084  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 19085  SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
 19086  #endif
 19087  SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
 19088  SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
 19089  SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
 19090  SQLITE_PRIVATE int sqlite3IsRowid(const char*);
 19091  SQLITE_PRIVATE void sqlite3GenerateRowDelete(
 19092      Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
 19093  SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
 19094  SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
 19095  SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
 19096  SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
 19097  SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
 19098                                       u8,u8,int,int*,int*,Upsert*);
 19099  #ifdef SQLITE_ENABLE_NULL_TRIM
 19100  SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
 19101  #else
 19102  # define sqlite3SetMakeRecordP5(A,B)
 19103  #endif
 19104  SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
 19105  SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
 19106  SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
 19107  SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
 19108  SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
 19109  SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
 19110  SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
 19111  SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
 19112  SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
 19113  SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
 19114  SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
 19115  SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
 19116  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
 19117  SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
 19118  SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
 19119  SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
 19120  SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
 19121  SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
 19122  SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
 19123  SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
 19124  SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
 19125  SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
 19126  
 19127  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
 19128  SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
 19129  #endif
 19130  
 19131  #ifndef SQLITE_OMIT_TRIGGER
 19132  SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
 19133                             Expr*,int, int);
 19134  SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
 19135  SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
 19136  SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
 19137  SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
 19138  SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
 19139  SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
 19140                              int, int, int);
 19141  SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
 19142    void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
 19143  SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
 19144  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
 19145                                          const char*,const char*);
 19146  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
 19147                                          Select*,u8,Upsert*,
 19148                                          const char*,const char*);
 19149  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
 19150                                          const char*,const char*);
 19151  SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
 19152                                          const char*,const char*);
 19153  SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
 19154  SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
 19155  SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
 19156  # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
 19157  # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
 19158  #else
 19159  # define sqlite3TriggersExist(B,C,D,E,F) 0
 19160  # define sqlite3DeleteTrigger(A,B)
 19161  # define sqlite3DropTriggerPtr(A,B)
 19162  # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
 19163  # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
 19164  # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
 19165  # define sqlite3TriggerList(X, Y) 0
 19166  # define sqlite3ParseToplevel(p) p
 19167  # define sqlite3IsToplevel(p) 1
 19168  # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
 19169  #endif
 19170  
 19171  SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
 19172  SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
 19173  SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
 19174  #ifndef SQLITE_OMIT_AUTHORIZATION
 19175  SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
 19176  SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
 19177  SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
 19178  SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
 19179  SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
 19180  #else
 19181  # define sqlite3AuthRead(a,b,c,d)
 19182  # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
 19183  # define sqlite3AuthContextPush(a,b,c)
 19184  # define sqlite3AuthContextPop(a)  ((void)(a))
 19185  #endif
 19186  SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
 19187  SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 19188  SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
 19189  SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
 19190  SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
 19191  SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
 19192  SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 19193  SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 19194  SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
 19195  SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
 19196  SQLITE_PRIVATE int sqlite3Atoi(const char*);
 19197  #ifndef SQLITE_OMIT_UTF16
 19198  SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
 19199  #endif
 19200  SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 19201  SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
 19202  SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
 19203  SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
 19204  #ifndef SQLITE_OMIT_VIRTUALTABLE
 19205  SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
 19206  #endif
 19207  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 19208      defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
 19209      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 19210  SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
 19211  #endif
 19212  SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
 19213  SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
 19214  SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
 19215  
 19216  /*
 19217  ** Routines to read and write variable-length integers.  These used to
 19218  ** be defined locally, but now we use the varint routines in the util.c
 19219  ** file.
 19220  */
 19221  SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
 19222  SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
 19223  SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
 19224  SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
 19225  
 19226  /*
 19227  ** The common case is for a varint to be a single byte.  They following
 19228  ** macros handle the common case without a procedure call, but then call
 19229  ** the procedure for larger varints.
 19230  */
 19231  #define getVarint32(A,B)  \
 19232    (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
 19233  #define putVarint32(A,B)  \
 19234    (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
 19235    sqlite3PutVarint((A),(B)))
 19236  #define getVarint    sqlite3GetVarint
 19237  #define putVarint    sqlite3PutVarint
 19238  
 19239  
 19240  SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
 19241  SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
 19242  SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
 19243  SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
 19244  SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
 19245  SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
 19246  SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 19247  SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
 19248  SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
 19249  SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
 19250  SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
 19251  SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
 19252  SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
 19253  SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
 19254  
 19255  #if defined(SQLITE_NEED_ERR_NAME)
 19256  SQLITE_PRIVATE const char *sqlite3ErrName(int);
 19257  #endif
 19258  
 19259  #ifdef SQLITE_ENABLE_DESERIALIZE
 19260  SQLITE_PRIVATE int sqlite3MemdbInit(void);
 19261  #endif
 19262  
 19263  SQLITE_PRIVATE const char *sqlite3ErrStr(int);
 19264  SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
 19265  SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
 19266  SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
 19267  SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
 19268  SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
 19269  SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
 19270  SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
 19271  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
 19272  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
 19273  SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
 19274  SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
 19275  SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
 19276  SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
 19277  SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
 19278  SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
 19279  SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
 19280  SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
 19281  SQLITE_PRIVATE int sqlite3AbsInt32(int);
 19282  #ifdef SQLITE_ENABLE_8_3_NAMES
 19283  SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
 19284  #else
 19285  # define sqlite3FileSuffix3(X,Y)
 19286  #endif
 19287  SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
 19288  
 19289  SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
 19290  SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
 19291  SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
 19292                          void(*)(void*));
 19293  SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
 19294  SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
 19295  SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
 19296  #ifndef SQLITE_OMIT_UTF16
 19297  SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
 19298  #endif
 19299  SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
 19300  SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
 19301  #ifndef SQLITE_AMALGAMATION
 19302  SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
 19303  SQLITE_PRIVATE const char sqlite3StrBINARY[];
 19304  SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
 19305  SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
 19306  SQLITE_PRIVATE const Token sqlite3IntTokens[];
 19307  SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
 19308  SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 19309  #ifndef SQLITE_OMIT_WSD
 19310  SQLITE_PRIVATE int sqlite3PendingByte;
 19311  #endif
 19312  #endif
 19313  #ifdef VDBE_PROFILE
 19314  SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
 19315  #endif
 19316  SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
 19317  SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 19318  SQLITE_PRIVATE void sqlite3AlterFunctions(void);
 19319  SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
 19320  SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
 19321  SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
 19322  SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
 19323  SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
 19324  SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
 19325  SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
 19326  SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
 19327  SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
 19328  SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
 19329  SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
 19330  SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
 19331  SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
 19332  SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
 19333  SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
 19334  SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
 19335  SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
 19336  SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
 19337  SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
 19338  SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
 19339  SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
 19340  SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
 19341  SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
 19342  SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
 19343  SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
 19344  SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
 19345  SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
 19346  SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
 19347  SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
 19348  SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
 19349  SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
 19350  SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
 19351  SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
 19352  SQLITE_PRIVATE void sqlite3SchemaClear(void *);
 19353  SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
 19354  SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
 19355  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
 19356  SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
 19357  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
 19358  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
 19359  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
 19360  
 19361  #ifdef SQLITE_DEBUG
 19362  SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 19363  #endif
 19364  SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
 19365    void (*)(sqlite3_context*,int,sqlite3_value **),
 19366    void (*)(sqlite3_context*,int,sqlite3_value **), 
 19367    void (*)(sqlite3_context*),
 19368    void (*)(sqlite3_context*),
 19369    void (*)(sqlite3_context*,int,sqlite3_value **), 
 19370    FuncDestructor *pDestructor
 19371  );
 19372  SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
 19373  SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
 19374  SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
 19375  SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
 19376  SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
 19377  
 19378  SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
 19379  SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
 19380  SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
 19381  SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
 19382  
 19383  SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
 19384  SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
 19385  
 19386  #ifndef SQLITE_OMIT_SUBQUERY
 19387  SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
 19388  #else
 19389  # define sqlite3ExprCheckIN(x,y) SQLITE_OK
 19390  #endif
 19391  
 19392  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 19393  SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
 19394  SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 19395      Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
 19396  SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
 19397  SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
 19398  SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
 19399  SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
 19400  #endif
 19401  
 19402  /*
 19403  ** The interface to the LEMON-generated parser
 19404  */
 19405  #ifndef SQLITE_AMALGAMATION
 19406  SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
 19407  SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
 19408  #endif
 19409  SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
 19410  SQLITE_PRIVATE int sqlite3ParserFallback(int);
 19411  #ifdef YYTRACKMAXSTACKDEPTH
 19412  SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
 19413  #endif
 19414  
 19415  SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
 19416  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 19417  SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
 19418  #else
 19419  # define sqlite3CloseExtensions(X)
 19420  #endif
 19421  
 19422  #ifndef SQLITE_OMIT_SHARED_CACHE
 19423  SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
 19424  #else
 19425    #define sqlite3TableLock(v,w,x,y,z)
 19426  #endif
 19427  
 19428  #ifdef SQLITE_TEST
 19429  SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
 19430  #endif
 19431  
 19432  #ifdef SQLITE_OMIT_VIRTUALTABLE
 19433  #  define sqlite3VtabClear(Y)
 19434  #  define sqlite3VtabSync(X,Y) SQLITE_OK
 19435  #  define sqlite3VtabRollback(X)
 19436  #  define sqlite3VtabCommit(X)
 19437  #  define sqlite3VtabInSync(db) 0
 19438  #  define sqlite3VtabLock(X)
 19439  #  define sqlite3VtabUnlock(X)
 19440  #  define sqlite3VtabUnlockList(X)
 19441  #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
 19442  #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
 19443  #else
 19444  SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
 19445  SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
 19446  SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
 19447  SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
 19448  SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
 19449  SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
 19450  SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
 19451  SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
 19452  SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
 19453  SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
 19454  SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
 19455  SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
 19456       sqlite3*,
 19457       const char*,
 19458       const sqlite3_module*,
 19459       void*,
 19460       void(*)(void*)
 19461     );
 19462  #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
 19463  #endif
 19464  SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
 19465  SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
 19466  SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
 19467  SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
 19468  SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
 19469  SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
 19470  SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
 19471  SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 19472  SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 19473  SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 19474  SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 19475  SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
 19476  SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 19477  SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 19478  SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 19479  SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
 19480  #ifdef SQLITE_ENABLE_NORMALIZE
 19481  SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
 19482  #endif
 19483  SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 19484  SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 19485  SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 19486  SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 19487  SQLITE_PRIVATE const char *sqlite3JournalModename(int);
 19488  #ifndef SQLITE_OMIT_WAL
 19489  SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
 19490  SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
 19491  #endif
 19492  #ifndef SQLITE_OMIT_CTE
 19493  SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
 19494  SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
 19495  SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
 19496  #else
 19497  #define sqlite3WithPush(x,y,z)
 19498  #define sqlite3WithDelete(x,y)
 19499  #endif
 19500  #ifndef SQLITE_OMIT_UPSERT
 19501  SQLITE_PRIVATE   Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
 19502  SQLITE_PRIVATE   void sqlite3UpsertDelete(sqlite3*,Upsert*);
 19503  SQLITE_PRIVATE   Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
 19504  SQLITE_PRIVATE   int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
 19505  SQLITE_PRIVATE   void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
 19506  #else
 19507  #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
 19508  #define sqlite3UpsertDelete(x,y)
 19509  #define sqlite3UpsertDup(x,y)       ((Upsert*)0)
 19510  #endif
 19511  
 19512  
 19513  /* Declarations for functions in fkey.c. All of these are replaced by
 19514  ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
 19515  ** key functionality is available. If OMIT_TRIGGER is defined but
 19516  ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
 19517  ** this case foreign keys are parsed, but no other functionality is
 19518  ** provided (enforcement of FK constraints requires the triggers sub-system).
 19519  */
 19520  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 19521  SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
 19522  SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
 19523  SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
 19524  SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
 19525  SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
 19526  SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
 19527  #else
 19528    #define sqlite3FkActions(a,b,c,d,e,f)
 19529    #define sqlite3FkCheck(a,b,c,d,e,f)
 19530    #define sqlite3FkDropTable(a,b,c)
 19531    #define sqlite3FkOldmask(a,b)         0
 19532    #define sqlite3FkRequired(a,b,c,d)    0
 19533    #define sqlite3FkReferences(a)        0
 19534  #endif
 19535  #ifndef SQLITE_OMIT_FOREIGN_KEY
 19536  SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
 19537  SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
 19538  #else
 19539    #define sqlite3FkDelete(a,b)
 19540    #define sqlite3FkLocateIndex(a,b,c,d,e)
 19541  #endif
 19542  
 19543  
 19544  /*
 19545  ** Available fault injectors.  Should be numbered beginning with 0.
 19546  */
 19547  #define SQLITE_FAULTINJECTOR_MALLOC     0
 19548  #define SQLITE_FAULTINJECTOR_COUNT      1
 19549  
 19550  /*
 19551  ** The interface to the code in fault.c used for identifying "benign"
 19552  ** malloc failures. This is only present if SQLITE_UNTESTABLE
 19553  ** is not defined.
 19554  */
 19555  #ifndef SQLITE_UNTESTABLE
 19556  SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
 19557  SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
 19558  #else
 19559    #define sqlite3BeginBenignMalloc()
 19560    #define sqlite3EndBenignMalloc()
 19561  #endif
 19562  
 19563  /*
 19564  ** Allowed return values from sqlite3FindInIndex()
 19565  */
 19566  #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
 19567  #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
 19568  #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
 19569  #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
 19570  #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
 19571  /*
 19572  ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
 19573  */
 19574  #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
 19575  #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
 19576  #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
 19577  SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
 19578  
 19579  SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
 19580  SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
 19581  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 19582   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 19583  SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
 19584  #endif
 19585  
 19586  SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
 19587  SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
 19588  
 19589  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
 19590  #if SQLITE_MAX_EXPR_DEPTH>0
 19591  SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
 19592  SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
 19593  #else
 19594    #define sqlite3SelectExprHeight(x) 0
 19595    #define sqlite3ExprCheckHeight(x,y)
 19596  #endif
 19597  
 19598  SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
 19599  SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
 19600  
 19601  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
 19602  SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
 19603  SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
 19604  SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
 19605  #else
 19606    #define sqlite3ConnectionBlocked(x,y)
 19607    #define sqlite3ConnectionUnlocked(x)
 19608    #define sqlite3ConnectionClosed(x)
 19609  #endif
 19610  
 19611  #ifdef SQLITE_DEBUG
 19612  SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
 19613  #endif
 19614  #if defined(YYCOVERAGE)
 19615  SQLITE_PRIVATE   int sqlite3ParserCoverage(FILE*);
 19616  #endif
 19617  
 19618  /*
 19619  ** If the SQLITE_ENABLE IOTRACE exists then the global variable
 19620  ** sqlite3IoTrace is a pointer to a printf-like routine used to
 19621  ** print I/O tracing messages.
 19622  */
 19623  #ifdef SQLITE_ENABLE_IOTRACE
 19624  # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
 19625  SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
 19626  SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
 19627  #else
 19628  # define IOTRACE(A)
 19629  # define sqlite3VdbeIOTraceSql(X)
 19630  #endif
 19631  
 19632  /*
 19633  ** These routines are available for the mem2.c debugging memory allocator
 19634  ** only.  They are used to verify that different "types" of memory
 19635  ** allocations are properly tracked by the system.
 19636  **
 19637  ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
 19638  ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
 19639  ** a single bit set.
 19640  **
 19641  ** sqlite3MemdebugHasType() returns true if any of the bits in its second
 19642  ** argument match the type set by the previous sqlite3MemdebugSetType().
 19643  ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
 19644  **
 19645  ** sqlite3MemdebugNoType() returns true if none of the bits in its second
 19646  ** argument match the type set by the previous sqlite3MemdebugSetType().
 19647  **
 19648  ** Perhaps the most important point is the difference between MEMTYPE_HEAP
 19649  ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
 19650  ** it might have been allocated by lookaside, except the allocation was
 19651  ** too large or lookaside was already full.  It is important to verify
 19652  ** that allocations that might have been satisfied by lookaside are not
 19653  ** passed back to non-lookaside free() routines.  Asserts such as the
 19654  ** example above are placed on the non-lookaside free() routines to verify
 19655  ** this constraint.
 19656  **
 19657  ** All of this is no-op for a production build.  It only comes into
 19658  ** play when the SQLITE_MEMDEBUG compile-time option is used.
 19659  */
 19660  #ifdef SQLITE_MEMDEBUG
 19661  SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
 19662  SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
 19663  SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
 19664  #else
 19665  # define sqlite3MemdebugSetType(X,Y)  /* no-op */
 19666  # define sqlite3MemdebugHasType(X,Y)  1
 19667  # define sqlite3MemdebugNoType(X,Y)   1
 19668  #endif
 19669  #define MEMTYPE_HEAP       0x01  /* General heap allocations */
 19670  #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
 19671  #define MEMTYPE_PCACHE     0x04  /* Page cache allocations */
 19672  
 19673  /*
 19674  ** Threading interface
 19675  */
 19676  #if SQLITE_MAX_WORKER_THREADS>0
 19677  SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
 19678  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
 19679  #endif
 19680  
 19681  #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
 19682  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
 19683  #endif
 19684  #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
 19685  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
 19686  #endif
 19687  
 19688  SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
 19689  SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
 19690  SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
 19691  SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
 19692  SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
 19693  
 19694  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 19695  SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
 19696  #endif
 19697  
 19698  #endif /* SQLITEINT_H */
 19699  
 19700  /************** End of sqliteInt.h *******************************************/
 19701  /************** Begin file global.c ******************************************/
 19702  /*
 19703  ** 2008 June 13
 19704  **
 19705  ** The author disclaims copyright to this source code.  In place of
 19706  ** a legal notice, here is a blessing:
 19707  **
 19708  **    May you do good and not evil.
 19709  **    May you find forgiveness for yourself and forgive others.
 19710  **    May you share freely, never taking more than you give.
 19711  **
 19712  *************************************************************************
 19713  **
 19714  ** This file contains definitions of global variables and constants.
 19715  */
 19716  /* #include "sqliteInt.h" */
 19717  
 19718  /* An array to map all upper-case characters into their corresponding
 19719  ** lower-case character. 
 19720  **
 19721  ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
 19722  ** handle case conversions for the UTF character set since the tables
 19723  ** involved are nearly as big or bigger than SQLite itself.
 19724  */
 19725  SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
 19726  #ifdef SQLITE_ASCII
 19727        0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
 19728       18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
 19729       36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
 19730       54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
 19731      104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
 19732      122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
 19733      108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
 19734      126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
 19735      144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
 19736      162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
 19737      180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
 19738      198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
 19739      216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
 19740      234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
 19741      252,253,254,255
 19742  #endif
 19743  #ifdef SQLITE_EBCDIC
 19744        0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
 19745       16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
 19746       32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
 19747       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
 19748       64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
 19749       80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
 19750       96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
 19751      112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
 19752      128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
 19753      144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
 19754      160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
 19755      176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
 19756      192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
 19757      208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
 19758      224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
 19759      240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
 19760  #endif
 19761  };
 19762  
 19763  /*
 19764  ** The following 256 byte lookup table is used to support SQLites built-in
 19765  ** equivalents to the following standard library functions:
 19766  **
 19767  **   isspace()                        0x01
 19768  **   isalpha()                        0x02
 19769  **   isdigit()                        0x04
 19770  **   isalnum()                        0x06
 19771  **   isxdigit()                       0x08
 19772  **   toupper()                        0x20
 19773  **   SQLite identifier character      0x40
 19774  **   Quote character                  0x80
 19775  **
 19776  ** Bit 0x20 is set if the mapped character requires translation to upper
 19777  ** case. i.e. if the character is a lower-case ASCII character.
 19778  ** If x is a lower-case ASCII character, then its upper-case equivalent
 19779  ** is (x - 0x20). Therefore toupper() can be implemented as:
 19780  **
 19781  **   (x & ~(map[x]&0x20))
 19782  **
 19783  ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
 19784  ** array. tolower() is used more often than toupper() by SQLite.
 19785  **
 19786  ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an 
 19787  ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
 19788  ** non-ASCII UTF character. Hence the test for whether or not a character is
 19789  ** part of an identifier is 0x46.
 19790  */
 19791  #ifdef SQLITE_ASCII
 19792  SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 19793    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
 19794    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
 19795    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
 19796    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
 19797    0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
 19798    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
 19799    0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
 19800    0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
 19801  
 19802    0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
 19803    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
 19804    0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
 19805    0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
 19806    0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
 19807    0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
 19808    0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
 19809    0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
 19810  
 19811    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
 19812    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
 19813    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
 19814    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
 19815    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
 19816    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
 19817    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
 19818    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
 19819  
 19820    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
 19821    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
 19822    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
 19823    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
 19824    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
 19825    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
 19826    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
 19827    0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
 19828  };
 19829  #endif
 19830  
 19831  /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
 19832  ** compatibility for legacy applications, the URI filename capability is
 19833  ** disabled by default.
 19834  **
 19835  ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
 19836  ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
 19837  **
 19838  ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
 19839  ** disabled. The default value may be changed by compiling with the
 19840  ** SQLITE_USE_URI symbol defined.
 19841  **
 19842  ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
 19843  ** enabled.
 19844  */
 19845  #ifndef SQLITE_USE_URI
 19846  # ifdef SQLITE_HAS_CODEC
 19847  #  define SQLITE_USE_URI 1
 19848  # else
 19849  #  define SQLITE_USE_URI 0
 19850  # endif
 19851  #endif
 19852  
 19853  /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
 19854  ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
 19855  ** that compile-time option is omitted.
 19856  */
 19857  #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
 19858  # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
 19859  #endif
 19860  
 19861  /* The minimum PMA size is set to this value multiplied by the database
 19862  ** page size in bytes.
 19863  */
 19864  #ifndef SQLITE_SORTER_PMASZ
 19865  # define SQLITE_SORTER_PMASZ 250
 19866  #endif
 19867  
 19868  /* Statement journals spill to disk when their size exceeds the following
 19869  ** threshold (in bytes). 0 means that statement journals are created and
 19870  ** written to disk immediately (the default behavior for SQLite versions
 19871  ** before 3.12.0).  -1 means always keep the entire statement journal in
 19872  ** memory.  (The statement journal is also always held entirely in memory
 19873  ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
 19874  ** setting.)
 19875  */
 19876  #ifndef SQLITE_STMTJRNL_SPILL 
 19877  # define SQLITE_STMTJRNL_SPILL (64*1024)
 19878  #endif
 19879  
 19880  /*
 19881  ** The default lookaside-configuration, the format "SZ,N".  SZ is the
 19882  ** number of bytes in each lookaside slot (should be a multiple of 8)
 19883  ** and N is the number of slots.  The lookaside-configuration can be
 19884  ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
 19885  ** or at run-time for an individual database connection using
 19886  ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
 19887  */
 19888  #ifndef SQLITE_DEFAULT_LOOKASIDE
 19889  # define SQLITE_DEFAULT_LOOKASIDE 1200,100
 19890  #endif
 19891  
 19892  
 19893  /* The default maximum size of an in-memory database created using
 19894  ** sqlite3_deserialize()
 19895  */
 19896  #ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
 19897  # define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
 19898  #endif
 19899  
 19900  /*
 19901  ** The following singleton contains the global configuration for
 19902  ** the SQLite library.
 19903  */
 19904  SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
 19905     SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
 19906     1,                         /* bCoreMutex */
 19907     SQLITE_THREADSAFE==1,      /* bFullMutex */
 19908     SQLITE_USE_URI,            /* bOpenUri */
 19909     SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
 19910     0,                         /* bSmallMalloc */
 19911     0x7ffffffe,                /* mxStrlen */
 19912     0,                         /* neverCorrupt */
 19913     SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
 19914     SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
 19915     {0,0,0,0,0,0,0,0},         /* m */
 19916     {0,0,0,0,0,0,0,0,0},       /* mutex */
 19917     {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
 19918     (void*)0,                  /* pHeap */
 19919     0,                         /* nHeap */
 19920     0, 0,                      /* mnHeap, mxHeap */
 19921     SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
 19922     SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
 19923     (void*)0,                  /* pPage */
 19924     0,                         /* szPage */
 19925     SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
 19926     0,                         /* mxParserStack */
 19927     0,                         /* sharedCacheEnabled */
 19928     SQLITE_SORTER_PMASZ,       /* szPma */
 19929     /* All the rest should always be initialized to zero */
 19930     0,                         /* isInit */
 19931     0,                         /* inProgress */
 19932     0,                         /* isMutexInit */
 19933     0,                         /* isMallocInit */
 19934     0,                         /* isPCacheInit */
 19935     0,                         /* nRefInitMutex */
 19936     0,                         /* pInitMutex */
 19937     0,                         /* xLog */
 19938     0,                         /* pLogArg */
 19939  #ifdef SQLITE_ENABLE_SQLLOG
 19940     0,                         /* xSqllog */
 19941     0,                         /* pSqllogArg */
 19942  #endif
 19943  #ifdef SQLITE_VDBE_COVERAGE
 19944     0,                         /* xVdbeBranch */
 19945     0,                         /* pVbeBranchArg */
 19946  #endif
 19947  #ifdef SQLITE_ENABLE_DESERIALIZE
 19948     SQLITE_MEMDB_DEFAULT_MAXSIZE,   /* mxMemdbSize */
 19949  #endif
 19950  #ifndef SQLITE_UNTESTABLE
 19951     0,                         /* xTestCallback */
 19952  #endif
 19953     0,                         /* bLocaltimeFault */
 19954     0,                         /* bInternalFunctions */
 19955     0x7ffffffe,                /* iOnceResetThreshold */
 19956     SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
 19957  };
 19958  
 19959  /*
 19960  ** Hash table for global functions - functions common to all
 19961  ** database connections.  After initialization, this table is
 19962  ** read-only.
 19963  */
 19964  SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 19965  
 19966  /*
 19967  ** Constant tokens for values 0 and 1.
 19968  */
 19969  SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
 19970     { "0", 1 },
 19971     { "1", 1 }
 19972  };
 19973  
 19974  #ifdef VDBE_PROFILE
 19975  /*
 19976  ** The following performance counter can be used in place of
 19977  ** sqlite3Hwtime() for profiling.  This is a no-op on standard builds.
 19978  */
 19979  SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
 19980  #endif
 19981  
 19982  /*
 19983  ** The value of the "pending" byte must be 0x40000000 (1 byte past the
 19984  ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
 19985  ** the database page that contains the pending byte.  It never attempts
 19986  ** to read or write that page.  The pending byte page is set aside
 19987  ** for use by the VFS layers as space for managing file locks.
 19988  **
 19989  ** During testing, it is often desirable to move the pending byte to
 19990  ** a different position in the file.  This allows code that has to
 19991  ** deal with the pending byte to run on files that are much smaller
 19992  ** than 1 GiB.  The sqlite3_test_control() interface can be used to
 19993  ** move the pending byte.
 19994  **
 19995  ** IMPORTANT:  Changing the pending byte to any value other than
 19996  ** 0x40000000 results in an incompatible database file format!
 19997  ** Changing the pending byte during operation will result in undefined
 19998  ** and incorrect behavior.
 19999  */
 20000  #ifndef SQLITE_OMIT_WSD
 20001  SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
 20002  #endif
 20003  
 20004  /* #include "opcodes.h" */
 20005  /*
 20006  ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
 20007  ** created by mkopcodeh.awk during compilation.  Data is obtained
 20008  ** from the comments following the "case OP_xxxx:" statements in
 20009  ** the vdbe.c file.  
 20010  */
 20011  SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
 20012  
 20013  /*
 20014  ** Name of the default collating sequence
 20015  */
 20016  SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
 20017  
 20018  /************** End of global.c **********************************************/
 20019  /************** Begin file status.c ******************************************/
 20020  /*
 20021  ** 2008 June 18
 20022  **
 20023  ** The author disclaims copyright to this source code.  In place of
 20024  ** a legal notice, here is a blessing:
 20025  **
 20026  **    May you do good and not evil.
 20027  **    May you find forgiveness for yourself and forgive others.
 20028  **    May you share freely, never taking more than you give.
 20029  **
 20030  *************************************************************************
 20031  **
 20032  ** This module implements the sqlite3_status() interface and related
 20033  ** functionality.
 20034  */
 20035  /* #include "sqliteInt.h" */
 20036  /************** Include vdbeInt.h in the middle of status.c ******************/
 20037  /************** Begin file vdbeInt.h *****************************************/
 20038  /*
 20039  ** 2003 September 6
 20040  **
 20041  ** The author disclaims copyright to this source code.  In place of
 20042  ** a legal notice, here is a blessing:
 20043  **
 20044  **    May you do good and not evil.
 20045  **    May you find forgiveness for yourself and forgive others.
 20046  **    May you share freely, never taking more than you give.
 20047  **
 20048  *************************************************************************
 20049  ** This is the header file for information that is private to the
 20050  ** VDBE.  This information used to all be at the top of the single
 20051  ** source code file "vdbe.c".  When that file became too big (over
 20052  ** 6000 lines long) it was split up into several smaller files and
 20053  ** this header information was factored out.
 20054  */
 20055  #ifndef SQLITE_VDBEINT_H
 20056  #define SQLITE_VDBEINT_H
 20057  
 20058  /*
 20059  ** The maximum number of times that a statement will try to reparse
 20060  ** itself before giving up and returning SQLITE_SCHEMA.
 20061  */
 20062  #ifndef SQLITE_MAX_SCHEMA_RETRY
 20063  # define SQLITE_MAX_SCHEMA_RETRY 50
 20064  #endif
 20065  
 20066  /*
 20067  ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
 20068  ** "explain" P4 display logic is enabled.
 20069  */
 20070  #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
 20071       || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 20072  # define VDBE_DISPLAY_P4 1
 20073  #else
 20074  # define VDBE_DISPLAY_P4 0
 20075  #endif
 20076  
 20077  /*
 20078  ** SQL is translated into a sequence of instructions to be
 20079  ** executed by a virtual machine.  Each instruction is an instance
 20080  ** of the following structure.
 20081  */
 20082  typedef struct VdbeOp Op;
 20083  
 20084  /*
 20085  ** Boolean values
 20086  */
 20087  typedef unsigned Bool;
 20088  
 20089  /* Opaque type used by code in vdbesort.c */
 20090  typedef struct VdbeSorter VdbeSorter;
 20091  
 20092  /* Elements of the linked list at Vdbe.pAuxData */
 20093  typedef struct AuxData AuxData;
 20094  
 20095  /* Types of VDBE cursors */
 20096  #define CURTYPE_BTREE       0
 20097  #define CURTYPE_SORTER      1
 20098  #define CURTYPE_VTAB        2
 20099  #define CURTYPE_PSEUDO      3
 20100  
 20101  /*
 20102  ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
 20103  **
 20104  **      * A b-tree cursor
 20105  **          -  In the main database or in an ephemeral database
 20106  **          -  On either an index or a table
 20107  **      * A sorter
 20108  **      * A virtual table
 20109  **      * A one-row "pseudotable" stored in a single register
 20110  */
 20111  typedef struct VdbeCursor VdbeCursor;
 20112  struct VdbeCursor {
 20113    u8 eCurType;            /* One of the CURTYPE_* values above */
 20114    i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
 20115    u8 nullRow;             /* True if pointing to a row with no data */
 20116    u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
 20117    u8 isTable;             /* True for rowid tables.  False for indexes */
 20118  #ifdef SQLITE_DEBUG
 20119    u8 seekOp;              /* Most recent seek operation on this cursor */
 20120    u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
 20121  #endif
 20122    Bool isEphemeral:1;     /* True for an ephemeral table */
 20123    Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
 20124    Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
 20125    Bool seekHit:1;         /* See the OP_SeekHit and OP_IfNoHope opcodes */
 20126    Btree *pBtx;            /* Separate file holding temporary table */
 20127    i64 seqCount;           /* Sequence counter */
 20128    int *aAltMap;           /* Mapping from table to index column numbers */
 20129  
 20130    /* Cached OP_Column parse information is only valid if cacheStatus matches
 20131    ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
 20132    ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
 20133    ** the cache is out of date. */
 20134    u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
 20135    int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
 20136                            ** if there have been no prior seeks on the cursor. */
 20137    /* seekResult does not distinguish between "no seeks have ever occurred
 20138    ** on this cursor" and "the most recent seek was an exact match".
 20139    ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
 20140  
 20141    /* When a new VdbeCursor is allocated, only the fields above are zeroed.
 20142    ** The fields that follow are uninitialized, and must be individually
 20143    ** initialized prior to first use. */
 20144    VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
 20145    union {
 20146      BtCursor *pCursor;          /* CURTYPE_BTREE or _PSEUDO.  Btree cursor */
 20147      sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.              Vtab cursor */
 20148      VdbeSorter *pSorter;        /* CURTYPE_SORTER.            Sorter object */
 20149    } uc;
 20150    KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
 20151    u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
 20152    Pgno pgnoRoot;          /* Root page of the open btree cursor */
 20153    i16 nField;             /* Number of fields in the header */
 20154    u16 nHdrParsed;         /* Number of header fields parsed so far */
 20155    i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
 20156    u32 *aOffset;           /* Pointer to aType[nField] */
 20157    const u8 *aRow;         /* Data for the current row, if all on one page */
 20158    u32 payloadSize;        /* Total number of bytes in the record */
 20159    u32 szRow;              /* Byte available in aRow */
 20160  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
 20161    u64 maskUsed;           /* Mask of columns used by this cursor */
 20162  #endif
 20163  
 20164    /* 2*nField extra array elements allocated for aType[], beyond the one
 20165    ** static element declared in the structure.  nField total array slots for
 20166    ** aType[] and nField+1 array slots for aOffset[] */
 20167    u32 aType[1];           /* Type values record decode.  MUST BE LAST */
 20168  };
 20169  
 20170  
 20171  /*
 20172  ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
 20173  */
 20174  #define CACHE_STALE 0
 20175  
 20176  /*
 20177  ** When a sub-program is executed (OP_Program), a structure of this type
 20178  ** is allocated to store the current value of the program counter, as
 20179  ** well as the current memory cell array and various other frame specific
 20180  ** values stored in the Vdbe struct. When the sub-program is finished, 
 20181  ** these values are copied back to the Vdbe from the VdbeFrame structure,
 20182  ** restoring the state of the VM to as it was before the sub-program
 20183  ** began executing.
 20184  **
 20185  ** The memory for a VdbeFrame object is allocated and managed by a memory
 20186  ** cell in the parent (calling) frame. When the memory cell is deleted or
 20187  ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
 20188  ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
 20189  ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
 20190  ** this instead of deleting the VdbeFrame immediately is to avoid recursive
 20191  ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
 20192  ** child frame are released.
 20193  **
 20194  ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
 20195  ** set to NULL if the currently executing frame is the main program.
 20196  */
 20197  typedef struct VdbeFrame VdbeFrame;
 20198  struct VdbeFrame {
 20199    Vdbe *v;                /* VM this frame belongs to */
 20200    VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
 20201    Op *aOp;                /* Program instructions for parent frame */
 20202    i64 *anExec;            /* Event counters from parent frame */
 20203    Mem *aMem;              /* Array of memory cells for parent frame */
 20204    VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
 20205    u8 *aOnce;              /* Bitmask used by OP_Once */
 20206    void *token;            /* Copy of SubProgram.token */
 20207    i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
 20208    AuxData *pAuxData;      /* Linked list of auxdata allocations */
 20209  #if SQLITE_DEBUG
 20210    u32 iFrameMagic;        /* magic number for sanity checking */
 20211  #endif
 20212    int nCursor;            /* Number of entries in apCsr */
 20213    int pc;                 /* Program Counter in parent (calling) frame */
 20214    int nOp;                /* Size of aOp array */
 20215    int nMem;               /* Number of entries in aMem */
 20216    int nChildMem;          /* Number of memory cells for child frame */
 20217    int nChildCsr;          /* Number of cursors for child frame */
 20218    int nChange;            /* Statement changes (Vdbe.nChange)     */
 20219    int nDbChange;          /* Value of db->nChange */
 20220  };
 20221  
 20222  /* Magic number for sanity checking on VdbeFrame objects */
 20223  #define SQLITE_FRAME_MAGIC 0x879fb71e
 20224  
 20225  /*
 20226  ** Return a pointer to the array of registers allocated for use
 20227  ** by a VdbeFrame.
 20228  */
 20229  #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
 20230  
 20231  /*
 20232  ** Internally, the vdbe manipulates nearly all SQL values as Mem
 20233  ** structures. Each Mem struct may cache multiple representations (string,
 20234  ** integer etc.) of the same value.
 20235  */
 20236  struct sqlite3_value {
 20237    union MemValue {
 20238      double r;           /* Real value used when MEM_Real is set in flags */
 20239      i64 i;              /* Integer value used when MEM_Int is set in flags */
 20240      int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */
 20241      const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
 20242      FuncDef *pDef;      /* Used only when flags==MEM_Agg */
 20243    } u;
 20244    u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
 20245    u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
 20246    u8  eSubtype;       /* Subtype for this value */
 20247    int n;              /* Number of characters in string value, excluding '\0' */
 20248    char *z;            /* String or BLOB value */
 20249    /* ShallowCopy only needs to copy the information above */
 20250    char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
 20251    int szMalloc;       /* Size of the zMalloc allocation */
 20252    u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
 20253    sqlite3 *db;        /* The associated database connection */
 20254    void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
 20255  #ifdef SQLITE_DEBUG
 20256    Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
 20257    u16 mScopyFlags;    /* flags value immediately after the shallow copy */
 20258  #endif
 20259  };
 20260  
 20261  /*
 20262  ** Size of struct Mem not including the Mem.zMalloc member or anything that
 20263  ** follows.
 20264  */
 20265  #define MEMCELLSIZE offsetof(Mem,zMalloc)
 20266  
 20267  /* One or more of the following flags are set to indicate the validOK
 20268  ** representations of the value stored in the Mem struct.
 20269  **
 20270  ** If the MEM_Null flag is set, then the value is an SQL NULL value.
 20271  ** For a pointer type created using sqlite3_bind_pointer() or
 20272  ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
 20273  **
 20274  ** If the MEM_Str flag is set then Mem.z points at a string representation.
 20275  ** Usually this is encoded in the same unicode encoding as the main
 20276  ** database (see below for exceptions). If the MEM_Term flag is also
 20277  ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
 20278  ** flags may coexist with the MEM_Str flag.
 20279  */
 20280  #define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
 20281  #define MEM_Str       0x0002   /* Value is a string */
 20282  #define MEM_Int       0x0004   /* Value is an integer */
 20283  #define MEM_Real      0x0008   /* Value is a real number */
 20284  #define MEM_Blob      0x0010   /* Value is a BLOB */
 20285  #define MEM_AffMask   0x001f   /* Mask of affinity bits */
 20286  /* Available          0x0020   */
 20287  /* Available          0x0040   */
 20288  #define MEM_Undefined 0x0080   /* Value is undefined */
 20289  #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
 20290  #define MEM_TypeMask  0xc1ff   /* Mask of type bits */
 20291  
 20292  
 20293  /* Whenever Mem contains a valid string or blob representation, one of
 20294  ** the following flags must be set to determine the memory management
 20295  ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
 20296  ** string is \000 or \u0000 terminated
 20297  */
 20298  #define MEM_Term      0x0200   /* String in Mem.z is zero terminated */
 20299  #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
 20300  #define MEM_Static    0x0800   /* Mem.z points to a static string */
 20301  #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
 20302  #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
 20303  #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
 20304  #define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
 20305  #ifdef SQLITE_OMIT_INCRBLOB
 20306    #undef MEM_Zero
 20307    #define MEM_Zero 0x0000
 20308  #endif
 20309  
 20310  /* Return TRUE if Mem X contains dynamically allocated content - anything
 20311  ** that needs to be deallocated to avoid a leak.
 20312  */
 20313  #define VdbeMemDynamic(X)  \
 20314    (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
 20315  
 20316  /*
 20317  ** Clear any existing type flags from a Mem and replace them with f
 20318  */
 20319  #define MemSetTypeFlag(p, f) \
 20320     ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
 20321  
 20322  /*
 20323  ** Return true if a memory cell is not marked as invalid.  This macro
 20324  ** is for use inside assert() statements only.
 20325  */
 20326  #ifdef SQLITE_DEBUG
 20327  #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
 20328  #endif
 20329  
 20330  /*
 20331  ** Each auxiliary data pointer stored by a user defined function 
 20332  ** implementation calling sqlite3_set_auxdata() is stored in an instance
 20333  ** of this structure. All such structures associated with a single VM
 20334  ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
 20335  ** when the VM is halted (if not before).
 20336  */
 20337  struct AuxData {
 20338    int iAuxOp;                     /* Instruction number of OP_Function opcode */
 20339    int iAuxArg;                    /* Index of function argument. */
 20340    void *pAux;                     /* Aux data pointer */
 20341    void (*xDeleteAux)(void*);      /* Destructor for the aux data */
 20342    AuxData *pNextAux;              /* Next element in list */
 20343  };
 20344  
 20345  /*
 20346  ** The "context" argument for an installable function.  A pointer to an
 20347  ** instance of this structure is the first argument to the routines used
 20348  ** implement the SQL functions.
 20349  **
 20350  ** There is a typedef for this structure in sqlite.h.  So all routines,
 20351  ** even the public interface to SQLite, can use a pointer to this structure.
 20352  ** But this file is the only place where the internal details of this
 20353  ** structure are known.
 20354  **
 20355  ** This structure is defined inside of vdbeInt.h because it uses substructures
 20356  ** (Mem) which are only defined there.
 20357  */
 20358  struct sqlite3_context {
 20359    Mem *pOut;              /* The return value is stored here */
 20360    FuncDef *pFunc;         /* Pointer to function information */
 20361    Mem *pMem;              /* Memory cell used to store aggregate context */
 20362    Vdbe *pVdbe;            /* The VM that owns this context */
 20363    int iOp;                /* Instruction number of OP_Function */
 20364    int isError;            /* Error code returned by the function. */
 20365    u8 skipFlag;            /* Skip accumulator loading if true */
 20366    u8 argc;                /* Number of arguments */
 20367    sqlite3_value *argv[1]; /* Argument set */
 20368  };
 20369  
 20370  /* A bitfield type for use inside of structures.  Always follow with :N where
 20371  ** N is the number of bits.
 20372  */
 20373  typedef unsigned bft;  /* Bit Field Type */
 20374  
 20375  /* The ScanStatus object holds a single value for the
 20376  ** sqlite3_stmt_scanstatus() interface.
 20377  */
 20378  typedef struct ScanStatus ScanStatus;
 20379  struct ScanStatus {
 20380    int addrExplain;                /* OP_Explain for loop */
 20381    int addrLoop;                   /* Address of "loops" counter */
 20382    int addrVisit;                  /* Address of "rows visited" counter */
 20383    int iSelectID;                  /* The "Select-ID" for this loop */
 20384    LogEst nEst;                    /* Estimated output rows per loop */
 20385    char *zName;                    /* Name of table or index */
 20386  };
 20387  
 20388  /* The DblquoteStr object holds the text of a double-quoted
 20389  ** string for a prepared statement.  A linked list of these objects
 20390  ** is constructed during statement parsing and is held on Vdbe.pDblStr.
 20391  ** When computing a normalized SQL statement for an SQL statement, that
 20392  ** list is consulted for each double-quoted identifier to see if the
 20393  ** identifier should really be a string literal.
 20394  */
 20395  typedef struct DblquoteStr DblquoteStr;
 20396  struct DblquoteStr {
 20397    DblquoteStr *pNextStr;   /* Next string literal in the list */
 20398    char z[8];               /* Dequoted value for the string */
 20399  };
 20400  
 20401  /*
 20402  ** An instance of the virtual machine.  This structure contains the complete
 20403  ** state of the virtual machine.
 20404  **
 20405  ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
 20406  ** is really a pointer to an instance of this structure.
 20407  */
 20408  struct Vdbe {
 20409    sqlite3 *db;            /* The database connection that owns this statement */
 20410    Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
 20411    Parse *pParse;          /* Parsing context used to create this Vdbe */
 20412    ynVar nVar;             /* Number of entries in aVar[] */
 20413    u32 magic;              /* Magic number for sanity checking */
 20414    int nMem;               /* Number of memory locations currently allocated */
 20415    int nCursor;            /* Number of slots in apCsr[] */
 20416    u32 cacheCtr;           /* VdbeCursor row cache generation counter */
 20417    int pc;                 /* The program counter */
 20418    int rc;                 /* Value to return */
 20419    int nChange;            /* Number of db changes made since last reset */
 20420    int iStatement;         /* Statement number (or 0 if has no opened stmt) */
 20421    i64 iCurrentTime;       /* Value of julianday('now') for this statement */
 20422    i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
 20423    i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
 20424    i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
 20425    Mem *aMem;              /* The memory locations */
 20426    Mem **apArg;            /* Arguments to currently executing user function */
 20427    VdbeCursor **apCsr;     /* One element of this array for each open cursor */
 20428    Mem *aVar;              /* Values for the OP_Variable opcode. */
 20429  
 20430    /* When allocating a new Vdbe object, all of the fields below should be
 20431    ** initialized to zero or NULL */
 20432  
 20433    Op *aOp;                /* Space to hold the virtual machine's program */
 20434    int nOp;                /* Number of instructions in the program */
 20435    int nOpAlloc;           /* Slots allocated for aOp[] */
 20436    Mem *aColName;          /* Column names to return */
 20437    Mem *pResultSet;        /* Pointer to an array of results */
 20438    char *zErrMsg;          /* Error message written here */
 20439    VList *pVList;          /* Name of variables */
 20440  #ifndef SQLITE_OMIT_TRACE
 20441    i64 startTime;          /* Time when query started - used for profiling */
 20442  #endif
 20443  #ifdef SQLITE_DEBUG
 20444    int rcApp;              /* errcode set by sqlite3_result_error_code() */
 20445    u32 nWrite;             /* Number of write operations that have occurred */
 20446  #endif
 20447    u16 nResColumn;         /* Number of columns in one row of the result set */
 20448    u8 errorAction;         /* Recovery action to do in case of an error */
 20449    u8 minWriteFileFormat;  /* Minimum file format for writable database files */
 20450    u8 prepFlags;           /* SQLITE_PREPARE_* flags */
 20451    bft expired:2;          /* 1: recompile VM immediately  2: when convenient */
 20452    bft explain:2;          /* True if EXPLAIN present on SQL command */
 20453    bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
 20454    bft changeCntOn:1;      /* True to update the change-counter */
 20455    bft runOnlyOnce:1;      /* Automatically expire on reset */
 20456    bft usesStmtJournal:1;  /* True if uses a statement journal */
 20457    bft readOnly:1;         /* True for statements that do not write */
 20458    bft bIsReader:1;        /* True for statements that read */
 20459    yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 20460    yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 20461    u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
 20462    char *zSql;             /* Text of the SQL statement that generated this */
 20463  #ifdef SQLITE_ENABLE_NORMALIZE
 20464    char *zNormSql;         /* Normalization of the associated SQL statement */
 20465    DblquoteStr *pDblStr;   /* List of double-quoted string literals */
 20466  #endif
 20467    void *pFree;            /* Free this when deleting the vdbe */
 20468    VdbeFrame *pFrame;      /* Parent frame */
 20469    VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
 20470    int nFrame;             /* Number of frames in pFrame list */
 20471    u32 expmask;            /* Binding to these vars invalidates VM */
 20472    SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
 20473    AuxData *pAuxData;      /* Linked list of auxdata allocations */
 20474  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 20475    i64 *anExec;            /* Number of times each op has been executed */
 20476    int nScan;              /* Entries in aScan[] */
 20477    ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
 20478  #endif
 20479  };
 20480  
 20481  /*
 20482  ** The following are allowed values for Vdbe.magic
 20483  */
 20484  #define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */
 20485  #define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */
 20486  #define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */
 20487  #define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */
 20488  #define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
 20489  
 20490  /*
 20491  ** Structure used to store the context required by the 
 20492  ** sqlite3_preupdate_*() API functions.
 20493  */
 20494  struct PreUpdate {
 20495    Vdbe *v;
 20496    VdbeCursor *pCsr;               /* Cursor to read old values from */
 20497    int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
 20498    u8 *aRecord;                    /* old.* database record */
 20499    KeyInfo keyinfo;
 20500    UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
 20501    UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
 20502    int iNewReg;                    /* Register for new.* values */
 20503    i64 iKey1;                      /* First key value passed to hook */
 20504    i64 iKey2;                      /* Second key value passed to hook */
 20505    Mem *aNew;                      /* Array of new.* values */
 20506    Table *pTab;                    /* Schema object being upated */          
 20507    Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
 20508  };
 20509  
 20510  /*
 20511  ** Function prototypes
 20512  */
 20513  SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
 20514  SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
 20515  void sqliteVdbePopStack(Vdbe*,int);
 20516  SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
 20517  SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
 20518  SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 20519  SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
 20520  SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
 20521  SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
 20522  SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
 20523  SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
 20524  
 20525  int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 20526  SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
 20527  SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
 20528  SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
 20529  #ifndef SQLITE_OMIT_EXPLAIN
 20530  SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 20531  #endif
 20532  SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
 20533  SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
 20534  SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
 20535  SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
 20536  SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
 20537  SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
 20538  SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
 20539  SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
 20540  SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
 20541  #ifdef SQLITE_OMIT_FLOATING_POINT
 20542  # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
 20543  #else
 20544  SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
 20545  #endif
 20546  SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
 20547  SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
 20548  SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
 20549  SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
 20550  #ifdef SQLITE_DEBUG
 20551  SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
 20552  #endif
 20553  SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
 20554  SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
 20555  SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
 20556  SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
 20557  SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
 20558  SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
 20559  SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
 20560  SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
 20561  SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
 20562  SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
 20563  SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
 20564  SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
 20565  SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
 20566  SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
 20567  #ifndef SQLITE_OMIT_WINDOWFUNC
 20568  SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
 20569  #endif
 20570  #ifndef SQLITE_OMIT_EXPLAIN
 20571  SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
 20572  #endif
 20573  SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
 20574  SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
 20575  SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
 20576  #ifdef SQLITE_DEBUG
 20577  SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
 20578  #endif
 20579  SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*);      /* Destructor on Mem */
 20580  SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
 20581  SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
 20582  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 20583  SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
 20584  #endif
 20585  SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
 20586  
 20587  SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
 20588  SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
 20589  SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
 20590  SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
 20591  SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
 20592  SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
 20593  SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
 20594  SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
 20595  
 20596  #ifdef SQLITE_DEBUG
 20597  SQLITE_PRIVATE   void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
 20598  SQLITE_PRIVATE   void sqlite3VdbeAssertAbortable(Vdbe*);
 20599  #else
 20600  # define sqlite3VdbeIncrWriteCounter(V,C)
 20601  # define sqlite3VdbeAssertAbortable(V)
 20602  #endif
 20603  
 20604  #if !defined(SQLITE_OMIT_SHARED_CACHE) 
 20605  SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
 20606  #else
 20607  # define sqlite3VdbeEnter(X)
 20608  #endif
 20609  
 20610  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 20611  SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
 20612  #else
 20613  # define sqlite3VdbeLeave(X)
 20614  #endif
 20615  
 20616  #ifdef SQLITE_DEBUG
 20617  SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
 20618  SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
 20619  #endif
 20620  
 20621  #ifndef SQLITE_OMIT_FOREIGN_KEY
 20622  SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
 20623  #else
 20624  # define sqlite3VdbeCheckFk(p,i) 0
 20625  #endif
 20626  
 20627  #ifdef SQLITE_DEBUG
 20628  SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
 20629  SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
 20630  #endif
 20631  #ifndef SQLITE_OMIT_UTF16
 20632  SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
 20633  SQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);
 20634  #endif
 20635  
 20636  #ifndef SQLITE_OMIT_INCRBLOB
 20637  SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
 20638    #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
 20639  #else
 20640    #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
 20641    #define ExpandBlob(P) SQLITE_OK
 20642  #endif
 20643  
 20644  #endif /* !defined(SQLITE_VDBEINT_H) */
 20645  
 20646  /************** End of vdbeInt.h *********************************************/
 20647  /************** Continuing where we left off in status.c *********************/
 20648  
 20649  /*
 20650  ** Variables in which to record status information.
 20651  */
 20652  #if SQLITE_PTRSIZE>4
 20653  typedef sqlite3_int64 sqlite3StatValueType;
 20654  #else
 20655  typedef u32 sqlite3StatValueType;
 20656  #endif
 20657  typedef struct sqlite3StatType sqlite3StatType;
 20658  static SQLITE_WSD struct sqlite3StatType {
 20659    sqlite3StatValueType nowValue[10];  /* Current value */
 20660    sqlite3StatValueType mxValue[10];   /* Maximum value */
 20661  } sqlite3Stat = { {0,}, {0,} };
 20662  
 20663  /*
 20664  ** Elements of sqlite3Stat[] are protected by either the memory allocator
 20665  ** mutex, or by the pcache1 mutex.  The following array determines which.
 20666  */
 20667  static const char statMutex[] = {
 20668    0,  /* SQLITE_STATUS_MEMORY_USED */
 20669    1,  /* SQLITE_STATUS_PAGECACHE_USED */
 20670    1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
 20671    0,  /* SQLITE_STATUS_SCRATCH_USED */
 20672    0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
 20673    0,  /* SQLITE_STATUS_MALLOC_SIZE */
 20674    0,  /* SQLITE_STATUS_PARSER_STACK */
 20675    1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
 20676    0,  /* SQLITE_STATUS_SCRATCH_SIZE */
 20677    0,  /* SQLITE_STATUS_MALLOC_COUNT */
 20678  };
 20679  
 20680  
 20681  /* The "wsdStat" macro will resolve to the status information
 20682  ** state vector.  If writable static data is unsupported on the target,
 20683  ** we have to locate the state vector at run-time.  In the more common
 20684  ** case where writable static data is supported, wsdStat can refer directly
 20685  ** to the "sqlite3Stat" state vector declared above.
 20686  */
 20687  #ifdef SQLITE_OMIT_WSD
 20688  # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
 20689  # define wsdStat x[0]
 20690  #else
 20691  # define wsdStatInit
 20692  # define wsdStat sqlite3Stat
 20693  #endif
 20694  
 20695  /*
 20696  ** Return the current value of a status parameter.  The caller must
 20697  ** be holding the appropriate mutex.
 20698  */
 20699  SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
 20700    wsdStatInit;
 20701    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 20702    assert( op>=0 && op<ArraySize(statMutex) );
 20703    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 20704                                             : sqlite3MallocMutex()) );
 20705    return wsdStat.nowValue[op];
 20706  }
 20707  
 20708  /*
 20709  ** Add N to the value of a status record.  The caller must hold the
 20710  ** appropriate mutex.  (Locking is checked by assert()).
 20711  **
 20712  ** The StatusUp() routine can accept positive or negative values for N.
 20713  ** The value of N is added to the current status value and the high-water
 20714  ** mark is adjusted if necessary.
 20715  **
 20716  ** The StatusDown() routine lowers the current value by N.  The highwater
 20717  ** mark is unchanged.  N must be non-negative for StatusDown().
 20718  */
 20719  SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
 20720    wsdStatInit;
 20721    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 20722    assert( op>=0 && op<ArraySize(statMutex) );
 20723    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 20724                                             : sqlite3MallocMutex()) );
 20725    wsdStat.nowValue[op] += N;
 20726    if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
 20727      wsdStat.mxValue[op] = wsdStat.nowValue[op];
 20728    }
 20729  }
 20730  SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
 20731    wsdStatInit;
 20732    assert( N>=0 );
 20733    assert( op>=0 && op<ArraySize(statMutex) );
 20734    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 20735                                             : sqlite3MallocMutex()) );
 20736    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 20737    wsdStat.nowValue[op] -= N;
 20738  }
 20739  
 20740  /*
 20741  ** Adjust the highwater mark if necessary.
 20742  ** The caller must hold the appropriate mutex.
 20743  */
 20744  SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
 20745    sqlite3StatValueType newValue;
 20746    wsdStatInit;
 20747    assert( X>=0 );
 20748    newValue = (sqlite3StatValueType)X;
 20749    assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
 20750    assert( op>=0 && op<ArraySize(statMutex) );
 20751    assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
 20752                                             : sqlite3MallocMutex()) );
 20753    assert( op==SQLITE_STATUS_MALLOC_SIZE
 20754            || op==SQLITE_STATUS_PAGECACHE_SIZE
 20755            || op==SQLITE_STATUS_PARSER_STACK );
 20756    if( newValue>wsdStat.mxValue[op] ){
 20757      wsdStat.mxValue[op] = newValue;
 20758    }
 20759  }
 20760  
 20761  /*
 20762  ** Query status information.
 20763  */
 20764  SQLITE_API int sqlite3_status64(
 20765    int op,
 20766    sqlite3_int64 *pCurrent,
 20767    sqlite3_int64 *pHighwater,
 20768    int resetFlag
 20769  ){
 20770    sqlite3_mutex *pMutex;
 20771    wsdStatInit;
 20772    if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
 20773      return SQLITE_MISUSE_BKPT;
 20774    }
 20775  #ifdef SQLITE_ENABLE_API_ARMOR
 20776    if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
 20777  #endif
 20778    pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
 20779    sqlite3_mutex_enter(pMutex);
 20780    *pCurrent = wsdStat.nowValue[op];
 20781    *pHighwater = wsdStat.mxValue[op];
 20782    if( resetFlag ){
 20783      wsdStat.mxValue[op] = wsdStat.nowValue[op];
 20784    }
 20785    sqlite3_mutex_leave(pMutex);
 20786    (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
 20787    return SQLITE_OK;
 20788  }
 20789  SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
 20790    sqlite3_int64 iCur = 0, iHwtr = 0;
 20791    int rc;
 20792  #ifdef SQLITE_ENABLE_API_ARMOR
 20793    if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
 20794  #endif
 20795    rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
 20796    if( rc==0 ){
 20797      *pCurrent = (int)iCur;
 20798      *pHighwater = (int)iHwtr;
 20799    }
 20800    return rc;
 20801  }
 20802  
 20803  /*
 20804  ** Return the number of LookasideSlot elements on the linked list
 20805  */
 20806  static u32 countLookasideSlots(LookasideSlot *p){
 20807    u32 cnt = 0;
 20808    while( p ){
 20809      p = p->pNext;
 20810      cnt++;
 20811    }
 20812    return cnt;
 20813  }
 20814  
 20815  /*
 20816  ** Count the number of slots of lookaside memory that are outstanding
 20817  */
 20818  SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
 20819    u32 nInit = countLookasideSlots(db->lookaside.pInit);
 20820    u32 nFree = countLookasideSlots(db->lookaside.pFree);
 20821    if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
 20822    return db->lookaside.nSlot - (nInit+nFree);
 20823  }
 20824  
 20825  /*
 20826  ** Query status information for a single database connection
 20827  */
 20828  SQLITE_API int sqlite3_db_status(
 20829    sqlite3 *db,          /* The database connection whose status is desired */
 20830    int op,               /* Status verb */
 20831    int *pCurrent,        /* Write current value here */
 20832    int *pHighwater,      /* Write high-water mark here */
 20833    int resetFlag         /* Reset high-water mark if true */
 20834  ){
 20835    int rc = SQLITE_OK;   /* Return code */
 20836  #ifdef SQLITE_ENABLE_API_ARMOR
 20837    if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
 20838      return SQLITE_MISUSE_BKPT;
 20839    }
 20840  #endif
 20841    sqlite3_mutex_enter(db->mutex);
 20842    switch( op ){
 20843      case SQLITE_DBSTATUS_LOOKASIDE_USED: {
 20844        *pCurrent = sqlite3LookasideUsed(db, pHighwater);
 20845        if( resetFlag ){
 20846          LookasideSlot *p = db->lookaside.pFree;
 20847          if( p ){
 20848            while( p->pNext ) p = p->pNext;
 20849            p->pNext = db->lookaside.pInit;
 20850            db->lookaside.pInit = db->lookaside.pFree;
 20851            db->lookaside.pFree = 0;
 20852          }
 20853        }
 20854        break;
 20855      }
 20856  
 20857      case SQLITE_DBSTATUS_LOOKASIDE_HIT:
 20858      case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
 20859      case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
 20860        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
 20861        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
 20862        testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
 20863        assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
 20864        assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
 20865        *pCurrent = 0;
 20866        *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
 20867        if( resetFlag ){
 20868          db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
 20869        }
 20870        break;
 20871      }
 20872  
 20873      /* 
 20874      ** Return an approximation for the amount of memory currently used
 20875      ** by all pagers associated with the given database connection.  The
 20876      ** highwater mark is meaningless and is returned as zero.
 20877      */
 20878      case SQLITE_DBSTATUS_CACHE_USED_SHARED:
 20879      case SQLITE_DBSTATUS_CACHE_USED: {
 20880        int totalUsed = 0;
 20881        int i;
 20882        sqlite3BtreeEnterAll(db);
 20883        for(i=0; i<db->nDb; i++){
 20884          Btree *pBt = db->aDb[i].pBt;
 20885          if( pBt ){
 20886            Pager *pPager = sqlite3BtreePager(pBt);
 20887            int nByte = sqlite3PagerMemUsed(pPager);
 20888            if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
 20889              nByte = nByte / sqlite3BtreeConnectionCount(pBt);
 20890            }
 20891            totalUsed += nByte;
 20892          }
 20893        }
 20894        sqlite3BtreeLeaveAll(db);
 20895        *pCurrent = totalUsed;
 20896        *pHighwater = 0;
 20897        break;
 20898      }
 20899  
 20900      /*
 20901      ** *pCurrent gets an accurate estimate of the amount of memory used
 20902      ** to store the schema for all databases (main, temp, and any ATTACHed
 20903      ** databases.  *pHighwater is set to zero.
 20904      */
 20905      case SQLITE_DBSTATUS_SCHEMA_USED: {
 20906        int i;                      /* Used to iterate through schemas */
 20907        int nByte = 0;              /* Used to accumulate return value */
 20908  
 20909        sqlite3BtreeEnterAll(db);
 20910        db->pnBytesFreed = &nByte;
 20911        for(i=0; i<db->nDb; i++){
 20912          Schema *pSchema = db->aDb[i].pSchema;
 20913          if( ALWAYS(pSchema!=0) ){
 20914            HashElem *p;
 20915  
 20916            nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
 20917                pSchema->tblHash.count 
 20918              + pSchema->trigHash.count
 20919              + pSchema->idxHash.count
 20920              + pSchema->fkeyHash.count
 20921            );
 20922            nByte += sqlite3_msize(pSchema->tblHash.ht);
 20923            nByte += sqlite3_msize(pSchema->trigHash.ht);
 20924            nByte += sqlite3_msize(pSchema->idxHash.ht);
 20925            nByte += sqlite3_msize(pSchema->fkeyHash.ht);
 20926  
 20927            for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
 20928              sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
 20929            }
 20930            for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
 20931              sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
 20932            }
 20933          }
 20934        }
 20935        db->pnBytesFreed = 0;
 20936        sqlite3BtreeLeaveAll(db);
 20937  
 20938        *pHighwater = 0;
 20939        *pCurrent = nByte;
 20940        break;
 20941      }
 20942  
 20943      /*
 20944      ** *pCurrent gets an accurate estimate of the amount of memory used
 20945      ** to store all prepared statements.
 20946      ** *pHighwater is set to zero.
 20947      */
 20948      case SQLITE_DBSTATUS_STMT_USED: {
 20949        struct Vdbe *pVdbe;         /* Used to iterate through VMs */
 20950        int nByte = 0;              /* Used to accumulate return value */
 20951  
 20952        db->pnBytesFreed = &nByte;
 20953        for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
 20954          sqlite3VdbeClearObject(db, pVdbe);
 20955          sqlite3DbFree(db, pVdbe);
 20956        }
 20957        db->pnBytesFreed = 0;
 20958  
 20959        *pHighwater = 0;  /* IMP: R-64479-57858 */
 20960        *pCurrent = nByte;
 20961  
 20962        break;
 20963      }
 20964  
 20965      /*
 20966      ** Set *pCurrent to the total cache hits or misses encountered by all
 20967      ** pagers the database handle is connected to. *pHighwater is always set 
 20968      ** to zero.
 20969      */
 20970      case SQLITE_DBSTATUS_CACHE_SPILL:
 20971        op = SQLITE_DBSTATUS_CACHE_WRITE+1;
 20972        /* Fall through into the next case */
 20973      case SQLITE_DBSTATUS_CACHE_HIT:
 20974      case SQLITE_DBSTATUS_CACHE_MISS:
 20975      case SQLITE_DBSTATUS_CACHE_WRITE:{
 20976        int i;
 20977        int nRet = 0;
 20978        assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
 20979        assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
 20980  
 20981        for(i=0; i<db->nDb; i++){
 20982          if( db->aDb[i].pBt ){
 20983            Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
 20984            sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
 20985          }
 20986        }
 20987        *pHighwater = 0; /* IMP: R-42420-56072 */
 20988                         /* IMP: R-54100-20147 */
 20989                         /* IMP: R-29431-39229 */
 20990        *pCurrent = nRet;
 20991        break;
 20992      }
 20993  
 20994      /* Set *pCurrent to non-zero if there are unresolved deferred foreign
 20995      ** key constraints.  Set *pCurrent to zero if all foreign key constraints
 20996      ** have been satisfied.  The *pHighwater is always set to zero.
 20997      */
 20998      case SQLITE_DBSTATUS_DEFERRED_FKS: {
 20999        *pHighwater = 0;  /* IMP: R-11967-56545 */
 21000        *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
 21001        break;
 21002      }
 21003  
 21004      default: {
 21005        rc = SQLITE_ERROR;
 21006      }
 21007    }
 21008    sqlite3_mutex_leave(db->mutex);
 21009    return rc;
 21010  }
 21011  
 21012  /************** End of status.c **********************************************/
 21013  /************** Begin file date.c ********************************************/
 21014  /*
 21015  ** 2003 October 31
 21016  **
 21017  ** The author disclaims copyright to this source code.  In place of
 21018  ** a legal notice, here is a blessing:
 21019  **
 21020  **    May you do good and not evil.
 21021  **    May you find forgiveness for yourself and forgive others.
 21022  **    May you share freely, never taking more than you give.
 21023  **
 21024  *************************************************************************
 21025  ** This file contains the C functions that implement date and time
 21026  ** functions for SQLite.  
 21027  **
 21028  ** There is only one exported symbol in this file - the function
 21029  ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
 21030  ** All other code has file scope.
 21031  **
 21032  ** SQLite processes all times and dates as julian day numbers.  The
 21033  ** dates and times are stored as the number of days since noon
 21034  ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
 21035  ** calendar system. 
 21036  **
 21037  ** 1970-01-01 00:00:00 is JD 2440587.5
 21038  ** 2000-01-01 00:00:00 is JD 2451544.5
 21039  **
 21040  ** This implementation requires years to be expressed as a 4-digit number
 21041  ** which means that only dates between 0000-01-01 and 9999-12-31 can
 21042  ** be represented, even though julian day numbers allow a much wider
 21043  ** range of dates.
 21044  **
 21045  ** The Gregorian calendar system is used for all dates and times,
 21046  ** even those that predate the Gregorian calendar.  Historians usually
 21047  ** use the julian calendar for dates prior to 1582-10-15 and for some
 21048  ** dates afterwards, depending on locale.  Beware of this difference.
 21049  **
 21050  ** The conversion algorithms are implemented based on descriptions
 21051  ** in the following text:
 21052  **
 21053  **      Jean Meeus
 21054  **      Astronomical Algorithms, 2nd Edition, 1998
 21055  **      ISBN 0-943396-61-1
 21056  **      Willmann-Bell, Inc
 21057  **      Richmond, Virginia (USA)
 21058  */
 21059  /* #include "sqliteInt.h" */
 21060  /* #include <stdlib.h> */
 21061  /* #include <assert.h> */
 21062  #include <time.h>
 21063  
 21064  #ifndef SQLITE_OMIT_DATETIME_FUNCS
 21065  
 21066  /*
 21067  ** The MSVC CRT on Windows CE may not have a localtime() function.
 21068  ** So declare a substitute.  The substitute function itself is
 21069  ** defined in "os_win.c".
 21070  */
 21071  #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
 21072      (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
 21073  struct tm *__cdecl localtime(const time_t *);
 21074  #endif
 21075  
 21076  /*
 21077  ** A structure for holding a single date and time.
 21078  */
 21079  typedef struct DateTime DateTime;
 21080  struct DateTime {
 21081    sqlite3_int64 iJD;  /* The julian day number times 86400000 */
 21082    int Y, M, D;        /* Year, month, and day */
 21083    int h, m;           /* Hour and minutes */
 21084    int tz;             /* Timezone offset in minutes */
 21085    double s;           /* Seconds */
 21086    char validJD;       /* True (1) if iJD is valid */
 21087    char rawS;          /* Raw numeric value stored in s */
 21088    char validYMD;      /* True (1) if Y,M,D are valid */
 21089    char validHMS;      /* True (1) if h,m,s are valid */
 21090    char validTZ;       /* True (1) if tz is valid */
 21091    char tzSet;         /* Timezone was set explicitly */
 21092    char isError;       /* An overflow has occurred */
 21093  };
 21094  
 21095  
 21096  /*
 21097  ** Convert zDate into one or more integers according to the conversion
 21098  ** specifier zFormat.
 21099  **
 21100  ** zFormat[] contains 4 characters for each integer converted, except for
 21101  ** the last integer which is specified by three characters.  The meaning
 21102  ** of a four-character format specifiers ABCD is:
 21103  **
 21104  **    A:   number of digits to convert.  Always "2" or "4".
 21105  **    B:   minimum value.  Always "0" or "1".
 21106  **    C:   maximum value, decoded as:
 21107  **           a:  12
 21108  **           b:  14
 21109  **           c:  24
 21110  **           d:  31
 21111  **           e:  59
 21112  **           f:  9999
 21113  **    D:   the separator character, or \000 to indicate this is the
 21114  **         last number to convert.
 21115  **
 21116  ** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
 21117  ** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
 21118  ** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
 21119  ** the 2-digit day which is the last integer in the set.
 21120  **
 21121  ** The function returns the number of successful conversions.
 21122  */
 21123  static int getDigits(const char *zDate, const char *zFormat, ...){
 21124    /* The aMx[] array translates the 3rd character of each format
 21125    ** spec into a max size:    a   b   c   d   e     f */
 21126    static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
 21127    va_list ap;
 21128    int cnt = 0;
 21129    char nextC;
 21130    va_start(ap, zFormat);
 21131    do{
 21132      char N = zFormat[0] - '0';
 21133      char min = zFormat[1] - '0';
 21134      int val = 0;
 21135      u16 max;
 21136  
 21137      assert( zFormat[2]>='a' && zFormat[2]<='f' );
 21138      max = aMx[zFormat[2] - 'a'];
 21139      nextC = zFormat[3];
 21140      val = 0;
 21141      while( N-- ){
 21142        if( !sqlite3Isdigit(*zDate) ){
 21143          goto end_getDigits;
 21144        }
 21145        val = val*10 + *zDate - '0';
 21146        zDate++;
 21147      }
 21148      if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
 21149        goto end_getDigits;
 21150      }
 21151      *va_arg(ap,int*) = val;
 21152      zDate++;
 21153      cnt++;
 21154      zFormat += 4;
 21155    }while( nextC );
 21156  end_getDigits:
 21157    va_end(ap);
 21158    return cnt;
 21159  }
 21160  
 21161  /*
 21162  ** Parse a timezone extension on the end of a date-time.
 21163  ** The extension is of the form:
 21164  **
 21165  **        (+/-)HH:MM
 21166  **
 21167  ** Or the "zulu" notation:
 21168  **
 21169  **        Z
 21170  **
 21171  ** If the parse is successful, write the number of minutes
 21172  ** of change in p->tz and return 0.  If a parser error occurs,
 21173  ** return non-zero.
 21174  **
 21175  ** A missing specifier is not considered an error.
 21176  */
 21177  static int parseTimezone(const char *zDate, DateTime *p){
 21178    int sgn = 0;
 21179    int nHr, nMn;
 21180    int c;
 21181    while( sqlite3Isspace(*zDate) ){ zDate++; }
 21182    p->tz = 0;
 21183    c = *zDate;
 21184    if( c=='-' ){
 21185      sgn = -1;
 21186    }else if( c=='+' ){
 21187      sgn = +1;
 21188    }else if( c=='Z' || c=='z' ){
 21189      zDate++;
 21190      goto zulu_time;
 21191    }else{
 21192      return c!=0;
 21193    }
 21194    zDate++;
 21195    if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
 21196      return 1;
 21197    }
 21198    zDate += 5;
 21199    p->tz = sgn*(nMn + nHr*60);
 21200  zulu_time:
 21201    while( sqlite3Isspace(*zDate) ){ zDate++; }
 21202    p->tzSet = 1;
 21203    return *zDate!=0;
 21204  }
 21205  
 21206  /*
 21207  ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
 21208  ** The HH, MM, and SS must each be exactly 2 digits.  The
 21209  ** fractional seconds FFFF can be one or more digits.
 21210  **
 21211  ** Return 1 if there is a parsing error and 0 on success.
 21212  */
 21213  static int parseHhMmSs(const char *zDate, DateTime *p){
 21214    int h, m, s;
 21215    double ms = 0.0;
 21216    if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
 21217      return 1;
 21218    }
 21219    zDate += 5;
 21220    if( *zDate==':' ){
 21221      zDate++;
 21222      if( getDigits(zDate, "20e", &s)!=1 ){
 21223        return 1;
 21224      }
 21225      zDate += 2;
 21226      if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
 21227        double rScale = 1.0;
 21228        zDate++;
 21229        while( sqlite3Isdigit(*zDate) ){
 21230          ms = ms*10.0 + *zDate - '0';
 21231          rScale *= 10.0;
 21232          zDate++;
 21233        }
 21234        ms /= rScale;
 21235      }
 21236    }else{
 21237      s = 0;
 21238    }
 21239    p->validJD = 0;
 21240    p->rawS = 0;
 21241    p->validHMS = 1;
 21242    p->h = h;
 21243    p->m = m;
 21244    p->s = s + ms;
 21245    if( parseTimezone(zDate, p) ) return 1;
 21246    p->validTZ = (p->tz!=0)?1:0;
 21247    return 0;
 21248  }
 21249  
 21250  /*
 21251  ** Put the DateTime object into its error state.
 21252  */
 21253  static void datetimeError(DateTime *p){
 21254    memset(p, 0, sizeof(*p));
 21255    p->isError = 1;
 21256  }
 21257  
 21258  /*
 21259  ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
 21260  ** that the YYYY-MM-DD is according to the Gregorian calendar.
 21261  **
 21262  ** Reference:  Meeus page 61
 21263  */
 21264  static void computeJD(DateTime *p){
 21265    int Y, M, D, A, B, X1, X2;
 21266  
 21267    if( p->validJD ) return;
 21268    if( p->validYMD ){
 21269      Y = p->Y;
 21270      M = p->M;
 21271      D = p->D;
 21272    }else{
 21273      Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
 21274      M = 1;
 21275      D = 1;
 21276    }
 21277    if( Y<-4713 || Y>9999 || p->rawS ){
 21278      datetimeError(p);
 21279      return;
 21280    }
 21281    if( M<=2 ){
 21282      Y--;
 21283      M += 12;
 21284    }
 21285    A = Y/100;
 21286    B = 2 - A + (A/4);
 21287    X1 = 36525*(Y+4716)/100;
 21288    X2 = 306001*(M+1)/10000;
 21289    p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
 21290    p->validJD = 1;
 21291    if( p->validHMS ){
 21292      p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
 21293      if( p->validTZ ){
 21294        p->iJD -= p->tz*60000;
 21295        p->validYMD = 0;
 21296        p->validHMS = 0;
 21297        p->validTZ = 0;
 21298      }
 21299    }
 21300  }
 21301  
 21302  /*
 21303  ** Parse dates of the form
 21304  **
 21305  **     YYYY-MM-DD HH:MM:SS.FFF
 21306  **     YYYY-MM-DD HH:MM:SS
 21307  **     YYYY-MM-DD HH:MM
 21308  **     YYYY-MM-DD
 21309  **
 21310  ** Write the result into the DateTime structure and return 0
 21311  ** on success and 1 if the input string is not a well-formed
 21312  ** date.
 21313  */
 21314  static int parseYyyyMmDd(const char *zDate, DateTime *p){
 21315    int Y, M, D, neg;
 21316  
 21317    if( zDate[0]=='-' ){
 21318      zDate++;
 21319      neg = 1;
 21320    }else{
 21321      neg = 0;
 21322    }
 21323    if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
 21324      return 1;
 21325    }
 21326    zDate += 10;
 21327    while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
 21328    if( parseHhMmSs(zDate, p)==0 ){
 21329      /* We got the time */
 21330    }else if( *zDate==0 ){
 21331      p->validHMS = 0;
 21332    }else{
 21333      return 1;
 21334    }
 21335    p->validJD = 0;
 21336    p->validYMD = 1;
 21337    p->Y = neg ? -Y : Y;
 21338    p->M = M;
 21339    p->D = D;
 21340    if( p->validTZ ){
 21341      computeJD(p);
 21342    }
 21343    return 0;
 21344  }
 21345  
 21346  /*
 21347  ** Set the time to the current time reported by the VFS.
 21348  **
 21349  ** Return the number of errors.
 21350  */
 21351  /*
 21352  static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
 21353    p->iJD = sqlite3StmtCurrentTime(context);
 21354    if( p->iJD>0 ){
 21355      p->validJD = 1;
 21356      return 0;
 21357    }else{
 21358      return 1;
 21359    }
 21360  }
 21361  */
 21362  
 21363  /*
 21364  ** Input "r" is a numeric quantity which might be a julian day number,
 21365  ** or the number of seconds since 1970.  If the value if r is within
 21366  ** range of a julian day number, install it as such and set validJD.
 21367  ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
 21368  */
 21369  static void setRawDateNumber(DateTime *p, double r){
 21370    p->s = r;
 21371    p->rawS = 1;
 21372    if( r>=0.0 && r<5373484.5 ){
 21373      p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
 21374      p->validJD = 1;
 21375    }
 21376  }
 21377  
 21378  /*
 21379  ** Attempt to parse the given string into a julian day number.  Return
 21380  ** the number of errors.
 21381  **
 21382  ** The following are acceptable forms for the input string:
 21383  **
 21384  **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
 21385  **      DDDD.DD 
 21386  **      now
 21387  **
 21388  ** In the first form, the +/-HH:MM is always optional.  The fractional
 21389  ** seconds extension (the ".FFF") is optional.  The seconds portion
 21390  ** (":SS.FFF") is option.  The year and date can be omitted as long
 21391  ** as there is a time string.  The time string can be omitted as long
 21392  ** as there is a year and date.
 21393  */
 21394  static int parseDateOrTime(
 21395    sqlite3_context *context, 
 21396    const char *zDate, 
 21397    DateTime *p
 21398  ){
 21399    double r;
 21400    if( parseYyyyMmDd(zDate,p)==0 ){
 21401      return 0;
 21402    }else if( parseHhMmSs(zDate, p)==0 ){
 21403      return 0;
 21404    }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
 21405      setRawDateNumber(p, r);
 21406      return 0;
 21407    }
 21408    return 1;
 21409  }
 21410  
 21411  /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
 21412  ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
 21413  ** for DateTime.iJD.
 21414  **
 21415  ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with 
 21416  ** such a large integer literal, so we have to encode it.
 21417  */
 21418  #define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
 21419  
 21420  /*
 21421  ** Return TRUE if the given julian day number is within range.
 21422  **
 21423  ** The input is the JulianDay times 86400000.
 21424  */
 21425  static int validJulianDay(sqlite3_int64 iJD){
 21426    return iJD>=0 && iJD<=INT_464269060799999;
 21427  }
 21428  
 21429  /*
 21430  ** Compute the Year, Month, and Day from the julian day number.
 21431  */
 21432  static void computeYMD(DateTime *p){
 21433    int Z, A, B, C, D, E, X1;
 21434    if( p->validYMD ) return;
 21435    if( !p->validJD ){
 21436      p->Y = 2000;
 21437      p->M = 1;
 21438      p->D = 1;
 21439    }else if( !validJulianDay(p->iJD) ){
 21440      datetimeError(p);
 21441      return;
 21442    }else{
 21443      Z = (int)((p->iJD + 43200000)/86400000);
 21444      A = (int)((Z - 1867216.25)/36524.25);
 21445      A = Z + 1 + A - (A/4);
 21446      B = A + 1524;
 21447      C = (int)((B - 122.1)/365.25);
 21448      D = (36525*(C&32767))/100;
 21449      E = (int)((B-D)/30.6001);
 21450      X1 = (int)(30.6001*E);
 21451      p->D = B - D - X1;
 21452      p->M = E<14 ? E-1 : E-13;
 21453      p->Y = p->M>2 ? C - 4716 : C - 4715;
 21454    }
 21455    p->validYMD = 1;
 21456  }
 21457  
 21458  /*
 21459  ** Compute the Hour, Minute, and Seconds from the julian day number.
 21460  */
 21461  static void computeHMS(DateTime *p){
 21462    int s;
 21463    if( p->validHMS ) return;
 21464    computeJD(p);
 21465    s = (int)((p->iJD + 43200000) % 86400000);
 21466    p->s = s/1000.0;
 21467    s = (int)p->s;
 21468    p->s -= s;
 21469    p->h = s/3600;
 21470    s -= p->h*3600;
 21471    p->m = s/60;
 21472    p->s += s - p->m*60;
 21473    p->rawS = 0;
 21474    p->validHMS = 1;
 21475  }
 21476  
 21477  /*
 21478  ** Compute both YMD and HMS
 21479  */
 21480  static void computeYMD_HMS(DateTime *p){
 21481    computeYMD(p);
 21482    computeHMS(p);
 21483  }
 21484  
 21485  /*
 21486  ** Clear the YMD and HMS and the TZ
 21487  */
 21488  static void clearYMD_HMS_TZ(DateTime *p){
 21489    p->validYMD = 0;
 21490    p->validHMS = 0;
 21491    p->validTZ = 0;
 21492  }
 21493  
 21494  #ifndef SQLITE_OMIT_LOCALTIME
 21495  /*
 21496  ** On recent Windows platforms, the localtime_s() function is available
 21497  ** as part of the "Secure CRT". It is essentially equivalent to 
 21498  ** localtime_r() available under most POSIX platforms, except that the 
 21499  ** order of the parameters is reversed.
 21500  **
 21501  ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
 21502  **
 21503  ** If the user has not indicated to use localtime_r() or localtime_s()
 21504  ** already, check for an MSVC build environment that provides 
 21505  ** localtime_s().
 21506  */
 21507  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
 21508      && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
 21509  #undef  HAVE_LOCALTIME_S
 21510  #define HAVE_LOCALTIME_S 1
 21511  #endif
 21512  
 21513  /*
 21514  ** The following routine implements the rough equivalent of localtime_r()
 21515  ** using whatever operating-system specific localtime facility that
 21516  ** is available.  This routine returns 0 on success and
 21517  ** non-zero on any kind of error.
 21518  **
 21519  ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
 21520  ** routine will always fail.
 21521  **
 21522  ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
 21523  ** library function localtime_r() is used to assist in the calculation of
 21524  ** local time.
 21525  */
 21526  static int osLocaltime(time_t *t, struct tm *pTm){
 21527    int rc;
 21528  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
 21529    struct tm *pX;
 21530  #if SQLITE_THREADSAFE>0
 21531    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 21532  #endif
 21533    sqlite3_mutex_enter(mutex);
 21534    pX = localtime(t);
 21535  #ifndef SQLITE_UNTESTABLE
 21536    if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
 21537  #endif
 21538    if( pX ) *pTm = *pX;
 21539    sqlite3_mutex_leave(mutex);
 21540    rc = pX==0;
 21541  #else
 21542  #ifndef SQLITE_UNTESTABLE
 21543    if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
 21544  #endif
 21545  #if HAVE_LOCALTIME_R
 21546    rc = localtime_r(t, pTm)==0;
 21547  #else
 21548    rc = localtime_s(pTm, t);
 21549  #endif /* HAVE_LOCALTIME_R */
 21550  #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
 21551    return rc;
 21552  }
 21553  #endif /* SQLITE_OMIT_LOCALTIME */
 21554  
 21555  
 21556  #ifndef SQLITE_OMIT_LOCALTIME
 21557  /*
 21558  ** Compute the difference (in milliseconds) between localtime and UTC
 21559  ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
 21560  ** return this value and set *pRc to SQLITE_OK. 
 21561  **
 21562  ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
 21563  ** is undefined in this case.
 21564  */
 21565  static sqlite3_int64 localtimeOffset(
 21566    DateTime *p,                    /* Date at which to calculate offset */
 21567    sqlite3_context *pCtx,          /* Write error here if one occurs */
 21568    int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
 21569  ){
 21570    DateTime x, y;
 21571    time_t t;
 21572    struct tm sLocal;
 21573  
 21574    /* Initialize the contents of sLocal to avoid a compiler warning. */
 21575    memset(&sLocal, 0, sizeof(sLocal));
 21576  
 21577    x = *p;
 21578    computeYMD_HMS(&x);
 21579    if( x.Y<1971 || x.Y>=2038 ){
 21580      /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
 21581      ** works for years between 1970 and 2037. For dates outside this range,
 21582      ** SQLite attempts to map the year into an equivalent year within this
 21583      ** range, do the calculation, then map the year back.
 21584      */
 21585      x.Y = 2000;
 21586      x.M = 1;
 21587      x.D = 1;
 21588      x.h = 0;
 21589      x.m = 0;
 21590      x.s = 0.0;
 21591    } else {
 21592      int s = (int)(x.s + 0.5);
 21593      x.s = s;
 21594    }
 21595    x.tz = 0;
 21596    x.validJD = 0;
 21597    computeJD(&x);
 21598    t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
 21599    if( osLocaltime(&t, &sLocal) ){
 21600      sqlite3_result_error(pCtx, "local time unavailable", -1);
 21601      *pRc = SQLITE_ERROR;
 21602      return 0;
 21603    }
 21604    y.Y = sLocal.tm_year + 1900;
 21605    y.M = sLocal.tm_mon + 1;
 21606    y.D = sLocal.tm_mday;
 21607    y.h = sLocal.tm_hour;
 21608    y.m = sLocal.tm_min;
 21609    y.s = sLocal.tm_sec;
 21610    y.validYMD = 1;
 21611    y.validHMS = 1;
 21612    y.validJD = 0;
 21613    y.rawS = 0;
 21614    y.validTZ = 0;
 21615    y.isError = 0;
 21616    computeJD(&y);
 21617    *pRc = SQLITE_OK;
 21618    return y.iJD - x.iJD;
 21619  }
 21620  #endif /* SQLITE_OMIT_LOCALTIME */
 21621  
 21622  /*
 21623  ** The following table defines various date transformations of the form
 21624  **
 21625  **            'NNN days'
 21626  **
 21627  ** Where NNN is an arbitrary floating-point number and "days" can be one
 21628  ** of several units of time.
 21629  */
 21630  static const struct {
 21631    u8 eType;           /* Transformation type code */
 21632    u8 nName;           /* Length of th name */
 21633    char *zName;        /* Name of the transformation */
 21634    double rLimit;      /* Maximum NNN value for this transform */
 21635    double rXform;      /* Constant used for this transform */
 21636  } aXformType[] = {
 21637    { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
 21638    { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
 21639    { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
 21640    { 0, 3, "day",    5373485.0,      86400000.0                  },
 21641    { 1, 5, "month",  176546.0,       30.0*86400000.0             },
 21642    { 2, 4, "year",   14713.0,        365.0*86400000.0            },
 21643  };
 21644  
 21645  /*
 21646  ** Process a modifier to a date-time stamp.  The modifiers are
 21647  ** as follows:
 21648  **
 21649  **     NNN days
 21650  **     NNN hours
 21651  **     NNN minutes
 21652  **     NNN.NNNN seconds
 21653  **     NNN months
 21654  **     NNN years
 21655  **     start of month
 21656  **     start of year
 21657  **     start of week
 21658  **     start of day
 21659  **     weekday N
 21660  **     unixepoch
 21661  **     localtime
 21662  **     utc
 21663  **
 21664  ** Return 0 on success and 1 if there is any kind of error. If the error
 21665  ** is in a system call (i.e. localtime()), then an error message is written
 21666  ** to context pCtx. If the error is an unrecognized modifier, no error is
 21667  ** written to pCtx.
 21668  */
 21669  static int parseModifier(
 21670    sqlite3_context *pCtx,      /* Function context */
 21671    const char *z,              /* The text of the modifier */
 21672    int n,                      /* Length of zMod in bytes */
 21673    DateTime *p                 /* The date/time value to be modified */
 21674  ){
 21675    int rc = 1;
 21676    double r;
 21677    switch(sqlite3UpperToLower[(u8)z[0]] ){
 21678  #ifndef SQLITE_OMIT_LOCALTIME
 21679      case 'l': {
 21680        /*    localtime
 21681        **
 21682        ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
 21683        ** show local time.
 21684        */
 21685        if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
 21686          computeJD(p);
 21687          p->iJD += localtimeOffset(p, pCtx, &rc);
 21688          clearYMD_HMS_TZ(p);
 21689        }
 21690        break;
 21691      }
 21692  #endif
 21693      case 'u': {
 21694        /*
 21695        **    unixepoch
 21696        **
 21697        ** Treat the current value of p->s as the number of
 21698        ** seconds since 1970.  Convert to a real julian day number.
 21699        */
 21700        if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
 21701          r = p->s*1000.0 + 210866760000000.0;
 21702          if( r>=0.0 && r<464269060800000.0 ){
 21703            clearYMD_HMS_TZ(p);
 21704            p->iJD = (sqlite3_int64)r;
 21705            p->validJD = 1;
 21706            p->rawS = 0;
 21707            rc = 0;
 21708          }
 21709        }
 21710  #ifndef SQLITE_OMIT_LOCALTIME
 21711        else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
 21712          if( p->tzSet==0 ){
 21713            sqlite3_int64 c1;
 21714            computeJD(p);
 21715            c1 = localtimeOffset(p, pCtx, &rc);
 21716            if( rc==SQLITE_OK ){
 21717              p->iJD -= c1;
 21718              clearYMD_HMS_TZ(p);
 21719              p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
 21720            }
 21721            p->tzSet = 1;
 21722          }else{
 21723            rc = SQLITE_OK;
 21724          }
 21725        }
 21726  #endif
 21727        break;
 21728      }
 21729      case 'w': {
 21730        /*
 21731        **    weekday N
 21732        **
 21733        ** Move the date to the same time on the next occurrence of
 21734        ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
 21735        ** date is already on the appropriate weekday, this is a no-op.
 21736        */
 21737        if( sqlite3_strnicmp(z, "weekday ", 8)==0
 21738                 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
 21739                 && (n=(int)r)==r && n>=0 && r<7 ){
 21740          sqlite3_int64 Z;
 21741          computeYMD_HMS(p);
 21742          p->validTZ = 0;
 21743          p->validJD = 0;
 21744          computeJD(p);
 21745          Z = ((p->iJD + 129600000)/86400000) % 7;
 21746          if( Z>n ) Z -= 7;
 21747          p->iJD += (n - Z)*86400000;
 21748          clearYMD_HMS_TZ(p);
 21749          rc = 0;
 21750        }
 21751        break;
 21752      }
 21753      case 's': {
 21754        /*
 21755        **    start of TTTTT
 21756        **
 21757        ** Move the date backwards to the beginning of the current day,
 21758        ** or month or year.
 21759        */
 21760        if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
 21761        if( !p->validJD && !p->validYMD && !p->validHMS ) break;
 21762        z += 9;
 21763        computeYMD(p);
 21764        p->validHMS = 1;
 21765        p->h = p->m = 0;
 21766        p->s = 0.0;
 21767        p->rawS = 0;
 21768        p->validTZ = 0;
 21769        p->validJD = 0;
 21770        if( sqlite3_stricmp(z,"month")==0 ){
 21771          p->D = 1;
 21772          rc = 0;
 21773        }else if( sqlite3_stricmp(z,"year")==0 ){
 21774          p->M = 1;
 21775          p->D = 1;
 21776          rc = 0;
 21777        }else if( sqlite3_stricmp(z,"day")==0 ){
 21778          rc = 0;
 21779        }
 21780        break;
 21781      }
 21782      case '+':
 21783      case '-':
 21784      case '0':
 21785      case '1':
 21786      case '2':
 21787      case '3':
 21788      case '4':
 21789      case '5':
 21790      case '6':
 21791      case '7':
 21792      case '8':
 21793      case '9': {
 21794        double rRounder;
 21795        int i;
 21796        for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
 21797        if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
 21798          rc = 1;
 21799          break;
 21800        }
 21801        if( z[n]==':' ){
 21802          /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
 21803          ** specified number of hours, minutes, seconds, and fractional seconds
 21804          ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
 21805          ** omitted.
 21806          */
 21807          const char *z2 = z;
 21808          DateTime tx;
 21809          sqlite3_int64 day;
 21810          if( !sqlite3Isdigit(*z2) ) z2++;
 21811          memset(&tx, 0, sizeof(tx));
 21812          if( parseHhMmSs(z2, &tx) ) break;
 21813          computeJD(&tx);
 21814          tx.iJD -= 43200000;
 21815          day = tx.iJD/86400000;
 21816          tx.iJD -= day*86400000;
 21817          if( z[0]=='-' ) tx.iJD = -tx.iJD;
 21818          computeJD(p);
 21819          clearYMD_HMS_TZ(p);
 21820          p->iJD += tx.iJD;
 21821          rc = 0;
 21822          break;
 21823        }
 21824  
 21825        /* If control reaches this point, it means the transformation is
 21826        ** one of the forms like "+NNN days".  */
 21827        z += n;
 21828        while( sqlite3Isspace(*z) ) z++;
 21829        n = sqlite3Strlen30(z);
 21830        if( n>10 || n<3 ) break;
 21831        if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
 21832        computeJD(p);
 21833        rc = 1;
 21834        rRounder = r<0 ? -0.5 : +0.5;
 21835        for(i=0; i<ArraySize(aXformType); i++){
 21836          if( aXformType[i].nName==n
 21837           && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
 21838           && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
 21839          ){
 21840            switch( aXformType[i].eType ){
 21841              case 1: { /* Special processing to add months */
 21842                int x;
 21843                computeYMD_HMS(p);
 21844                p->M += (int)r;
 21845                x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
 21846                p->Y += x;
 21847                p->M -= x*12;
 21848                p->validJD = 0;
 21849                r -= (int)r;
 21850                break;
 21851              }
 21852              case 2: { /* Special processing to add years */
 21853                int y = (int)r;
 21854                computeYMD_HMS(p);
 21855                p->Y += y;
 21856                p->validJD = 0;
 21857                r -= (int)r;
 21858                break;
 21859              }
 21860            }
 21861            computeJD(p);
 21862            p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
 21863            rc = 0;
 21864            break;
 21865          }
 21866        }
 21867        clearYMD_HMS_TZ(p);
 21868        break;
 21869      }
 21870      default: {
 21871        break;
 21872      }
 21873    }
 21874    return rc;
 21875  }
 21876  
 21877  /*
 21878  ** Process time function arguments.  argv[0] is a date-time stamp.
 21879  ** argv[1] and following are modifiers.  Parse them all and write
 21880  ** the resulting time into the DateTime structure p.  Return 0
 21881  ** on success and 1 if there are any errors.
 21882  **
 21883  ** If there are zero parameters (if even argv[0] is undefined)
 21884  ** then assume a default value of "now" for argv[0].
 21885  */
 21886  static int isDate(
 21887    sqlite3_context *context, 
 21888    int argc, 
 21889    sqlite3_value **argv, 
 21890    DateTime *p
 21891  ){
 21892    int i, n;
 21893    const unsigned char *z;
 21894    int eType;
 21895    memset(p, 0, sizeof(*p));
 21896    if( argc==0 ){
 21897      return 1;
 21898    }
 21899    if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
 21900                     || eType==SQLITE_INTEGER ){
 21901      setRawDateNumber(p, sqlite3_value_double(argv[0]));
 21902    }else{
 21903      z = sqlite3_value_text(argv[0]);
 21904      if( !z || parseDateOrTime(context, (char*)z, p) ){
 21905        return 1;
 21906      }
 21907    }
 21908    for(i=1; i<argc; i++){
 21909      z = sqlite3_value_text(argv[i]);
 21910      n = sqlite3_value_bytes(argv[i]);
 21911      if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
 21912    }
 21913    computeJD(p);
 21914    if( p->isError || !validJulianDay(p->iJD) ) return 1;
 21915    return 0;
 21916  }
 21917  
 21918  
 21919  /*
 21920  ** The following routines implement the various date and time functions
 21921  ** of SQLite.
 21922  */
 21923  
 21924  /*
 21925  **    julianday( TIMESTRING, MOD, MOD, ...)
 21926  **
 21927  ** Return the julian day number of the date specified in the arguments
 21928  */
 21929  static void juliandayFunc(
 21930    sqlite3_context *context,
 21931    int argc,
 21932    sqlite3_value **argv
 21933  ){
 21934    DateTime x;
 21935    if( isDate(context, argc, argv, &x)==0 ){
 21936      computeJD(&x);
 21937      sqlite3_result_double(context, x.iJD/86400000.0);
 21938    }
 21939  }
 21940  
 21941  /*
 21942  **    datetime( TIMESTRING, MOD, MOD, ...)
 21943  **
 21944  ** Return YYYY-MM-DD HH:MM:SS
 21945  */
 21946  static void datetimeFunc(
 21947    sqlite3_context *context,
 21948    int argc,
 21949    sqlite3_value **argv
 21950  ){
 21951    DateTime x;
 21952    if( isDate(context, argc, argv, &x)==0 ){
 21953      char zBuf[100];
 21954      computeYMD_HMS(&x);
 21955      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
 21956                       x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
 21957      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 21958    }
 21959  }
 21960  
 21961  /*
 21962  **    time( TIMESTRING, MOD, MOD, ...)
 21963  **
 21964  ** Return HH:MM:SS
 21965  */
 21966  static void timeFunc(
 21967    sqlite3_context *context,
 21968    int argc,
 21969    sqlite3_value **argv
 21970  ){
 21971    DateTime x;
 21972    if( isDate(context, argc, argv, &x)==0 ){
 21973      char zBuf[100];
 21974      computeHMS(&x);
 21975      sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
 21976      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 21977    }
 21978  }
 21979  
 21980  /*
 21981  **    date( TIMESTRING, MOD, MOD, ...)
 21982  **
 21983  ** Return YYYY-MM-DD
 21984  */
 21985  static void dateFunc(
 21986    sqlite3_context *context,
 21987    int argc,
 21988    sqlite3_value **argv
 21989  ){
 21990    DateTime x;
 21991    if( isDate(context, argc, argv, &x)==0 ){
 21992      char zBuf[100];
 21993      computeYMD(&x);
 21994      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
 21995      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 21996    }
 21997  }
 21998  
 21999  /*
 22000  **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
 22001  **
 22002  ** Return a string described by FORMAT.  Conversions as follows:
 22003  **
 22004  **   %d  day of month
 22005  **   %f  ** fractional seconds  SS.SSS
 22006  **   %H  hour 00-24
 22007  **   %j  day of year 000-366
 22008  **   %J  ** julian day number
 22009  **   %m  month 01-12
 22010  **   %M  minute 00-59
 22011  **   %s  seconds since 1970-01-01
 22012  **   %S  seconds 00-59
 22013  **   %w  day of week 0-6  sunday==0
 22014  **   %W  week of year 00-53
 22015  **   %Y  year 0000-9999
 22016  **   %%  %
 22017  */
 22018  static void strftimeFunc(
 22019    sqlite3_context *context,
 22020    int argc,
 22021    sqlite3_value **argv
 22022  ){
 22023    DateTime x;
 22024    u64 n;
 22025    size_t i,j;
 22026    char *z;
 22027    sqlite3 *db;
 22028    const char *zFmt;
 22029    char zBuf[100];
 22030    if( argc==0 ) return;
 22031    zFmt = (const char*)sqlite3_value_text(argv[0]);
 22032    if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
 22033    db = sqlite3_context_db_handle(context);
 22034    for(i=0, n=1; zFmt[i]; i++, n++){
 22035      if( zFmt[i]=='%' ){
 22036        switch( zFmt[i+1] ){
 22037          case 'd':
 22038          case 'H':
 22039          case 'm':
 22040          case 'M':
 22041          case 'S':
 22042          case 'W':
 22043            n++;
 22044            /* fall thru */
 22045          case 'w':
 22046          case '%':
 22047            break;
 22048          case 'f':
 22049            n += 8;
 22050            break;
 22051          case 'j':
 22052            n += 3;
 22053            break;
 22054          case 'Y':
 22055            n += 8;
 22056            break;
 22057          case 's':
 22058          case 'J':
 22059            n += 50;
 22060            break;
 22061          default:
 22062            return;  /* ERROR.  return a NULL */
 22063        }
 22064        i++;
 22065      }
 22066    }
 22067    testcase( n==sizeof(zBuf)-1 );
 22068    testcase( n==sizeof(zBuf) );
 22069    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
 22070    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
 22071    if( n<sizeof(zBuf) ){
 22072      z = zBuf;
 22073    }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 22074      sqlite3_result_error_toobig(context);
 22075      return;
 22076    }else{
 22077      z = sqlite3DbMallocRawNN(db, (int)n);
 22078      if( z==0 ){
 22079        sqlite3_result_error_nomem(context);
 22080        return;
 22081      }
 22082    }
 22083    computeJD(&x);
 22084    computeYMD_HMS(&x);
 22085    for(i=j=0; zFmt[i]; i++){
 22086      if( zFmt[i]!='%' ){
 22087        z[j++] = zFmt[i];
 22088      }else{
 22089        i++;
 22090        switch( zFmt[i] ){
 22091          case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
 22092          case 'f': {
 22093            double s = x.s;
 22094            if( s>59.999 ) s = 59.999;
 22095            sqlite3_snprintf(7, &z[j],"%06.3f", s);
 22096            j += sqlite3Strlen30(&z[j]);
 22097            break;
 22098          }
 22099          case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
 22100          case 'W': /* Fall thru */
 22101          case 'j': {
 22102            int nDay;             /* Number of days since 1st day of year */
 22103            DateTime y = x;
 22104            y.validJD = 0;
 22105            y.M = 1;
 22106            y.D = 1;
 22107            computeJD(&y);
 22108            nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
 22109            if( zFmt[i]=='W' ){
 22110              int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
 22111              wd = (int)(((x.iJD+43200000)/86400000)%7);
 22112              sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
 22113              j += 2;
 22114            }else{
 22115              sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
 22116              j += 3;
 22117            }
 22118            break;
 22119          }
 22120          case 'J': {
 22121            sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
 22122            j+=sqlite3Strlen30(&z[j]);
 22123            break;
 22124          }
 22125          case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
 22126          case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
 22127          case 's': {
 22128            sqlite3_snprintf(30,&z[j],"%lld",
 22129                             (i64)(x.iJD/1000 - 21086676*(i64)10000));
 22130            j += sqlite3Strlen30(&z[j]);
 22131            break;
 22132          }
 22133          case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
 22134          case 'w': {
 22135            z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
 22136            break;
 22137          }
 22138          case 'Y': {
 22139            sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
 22140            break;
 22141          }
 22142          default:   z[j++] = '%'; break;
 22143        }
 22144      }
 22145    }
 22146    z[j] = 0;
 22147    sqlite3_result_text(context, z, -1,
 22148                        z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
 22149  }
 22150  #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
 22151  
 22152  #ifdef SQLITE_OMIT_DATETIME_FUNCS
 22153  /*
 22154  ** If the library is compiled to omit the full-scale date and time
 22155  ** handling (to get a smaller binary), the following minimal version
 22156  ** of the functions current_time(), current_date() and current_timestamp()
 22157  ** are included instead. This is to support column declarations that
 22158  ** include "DEFAULT CURRENT_TIME" etc.
 22159  **
 22160  ** This function uses the C-library functions time(), gmtime()
 22161  ** and strftime(). The format string to pass to strftime() is supplied
 22162  ** as the user-data for the function.
 22163  */
 22164  static void currentTimeFunc(
 22165    sqlite3_context *context,
 22166    int argc,
 22167    sqlite3_value **argv
 22168  ){
 22169    time_t t;
 22170    char *zFormat = (char *)sqlite3_user_data(context);
 22171    sqlite3_int64 iT;
 22172    struct tm *pTm;
 22173    struct tm sNow;
 22174    char zBuf[20];
 22175  
 22176    UNUSED_PARAMETER(argc);
 22177    UNUSED_PARAMETER(argv);
 22178  
 22179    iT = sqlite3StmtCurrentTime(context);
 22180    if( iT<=0 ) return;
 22181    t = iT/1000 - 10000*(sqlite3_int64)21086676;
 22182  #if HAVE_GMTIME_R
 22183    pTm = gmtime_r(&t, &sNow);
 22184  #else
 22185    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 22186    pTm = gmtime(&t);
 22187    if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
 22188    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 22189  #endif
 22190    if( pTm ){
 22191      strftime(zBuf, 20, zFormat, &sNow);
 22192      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
 22193    }
 22194  }
 22195  #endif
 22196  
 22197  /*
 22198  ** This function registered all of the above C functions as SQL
 22199  ** functions.  This should be the only routine in this file with
 22200  ** external linkage.
 22201  */
 22202  SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
 22203    static FuncDef aDateTimeFuncs[] = {
 22204  #ifndef SQLITE_OMIT_DATETIME_FUNCS
 22205      PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
 22206      PURE_DATE(date,             -1, 0, 0, dateFunc      ),
 22207      PURE_DATE(time,             -1, 0, 0, timeFunc      ),
 22208      PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
 22209      PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),
 22210  #else
 22211      STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
 22212      STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
 22213      STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
 22214  #endif
 22215    };
 22216    sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
 22217  }
 22218  
 22219  /************** End of date.c ************************************************/
 22220  /************** Begin file os.c **********************************************/
 22221  /*
 22222  ** 2005 November 29
 22223  **
 22224  ** The author disclaims copyright to this source code.  In place of
 22225  ** a legal notice, here is a blessing:
 22226  **
 22227  **    May you do good and not evil.
 22228  **    May you find forgiveness for yourself and forgive others.
 22229  **    May you share freely, never taking more than you give.
 22230  **
 22231  ******************************************************************************
 22232  **
 22233  ** This file contains OS interface code that is common to all
 22234  ** architectures.
 22235  */
 22236  /* #include "sqliteInt.h" */
 22237  
 22238  /*
 22239  ** If we compile with the SQLITE_TEST macro set, then the following block
 22240  ** of code will give us the ability to simulate a disk I/O error.  This
 22241  ** is used for testing the I/O recovery logic.
 22242  */
 22243  #if defined(SQLITE_TEST)
 22244  SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
 22245  SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
 22246  SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
 22247  SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
 22248  SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
 22249  SQLITE_API int sqlite3_diskfull_pending = 0;
 22250  SQLITE_API int sqlite3_diskfull = 0;
 22251  #endif /* defined(SQLITE_TEST) */
 22252  
 22253  /*
 22254  ** When testing, also keep a count of the number of open files.
 22255  */
 22256  #if defined(SQLITE_TEST)
 22257  SQLITE_API int sqlite3_open_file_count = 0;
 22258  #endif /* defined(SQLITE_TEST) */
 22259  
 22260  /*
 22261  ** The default SQLite sqlite3_vfs implementations do not allocate
 22262  ** memory (actually, os_unix.c allocates a small amount of memory
 22263  ** from within OsOpen()), but some third-party implementations may.
 22264  ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
 22265  ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
 22266  **
 22267  ** The following functions are instrumented for malloc() failure
 22268  ** testing:
 22269  **
 22270  **     sqlite3OsRead()
 22271  **     sqlite3OsWrite()
 22272  **     sqlite3OsSync()
 22273  **     sqlite3OsFileSize()
 22274  **     sqlite3OsLock()
 22275  **     sqlite3OsCheckReservedLock()
 22276  **     sqlite3OsFileControl()
 22277  **     sqlite3OsShmMap()
 22278  **     sqlite3OsOpen()
 22279  **     sqlite3OsDelete()
 22280  **     sqlite3OsAccess()
 22281  **     sqlite3OsFullPathname()
 22282  **
 22283  */
 22284  #if defined(SQLITE_TEST)
 22285  SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
 22286    #define DO_OS_MALLOC_TEST(x)                                       \
 22287    if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
 22288      void *pTstAlloc = sqlite3Malloc(10);                             \
 22289      if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
 22290      sqlite3_free(pTstAlloc);                                         \
 22291    }
 22292  #else
 22293    #define DO_OS_MALLOC_TEST(x)
 22294  #endif
 22295  
 22296  /*
 22297  ** The following routines are convenience wrappers around methods
 22298  ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
 22299  ** of this would be completely automatic if SQLite were coded using
 22300  ** C++ instead of plain old C.
 22301  */
 22302  SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
 22303    if( pId->pMethods ){
 22304      pId->pMethods->xClose(pId);
 22305      pId->pMethods = 0;
 22306    }
 22307  }
 22308  SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
 22309    DO_OS_MALLOC_TEST(id);
 22310    return id->pMethods->xRead(id, pBuf, amt, offset);
 22311  }
 22312  SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
 22313    DO_OS_MALLOC_TEST(id);
 22314    return id->pMethods->xWrite(id, pBuf, amt, offset);
 22315  }
 22316  SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
 22317    return id->pMethods->xTruncate(id, size);
 22318  }
 22319  SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
 22320    DO_OS_MALLOC_TEST(id);
 22321    return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
 22322  }
 22323  SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
 22324    DO_OS_MALLOC_TEST(id);
 22325    return id->pMethods->xFileSize(id, pSize);
 22326  }
 22327  SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
 22328    DO_OS_MALLOC_TEST(id);
 22329    return id->pMethods->xLock(id, lockType);
 22330  }
 22331  SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
 22332    return id->pMethods->xUnlock(id, lockType);
 22333  }
 22334  SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
 22335    DO_OS_MALLOC_TEST(id);
 22336    return id->pMethods->xCheckReservedLock(id, pResOut);
 22337  }
 22338  
 22339  /*
 22340  ** Use sqlite3OsFileControl() when we are doing something that might fail
 22341  ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
 22342  ** when simply tossing information over the wall to the VFS and we do not
 22343  ** really care if the VFS receives and understands the information since it
 22344  ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
 22345  ** routine has no return value since the return value would be meaningless.
 22346  */
 22347  SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
 22348    if( id->pMethods==0 ) return SQLITE_NOTFOUND;
 22349  #ifdef SQLITE_TEST
 22350    if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
 22351     && op!=SQLITE_FCNTL_LOCK_TIMEOUT
 22352    ){
 22353      /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
 22354      ** is using a regular VFS, it is called after the corresponding
 22355      ** transaction has been committed. Injecting a fault at this point
 22356      ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
 22357      ** but the transaction is committed anyway.
 22358      **
 22359      ** The core must call OsFileControl() though, not OsFileControlHint(),
 22360      ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
 22361      ** means the commit really has failed and an error should be returned
 22362      ** to the user.  */
 22363      DO_OS_MALLOC_TEST(id);
 22364    }
 22365  #endif
 22366    return id->pMethods->xFileControl(id, op, pArg);
 22367  }
 22368  SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
 22369    if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
 22370  }
 22371  
 22372  SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
 22373    int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
 22374    return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
 22375  }
 22376  SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
 22377    return id->pMethods->xDeviceCharacteristics(id);
 22378  }
 22379  #ifndef SQLITE_OMIT_WAL
 22380  SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
 22381    return id->pMethods->xShmLock(id, offset, n, flags);
 22382  }
 22383  SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
 22384    id->pMethods->xShmBarrier(id);
 22385  }
 22386  SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
 22387    return id->pMethods->xShmUnmap(id, deleteFlag);
 22388  }
 22389  SQLITE_PRIVATE int sqlite3OsShmMap(
 22390    sqlite3_file *id,               /* Database file handle */
 22391    int iPage,
 22392    int pgsz,
 22393    int bExtend,                    /* True to extend file if necessary */
 22394    void volatile **pp              /* OUT: Pointer to mapping */
 22395  ){
 22396    DO_OS_MALLOC_TEST(id);
 22397    return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
 22398  }
 22399  #endif /* SQLITE_OMIT_WAL */
 22400  
 22401  #if SQLITE_MAX_MMAP_SIZE>0
 22402  /* The real implementation of xFetch and xUnfetch */
 22403  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 22404    DO_OS_MALLOC_TEST(id);
 22405    return id->pMethods->xFetch(id, iOff, iAmt, pp);
 22406  }
 22407  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 22408    return id->pMethods->xUnfetch(id, iOff, p);
 22409  }
 22410  #else
 22411  /* No-op stubs to use when memory-mapped I/O is disabled */
 22412  SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
 22413    *pp = 0;
 22414    return SQLITE_OK;
 22415  }
 22416  SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
 22417    return SQLITE_OK;
 22418  }
 22419  #endif
 22420  
 22421  /*
 22422  ** The next group of routines are convenience wrappers around the
 22423  ** VFS methods.
 22424  */
 22425  SQLITE_PRIVATE int sqlite3OsOpen(
 22426    sqlite3_vfs *pVfs,
 22427    const char *zPath,
 22428    sqlite3_file *pFile,
 22429    int flags,
 22430    int *pFlagsOut
 22431  ){
 22432    int rc;
 22433    DO_OS_MALLOC_TEST(0);
 22434    /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
 22435    ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
 22436    ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
 22437    ** reaching the VFS. */
 22438    rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
 22439    assert( rc==SQLITE_OK || pFile->pMethods==0 );
 22440    return rc;
 22441  }
 22442  SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 22443    DO_OS_MALLOC_TEST(0);
 22444    assert( dirSync==0 || dirSync==1 );
 22445    return pVfs->xDelete(pVfs, zPath, dirSync);
 22446  }
 22447  SQLITE_PRIVATE int sqlite3OsAccess(
 22448    sqlite3_vfs *pVfs,
 22449    const char *zPath,
 22450    int flags,
 22451    int *pResOut
 22452  ){
 22453    DO_OS_MALLOC_TEST(0);
 22454    return pVfs->xAccess(pVfs, zPath, flags, pResOut);
 22455  }
 22456  SQLITE_PRIVATE int sqlite3OsFullPathname(
 22457    sqlite3_vfs *pVfs,
 22458    const char *zPath,
 22459    int nPathOut,
 22460    char *zPathOut
 22461  ){
 22462    DO_OS_MALLOC_TEST(0);
 22463    zPathOut[0] = 0;
 22464    return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
 22465  }
 22466  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 22467  SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 22468    return pVfs->xDlOpen(pVfs, zPath);
 22469  }
 22470  SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 22471    pVfs->xDlError(pVfs, nByte, zBufOut);
 22472  }
 22473  SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
 22474    return pVfs->xDlSym(pVfs, pHdle, zSym);
 22475  }
 22476  SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
 22477    pVfs->xDlClose(pVfs, pHandle);
 22478  }
 22479  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 22480  SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 22481    return pVfs->xRandomness(pVfs, nByte, zBufOut);
 22482  }
 22483  SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
 22484    return pVfs->xSleep(pVfs, nMicro);
 22485  }
 22486  SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
 22487    return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
 22488  }
 22489  SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
 22490    int rc;
 22491    /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
 22492    ** method to get the current date and time if that method is available
 22493    ** (if iVersion is 2 or greater and the function pointer is not NULL) and
 22494    ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
 22495    ** unavailable.
 22496    */
 22497    if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
 22498      rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
 22499    }else{
 22500      double r;
 22501      rc = pVfs->xCurrentTime(pVfs, &r);
 22502      *pTimeOut = (sqlite3_int64)(r*86400000.0);
 22503    }
 22504    return rc;
 22505  }
 22506  
 22507  SQLITE_PRIVATE int sqlite3OsOpenMalloc(
 22508    sqlite3_vfs *pVfs,
 22509    const char *zFile,
 22510    sqlite3_file **ppFile,
 22511    int flags,
 22512    int *pOutFlags
 22513  ){
 22514    int rc;
 22515    sqlite3_file *pFile;
 22516    pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
 22517    if( pFile ){
 22518      rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
 22519      if( rc!=SQLITE_OK ){
 22520        sqlite3_free(pFile);
 22521      }else{
 22522        *ppFile = pFile;
 22523      }
 22524    }else{
 22525      rc = SQLITE_NOMEM_BKPT;
 22526    }
 22527    return rc;
 22528  }
 22529  SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
 22530    assert( pFile );
 22531    sqlite3OsClose(pFile);
 22532    sqlite3_free(pFile);
 22533  }
 22534  
 22535  /*
 22536  ** This function is a wrapper around the OS specific implementation of
 22537  ** sqlite3_os_init(). The purpose of the wrapper is to provide the
 22538  ** ability to simulate a malloc failure, so that the handling of an
 22539  ** error in sqlite3_os_init() by the upper layers can be tested.
 22540  */
 22541  SQLITE_PRIVATE int sqlite3OsInit(void){
 22542    void *p = sqlite3_malloc(10);
 22543    if( p==0 ) return SQLITE_NOMEM_BKPT;
 22544    sqlite3_free(p);
 22545    return sqlite3_os_init();
 22546  }
 22547  
 22548  /*
 22549  ** The list of all registered VFS implementations.
 22550  */
 22551  static sqlite3_vfs * SQLITE_WSD vfsList = 0;
 22552  #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
 22553  
 22554  /*
 22555  ** Locate a VFS by name.  If no name is given, simply return the
 22556  ** first VFS on the list.
 22557  */
 22558  SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
 22559    sqlite3_vfs *pVfs = 0;
 22560  #if SQLITE_THREADSAFE
 22561    sqlite3_mutex *mutex;
 22562  #endif
 22563  #ifndef SQLITE_OMIT_AUTOINIT
 22564    int rc = sqlite3_initialize();
 22565    if( rc ) return 0;
 22566  #endif
 22567  #if SQLITE_THREADSAFE
 22568    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 22569  #endif
 22570    sqlite3_mutex_enter(mutex);
 22571    for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
 22572      if( zVfs==0 ) break;
 22573      if( strcmp(zVfs, pVfs->zName)==0 ) break;
 22574    }
 22575    sqlite3_mutex_leave(mutex);
 22576    return pVfs;
 22577  }
 22578  
 22579  /*
 22580  ** Unlink a VFS from the linked list
 22581  */
 22582  static void vfsUnlink(sqlite3_vfs *pVfs){
 22583    assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
 22584    if( pVfs==0 ){
 22585      /* No-op */
 22586    }else if( vfsList==pVfs ){
 22587      vfsList = pVfs->pNext;
 22588    }else if( vfsList ){
 22589      sqlite3_vfs *p = vfsList;
 22590      while( p->pNext && p->pNext!=pVfs ){
 22591        p = p->pNext;
 22592      }
 22593      if( p->pNext==pVfs ){
 22594        p->pNext = pVfs->pNext;
 22595      }
 22596    }
 22597  }
 22598  
 22599  /*
 22600  ** Register a VFS with the system.  It is harmless to register the same
 22601  ** VFS multiple times.  The new VFS becomes the default if makeDflt is
 22602  ** true.
 22603  */
 22604  SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
 22605    MUTEX_LOGIC(sqlite3_mutex *mutex;)
 22606  #ifndef SQLITE_OMIT_AUTOINIT
 22607    int rc = sqlite3_initialize();
 22608    if( rc ) return rc;
 22609  #endif
 22610  #ifdef SQLITE_ENABLE_API_ARMOR
 22611    if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
 22612  #endif
 22613  
 22614    MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 22615    sqlite3_mutex_enter(mutex);
 22616    vfsUnlink(pVfs);
 22617    if( makeDflt || vfsList==0 ){
 22618      pVfs->pNext = vfsList;
 22619      vfsList = pVfs;
 22620    }else{
 22621      pVfs->pNext = vfsList->pNext;
 22622      vfsList->pNext = pVfs;
 22623    }
 22624    assert(vfsList);
 22625    sqlite3_mutex_leave(mutex);
 22626    return SQLITE_OK;
 22627  }
 22628  
 22629  /*
 22630  ** Unregister a VFS so that it is no longer accessible.
 22631  */
 22632  SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
 22633    MUTEX_LOGIC(sqlite3_mutex *mutex;)
 22634  #ifndef SQLITE_OMIT_AUTOINIT
 22635    int rc = sqlite3_initialize();
 22636    if( rc ) return rc;
 22637  #endif
 22638    MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 22639    sqlite3_mutex_enter(mutex);
 22640    vfsUnlink(pVfs);
 22641    sqlite3_mutex_leave(mutex);
 22642    return SQLITE_OK;
 22643  }
 22644  
 22645  /************** End of os.c **************************************************/
 22646  /************** Begin file fault.c *******************************************/
 22647  /*
 22648  ** 2008 Jan 22
 22649  **
 22650  ** The author disclaims copyright to this source code.  In place of
 22651  ** a legal notice, here is a blessing:
 22652  **
 22653  **    May you do good and not evil.
 22654  **    May you find forgiveness for yourself and forgive others.
 22655  **    May you share freely, never taking more than you give.
 22656  **
 22657  *************************************************************************
 22658  **
 22659  ** This file contains code to support the concept of "benign" 
 22660  ** malloc failures (when the xMalloc() or xRealloc() method of the
 22661  ** sqlite3_mem_methods structure fails to allocate a block of memory
 22662  ** and returns 0). 
 22663  **
 22664  ** Most malloc failures are non-benign. After they occur, SQLite
 22665  ** abandons the current operation and returns an error code (usually
 22666  ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
 22667  ** fatal. For example, if a malloc fails while resizing a hash table, this 
 22668  ** is completely recoverable simply by not carrying out the resize. The 
 22669  ** hash table will continue to function normally.  So a malloc failure 
 22670  ** during a hash table resize is a benign fault.
 22671  */
 22672  
 22673  /* #include "sqliteInt.h" */
 22674  
 22675  #ifndef SQLITE_UNTESTABLE
 22676  
 22677  /*
 22678  ** Global variables.
 22679  */
 22680  typedef struct BenignMallocHooks BenignMallocHooks;
 22681  static SQLITE_WSD struct BenignMallocHooks {
 22682    void (*xBenignBegin)(void);
 22683    void (*xBenignEnd)(void);
 22684  } sqlite3Hooks = { 0, 0 };
 22685  
 22686  /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
 22687  ** structure.  If writable static data is unsupported on the target,
 22688  ** we have to locate the state vector at run-time.  In the more common
 22689  ** case where writable static data is supported, wsdHooks can refer directly
 22690  ** to the "sqlite3Hooks" state vector declared above.
 22691  */
 22692  #ifdef SQLITE_OMIT_WSD
 22693  # define wsdHooksInit \
 22694    BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
 22695  # define wsdHooks x[0]
 22696  #else
 22697  # define wsdHooksInit
 22698  # define wsdHooks sqlite3Hooks
 22699  #endif
 22700  
 22701  
 22702  /*
 22703  ** Register hooks to call when sqlite3BeginBenignMalloc() and
 22704  ** sqlite3EndBenignMalloc() are called, respectively.
 22705  */
 22706  SQLITE_PRIVATE void sqlite3BenignMallocHooks(
 22707    void (*xBenignBegin)(void),
 22708    void (*xBenignEnd)(void)
 22709  ){
 22710    wsdHooksInit;
 22711    wsdHooks.xBenignBegin = xBenignBegin;
 22712    wsdHooks.xBenignEnd = xBenignEnd;
 22713  }
 22714  
 22715  /*
 22716  ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
 22717  ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
 22718  ** indicates that subsequent malloc failures are non-benign.
 22719  */
 22720  SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
 22721    wsdHooksInit;
 22722    if( wsdHooks.xBenignBegin ){
 22723      wsdHooks.xBenignBegin();
 22724    }
 22725  }
 22726  SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
 22727    wsdHooksInit;
 22728    if( wsdHooks.xBenignEnd ){
 22729      wsdHooks.xBenignEnd();
 22730    }
 22731  }
 22732  
 22733  #endif   /* #ifndef SQLITE_UNTESTABLE */
 22734  
 22735  /************** End of fault.c ***********************************************/
 22736  /************** Begin file mem0.c ********************************************/
 22737  /*
 22738  ** 2008 October 28
 22739  **
 22740  ** The author disclaims copyright to this source code.  In place of
 22741  ** a legal notice, here is a blessing:
 22742  **
 22743  **    May you do good and not evil.
 22744  **    May you find forgiveness for yourself and forgive others.
 22745  **    May you share freely, never taking more than you give.
 22746  **
 22747  *************************************************************************
 22748  **
 22749  ** This file contains a no-op memory allocation drivers for use when
 22750  ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
 22751  ** here always fail.  SQLite will not operate with these drivers.  These
 22752  ** are merely placeholders.  Real drivers must be substituted using
 22753  ** sqlite3_config() before SQLite will operate.
 22754  */
 22755  /* #include "sqliteInt.h" */
 22756  
 22757  /*
 22758  ** This version of the memory allocator is the default.  It is
 22759  ** used when no other memory allocator is specified using compile-time
 22760  ** macros.
 22761  */
 22762  #ifdef SQLITE_ZERO_MALLOC
 22763  
 22764  /*
 22765  ** No-op versions of all memory allocation routines
 22766  */
 22767  static void *sqlite3MemMalloc(int nByte){ return 0; }
 22768  static void sqlite3MemFree(void *pPrior){ return; }
 22769  static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
 22770  static int sqlite3MemSize(void *pPrior){ return 0; }
 22771  static int sqlite3MemRoundup(int n){ return n; }
 22772  static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
 22773  static void sqlite3MemShutdown(void *NotUsed){ return; }
 22774  
 22775  /*
 22776  ** This routine is the only routine in this file with external linkage.
 22777  **
 22778  ** Populate the low-level memory allocation function pointers in
 22779  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 22780  */
 22781  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 22782    static const sqlite3_mem_methods defaultMethods = {
 22783       sqlite3MemMalloc,
 22784       sqlite3MemFree,
 22785       sqlite3MemRealloc,
 22786       sqlite3MemSize,
 22787       sqlite3MemRoundup,
 22788       sqlite3MemInit,
 22789       sqlite3MemShutdown,
 22790       0
 22791    };
 22792    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 22793  }
 22794  
 22795  #endif /* SQLITE_ZERO_MALLOC */
 22796  
 22797  /************** End of mem0.c ************************************************/
 22798  /************** Begin file mem1.c ********************************************/
 22799  /*
 22800  ** 2007 August 14
 22801  **
 22802  ** The author disclaims copyright to this source code.  In place of
 22803  ** a legal notice, here is a blessing:
 22804  **
 22805  **    May you do good and not evil.
 22806  **    May you find forgiveness for yourself and forgive others.
 22807  **    May you share freely, never taking more than you give.
 22808  **
 22809  *************************************************************************
 22810  **
 22811  ** This file contains low-level memory allocation drivers for when
 22812  ** SQLite will use the standard C-library malloc/realloc/free interface
 22813  ** to obtain the memory it needs.
 22814  **
 22815  ** This file contains implementations of the low-level memory allocation
 22816  ** routines specified in the sqlite3_mem_methods object.  The content of
 22817  ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
 22818  ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
 22819  ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
 22820  ** default configuration is to use memory allocation routines in this
 22821  ** file.
 22822  **
 22823  ** C-preprocessor macro summary:
 22824  **
 22825  **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
 22826  **                                the malloc_usable_size() interface exists
 22827  **                                on the target platform.  Or, this symbol
 22828  **                                can be set manually, if desired.
 22829  **                                If an equivalent interface exists by
 22830  **                                a different name, using a separate -D
 22831  **                                option to rename it.
 22832  **
 22833  **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
 22834  **                                memory allocator.  Set this symbol to enable
 22835  **                                building on older macs.
 22836  **
 22837  **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
 22838  **                                _msize() on windows systems.  This might
 22839  **                                be necessary when compiling for Delphi,
 22840  **                                for example.
 22841  */
 22842  /* #include "sqliteInt.h" */
 22843  
 22844  /*
 22845  ** This version of the memory allocator is the default.  It is
 22846  ** used when no other memory allocator is specified using compile-time
 22847  ** macros.
 22848  */
 22849  #ifdef SQLITE_SYSTEM_MALLOC
 22850  #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 22851  
 22852  /*
 22853  ** Use the zone allocator available on apple products unless the
 22854  ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
 22855  */
 22856  #include <sys/sysctl.h>
 22857  #include <malloc/malloc.h>
 22858  #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
 22859  #include <libkern/OSAtomic.h>
 22860  #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
 22861  static malloc_zone_t* _sqliteZone_;
 22862  #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
 22863  #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
 22864  #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
 22865  #define SQLITE_MALLOCSIZE(x) \
 22866          (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
 22867  
 22868  #else /* if not __APPLE__ */
 22869  
 22870  /*
 22871  ** Use standard C library malloc and free on non-Apple systems.  
 22872  ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
 22873  */
 22874  #define SQLITE_MALLOC(x)             malloc(x)
 22875  #define SQLITE_FREE(x)               free(x)
 22876  #define SQLITE_REALLOC(x,y)          realloc((x),(y))
 22877  
 22878  /*
 22879  ** The malloc.h header file is needed for malloc_usable_size() function
 22880  ** on some systems (e.g. Linux).
 22881  */
 22882  #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
 22883  #  define SQLITE_USE_MALLOC_H 1
 22884  #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
 22885  /*
 22886  ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
 22887  ** use of _msize() is automatic, but can be disabled by compiling with
 22888  ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
 22889  ** the malloc.h header file.
 22890  */
 22891  #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
 22892  #  define SQLITE_USE_MALLOC_H
 22893  #  define SQLITE_USE_MSIZE
 22894  #endif
 22895  
 22896  /*
 22897  ** Include the malloc.h header file, if necessary.  Also set define macro
 22898  ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
 22899  ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
 22900  ** The memory size function can always be overridden manually by defining
 22901  ** the macro SQLITE_MALLOCSIZE to the desired function name.
 22902  */
 22903  #if defined(SQLITE_USE_MALLOC_H)
 22904  #  include <malloc.h>
 22905  #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
 22906  #    if !defined(SQLITE_MALLOCSIZE)
 22907  #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
 22908  #    endif
 22909  #  elif defined(SQLITE_USE_MSIZE)
 22910  #    if !defined(SQLITE_MALLOCSIZE)
 22911  #      define SQLITE_MALLOCSIZE      _msize
 22912  #    endif
 22913  #  endif
 22914  #endif /* defined(SQLITE_USE_MALLOC_H) */
 22915  
 22916  #endif /* __APPLE__ or not __APPLE__ */
 22917  
 22918  /*
 22919  ** Like malloc(), but remember the size of the allocation
 22920  ** so that we can find it later using sqlite3MemSize().
 22921  **
 22922  ** For this low-level routine, we are guaranteed that nByte>0 because
 22923  ** cases of nByte<=0 will be intercepted and dealt with by higher level
 22924  ** routines.
 22925  */
 22926  static void *sqlite3MemMalloc(int nByte){
 22927  #ifdef SQLITE_MALLOCSIZE
 22928    void *p;
 22929    testcase( ROUND8(nByte)==nByte );
 22930    p = SQLITE_MALLOC( nByte );
 22931    if( p==0 ){
 22932      testcase( sqlite3GlobalConfig.xLog!=0 );
 22933      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 22934    }
 22935    return p;
 22936  #else
 22937    sqlite3_int64 *p;
 22938    assert( nByte>0 );
 22939    testcase( ROUND8(nByte)!=nByte );
 22940    p = SQLITE_MALLOC( nByte+8 );
 22941    if( p ){
 22942      p[0] = nByte;
 22943      p++;
 22944    }else{
 22945      testcase( sqlite3GlobalConfig.xLog!=0 );
 22946      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
 22947    }
 22948    return (void *)p;
 22949  #endif
 22950  }
 22951  
 22952  /*
 22953  ** Like free() but works for allocations obtained from sqlite3MemMalloc()
 22954  ** or sqlite3MemRealloc().
 22955  **
 22956  ** For this low-level routine, we already know that pPrior!=0 since
 22957  ** cases where pPrior==0 will have been intecepted and dealt with
 22958  ** by higher-level routines.
 22959  */
 22960  static void sqlite3MemFree(void *pPrior){
 22961  #ifdef SQLITE_MALLOCSIZE
 22962    SQLITE_FREE(pPrior);
 22963  #else
 22964    sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 22965    assert( pPrior!=0 );
 22966    p--;
 22967    SQLITE_FREE(p);
 22968  #endif
 22969  }
 22970  
 22971  /*
 22972  ** Report the allocated size of a prior return from xMalloc()
 22973  ** or xRealloc().
 22974  */
 22975  static int sqlite3MemSize(void *pPrior){
 22976  #ifdef SQLITE_MALLOCSIZE
 22977    assert( pPrior!=0 );
 22978    return (int)SQLITE_MALLOCSIZE(pPrior);
 22979  #else
 22980    sqlite3_int64 *p;
 22981    assert( pPrior!=0 );
 22982    p = (sqlite3_int64*)pPrior;
 22983    p--;
 22984    return (int)p[0];
 22985  #endif
 22986  }
 22987  
 22988  /*
 22989  ** Like realloc().  Resize an allocation previously obtained from
 22990  ** sqlite3MemMalloc().
 22991  **
 22992  ** For this low-level interface, we know that pPrior!=0.  Cases where
 22993  ** pPrior==0 while have been intercepted by higher-level routine and
 22994  ** redirected to xMalloc.  Similarly, we know that nByte>0 because
 22995  ** cases where nByte<=0 will have been intercepted by higher-level
 22996  ** routines and redirected to xFree.
 22997  */
 22998  static void *sqlite3MemRealloc(void *pPrior, int nByte){
 22999  #ifdef SQLITE_MALLOCSIZE
 23000    void *p = SQLITE_REALLOC(pPrior, nByte);
 23001    if( p==0 ){
 23002      testcase( sqlite3GlobalConfig.xLog!=0 );
 23003      sqlite3_log(SQLITE_NOMEM,
 23004        "failed memory resize %u to %u bytes",
 23005        SQLITE_MALLOCSIZE(pPrior), nByte);
 23006    }
 23007    return p;
 23008  #else
 23009    sqlite3_int64 *p = (sqlite3_int64*)pPrior;
 23010    assert( pPrior!=0 && nByte>0 );
 23011    assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
 23012    p--;
 23013    p = SQLITE_REALLOC(p, nByte+8 );
 23014    if( p ){
 23015      p[0] = nByte;
 23016      p++;
 23017    }else{
 23018      testcase( sqlite3GlobalConfig.xLog!=0 );
 23019      sqlite3_log(SQLITE_NOMEM,
 23020        "failed memory resize %u to %u bytes",
 23021        sqlite3MemSize(pPrior), nByte);
 23022    }
 23023    return (void*)p;
 23024  #endif
 23025  }
 23026  
 23027  /*
 23028  ** Round up a request size to the next valid allocation size.
 23029  */
 23030  static int sqlite3MemRoundup(int n){
 23031    return ROUND8(n);
 23032  }
 23033  
 23034  /*
 23035  ** Initialize this module.
 23036  */
 23037  static int sqlite3MemInit(void *NotUsed){
 23038  #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
 23039    int cpuCount;
 23040    size_t len;
 23041    if( _sqliteZone_ ){
 23042      return SQLITE_OK;
 23043    }
 23044    len = sizeof(cpuCount);
 23045    /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
 23046    sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
 23047    if( cpuCount>1 ){
 23048      /* defer MT decisions to system malloc */
 23049      _sqliteZone_ = malloc_default_zone();
 23050    }else{
 23051      /* only 1 core, use our own zone to contention over global locks, 
 23052      ** e.g. we have our own dedicated locks */
 23053      _sqliteZone_ = malloc_create_zone(4096, 0);
 23054      malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
 23055    }
 23056  #endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
 23057    UNUSED_PARAMETER(NotUsed);
 23058    return SQLITE_OK;
 23059  }
 23060  
 23061  /*
 23062  ** Deinitialize this module.
 23063  */
 23064  static void sqlite3MemShutdown(void *NotUsed){
 23065    UNUSED_PARAMETER(NotUsed);
 23066    return;
 23067  }
 23068  
 23069  /*
 23070  ** This routine is the only routine in this file with external linkage.
 23071  **
 23072  ** Populate the low-level memory allocation function pointers in
 23073  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 23074  */
 23075  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 23076    static const sqlite3_mem_methods defaultMethods = {
 23077       sqlite3MemMalloc,
 23078       sqlite3MemFree,
 23079       sqlite3MemRealloc,
 23080       sqlite3MemSize,
 23081       sqlite3MemRoundup,
 23082       sqlite3MemInit,
 23083       sqlite3MemShutdown,
 23084       0
 23085    };
 23086    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 23087  }
 23088  
 23089  #endif /* SQLITE_SYSTEM_MALLOC */
 23090  
 23091  /************** End of mem1.c ************************************************/
 23092  /************** Begin file mem2.c ********************************************/
 23093  /*
 23094  ** 2007 August 15
 23095  **
 23096  ** The author disclaims copyright to this source code.  In place of
 23097  ** a legal notice, here is a blessing:
 23098  **
 23099  **    May you do good and not evil.
 23100  **    May you find forgiveness for yourself and forgive others.
 23101  **    May you share freely, never taking more than you give.
 23102  **
 23103  *************************************************************************
 23104  **
 23105  ** This file contains low-level memory allocation drivers for when
 23106  ** SQLite will use the standard C-library malloc/realloc/free interface
 23107  ** to obtain the memory it needs while adding lots of additional debugging
 23108  ** information to each allocation in order to help detect and fix memory
 23109  ** leaks and memory usage errors.
 23110  **
 23111  ** This file contains implementations of the low-level memory allocation
 23112  ** routines specified in the sqlite3_mem_methods object.
 23113  */
 23114  /* #include "sqliteInt.h" */
 23115  
 23116  /*
 23117  ** This version of the memory allocator is used only if the
 23118  ** SQLITE_MEMDEBUG macro is defined
 23119  */
 23120  #ifdef SQLITE_MEMDEBUG
 23121  
 23122  /*
 23123  ** The backtrace functionality is only available with GLIBC
 23124  */
 23125  #ifdef __GLIBC__
 23126    extern int backtrace(void**,int);
 23127    extern void backtrace_symbols_fd(void*const*,int,int);
 23128  #else
 23129  # define backtrace(A,B) 1
 23130  # define backtrace_symbols_fd(A,B,C)
 23131  #endif
 23132  /* #include <stdio.h> */
 23133  
 23134  /*
 23135  ** Each memory allocation looks like this:
 23136  **
 23137  **  ------------------------------------------------------------------------
 23138  **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
 23139  **  ------------------------------------------------------------------------
 23140  **
 23141  ** The application code sees only a pointer to the allocation.  We have
 23142  ** to back up from the allocation pointer to find the MemBlockHdr.  The
 23143  ** MemBlockHdr tells us the size of the allocation and the number of
 23144  ** backtrace pointers.  There is also a guard word at the end of the
 23145  ** MemBlockHdr.
 23146  */
 23147  struct MemBlockHdr {
 23148    i64 iSize;                          /* Size of this allocation */
 23149    struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
 23150    char nBacktrace;                    /* Number of backtraces on this alloc */
 23151    char nBacktraceSlots;               /* Available backtrace slots */
 23152    u8 nTitle;                          /* Bytes of title; includes '\0' */
 23153    u8 eType;                           /* Allocation type code */
 23154    int iForeGuard;                     /* Guard word for sanity */
 23155  };
 23156  
 23157  /*
 23158  ** Guard words
 23159  */
 23160  #define FOREGUARD 0x80F5E153
 23161  #define REARGUARD 0xE4676B53
 23162  
 23163  /*
 23164  ** Number of malloc size increments to track.
 23165  */
 23166  #define NCSIZE  1000
 23167  
 23168  /*
 23169  ** All of the static variables used by this module are collected
 23170  ** into a single structure named "mem".  This is to keep the
 23171  ** static variables organized and to reduce namespace pollution
 23172  ** when this module is combined with other in the amalgamation.
 23173  */
 23174  static struct {
 23175    
 23176    /*
 23177    ** Mutex to control access to the memory allocation subsystem.
 23178    */
 23179    sqlite3_mutex *mutex;
 23180  
 23181    /*
 23182    ** Head and tail of a linked list of all outstanding allocations
 23183    */
 23184    struct MemBlockHdr *pFirst;
 23185    struct MemBlockHdr *pLast;
 23186    
 23187    /*
 23188    ** The number of levels of backtrace to save in new allocations.
 23189    */
 23190    int nBacktrace;
 23191    void (*xBacktrace)(int, int, void **);
 23192  
 23193    /*
 23194    ** Title text to insert in front of each block
 23195    */
 23196    int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
 23197    char zTitle[100];  /* The title text */
 23198  
 23199    /* 
 23200    ** sqlite3MallocDisallow() increments the following counter.
 23201    ** sqlite3MallocAllow() decrements it.
 23202    */
 23203    int disallow; /* Do not allow memory allocation */
 23204  
 23205    /*
 23206    ** Gather statistics on the sizes of memory allocations.
 23207    ** nAlloc[i] is the number of allocation attempts of i*8
 23208    ** bytes.  i==NCSIZE is the number of allocation attempts for
 23209    ** sizes more than NCSIZE*8 bytes.
 23210    */
 23211    int nAlloc[NCSIZE];      /* Total number of allocations */
 23212    int nCurrent[NCSIZE];    /* Current number of allocations */
 23213    int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
 23214  
 23215  } mem;
 23216  
 23217  
 23218  /*
 23219  ** Adjust memory usage statistics
 23220  */
 23221  static void adjustStats(int iSize, int increment){
 23222    int i = ROUND8(iSize)/8;
 23223    if( i>NCSIZE-1 ){
 23224      i = NCSIZE - 1;
 23225    }
 23226    if( increment>0 ){
 23227      mem.nAlloc[i]++;
 23228      mem.nCurrent[i]++;
 23229      if( mem.nCurrent[i]>mem.mxCurrent[i] ){
 23230        mem.mxCurrent[i] = mem.nCurrent[i];
 23231      }
 23232    }else{
 23233      mem.nCurrent[i]--;
 23234      assert( mem.nCurrent[i]>=0 );
 23235    }
 23236  }
 23237  
 23238  /*
 23239  ** Given an allocation, find the MemBlockHdr for that allocation.
 23240  **
 23241  ** This routine checks the guards at either end of the allocation and
 23242  ** if they are incorrect it asserts.
 23243  */
 23244  static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
 23245    struct MemBlockHdr *p;
 23246    int *pInt;
 23247    u8 *pU8;
 23248    int nReserve;
 23249  
 23250    p = (struct MemBlockHdr*)pAllocation;
 23251    p--;
 23252    assert( p->iForeGuard==(int)FOREGUARD );
 23253    nReserve = ROUND8(p->iSize);
 23254    pInt = (int*)pAllocation;
 23255    pU8 = (u8*)pAllocation;
 23256    assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
 23257    /* This checks any of the "extra" bytes allocated due
 23258    ** to rounding up to an 8 byte boundary to ensure 
 23259    ** they haven't been overwritten.
 23260    */
 23261    while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
 23262    return p;
 23263  }
 23264  
 23265  /*
 23266  ** Return the number of bytes currently allocated at address p.
 23267  */
 23268  static int sqlite3MemSize(void *p){
 23269    struct MemBlockHdr *pHdr;
 23270    if( !p ){
 23271      return 0;
 23272    }
 23273    pHdr = sqlite3MemsysGetHeader(p);
 23274    return (int)pHdr->iSize;
 23275  }
 23276  
 23277  /*
 23278  ** Initialize the memory allocation subsystem.
 23279  */
 23280  static int sqlite3MemInit(void *NotUsed){
 23281    UNUSED_PARAMETER(NotUsed);
 23282    assert( (sizeof(struct MemBlockHdr)&7) == 0 );
 23283    if( !sqlite3GlobalConfig.bMemstat ){
 23284      /* If memory status is enabled, then the malloc.c wrapper will already
 23285      ** hold the STATIC_MEM mutex when the routines here are invoked. */
 23286      mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 23287    }
 23288    return SQLITE_OK;
 23289  }
 23290  
 23291  /*
 23292  ** Deinitialize the memory allocation subsystem.
 23293  */
 23294  static void sqlite3MemShutdown(void *NotUsed){
 23295    UNUSED_PARAMETER(NotUsed);
 23296    mem.mutex = 0;
 23297  }
 23298  
 23299  /*
 23300  ** Round up a request size to the next valid allocation size.
 23301  */
 23302  static int sqlite3MemRoundup(int n){
 23303    return ROUND8(n);
 23304  }
 23305  
 23306  /*
 23307  ** Fill a buffer with pseudo-random bytes.  This is used to preset
 23308  ** the content of a new memory allocation to unpredictable values and
 23309  ** to clear the content of a freed allocation to unpredictable values.
 23310  */
 23311  static void randomFill(char *pBuf, int nByte){
 23312    unsigned int x, y, r;
 23313    x = SQLITE_PTR_TO_INT(pBuf);
 23314    y = nByte | 1;
 23315    while( nByte >= 4 ){
 23316      x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 23317      y = y*1103515245 + 12345;
 23318      r = x ^ y;
 23319      *(int*)pBuf = r;
 23320      pBuf += 4;
 23321      nByte -= 4;
 23322    }
 23323    while( nByte-- > 0 ){
 23324      x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
 23325      y = y*1103515245 + 12345;
 23326      r = x ^ y;
 23327      *(pBuf++) = r & 0xff;
 23328    }
 23329  }
 23330  
 23331  /*
 23332  ** Allocate nByte bytes of memory.
 23333  */
 23334  static void *sqlite3MemMalloc(int nByte){
 23335    struct MemBlockHdr *pHdr;
 23336    void **pBt;
 23337    char *z;
 23338    int *pInt;
 23339    void *p = 0;
 23340    int totalSize;
 23341    int nReserve;
 23342    sqlite3_mutex_enter(mem.mutex);
 23343    assert( mem.disallow==0 );
 23344    nReserve = ROUND8(nByte);
 23345    totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
 23346                 mem.nBacktrace*sizeof(void*) + mem.nTitle;
 23347    p = malloc(totalSize);
 23348    if( p ){
 23349      z = p;
 23350      pBt = (void**)&z[mem.nTitle];
 23351      pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
 23352      pHdr->pNext = 0;
 23353      pHdr->pPrev = mem.pLast;
 23354      if( mem.pLast ){
 23355        mem.pLast->pNext = pHdr;
 23356      }else{
 23357        mem.pFirst = pHdr;
 23358      }
 23359      mem.pLast = pHdr;
 23360      pHdr->iForeGuard = FOREGUARD;
 23361      pHdr->eType = MEMTYPE_HEAP;
 23362      pHdr->nBacktraceSlots = mem.nBacktrace;
 23363      pHdr->nTitle = mem.nTitle;
 23364      if( mem.nBacktrace ){
 23365        void *aAddr[40];
 23366        pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
 23367        memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
 23368        assert(pBt[0]);
 23369        if( mem.xBacktrace ){
 23370          mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
 23371        }
 23372      }else{
 23373        pHdr->nBacktrace = 0;
 23374      }
 23375      if( mem.nTitle ){
 23376        memcpy(z, mem.zTitle, mem.nTitle);
 23377      }
 23378      pHdr->iSize = nByte;
 23379      adjustStats(nByte, +1);
 23380      pInt = (int*)&pHdr[1];
 23381      pInt[nReserve/sizeof(int)] = REARGUARD;
 23382      randomFill((char*)pInt, nByte);
 23383      memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
 23384      p = (void*)pInt;
 23385    }
 23386    sqlite3_mutex_leave(mem.mutex);
 23387    return p; 
 23388  }
 23389  
 23390  /*
 23391  ** Free memory.
 23392  */
 23393  static void sqlite3MemFree(void *pPrior){
 23394    struct MemBlockHdr *pHdr;
 23395    void **pBt;
 23396    char *z;
 23397    assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
 23398         || mem.mutex!=0 );
 23399    pHdr = sqlite3MemsysGetHeader(pPrior);
 23400    pBt = (void**)pHdr;
 23401    pBt -= pHdr->nBacktraceSlots;
 23402    sqlite3_mutex_enter(mem.mutex);
 23403    if( pHdr->pPrev ){
 23404      assert( pHdr->pPrev->pNext==pHdr );
 23405      pHdr->pPrev->pNext = pHdr->pNext;
 23406    }else{
 23407      assert( mem.pFirst==pHdr );
 23408      mem.pFirst = pHdr->pNext;
 23409    }
 23410    if( pHdr->pNext ){
 23411      assert( pHdr->pNext->pPrev==pHdr );
 23412      pHdr->pNext->pPrev = pHdr->pPrev;
 23413    }else{
 23414      assert( mem.pLast==pHdr );
 23415      mem.pLast = pHdr->pPrev;
 23416    }
 23417    z = (char*)pBt;
 23418    z -= pHdr->nTitle;
 23419    adjustStats((int)pHdr->iSize, -1);
 23420    randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
 23421                  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
 23422    free(z);
 23423    sqlite3_mutex_leave(mem.mutex);  
 23424  }
 23425  
 23426  /*
 23427  ** Change the size of an existing memory allocation.
 23428  **
 23429  ** For this debugging implementation, we *always* make a copy of the
 23430  ** allocation into a new place in memory.  In this way, if the 
 23431  ** higher level code is using pointer to the old allocation, it is 
 23432  ** much more likely to break and we are much more liking to find
 23433  ** the error.
 23434  */
 23435  static void *sqlite3MemRealloc(void *pPrior, int nByte){
 23436    struct MemBlockHdr *pOldHdr;
 23437    void *pNew;
 23438    assert( mem.disallow==0 );
 23439    assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
 23440    pOldHdr = sqlite3MemsysGetHeader(pPrior);
 23441    pNew = sqlite3MemMalloc(nByte);
 23442    if( pNew ){
 23443      memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
 23444      if( nByte>pOldHdr->iSize ){
 23445        randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
 23446      }
 23447      sqlite3MemFree(pPrior);
 23448    }
 23449    return pNew;
 23450  }
 23451  
 23452  /*
 23453  ** Populate the low-level memory allocation function pointers in
 23454  ** sqlite3GlobalConfig.m with pointers to the routines in this file.
 23455  */
 23456  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 23457    static const sqlite3_mem_methods defaultMethods = {
 23458       sqlite3MemMalloc,
 23459       sqlite3MemFree,
 23460       sqlite3MemRealloc,
 23461       sqlite3MemSize,
 23462       sqlite3MemRoundup,
 23463       sqlite3MemInit,
 23464       sqlite3MemShutdown,
 23465       0
 23466    };
 23467    sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
 23468  }
 23469  
 23470  /*
 23471  ** Set the "type" of an allocation.
 23472  */
 23473  SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
 23474    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 23475      struct MemBlockHdr *pHdr;
 23476      pHdr = sqlite3MemsysGetHeader(p);
 23477      assert( pHdr->iForeGuard==FOREGUARD );
 23478      pHdr->eType = eType;
 23479    }
 23480  }
 23481  
 23482  /*
 23483  ** Return TRUE if the mask of type in eType matches the type of the
 23484  ** allocation p.  Also return true if p==NULL.
 23485  **
 23486  ** This routine is designed for use within an assert() statement, to
 23487  ** verify the type of an allocation.  For example:
 23488  **
 23489  **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 23490  */
 23491  SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
 23492    int rc = 1;
 23493    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 23494      struct MemBlockHdr *pHdr;
 23495      pHdr = sqlite3MemsysGetHeader(p);
 23496      assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 23497      if( (pHdr->eType&eType)==0 ){
 23498        rc = 0;
 23499      }
 23500    }
 23501    return rc;
 23502  }
 23503  
 23504  /*
 23505  ** Return TRUE if the mask of type in eType matches no bits of the type of the
 23506  ** allocation p.  Also return true if p==NULL.
 23507  **
 23508  ** This routine is designed for use within an assert() statement, to
 23509  ** verify the type of an allocation.  For example:
 23510  **
 23511  **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 23512  */
 23513  SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
 23514    int rc = 1;
 23515    if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
 23516      struct MemBlockHdr *pHdr;
 23517      pHdr = sqlite3MemsysGetHeader(p);
 23518      assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
 23519      if( (pHdr->eType&eType)!=0 ){
 23520        rc = 0;
 23521      }
 23522    }
 23523    return rc;
 23524  }
 23525  
 23526  /*
 23527  ** Set the number of backtrace levels kept for each allocation.
 23528  ** A value of zero turns off backtracing.  The number is always rounded
 23529  ** up to a multiple of 2.
 23530  */
 23531  SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
 23532    if( depth<0 ){ depth = 0; }
 23533    if( depth>20 ){ depth = 20; }
 23534    depth = (depth+1)&0xfe;
 23535    mem.nBacktrace = depth;
 23536  }
 23537  
 23538  SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
 23539    mem.xBacktrace = xBacktrace;
 23540  }
 23541  
 23542  /*
 23543  ** Set the title string for subsequent allocations.
 23544  */
 23545  SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
 23546    unsigned int n = sqlite3Strlen30(zTitle) + 1;
 23547    sqlite3_mutex_enter(mem.mutex);
 23548    if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
 23549    memcpy(mem.zTitle, zTitle, n);
 23550    mem.zTitle[n] = 0;
 23551    mem.nTitle = ROUND8(n);
 23552    sqlite3_mutex_leave(mem.mutex);
 23553  }
 23554  
 23555  SQLITE_PRIVATE void sqlite3MemdebugSync(){
 23556    struct MemBlockHdr *pHdr;
 23557    for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 23558      void **pBt = (void**)pHdr;
 23559      pBt -= pHdr->nBacktraceSlots;
 23560      mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
 23561    }
 23562  }
 23563  
 23564  /*
 23565  ** Open the file indicated and write a log of all unfreed memory 
 23566  ** allocations into that log.
 23567  */
 23568  SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
 23569    FILE *out;
 23570    struct MemBlockHdr *pHdr;
 23571    void **pBt;
 23572    int i;
 23573    out = fopen(zFilename, "w");
 23574    if( out==0 ){
 23575      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 23576                      zFilename);
 23577      return;
 23578    }
 23579    for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
 23580      char *z = (char*)pHdr;
 23581      z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
 23582      fprintf(out, "**** %lld bytes at %p from %s ****\n", 
 23583              pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
 23584      if( pHdr->nBacktrace ){
 23585        fflush(out);
 23586        pBt = (void**)pHdr;
 23587        pBt -= pHdr->nBacktraceSlots;
 23588        backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
 23589        fprintf(out, "\n");
 23590      }
 23591    }
 23592    fprintf(out, "COUNTS:\n");
 23593    for(i=0; i<NCSIZE-1; i++){
 23594      if( mem.nAlloc[i] ){
 23595        fprintf(out, "   %5d: %10d %10d %10d\n", 
 23596              i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
 23597      }
 23598    }
 23599    if( mem.nAlloc[NCSIZE-1] ){
 23600      fprintf(out, "   %5d: %10d %10d %10d\n",
 23601               NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
 23602               mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
 23603    }
 23604    fclose(out);
 23605  }
 23606  
 23607  /*
 23608  ** Return the number of times sqlite3MemMalloc() has been called.
 23609  */
 23610  SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 23611    int i;
 23612    int nTotal = 0;
 23613    for(i=0; i<NCSIZE; i++){
 23614      nTotal += mem.nAlloc[i];
 23615    }
 23616    return nTotal;
 23617  }
 23618  
 23619  
 23620  #endif /* SQLITE_MEMDEBUG */
 23621  
 23622  /************** End of mem2.c ************************************************/
 23623  /************** Begin file mem3.c ********************************************/
 23624  /*
 23625  ** 2007 October 14
 23626  **
 23627  ** The author disclaims copyright to this source code.  In place of
 23628  ** a legal notice, here is a blessing:
 23629  **
 23630  **    May you do good and not evil.
 23631  **    May you find forgiveness for yourself and forgive others.
 23632  **    May you share freely, never taking more than you give.
 23633  **
 23634  *************************************************************************
 23635  ** This file contains the C functions that implement a memory
 23636  ** allocation subsystem for use by SQLite. 
 23637  **
 23638  ** This version of the memory allocation subsystem omits all
 23639  ** use of malloc(). The SQLite user supplies a block of memory
 23640  ** before calling sqlite3_initialize() from which allocations
 23641  ** are made and returned by the xMalloc() and xRealloc() 
 23642  ** implementations. Once sqlite3_initialize() has been called,
 23643  ** the amount of memory available to SQLite is fixed and cannot
 23644  ** be changed.
 23645  **
 23646  ** This version of the memory allocation subsystem is included
 23647  ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
 23648  */
 23649  /* #include "sqliteInt.h" */
 23650  
 23651  /*
 23652  ** This version of the memory allocator is only built into the library
 23653  ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
 23654  ** mean that the library will use a memory-pool by default, just that
 23655  ** it is available. The mempool allocator is activated by calling
 23656  ** sqlite3_config().
 23657  */
 23658  #ifdef SQLITE_ENABLE_MEMSYS3
 23659  
 23660  /*
 23661  ** Maximum size (in Mem3Blocks) of a "small" chunk.
 23662  */
 23663  #define MX_SMALL 10
 23664  
 23665  
 23666  /*
 23667  ** Number of freelist hash slots
 23668  */
 23669  #define N_HASH  61
 23670  
 23671  /*
 23672  ** A memory allocation (also called a "chunk") consists of two or 
 23673  ** more blocks where each block is 8 bytes.  The first 8 bytes are 
 23674  ** a header that is not returned to the user.
 23675  **
 23676  ** A chunk is two or more blocks that is either checked out or
 23677  ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
 23678  ** size of the allocation in blocks if the allocation is free.
 23679  ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
 23680  ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
 23681  ** is true if the previous chunk is checked out and false if the
 23682  ** previous chunk is free.  The u.hdr.prevSize field is the size of
 23683  ** the previous chunk in blocks if the previous chunk is on the
 23684  ** freelist. If the previous chunk is checked out, then
 23685  ** u.hdr.prevSize can be part of the data for that chunk and should
 23686  ** not be read or written.
 23687  **
 23688  ** We often identify a chunk by its index in mem3.aPool[].  When
 23689  ** this is done, the chunk index refers to the second block of
 23690  ** the chunk.  In this way, the first chunk has an index of 1.
 23691  ** A chunk index of 0 means "no such chunk" and is the equivalent
 23692  ** of a NULL pointer.
 23693  **
 23694  ** The second block of free chunks is of the form u.list.  The
 23695  ** two fields form a double-linked list of chunks of related sizes.
 23696  ** Pointers to the head of the list are stored in mem3.aiSmall[] 
 23697  ** for smaller chunks and mem3.aiHash[] for larger chunks.
 23698  **
 23699  ** The second block of a chunk is user data if the chunk is checked 
 23700  ** out.  If a chunk is checked out, the user data may extend into
 23701  ** the u.hdr.prevSize value of the following chunk.
 23702  */
 23703  typedef struct Mem3Block Mem3Block;
 23704  struct Mem3Block {
 23705    union {
 23706      struct {
 23707        u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
 23708        u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
 23709      } hdr;
 23710      struct {
 23711        u32 next;       /* Index in mem3.aPool[] of next free chunk */
 23712        u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
 23713      } list;
 23714    } u;
 23715  };
 23716  
 23717  /*
 23718  ** All of the static variables used by this module are collected
 23719  ** into a single structure named "mem3".  This is to keep the
 23720  ** static variables organized and to reduce namespace pollution
 23721  ** when this module is combined with other in the amalgamation.
 23722  */
 23723  static SQLITE_WSD struct Mem3Global {
 23724    /*
 23725    ** Memory available for allocation. nPool is the size of the array
 23726    ** (in Mem3Blocks) pointed to by aPool less 2.
 23727    */
 23728    u32 nPool;
 23729    Mem3Block *aPool;
 23730  
 23731    /*
 23732    ** True if we are evaluating an out-of-memory callback.
 23733    */
 23734    int alarmBusy;
 23735    
 23736    /*
 23737    ** Mutex to control access to the memory allocation subsystem.
 23738    */
 23739    sqlite3_mutex *mutex;
 23740    
 23741    /*
 23742    ** The minimum amount of free space that we have seen.
 23743    */
 23744    u32 mnMaster;
 23745  
 23746    /*
 23747    ** iMaster is the index of the master chunk.  Most new allocations
 23748    ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
 23749    ** of the current master.  iMaster is 0 if there is not master chunk.
 23750    ** The master chunk is not in either the aiHash[] or aiSmall[].
 23751    */
 23752    u32 iMaster;
 23753    u32 szMaster;
 23754  
 23755    /*
 23756    ** Array of lists of free blocks according to the block size 
 23757    ** for smaller chunks, or a hash on the block size for larger
 23758    ** chunks.
 23759    */
 23760    u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
 23761    u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
 23762  } mem3 = { 97535575 };
 23763  
 23764  #define mem3 GLOBAL(struct Mem3Global, mem3)
 23765  
 23766  /*
 23767  ** Unlink the chunk at mem3.aPool[i] from list it is currently
 23768  ** on.  *pRoot is the list that i is a member of.
 23769  */
 23770  static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
 23771    u32 next = mem3.aPool[i].u.list.next;
 23772    u32 prev = mem3.aPool[i].u.list.prev;
 23773    assert( sqlite3_mutex_held(mem3.mutex) );
 23774    if( prev==0 ){
 23775      *pRoot = next;
 23776    }else{
 23777      mem3.aPool[prev].u.list.next = next;
 23778    }
 23779    if( next ){
 23780      mem3.aPool[next].u.list.prev = prev;
 23781    }
 23782    mem3.aPool[i].u.list.next = 0;
 23783    mem3.aPool[i].u.list.prev = 0;
 23784  }
 23785  
 23786  /*
 23787  ** Unlink the chunk at index i from 
 23788  ** whatever list is currently a member of.
 23789  */
 23790  static void memsys3Unlink(u32 i){
 23791    u32 size, hash;
 23792    assert( sqlite3_mutex_held(mem3.mutex) );
 23793    assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 23794    assert( i>=1 );
 23795    size = mem3.aPool[i-1].u.hdr.size4x/4;
 23796    assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 23797    assert( size>=2 );
 23798    if( size <= MX_SMALL ){
 23799      memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
 23800    }else{
 23801      hash = size % N_HASH;
 23802      memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 23803    }
 23804  }
 23805  
 23806  /*
 23807  ** Link the chunk at mem3.aPool[i] so that is on the list rooted
 23808  ** at *pRoot.
 23809  */
 23810  static void memsys3LinkIntoList(u32 i, u32 *pRoot){
 23811    assert( sqlite3_mutex_held(mem3.mutex) );
 23812    mem3.aPool[i].u.list.next = *pRoot;
 23813    mem3.aPool[i].u.list.prev = 0;
 23814    if( *pRoot ){
 23815      mem3.aPool[*pRoot].u.list.prev = i;
 23816    }
 23817    *pRoot = i;
 23818  }
 23819  
 23820  /*
 23821  ** Link the chunk at index i into either the appropriate
 23822  ** small chunk list, or into the large chunk hash table.
 23823  */
 23824  static void memsys3Link(u32 i){
 23825    u32 size, hash;
 23826    assert( sqlite3_mutex_held(mem3.mutex) );
 23827    assert( i>=1 );
 23828    assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
 23829    size = mem3.aPool[i-1].u.hdr.size4x/4;
 23830    assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
 23831    assert( size>=2 );
 23832    if( size <= MX_SMALL ){
 23833      memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
 23834    }else{
 23835      hash = size % N_HASH;
 23836      memsys3LinkIntoList(i, &mem3.aiHash[hash]);
 23837    }
 23838  }
 23839  
 23840  /*
 23841  ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
 23842  ** will already be held (obtained by code in malloc.c) if
 23843  ** sqlite3GlobalConfig.bMemStat is true.
 23844  */
 23845  static void memsys3Enter(void){
 23846    if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
 23847      mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 23848    }
 23849    sqlite3_mutex_enter(mem3.mutex);
 23850  }
 23851  static void memsys3Leave(void){
 23852    sqlite3_mutex_leave(mem3.mutex);
 23853  }
 23854  
 23855  /*
 23856  ** Called when we are unable to satisfy an allocation of nBytes.
 23857  */
 23858  static void memsys3OutOfMemory(int nByte){
 23859    if( !mem3.alarmBusy ){
 23860      mem3.alarmBusy = 1;
 23861      assert( sqlite3_mutex_held(mem3.mutex) );
 23862      sqlite3_mutex_leave(mem3.mutex);
 23863      sqlite3_release_memory(nByte);
 23864      sqlite3_mutex_enter(mem3.mutex);
 23865      mem3.alarmBusy = 0;
 23866    }
 23867  }
 23868  
 23869  
 23870  /*
 23871  ** Chunk i is a free chunk that has been unlinked.  Adjust its 
 23872  ** size parameters for check-out and return a pointer to the 
 23873  ** user portion of the chunk.
 23874  */
 23875  static void *memsys3Checkout(u32 i, u32 nBlock){
 23876    u32 x;
 23877    assert( sqlite3_mutex_held(mem3.mutex) );
 23878    assert( i>=1 );
 23879    assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
 23880    assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
 23881    x = mem3.aPool[i-1].u.hdr.size4x;
 23882    mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
 23883    mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
 23884    mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
 23885    return &mem3.aPool[i];
 23886  }
 23887  
 23888  /*
 23889  ** Carve a piece off of the end of the mem3.iMaster free chunk.
 23890  ** Return a pointer to the new allocation.  Or, if the master chunk
 23891  ** is not large enough, return 0.
 23892  */
 23893  static void *memsys3FromMaster(u32 nBlock){
 23894    assert( sqlite3_mutex_held(mem3.mutex) );
 23895    assert( mem3.szMaster>=nBlock );
 23896    if( nBlock>=mem3.szMaster-1 ){
 23897      /* Use the entire master */
 23898      void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
 23899      mem3.iMaster = 0;
 23900      mem3.szMaster = 0;
 23901      mem3.mnMaster = 0;
 23902      return p;
 23903    }else{
 23904      /* Split the master block.  Return the tail. */
 23905      u32 newi, x;
 23906      newi = mem3.iMaster + mem3.szMaster - nBlock;
 23907      assert( newi > mem3.iMaster+1 );
 23908      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
 23909      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
 23910      mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
 23911      mem3.szMaster -= nBlock;
 23912      mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
 23913      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 23914      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 23915      if( mem3.szMaster < mem3.mnMaster ){
 23916        mem3.mnMaster = mem3.szMaster;
 23917      }
 23918      return (void*)&mem3.aPool[newi];
 23919    }
 23920  }
 23921  
 23922  /*
 23923  ** *pRoot is the head of a list of free chunks of the same size
 23924  ** or same size hash.  In other words, *pRoot is an entry in either
 23925  ** mem3.aiSmall[] or mem3.aiHash[].  
 23926  **
 23927  ** This routine examines all entries on the given list and tries
 23928  ** to coalesce each entries with adjacent free chunks.  
 23929  **
 23930  ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
 23931  ** the current mem3.iMaster with the new larger chunk.  In order for
 23932  ** this mem3.iMaster replacement to work, the master chunk must be
 23933  ** linked into the hash tables.  That is not the normal state of
 23934  ** affairs, of course.  The calling routine must link the master
 23935  ** chunk before invoking this routine, then must unlink the (possibly
 23936  ** changed) master chunk once this routine has finished.
 23937  */
 23938  static void memsys3Merge(u32 *pRoot){
 23939    u32 iNext, prev, size, i, x;
 23940  
 23941    assert( sqlite3_mutex_held(mem3.mutex) );
 23942    for(i=*pRoot; i>0; i=iNext){
 23943      iNext = mem3.aPool[i].u.list.next;
 23944      size = mem3.aPool[i-1].u.hdr.size4x;
 23945      assert( (size&1)==0 );
 23946      if( (size&2)==0 ){
 23947        memsys3UnlinkFromList(i, pRoot);
 23948        assert( i > mem3.aPool[i-1].u.hdr.prevSize );
 23949        prev = i - mem3.aPool[i-1].u.hdr.prevSize;
 23950        if( prev==iNext ){
 23951          iNext = mem3.aPool[prev].u.list.next;
 23952        }
 23953        memsys3Unlink(prev);
 23954        size = i + size/4 - prev;
 23955        x = mem3.aPool[prev-1].u.hdr.size4x & 2;
 23956        mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
 23957        mem3.aPool[prev+size-1].u.hdr.prevSize = size;
 23958        memsys3Link(prev);
 23959        i = prev;
 23960      }else{
 23961        size /= 4;
 23962      }
 23963      if( size>mem3.szMaster ){
 23964        mem3.iMaster = i;
 23965        mem3.szMaster = size;
 23966      }
 23967    }
 23968  }
 23969  
 23970  /*
 23971  ** Return a block of memory of at least nBytes in size.
 23972  ** Return NULL if unable.
 23973  **
 23974  ** This function assumes that the necessary mutexes, if any, are
 23975  ** already held by the caller. Hence "Unsafe".
 23976  */
 23977  static void *memsys3MallocUnsafe(int nByte){
 23978    u32 i;
 23979    u32 nBlock;
 23980    u32 toFree;
 23981  
 23982    assert( sqlite3_mutex_held(mem3.mutex) );
 23983    assert( sizeof(Mem3Block)==8 );
 23984    if( nByte<=12 ){
 23985      nBlock = 2;
 23986    }else{
 23987      nBlock = (nByte + 11)/8;
 23988    }
 23989    assert( nBlock>=2 );
 23990  
 23991    /* STEP 1:
 23992    ** Look for an entry of the correct size in either the small
 23993    ** chunk table or in the large chunk hash table.  This is
 23994    ** successful most of the time (about 9 times out of 10).
 23995    */
 23996    if( nBlock <= MX_SMALL ){
 23997      i = mem3.aiSmall[nBlock-2];
 23998      if( i>0 ){
 23999        memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
 24000        return memsys3Checkout(i, nBlock);
 24001      }
 24002    }else{
 24003      int hash = nBlock % N_HASH;
 24004      for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
 24005        if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
 24006          memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
 24007          return memsys3Checkout(i, nBlock);
 24008        }
 24009      }
 24010    }
 24011  
 24012    /* STEP 2:
 24013    ** Try to satisfy the allocation by carving a piece off of the end
 24014    ** of the master chunk.  This step usually works if step 1 fails.
 24015    */
 24016    if( mem3.szMaster>=nBlock ){
 24017      return memsys3FromMaster(nBlock);
 24018    }
 24019  
 24020  
 24021    /* STEP 3:  
 24022    ** Loop through the entire memory pool.  Coalesce adjacent free
 24023    ** chunks.  Recompute the master chunk as the largest free chunk.
 24024    ** Then try again to satisfy the allocation by carving a piece off
 24025    ** of the end of the master chunk.  This step happens very
 24026    ** rarely (we hope!)
 24027    */
 24028    for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
 24029      memsys3OutOfMemory(toFree);
 24030      if( mem3.iMaster ){
 24031        memsys3Link(mem3.iMaster);
 24032        mem3.iMaster = 0;
 24033        mem3.szMaster = 0;
 24034      }
 24035      for(i=0; i<N_HASH; i++){
 24036        memsys3Merge(&mem3.aiHash[i]);
 24037      }
 24038      for(i=0; i<MX_SMALL-1; i++){
 24039        memsys3Merge(&mem3.aiSmall[i]);
 24040      }
 24041      if( mem3.szMaster ){
 24042        memsys3Unlink(mem3.iMaster);
 24043        if( mem3.szMaster>=nBlock ){
 24044          return memsys3FromMaster(nBlock);
 24045        }
 24046      }
 24047    }
 24048  
 24049    /* If none of the above worked, then we fail. */
 24050    return 0;
 24051  }
 24052  
 24053  /*
 24054  ** Free an outstanding memory allocation.
 24055  **
 24056  ** This function assumes that the necessary mutexes, if any, are
 24057  ** already held by the caller. Hence "Unsafe".
 24058  */
 24059  static void memsys3FreeUnsafe(void *pOld){
 24060    Mem3Block *p = (Mem3Block*)pOld;
 24061    int i;
 24062    u32 size, x;
 24063    assert( sqlite3_mutex_held(mem3.mutex) );
 24064    assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
 24065    i = p - mem3.aPool;
 24066    assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
 24067    size = mem3.aPool[i-1].u.hdr.size4x/4;
 24068    assert( i+size<=mem3.nPool+1 );
 24069    mem3.aPool[i-1].u.hdr.size4x &= ~1;
 24070    mem3.aPool[i+size-1].u.hdr.prevSize = size;
 24071    mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
 24072    memsys3Link(i);
 24073  
 24074    /* Try to expand the master using the newly freed chunk */
 24075    if( mem3.iMaster ){
 24076      while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
 24077        size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
 24078        mem3.iMaster -= size;
 24079        mem3.szMaster += size;
 24080        memsys3Unlink(mem3.iMaster);
 24081        x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 24082        mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 24083        mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 24084      }
 24085      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
 24086      while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
 24087        memsys3Unlink(mem3.iMaster+mem3.szMaster);
 24088        mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
 24089        mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
 24090        mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
 24091      }
 24092    }
 24093  }
 24094  
 24095  /*
 24096  ** Return the size of an outstanding allocation, in bytes.  The
 24097  ** size returned omits the 8-byte header overhead.  This only
 24098  ** works for chunks that are currently checked out.
 24099  */
 24100  static int memsys3Size(void *p){
 24101    Mem3Block *pBlock;
 24102    assert( p!=0 );
 24103    pBlock = (Mem3Block*)p;
 24104    assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
 24105    return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
 24106  }
 24107  
 24108  /*
 24109  ** Round up a request size to the next valid allocation size.
 24110  */
 24111  static int memsys3Roundup(int n){
 24112    if( n<=12 ){
 24113      return 12;
 24114    }else{
 24115      return ((n+11)&~7) - 4;
 24116    }
 24117  }
 24118  
 24119  /*
 24120  ** Allocate nBytes of memory.
 24121  */
 24122  static void *memsys3Malloc(int nBytes){
 24123    sqlite3_int64 *p;
 24124    assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
 24125    memsys3Enter();
 24126    p = memsys3MallocUnsafe(nBytes);
 24127    memsys3Leave();
 24128    return (void*)p; 
 24129  }
 24130  
 24131  /*
 24132  ** Free memory.
 24133  */
 24134  static void memsys3Free(void *pPrior){
 24135    assert( pPrior );
 24136    memsys3Enter();
 24137    memsys3FreeUnsafe(pPrior);
 24138    memsys3Leave();
 24139  }
 24140  
 24141  /*
 24142  ** Change the size of an existing memory allocation
 24143  */
 24144  static void *memsys3Realloc(void *pPrior, int nBytes){
 24145    int nOld;
 24146    void *p;
 24147    if( pPrior==0 ){
 24148      return sqlite3_malloc(nBytes);
 24149    }
 24150    if( nBytes<=0 ){
 24151      sqlite3_free(pPrior);
 24152      return 0;
 24153    }
 24154    nOld = memsys3Size(pPrior);
 24155    if( nBytes<=nOld && nBytes>=nOld-128 ){
 24156      return pPrior;
 24157    }
 24158    memsys3Enter();
 24159    p = memsys3MallocUnsafe(nBytes);
 24160    if( p ){
 24161      if( nOld<nBytes ){
 24162        memcpy(p, pPrior, nOld);
 24163      }else{
 24164        memcpy(p, pPrior, nBytes);
 24165      }
 24166      memsys3FreeUnsafe(pPrior);
 24167    }
 24168    memsys3Leave();
 24169    return p;
 24170  }
 24171  
 24172  /*
 24173  ** Initialize this module.
 24174  */
 24175  static int memsys3Init(void *NotUsed){
 24176    UNUSED_PARAMETER(NotUsed);
 24177    if( !sqlite3GlobalConfig.pHeap ){
 24178      return SQLITE_ERROR;
 24179    }
 24180  
 24181    /* Store a pointer to the memory block in global structure mem3. */
 24182    assert( sizeof(Mem3Block)==8 );
 24183    mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
 24184    mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
 24185  
 24186    /* Initialize the master block. */
 24187    mem3.szMaster = mem3.nPool;
 24188    mem3.mnMaster = mem3.szMaster;
 24189    mem3.iMaster = 1;
 24190    mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
 24191    mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
 24192    mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
 24193  
 24194    return SQLITE_OK;
 24195  }
 24196  
 24197  /*
 24198  ** Deinitialize this module.
 24199  */
 24200  static void memsys3Shutdown(void *NotUsed){
 24201    UNUSED_PARAMETER(NotUsed);
 24202    mem3.mutex = 0;
 24203    return;
 24204  }
 24205  
 24206  
 24207  
 24208  /*
 24209  ** Open the file indicated and write a log of all unfreed memory 
 24210  ** allocations into that log.
 24211  */
 24212  SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
 24213  #ifdef SQLITE_DEBUG
 24214    FILE *out;
 24215    u32 i, j;
 24216    u32 size;
 24217    if( zFilename==0 || zFilename[0]==0 ){
 24218      out = stdout;
 24219    }else{
 24220      out = fopen(zFilename, "w");
 24221      if( out==0 ){
 24222        fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 24223                        zFilename);
 24224        return;
 24225      }
 24226    }
 24227    memsys3Enter();
 24228    fprintf(out, "CHUNKS:\n");
 24229    for(i=1; i<=mem3.nPool; i+=size/4){
 24230      size = mem3.aPool[i-1].u.hdr.size4x;
 24231      if( size/4<=1 ){
 24232        fprintf(out, "%p size error\n", &mem3.aPool[i]);
 24233        assert( 0 );
 24234        break;
 24235      }
 24236      if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
 24237        fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
 24238        assert( 0 );
 24239        break;
 24240      }
 24241      if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
 24242        fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
 24243        assert( 0 );
 24244        break;
 24245      }
 24246      if( size&1 ){
 24247        fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
 24248      }else{
 24249        fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
 24250                    i==mem3.iMaster ? " **master**" : "");
 24251      }
 24252    }
 24253    for(i=0; i<MX_SMALL-1; i++){
 24254      if( mem3.aiSmall[i]==0 ) continue;
 24255      fprintf(out, "small(%2d):", i);
 24256      for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
 24257        fprintf(out, " %p(%d)", &mem3.aPool[j],
 24258                (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 24259      }
 24260      fprintf(out, "\n"); 
 24261    }
 24262    for(i=0; i<N_HASH; i++){
 24263      if( mem3.aiHash[i]==0 ) continue;
 24264      fprintf(out, "hash(%2d):", i);
 24265      for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
 24266        fprintf(out, " %p(%d)", &mem3.aPool[j],
 24267                (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
 24268      }
 24269      fprintf(out, "\n"); 
 24270    }
 24271    fprintf(out, "master=%d\n", mem3.iMaster);
 24272    fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
 24273    fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
 24274    sqlite3_mutex_leave(mem3.mutex);
 24275    if( out==stdout ){
 24276      fflush(stdout);
 24277    }else{
 24278      fclose(out);
 24279    }
 24280  #else
 24281    UNUSED_PARAMETER(zFilename);
 24282  #endif
 24283  }
 24284  
 24285  /*
 24286  ** This routine is the only routine in this file with external 
 24287  ** linkage.
 24288  **
 24289  ** Populate the low-level memory allocation function pointers in
 24290  ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 24291  ** arguments specify the block of memory to manage.
 24292  **
 24293  ** This routine is only called by sqlite3_config(), and therefore
 24294  ** is not required to be threadsafe (it is not).
 24295  */
 24296  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
 24297    static const sqlite3_mem_methods mempoolMethods = {
 24298       memsys3Malloc,
 24299       memsys3Free,
 24300       memsys3Realloc,
 24301       memsys3Size,
 24302       memsys3Roundup,
 24303       memsys3Init,
 24304       memsys3Shutdown,
 24305       0
 24306    };
 24307    return &mempoolMethods;
 24308  }
 24309  
 24310  #endif /* SQLITE_ENABLE_MEMSYS3 */
 24311  
 24312  /************** End of mem3.c ************************************************/
 24313  /************** Begin file mem5.c ********************************************/
 24314  /*
 24315  ** 2007 October 14
 24316  **
 24317  ** The author disclaims copyright to this source code.  In place of
 24318  ** a legal notice, here is a blessing:
 24319  **
 24320  **    May you do good and not evil.
 24321  **    May you find forgiveness for yourself and forgive others.
 24322  **    May you share freely, never taking more than you give.
 24323  **
 24324  *************************************************************************
 24325  ** This file contains the C functions that implement a memory
 24326  ** allocation subsystem for use by SQLite. 
 24327  **
 24328  ** This version of the memory allocation subsystem omits all
 24329  ** use of malloc(). The application gives SQLite a block of memory
 24330  ** before calling sqlite3_initialize() from which allocations
 24331  ** are made and returned by the xMalloc() and xRealloc() 
 24332  ** implementations. Once sqlite3_initialize() has been called,
 24333  ** the amount of memory available to SQLite is fixed and cannot
 24334  ** be changed.
 24335  **
 24336  ** This version of the memory allocation subsystem is included
 24337  ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
 24338  **
 24339  ** This memory allocator uses the following algorithm:
 24340  **
 24341  **   1.  All memory allocation sizes are rounded up to a power of 2.
 24342  **
 24343  **   2.  If two adjacent free blocks are the halves of a larger block,
 24344  **       then the two blocks are coalesced into the single larger block.
 24345  **
 24346  **   3.  New memory is allocated from the first available free block.
 24347  **
 24348  ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
 24349  ** Concerning Dynamic Storage Allocation". Journal of the Association for
 24350  ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
 24351  ** 
 24352  ** Let n be the size of the largest allocation divided by the minimum
 24353  ** allocation size (after rounding all sizes up to a power of 2.)  Let M
 24354  ** be the maximum amount of memory ever outstanding at one time.  Let
 24355  ** N be the total amount of memory available for allocation.  Robson
 24356  ** proved that this memory allocator will never breakdown due to 
 24357  ** fragmentation as long as the following constraint holds:
 24358  **
 24359  **      N >=  M*(1 + log2(n)/2) - n + 1
 24360  **
 24361  ** The sqlite3_status() logic tracks the maximum values of n and M so
 24362  ** that an application can, at any time, verify this constraint.
 24363  */
 24364  /* #include "sqliteInt.h" */
 24365  
 24366  /*
 24367  ** This version of the memory allocator is used only when 
 24368  ** SQLITE_ENABLE_MEMSYS5 is defined.
 24369  */
 24370  #ifdef SQLITE_ENABLE_MEMSYS5
 24371  
 24372  /*
 24373  ** A minimum allocation is an instance of the following structure.
 24374  ** Larger allocations are an array of these structures where the
 24375  ** size of the array is a power of 2.
 24376  **
 24377  ** The size of this object must be a power of two.  That fact is
 24378  ** verified in memsys5Init().
 24379  */
 24380  typedef struct Mem5Link Mem5Link;
 24381  struct Mem5Link {
 24382    int next;       /* Index of next free chunk */
 24383    int prev;       /* Index of previous free chunk */
 24384  };
 24385  
 24386  /*
 24387  ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
 24388  ** mem5.szAtom is always at least 8 and 32-bit integers are used,
 24389  ** it is not actually possible to reach this limit.
 24390  */
 24391  #define LOGMAX 30
 24392  
 24393  /*
 24394  ** Masks used for mem5.aCtrl[] elements.
 24395  */
 24396  #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
 24397  #define CTRL_FREE     0x20    /* True if not checked out */
 24398  
 24399  /*
 24400  ** All of the static variables used by this module are collected
 24401  ** into a single structure named "mem5".  This is to keep the
 24402  ** static variables organized and to reduce namespace pollution
 24403  ** when this module is combined with other in the amalgamation.
 24404  */
 24405  static SQLITE_WSD struct Mem5Global {
 24406    /*
 24407    ** Memory available for allocation
 24408    */
 24409    int szAtom;      /* Smallest possible allocation in bytes */
 24410    int nBlock;      /* Number of szAtom sized blocks in zPool */
 24411    u8 *zPool;       /* Memory available to be allocated */
 24412    
 24413    /*
 24414    ** Mutex to control access to the memory allocation subsystem.
 24415    */
 24416    sqlite3_mutex *mutex;
 24417  
 24418  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24419    /*
 24420    ** Performance statistics
 24421    */
 24422    u64 nAlloc;         /* Total number of calls to malloc */
 24423    u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
 24424    u64 totalExcess;    /* Total internal fragmentation */
 24425    u32 currentOut;     /* Current checkout, including internal fragmentation */
 24426    u32 currentCount;   /* Current number of distinct checkouts */
 24427    u32 maxOut;         /* Maximum instantaneous currentOut */
 24428    u32 maxCount;       /* Maximum instantaneous currentCount */
 24429    u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
 24430  #endif
 24431    
 24432    /*
 24433    ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
 24434    ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
 24435    ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
 24436    */
 24437    int aiFreelist[LOGMAX+1];
 24438  
 24439    /*
 24440    ** Space for tracking which blocks are checked out and the size
 24441    ** of each block.  One byte per block.
 24442    */
 24443    u8 *aCtrl;
 24444  
 24445  } mem5;
 24446  
 24447  /*
 24448  ** Access the static variable through a macro for SQLITE_OMIT_WSD.
 24449  */
 24450  #define mem5 GLOBAL(struct Mem5Global, mem5)
 24451  
 24452  /*
 24453  ** Assuming mem5.zPool is divided up into an array of Mem5Link
 24454  ** structures, return a pointer to the idx-th such link.
 24455  */
 24456  #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
 24457  
 24458  /*
 24459  ** Unlink the chunk at mem5.aPool[i] from list it is currently
 24460  ** on.  It should be found on mem5.aiFreelist[iLogsize].
 24461  */
 24462  static void memsys5Unlink(int i, int iLogsize){
 24463    int next, prev;
 24464    assert( i>=0 && i<mem5.nBlock );
 24465    assert( iLogsize>=0 && iLogsize<=LOGMAX );
 24466    assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 24467  
 24468    next = MEM5LINK(i)->next;
 24469    prev = MEM5LINK(i)->prev;
 24470    if( prev<0 ){
 24471      mem5.aiFreelist[iLogsize] = next;
 24472    }else{
 24473      MEM5LINK(prev)->next = next;
 24474    }
 24475    if( next>=0 ){
 24476      MEM5LINK(next)->prev = prev;
 24477    }
 24478  }
 24479  
 24480  /*
 24481  ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
 24482  ** free list.
 24483  */
 24484  static void memsys5Link(int i, int iLogsize){
 24485    int x;
 24486    assert( sqlite3_mutex_held(mem5.mutex) );
 24487    assert( i>=0 && i<mem5.nBlock );
 24488    assert( iLogsize>=0 && iLogsize<=LOGMAX );
 24489    assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
 24490  
 24491    x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
 24492    MEM5LINK(i)->prev = -1;
 24493    if( x>=0 ){
 24494      assert( x<mem5.nBlock );
 24495      MEM5LINK(x)->prev = i;
 24496    }
 24497    mem5.aiFreelist[iLogsize] = i;
 24498  }
 24499  
 24500  /*
 24501  ** Obtain or release the mutex needed to access global data structures.
 24502  */
 24503  static void memsys5Enter(void){
 24504    sqlite3_mutex_enter(mem5.mutex);
 24505  }
 24506  static void memsys5Leave(void){
 24507    sqlite3_mutex_leave(mem5.mutex);
 24508  }
 24509  
 24510  /*
 24511  ** Return the size of an outstanding allocation, in bytes.
 24512  ** This only works for chunks that are currently checked out.
 24513  */
 24514  static int memsys5Size(void *p){
 24515    int iSize, i;
 24516    assert( p!=0 );
 24517    i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
 24518    assert( i>=0 && i<mem5.nBlock );
 24519    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
 24520    return iSize;
 24521  }
 24522  
 24523  /*
 24524  ** Return a block of memory of at least nBytes in size.
 24525  ** Return NULL if unable.  Return NULL if nBytes==0.
 24526  **
 24527  ** The caller guarantees that nByte is positive.
 24528  **
 24529  ** The caller has obtained a mutex prior to invoking this
 24530  ** routine so there is never any chance that two or more
 24531  ** threads can be in this routine at the same time.
 24532  */
 24533  static void *memsys5MallocUnsafe(int nByte){
 24534    int i;           /* Index of a mem5.aPool[] slot */
 24535    int iBin;        /* Index into mem5.aiFreelist[] */
 24536    int iFullSz;     /* Size of allocation rounded up to power of 2 */
 24537    int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
 24538  
 24539    /* nByte must be a positive */
 24540    assert( nByte>0 );
 24541  
 24542    /* No more than 1GiB per allocation */
 24543    if( nByte > 0x40000000 ) return 0;
 24544  
 24545  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24546    /* Keep track of the maximum allocation request.  Even unfulfilled
 24547    ** requests are counted */
 24548    if( (u32)nByte>mem5.maxRequest ){
 24549      mem5.maxRequest = nByte;
 24550    }
 24551  #endif
 24552  
 24553  
 24554    /* Round nByte up to the next valid power of two */
 24555    for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
 24556  
 24557    /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
 24558    ** block.  If not, then split a block of the next larger power of
 24559    ** two in order to create a new free block of size iLogsize.
 24560    */
 24561    for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
 24562    if( iBin>LOGMAX ){
 24563      testcase( sqlite3GlobalConfig.xLog!=0 );
 24564      sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
 24565      return 0;
 24566    }
 24567    i = mem5.aiFreelist[iBin];
 24568    memsys5Unlink(i, iBin);
 24569    while( iBin>iLogsize ){
 24570      int newSize;
 24571  
 24572      iBin--;
 24573      newSize = 1 << iBin;
 24574      mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
 24575      memsys5Link(i+newSize, iBin);
 24576    }
 24577    mem5.aCtrl[i] = iLogsize;
 24578  
 24579  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24580    /* Update allocator performance statistics. */
 24581    mem5.nAlloc++;
 24582    mem5.totalAlloc += iFullSz;
 24583    mem5.totalExcess += iFullSz - nByte;
 24584    mem5.currentCount++;
 24585    mem5.currentOut += iFullSz;
 24586    if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
 24587    if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
 24588  #endif
 24589  
 24590  #ifdef SQLITE_DEBUG
 24591    /* Make sure the allocated memory does not assume that it is set to zero
 24592    ** or retains a value from a previous allocation */
 24593    memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
 24594  #endif
 24595  
 24596    /* Return a pointer to the allocated memory. */
 24597    return (void*)&mem5.zPool[i*mem5.szAtom];
 24598  }
 24599  
 24600  /*
 24601  ** Free an outstanding memory allocation.
 24602  */
 24603  static void memsys5FreeUnsafe(void *pOld){
 24604    u32 size, iLogsize;
 24605    int iBlock;
 24606  
 24607    /* Set iBlock to the index of the block pointed to by pOld in 
 24608    ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
 24609    */
 24610    iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
 24611  
 24612    /* Check that the pointer pOld points to a valid, non-free block. */
 24613    assert( iBlock>=0 && iBlock<mem5.nBlock );
 24614    assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
 24615    assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
 24616  
 24617    iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
 24618    size = 1<<iLogsize;
 24619    assert( iBlock+size-1<(u32)mem5.nBlock );
 24620  
 24621    mem5.aCtrl[iBlock] |= CTRL_FREE;
 24622    mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
 24623  
 24624  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 24625    assert( mem5.currentCount>0 );
 24626    assert( mem5.currentOut>=(size*mem5.szAtom) );
 24627    mem5.currentCount--;
 24628    mem5.currentOut -= size*mem5.szAtom;
 24629    assert( mem5.currentOut>0 || mem5.currentCount==0 );
 24630    assert( mem5.currentCount>0 || mem5.currentOut==0 );
 24631  #endif
 24632  
 24633    mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 24634    while( ALWAYS(iLogsize<LOGMAX) ){
 24635      int iBuddy;
 24636      if( (iBlock>>iLogsize) & 1 ){
 24637        iBuddy = iBlock - size;
 24638        assert( iBuddy>=0 );
 24639      }else{
 24640        iBuddy = iBlock + size;
 24641        if( iBuddy>=mem5.nBlock ) break;
 24642      }
 24643      if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
 24644      memsys5Unlink(iBuddy, iLogsize);
 24645      iLogsize++;
 24646      if( iBuddy<iBlock ){
 24647        mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
 24648        mem5.aCtrl[iBlock] = 0;
 24649        iBlock = iBuddy;
 24650      }else{
 24651        mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
 24652        mem5.aCtrl[iBuddy] = 0;
 24653      }
 24654      size *= 2;
 24655    }
 24656  
 24657  #ifdef SQLITE_DEBUG
 24658    /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
 24659    ** not used after being freed */
 24660    memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
 24661  #endif
 24662  
 24663    memsys5Link(iBlock, iLogsize);
 24664  }
 24665  
 24666  /*
 24667  ** Allocate nBytes of memory.
 24668  */
 24669  static void *memsys5Malloc(int nBytes){
 24670    sqlite3_int64 *p = 0;
 24671    if( nBytes>0 ){
 24672      memsys5Enter();
 24673      p = memsys5MallocUnsafe(nBytes);
 24674      memsys5Leave();
 24675    }
 24676    return (void*)p; 
 24677  }
 24678  
 24679  /*
 24680  ** Free memory.
 24681  **
 24682  ** The outer layer memory allocator prevents this routine from
 24683  ** being called with pPrior==0.
 24684  */
 24685  static void memsys5Free(void *pPrior){
 24686    assert( pPrior!=0 );
 24687    memsys5Enter();
 24688    memsys5FreeUnsafe(pPrior);
 24689    memsys5Leave();  
 24690  }
 24691  
 24692  /*
 24693  ** Change the size of an existing memory allocation.
 24694  **
 24695  ** The outer layer memory allocator prevents this routine from
 24696  ** being called with pPrior==0.  
 24697  **
 24698  ** nBytes is always a value obtained from a prior call to
 24699  ** memsys5Round().  Hence nBytes is always a non-negative power
 24700  ** of two.  If nBytes==0 that means that an oversize allocation
 24701  ** (an allocation larger than 0x40000000) was requested and this
 24702  ** routine should return 0 without freeing pPrior.
 24703  */
 24704  static void *memsys5Realloc(void *pPrior, int nBytes){
 24705    int nOld;
 24706    void *p;
 24707    assert( pPrior!=0 );
 24708    assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
 24709    assert( nBytes>=0 );
 24710    if( nBytes==0 ){
 24711      return 0;
 24712    }
 24713    nOld = memsys5Size(pPrior);
 24714    if( nBytes<=nOld ){
 24715      return pPrior;
 24716    }
 24717    p = memsys5Malloc(nBytes);
 24718    if( p ){
 24719      memcpy(p, pPrior, nOld);
 24720      memsys5Free(pPrior);
 24721    }
 24722    return p;
 24723  }
 24724  
 24725  /*
 24726  ** Round up a request size to the next valid allocation size.  If
 24727  ** the allocation is too large to be handled by this allocation system,
 24728  ** return 0.
 24729  **
 24730  ** All allocations must be a power of two and must be expressed by a
 24731  ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
 24732  ** or 1073741824 bytes.
 24733  */
 24734  static int memsys5Roundup(int n){
 24735    int iFullSz;
 24736    if( n > 0x40000000 ) return 0;
 24737    for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
 24738    return iFullSz;
 24739  }
 24740  
 24741  /*
 24742  ** Return the ceiling of the logarithm base 2 of iValue.
 24743  **
 24744  ** Examples:   memsys5Log(1) -> 0
 24745  **             memsys5Log(2) -> 1
 24746  **             memsys5Log(4) -> 2
 24747  **             memsys5Log(5) -> 3
 24748  **             memsys5Log(8) -> 3
 24749  **             memsys5Log(9) -> 4
 24750  */
 24751  static int memsys5Log(int iValue){
 24752    int iLog;
 24753    for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
 24754    return iLog;
 24755  }
 24756  
 24757  /*
 24758  ** Initialize the memory allocator.
 24759  **
 24760  ** This routine is not threadsafe.  The caller must be holding a mutex
 24761  ** to prevent multiple threads from entering at the same time.
 24762  */
 24763  static int memsys5Init(void *NotUsed){
 24764    int ii;            /* Loop counter */
 24765    int nByte;         /* Number of bytes of memory available to this allocator */
 24766    u8 *zByte;         /* Memory usable by this allocator */
 24767    int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
 24768    int iOffset;       /* An offset into mem5.aCtrl[] */
 24769  
 24770    UNUSED_PARAMETER(NotUsed);
 24771  
 24772    /* For the purposes of this routine, disable the mutex */
 24773    mem5.mutex = 0;
 24774  
 24775    /* The size of a Mem5Link object must be a power of two.  Verify that
 24776    ** this is case.
 24777    */
 24778    assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
 24779  
 24780    nByte = sqlite3GlobalConfig.nHeap;
 24781    zByte = (u8*)sqlite3GlobalConfig.pHeap;
 24782    assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
 24783  
 24784    /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
 24785    nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
 24786    mem5.szAtom = (1<<nMinLog);
 24787    while( (int)sizeof(Mem5Link)>mem5.szAtom ){
 24788      mem5.szAtom = mem5.szAtom << 1;
 24789    }
 24790  
 24791    mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
 24792    mem5.zPool = zByte;
 24793    mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
 24794  
 24795    for(ii=0; ii<=LOGMAX; ii++){
 24796      mem5.aiFreelist[ii] = -1;
 24797    }
 24798  
 24799    iOffset = 0;
 24800    for(ii=LOGMAX; ii>=0; ii--){
 24801      int nAlloc = (1<<ii);
 24802      if( (iOffset+nAlloc)<=mem5.nBlock ){
 24803        mem5.aCtrl[iOffset] = ii | CTRL_FREE;
 24804        memsys5Link(iOffset, ii);
 24805        iOffset += nAlloc;
 24806      }
 24807      assert((iOffset+nAlloc)>mem5.nBlock);
 24808    }
 24809  
 24810    /* If a mutex is required for normal operation, allocate one */
 24811    if( sqlite3GlobalConfig.bMemstat==0 ){
 24812      mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 24813    }
 24814  
 24815    return SQLITE_OK;
 24816  }
 24817  
 24818  /*
 24819  ** Deinitialize this module.
 24820  */
 24821  static void memsys5Shutdown(void *NotUsed){
 24822    UNUSED_PARAMETER(NotUsed);
 24823    mem5.mutex = 0;
 24824    return;
 24825  }
 24826  
 24827  #ifdef SQLITE_TEST
 24828  /*
 24829  ** Open the file indicated and write a log of all unfreed memory 
 24830  ** allocations into that log.
 24831  */
 24832  SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
 24833    FILE *out;
 24834    int i, j, n;
 24835    int nMinLog;
 24836  
 24837    if( zFilename==0 || zFilename[0]==0 ){
 24838      out = stdout;
 24839    }else{
 24840      out = fopen(zFilename, "w");
 24841      if( out==0 ){
 24842        fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
 24843                        zFilename);
 24844        return;
 24845      }
 24846    }
 24847    memsys5Enter();
 24848    nMinLog = memsys5Log(mem5.szAtom);
 24849    for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
 24850      for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
 24851      fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
 24852    }
 24853    fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
 24854    fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
 24855    fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
 24856    fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
 24857    fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
 24858    fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
 24859    fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
 24860    fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
 24861    memsys5Leave();
 24862    if( out==stdout ){
 24863      fflush(stdout);
 24864    }else{
 24865      fclose(out);
 24866    }
 24867  }
 24868  #endif
 24869  
 24870  /*
 24871  ** This routine is the only routine in this file with external 
 24872  ** linkage. It returns a pointer to a static sqlite3_mem_methods
 24873  ** struct populated with the memsys5 methods.
 24874  */
 24875  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
 24876    static const sqlite3_mem_methods memsys5Methods = {
 24877       memsys5Malloc,
 24878       memsys5Free,
 24879       memsys5Realloc,
 24880       memsys5Size,
 24881       memsys5Roundup,
 24882       memsys5Init,
 24883       memsys5Shutdown,
 24884       0
 24885    };
 24886    return &memsys5Methods;
 24887  }
 24888  
 24889  #endif /* SQLITE_ENABLE_MEMSYS5 */
 24890  
 24891  /************** End of mem5.c ************************************************/
 24892  /************** Begin file mutex.c *******************************************/
 24893  /*
 24894  ** 2007 August 14
 24895  **
 24896  ** The author disclaims copyright to this source code.  In place of
 24897  ** a legal notice, here is a blessing:
 24898  **
 24899  **    May you do good and not evil.
 24900  **    May you find forgiveness for yourself and forgive others.
 24901  **    May you share freely, never taking more than you give.
 24902  **
 24903  *************************************************************************
 24904  ** This file contains the C functions that implement mutexes.
 24905  **
 24906  ** This file contains code that is common across all mutex implementations.
 24907  */
 24908  /* #include "sqliteInt.h" */
 24909  
 24910  #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
 24911  /*
 24912  ** For debugging purposes, record when the mutex subsystem is initialized
 24913  ** and uninitialized so that we can assert() if there is an attempt to
 24914  ** allocate a mutex while the system is uninitialized.
 24915  */
 24916  static SQLITE_WSD int mutexIsInit = 0;
 24917  #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
 24918  
 24919  
 24920  #ifndef SQLITE_MUTEX_OMIT
 24921  
 24922  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
 24923  /*
 24924  ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
 24925  ** the implementation of a wrapper around the system default mutex
 24926  ** implementation (sqlite3DefaultMutex()). 
 24927  **
 24928  ** Most calls are passed directly through to the underlying default
 24929  ** mutex implementation. Except, if a mutex is configured by calling
 24930  ** sqlite3MutexWarnOnContention() on it, then if contention is ever
 24931  ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
 24932  **
 24933  ** This type of mutex is used as the database handle mutex when testing
 24934  ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
 24935  */
 24936  
 24937  /* 
 24938  ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
 24939  ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
 24940  ** allocated by the system mutex implementation. Variable iType is usually set
 24941  ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
 24942  ** or one of the static mutex identifiers. Or, if this is a recursive mutex
 24943  ** that has been configured using sqlite3MutexWarnOnContention(), it is
 24944  ** set to SQLITE_MUTEX_WARNONCONTENTION.
 24945  */
 24946  typedef struct CheckMutex CheckMutex;
 24947  struct CheckMutex {
 24948    int iType;
 24949    sqlite3_mutex *mutex;
 24950  };
 24951  
 24952  #define SQLITE_MUTEX_WARNONCONTENTION  (-1)
 24953  
 24954  /* 
 24955  ** Pointer to real mutex methods object used by the CheckMutex
 24956  ** implementation. Set by checkMutexInit(). 
 24957  */
 24958  static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
 24959  
 24960  #ifdef SQLITE_DEBUG
 24961  static int checkMutexHeld(sqlite3_mutex *p){
 24962    return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
 24963  }
 24964  static int checkMutexNotheld(sqlite3_mutex *p){
 24965    return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
 24966  }
 24967  #endif
 24968  
 24969  /*
 24970  ** Initialize and deinitialize the mutex subsystem.
 24971  */
 24972  static int checkMutexInit(void){ 
 24973    pGlobalMutexMethods = sqlite3DefaultMutex();
 24974    return SQLITE_OK; 
 24975  }
 24976  static int checkMutexEnd(void){ 
 24977    pGlobalMutexMethods = 0;
 24978    return SQLITE_OK; 
 24979  }
 24980  
 24981  /*
 24982  ** Allocate a mutex.
 24983  */
 24984  static sqlite3_mutex *checkMutexAlloc(int iType){
 24985    static CheckMutex staticMutexes[] = {
 24986      {2, 0}, {3, 0}, {4, 0}, {5, 0},
 24987      {6, 0}, {7, 0}, {8, 0}, {9, 0},
 24988      {10, 0}, {11, 0}, {12, 0}, {13, 0}
 24989    };
 24990    CheckMutex *p = 0;
 24991  
 24992    assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
 24993    if( iType<2 ){
 24994      p = sqlite3MallocZero(sizeof(CheckMutex));
 24995      if( p==0 ) return 0;
 24996      p->iType = iType;
 24997    }else{
 24998  #ifdef SQLITE_ENABLE_API_ARMOR
 24999      if( iType-2>=ArraySize(staticMutexes) ){
 25000        (void)SQLITE_MISUSE_BKPT;
 25001        return 0;
 25002      }
 25003  #endif
 25004      p = &staticMutexes[iType-2];
 25005    }
 25006  
 25007    if( p->mutex==0 ){
 25008      p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
 25009      if( p->mutex==0 ){
 25010        if( iType<2 ){
 25011          sqlite3_free(p);
 25012        }
 25013        p = 0;
 25014      }
 25015    }
 25016  
 25017    return (sqlite3_mutex*)p;
 25018  }
 25019  
 25020  /*
 25021  ** Free a mutex.
 25022  */
 25023  static void checkMutexFree(sqlite3_mutex *p){
 25024    assert( SQLITE_MUTEX_RECURSIVE<2 );
 25025    assert( SQLITE_MUTEX_FAST<2 );
 25026    assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
 25027  
 25028  #if SQLITE_ENABLE_API_ARMOR
 25029    if( ((CheckMutex*)p)->iType<2 )
 25030  #endif
 25031    {
 25032      CheckMutex *pCheck = (CheckMutex*)p;
 25033      pGlobalMutexMethods->xMutexFree(pCheck->mutex);
 25034      sqlite3_free(pCheck);
 25035    }
 25036  #ifdef SQLITE_ENABLE_API_ARMOR
 25037    else{
 25038      (void)SQLITE_MISUSE_BKPT;
 25039    }
 25040  #endif
 25041  }
 25042  
 25043  /*
 25044  ** Enter the mutex.
 25045  */
 25046  static void checkMutexEnter(sqlite3_mutex *p){
 25047    CheckMutex *pCheck = (CheckMutex*)p;
 25048    if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
 25049      if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
 25050        return;
 25051      }
 25052      sqlite3_log(SQLITE_MISUSE, 
 25053          "illegal multi-threaded access to database connection"
 25054      );
 25055    }
 25056    pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
 25057  }
 25058  
 25059  /*
 25060  ** Enter the mutex (do not block).
 25061  */
 25062  static int checkMutexTry(sqlite3_mutex *p){
 25063    CheckMutex *pCheck = (CheckMutex*)p;
 25064    return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
 25065  }
 25066  
 25067  /*
 25068  ** Leave the mutex.
 25069  */
 25070  static void checkMutexLeave(sqlite3_mutex *p){
 25071    CheckMutex *pCheck = (CheckMutex*)p;
 25072    pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
 25073  }
 25074  
 25075  sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
 25076    static const sqlite3_mutex_methods sMutex = {
 25077      checkMutexInit,
 25078      checkMutexEnd,
 25079      checkMutexAlloc,
 25080      checkMutexFree,
 25081      checkMutexEnter,
 25082      checkMutexTry,
 25083      checkMutexLeave,
 25084  #ifdef SQLITE_DEBUG
 25085      checkMutexHeld,
 25086      checkMutexNotheld
 25087  #else
 25088      0,
 25089      0
 25090  #endif
 25091    };
 25092    return &sMutex;
 25093  }
 25094  
 25095  /*
 25096  ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
 25097  ** one on which there should be no contention.
 25098  */
 25099  SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
 25100    if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
 25101      CheckMutex *pCheck = (CheckMutex*)p;
 25102      assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
 25103      pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
 25104    }
 25105  }
 25106  #endif   /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
 25107  
 25108  /*
 25109  ** Initialize the mutex system.
 25110  */
 25111  SQLITE_PRIVATE int sqlite3MutexInit(void){ 
 25112    int rc = SQLITE_OK;
 25113    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
 25114      /* If the xMutexAlloc method has not been set, then the user did not
 25115      ** install a mutex implementation via sqlite3_config() prior to 
 25116      ** sqlite3_initialize() being called. This block copies pointers to
 25117      ** the default implementation into the sqlite3GlobalConfig structure.
 25118      */
 25119      sqlite3_mutex_methods const *pFrom;
 25120      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
 25121  
 25122      if( sqlite3GlobalConfig.bCoreMutex ){
 25123  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
 25124        pFrom = multiThreadedCheckMutex();
 25125  #else
 25126        pFrom = sqlite3DefaultMutex();
 25127  #endif
 25128      }else{
 25129        pFrom = sqlite3NoopMutex();
 25130      }
 25131      pTo->xMutexInit = pFrom->xMutexInit;
 25132      pTo->xMutexEnd = pFrom->xMutexEnd;
 25133      pTo->xMutexFree = pFrom->xMutexFree;
 25134      pTo->xMutexEnter = pFrom->xMutexEnter;
 25135      pTo->xMutexTry = pFrom->xMutexTry;
 25136      pTo->xMutexLeave = pFrom->xMutexLeave;
 25137      pTo->xMutexHeld = pFrom->xMutexHeld;
 25138      pTo->xMutexNotheld = pFrom->xMutexNotheld;
 25139      sqlite3MemoryBarrier();
 25140      pTo->xMutexAlloc = pFrom->xMutexAlloc;
 25141    }
 25142    assert( sqlite3GlobalConfig.mutex.xMutexInit );
 25143    rc = sqlite3GlobalConfig.mutex.xMutexInit();
 25144  
 25145  #ifdef SQLITE_DEBUG
 25146    GLOBAL(int, mutexIsInit) = 1;
 25147  #endif
 25148  
 25149    return rc;
 25150  }
 25151  
 25152  /*
 25153  ** Shutdown the mutex system. This call frees resources allocated by
 25154  ** sqlite3MutexInit().
 25155  */
 25156  SQLITE_PRIVATE int sqlite3MutexEnd(void){
 25157    int rc = SQLITE_OK;
 25158    if( sqlite3GlobalConfig.mutex.xMutexEnd ){
 25159      rc = sqlite3GlobalConfig.mutex.xMutexEnd();
 25160    }
 25161  
 25162  #ifdef SQLITE_DEBUG
 25163    GLOBAL(int, mutexIsInit) = 0;
 25164  #endif
 25165  
 25166    return rc;
 25167  }
 25168  
 25169  /*
 25170  ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
 25171  */
 25172  SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
 25173  #ifndef SQLITE_OMIT_AUTOINIT
 25174    if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
 25175    if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
 25176  #endif
 25177    assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
 25178    return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 25179  }
 25180  
 25181  SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
 25182    if( !sqlite3GlobalConfig.bCoreMutex ){
 25183      return 0;
 25184    }
 25185    assert( GLOBAL(int, mutexIsInit) );
 25186    assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
 25187    return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
 25188  }
 25189  
 25190  /*
 25191  ** Free a dynamic mutex.
 25192  */
 25193  SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
 25194    if( p ){
 25195      assert( sqlite3GlobalConfig.mutex.xMutexFree );
 25196      sqlite3GlobalConfig.mutex.xMutexFree(p);
 25197    }
 25198  }
 25199  
 25200  /*
 25201  ** Obtain the mutex p. If some other thread already has the mutex, block
 25202  ** until it can be obtained.
 25203  */
 25204  SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
 25205    if( p ){
 25206      assert( sqlite3GlobalConfig.mutex.xMutexEnter );
 25207      sqlite3GlobalConfig.mutex.xMutexEnter(p);
 25208    }
 25209  }
 25210  
 25211  /*
 25212  ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
 25213  ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
 25214  */
 25215  SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
 25216    int rc = SQLITE_OK;
 25217    if( p ){
 25218      assert( sqlite3GlobalConfig.mutex.xMutexTry );
 25219      return sqlite3GlobalConfig.mutex.xMutexTry(p);
 25220    }
 25221    return rc;
 25222  }
 25223  
 25224  /*
 25225  ** The sqlite3_mutex_leave() routine exits a mutex that was previously
 25226  ** entered by the same thread.  The behavior is undefined if the mutex 
 25227  ** is not currently entered. If a NULL pointer is passed as an argument
 25228  ** this function is a no-op.
 25229  */
 25230  SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
 25231    if( p ){
 25232      assert( sqlite3GlobalConfig.mutex.xMutexLeave );
 25233      sqlite3GlobalConfig.mutex.xMutexLeave(p);
 25234    }
 25235  }
 25236  
 25237  #ifndef NDEBUG
 25238  /*
 25239  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 25240  ** intended for use inside assert() statements.
 25241  */
 25242  SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
 25243    assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
 25244    return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
 25245  }
 25246  SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
 25247    assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
 25248    return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
 25249  }
 25250  #endif
 25251  
 25252  #endif /* !defined(SQLITE_MUTEX_OMIT) */
 25253  
 25254  /************** End of mutex.c ***********************************************/
 25255  /************** Begin file mutex_noop.c **************************************/
 25256  /*
 25257  ** 2008 October 07
 25258  **
 25259  ** The author disclaims copyright to this source code.  In place of
 25260  ** a legal notice, here is a blessing:
 25261  **
 25262  **    May you do good and not evil.
 25263  **    May you find forgiveness for yourself and forgive others.
 25264  **    May you share freely, never taking more than you give.
 25265  **
 25266  *************************************************************************
 25267  ** This file contains the C functions that implement mutexes.
 25268  **
 25269  ** This implementation in this file does not provide any mutual
 25270  ** exclusion and is thus suitable for use only in applications
 25271  ** that use SQLite in a single thread.  The routines defined
 25272  ** here are place-holders.  Applications can substitute working
 25273  ** mutex routines at start-time using the
 25274  **
 25275  **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
 25276  **
 25277  ** interface.
 25278  **
 25279  ** If compiled with SQLITE_DEBUG, then additional logic is inserted
 25280  ** that does error checking on mutexes to make sure they are being
 25281  ** called correctly.
 25282  */
 25283  /* #include "sqliteInt.h" */
 25284  
 25285  #ifndef SQLITE_MUTEX_OMIT
 25286  
 25287  #ifndef SQLITE_DEBUG
 25288  /*
 25289  ** Stub routines for all mutex methods.
 25290  **
 25291  ** This routines provide no mutual exclusion or error checking.
 25292  */
 25293  static int noopMutexInit(void){ return SQLITE_OK; }
 25294  static int noopMutexEnd(void){ return SQLITE_OK; }
 25295  static sqlite3_mutex *noopMutexAlloc(int id){ 
 25296    UNUSED_PARAMETER(id);
 25297    return (sqlite3_mutex*)8; 
 25298  }
 25299  static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 25300  static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 25301  static int noopMutexTry(sqlite3_mutex *p){
 25302    UNUSED_PARAMETER(p);
 25303    return SQLITE_OK;
 25304  }
 25305  static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 25306  
 25307  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 25308    static const sqlite3_mutex_methods sMutex = {
 25309      noopMutexInit,
 25310      noopMutexEnd,
 25311      noopMutexAlloc,
 25312      noopMutexFree,
 25313      noopMutexEnter,
 25314      noopMutexTry,
 25315      noopMutexLeave,
 25316  
 25317      0,
 25318      0,
 25319    };
 25320  
 25321    return &sMutex;
 25322  }
 25323  #endif /* !SQLITE_DEBUG */
 25324  
 25325  #ifdef SQLITE_DEBUG
 25326  /*
 25327  ** In this implementation, error checking is provided for testing
 25328  ** and debugging purposes.  The mutexes still do not provide any
 25329  ** mutual exclusion.
 25330  */
 25331  
 25332  /*
 25333  ** The mutex object
 25334  */
 25335  typedef struct sqlite3_debug_mutex {
 25336    int id;     /* The mutex type */
 25337    int cnt;    /* Number of entries without a matching leave */
 25338  } sqlite3_debug_mutex;
 25339  
 25340  /*
 25341  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 25342  ** intended for use inside assert() statements.
 25343  */
 25344  static int debugMutexHeld(sqlite3_mutex *pX){
 25345    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25346    return p==0 || p->cnt>0;
 25347  }
 25348  static int debugMutexNotheld(sqlite3_mutex *pX){
 25349    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25350    return p==0 || p->cnt==0;
 25351  }
 25352  
 25353  /*
 25354  ** Initialize and deinitialize the mutex subsystem.
 25355  */
 25356  static int debugMutexInit(void){ return SQLITE_OK; }
 25357  static int debugMutexEnd(void){ return SQLITE_OK; }
 25358  
 25359  /*
 25360  ** The sqlite3_mutex_alloc() routine allocates a new
 25361  ** mutex and returns a pointer to it.  If it returns NULL
 25362  ** that means that a mutex could not be allocated. 
 25363  */
 25364  static sqlite3_mutex *debugMutexAlloc(int id){
 25365    static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
 25366    sqlite3_debug_mutex *pNew = 0;
 25367    switch( id ){
 25368      case SQLITE_MUTEX_FAST:
 25369      case SQLITE_MUTEX_RECURSIVE: {
 25370        pNew = sqlite3Malloc(sizeof(*pNew));
 25371        if( pNew ){
 25372          pNew->id = id;
 25373          pNew->cnt = 0;
 25374        }
 25375        break;
 25376      }
 25377      default: {
 25378  #ifdef SQLITE_ENABLE_API_ARMOR
 25379        if( id-2<0 || id-2>=ArraySize(aStatic) ){
 25380          (void)SQLITE_MISUSE_BKPT;
 25381          return 0;
 25382        }
 25383  #endif
 25384        pNew = &aStatic[id-2];
 25385        pNew->id = id;
 25386        break;
 25387      }
 25388    }
 25389    return (sqlite3_mutex*)pNew;
 25390  }
 25391  
 25392  /*
 25393  ** This routine deallocates a previously allocated mutex.
 25394  */
 25395  static void debugMutexFree(sqlite3_mutex *pX){
 25396    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25397    assert( p->cnt==0 );
 25398    if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
 25399      sqlite3_free(p);
 25400    }else{
 25401  #ifdef SQLITE_ENABLE_API_ARMOR
 25402      (void)SQLITE_MISUSE_BKPT;
 25403  #endif
 25404    }
 25405  }
 25406  
 25407  /*
 25408  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 25409  ** to enter a mutex.  If another thread is already within the mutex,
 25410  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 25411  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 25412  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 25413  ** be entered multiple times by the same thread.  In such cases the,
 25414  ** mutex must be exited an equal number of times before another thread
 25415  ** can enter.  If the same thread tries to enter any other kind of mutex
 25416  ** more than once, the behavior is undefined.
 25417  */
 25418  static void debugMutexEnter(sqlite3_mutex *pX){
 25419    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25420    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 25421    p->cnt++;
 25422  }
 25423  static int debugMutexTry(sqlite3_mutex *pX){
 25424    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25425    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 25426    p->cnt++;
 25427    return SQLITE_OK;
 25428  }
 25429  
 25430  /*
 25431  ** The sqlite3_mutex_leave() routine exits a mutex that was
 25432  ** previously entered by the same thread.  The behavior
 25433  ** is undefined if the mutex is not currently entered or
 25434  ** is not currently allocated.  SQLite will never do either.
 25435  */
 25436  static void debugMutexLeave(sqlite3_mutex *pX){
 25437    sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
 25438    assert( debugMutexHeld(pX) );
 25439    p->cnt--;
 25440    assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
 25441  }
 25442  
 25443  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
 25444    static const sqlite3_mutex_methods sMutex = {
 25445      debugMutexInit,
 25446      debugMutexEnd,
 25447      debugMutexAlloc,
 25448      debugMutexFree,
 25449      debugMutexEnter,
 25450      debugMutexTry,
 25451      debugMutexLeave,
 25452  
 25453      debugMutexHeld,
 25454      debugMutexNotheld
 25455    };
 25456  
 25457    return &sMutex;
 25458  }
 25459  #endif /* SQLITE_DEBUG */
 25460  
 25461  /*
 25462  ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
 25463  ** is used regardless of the run-time threadsafety setting.
 25464  */
 25465  #ifdef SQLITE_MUTEX_NOOP
 25466  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 25467    return sqlite3NoopMutex();
 25468  }
 25469  #endif /* defined(SQLITE_MUTEX_NOOP) */
 25470  #endif /* !defined(SQLITE_MUTEX_OMIT) */
 25471  
 25472  /************** End of mutex_noop.c ******************************************/
 25473  /************** Begin file mutex_unix.c **************************************/
 25474  /*
 25475  ** 2007 August 28
 25476  **
 25477  ** The author disclaims copyright to this source code.  In place of
 25478  ** a legal notice, here is a blessing:
 25479  **
 25480  **    May you do good and not evil.
 25481  **    May you find forgiveness for yourself and forgive others.
 25482  **    May you share freely, never taking more than you give.
 25483  **
 25484  *************************************************************************
 25485  ** This file contains the C functions that implement mutexes for pthreads
 25486  */
 25487  /* #include "sqliteInt.h" */
 25488  
 25489  /*
 25490  ** The code in this file is only used if we are compiling threadsafe
 25491  ** under unix with pthreads.
 25492  **
 25493  ** Note that this implementation requires a version of pthreads that
 25494  ** supports recursive mutexes.
 25495  */
 25496  #ifdef SQLITE_MUTEX_PTHREADS
 25497  
 25498  #include <pthread.h>
 25499  
 25500  /*
 25501  ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
 25502  ** are necessary under two condidtions:  (1) Debug builds and (2) using
 25503  ** home-grown mutexes.  Encapsulate these conditions into a single #define.
 25504  */
 25505  #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
 25506  # define SQLITE_MUTEX_NREF 1
 25507  #else
 25508  # define SQLITE_MUTEX_NREF 0
 25509  #endif
 25510  
 25511  /*
 25512  ** Each recursive mutex is an instance of the following structure.
 25513  */
 25514  struct sqlite3_mutex {
 25515    pthread_mutex_t mutex;     /* Mutex controlling the lock */
 25516  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 25517    int id;                    /* Mutex type */
 25518  #endif
 25519  #if SQLITE_MUTEX_NREF
 25520    volatile int nRef;         /* Number of entrances */
 25521    volatile pthread_t owner;  /* Thread that is within this mutex */
 25522    int trace;                 /* True to trace changes */
 25523  #endif
 25524  };
 25525  #if SQLITE_MUTEX_NREF
 25526  # define SQLITE3_MUTEX_INITIALIZER(id) \
 25527       {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
 25528  #elif defined(SQLITE_ENABLE_API_ARMOR)
 25529  # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
 25530  #else
 25531  #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
 25532  #endif
 25533  
 25534  /*
 25535  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 25536  ** intended for use only inside assert() statements.  On some platforms,
 25537  ** there might be race conditions that can cause these routines to
 25538  ** deliver incorrect results.  In particular, if pthread_equal() is
 25539  ** not an atomic operation, then these routines might delivery
 25540  ** incorrect results.  On most platforms, pthread_equal() is a 
 25541  ** comparison of two integers and is therefore atomic.  But we are
 25542  ** told that HPUX is not such a platform.  If so, then these routines
 25543  ** will not always work correctly on HPUX.
 25544  **
 25545  ** On those platforms where pthread_equal() is not atomic, SQLite
 25546  ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
 25547  ** make sure no assert() statements are evaluated and hence these
 25548  ** routines are never called.
 25549  */
 25550  #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
 25551  static int pthreadMutexHeld(sqlite3_mutex *p){
 25552    return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
 25553  }
 25554  static int pthreadMutexNotheld(sqlite3_mutex *p){
 25555    return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
 25556  }
 25557  #endif
 25558  
 25559  /*
 25560  ** Try to provide a memory barrier operation, needed for initialization
 25561  ** and also for the implementation of xShmBarrier in the VFS in cases
 25562  ** where SQLite is compiled without mutexes.
 25563  */
 25564  SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
 25565  #if defined(SQLITE_MEMORY_BARRIER)
 25566    SQLITE_MEMORY_BARRIER;
 25567  #elif defined(__GNUC__) && GCC_VERSION>=4001000
 25568    __sync_synchronize();
 25569  #endif
 25570  }
 25571  
 25572  /*
 25573  ** Initialize and deinitialize the mutex subsystem.
 25574  */
 25575  static int pthreadMutexInit(void){ return SQLITE_OK; }
 25576  static int pthreadMutexEnd(void){ return SQLITE_OK; }
 25577  
 25578  /*
 25579  ** The sqlite3_mutex_alloc() routine allocates a new
 25580  ** mutex and returns a pointer to it.  If it returns NULL
 25581  ** that means that a mutex could not be allocated.  SQLite
 25582  ** will unwind its stack and return an error.  The argument
 25583  ** to sqlite3_mutex_alloc() is one of these integer constants:
 25584  **
 25585  ** <ul>
 25586  ** <li>  SQLITE_MUTEX_FAST
 25587  ** <li>  SQLITE_MUTEX_RECURSIVE
 25588  ** <li>  SQLITE_MUTEX_STATIC_MASTER
 25589  ** <li>  SQLITE_MUTEX_STATIC_MEM
 25590  ** <li>  SQLITE_MUTEX_STATIC_OPEN
 25591  ** <li>  SQLITE_MUTEX_STATIC_PRNG
 25592  ** <li>  SQLITE_MUTEX_STATIC_LRU
 25593  ** <li>  SQLITE_MUTEX_STATIC_PMEM
 25594  ** <li>  SQLITE_MUTEX_STATIC_APP1
 25595  ** <li>  SQLITE_MUTEX_STATIC_APP2
 25596  ** <li>  SQLITE_MUTEX_STATIC_APP3
 25597  ** <li>  SQLITE_MUTEX_STATIC_VFS1
 25598  ** <li>  SQLITE_MUTEX_STATIC_VFS2
 25599  ** <li>  SQLITE_MUTEX_STATIC_VFS3
 25600  ** </ul>
 25601  **
 25602  ** The first two constants cause sqlite3_mutex_alloc() to create
 25603  ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 25604  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 25605  ** The mutex implementation does not need to make a distinction
 25606  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 25607  ** not want to.  But SQLite will only request a recursive mutex in
 25608  ** cases where it really needs one.  If a faster non-recursive mutex
 25609  ** implementation is available on the host platform, the mutex subsystem
 25610  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
 25611  **
 25612  ** The other allowed parameters to sqlite3_mutex_alloc() each return
 25613  ** a pointer to a static preexisting mutex.  Six static mutexes are
 25614  ** used by the current version of SQLite.  Future versions of SQLite
 25615  ** may add additional static mutexes.  Static mutexes are for internal
 25616  ** use by SQLite only.  Applications that use SQLite mutexes should
 25617  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 25618  ** SQLITE_MUTEX_RECURSIVE.
 25619  **
 25620  ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 25621  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 25622  ** returns a different mutex on every call.  But for the static 
 25623  ** mutex types, the same mutex is returned on every call that has
 25624  ** the same type number.
 25625  */
 25626  static sqlite3_mutex *pthreadMutexAlloc(int iType){
 25627    static sqlite3_mutex staticMutexes[] = {
 25628      SQLITE3_MUTEX_INITIALIZER(2),
 25629      SQLITE3_MUTEX_INITIALIZER(3),
 25630      SQLITE3_MUTEX_INITIALIZER(4),
 25631      SQLITE3_MUTEX_INITIALIZER(5),
 25632      SQLITE3_MUTEX_INITIALIZER(6),
 25633      SQLITE3_MUTEX_INITIALIZER(7),
 25634      SQLITE3_MUTEX_INITIALIZER(8),
 25635      SQLITE3_MUTEX_INITIALIZER(9),
 25636      SQLITE3_MUTEX_INITIALIZER(10),
 25637      SQLITE3_MUTEX_INITIALIZER(11),
 25638      SQLITE3_MUTEX_INITIALIZER(12),
 25639      SQLITE3_MUTEX_INITIALIZER(13)
 25640    };
 25641    sqlite3_mutex *p;
 25642    switch( iType ){
 25643      case SQLITE_MUTEX_RECURSIVE: {
 25644        p = sqlite3MallocZero( sizeof(*p) );
 25645        if( p ){
 25646  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 25647          /* If recursive mutexes are not available, we will have to
 25648          ** build our own.  See below. */
 25649          pthread_mutex_init(&p->mutex, 0);
 25650  #else
 25651          /* Use a recursive mutex if it is available */
 25652          pthread_mutexattr_t recursiveAttr;
 25653          pthread_mutexattr_init(&recursiveAttr);
 25654          pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
 25655          pthread_mutex_init(&p->mutex, &recursiveAttr);
 25656          pthread_mutexattr_destroy(&recursiveAttr);
 25657  #endif
 25658  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 25659          p->id = SQLITE_MUTEX_RECURSIVE;
 25660  #endif
 25661        }
 25662        break;
 25663      }
 25664      case SQLITE_MUTEX_FAST: {
 25665        p = sqlite3MallocZero( sizeof(*p) );
 25666        if( p ){
 25667          pthread_mutex_init(&p->mutex, 0);
 25668  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 25669          p->id = SQLITE_MUTEX_FAST;
 25670  #endif
 25671        }
 25672        break;
 25673      }
 25674      default: {
 25675  #ifdef SQLITE_ENABLE_API_ARMOR
 25676        if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
 25677          (void)SQLITE_MISUSE_BKPT;
 25678          return 0;
 25679        }
 25680  #endif
 25681        p = &staticMutexes[iType-2];
 25682        break;
 25683      }
 25684    }
 25685  #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
 25686    assert( p==0 || p->id==iType );
 25687  #endif
 25688    return p;
 25689  }
 25690  
 25691  
 25692  /*
 25693  ** This routine deallocates a previously
 25694  ** allocated mutex.  SQLite is careful to deallocate every
 25695  ** mutex that it allocates.
 25696  */
 25697  static void pthreadMutexFree(sqlite3_mutex *p){
 25698    assert( p->nRef==0 );
 25699  #if SQLITE_ENABLE_API_ARMOR
 25700    if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
 25701  #endif
 25702    {
 25703      pthread_mutex_destroy(&p->mutex);
 25704      sqlite3_free(p);
 25705    }
 25706  #ifdef SQLITE_ENABLE_API_ARMOR
 25707    else{
 25708      (void)SQLITE_MISUSE_BKPT;
 25709    }
 25710  #endif
 25711  }
 25712  
 25713  /*
 25714  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 25715  ** to enter a mutex.  If another thread is already within the mutex,
 25716  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 25717  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 25718  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 25719  ** be entered multiple times by the same thread.  In such cases the,
 25720  ** mutex must be exited an equal number of times before another thread
 25721  ** can enter.  If the same thread tries to enter any other kind of mutex
 25722  ** more than once, the behavior is undefined.
 25723  */
 25724  static void pthreadMutexEnter(sqlite3_mutex *p){
 25725    assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 25726  
 25727  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 25728    /* If recursive mutexes are not available, then we have to grow
 25729    ** our own.  This implementation assumes that pthread_equal()
 25730    ** is atomic - that it cannot be deceived into thinking self
 25731    ** and p->owner are equal if p->owner changes between two values
 25732    ** that are not equal to self while the comparison is taking place.
 25733    ** This implementation also assumes a coherent cache - that 
 25734    ** separate processes cannot read different values from the same
 25735    ** address at the same time.  If either of these two conditions
 25736    ** are not met, then the mutexes will fail and problems will result.
 25737    */
 25738    {
 25739      pthread_t self = pthread_self();
 25740      if( p->nRef>0 && pthread_equal(p->owner, self) ){
 25741        p->nRef++;
 25742      }else{
 25743        pthread_mutex_lock(&p->mutex);
 25744        assert( p->nRef==0 );
 25745        p->owner = self;
 25746        p->nRef = 1;
 25747      }
 25748    }
 25749  #else
 25750    /* Use the built-in recursive mutexes if they are available.
 25751    */
 25752    pthread_mutex_lock(&p->mutex);
 25753  #if SQLITE_MUTEX_NREF
 25754    assert( p->nRef>0 || p->owner==0 );
 25755    p->owner = pthread_self();
 25756    p->nRef++;
 25757  #endif
 25758  #endif
 25759  
 25760  #ifdef SQLITE_DEBUG
 25761    if( p->trace ){
 25762      printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 25763    }
 25764  #endif
 25765  }
 25766  static int pthreadMutexTry(sqlite3_mutex *p){
 25767    int rc;
 25768    assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
 25769  
 25770  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 25771    /* If recursive mutexes are not available, then we have to grow
 25772    ** our own.  This implementation assumes that pthread_equal()
 25773    ** is atomic - that it cannot be deceived into thinking self
 25774    ** and p->owner are equal if p->owner changes between two values
 25775    ** that are not equal to self while the comparison is taking place.
 25776    ** This implementation also assumes a coherent cache - that 
 25777    ** separate processes cannot read different values from the same
 25778    ** address at the same time.  If either of these two conditions
 25779    ** are not met, then the mutexes will fail and problems will result.
 25780    */
 25781    {
 25782      pthread_t self = pthread_self();
 25783      if( p->nRef>0 && pthread_equal(p->owner, self) ){
 25784        p->nRef++;
 25785        rc = SQLITE_OK;
 25786      }else if( pthread_mutex_trylock(&p->mutex)==0 ){
 25787        assert( p->nRef==0 );
 25788        p->owner = self;
 25789        p->nRef = 1;
 25790        rc = SQLITE_OK;
 25791      }else{
 25792        rc = SQLITE_BUSY;
 25793      }
 25794    }
 25795  #else
 25796    /* Use the built-in recursive mutexes if they are available.
 25797    */
 25798    if( pthread_mutex_trylock(&p->mutex)==0 ){
 25799  #if SQLITE_MUTEX_NREF
 25800      p->owner = pthread_self();
 25801      p->nRef++;
 25802  #endif
 25803      rc = SQLITE_OK;
 25804    }else{
 25805      rc = SQLITE_BUSY;
 25806    }
 25807  #endif
 25808  
 25809  #ifdef SQLITE_DEBUG
 25810    if( rc==SQLITE_OK && p->trace ){
 25811      printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 25812    }
 25813  #endif
 25814    return rc;
 25815  }
 25816  
 25817  /*
 25818  ** The sqlite3_mutex_leave() routine exits a mutex that was
 25819  ** previously entered by the same thread.  The behavior
 25820  ** is undefined if the mutex is not currently entered or
 25821  ** is not currently allocated.  SQLite will never do either.
 25822  */
 25823  static void pthreadMutexLeave(sqlite3_mutex *p){
 25824    assert( pthreadMutexHeld(p) );
 25825  #if SQLITE_MUTEX_NREF
 25826    p->nRef--;
 25827    if( p->nRef==0 ) p->owner = 0;
 25828  #endif
 25829    assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 25830  
 25831  #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
 25832    if( p->nRef==0 ){
 25833      pthread_mutex_unlock(&p->mutex);
 25834    }
 25835  #else
 25836    pthread_mutex_unlock(&p->mutex);
 25837  #endif
 25838  
 25839  #ifdef SQLITE_DEBUG
 25840    if( p->trace ){
 25841      printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
 25842    }
 25843  #endif
 25844  }
 25845  
 25846  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 25847    static const sqlite3_mutex_methods sMutex = {
 25848      pthreadMutexInit,
 25849      pthreadMutexEnd,
 25850      pthreadMutexAlloc,
 25851      pthreadMutexFree,
 25852      pthreadMutexEnter,
 25853      pthreadMutexTry,
 25854      pthreadMutexLeave,
 25855  #ifdef SQLITE_DEBUG
 25856      pthreadMutexHeld,
 25857      pthreadMutexNotheld
 25858  #else
 25859      0,
 25860      0
 25861  #endif
 25862    };
 25863  
 25864    return &sMutex;
 25865  }
 25866  
 25867  #endif /* SQLITE_MUTEX_PTHREADS */
 25868  
 25869  /************** End of mutex_unix.c ******************************************/
 25870  /************** Begin file mutex_w32.c ***************************************/
 25871  /*
 25872  ** 2007 August 14
 25873  **
 25874  ** The author disclaims copyright to this source code.  In place of
 25875  ** a legal notice, here is a blessing:
 25876  **
 25877  **    May you do good and not evil.
 25878  **    May you find forgiveness for yourself and forgive others.
 25879  **    May you share freely, never taking more than you give.
 25880  **
 25881  *************************************************************************
 25882  ** This file contains the C functions that implement mutexes for Win32.
 25883  */
 25884  /* #include "sqliteInt.h" */
 25885  
 25886  #if SQLITE_OS_WIN
 25887  /*
 25888  ** Include code that is common to all os_*.c files
 25889  */
 25890  /************** Include os_common.h in the middle of mutex_w32.c *************/
 25891  /************** Begin file os_common.h ***************************************/
 25892  /*
 25893  ** 2004 May 22
 25894  **
 25895  ** The author disclaims copyright to this source code.  In place of
 25896  ** a legal notice, here is a blessing:
 25897  **
 25898  **    May you do good and not evil.
 25899  **    May you find forgiveness for yourself and forgive others.
 25900  **    May you share freely, never taking more than you give.
 25901  **
 25902  ******************************************************************************
 25903  **
 25904  ** This file contains macros and a little bit of code that is common to
 25905  ** all of the platform-specific files (os_*.c) and is #included into those
 25906  ** files.
 25907  **
 25908  ** This file should be #included by the os_*.c files only.  It is not a
 25909  ** general purpose header file.
 25910  */
 25911  #ifndef _OS_COMMON_H_
 25912  #define _OS_COMMON_H_
 25913  
 25914  /*
 25915  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 25916  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 25917  ** switch.  The following code should catch this problem at compile-time.
 25918  */
 25919  #ifdef MEMORY_DEBUG
 25920  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 25921  #endif
 25922  
 25923  /*
 25924  ** Macros for performance tracing.  Normally turned off.  Only works
 25925  ** on i486 hardware.
 25926  */
 25927  #ifdef SQLITE_PERFORMANCE_TRACE
 25928  
 25929  /*
 25930  ** hwtime.h contains inline assembler code for implementing
 25931  ** high-performance timing routines.
 25932  */
 25933  /************** Include hwtime.h in the middle of os_common.h ****************/
 25934  /************** Begin file hwtime.h ******************************************/
 25935  /*
 25936  ** 2008 May 27
 25937  **
 25938  ** The author disclaims copyright to this source code.  In place of
 25939  ** a legal notice, here is a blessing:
 25940  **
 25941  **    May you do good and not evil.
 25942  **    May you find forgiveness for yourself and forgive others.
 25943  **    May you share freely, never taking more than you give.
 25944  **
 25945  ******************************************************************************
 25946  **
 25947  ** This file contains inline asm code for retrieving "high-performance"
 25948  ** counters for x86 class CPUs.
 25949  */
 25950  #ifndef SQLITE_HWTIME_H
 25951  #define SQLITE_HWTIME_H
 25952  
 25953  /*
 25954  ** The following routine only works on pentium-class (or newer) processors.
 25955  ** It uses the RDTSC opcode to read the cycle count value out of the
 25956  ** processor and returns that value.  This can be used for high-res
 25957  ** profiling.
 25958  */
 25959  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 25960        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 25961  
 25962    #if defined(__GNUC__)
 25963  
 25964    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 25965       unsigned int lo, hi;
 25966       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 25967       return (sqlite_uint64)hi << 32 | lo;
 25968    }
 25969  
 25970    #elif defined(_MSC_VER)
 25971  
 25972    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 25973       __asm {
 25974          rdtsc
 25975          ret       ; return value at EDX:EAX
 25976       }
 25977    }
 25978  
 25979    #endif
 25980  
 25981  #elif (defined(__GNUC__) && defined(__x86_64__))
 25982  
 25983    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 25984        unsigned long val;
 25985        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 25986        return val;
 25987    }
 25988   
 25989  #elif (defined(__GNUC__) && defined(__ppc__))
 25990  
 25991    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 25992        unsigned long long retval;
 25993        unsigned long junk;
 25994        __asm__ __volatile__ ("\n\
 25995            1:      mftbu   %1\n\
 25996                    mftb    %L0\n\
 25997                    mftbu   %0\n\
 25998                    cmpw    %0,%1\n\
 25999                    bne     1b"
 26000                    : "=r" (retval), "=r" (junk));
 26001        return retval;
 26002    }
 26003  
 26004  #else
 26005  
 26006    #error Need implementation of sqlite3Hwtime() for your platform.
 26007  
 26008    /*
 26009    ** To compile without implementing sqlite3Hwtime() for your platform,
 26010    ** you can remove the above #error and use the following
 26011    ** stub function.  You will lose timing support for many
 26012    ** of the debugging and testing utilities, but it should at
 26013    ** least compile and run.
 26014    */
 26015  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 26016  
 26017  #endif
 26018  
 26019  #endif /* !defined(SQLITE_HWTIME_H) */
 26020  
 26021  /************** End of hwtime.h **********************************************/
 26022  /************** Continuing where we left off in os_common.h ******************/
 26023  
 26024  static sqlite_uint64 g_start;
 26025  static sqlite_uint64 g_elapsed;
 26026  #define TIMER_START       g_start=sqlite3Hwtime()
 26027  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 26028  #define TIMER_ELAPSED     g_elapsed
 26029  #else
 26030  #define TIMER_START
 26031  #define TIMER_END
 26032  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 26033  #endif
 26034  
 26035  /*
 26036  ** If we compile with the SQLITE_TEST macro set, then the following block
 26037  ** of code will give us the ability to simulate a disk I/O error.  This
 26038  ** is used for testing the I/O recovery logic.
 26039  */
 26040  #if defined(SQLITE_TEST)
 26041  SQLITE_API extern int sqlite3_io_error_hit;
 26042  SQLITE_API extern int sqlite3_io_error_hardhit;
 26043  SQLITE_API extern int sqlite3_io_error_pending;
 26044  SQLITE_API extern int sqlite3_io_error_persist;
 26045  SQLITE_API extern int sqlite3_io_error_benign;
 26046  SQLITE_API extern int sqlite3_diskfull_pending;
 26047  SQLITE_API extern int sqlite3_diskfull;
 26048  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 26049  #define SimulateIOError(CODE)  \
 26050    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 26051         || sqlite3_io_error_pending-- == 1 )  \
 26052                { local_ioerr(); CODE; }
 26053  static void local_ioerr(){
 26054    IOTRACE(("IOERR\n"));
 26055    sqlite3_io_error_hit++;
 26056    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 26057  }
 26058  #define SimulateDiskfullError(CODE) \
 26059     if( sqlite3_diskfull_pending ){ \
 26060       if( sqlite3_diskfull_pending == 1 ){ \
 26061         local_ioerr(); \
 26062         sqlite3_diskfull = 1; \
 26063         sqlite3_io_error_hit = 1; \
 26064         CODE; \
 26065       }else{ \
 26066         sqlite3_diskfull_pending--; \
 26067       } \
 26068     }
 26069  #else
 26070  #define SimulateIOErrorBenign(X)
 26071  #define SimulateIOError(A)
 26072  #define SimulateDiskfullError(A)
 26073  #endif /* defined(SQLITE_TEST) */
 26074  
 26075  /*
 26076  ** When testing, keep a count of the number of open files.
 26077  */
 26078  #if defined(SQLITE_TEST)
 26079  SQLITE_API extern int sqlite3_open_file_count;
 26080  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 26081  #else
 26082  #define OpenCounter(X)
 26083  #endif /* defined(SQLITE_TEST) */
 26084  
 26085  #endif /* !defined(_OS_COMMON_H_) */
 26086  
 26087  /************** End of os_common.h *******************************************/
 26088  /************** Continuing where we left off in mutex_w32.c ******************/
 26089  
 26090  /*
 26091  ** Include the header file for the Windows VFS.
 26092  */
 26093  /************** Include os_win.h in the middle of mutex_w32.c ****************/
 26094  /************** Begin file os_win.h ******************************************/
 26095  /*
 26096  ** 2013 November 25
 26097  **
 26098  ** The author disclaims copyright to this source code.  In place of
 26099  ** a legal notice, here is a blessing:
 26100  **
 26101  **    May you do good and not evil.
 26102  **    May you find forgiveness for yourself and forgive others.
 26103  **    May you share freely, never taking more than you give.
 26104  **
 26105  ******************************************************************************
 26106  **
 26107  ** This file contains code that is specific to Windows.
 26108  */
 26109  #ifndef SQLITE_OS_WIN_H
 26110  #define SQLITE_OS_WIN_H
 26111  
 26112  /*
 26113  ** Include the primary Windows SDK header file.
 26114  */
 26115  #include "windows.h"
 26116  
 26117  #ifdef __CYGWIN__
 26118  # include <sys/cygwin.h>
 26119  #endif
 26120  #if defined(__CYGWIN__) | defined(__MINGW32__)
 26121  # include <errno.h> /* amalgamator: dontcache */
 26122  #endif
 26123  
 26124  /*
 26125  ** Determine if we are dealing with Windows NT.
 26126  **
 26127  ** We ought to be able to determine if we are compiling for Windows 9x or
 26128  ** Windows NT using the _WIN32_WINNT macro as follows:
 26129  **
 26130  ** #if defined(_WIN32_WINNT)
 26131  ** # define SQLITE_OS_WINNT 1
 26132  ** #else
 26133  ** # define SQLITE_OS_WINNT 0
 26134  ** #endif
 26135  **
 26136  ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
 26137  ** it ought to, so the above test does not work.  We'll just assume that
 26138  ** everything is Windows NT unless the programmer explicitly says otherwise
 26139  ** by setting SQLITE_OS_WINNT to 0.
 26140  */
 26141  #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
 26142  # define SQLITE_OS_WINNT 1
 26143  #endif
 26144  
 26145  /*
 26146  ** Determine if we are dealing with Windows CE - which has a much reduced
 26147  ** API.
 26148  */
 26149  #if defined(_WIN32_WCE)
 26150  # define SQLITE_OS_WINCE 1
 26151  #else
 26152  # define SQLITE_OS_WINCE 0
 26153  #endif
 26154  
 26155  /*
 26156  ** Determine if we are dealing with WinRT, which provides only a subset of
 26157  ** the full Win32 API.
 26158  */
 26159  #if !defined(SQLITE_OS_WINRT)
 26160  # define SQLITE_OS_WINRT 0
 26161  #endif
 26162  
 26163  /*
 26164  ** For WinCE, some API function parameters do not appear to be declared as
 26165  ** volatile.
 26166  */
 26167  #if SQLITE_OS_WINCE
 26168  # define SQLITE_WIN32_VOLATILE
 26169  #else
 26170  # define SQLITE_WIN32_VOLATILE volatile
 26171  #endif
 26172  
 26173  /*
 26174  ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
 26175  ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
 26176  */
 26177  #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
 26178      SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
 26179  # define SQLITE_OS_WIN_THREADS 1
 26180  #else
 26181  # define SQLITE_OS_WIN_THREADS 0
 26182  #endif
 26183  
 26184  #endif /* SQLITE_OS_WIN_H */
 26185  
 26186  /************** End of os_win.h **********************************************/
 26187  /************** Continuing where we left off in mutex_w32.c ******************/
 26188  #endif
 26189  
 26190  /*
 26191  ** The code in this file is only used if we are compiling multithreaded
 26192  ** on a Win32 system.
 26193  */
 26194  #ifdef SQLITE_MUTEX_W32
 26195  
 26196  /*
 26197  ** Each recursive mutex is an instance of the following structure.
 26198  */
 26199  struct sqlite3_mutex {
 26200    CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
 26201    int id;                    /* Mutex type */
 26202  #ifdef SQLITE_DEBUG
 26203    volatile int nRef;         /* Number of enterances */
 26204    volatile DWORD owner;      /* Thread holding this mutex */
 26205    volatile LONG trace;       /* True to trace changes */
 26206  #endif
 26207  };
 26208  
 26209  /*
 26210  ** These are the initializer values used when declaring a "static" mutex
 26211  ** on Win32.  It should be noted that all mutexes require initialization
 26212  ** on the Win32 platform.
 26213  */
 26214  #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
 26215  
 26216  #ifdef SQLITE_DEBUG
 26217  #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
 26218                                      0L, (DWORD)0, 0 }
 26219  #else
 26220  #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
 26221  #endif
 26222  
 26223  #ifdef SQLITE_DEBUG
 26224  /*
 26225  ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
 26226  ** intended for use only inside assert() statements.
 26227  */
 26228  static int winMutexHeld(sqlite3_mutex *p){
 26229    return p->nRef!=0 && p->owner==GetCurrentThreadId();
 26230  }
 26231  
 26232  static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
 26233    return p->nRef==0 || p->owner!=tid;
 26234  }
 26235  
 26236  static int winMutexNotheld(sqlite3_mutex *p){
 26237    DWORD tid = GetCurrentThreadId();
 26238    return winMutexNotheld2(p, tid);
 26239  }
 26240  #endif
 26241  
 26242  /*
 26243  ** Try to provide a memory barrier operation, needed for initialization
 26244  ** and also for the xShmBarrier method of the VFS in cases when SQLite is
 26245  ** compiled without mutexes (SQLITE_THREADSAFE=0).
 26246  */
 26247  SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
 26248  #if defined(SQLITE_MEMORY_BARRIER)
 26249    SQLITE_MEMORY_BARRIER;
 26250  #elif defined(__GNUC__)
 26251    __sync_synchronize();
 26252  #elif MSVC_VERSION>=1300
 26253    _ReadWriteBarrier();
 26254  #elif defined(MemoryBarrier)
 26255    MemoryBarrier();
 26256  #endif
 26257  }
 26258  
 26259  /*
 26260  ** Initialize and deinitialize the mutex subsystem.
 26261  */
 26262  static sqlite3_mutex winMutex_staticMutexes[] = {
 26263    SQLITE3_MUTEX_INITIALIZER(2),
 26264    SQLITE3_MUTEX_INITIALIZER(3),
 26265    SQLITE3_MUTEX_INITIALIZER(4),
 26266    SQLITE3_MUTEX_INITIALIZER(5),
 26267    SQLITE3_MUTEX_INITIALIZER(6),
 26268    SQLITE3_MUTEX_INITIALIZER(7),
 26269    SQLITE3_MUTEX_INITIALIZER(8),
 26270    SQLITE3_MUTEX_INITIALIZER(9),
 26271    SQLITE3_MUTEX_INITIALIZER(10),
 26272    SQLITE3_MUTEX_INITIALIZER(11),
 26273    SQLITE3_MUTEX_INITIALIZER(12),
 26274    SQLITE3_MUTEX_INITIALIZER(13)
 26275  };
 26276  
 26277  static int winMutex_isInit = 0;
 26278  static int winMutex_isNt = -1; /* <0 means "need to query" */
 26279  
 26280  /* As the winMutexInit() and winMutexEnd() functions are called as part
 26281  ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
 26282  ** "interlocked" magic used here is probably not strictly necessary.
 26283  */
 26284  static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
 26285  
 26286  SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
 26287  SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
 26288  
 26289  static int winMutexInit(void){
 26290    /* The first to increment to 1 does actual initialization */
 26291    if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
 26292      int i;
 26293      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 26294  #if SQLITE_OS_WINRT
 26295        InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
 26296  #else
 26297        InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
 26298  #endif
 26299      }
 26300      winMutex_isInit = 1;
 26301    }else{
 26302      /* Another thread is (in the process of) initializing the static
 26303      ** mutexes */
 26304      while( !winMutex_isInit ){
 26305        sqlite3_win32_sleep(1);
 26306      }
 26307    }
 26308    return SQLITE_OK;
 26309  }
 26310  
 26311  static int winMutexEnd(void){
 26312    /* The first to decrement to 0 does actual shutdown
 26313    ** (which should be the last to shutdown.) */
 26314    if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
 26315      if( winMutex_isInit==1 ){
 26316        int i;
 26317        for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
 26318          DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
 26319        }
 26320        winMutex_isInit = 0;
 26321      }
 26322    }
 26323    return SQLITE_OK;
 26324  }
 26325  
 26326  /*
 26327  ** The sqlite3_mutex_alloc() routine allocates a new
 26328  ** mutex and returns a pointer to it.  If it returns NULL
 26329  ** that means that a mutex could not be allocated.  SQLite
 26330  ** will unwind its stack and return an error.  The argument
 26331  ** to sqlite3_mutex_alloc() is one of these integer constants:
 26332  **
 26333  ** <ul>
 26334  ** <li>  SQLITE_MUTEX_FAST
 26335  ** <li>  SQLITE_MUTEX_RECURSIVE
 26336  ** <li>  SQLITE_MUTEX_STATIC_MASTER
 26337  ** <li>  SQLITE_MUTEX_STATIC_MEM
 26338  ** <li>  SQLITE_MUTEX_STATIC_OPEN
 26339  ** <li>  SQLITE_MUTEX_STATIC_PRNG
 26340  ** <li>  SQLITE_MUTEX_STATIC_LRU
 26341  ** <li>  SQLITE_MUTEX_STATIC_PMEM
 26342  ** <li>  SQLITE_MUTEX_STATIC_APP1
 26343  ** <li>  SQLITE_MUTEX_STATIC_APP2
 26344  ** <li>  SQLITE_MUTEX_STATIC_APP3
 26345  ** <li>  SQLITE_MUTEX_STATIC_VFS1
 26346  ** <li>  SQLITE_MUTEX_STATIC_VFS2
 26347  ** <li>  SQLITE_MUTEX_STATIC_VFS3
 26348  ** </ul>
 26349  **
 26350  ** The first two constants cause sqlite3_mutex_alloc() to create
 26351  ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 26352  ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 26353  ** The mutex implementation does not need to make a distinction
 26354  ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 26355  ** not want to.  But SQLite will only request a recursive mutex in
 26356  ** cases where it really needs one.  If a faster non-recursive mutex
 26357  ** implementation is available on the host platform, the mutex subsystem
 26358  ** might return such a mutex in response to SQLITE_MUTEX_FAST.
 26359  **
 26360  ** The other allowed parameters to sqlite3_mutex_alloc() each return
 26361  ** a pointer to a static preexisting mutex.  Six static mutexes are
 26362  ** used by the current version of SQLite.  Future versions of SQLite
 26363  ** may add additional static mutexes.  Static mutexes are for internal
 26364  ** use by SQLite only.  Applications that use SQLite mutexes should
 26365  ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 26366  ** SQLITE_MUTEX_RECURSIVE.
 26367  **
 26368  ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 26369  ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 26370  ** returns a different mutex on every call.  But for the static
 26371  ** mutex types, the same mutex is returned on every call that has
 26372  ** the same type number.
 26373  */
 26374  static sqlite3_mutex *winMutexAlloc(int iType){
 26375    sqlite3_mutex *p;
 26376  
 26377    switch( iType ){
 26378      case SQLITE_MUTEX_FAST:
 26379      case SQLITE_MUTEX_RECURSIVE: {
 26380        p = sqlite3MallocZero( sizeof(*p) );
 26381        if( p ){
 26382          p->id = iType;
 26383  #ifdef SQLITE_DEBUG
 26384  #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
 26385          p->trace = 1;
 26386  #endif
 26387  #endif
 26388  #if SQLITE_OS_WINRT
 26389          InitializeCriticalSectionEx(&p->mutex, 0, 0);
 26390  #else
 26391          InitializeCriticalSection(&p->mutex);
 26392  #endif
 26393        }
 26394        break;
 26395      }
 26396      default: {
 26397  #ifdef SQLITE_ENABLE_API_ARMOR
 26398        if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
 26399          (void)SQLITE_MISUSE_BKPT;
 26400          return 0;
 26401        }
 26402  #endif
 26403        p = &winMutex_staticMutexes[iType-2];
 26404  #ifdef SQLITE_DEBUG
 26405  #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
 26406        InterlockedCompareExchange(&p->trace, 1, 0);
 26407  #endif
 26408  #endif
 26409        break;
 26410      }
 26411    }
 26412    assert( p==0 || p->id==iType );
 26413    return p;
 26414  }
 26415  
 26416  
 26417  /*
 26418  ** This routine deallocates a previously
 26419  ** allocated mutex.  SQLite is careful to deallocate every
 26420  ** mutex that it allocates.
 26421  */
 26422  static void winMutexFree(sqlite3_mutex *p){
 26423    assert( p );
 26424    assert( p->nRef==0 && p->owner==0 );
 26425    if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
 26426      DeleteCriticalSection(&p->mutex);
 26427      sqlite3_free(p);
 26428    }else{
 26429  #ifdef SQLITE_ENABLE_API_ARMOR
 26430      (void)SQLITE_MISUSE_BKPT;
 26431  #endif
 26432    }
 26433  }
 26434  
 26435  /*
 26436  ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 26437  ** to enter a mutex.  If another thread is already within the mutex,
 26438  ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 26439  ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
 26440  ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
 26441  ** be entered multiple times by the same thread.  In such cases the,
 26442  ** mutex must be exited an equal number of times before another thread
 26443  ** can enter.  If the same thread tries to enter any other kind of mutex
 26444  ** more than once, the behavior is undefined.
 26445  */
 26446  static void winMutexEnter(sqlite3_mutex *p){
 26447  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 26448    DWORD tid = GetCurrentThreadId();
 26449  #endif
 26450  #ifdef SQLITE_DEBUG
 26451    assert( p );
 26452    assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 26453  #else
 26454    assert( p );
 26455  #endif
 26456    assert( winMutex_isInit==1 );
 26457    EnterCriticalSection(&p->mutex);
 26458  #ifdef SQLITE_DEBUG
 26459    assert( p->nRef>0 || p->owner==0 );
 26460    p->owner = tid;
 26461    p->nRef++;
 26462    if( p->trace ){
 26463      OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
 26464               tid, p->id, p, p->trace, p->nRef));
 26465    }
 26466  #endif
 26467  }
 26468  
 26469  static int winMutexTry(sqlite3_mutex *p){
 26470  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 26471    DWORD tid = GetCurrentThreadId();
 26472  #endif
 26473    int rc = SQLITE_BUSY;
 26474    assert( p );
 26475    assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
 26476    /*
 26477    ** The sqlite3_mutex_try() routine is very rarely used, and when it
 26478    ** is used it is merely an optimization.  So it is OK for it to always
 26479    ** fail.
 26480    **
 26481    ** The TryEnterCriticalSection() interface is only available on WinNT.
 26482    ** And some windows compilers complain if you try to use it without
 26483    ** first doing some #defines that prevent SQLite from building on Win98.
 26484    ** For that reason, we will omit this optimization for now.  See
 26485    ** ticket #2685.
 26486    */
 26487  #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
 26488    assert( winMutex_isInit==1 );
 26489    assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
 26490    if( winMutex_isNt<0 ){
 26491      winMutex_isNt = sqlite3_win32_is_nt();
 26492    }
 26493    assert( winMutex_isNt==0 || winMutex_isNt==1 );
 26494    if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
 26495  #ifdef SQLITE_DEBUG
 26496      p->owner = tid;
 26497      p->nRef++;
 26498  #endif
 26499      rc = SQLITE_OK;
 26500    }
 26501  #else
 26502    UNUSED_PARAMETER(p);
 26503  #endif
 26504  #ifdef SQLITE_DEBUG
 26505    if( p->trace ){
 26506      OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
 26507               tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
 26508    }
 26509  #endif
 26510    return rc;
 26511  }
 26512  
 26513  /*
 26514  ** The sqlite3_mutex_leave() routine exits a mutex that was
 26515  ** previously entered by the same thread.  The behavior
 26516  ** is undefined if the mutex is not currently entered or
 26517  ** is not currently allocated.  SQLite will never do either.
 26518  */
 26519  static void winMutexLeave(sqlite3_mutex *p){
 26520  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 26521    DWORD tid = GetCurrentThreadId();
 26522  #endif
 26523    assert( p );
 26524  #ifdef SQLITE_DEBUG
 26525    assert( p->nRef>0 );
 26526    assert( p->owner==tid );
 26527    p->nRef--;
 26528    if( p->nRef==0 ) p->owner = 0;
 26529    assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
 26530  #endif
 26531    assert( winMutex_isInit==1 );
 26532    LeaveCriticalSection(&p->mutex);
 26533  #ifdef SQLITE_DEBUG
 26534    if( p->trace ){
 26535      OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
 26536               tid, p->id, p, p->trace, p->nRef));
 26537    }
 26538  #endif
 26539  }
 26540  
 26541  SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 26542    static const sqlite3_mutex_methods sMutex = {
 26543      winMutexInit,
 26544      winMutexEnd,
 26545      winMutexAlloc,
 26546      winMutexFree,
 26547      winMutexEnter,
 26548      winMutexTry,
 26549      winMutexLeave,
 26550  #ifdef SQLITE_DEBUG
 26551      winMutexHeld,
 26552      winMutexNotheld
 26553  #else
 26554      0,
 26555      0
 26556  #endif
 26557    };
 26558    return &sMutex;
 26559  }
 26560  
 26561  #endif /* SQLITE_MUTEX_W32 */
 26562  
 26563  /************** End of mutex_w32.c *******************************************/
 26564  /************** Begin file malloc.c ******************************************/
 26565  /*
 26566  ** 2001 September 15
 26567  **
 26568  ** The author disclaims copyright to this source code.  In place of
 26569  ** a legal notice, here is a blessing:
 26570  **
 26571  **    May you do good and not evil.
 26572  **    May you find forgiveness for yourself and forgive others.
 26573  **    May you share freely, never taking more than you give.
 26574  **
 26575  *************************************************************************
 26576  **
 26577  ** Memory allocation functions used throughout sqlite.
 26578  */
 26579  /* #include "sqliteInt.h" */
 26580  /* #include <stdarg.h> */
 26581  
 26582  /*
 26583  ** Attempt to release up to n bytes of non-essential memory currently
 26584  ** held by SQLite. An example of non-essential memory is memory used to
 26585  ** cache database pages that are not currently in use.
 26586  */
 26587  SQLITE_API int sqlite3_release_memory(int n){
 26588  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 26589    return sqlite3PcacheReleaseMemory(n);
 26590  #else
 26591    /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
 26592    ** is a no-op returning zero if SQLite is not compiled with
 26593    ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
 26594    UNUSED_PARAMETER(n);
 26595    return 0;
 26596  #endif
 26597  }
 26598  
 26599  /*
 26600  ** State information local to the memory allocation subsystem.
 26601  */
 26602  static SQLITE_WSD struct Mem0Global {
 26603    sqlite3_mutex *mutex;         /* Mutex to serialize access */
 26604    sqlite3_int64 alarmThreshold; /* The soft heap limit */
 26605  
 26606    /*
 26607    ** True if heap is nearly "full" where "full" is defined by the
 26608    ** sqlite3_soft_heap_limit() setting.
 26609    */
 26610    int nearlyFull;
 26611  } mem0 = { 0, 0, 0 };
 26612  
 26613  #define mem0 GLOBAL(struct Mem0Global, mem0)
 26614  
 26615  /*
 26616  ** Return the memory allocator mutex. sqlite3_status() needs it.
 26617  */
 26618  SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
 26619    return mem0.mutex;
 26620  }
 26621  
 26622  #ifndef SQLITE_OMIT_DEPRECATED
 26623  /*
 26624  ** Deprecated external interface.  It used to set an alarm callback
 26625  ** that was invoked when memory usage grew too large.  Now it is a
 26626  ** no-op.
 26627  */
 26628  SQLITE_API int sqlite3_memory_alarm(
 26629    void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
 26630    void *pArg,
 26631    sqlite3_int64 iThreshold
 26632  ){
 26633    (void)xCallback;
 26634    (void)pArg;
 26635    (void)iThreshold;
 26636    return SQLITE_OK;
 26637  }
 26638  #endif
 26639  
 26640  /*
 26641  ** Set the soft heap-size limit for the library. Passing a zero or 
 26642  ** negative value indicates no limit.
 26643  */
 26644  SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
 26645    sqlite3_int64 priorLimit;
 26646    sqlite3_int64 excess;
 26647    sqlite3_int64 nUsed;
 26648  #ifndef SQLITE_OMIT_AUTOINIT
 26649    int rc = sqlite3_initialize();
 26650    if( rc ) return -1;
 26651  #endif
 26652    sqlite3_mutex_enter(mem0.mutex);
 26653    priorLimit = mem0.alarmThreshold;
 26654    if( n<0 ){
 26655      sqlite3_mutex_leave(mem0.mutex);
 26656      return priorLimit;
 26657    }
 26658    mem0.alarmThreshold = n;
 26659    nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 26660    mem0.nearlyFull = (n>0 && n<=nUsed);
 26661    sqlite3_mutex_leave(mem0.mutex);
 26662    excess = sqlite3_memory_used() - n;
 26663    if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
 26664    return priorLimit;
 26665  }
 26666  SQLITE_API void sqlite3_soft_heap_limit(int n){
 26667    if( n<0 ) n = 0;
 26668    sqlite3_soft_heap_limit64(n);
 26669  }
 26670  
 26671  /*
 26672  ** Initialize the memory allocation subsystem.
 26673  */
 26674  SQLITE_PRIVATE int sqlite3MallocInit(void){
 26675    int rc;
 26676    if( sqlite3GlobalConfig.m.xMalloc==0 ){
 26677      sqlite3MemSetDefault();
 26678    }
 26679    memset(&mem0, 0, sizeof(mem0));
 26680    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
 26681    if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
 26682        || sqlite3GlobalConfig.nPage<=0 ){
 26683      sqlite3GlobalConfig.pPage = 0;
 26684      sqlite3GlobalConfig.szPage = 0;
 26685    }
 26686    rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
 26687    if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
 26688    return rc;
 26689  }
 26690  
 26691  /*
 26692  ** Return true if the heap is currently under memory pressure - in other
 26693  ** words if the amount of heap used is close to the limit set by
 26694  ** sqlite3_soft_heap_limit().
 26695  */
 26696  SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
 26697    return mem0.nearlyFull;
 26698  }
 26699  
 26700  /*
 26701  ** Deinitialize the memory allocation subsystem.
 26702  */
 26703  SQLITE_PRIVATE void sqlite3MallocEnd(void){
 26704    if( sqlite3GlobalConfig.m.xShutdown ){
 26705      sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
 26706    }
 26707    memset(&mem0, 0, sizeof(mem0));
 26708  }
 26709  
 26710  /*
 26711  ** Return the amount of memory currently checked out.
 26712  */
 26713  SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
 26714    sqlite3_int64 res, mx;
 26715    sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
 26716    return res;
 26717  }
 26718  
 26719  /*
 26720  ** Return the maximum amount of memory that has ever been
 26721  ** checked out since either the beginning of this process
 26722  ** or since the most recent reset.
 26723  */
 26724  SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
 26725    sqlite3_int64 res, mx;
 26726    sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
 26727    return mx;
 26728  }
 26729  
 26730  /*
 26731  ** Trigger the alarm 
 26732  */
 26733  static void sqlite3MallocAlarm(int nByte){
 26734    if( mem0.alarmThreshold<=0 ) return;
 26735    sqlite3_mutex_leave(mem0.mutex);
 26736    sqlite3_release_memory(nByte);
 26737    sqlite3_mutex_enter(mem0.mutex);
 26738  }
 26739  
 26740  /*
 26741  ** Do a memory allocation with statistics and alarms.  Assume the
 26742  ** lock is already held.
 26743  */
 26744  static void mallocWithAlarm(int n, void **pp){
 26745    void *p;
 26746    int nFull;
 26747    assert( sqlite3_mutex_held(mem0.mutex) );
 26748    assert( n>0 );
 26749  
 26750    /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
 26751    ** implementation of malloc_good_size(), which must be called in debug
 26752    ** mode and specifically when the DMD "Dark Matter Detector" is enabled
 26753    ** or else a crash results.  Hence, do not attempt to optimize out the
 26754    ** following xRoundup() call. */
 26755    nFull = sqlite3GlobalConfig.m.xRoundup(n);
 26756  
 26757  #ifdef SQLITE_MAX_MEMORY
 26758    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
 26759      *pp = 0;
 26760      return;
 26761    }
 26762  #endif
 26763  
 26764    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
 26765    if( mem0.alarmThreshold>0 ){
 26766      sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
 26767      if( nUsed >= mem0.alarmThreshold - nFull ){
 26768        mem0.nearlyFull = 1;
 26769        sqlite3MallocAlarm(nFull);
 26770      }else{
 26771        mem0.nearlyFull = 0;
 26772      }
 26773    }
 26774    p = sqlite3GlobalConfig.m.xMalloc(nFull);
 26775  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 26776    if( p==0 && mem0.alarmThreshold>0 ){
 26777      sqlite3MallocAlarm(nFull);
 26778      p = sqlite3GlobalConfig.m.xMalloc(nFull);
 26779    }
 26780  #endif
 26781    if( p ){
 26782      nFull = sqlite3MallocSize(p);
 26783      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
 26784      sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
 26785    }
 26786    *pp = p;
 26787  }
 26788  
 26789  /*
 26790  ** Allocate memory.  This routine is like sqlite3_malloc() except that it
 26791  ** assumes the memory subsystem has already been initialized.
 26792  */
 26793  SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
 26794    void *p;
 26795    if( n==0 || n>=0x7fffff00 ){
 26796      /* A memory allocation of a number of bytes which is near the maximum
 26797      ** signed integer value might cause an integer overflow inside of the
 26798      ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
 26799      ** 255 bytes of overhead.  SQLite itself will never use anything near
 26800      ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
 26801      p = 0;
 26802    }else if( sqlite3GlobalConfig.bMemstat ){
 26803      sqlite3_mutex_enter(mem0.mutex);
 26804      mallocWithAlarm((int)n, &p);
 26805      sqlite3_mutex_leave(mem0.mutex);
 26806    }else{
 26807      p = sqlite3GlobalConfig.m.xMalloc((int)n);
 26808    }
 26809    assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
 26810    return p;
 26811  }
 26812  
 26813  /*
 26814  ** This version of the memory allocation is for use by the application.
 26815  ** First make sure the memory subsystem is initialized, then do the
 26816  ** allocation.
 26817  */
 26818  SQLITE_API void *sqlite3_malloc(int n){
 26819  #ifndef SQLITE_OMIT_AUTOINIT
 26820    if( sqlite3_initialize() ) return 0;
 26821  #endif
 26822    return n<=0 ? 0 : sqlite3Malloc(n);
 26823  }
 26824  SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
 26825  #ifndef SQLITE_OMIT_AUTOINIT
 26826    if( sqlite3_initialize() ) return 0;
 26827  #endif
 26828    return sqlite3Malloc(n);
 26829  }
 26830  
 26831  /*
 26832  ** TRUE if p is a lookaside memory allocation from db
 26833  */
 26834  #ifndef SQLITE_OMIT_LOOKASIDE
 26835  static int isLookaside(sqlite3 *db, void *p){
 26836    return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
 26837  }
 26838  #else
 26839  #define isLookaside(A,B) 0
 26840  #endif
 26841  
 26842  /*
 26843  ** Return the size of a memory allocation previously obtained from
 26844  ** sqlite3Malloc() or sqlite3_malloc().
 26845  */
 26846  SQLITE_PRIVATE int sqlite3MallocSize(void *p){
 26847    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 26848    return sqlite3GlobalConfig.m.xSize(p);
 26849  }
 26850  SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
 26851    assert( p!=0 );
 26852    if( db==0 || !isLookaside(db,p) ){
 26853  #ifdef SQLITE_DEBUG
 26854      if( db==0 ){
 26855        assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 26856        assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 26857      }else{
 26858        assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 26859        assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 26860      }
 26861  #endif
 26862      return sqlite3GlobalConfig.m.xSize(p);
 26863    }else{
 26864      assert( sqlite3_mutex_held(db->mutex) );
 26865      return db->lookaside.sz;
 26866    }
 26867  }
 26868  SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
 26869    assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 26870    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 26871    return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
 26872  }
 26873  
 26874  /*
 26875  ** Free memory previously obtained from sqlite3Malloc().
 26876  */
 26877  SQLITE_API void sqlite3_free(void *p){
 26878    if( p==0 ) return;  /* IMP: R-49053-54554 */
 26879    assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
 26880    assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
 26881    if( sqlite3GlobalConfig.bMemstat ){
 26882      sqlite3_mutex_enter(mem0.mutex);
 26883      sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
 26884      sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
 26885      sqlite3GlobalConfig.m.xFree(p);
 26886      sqlite3_mutex_leave(mem0.mutex);
 26887    }else{
 26888      sqlite3GlobalConfig.m.xFree(p);
 26889    }
 26890  }
 26891  
 26892  /*
 26893  ** Add the size of memory allocation "p" to the count in
 26894  ** *db->pnBytesFreed.
 26895  */
 26896  static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
 26897    *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
 26898  }
 26899  
 26900  /*
 26901  ** Free memory that might be associated with a particular database
 26902  ** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
 26903  ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
 26904  */
 26905  SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
 26906    assert( db==0 || sqlite3_mutex_held(db->mutex) );
 26907    assert( p!=0 );
 26908    if( db ){
 26909      if( db->pnBytesFreed ){
 26910        measureAllocationSize(db, p);
 26911        return;
 26912      }
 26913      if( isLookaside(db, p) ){
 26914        LookasideSlot *pBuf = (LookasideSlot*)p;
 26915  #ifdef SQLITE_DEBUG
 26916        /* Trash all content in the buffer being freed */
 26917        memset(p, 0xaa, db->lookaside.sz);
 26918  #endif
 26919        pBuf->pNext = db->lookaside.pFree;
 26920        db->lookaside.pFree = pBuf;
 26921        return;
 26922      }
 26923    }
 26924    assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 26925    assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 26926    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
 26927    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 26928    sqlite3_free(p);
 26929  }
 26930  SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
 26931    assert( db==0 || sqlite3_mutex_held(db->mutex) );
 26932    if( p ) sqlite3DbFreeNN(db, p);
 26933  }
 26934  
 26935  /*
 26936  ** Change the size of an existing memory allocation
 26937  */
 26938  SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
 26939    int nOld, nNew, nDiff;
 26940    void *pNew;
 26941    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
 26942    assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
 26943    if( pOld==0 ){
 26944      return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
 26945    }
 26946    if( nBytes==0 ){
 26947      sqlite3_free(pOld); /* IMP: R-26507-47431 */
 26948      return 0;
 26949    }
 26950    if( nBytes>=0x7fffff00 ){
 26951      /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
 26952      return 0;
 26953    }
 26954    nOld = sqlite3MallocSize(pOld);
 26955    /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
 26956    ** argument to xRealloc is always a value returned by a prior call to
 26957    ** xRoundup. */
 26958    nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
 26959    if( nOld==nNew ){
 26960      pNew = pOld;
 26961    }else if( sqlite3GlobalConfig.bMemstat ){
 26962      sqlite3_mutex_enter(mem0.mutex);
 26963      sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
 26964      nDiff = nNew - nOld;
 26965      if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
 26966            mem0.alarmThreshold-nDiff ){
 26967        sqlite3MallocAlarm(nDiff);
 26968      }
 26969      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 26970      if( pNew==0 && mem0.alarmThreshold>0 ){
 26971        sqlite3MallocAlarm((int)nBytes);
 26972        pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 26973      }
 26974      if( pNew ){
 26975        nNew = sqlite3MallocSize(pNew);
 26976        sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
 26977      }
 26978      sqlite3_mutex_leave(mem0.mutex);
 26979    }else{
 26980      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
 26981    }
 26982    assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
 26983    return pNew;
 26984  }
 26985  
 26986  /*
 26987  ** The public interface to sqlite3Realloc.  Make sure that the memory
 26988  ** subsystem is initialized prior to invoking sqliteRealloc.
 26989  */
 26990  SQLITE_API void *sqlite3_realloc(void *pOld, int n){
 26991  #ifndef SQLITE_OMIT_AUTOINIT
 26992    if( sqlite3_initialize() ) return 0;
 26993  #endif
 26994    if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
 26995    return sqlite3Realloc(pOld, n);
 26996  }
 26997  SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
 26998  #ifndef SQLITE_OMIT_AUTOINIT
 26999    if( sqlite3_initialize() ) return 0;
 27000  #endif
 27001    return sqlite3Realloc(pOld, n);
 27002  }
 27003  
 27004  
 27005  /*
 27006  ** Allocate and zero memory.
 27007  */ 
 27008  SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
 27009    void *p = sqlite3Malloc(n);
 27010    if( p ){
 27011      memset(p, 0, (size_t)n);
 27012    }
 27013    return p;
 27014  }
 27015  
 27016  /*
 27017  ** Allocate and zero memory.  If the allocation fails, make
 27018  ** the mallocFailed flag in the connection pointer.
 27019  */
 27020  SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
 27021    void *p;
 27022    testcase( db==0 );
 27023    p = sqlite3DbMallocRaw(db, n);
 27024    if( p ) memset(p, 0, (size_t)n);
 27025    return p;
 27026  }
 27027  
 27028  
 27029  /* Finish the work of sqlite3DbMallocRawNN for the unusual and
 27030  ** slower case when the allocation cannot be fulfilled using lookaside.
 27031  */
 27032  static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
 27033    void *p;
 27034    assert( db!=0 );
 27035    p = sqlite3Malloc(n);
 27036    if( !p ) sqlite3OomFault(db);
 27037    sqlite3MemdebugSetType(p, 
 27038           (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
 27039    return p;
 27040  }
 27041  
 27042  /*
 27043  ** Allocate memory, either lookaside (if possible) or heap.  
 27044  ** If the allocation fails, set the mallocFailed flag in
 27045  ** the connection pointer.
 27046  **
 27047  ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
 27048  ** failure on the same database connection) then always return 0.
 27049  ** Hence for a particular database connection, once malloc starts
 27050  ** failing, it fails consistently until mallocFailed is reset.
 27051  ** This is an important assumption.  There are many places in the
 27052  ** code that do things like this:
 27053  **
 27054  **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
 27055  **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
 27056  **         if( b ) a[10] = 9;
 27057  **
 27058  ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
 27059  ** that all prior mallocs (ex: "a") worked too.
 27060  **
 27061  ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
 27062  ** not a NULL pointer.
 27063  */
 27064  SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
 27065    void *p;
 27066    if( db ) return sqlite3DbMallocRawNN(db, n);
 27067    p = sqlite3Malloc(n);
 27068    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 27069    return p;
 27070  }
 27071  SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
 27072  #ifndef SQLITE_OMIT_LOOKASIDE
 27073    LookasideSlot *pBuf;
 27074    assert( db!=0 );
 27075    assert( sqlite3_mutex_held(db->mutex) );
 27076    assert( db->pnBytesFreed==0 );
 27077    if( db->lookaside.bDisable==0 ){
 27078      assert( db->mallocFailed==0 );
 27079      if( n>db->lookaside.sz ){
 27080        db->lookaside.anStat[1]++;
 27081      }else if( (pBuf = db->lookaside.pFree)!=0 ){
 27082        db->lookaside.pFree = pBuf->pNext;
 27083        db->lookaside.anStat[0]++;
 27084        return (void*)pBuf;
 27085      }else if( (pBuf = db->lookaside.pInit)!=0 ){
 27086        db->lookaside.pInit = pBuf->pNext;
 27087        db->lookaside.anStat[0]++;
 27088        return (void*)pBuf;
 27089      }else{
 27090        db->lookaside.anStat[2]++;
 27091      }
 27092    }else if( db->mallocFailed ){
 27093      return 0;
 27094    }
 27095  #else
 27096    assert( db!=0 );
 27097    assert( sqlite3_mutex_held(db->mutex) );
 27098    assert( db->pnBytesFreed==0 );
 27099    if( db->mallocFailed ){
 27100      return 0;
 27101    }
 27102  #endif
 27103    return dbMallocRawFinish(db, n);
 27104  }
 27105  
 27106  /* Forward declaration */
 27107  static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
 27108  
 27109  /*
 27110  ** Resize the block of memory pointed to by p to n bytes. If the
 27111  ** resize fails, set the mallocFailed flag in the connection object.
 27112  */
 27113  SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
 27114    assert( db!=0 );
 27115    if( p==0 ) return sqlite3DbMallocRawNN(db, n);
 27116    assert( sqlite3_mutex_held(db->mutex) );
 27117    if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
 27118    return dbReallocFinish(db, p, n);
 27119  }
 27120  static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
 27121    void *pNew = 0;
 27122    assert( db!=0 );
 27123    assert( p!=0 );
 27124    if( db->mallocFailed==0 ){
 27125      if( isLookaside(db, p) ){
 27126        pNew = sqlite3DbMallocRawNN(db, n);
 27127        if( pNew ){
 27128          memcpy(pNew, p, db->lookaside.sz);
 27129          sqlite3DbFree(db, p);
 27130        }
 27131      }else{
 27132        assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 27133        assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
 27134        sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 27135        pNew = sqlite3_realloc64(p, n);
 27136        if( !pNew ){
 27137          sqlite3OomFault(db);
 27138        }
 27139        sqlite3MemdebugSetType(pNew,
 27140              (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
 27141      }
 27142    }
 27143    return pNew;
 27144  }
 27145  
 27146  /*
 27147  ** Attempt to reallocate p.  If the reallocation fails, then free p
 27148  ** and set the mallocFailed flag in the database connection.
 27149  */
 27150  SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
 27151    void *pNew;
 27152    pNew = sqlite3DbRealloc(db, p, n);
 27153    if( !pNew ){
 27154      sqlite3DbFree(db, p);
 27155    }
 27156    return pNew;
 27157  }
 27158  
 27159  /*
 27160  ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
 27161  ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
 27162  ** is because when memory debugging is turned on, these two functions are 
 27163  ** called via macros that record the current file and line number in the
 27164  ** ThreadData structure.
 27165  */
 27166  SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
 27167    char *zNew;
 27168    size_t n;
 27169    if( z==0 ){
 27170      return 0;
 27171    }
 27172    n = strlen(z) + 1;
 27173    zNew = sqlite3DbMallocRaw(db, n);
 27174    if( zNew ){
 27175      memcpy(zNew, z, n);
 27176    }
 27177    return zNew;
 27178  }
 27179  SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
 27180    char *zNew;
 27181    assert( db!=0 );
 27182    if( z==0 ){
 27183      return 0;
 27184    }
 27185    assert( (n&0x7fffffff)==n );
 27186    zNew = sqlite3DbMallocRawNN(db, n+1);
 27187    if( zNew ){
 27188      memcpy(zNew, z, (size_t)n);
 27189      zNew[n] = 0;
 27190    }
 27191    return zNew;
 27192  }
 27193  
 27194  /*
 27195  ** The text between zStart and zEnd represents a phrase within a larger
 27196  ** SQL statement.  Make a copy of this phrase in space obtained form
 27197  ** sqlite3DbMalloc().  Omit leading and trailing whitespace.
 27198  */
 27199  SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
 27200    int n;
 27201    while( sqlite3Isspace(zStart[0]) ) zStart++;
 27202    n = (int)(zEnd - zStart);
 27203    while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
 27204    return sqlite3DbStrNDup(db, zStart, n);
 27205  }
 27206  
 27207  /*
 27208  ** Free any prior content in *pz and replace it with a copy of zNew.
 27209  */
 27210  SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
 27211    sqlite3DbFree(db, *pz);
 27212    *pz = sqlite3DbStrDup(db, zNew);
 27213  }
 27214  
 27215  /*
 27216  ** Call this routine to record the fact that an OOM (out-of-memory) error
 27217  ** has happened.  This routine will set db->mallocFailed, and also
 27218  ** temporarily disable the lookaside memory allocator and interrupt
 27219  ** any running VDBEs.
 27220  */
 27221  SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
 27222    if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
 27223      db->mallocFailed = 1;
 27224      if( db->nVdbeExec>0 ){
 27225        db->u1.isInterrupted = 1;
 27226      }
 27227      db->lookaside.bDisable++;
 27228    }
 27229  }
 27230  
 27231  /*
 27232  ** This routine reactivates the memory allocator and clears the
 27233  ** db->mallocFailed flag as necessary.
 27234  **
 27235  ** The memory allocator is not restarted if there are running
 27236  ** VDBEs.
 27237  */
 27238  SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
 27239    if( db->mallocFailed && db->nVdbeExec==0 ){
 27240      db->mallocFailed = 0;
 27241      db->u1.isInterrupted = 0;
 27242      assert( db->lookaside.bDisable>0 );
 27243      db->lookaside.bDisable--;
 27244    }
 27245  }
 27246  
 27247  /*
 27248  ** Take actions at the end of an API call to indicate an OOM error
 27249  */
 27250  static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
 27251    sqlite3OomClear(db);
 27252    sqlite3Error(db, SQLITE_NOMEM);
 27253    return SQLITE_NOMEM_BKPT;
 27254  }
 27255  
 27256  /*
 27257  ** This function must be called before exiting any API function (i.e. 
 27258  ** returning control to the user) that has called sqlite3_malloc or
 27259  ** sqlite3_realloc.
 27260  **
 27261  ** The returned value is normally a copy of the second argument to this
 27262  ** function. However, if a malloc() failure has occurred since the previous
 27263  ** invocation SQLITE_NOMEM is returned instead. 
 27264  **
 27265  ** If an OOM as occurred, then the connection error-code (the value
 27266  ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
 27267  */
 27268  SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
 27269    /* If the db handle must hold the connection handle mutex here.
 27270    ** Otherwise the read (and possible write) of db->mallocFailed 
 27271    ** is unsafe, as is the call to sqlite3Error().
 27272    */
 27273    assert( db!=0 );
 27274    assert( sqlite3_mutex_held(db->mutex) );
 27275    if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
 27276      return apiOomError(db);
 27277    }
 27278    return rc & db->errMask;
 27279  }
 27280  
 27281  /************** End of malloc.c **********************************************/
 27282  /************** Begin file printf.c ******************************************/
 27283  /*
 27284  ** The "printf" code that follows dates from the 1980's.  It is in
 27285  ** the public domain. 
 27286  **
 27287  **************************************************************************
 27288  **
 27289  ** This file contains code for a set of "printf"-like routines.  These
 27290  ** routines format strings much like the printf() from the standard C
 27291  ** library, though the implementation here has enhancements to support
 27292  ** SQLite.
 27293  */
 27294  /* #include "sqliteInt.h" */
 27295  
 27296  /*
 27297  ** Conversion types fall into various categories as defined by the
 27298  ** following enumeration.
 27299  */
 27300  #define etRADIX       0 /* non-decimal integer types.  %x %o */
 27301  #define etFLOAT       1 /* Floating point.  %f */
 27302  #define etEXP         2 /* Exponentional notation. %e and %E */
 27303  #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
 27304  #define etSIZE        4 /* Return number of characters processed so far. %n */
 27305  #define etSTRING      5 /* Strings. %s */
 27306  #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
 27307  #define etPERCENT     7 /* Percent symbol. %% */
 27308  #define etCHARX       8 /* Characters. %c */
 27309  /* The rest are extensions, not normally found in printf() */
 27310  #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
 27311  #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
 27312                            NULL pointers replaced by SQL NULL.  %Q */
 27313  #define etTOKEN      11 /* a pointer to a Token structure */
 27314  #define etSRCLIST    12 /* a pointer to a SrcList */
 27315  #define etPOINTER    13 /* The %p conversion */
 27316  #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
 27317  #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
 27318  #define etDECIMAL    16 /* %d or %u, but not %x, %o */
 27319  
 27320  #define etINVALID    17 /* Any unrecognized conversion type */
 27321  
 27322  
 27323  /*
 27324  ** An "etByte" is an 8-bit unsigned value.
 27325  */
 27326  typedef unsigned char etByte;
 27327  
 27328  /*
 27329  ** Each builtin conversion character (ex: the 'd' in "%d") is described
 27330  ** by an instance of the following structure
 27331  */
 27332  typedef struct et_info {   /* Information about each format field */
 27333    char fmttype;            /* The format field code letter */
 27334    etByte base;             /* The base for radix conversion */
 27335    etByte flags;            /* One or more of FLAG_ constants below */
 27336    etByte type;             /* Conversion paradigm */
 27337    etByte charset;          /* Offset into aDigits[] of the digits string */
 27338    etByte prefix;           /* Offset into aPrefix[] of the prefix string */
 27339  } et_info;
 27340  
 27341  /*
 27342  ** Allowed values for et_info.flags
 27343  */
 27344  #define FLAG_SIGNED    1     /* True if the value to convert is signed */
 27345  #define FLAG_STRING    4     /* Allow infinite precision */
 27346  
 27347  
 27348  /*
 27349  ** The following table is searched linearly, so it is good to put the
 27350  ** most frequently used conversion types first.
 27351  */
 27352  static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
 27353  static const char aPrefix[] = "-x0\000X0";
 27354  static const et_info fmtinfo[] = {
 27355    {  'd', 10, 1, etDECIMAL,    0,  0 },
 27356    {  's',  0, 4, etSTRING,     0,  0 },
 27357    {  'g',  0, 1, etGENERIC,    30, 0 },
 27358    {  'z',  0, 4, etDYNSTRING,  0,  0 },
 27359    {  'q',  0, 4, etSQLESCAPE,  0,  0 },
 27360    {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
 27361    {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
 27362    {  'c',  0, 0, etCHARX,      0,  0 },
 27363    {  'o',  8, 0, etRADIX,      0,  2 },
 27364    {  'u', 10, 0, etDECIMAL,    0,  0 },
 27365    {  'x', 16, 0, etRADIX,      16, 1 },
 27366    {  'X', 16, 0, etRADIX,      0,  4 },
 27367  #ifndef SQLITE_OMIT_FLOATING_POINT
 27368    {  'f',  0, 1, etFLOAT,      0,  0 },
 27369    {  'e',  0, 1, etEXP,        30, 0 },
 27370    {  'E',  0, 1, etEXP,        14, 0 },
 27371    {  'G',  0, 1, etGENERIC,    14, 0 },
 27372  #endif
 27373    {  'i', 10, 1, etDECIMAL,    0,  0 },
 27374    {  'n',  0, 0, etSIZE,       0,  0 },
 27375    {  '%',  0, 0, etPERCENT,    0,  0 },
 27376    {  'p', 16, 0, etPOINTER,    0,  1 },
 27377  
 27378    /* All the rest are undocumented and are for internal use only */
 27379    {  'T',  0, 0, etTOKEN,      0,  0 },
 27380    {  'S',  0, 0, etSRCLIST,    0,  0 },
 27381    {  'r', 10, 1, etORDINAL,    0,  0 },
 27382  };
 27383  
 27384  /*
 27385  ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
 27386  ** conversions will work.
 27387  */
 27388  #ifndef SQLITE_OMIT_FLOATING_POINT
 27389  /*
 27390  ** "*val" is a double such that 0.1 <= *val < 10.0
 27391  ** Return the ascii code for the leading digit of *val, then
 27392  ** multiply "*val" by 10.0 to renormalize.
 27393  **
 27394  ** Example:
 27395  **     input:     *val = 3.14159
 27396  **     output:    *val = 1.4159    function return = '3'
 27397  **
 27398  ** The counter *cnt is incremented each time.  After counter exceeds
 27399  ** 16 (the number of significant digits in a 64-bit float) '0' is
 27400  ** always returned.
 27401  */
 27402  static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
 27403    int digit;
 27404    LONGDOUBLE_TYPE d;
 27405    if( (*cnt)<=0 ) return '0';
 27406    (*cnt)--;
 27407    digit = (int)*val;
 27408    d = digit;
 27409    digit += '0';
 27410    *val = (*val - d)*10.0;
 27411    return (char)digit;
 27412  }
 27413  #endif /* SQLITE_OMIT_FLOATING_POINT */
 27414  
 27415  /*
 27416  ** Set the StrAccum object to an error mode.
 27417  */
 27418  static void setStrAccumError(StrAccum *p, u8 eError){
 27419    assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
 27420    p->accError = eError;
 27421    p->nAlloc = 0;
 27422  }
 27423  
 27424  /*
 27425  ** Extra argument values from a PrintfArguments object
 27426  */
 27427  static sqlite3_int64 getIntArg(PrintfArguments *p){
 27428    if( p->nArg<=p->nUsed ) return 0;
 27429    return sqlite3_value_int64(p->apArg[p->nUsed++]);
 27430  }
 27431  static double getDoubleArg(PrintfArguments *p){
 27432    if( p->nArg<=p->nUsed ) return 0.0;
 27433    return sqlite3_value_double(p->apArg[p->nUsed++]);
 27434  }
 27435  static char *getTextArg(PrintfArguments *p){
 27436    if( p->nArg<=p->nUsed ) return 0;
 27437    return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
 27438  }
 27439  
 27440  /*
 27441  ** Allocate memory for a temporary buffer needed for printf rendering.
 27442  **
 27443  ** If the requested size of the temp buffer is larger than the size
 27444  ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
 27445  ** Do the size check before the memory allocation to prevent rogue
 27446  ** SQL from requesting large allocations using the precision or width
 27447  ** field of the printf() function.
 27448  */
 27449  static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
 27450    char *z;
 27451    if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
 27452      setStrAccumError(pAccum, SQLITE_TOOBIG);
 27453      return 0;
 27454    }
 27455    z = sqlite3DbMallocRaw(pAccum->db, n);
 27456    if( z==0 ){
 27457      setStrAccumError(pAccum, SQLITE_NOMEM);
 27458    }
 27459    return z;
 27460  }
 27461  
 27462  /*
 27463  ** On machines with a small stack size, you can redefine the
 27464  ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
 27465  */
 27466  #ifndef SQLITE_PRINT_BUF_SIZE
 27467  # define SQLITE_PRINT_BUF_SIZE 70
 27468  #endif
 27469  #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
 27470  
 27471  /*
 27472  ** Render a string given by "fmt" into the StrAccum object.
 27473  */
 27474  SQLITE_API void sqlite3_str_vappendf(
 27475    sqlite3_str *pAccum,       /* Accumulate results here */
 27476    const char *fmt,           /* Format string */
 27477    va_list ap                 /* arguments */
 27478  ){
 27479    int c;                     /* Next character in the format string */
 27480    char *bufpt;               /* Pointer to the conversion buffer */
 27481    int precision;             /* Precision of the current field */
 27482    int length;                /* Length of the field */
 27483    int idx;                   /* A general purpose loop counter */
 27484    int width;                 /* Width of the current field */
 27485    etByte flag_leftjustify;   /* True if "-" flag is present */
 27486    etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
 27487    etByte flag_alternateform; /* True if "#" flag is present */
 27488    etByte flag_altform2;      /* True if "!" flag is present */
 27489    etByte flag_zeropad;       /* True if field width constant starts with zero */
 27490    etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
 27491    etByte done;               /* Loop termination flag */
 27492    etByte cThousand;          /* Thousands separator for %d and %u */
 27493    etByte xtype = etINVALID;  /* Conversion paradigm */
 27494    u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
 27495    char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
 27496    sqlite_uint64 longvalue;   /* Value for integer types */
 27497    LONGDOUBLE_TYPE realvalue; /* Value for real types */
 27498    const et_info *infop;      /* Pointer to the appropriate info structure */
 27499    char *zOut;                /* Rendering buffer */
 27500    int nOut;                  /* Size of the rendering buffer */
 27501    char *zExtra = 0;          /* Malloced memory used by some conversion */
 27502  #ifndef SQLITE_OMIT_FLOATING_POINT
 27503    int  exp, e2;              /* exponent of real numbers */
 27504    int nsd;                   /* Number of significant digits returned */
 27505    double rounder;            /* Used for rounding floating point values */
 27506    etByte flag_dp;            /* True if decimal point should be shown */
 27507    etByte flag_rtz;           /* True if trailing zeros should be removed */
 27508  #endif
 27509    PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
 27510    char buf[etBUFSIZE];       /* Conversion buffer */
 27511  
 27512    /* pAccum never starts out with an empty buffer that was obtained from 
 27513    ** malloc().  This precondition is required by the mprintf("%z...")
 27514    ** optimization. */
 27515    assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
 27516  
 27517    bufpt = 0;
 27518    if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
 27519      pArgList = va_arg(ap, PrintfArguments*);
 27520      bArgList = 1;
 27521    }else{
 27522      bArgList = 0;
 27523    }
 27524    for(; (c=(*fmt))!=0; ++fmt){
 27525      if( c!='%' ){
 27526        bufpt = (char *)fmt;
 27527  #if HAVE_STRCHRNUL
 27528        fmt = strchrnul(fmt, '%');
 27529  #else
 27530        do{ fmt++; }while( *fmt && *fmt != '%' );
 27531  #endif
 27532        sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
 27533        if( *fmt==0 ) break;
 27534      }
 27535      if( (c=(*++fmt))==0 ){
 27536        sqlite3_str_append(pAccum, "%", 1);
 27537        break;
 27538      }
 27539      /* Find out what flags are present */
 27540      flag_leftjustify = flag_prefix = cThousand =
 27541       flag_alternateform = flag_altform2 = flag_zeropad = 0;
 27542      done = 0;
 27543      width = 0;
 27544      flag_long = 0;
 27545      precision = -1;
 27546      do{
 27547        switch( c ){
 27548          case '-':   flag_leftjustify = 1;     break;
 27549          case '+':   flag_prefix = '+';        break;
 27550          case ' ':   flag_prefix = ' ';        break;
 27551          case '#':   flag_alternateform = 1;   break;
 27552          case '!':   flag_altform2 = 1;        break;
 27553          case '0':   flag_zeropad = 1;         break;
 27554          case ',':   cThousand = ',';          break;
 27555          default:    done = 1;                 break;
 27556          case 'l': {
 27557            flag_long = 1;
 27558            c = *++fmt;
 27559            if( c=='l' ){
 27560              c = *++fmt;
 27561              flag_long = 2;
 27562            }
 27563            done = 1;
 27564            break;
 27565          }
 27566          case '1': case '2': case '3': case '4': case '5':
 27567          case '6': case '7': case '8': case '9': {
 27568            unsigned wx = c - '0';
 27569            while( (c = *++fmt)>='0' && c<='9' ){
 27570              wx = wx*10 + c - '0';
 27571            }
 27572            testcase( wx>0x7fffffff );
 27573            width = wx & 0x7fffffff;
 27574  #ifdef SQLITE_PRINTF_PRECISION_LIMIT
 27575            if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
 27576              width = SQLITE_PRINTF_PRECISION_LIMIT;
 27577            }
 27578  #endif
 27579            if( c!='.' && c!='l' ){
 27580              done = 1;
 27581            }else{
 27582              fmt--;
 27583            }
 27584            break;
 27585          }
 27586          case '*': {
 27587            if( bArgList ){
 27588              width = (int)getIntArg(pArgList);
 27589            }else{
 27590              width = va_arg(ap,int);
 27591            }
 27592            if( width<0 ){
 27593              flag_leftjustify = 1;
 27594              width = width >= -2147483647 ? -width : 0;
 27595            }
 27596  #ifdef SQLITE_PRINTF_PRECISION_LIMIT
 27597            if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
 27598              width = SQLITE_PRINTF_PRECISION_LIMIT;
 27599            }
 27600  #endif
 27601            if( (c = fmt[1])!='.' && c!='l' ){
 27602              c = *++fmt;
 27603              done = 1;
 27604            }
 27605            break;
 27606          }
 27607          case '.': {
 27608            c = *++fmt;
 27609            if( c=='*' ){
 27610              if( bArgList ){
 27611                precision = (int)getIntArg(pArgList);
 27612              }else{
 27613                precision = va_arg(ap,int);
 27614              }
 27615              if( precision<0 ){
 27616                precision = precision >= -2147483647 ? -precision : -1;
 27617              }
 27618              c = *++fmt;
 27619            }else{
 27620              unsigned px = 0;
 27621              while( c>='0' && c<='9' ){
 27622                px = px*10 + c - '0';
 27623                c = *++fmt;
 27624              }
 27625              testcase( px>0x7fffffff );
 27626              precision = px & 0x7fffffff;
 27627            }
 27628  #ifdef SQLITE_PRINTF_PRECISION_LIMIT
 27629            if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
 27630              precision = SQLITE_PRINTF_PRECISION_LIMIT;
 27631            }
 27632  #endif
 27633            if( c=='l' ){
 27634              --fmt;
 27635            }else{
 27636              done = 1;
 27637            }
 27638            break;
 27639          }
 27640        }
 27641      }while( !done && (c=(*++fmt))!=0 );
 27642  
 27643      /* Fetch the info entry for the field */
 27644      infop = &fmtinfo[0];
 27645      xtype = etINVALID;
 27646      for(idx=0; idx<ArraySize(fmtinfo); idx++){
 27647        if( c==fmtinfo[idx].fmttype ){
 27648          infop = &fmtinfo[idx];
 27649          xtype = infop->type;
 27650          break;
 27651        }
 27652      }
 27653  
 27654      /*
 27655      ** At this point, variables are initialized as follows:
 27656      **
 27657      **   flag_alternateform          TRUE if a '#' is present.
 27658      **   flag_altform2               TRUE if a '!' is present.
 27659      **   flag_prefix                 '+' or ' ' or zero
 27660      **   flag_leftjustify            TRUE if a '-' is present or if the
 27661      **                               field width was negative.
 27662      **   flag_zeropad                TRUE if the width began with 0.
 27663      **   flag_long                   1 for "l", 2 for "ll"
 27664      **   width                       The specified field width.  This is
 27665      **                               always non-negative.  Zero is the default.
 27666      **   precision                   The specified precision.  The default
 27667      **                               is -1.
 27668      **   xtype                       The class of the conversion.
 27669      **   infop                       Pointer to the appropriate info struct.
 27670      */
 27671      switch( xtype ){
 27672        case etPOINTER:
 27673          flag_long = sizeof(char*)==sizeof(i64) ? 2 :
 27674                       sizeof(char*)==sizeof(long int) ? 1 : 0;
 27675          /* Fall through into the next case */
 27676        case etORDINAL:
 27677        case etRADIX:      
 27678          cThousand = 0;
 27679          /* Fall through into the next case */
 27680        case etDECIMAL:
 27681          if( infop->flags & FLAG_SIGNED ){
 27682            i64 v;
 27683            if( bArgList ){
 27684              v = getIntArg(pArgList);
 27685            }else if( flag_long ){
 27686              if( flag_long==2 ){
 27687                v = va_arg(ap,i64) ;
 27688              }else{
 27689                v = va_arg(ap,long int);
 27690              }
 27691            }else{
 27692              v = va_arg(ap,int);
 27693            }
 27694            if( v<0 ){
 27695              if( v==SMALLEST_INT64 ){
 27696                longvalue = ((u64)1)<<63;
 27697              }else{
 27698                longvalue = -v;
 27699              }
 27700              prefix = '-';
 27701            }else{
 27702              longvalue = v;
 27703              prefix = flag_prefix;
 27704            }
 27705          }else{
 27706            if( bArgList ){
 27707              longvalue = (u64)getIntArg(pArgList);
 27708            }else if( flag_long ){
 27709              if( flag_long==2 ){
 27710                longvalue = va_arg(ap,u64);
 27711              }else{
 27712                longvalue = va_arg(ap,unsigned long int);
 27713              }
 27714            }else{
 27715              longvalue = va_arg(ap,unsigned int);
 27716            }
 27717            prefix = 0;
 27718          }
 27719          if( longvalue==0 ) flag_alternateform = 0;
 27720          if( flag_zeropad && precision<width-(prefix!=0) ){
 27721            precision = width-(prefix!=0);
 27722          }
 27723          if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
 27724            nOut = etBUFSIZE;
 27725            zOut = buf;
 27726          }else{
 27727            u64 n;
 27728            n = (u64)precision + 10;
 27729            if( cThousand ) n += precision/3;
 27730            zOut = zExtra = printfTempBuf(pAccum, n);
 27731            if( zOut==0 ) return;
 27732            nOut = (int)n;
 27733          }
 27734          bufpt = &zOut[nOut-1];
 27735          if( xtype==etORDINAL ){
 27736            static const char zOrd[] = "thstndrd";
 27737            int x = (int)(longvalue % 10);
 27738            if( x>=4 || (longvalue/10)%10==1 ){
 27739              x = 0;
 27740            }
 27741            *(--bufpt) = zOrd[x*2+1];
 27742            *(--bufpt) = zOrd[x*2];
 27743          }
 27744          {
 27745            const char *cset = &aDigits[infop->charset];
 27746            u8 base = infop->base;
 27747            do{                                           /* Convert to ascii */
 27748              *(--bufpt) = cset[longvalue%base];
 27749              longvalue = longvalue/base;
 27750            }while( longvalue>0 );
 27751          }
 27752          length = (int)(&zOut[nOut-1]-bufpt);
 27753          while( precision>length ){
 27754            *(--bufpt) = '0';                             /* Zero pad */
 27755            length++;
 27756          }
 27757          if( cThousand ){
 27758            int nn = (length - 1)/3;  /* Number of "," to insert */
 27759            int ix = (length - 1)%3 + 1;
 27760            bufpt -= nn;
 27761            for(idx=0; nn>0; idx++){
 27762              bufpt[idx] = bufpt[idx+nn];
 27763              ix--;
 27764              if( ix==0 ){
 27765                bufpt[++idx] = cThousand;
 27766                nn--;
 27767                ix = 3;
 27768              }
 27769            }
 27770          }
 27771          if( prefix ) *(--bufpt) = prefix;               /* Add sign */
 27772          if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
 27773            const char *pre;
 27774            char x;
 27775            pre = &aPrefix[infop->prefix];
 27776            for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
 27777          }
 27778          length = (int)(&zOut[nOut-1]-bufpt);
 27779          break;
 27780        case etFLOAT:
 27781        case etEXP:
 27782        case etGENERIC:
 27783          if( bArgList ){
 27784            realvalue = getDoubleArg(pArgList);
 27785          }else{
 27786            realvalue = va_arg(ap,double);
 27787          }
 27788  #ifdef SQLITE_OMIT_FLOATING_POINT
 27789          length = 0;
 27790  #else
 27791          if( precision<0 ) precision = 6;         /* Set default precision */
 27792          if( realvalue<0.0 ){
 27793            realvalue = -realvalue;
 27794            prefix = '-';
 27795          }else{
 27796            prefix = flag_prefix;
 27797          }
 27798          if( xtype==etGENERIC && precision>0 ) precision--;
 27799          testcase( precision>0xfff );
 27800          for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
 27801          if( xtype==etFLOAT ) realvalue += rounder;
 27802          /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
 27803          exp = 0;
 27804          if( sqlite3IsNaN((double)realvalue) ){
 27805            bufpt = "NaN";
 27806            length = 3;
 27807            break;
 27808          }
 27809          if( realvalue>0.0 ){
 27810            LONGDOUBLE_TYPE scale = 1.0;
 27811            while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
 27812            while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
 27813            while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
 27814            realvalue /= scale;
 27815            while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
 27816            while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
 27817            if( exp>350 ){
 27818              bufpt = buf;
 27819              buf[0] = prefix;
 27820              memcpy(buf+(prefix!=0),"Inf",4);
 27821              length = 3+(prefix!=0);
 27822              break;
 27823            }
 27824          }
 27825          bufpt = buf;
 27826          /*
 27827          ** If the field type is etGENERIC, then convert to either etEXP
 27828          ** or etFLOAT, as appropriate.
 27829          */
 27830          if( xtype!=etFLOAT ){
 27831            realvalue += rounder;
 27832            if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
 27833          }
 27834          if( xtype==etGENERIC ){
 27835            flag_rtz = !flag_alternateform;
 27836            if( exp<-4 || exp>precision ){
 27837              xtype = etEXP;
 27838            }else{
 27839              precision = precision - exp;
 27840              xtype = etFLOAT;
 27841            }
 27842          }else{
 27843            flag_rtz = flag_altform2;
 27844          }
 27845          if( xtype==etEXP ){
 27846            e2 = 0;
 27847          }else{
 27848            e2 = exp;
 27849          }
 27850          {
 27851            i64 szBufNeeded;           /* Size of a temporary buffer needed */
 27852            szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
 27853            if( szBufNeeded > etBUFSIZE ){
 27854              bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
 27855              if( bufpt==0 ) return;
 27856            }
 27857          }
 27858          zOut = bufpt;
 27859          nsd = 16 + flag_altform2*10;
 27860          flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
 27861          /* The sign in front of the number */
 27862          if( prefix ){
 27863            *(bufpt++) = prefix;
 27864          }
 27865          /* Digits prior to the decimal point */
 27866          if( e2<0 ){
 27867            *(bufpt++) = '0';
 27868          }else{
 27869            for(; e2>=0; e2--){
 27870              *(bufpt++) = et_getdigit(&realvalue,&nsd);
 27871            }
 27872          }
 27873          /* The decimal point */
 27874          if( flag_dp ){
 27875            *(bufpt++) = '.';
 27876          }
 27877          /* "0" digits after the decimal point but before the first
 27878          ** significant digit of the number */
 27879          for(e2++; e2<0; precision--, e2++){
 27880            assert( precision>0 );
 27881            *(bufpt++) = '0';
 27882          }
 27883          /* Significant digits after the decimal point */
 27884          while( (precision--)>0 ){
 27885            *(bufpt++) = et_getdigit(&realvalue,&nsd);
 27886          }
 27887          /* Remove trailing zeros and the "." if no digits follow the "." */
 27888          if( flag_rtz && flag_dp ){
 27889            while( bufpt[-1]=='0' ) *(--bufpt) = 0;
 27890            assert( bufpt>zOut );
 27891            if( bufpt[-1]=='.' ){
 27892              if( flag_altform2 ){
 27893                *(bufpt++) = '0';
 27894              }else{
 27895                *(--bufpt) = 0;
 27896              }
 27897            }
 27898          }
 27899          /* Add the "eNNN" suffix */
 27900          if( xtype==etEXP ){
 27901            *(bufpt++) = aDigits[infop->charset];
 27902            if( exp<0 ){
 27903              *(bufpt++) = '-'; exp = -exp;
 27904            }else{
 27905              *(bufpt++) = '+';
 27906            }
 27907            if( exp>=100 ){
 27908              *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
 27909              exp %= 100;
 27910            }
 27911            *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
 27912            *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
 27913          }
 27914          *bufpt = 0;
 27915  
 27916          /* The converted number is in buf[] and zero terminated. Output it.
 27917          ** Note that the number is in the usual order, not reversed as with
 27918          ** integer conversions. */
 27919          length = (int)(bufpt-zOut);
 27920          bufpt = zOut;
 27921  
 27922          /* Special case:  Add leading zeros if the flag_zeropad flag is
 27923          ** set and we are not left justified */
 27924          if( flag_zeropad && !flag_leftjustify && length < width){
 27925            int i;
 27926            int nPad = width - length;
 27927            for(i=width; i>=nPad; i--){
 27928              bufpt[i] = bufpt[i-nPad];
 27929            }
 27930            i = prefix!=0;
 27931            while( nPad-- ) bufpt[i++] = '0';
 27932            length = width;
 27933          }
 27934  #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
 27935          break;
 27936        case etSIZE:
 27937          if( !bArgList ){
 27938            *(va_arg(ap,int*)) = pAccum->nChar;
 27939          }
 27940          length = width = 0;
 27941          break;
 27942        case etPERCENT:
 27943          buf[0] = '%';
 27944          bufpt = buf;
 27945          length = 1;
 27946          break;
 27947        case etCHARX:
 27948          if( bArgList ){
 27949            bufpt = getTextArg(pArgList);
 27950            length = 1;
 27951            if( bufpt ){
 27952              buf[0] = c = *(bufpt++);
 27953              if( (c&0xc0)==0xc0 ){
 27954                while( length<4 && (bufpt[0]&0xc0)==0x80 ){
 27955                  buf[length++] = *(bufpt++);
 27956                }
 27957              }
 27958            }else{
 27959              buf[0] = 0;
 27960            }
 27961          }else{
 27962            unsigned int ch = va_arg(ap,unsigned int);
 27963            if( ch<0x00080 ){
 27964              buf[0] = ch & 0xff;
 27965              length = 1;
 27966            }else if( ch<0x00800 ){
 27967              buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
 27968              buf[1] = 0x80 + (u8)(ch & 0x3f);
 27969              length = 2;
 27970            }else if( ch<0x10000 ){
 27971              buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
 27972              buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
 27973              buf[2] = 0x80 + (u8)(ch & 0x3f);
 27974              length = 3;
 27975            }else{
 27976              buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
 27977              buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
 27978              buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
 27979              buf[3] = 0x80 + (u8)(ch & 0x3f);
 27980              length = 4;
 27981            }
 27982          }
 27983          if( precision>1 ){
 27984            width -= precision-1;
 27985            if( width>1 && !flag_leftjustify ){
 27986              sqlite3_str_appendchar(pAccum, width-1, ' ');
 27987              width = 0;
 27988            }
 27989            while( precision-- > 1 ){
 27990              sqlite3_str_append(pAccum, buf, length);
 27991            }
 27992          }
 27993          bufpt = buf;
 27994          flag_altform2 = 1;
 27995          goto adjust_width_for_utf8;
 27996        case etSTRING:
 27997        case etDYNSTRING:
 27998          if( bArgList ){
 27999            bufpt = getTextArg(pArgList);
 28000            xtype = etSTRING;
 28001          }else{
 28002            bufpt = va_arg(ap,char*);
 28003          }
 28004          if( bufpt==0 ){
 28005            bufpt = "";
 28006          }else if( xtype==etDYNSTRING ){
 28007            if( pAccum->nChar==0
 28008             && pAccum->mxAlloc
 28009             && width==0
 28010             && precision<0
 28011             && pAccum->accError==0
 28012            ){
 28013              /* Special optimization for sqlite3_mprintf("%z..."):
 28014              ** Extend an existing memory allocation rather than creating
 28015              ** a new one. */
 28016              assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
 28017              pAccum->zText = bufpt;
 28018              pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
 28019              pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
 28020              pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
 28021              length = 0;
 28022              break;
 28023            }
 28024            zExtra = bufpt;
 28025          }
 28026          if( precision>=0 ){
 28027            if( flag_altform2 ){
 28028              /* Set length to the number of bytes needed in order to display
 28029              ** precision characters */
 28030              unsigned char *z = (unsigned char*)bufpt;
 28031              while( precision-- > 0 && z[0] ){
 28032                SQLITE_SKIP_UTF8(z);
 28033              }
 28034              length = (int)(z - (unsigned char*)bufpt);
 28035            }else{
 28036              for(length=0; length<precision && bufpt[length]; length++){}
 28037            }
 28038          }else{
 28039            length = 0x7fffffff & (int)strlen(bufpt);
 28040          }
 28041        adjust_width_for_utf8:
 28042          if( flag_altform2 && width>0 ){
 28043            /* Adjust width to account for extra bytes in UTF-8 characters */
 28044            int ii = length - 1;
 28045            while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
 28046          }
 28047          break;
 28048        case etSQLESCAPE:           /* %q: Escape ' characters */
 28049        case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
 28050        case etSQLESCAPE3: {        /* %w: Escape " characters */
 28051          int i, j, k, n, isnull;
 28052          int needQuote;
 28053          char ch;
 28054          char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
 28055          char *escarg;
 28056  
 28057          if( bArgList ){
 28058            escarg = getTextArg(pArgList);
 28059          }else{
 28060            escarg = va_arg(ap,char*);
 28061          }
 28062          isnull = escarg==0;
 28063          if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
 28064          /* For %q, %Q, and %w, the precision is the number of byte (or
 28065          ** characters if the ! flags is present) to use from the input.
 28066          ** Because of the extra quoting characters inserted, the number
 28067          ** of output characters may be larger than the precision.
 28068          */
 28069          k = precision;
 28070          for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
 28071            if( ch==q )  n++;
 28072            if( flag_altform2 && (ch&0xc0)==0xc0 ){
 28073              while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
 28074            }
 28075          }
 28076          needQuote = !isnull && xtype==etSQLESCAPE2;
 28077          n += i + 3;
 28078          if( n>etBUFSIZE ){
 28079            bufpt = zExtra = printfTempBuf(pAccum, n);
 28080            if( bufpt==0 ) return;
 28081          }else{
 28082            bufpt = buf;
 28083          }
 28084          j = 0;
 28085          if( needQuote ) bufpt[j++] = q;
 28086          k = i;
 28087          for(i=0; i<k; i++){
 28088            bufpt[j++] = ch = escarg[i];
 28089            if( ch==q ) bufpt[j++] = ch;
 28090          }
 28091          if( needQuote ) bufpt[j++] = q;
 28092          bufpt[j] = 0;
 28093          length = j;
 28094          goto adjust_width_for_utf8;
 28095        }
 28096        case etTOKEN: {
 28097          Token *pToken;
 28098          if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 28099          pToken = va_arg(ap, Token*);
 28100          assert( bArgList==0 );
 28101          if( pToken && pToken->n ){
 28102            sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
 28103          }
 28104          length = width = 0;
 28105          break;
 28106        }
 28107        case etSRCLIST: {
 28108          SrcList *pSrc;
 28109          int k;
 28110          struct SrcList_item *pItem;
 28111          if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
 28112          pSrc = va_arg(ap, SrcList*);
 28113          k = va_arg(ap, int);
 28114          pItem = &pSrc->a[k];
 28115          assert( bArgList==0 );
 28116          assert( k>=0 && k<pSrc->nSrc );
 28117          if( pItem->zDatabase ){
 28118            sqlite3_str_appendall(pAccum, pItem->zDatabase);
 28119            sqlite3_str_append(pAccum, ".", 1);
 28120          }
 28121          sqlite3_str_appendall(pAccum, pItem->zName);
 28122          length = width = 0;
 28123          break;
 28124        }
 28125        default: {
 28126          assert( xtype==etINVALID );
 28127          return;
 28128        }
 28129      }/* End switch over the format type */
 28130      /*
 28131      ** The text of the conversion is pointed to by "bufpt" and is
 28132      ** "length" characters long.  The field width is "width".  Do
 28133      ** the output.  Both length and width are in bytes, not characters,
 28134      ** at this point.  If the "!" flag was present on string conversions
 28135      ** indicating that width and precision should be expressed in characters,
 28136      ** then the values have been translated prior to reaching this point.
 28137      */
 28138      width -= length;
 28139      if( width>0 ){
 28140        if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
 28141        sqlite3_str_append(pAccum, bufpt, length);
 28142        if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
 28143      }else{
 28144        sqlite3_str_append(pAccum, bufpt, length);
 28145      }
 28146  
 28147      if( zExtra ){
 28148        sqlite3DbFree(pAccum->db, zExtra);
 28149        zExtra = 0;
 28150      }
 28151    }/* End for loop over the format string */
 28152  } /* End of function */
 28153  
 28154  /*
 28155  ** Enlarge the memory allocation on a StrAccum object so that it is
 28156  ** able to accept at least N more bytes of text.
 28157  **
 28158  ** Return the number of bytes of text that StrAccum is able to accept
 28159  ** after the attempted enlargement.  The value returned might be zero.
 28160  */
 28161  static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
 28162    char *zNew;
 28163    assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
 28164    if( p->accError ){
 28165      testcase(p->accError==SQLITE_TOOBIG);
 28166      testcase(p->accError==SQLITE_NOMEM);
 28167      return 0;
 28168    }
 28169    if( p->mxAlloc==0 ){
 28170      N = p->nAlloc - p->nChar - 1;
 28171      setStrAccumError(p, SQLITE_TOOBIG);
 28172      return N;
 28173    }else{
 28174      char *zOld = isMalloced(p) ? p->zText : 0;
 28175      i64 szNew = p->nChar;
 28176      szNew += N + 1;
 28177      if( szNew+p->nChar<=p->mxAlloc ){
 28178        /* Force exponential buffer size growth as long as it does not overflow,
 28179        ** to avoid having to call this routine too often */
 28180        szNew += p->nChar;
 28181      }
 28182      if( szNew > p->mxAlloc ){
 28183        sqlite3_str_reset(p);
 28184        setStrAccumError(p, SQLITE_TOOBIG);
 28185        return 0;
 28186      }else{
 28187        p->nAlloc = (int)szNew;
 28188      }
 28189      if( p->db ){
 28190        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
 28191      }else{
 28192        zNew = sqlite3_realloc64(zOld, p->nAlloc);
 28193      }
 28194      if( zNew ){
 28195        assert( p->zText!=0 || p->nChar==0 );
 28196        if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
 28197        p->zText = zNew;
 28198        p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
 28199        p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 28200      }else{
 28201        sqlite3_str_reset(p);
 28202        setStrAccumError(p, SQLITE_NOMEM);
 28203        return 0;
 28204      }
 28205    }
 28206    return N;
 28207  }
 28208  
 28209  /*
 28210  ** Append N copies of character c to the given string buffer.
 28211  */
 28212  SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
 28213    testcase( p->nChar + (i64)N > 0x7fffffff );
 28214    if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
 28215      return;
 28216    }
 28217    while( (N--)>0 ) p->zText[p->nChar++] = c;
 28218  }
 28219  
 28220  /*
 28221  ** The StrAccum "p" is not large enough to accept N new bytes of z[].
 28222  ** So enlarge if first, then do the append.
 28223  **
 28224  ** This is a helper routine to sqlite3_str_append() that does special-case
 28225  ** work (enlarging the buffer) using tail recursion, so that the
 28226  ** sqlite3_str_append() routine can use fast calling semantics.
 28227  */
 28228  static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
 28229    N = sqlite3StrAccumEnlarge(p, N);
 28230    if( N>0 ){
 28231      memcpy(&p->zText[p->nChar], z, N);
 28232      p->nChar += N;
 28233    }
 28234  }
 28235  
 28236  /*
 28237  ** Append N bytes of text from z to the StrAccum object.  Increase the
 28238  ** size of the memory allocation for StrAccum if necessary.
 28239  */
 28240  SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
 28241    assert( z!=0 || N==0 );
 28242    assert( p->zText!=0 || p->nChar==0 || p->accError );
 28243    assert( N>=0 );
 28244    assert( p->accError==0 || p->nAlloc==0 );
 28245    if( p->nChar+N >= p->nAlloc ){
 28246      enlargeAndAppend(p,z,N);
 28247    }else if( N ){
 28248      assert( p->zText );
 28249      p->nChar += N;
 28250      memcpy(&p->zText[p->nChar-N], z, N);
 28251    }
 28252  }
 28253  
 28254  /*
 28255  ** Append the complete text of zero-terminated string z[] to the p string.
 28256  */
 28257  SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
 28258    sqlite3_str_append(p, z, sqlite3Strlen30(z));
 28259  }
 28260  
 28261  
 28262  /*
 28263  ** Finish off a string by making sure it is zero-terminated.
 28264  ** Return a pointer to the resulting string.  Return a NULL
 28265  ** pointer if any kind of error was encountered.
 28266  */
 28267  static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
 28268    char *zText;
 28269    assert( p->mxAlloc>0 && !isMalloced(p) );
 28270    zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
 28271    if( zText ){
 28272      memcpy(zText, p->zText, p->nChar+1);
 28273      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
 28274    }else{
 28275      setStrAccumError(p, SQLITE_NOMEM);
 28276    }
 28277    p->zText = zText;
 28278    return zText;
 28279  }
 28280  SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
 28281    if( p->zText ){
 28282      p->zText[p->nChar] = 0;
 28283      if( p->mxAlloc>0 && !isMalloced(p) ){
 28284        return strAccumFinishRealloc(p);
 28285      }
 28286    }
 28287    return p->zText;
 28288  }
 28289  
 28290  /*
 28291  ** This singleton is an sqlite3_str object that is returned if
 28292  ** sqlite3_malloc() fails to provide space for a real one.  This
 28293  ** sqlite3_str object accepts no new text and always returns
 28294  ** an SQLITE_NOMEM error.
 28295  */
 28296  static sqlite3_str sqlite3OomStr = {
 28297     0, 0, 0, 0, 0, SQLITE_NOMEM, 0
 28298  };
 28299  
 28300  /* Finalize a string created using sqlite3_str_new().
 28301  */
 28302  SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
 28303    char *z;
 28304    if( p!=0 && p!=&sqlite3OomStr ){
 28305      z = sqlite3StrAccumFinish(p);
 28306      sqlite3_free(p);
 28307    }else{
 28308      z = 0;
 28309    }
 28310    return z;
 28311  }
 28312  
 28313  /* Return any error code associated with p */
 28314  SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
 28315    return p ? p->accError : SQLITE_NOMEM;
 28316  }
 28317  
 28318  /* Return the current length of p in bytes */
 28319  SQLITE_API int sqlite3_str_length(sqlite3_str *p){
 28320    return p ? p->nChar : 0;
 28321  }
 28322  
 28323  /* Return the current value for p */
 28324  SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
 28325    if( p==0 || p->nChar==0 ) return 0;
 28326    p->zText[p->nChar] = 0;
 28327    return p->zText;
 28328  }
 28329  
 28330  /*
 28331  ** Reset an StrAccum string.  Reclaim all malloced memory.
 28332  */
 28333  SQLITE_API void sqlite3_str_reset(StrAccum *p){
 28334    if( isMalloced(p) ){
 28335      sqlite3DbFree(p->db, p->zText);
 28336      p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
 28337    }
 28338    p->nAlloc = 0;
 28339    p->nChar = 0;
 28340    p->zText = 0;
 28341  }
 28342  
 28343  /* Destroy a string created using sqlite3_str_new().
 28344  */
 28345  SQLITE_API void sqlite3_str_destroy(sqlite3_str *p){
 28346    sqlite3_str_reset(p);
 28347    sqlite3_str_finish(p);
 28348  }
 28349  
 28350  /*
 28351  ** Initialize a string accumulator.
 28352  **
 28353  ** p:     The accumulator to be initialized.
 28354  ** db:    Pointer to a database connection.  May be NULL.  Lookaside
 28355  **        memory is used if not NULL. db->mallocFailed is set appropriately
 28356  **        when not NULL.
 28357  ** zBase: An initial buffer.  May be NULL in which case the initial buffer
 28358  **        is malloced.
 28359  ** n:     Size of zBase in bytes.  If total space requirements never exceed
 28360  **        n then no memory allocations ever occur.
 28361  ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
 28362  **        allocations will ever occur.
 28363  */
 28364  SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
 28365    p->zText = zBase;
 28366    p->db = db;
 28367    p->nAlloc = n;
 28368    p->mxAlloc = mx;
 28369    p->nChar = 0;
 28370    p->accError = 0;
 28371    p->printfFlags = 0;
 28372  }
 28373  
 28374  /* Allocate and initialize a new dynamic string object */
 28375  SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
 28376    sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
 28377    if( p ){
 28378      sqlite3StrAccumInit(p, 0, 0, 0,
 28379              db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
 28380    }else{
 28381      p = &sqlite3OomStr;
 28382    }
 28383    return p;
 28384  }
 28385  
 28386  /*
 28387  ** Print into memory obtained from sqliteMalloc().  Use the internal
 28388  ** %-conversion extensions.
 28389  */
 28390  SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
 28391    char *z;
 28392    char zBase[SQLITE_PRINT_BUF_SIZE];
 28393    StrAccum acc;
 28394    assert( db!=0 );
 28395    sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
 28396                        db->aLimit[SQLITE_LIMIT_LENGTH]);
 28397    acc.printfFlags = SQLITE_PRINTF_INTERNAL;
 28398    sqlite3_str_vappendf(&acc, zFormat, ap);
 28399    z = sqlite3StrAccumFinish(&acc);
 28400    if( acc.accError==SQLITE_NOMEM ){
 28401      sqlite3OomFault(db);
 28402    }
 28403    return z;
 28404  }
 28405  
 28406  /*
 28407  ** Print into memory obtained from sqliteMalloc().  Use the internal
 28408  ** %-conversion extensions.
 28409  */
 28410  SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
 28411    va_list ap;
 28412    char *z;
 28413    va_start(ap, zFormat);
 28414    z = sqlite3VMPrintf(db, zFormat, ap);
 28415    va_end(ap);
 28416    return z;
 28417  }
 28418  
 28419  /*
 28420  ** Print into memory obtained from sqlite3_malloc().  Omit the internal
 28421  ** %-conversion extensions.
 28422  */
 28423  SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
 28424    char *z;
 28425    char zBase[SQLITE_PRINT_BUF_SIZE];
 28426    StrAccum acc;
 28427  
 28428  #ifdef SQLITE_ENABLE_API_ARMOR  
 28429    if( zFormat==0 ){
 28430      (void)SQLITE_MISUSE_BKPT;
 28431      return 0;
 28432    }
 28433  #endif
 28434  #ifndef SQLITE_OMIT_AUTOINIT
 28435    if( sqlite3_initialize() ) return 0;
 28436  #endif
 28437    sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
 28438    sqlite3_str_vappendf(&acc, zFormat, ap);
 28439    z = sqlite3StrAccumFinish(&acc);
 28440    return z;
 28441  }
 28442  
 28443  /*
 28444  ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
 28445  ** %-conversion extensions.
 28446  */
 28447  SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
 28448    va_list ap;
 28449    char *z;
 28450  #ifndef SQLITE_OMIT_AUTOINIT
 28451    if( sqlite3_initialize() ) return 0;
 28452  #endif
 28453    va_start(ap, zFormat);
 28454    z = sqlite3_vmprintf(zFormat, ap);
 28455    va_end(ap);
 28456    return z;
 28457  }
 28458  
 28459  /*
 28460  ** sqlite3_snprintf() works like snprintf() except that it ignores the
 28461  ** current locale settings.  This is important for SQLite because we
 28462  ** are not able to use a "," as the decimal point in place of "." as
 28463  ** specified by some locales.
 28464  **
 28465  ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
 28466  ** from the snprintf() standard.  Unfortunately, it is too late to change
 28467  ** this without breaking compatibility, so we just have to live with the
 28468  ** mistake.
 28469  **
 28470  ** sqlite3_vsnprintf() is the varargs version.
 28471  */
 28472  SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
 28473    StrAccum acc;
 28474    if( n<=0 ) return zBuf;
 28475  #ifdef SQLITE_ENABLE_API_ARMOR
 28476    if( zBuf==0 || zFormat==0 ) {
 28477      (void)SQLITE_MISUSE_BKPT;
 28478      if( zBuf ) zBuf[0] = 0;
 28479      return zBuf;
 28480    }
 28481  #endif
 28482    sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
 28483    sqlite3_str_vappendf(&acc, zFormat, ap);
 28484    zBuf[acc.nChar] = 0;
 28485    return zBuf;
 28486  }
 28487  SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
 28488    char *z;
 28489    va_list ap;
 28490    va_start(ap,zFormat);
 28491    z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
 28492    va_end(ap);
 28493    return z;
 28494  }
 28495  
 28496  /*
 28497  ** This is the routine that actually formats the sqlite3_log() message.
 28498  ** We house it in a separate routine from sqlite3_log() to avoid using
 28499  ** stack space on small-stack systems when logging is disabled.
 28500  **
 28501  ** sqlite3_log() must render into a static buffer.  It cannot dynamically
 28502  ** allocate memory because it might be called while the memory allocator
 28503  ** mutex is held.
 28504  **
 28505  ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
 28506  ** certain format characters (%q) or for very large precisions or widths.
 28507  ** Care must be taken that any sqlite3_log() calls that occur while the
 28508  ** memory mutex is held do not use these mechanisms.
 28509  */
 28510  static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
 28511    StrAccum acc;                          /* String accumulator */
 28512    char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
 28513  
 28514    sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
 28515    sqlite3_str_vappendf(&acc, zFormat, ap);
 28516    sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
 28517                             sqlite3StrAccumFinish(&acc));
 28518  }
 28519  
 28520  /*
 28521  ** Format and write a message to the log if logging is enabled.
 28522  */
 28523  SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
 28524    va_list ap;                             /* Vararg list */
 28525    if( sqlite3GlobalConfig.xLog ){
 28526      va_start(ap, zFormat);
 28527      renderLogMsg(iErrCode, zFormat, ap);
 28528      va_end(ap);
 28529    }
 28530  }
 28531  
 28532  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 28533  /*
 28534  ** A version of printf() that understands %lld.  Used for debugging.
 28535  ** The printf() built into some versions of windows does not understand %lld
 28536  ** and segfaults if you give it a long long int.
 28537  */
 28538  SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
 28539    va_list ap;
 28540    StrAccum acc;
 28541    char zBuf[500];
 28542    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 28543    va_start(ap,zFormat);
 28544    sqlite3_str_vappendf(&acc, zFormat, ap);
 28545    va_end(ap);
 28546    sqlite3StrAccumFinish(&acc);
 28547  #ifdef SQLITE_OS_TRACE_PROC
 28548    {
 28549      extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
 28550      SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
 28551    }
 28552  #else
 28553    fprintf(stdout,"%s", zBuf);
 28554    fflush(stdout);
 28555  #endif
 28556  }
 28557  #endif
 28558  
 28559  
 28560  /*
 28561  ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
 28562  ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
 28563  */
 28564  SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
 28565    va_list ap;
 28566    va_start(ap,zFormat);
 28567    sqlite3_str_vappendf(p, zFormat, ap);
 28568    va_end(ap);
 28569  }
 28570  
 28571  /************** End of printf.c **********************************************/
 28572  /************** Begin file treeview.c ****************************************/
 28573  /*
 28574  ** 2015-06-08
 28575  **
 28576  ** The author disclaims copyright to this source code.  In place of
 28577  ** a legal notice, here is a blessing:
 28578  **
 28579  **    May you do good and not evil.
 28580  **    May you find forgiveness for yourself and forgive others.
 28581  **    May you share freely, never taking more than you give.
 28582  **
 28583  *************************************************************************
 28584  **
 28585  ** This file contains C code to implement the TreeView debugging routines.
 28586  ** These routines print a parse tree to standard output for debugging and
 28587  ** analysis. 
 28588  **
 28589  ** The interfaces in this file is only available when compiling
 28590  ** with SQLITE_DEBUG.
 28591  */
 28592  /* #include "sqliteInt.h" */
 28593  #ifdef SQLITE_DEBUG
 28594  
 28595  /*
 28596  ** Add a new subitem to the tree.  The moreToFollow flag indicates that this
 28597  ** is not the last item in the tree.
 28598  */
 28599  static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
 28600    if( p==0 ){
 28601      p = sqlite3_malloc64( sizeof(*p) );
 28602      if( p==0 ) return 0;
 28603      memset(p, 0, sizeof(*p));
 28604    }else{
 28605      p->iLevel++;
 28606    }
 28607    assert( moreToFollow==0 || moreToFollow==1 );
 28608    if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
 28609    return p;
 28610  }
 28611  
 28612  /*
 28613  ** Finished with one layer of the tree
 28614  */
 28615  static void sqlite3TreeViewPop(TreeView *p){
 28616    if( p==0 ) return;
 28617    p->iLevel--;
 28618    if( p->iLevel<0 ) sqlite3_free(p);
 28619  }
 28620  
 28621  /*
 28622  ** Generate a single line of output for the tree, with a prefix that contains
 28623  ** all the appropriate tree lines
 28624  */
 28625  static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
 28626    va_list ap;
 28627    int i;
 28628    StrAccum acc;
 28629    char zBuf[500];
 28630    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
 28631    if( p ){
 28632      for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
 28633        sqlite3_str_append(&acc, p->bLine[i] ? "|   " : "    ", 4);
 28634      }
 28635      sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
 28636    }
 28637    if( zFormat!=0 ){
 28638      va_start(ap, zFormat);
 28639      sqlite3_str_vappendf(&acc, zFormat, ap);
 28640      va_end(ap);
 28641      assert( acc.nChar>0 );
 28642      sqlite3_str_append(&acc, "\n", 1);
 28643    }
 28644    sqlite3StrAccumFinish(&acc);
 28645    fprintf(stdout,"%s", zBuf);
 28646    fflush(stdout);
 28647  }
 28648  
 28649  /*
 28650  ** Shorthand for starting a new tree item that consists of a single label
 28651  */
 28652  static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
 28653    p = sqlite3TreeViewPush(p, moreFollows);
 28654    sqlite3TreeViewLine(p, "%s", zLabel);
 28655  }
 28656  
 28657  /*
 28658  ** Generate a human-readable description of a WITH clause.
 28659  */
 28660  SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
 28661    int i;
 28662    if( pWith==0 ) return;
 28663    if( pWith->nCte==0 ) return;
 28664    if( pWith->pOuter ){
 28665      sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
 28666    }else{
 28667      sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
 28668    }
 28669    if( pWith->nCte>0 ){
 28670      pView = sqlite3TreeViewPush(pView, 1);
 28671      for(i=0; i<pWith->nCte; i++){
 28672        StrAccum x;
 28673        char zLine[1000];
 28674        const struct Cte *pCte = &pWith->a[i];
 28675        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 28676        sqlite3_str_appendf(&x, "%s", pCte->zName);
 28677        if( pCte->pCols && pCte->pCols->nExpr>0 ){
 28678          char cSep = '(';
 28679          int j;
 28680          for(j=0; j<pCte->pCols->nExpr; j++){
 28681            sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
 28682            cSep = ',';
 28683          }
 28684          sqlite3_str_appendf(&x, ")");
 28685        }
 28686        sqlite3_str_appendf(&x, " AS");
 28687        sqlite3StrAccumFinish(&x);
 28688        sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
 28689        sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
 28690        sqlite3TreeViewPop(pView);
 28691      }
 28692      sqlite3TreeViewPop(pView);
 28693    }
 28694  }
 28695  
 28696  /*
 28697  ** Generate a human-readable description of a SrcList object.
 28698  */
 28699  SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
 28700    int i;
 28701    for(i=0; i<pSrc->nSrc; i++){
 28702      const struct SrcList_item *pItem = &pSrc->a[i];
 28703      StrAccum x;
 28704      char zLine[100];
 28705      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
 28706      sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
 28707      if( pItem->zDatabase ){
 28708        sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
 28709      }else if( pItem->zName ){
 28710        sqlite3_str_appendf(&x, " %s", pItem->zName);
 28711      }
 28712      if( pItem->pTab ){
 28713        sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p",
 28714             pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab);
 28715      }
 28716      if( pItem->zAlias ){
 28717        sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
 28718      }
 28719      if( pItem->fg.jointype & JT_LEFT ){
 28720        sqlite3_str_appendf(&x, " LEFT-JOIN");
 28721      }
 28722      sqlite3StrAccumFinish(&x);
 28723      sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); 
 28724      if( pItem->pSelect ){
 28725        sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
 28726      }
 28727      if( pItem->fg.isTabFunc ){
 28728        sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
 28729      }
 28730      sqlite3TreeViewPop(pView);
 28731    }
 28732  }
 28733  
 28734  /*
 28735  ** Generate a human-readable description of a Select object.
 28736  */
 28737  SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
 28738    int n = 0;
 28739    int cnt = 0;
 28740    if( p==0 ){
 28741      sqlite3TreeViewLine(pView, "nil-SELECT");
 28742      return;
 28743    } 
 28744    pView = sqlite3TreeViewPush(pView, moreToFollow);
 28745    if( p->pWith ){
 28746      sqlite3TreeViewWith(pView, p->pWith, 1);
 28747      cnt = 1;
 28748      sqlite3TreeViewPush(pView, 1);
 28749    }
 28750    do{
 28751      sqlite3TreeViewLine(pView,
 28752        "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
 28753        ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
 28754        ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
 28755        p->selId, p, p->selFlags,
 28756        (int)p->nSelectRow
 28757      );
 28758      if( cnt++ ) sqlite3TreeViewPop(pView);
 28759      if( p->pPrior ){
 28760        n = 1000;
 28761      }else{
 28762        n = 0;
 28763        if( p->pSrc && p->pSrc->nSrc ) n++;
 28764        if( p->pWhere ) n++;
 28765        if( p->pGroupBy ) n++;
 28766        if( p->pHaving ) n++;
 28767        if( p->pOrderBy ) n++;
 28768        if( p->pLimit ) n++;
 28769  #ifndef SQLITE_OMIT_WINDOWFUNC
 28770        if( p->pWin ) n++;
 28771        if( p->pWinDefn ) n++;
 28772  #endif
 28773      }
 28774      sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
 28775  #ifndef SQLITE_OMIT_WINDOWFUNC
 28776      if( p->pWin ){
 28777        Window *pX;
 28778        pView = sqlite3TreeViewPush(pView, (n--)>0);
 28779        sqlite3TreeViewLine(pView, "window-functions");
 28780        for(pX=p->pWin; pX; pX=pX->pNextWin){
 28781          sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
 28782        }
 28783        sqlite3TreeViewPop(pView);
 28784      }
 28785  #endif
 28786      if( p->pSrc && p->pSrc->nSrc ){
 28787        pView = sqlite3TreeViewPush(pView, (n--)>0);
 28788        sqlite3TreeViewLine(pView, "FROM");
 28789        sqlite3TreeViewSrcList(pView, p->pSrc);
 28790        sqlite3TreeViewPop(pView);
 28791      }
 28792      if( p->pWhere ){
 28793        sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
 28794        sqlite3TreeViewExpr(pView, p->pWhere, 0);
 28795        sqlite3TreeViewPop(pView);
 28796      }
 28797      if( p->pGroupBy ){
 28798        sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
 28799      }
 28800      if( p->pHaving ){
 28801        sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
 28802        sqlite3TreeViewExpr(pView, p->pHaving, 0);
 28803        sqlite3TreeViewPop(pView);
 28804      }
 28805  #ifndef SQLITE_OMIT_WINDOWFUNC
 28806      if( p->pWinDefn ){
 28807        Window *pX;
 28808        sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
 28809        for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
 28810          sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
 28811        }
 28812        sqlite3TreeViewPop(pView);
 28813      }
 28814  #endif
 28815      if( p->pOrderBy ){
 28816        sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
 28817      }
 28818      if( p->pLimit ){
 28819        sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
 28820        sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
 28821        if( p->pLimit->pRight ){
 28822          sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
 28823          sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
 28824          sqlite3TreeViewPop(pView);
 28825        }
 28826        sqlite3TreeViewPop(pView);
 28827      }
 28828      if( p->pPrior ){
 28829        const char *zOp = "UNION";
 28830        switch( p->op ){
 28831          case TK_ALL:         zOp = "UNION ALL";  break;
 28832          case TK_INTERSECT:   zOp = "INTERSECT";  break;
 28833          case TK_EXCEPT:      zOp = "EXCEPT";     break;
 28834        }
 28835        sqlite3TreeViewItem(pView, zOp, 1);
 28836      }
 28837      p = p->pPrior;
 28838    }while( p!=0 );
 28839    sqlite3TreeViewPop(pView);
 28840  }
 28841  
 28842  #ifndef SQLITE_OMIT_WINDOWFUNC
 28843  /*
 28844  ** Generate a description of starting or stopping bounds
 28845  */
 28846  SQLITE_PRIVATE void sqlite3TreeViewBound(
 28847    TreeView *pView,        /* View context */
 28848    u8 eBound,              /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
 28849    Expr *pExpr,            /* Value for PRECEDING or FOLLOWING */
 28850    u8 moreToFollow         /* True if more to follow */
 28851  ){
 28852    switch( eBound ){
 28853      case TK_UNBOUNDED: {
 28854        sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
 28855        sqlite3TreeViewPop(pView);
 28856        break;
 28857      }
 28858      case TK_CURRENT: {
 28859        sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
 28860        sqlite3TreeViewPop(pView);
 28861        break;
 28862      }
 28863      case TK_PRECEDING: {
 28864        sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
 28865        sqlite3TreeViewExpr(pView, pExpr, 0);
 28866        sqlite3TreeViewPop(pView);
 28867        break;
 28868      }
 28869      case TK_FOLLOWING: {
 28870        sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
 28871        sqlite3TreeViewExpr(pView, pExpr, 0);
 28872        sqlite3TreeViewPop(pView);
 28873        break;
 28874      }
 28875    }
 28876  }
 28877  #endif /* SQLITE_OMIT_WINDOWFUNC */
 28878  
 28879  #ifndef SQLITE_OMIT_WINDOWFUNC
 28880  /*
 28881  ** Generate a human-readable explanation for a Window object
 28882  */
 28883  SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
 28884    pView = sqlite3TreeViewPush(pView, more);
 28885    if( pWin->zName ){
 28886      sqlite3TreeViewLine(pView, "OVER %s", pWin->zName);
 28887    }else{
 28888      sqlite3TreeViewLine(pView, "OVER");
 28889    }
 28890    if( pWin->pPartition ){
 28891      sqlite3TreeViewExprList(pView, pWin->pPartition, 1, "PARTITION-BY");
 28892    }
 28893    if( pWin->pOrderBy ){
 28894      sqlite3TreeViewExprList(pView, pWin->pOrderBy, 1, "ORDER-BY");
 28895    }
 28896    if( pWin->eType ){
 28897      sqlite3TreeViewItem(pView, pWin->eType==TK_RANGE ? "RANGE" : "ROWS", 0);
 28898      sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
 28899      sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
 28900      sqlite3TreeViewPop(pView);
 28901    }
 28902    sqlite3TreeViewPop(pView);
 28903  }
 28904  #endif /* SQLITE_OMIT_WINDOWFUNC */
 28905  
 28906  #ifndef SQLITE_OMIT_WINDOWFUNC
 28907  /*
 28908  ** Generate a human-readable explanation for a Window Function object
 28909  */
 28910  SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
 28911    pView = sqlite3TreeViewPush(pView, more);
 28912    sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
 28913                         pWin->pFunc->zName, pWin->pFunc->nArg);
 28914    sqlite3TreeViewWindow(pView, pWin, 0);
 28915    sqlite3TreeViewPop(pView);
 28916  }
 28917  #endif /* SQLITE_OMIT_WINDOWFUNC */
 28918  
 28919  /*
 28920  ** Generate a human-readable explanation of an expression tree.
 28921  */
 28922  SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
 28923    const char *zBinOp = 0;   /* Binary operator */
 28924    const char *zUniOp = 0;   /* Unary operator */
 28925    char zFlgs[60];
 28926    pView = sqlite3TreeViewPush(pView, moreToFollow);
 28927    if( pExpr==0 ){
 28928      sqlite3TreeViewLine(pView, "nil");
 28929      sqlite3TreeViewPop(pView);
 28930      return;
 28931    }
 28932    if( pExpr->flags ){
 28933      if( ExprHasProperty(pExpr, EP_FromJoin) ){
 28934        sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x iRJT=%d",
 28935                         pExpr->flags, pExpr->iRightJoinTable);
 28936      }else{
 28937        sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
 28938      }
 28939    }else{
 28940      zFlgs[0] = 0;
 28941    }
 28942    switch( pExpr->op ){
 28943      case TK_AGG_COLUMN: {
 28944        sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
 28945              pExpr->iTable, pExpr->iColumn, zFlgs);
 28946        break;
 28947      }
 28948      case TK_COLUMN: {
 28949        if( pExpr->iTable<0 ){
 28950          /* This only happens when coding check constraints */
 28951          sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
 28952        }else{
 28953          sqlite3TreeViewLine(pView, "{%d:%d}%s",
 28954                               pExpr->iTable, pExpr->iColumn, zFlgs);
 28955        }
 28956        if( ExprHasProperty(pExpr, EP_FixedCol) ){
 28957          sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 28958        }
 28959        break;
 28960      }
 28961      case TK_INTEGER: {
 28962        if( pExpr->flags & EP_IntValue ){
 28963          sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
 28964        }else{
 28965          sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
 28966        }
 28967        break;
 28968      }
 28969  #ifndef SQLITE_OMIT_FLOATING_POINT
 28970      case TK_FLOAT: {
 28971        sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
 28972        break;
 28973      }
 28974  #endif
 28975      case TK_STRING: {
 28976        sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
 28977        break;
 28978      }
 28979      case TK_NULL: {
 28980        sqlite3TreeViewLine(pView,"NULL");
 28981        break;
 28982      }
 28983      case TK_TRUEFALSE: {
 28984        sqlite3TreeViewLine(pView,
 28985           sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
 28986        break;
 28987      }
 28988  #ifndef SQLITE_OMIT_BLOB_LITERAL
 28989      case TK_BLOB: {
 28990        sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
 28991        break;
 28992      }
 28993  #endif
 28994      case TK_VARIABLE: {
 28995        sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
 28996                            pExpr->u.zToken, pExpr->iColumn);
 28997        break;
 28998      }
 28999      case TK_REGISTER: {
 29000        sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
 29001        break;
 29002      }
 29003      case TK_ID: {
 29004        sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
 29005        break;
 29006      }
 29007  #ifndef SQLITE_OMIT_CAST
 29008      case TK_CAST: {
 29009        /* Expressions of the form:   CAST(pLeft AS token) */
 29010        sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
 29011        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 29012        break;
 29013      }
 29014  #endif /* SQLITE_OMIT_CAST */
 29015      case TK_LT:      zBinOp = "LT";     break;
 29016      case TK_LE:      zBinOp = "LE";     break;
 29017      case TK_GT:      zBinOp = "GT";     break;
 29018      case TK_GE:      zBinOp = "GE";     break;
 29019      case TK_NE:      zBinOp = "NE";     break;
 29020      case TK_EQ:      zBinOp = "EQ";     break;
 29021      case TK_IS:      zBinOp = "IS";     break;
 29022      case TK_ISNOT:   zBinOp = "ISNOT";  break;
 29023      case TK_AND:     zBinOp = "AND";    break;
 29024      case TK_OR:      zBinOp = "OR";     break;
 29025      case TK_PLUS:    zBinOp = "ADD";    break;
 29026      case TK_STAR:    zBinOp = "MUL";    break;
 29027      case TK_MINUS:   zBinOp = "SUB";    break;
 29028      case TK_REM:     zBinOp = "REM";    break;
 29029      case TK_BITAND:  zBinOp = "BITAND"; break;
 29030      case TK_BITOR:   zBinOp = "BITOR";  break;
 29031      case TK_SLASH:   zBinOp = "DIV";    break;
 29032      case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
 29033      case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
 29034      case TK_CONCAT:  zBinOp = "CONCAT"; break;
 29035      case TK_DOT:     zBinOp = "DOT";    break;
 29036  
 29037      case TK_UMINUS:  zUniOp = "UMINUS"; break;
 29038      case TK_UPLUS:   zUniOp = "UPLUS";  break;
 29039      case TK_BITNOT:  zUniOp = "BITNOT"; break;
 29040      case TK_NOT:     zUniOp = "NOT";    break;
 29041      case TK_ISNULL:  zUniOp = "ISNULL"; break;
 29042      case TK_NOTNULL: zUniOp = "NOTNULL"; break;
 29043  
 29044      case TK_TRUTH: {
 29045        int x;
 29046        const char *azOp[] = {
 29047           "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
 29048        };
 29049        assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
 29050        assert( pExpr->pRight );
 29051        assert( pExpr->pRight->op==TK_TRUEFALSE );
 29052        x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
 29053        zUniOp = azOp[x];
 29054        break;
 29055      }
 29056  
 29057      case TK_SPAN: {
 29058        sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
 29059        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 29060        break;
 29061      }
 29062  
 29063      case TK_COLLATE: {
 29064        sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
 29065        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 29066        break;
 29067      }
 29068  
 29069      case TK_AGG_FUNCTION:
 29070      case TK_FUNCTION: {
 29071        ExprList *pFarg;       /* List of function arguments */
 29072        Window *pWin;
 29073        if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 29074          pFarg = 0;
 29075          pWin = 0;
 29076        }else{
 29077          pFarg = pExpr->x.pList;
 29078  #ifndef SQLITE_OMIT_WINDOWFUNC
 29079          pWin = pExpr->y.pWin;
 29080  #else
 29081          pWin = 0;
 29082  #endif 
 29083        }
 29084        if( pExpr->op==TK_AGG_FUNCTION ){
 29085          sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
 29086                               pExpr->op2, pExpr->u.zToken);
 29087        }else{
 29088          sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
 29089        }
 29090        if( pFarg ){
 29091          sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
 29092        }
 29093  #ifndef SQLITE_OMIT_WINDOWFUNC
 29094        if( pWin ){
 29095          sqlite3TreeViewWindow(pView, pWin, 0);
 29096        }
 29097  #endif
 29098        break;
 29099      }
 29100  #ifndef SQLITE_OMIT_SUBQUERY
 29101      case TK_EXISTS: {
 29102        sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
 29103        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 29104        break;
 29105      }
 29106      case TK_SELECT: {
 29107        sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
 29108        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 29109        break;
 29110      }
 29111      case TK_IN: {
 29112        sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
 29113        sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 29114        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 29115          sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
 29116        }else{
 29117          sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
 29118        }
 29119        break;
 29120      }
 29121  #endif /* SQLITE_OMIT_SUBQUERY */
 29122  
 29123      /*
 29124      **    x BETWEEN y AND z
 29125      **
 29126      ** This is equivalent to
 29127      **
 29128      **    x>=y AND x<=z
 29129      **
 29130      ** X is stored in pExpr->pLeft.
 29131      ** Y is stored in pExpr->pList->a[0].pExpr.
 29132      ** Z is stored in pExpr->pList->a[1].pExpr.
 29133      */
 29134      case TK_BETWEEN: {
 29135        Expr *pX = pExpr->pLeft;
 29136        Expr *pY = pExpr->x.pList->a[0].pExpr;
 29137        Expr *pZ = pExpr->x.pList->a[1].pExpr;
 29138        sqlite3TreeViewLine(pView, "BETWEEN");
 29139        sqlite3TreeViewExpr(pView, pX, 1);
 29140        sqlite3TreeViewExpr(pView, pY, 1);
 29141        sqlite3TreeViewExpr(pView, pZ, 0);
 29142        break;
 29143      }
 29144      case TK_TRIGGER: {
 29145        /* If the opcode is TK_TRIGGER, then the expression is a reference
 29146        ** to a column in the new.* or old.* pseudo-tables available to
 29147        ** trigger programs. In this case Expr.iTable is set to 1 for the
 29148        ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
 29149        ** is set to the column of the pseudo-table to read, or to -1 to
 29150        ** read the rowid field.
 29151        */
 29152        sqlite3TreeViewLine(pView, "%s(%d)", 
 29153            pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
 29154        break;
 29155      }
 29156      case TK_CASE: {
 29157        sqlite3TreeViewLine(pView, "CASE");
 29158        sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 29159        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
 29160        break;
 29161      }
 29162  #ifndef SQLITE_OMIT_TRIGGER
 29163      case TK_RAISE: {
 29164        const char *zType = "unk";
 29165        switch( pExpr->affinity ){
 29166          case OE_Rollback:   zType = "rollback";  break;
 29167          case OE_Abort:      zType = "abort";     break;
 29168          case OE_Fail:       zType = "fail";      break;
 29169          case OE_Ignore:     zType = "ignore";    break;
 29170        }
 29171        sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
 29172        break;
 29173      }
 29174  #endif
 29175      case TK_MATCH: {
 29176        sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
 29177                            pExpr->iTable, pExpr->iColumn, zFlgs);
 29178        sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
 29179        break;
 29180      }
 29181      case TK_VECTOR: {
 29182        sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
 29183        break;
 29184      }
 29185      case TK_SELECT_COLUMN: {
 29186        sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
 29187        sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
 29188        break;
 29189      }
 29190      case TK_IF_NULL_ROW: {
 29191        sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
 29192        sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 29193        break;
 29194      }
 29195      default: {
 29196        sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
 29197        break;
 29198      }
 29199    }
 29200    if( zBinOp ){
 29201      sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
 29202      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
 29203      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
 29204    }else if( zUniOp ){
 29205      sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
 29206      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
 29207    }
 29208    sqlite3TreeViewPop(pView);
 29209  }
 29210  
 29211  
 29212  /*
 29213  ** Generate a human-readable explanation of an expression list.
 29214  */
 29215  SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
 29216    TreeView *pView,
 29217    const ExprList *pList,
 29218    const char *zLabel
 29219  ){
 29220    if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
 29221    if( pList==0 ){
 29222      sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
 29223    }else{
 29224      int i;
 29225      sqlite3TreeViewLine(pView, "%s", zLabel);
 29226      for(i=0; i<pList->nExpr; i++){
 29227        int j = pList->a[i].u.x.iOrderByCol;
 29228        char *zName = pList->a[i].zName;
 29229        int moreToFollow = i<pList->nExpr - 1;
 29230        if( j || zName ){
 29231          sqlite3TreeViewPush(pView, moreToFollow);
 29232          moreToFollow = 0;
 29233          sqlite3TreeViewLine(pView, 0);
 29234          if( zName ){
 29235            fprintf(stdout, "AS %s ", zName);
 29236          }
 29237          if( j ){
 29238            fprintf(stdout, "iOrderByCol=%d", j);
 29239          }
 29240          fprintf(stdout, "\n");
 29241          fflush(stdout);
 29242        }
 29243        sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
 29244        if( j || zName ){
 29245          sqlite3TreeViewPop(pView);
 29246        }
 29247      }
 29248    }
 29249  }
 29250  SQLITE_PRIVATE void sqlite3TreeViewExprList(
 29251    TreeView *pView,
 29252    const ExprList *pList,
 29253    u8 moreToFollow,
 29254    const char *zLabel
 29255  ){
 29256    pView = sqlite3TreeViewPush(pView, moreToFollow);
 29257    sqlite3TreeViewBareExprList(pView, pList, zLabel);
 29258    sqlite3TreeViewPop(pView);
 29259  }
 29260  
 29261  #endif /* SQLITE_DEBUG */
 29262  
 29263  /************** End of treeview.c ********************************************/
 29264  /************** Begin file random.c ******************************************/
 29265  /*
 29266  ** 2001 September 15
 29267  **
 29268  ** The author disclaims copyright to this source code.  In place of
 29269  ** a legal notice, here is a blessing:
 29270  **
 29271  **    May you do good and not evil.
 29272  **    May you find forgiveness for yourself and forgive others.
 29273  **    May you share freely, never taking more than you give.
 29274  **
 29275  *************************************************************************
 29276  ** This file contains code to implement a pseudo-random number
 29277  ** generator (PRNG) for SQLite.
 29278  **
 29279  ** Random numbers are used by some of the database backends in order
 29280  ** to generate random integer keys for tables or random filenames.
 29281  */
 29282  /* #include "sqliteInt.h" */
 29283  
 29284  
 29285  /* All threads share a single random number generator.
 29286  ** This structure is the current state of the generator.
 29287  */
 29288  static SQLITE_WSD struct sqlite3PrngType {
 29289    unsigned char isInit;          /* True if initialized */
 29290    unsigned char i, j;            /* State variables */
 29291    unsigned char s[256];          /* State variables */
 29292  } sqlite3Prng;
 29293  
 29294  /*
 29295  ** Return N random bytes.
 29296  */
 29297  SQLITE_API void sqlite3_randomness(int N, void *pBuf){
 29298    unsigned char t;
 29299    unsigned char *zBuf = pBuf;
 29300  
 29301    /* The "wsdPrng" macro will resolve to the pseudo-random number generator
 29302    ** state vector.  If writable static data is unsupported on the target,
 29303    ** we have to locate the state vector at run-time.  In the more common
 29304    ** case where writable static data is supported, wsdPrng can refer directly
 29305    ** to the "sqlite3Prng" state vector declared above.
 29306    */
 29307  #ifdef SQLITE_OMIT_WSD
 29308    struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
 29309  # define wsdPrng p[0]
 29310  #else
 29311  # define wsdPrng sqlite3Prng
 29312  #endif
 29313  
 29314  #if SQLITE_THREADSAFE
 29315    sqlite3_mutex *mutex;
 29316  #endif
 29317  
 29318  #ifndef SQLITE_OMIT_AUTOINIT
 29319    if( sqlite3_initialize() ) return;
 29320  #endif
 29321  
 29322  #if SQLITE_THREADSAFE
 29323    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
 29324  #endif
 29325  
 29326    sqlite3_mutex_enter(mutex);
 29327    if( N<=0 || pBuf==0 ){
 29328      wsdPrng.isInit = 0;
 29329      sqlite3_mutex_leave(mutex);
 29330      return;
 29331    }
 29332  
 29333    /* Initialize the state of the random number generator once,
 29334    ** the first time this routine is called.  The seed value does
 29335    ** not need to contain a lot of randomness since we are not
 29336    ** trying to do secure encryption or anything like that...
 29337    **
 29338    ** Nothing in this file or anywhere else in SQLite does any kind of
 29339    ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
 29340    ** number generator) not as an encryption device.
 29341    */
 29342    if( !wsdPrng.isInit ){
 29343      int i;
 29344      char k[256];
 29345      wsdPrng.j = 0;
 29346      wsdPrng.i = 0;
 29347      sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
 29348      for(i=0; i<256; i++){
 29349        wsdPrng.s[i] = (u8)i;
 29350      }
 29351      for(i=0; i<256; i++){
 29352        wsdPrng.j += wsdPrng.s[i] + k[i];
 29353        t = wsdPrng.s[wsdPrng.j];
 29354        wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
 29355        wsdPrng.s[i] = t;
 29356      }
 29357      wsdPrng.isInit = 1;
 29358    }
 29359  
 29360    assert( N>0 );
 29361    do{
 29362      wsdPrng.i++;
 29363      t = wsdPrng.s[wsdPrng.i];
 29364      wsdPrng.j += t;
 29365      wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
 29366      wsdPrng.s[wsdPrng.j] = t;
 29367      t += wsdPrng.s[wsdPrng.i];
 29368      *(zBuf++) = wsdPrng.s[t];
 29369    }while( --N );
 29370    sqlite3_mutex_leave(mutex);
 29371  }
 29372  
 29373  #ifndef SQLITE_UNTESTABLE
 29374  /*
 29375  ** For testing purposes, we sometimes want to preserve the state of
 29376  ** PRNG and restore the PRNG to its saved state at a later time, or
 29377  ** to reset the PRNG to its initial state.  These routines accomplish
 29378  ** those tasks.
 29379  **
 29380  ** The sqlite3_test_control() interface calls these routines to
 29381  ** control the PRNG.
 29382  */
 29383  static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
 29384  SQLITE_PRIVATE void sqlite3PrngSaveState(void){
 29385    memcpy(
 29386      &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 29387      &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 29388      sizeof(sqlite3Prng)
 29389    );
 29390  }
 29391  SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
 29392    memcpy(
 29393      &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
 29394      &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
 29395      sizeof(sqlite3Prng)
 29396    );
 29397  }
 29398  #endif /* SQLITE_UNTESTABLE */
 29399  
 29400  /************** End of random.c **********************************************/
 29401  /************** Begin file threads.c *****************************************/
 29402  /*
 29403  ** 2012 July 21
 29404  **
 29405  ** The author disclaims copyright to this source code.  In place of
 29406  ** a legal notice, here is a blessing:
 29407  **
 29408  **    May you do good and not evil.
 29409  **    May you find forgiveness for yourself and forgive others.
 29410  **    May you share freely, never taking more than you give.
 29411  **
 29412  ******************************************************************************
 29413  **
 29414  ** This file presents a simple cross-platform threading interface for
 29415  ** use internally by SQLite.
 29416  **
 29417  ** A "thread" can be created using sqlite3ThreadCreate().  This thread
 29418  ** runs independently of its creator until it is joined using
 29419  ** sqlite3ThreadJoin(), at which point it terminates.
 29420  **
 29421  ** Threads do not have to be real.  It could be that the work of the
 29422  ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
 29423  ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
 29424  ** single threaded systems.  Nothing in SQLite requires multiple threads.
 29425  ** This interface exists so that applications that want to take advantage
 29426  ** of multiple cores can do so, while also allowing applications to stay
 29427  ** single-threaded if desired.
 29428  */
 29429  /* #include "sqliteInt.h" */
 29430  #if SQLITE_OS_WIN
 29431  /* #  include "os_win.h" */
 29432  #endif
 29433  
 29434  #if SQLITE_MAX_WORKER_THREADS>0
 29435  
 29436  /********************************* Unix Pthreads ****************************/
 29437  #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
 29438  
 29439  #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
 29440  /* #include <pthread.h> */
 29441  
 29442  /* A running thread */
 29443  struct SQLiteThread {
 29444    pthread_t tid;                 /* Thread ID */
 29445    int done;                      /* Set to true when thread finishes */
 29446    void *pOut;                    /* Result returned by the thread */
 29447    void *(*xTask)(void*);         /* The thread routine */
 29448    void *pIn;                     /* Argument to the thread */
 29449  };
 29450  
 29451  /* Create a new thread */
 29452  SQLITE_PRIVATE int sqlite3ThreadCreate(
 29453    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 29454    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 29455    void *pIn                 /* Argument passed into xTask() */
 29456  ){
 29457    SQLiteThread *p;
 29458    int rc;
 29459  
 29460    assert( ppThread!=0 );
 29461    assert( xTask!=0 );
 29462    /* This routine is never used in single-threaded mode */
 29463    assert( sqlite3GlobalConfig.bCoreMutex!=0 );
 29464  
 29465    *ppThread = 0;
 29466    p = sqlite3Malloc(sizeof(*p));
 29467    if( p==0 ) return SQLITE_NOMEM_BKPT;
 29468    memset(p, 0, sizeof(*p));
 29469    p->xTask = xTask;
 29470    p->pIn = pIn;
 29471    /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 29472    ** function that returns SQLITE_ERROR when passed the argument 200, that
 29473    ** forces worker threads to run sequentially and deterministically 
 29474    ** for testing purposes. */
 29475    if( sqlite3FaultSim(200) ){
 29476      rc = 1;
 29477    }else{    
 29478      rc = pthread_create(&p->tid, 0, xTask, pIn);
 29479    }
 29480    if( rc ){
 29481      p->done = 1;
 29482      p->pOut = xTask(pIn);
 29483    }
 29484    *ppThread = p;
 29485    return SQLITE_OK;
 29486  }
 29487  
 29488  /* Get the results of the thread */
 29489  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 29490    int rc;
 29491  
 29492    assert( ppOut!=0 );
 29493    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 29494    if( p->done ){
 29495      *ppOut = p->pOut;
 29496      rc = SQLITE_OK;
 29497    }else{
 29498      rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
 29499    }
 29500    sqlite3_free(p);
 29501    return rc;
 29502  }
 29503  
 29504  #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
 29505  /******************************** End Unix Pthreads *************************/
 29506  
 29507  
 29508  /********************************* Win32 Threads ****************************/
 29509  #if SQLITE_OS_WIN_THREADS
 29510  
 29511  #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
 29512  #include <process.h>
 29513  
 29514  /* A running thread */
 29515  struct SQLiteThread {
 29516    void *tid;               /* The thread handle */
 29517    unsigned id;             /* The thread identifier */
 29518    void *(*xTask)(void*);   /* The routine to run as a thread */
 29519    void *pIn;               /* Argument to xTask */
 29520    void *pResult;           /* Result of xTask */
 29521  };
 29522  
 29523  /* Thread procedure Win32 compatibility shim */
 29524  static unsigned __stdcall sqlite3ThreadProc(
 29525    void *pArg  /* IN: Pointer to the SQLiteThread structure */
 29526  ){
 29527    SQLiteThread *p = (SQLiteThread *)pArg;
 29528  
 29529    assert( p!=0 );
 29530  #if 0
 29531    /*
 29532    ** This assert appears to trigger spuriously on certain
 29533    ** versions of Windows, possibly due to _beginthreadex()
 29534    ** and/or CreateThread() not fully setting their thread
 29535    ** ID parameter before starting the thread.
 29536    */
 29537    assert( p->id==GetCurrentThreadId() );
 29538  #endif
 29539    assert( p->xTask!=0 );
 29540    p->pResult = p->xTask(p->pIn);
 29541  
 29542    _endthreadex(0);
 29543    return 0; /* NOT REACHED */
 29544  }
 29545  
 29546  /* Create a new thread */
 29547  SQLITE_PRIVATE int sqlite3ThreadCreate(
 29548    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 29549    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 29550    void *pIn                 /* Argument passed into xTask() */
 29551  ){
 29552    SQLiteThread *p;
 29553  
 29554    assert( ppThread!=0 );
 29555    assert( xTask!=0 );
 29556    *ppThread = 0;
 29557    p = sqlite3Malloc(sizeof(*p));
 29558    if( p==0 ) return SQLITE_NOMEM_BKPT;
 29559    /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
 29560    ** function that returns SQLITE_ERROR when passed the argument 200, that
 29561    ** forces worker threads to run sequentially and deterministically 
 29562    ** (via the sqlite3FaultSim() term of the conditional) for testing
 29563    ** purposes. */
 29564    if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
 29565      memset(p, 0, sizeof(*p));
 29566    }else{
 29567      p->xTask = xTask;
 29568      p->pIn = pIn;
 29569      p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
 29570      if( p->tid==0 ){
 29571        memset(p, 0, sizeof(*p));
 29572      }
 29573    }
 29574    if( p->xTask==0 ){
 29575      p->id = GetCurrentThreadId();
 29576      p->pResult = xTask(pIn);
 29577    }
 29578    *ppThread = p;
 29579    return SQLITE_OK;
 29580  }
 29581  
 29582  SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
 29583  
 29584  /* Get the results of the thread */
 29585  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 29586    DWORD rc;
 29587    BOOL bRc;
 29588  
 29589    assert( ppOut!=0 );
 29590    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 29591    if( p->xTask==0 ){
 29592      /* assert( p->id==GetCurrentThreadId() ); */
 29593      rc = WAIT_OBJECT_0;
 29594      assert( p->tid==0 );
 29595    }else{
 29596      assert( p->id!=0 && p->id!=GetCurrentThreadId() );
 29597      rc = sqlite3Win32Wait((HANDLE)p->tid);
 29598      assert( rc!=WAIT_IO_COMPLETION );
 29599      bRc = CloseHandle((HANDLE)p->tid);
 29600      assert( bRc );
 29601    }
 29602    if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
 29603    sqlite3_free(p);
 29604    return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
 29605  }
 29606  
 29607  #endif /* SQLITE_OS_WIN_THREADS */
 29608  /******************************** End Win32 Threads *************************/
 29609  
 29610  
 29611  /********************************* Single-Threaded **************************/
 29612  #ifndef SQLITE_THREADS_IMPLEMENTED
 29613  /*
 29614  ** This implementation does not actually create a new thread.  It does the
 29615  ** work of the thread in the main thread, when either the thread is created
 29616  ** or when it is joined
 29617  */
 29618  
 29619  /* A running thread */
 29620  struct SQLiteThread {
 29621    void *(*xTask)(void*);   /* The routine to run as a thread */
 29622    void *pIn;               /* Argument to xTask */
 29623    void *pResult;           /* Result of xTask */
 29624  };
 29625  
 29626  /* Create a new thread */
 29627  SQLITE_PRIVATE int sqlite3ThreadCreate(
 29628    SQLiteThread **ppThread,  /* OUT: Write the thread object here */
 29629    void *(*xTask)(void*),    /* Routine to run in a separate thread */
 29630    void *pIn                 /* Argument passed into xTask() */
 29631  ){
 29632    SQLiteThread *p;
 29633  
 29634    assert( ppThread!=0 );
 29635    assert( xTask!=0 );
 29636    *ppThread = 0;
 29637    p = sqlite3Malloc(sizeof(*p));
 29638    if( p==0 ) return SQLITE_NOMEM_BKPT;
 29639    if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
 29640      p->xTask = xTask;
 29641      p->pIn = pIn;
 29642    }else{
 29643      p->xTask = 0;
 29644      p->pResult = xTask(pIn);
 29645    }
 29646    *ppThread = p;
 29647    return SQLITE_OK;
 29648  }
 29649  
 29650  /* Get the results of the thread */
 29651  SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 29652  
 29653    assert( ppOut!=0 );
 29654    if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
 29655    if( p->xTask ){
 29656      *ppOut = p->xTask(p->pIn);
 29657    }else{
 29658      *ppOut = p->pResult;
 29659    }
 29660    sqlite3_free(p);
 29661  
 29662  #if defined(SQLITE_TEST)
 29663    {
 29664      void *pTstAlloc = sqlite3Malloc(10);
 29665      if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
 29666      sqlite3_free(pTstAlloc);
 29667    }
 29668  #endif
 29669  
 29670    return SQLITE_OK;
 29671  }
 29672  
 29673  #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
 29674  /****************************** End Single-Threaded *************************/
 29675  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 29676  
 29677  /************** End of threads.c *********************************************/
 29678  /************** Begin file utf.c *********************************************/
 29679  /*
 29680  ** 2004 April 13
 29681  **
 29682  ** The author disclaims copyright to this source code.  In place of
 29683  ** a legal notice, here is a blessing:
 29684  **
 29685  **    May you do good and not evil.
 29686  **    May you find forgiveness for yourself and forgive others.
 29687  **    May you share freely, never taking more than you give.
 29688  **
 29689  *************************************************************************
 29690  ** This file contains routines used to translate between UTF-8, 
 29691  ** UTF-16, UTF-16BE, and UTF-16LE.
 29692  **
 29693  ** Notes on UTF-8:
 29694  **
 29695  **   Byte-0    Byte-1    Byte-2    Byte-3    Value
 29696  **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
 29697  **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
 29698  **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
 29699  **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
 29700  **
 29701  **
 29702  ** Notes on UTF-16:  (with wwww+1==uuuuu)
 29703  **
 29704  **      Word-0               Word-1          Value
 29705  **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
 29706  **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
 29707  **
 29708  **
 29709  ** BOM or Byte Order Mark:
 29710  **     0xff 0xfe   little-endian utf-16 follows
 29711  **     0xfe 0xff   big-endian utf-16 follows
 29712  **
 29713  */
 29714  /* #include "sqliteInt.h" */
 29715  /* #include <assert.h> */
 29716  /* #include "vdbeInt.h" */
 29717  
 29718  #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
 29719  /*
 29720  ** The following constant value is used by the SQLITE_BIGENDIAN and
 29721  ** SQLITE_LITTLEENDIAN macros.
 29722  */
 29723  SQLITE_PRIVATE const int sqlite3one = 1;
 29724  #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
 29725  
 29726  /*
 29727  ** This lookup table is used to help decode the first byte of
 29728  ** a multi-byte UTF8 character.
 29729  */
 29730  static const unsigned char sqlite3Utf8Trans1[] = {
 29731    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 29732    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 29733    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
 29734    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
 29735    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 29736    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 29737    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 29738    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
 29739  };
 29740  
 29741  
 29742  #define WRITE_UTF8(zOut, c) {                          \
 29743    if( c<0x00080 ){                                     \
 29744      *zOut++ = (u8)(c&0xFF);                            \
 29745    }                                                    \
 29746    else if( c<0x00800 ){                                \
 29747      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
 29748      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 29749    }                                                    \
 29750    else if( c<0x10000 ){                                \
 29751      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
 29752      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 29753      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 29754    }else{                                               \
 29755      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
 29756      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
 29757      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
 29758      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
 29759    }                                                    \
 29760  }
 29761  
 29762  #define WRITE_UTF16LE(zOut, c) {                                    \
 29763    if( c<=0xFFFF ){                                                  \
 29764      *zOut++ = (u8)(c&0x00FF);                                       \
 29765      *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 29766    }else{                                                            \
 29767      *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 29768      *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 29769      *zOut++ = (u8)(c&0x00FF);                                       \
 29770      *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 29771    }                                                                 \
 29772  }
 29773  
 29774  #define WRITE_UTF16BE(zOut, c) {                                    \
 29775    if( c<=0xFFFF ){                                                  \
 29776      *zOut++ = (u8)((c>>8)&0x00FF);                                  \
 29777      *zOut++ = (u8)(c&0x00FF);                                       \
 29778    }else{                                                            \
 29779      *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
 29780      *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
 29781      *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
 29782      *zOut++ = (u8)(c&0x00FF);                                       \
 29783    }                                                                 \
 29784  }
 29785  
 29786  #define READ_UTF16LE(zIn, TERM, c){                                   \
 29787    c = (*zIn++);                                                       \
 29788    c += ((*zIn++)<<8);                                                 \
 29789    if( c>=0xD800 && c<0xE000 && TERM ){                                \
 29790      int c2 = (*zIn++);                                                \
 29791      c2 += ((*zIn++)<<8);                                              \
 29792      c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 29793    }                                                                   \
 29794  }
 29795  
 29796  #define READ_UTF16BE(zIn, TERM, c){                                   \
 29797    c = ((*zIn++)<<8);                                                  \
 29798    c += (*zIn++);                                                      \
 29799    if( c>=0xD800 && c<0xE000 && TERM ){                                \
 29800      int c2 = ((*zIn++)<<8);                                           \
 29801      c2 += (*zIn++);                                                   \
 29802      c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
 29803    }                                                                   \
 29804  }
 29805  
 29806  /*
 29807  ** Translate a single UTF-8 character.  Return the unicode value.
 29808  **
 29809  ** During translation, assume that the byte that zTerm points
 29810  ** is a 0x00.
 29811  **
 29812  ** Write a pointer to the next unread byte back into *pzNext.
 29813  **
 29814  ** Notes On Invalid UTF-8:
 29815  **
 29816  **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
 29817  **     be encoded as a multi-byte character.  Any multi-byte character that
 29818  **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
 29819  **
 29820  **  *  This routine never allows a UTF16 surrogate value to be encoded.
 29821  **     If a multi-byte character attempts to encode a value between
 29822  **     0xd800 and 0xe000 then it is rendered as 0xfffd.
 29823  **
 29824  **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
 29825  **     byte of a character are interpreted as single-byte characters
 29826  **     and rendered as themselves even though they are technically
 29827  **     invalid characters.
 29828  **
 29829  **  *  This routine accepts over-length UTF8 encodings
 29830  **     for unicode values 0x80 and greater.  It does not change over-length
 29831  **     encodings to 0xfffd as some systems recommend.
 29832  */
 29833  #define READ_UTF8(zIn, zTerm, c)                           \
 29834    c = *(zIn++);                                            \
 29835    if( c>=0xc0 ){                                           \
 29836      c = sqlite3Utf8Trans1[c-0xc0];                         \
 29837      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
 29838        c = (c<<6) + (0x3f & *(zIn++));                      \
 29839      }                                                      \
 29840      if( c<0x80                                             \
 29841          || (c&0xFFFFF800)==0xD800                          \
 29842          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
 29843    }
 29844  SQLITE_PRIVATE u32 sqlite3Utf8Read(
 29845    const unsigned char **pz    /* Pointer to string from which to read char */
 29846  ){
 29847    unsigned int c;
 29848  
 29849    /* Same as READ_UTF8() above but without the zTerm parameter.
 29850    ** For this routine, we assume the UTF8 string is always zero-terminated.
 29851    */
 29852    c = *((*pz)++);
 29853    if( c>=0xc0 ){
 29854      c = sqlite3Utf8Trans1[c-0xc0];
 29855      while( (*(*pz) & 0xc0)==0x80 ){
 29856        c = (c<<6) + (0x3f & *((*pz)++));
 29857      }
 29858      if( c<0x80
 29859          || (c&0xFFFFF800)==0xD800
 29860          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
 29861    }
 29862    return c;
 29863  }
 29864  
 29865  
 29866  
 29867  
 29868  /*
 29869  ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
 29870  ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
 29871  */ 
 29872  /* #define TRANSLATE_TRACE 1 */
 29873  
 29874  #ifndef SQLITE_OMIT_UTF16
 29875  /*
 29876  ** This routine transforms the internal text encoding used by pMem to
 29877  ** desiredEnc. It is an error if the string is already of the desired
 29878  ** encoding, or if *pMem does not contain a string value.
 29879  */
 29880  SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
 29881    int len;                    /* Maximum length of output string in bytes */
 29882    unsigned char *zOut;                  /* Output buffer */
 29883    unsigned char *zIn;                   /* Input iterator */
 29884    unsigned char *zTerm;                 /* End of input */
 29885    unsigned char *z;                     /* Output iterator */
 29886    unsigned int c;
 29887  
 29888    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 29889    assert( pMem->flags&MEM_Str );
 29890    assert( pMem->enc!=desiredEnc );
 29891    assert( pMem->enc!=0 );
 29892    assert( pMem->n>=0 );
 29893  
 29894  #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 29895    {
 29896      char zBuf[100];
 29897      sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 29898      fprintf(stderr, "INPUT:  %s\n", zBuf);
 29899    }
 29900  #endif
 29901  
 29902    /* If the translation is between UTF-16 little and big endian, then 
 29903    ** all that is required is to swap the byte order. This case is handled
 29904    ** differently from the others.
 29905    */
 29906    if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
 29907      u8 temp;
 29908      int rc;
 29909      rc = sqlite3VdbeMemMakeWriteable(pMem);
 29910      if( rc!=SQLITE_OK ){
 29911        assert( rc==SQLITE_NOMEM );
 29912        return SQLITE_NOMEM_BKPT;
 29913      }
 29914      zIn = (u8*)pMem->z;
 29915      zTerm = &zIn[pMem->n&~1];
 29916      while( zIn<zTerm ){
 29917        temp = *zIn;
 29918        *zIn = *(zIn+1);
 29919        zIn++;
 29920        *zIn++ = temp;
 29921      }
 29922      pMem->enc = desiredEnc;
 29923      goto translate_out;
 29924    }
 29925  
 29926    /* Set len to the maximum number of bytes required in the output buffer. */
 29927    if( desiredEnc==SQLITE_UTF8 ){
 29928      /* When converting from UTF-16, the maximum growth results from
 29929      ** translating a 2-byte character to a 4-byte UTF-8 character.
 29930      ** A single byte is required for the output string
 29931      ** nul-terminator.
 29932      */
 29933      pMem->n &= ~1;
 29934      len = pMem->n * 2 + 1;
 29935    }else{
 29936      /* When converting from UTF-8 to UTF-16 the maximum growth is caused
 29937      ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
 29938      ** character. Two bytes are required in the output buffer for the
 29939      ** nul-terminator.
 29940      */
 29941      len = pMem->n * 2 + 2;
 29942    }
 29943  
 29944    /* Set zIn to point at the start of the input buffer and zTerm to point 1
 29945    ** byte past the end.
 29946    **
 29947    ** Variable zOut is set to point at the output buffer, space obtained
 29948    ** from sqlite3_malloc().
 29949    */
 29950    zIn = (u8*)pMem->z;
 29951    zTerm = &zIn[pMem->n];
 29952    zOut = sqlite3DbMallocRaw(pMem->db, len);
 29953    if( !zOut ){
 29954      return SQLITE_NOMEM_BKPT;
 29955    }
 29956    z = zOut;
 29957  
 29958    if( pMem->enc==SQLITE_UTF8 ){
 29959      if( desiredEnc==SQLITE_UTF16LE ){
 29960        /* UTF-8 -> UTF-16 Little-endian */
 29961        while( zIn<zTerm ){
 29962          READ_UTF8(zIn, zTerm, c);
 29963          WRITE_UTF16LE(z, c);
 29964        }
 29965      }else{
 29966        assert( desiredEnc==SQLITE_UTF16BE );
 29967        /* UTF-8 -> UTF-16 Big-endian */
 29968        while( zIn<zTerm ){
 29969          READ_UTF8(zIn, zTerm, c);
 29970          WRITE_UTF16BE(z, c);
 29971        }
 29972      }
 29973      pMem->n = (int)(z - zOut);
 29974      *z++ = 0;
 29975    }else{
 29976      assert( desiredEnc==SQLITE_UTF8 );
 29977      if( pMem->enc==SQLITE_UTF16LE ){
 29978        /* UTF-16 Little-endian -> UTF-8 */
 29979        while( zIn<zTerm ){
 29980          READ_UTF16LE(zIn, zIn<zTerm, c); 
 29981          WRITE_UTF8(z, c);
 29982        }
 29983      }else{
 29984        /* UTF-16 Big-endian -> UTF-8 */
 29985        while( zIn<zTerm ){
 29986          READ_UTF16BE(zIn, zIn<zTerm, c); 
 29987          WRITE_UTF8(z, c);
 29988        }
 29989      }
 29990      pMem->n = (int)(z - zOut);
 29991    }
 29992    *z = 0;
 29993    assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
 29994  
 29995    c = pMem->flags;
 29996    sqlite3VdbeMemRelease(pMem);
 29997    pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
 29998    pMem->enc = desiredEnc;
 29999    pMem->z = (char*)zOut;
 30000    pMem->zMalloc = pMem->z;
 30001    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
 30002  
 30003  translate_out:
 30004  #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
 30005    {
 30006      char zBuf[100];
 30007      sqlite3VdbeMemPrettyPrint(pMem, zBuf);
 30008      fprintf(stderr, "OUTPUT: %s\n", zBuf);
 30009    }
 30010  #endif
 30011    return SQLITE_OK;
 30012  }
 30013  #endif /* SQLITE_OMIT_UTF16 */
 30014  
 30015  #ifndef SQLITE_OMIT_UTF16
 30016  /*
 30017  ** This routine checks for a byte-order mark at the beginning of the 
 30018  ** UTF-16 string stored in *pMem. If one is present, it is removed and
 30019  ** the encoding of the Mem adjusted. This routine does not do any
 30020  ** byte-swapping, it just sets Mem.enc appropriately.
 30021  **
 30022  ** The allocation (static, dynamic etc.) and encoding of the Mem may be
 30023  ** changed by this function.
 30024  */
 30025  SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
 30026    int rc = SQLITE_OK;
 30027    u8 bom = 0;
 30028  
 30029    assert( pMem->n>=0 );
 30030    if( pMem->n>1 ){
 30031      u8 b1 = *(u8 *)pMem->z;
 30032      u8 b2 = *(((u8 *)pMem->z) + 1);
 30033      if( b1==0xFE && b2==0xFF ){
 30034        bom = SQLITE_UTF16BE;
 30035      }
 30036      if( b1==0xFF && b2==0xFE ){
 30037        bom = SQLITE_UTF16LE;
 30038      }
 30039    }
 30040    
 30041    if( bom ){
 30042      rc = sqlite3VdbeMemMakeWriteable(pMem);
 30043      if( rc==SQLITE_OK ){
 30044        pMem->n -= 2;
 30045        memmove(pMem->z, &pMem->z[2], pMem->n);
 30046        pMem->z[pMem->n] = '\0';
 30047        pMem->z[pMem->n+1] = '\0';
 30048        pMem->flags |= MEM_Term;
 30049        pMem->enc = bom;
 30050      }
 30051    }
 30052    return rc;
 30053  }
 30054  #endif /* SQLITE_OMIT_UTF16 */
 30055  
 30056  /*
 30057  ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
 30058  ** return the number of unicode characters in pZ up to (but not including)
 30059  ** the first 0x00 byte. If nByte is not less than zero, return the
 30060  ** number of unicode characters in the first nByte of pZ (or up to 
 30061  ** the first 0x00, whichever comes first).
 30062  */
 30063  SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
 30064    int r = 0;
 30065    const u8 *z = (const u8*)zIn;
 30066    const u8 *zTerm;
 30067    if( nByte>=0 ){
 30068      zTerm = &z[nByte];
 30069    }else{
 30070      zTerm = (const u8*)(-1);
 30071    }
 30072    assert( z<=zTerm );
 30073    while( *z!=0 && z<zTerm ){
 30074      SQLITE_SKIP_UTF8(z);
 30075      r++;
 30076    }
 30077    return r;
 30078  }
 30079  
 30080  /* This test function is not currently used by the automated test-suite. 
 30081  ** Hence it is only available in debug builds.
 30082  */
 30083  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 30084  /*
 30085  ** Translate UTF-8 to UTF-8.
 30086  **
 30087  ** This has the effect of making sure that the string is well-formed
 30088  ** UTF-8.  Miscoded characters are removed.
 30089  **
 30090  ** The translation is done in-place and aborted if the output
 30091  ** overruns the input.
 30092  */
 30093  SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
 30094    unsigned char *zOut = zIn;
 30095    unsigned char *zStart = zIn;
 30096    u32 c;
 30097  
 30098    while( zIn[0] && zOut<=zIn ){
 30099      c = sqlite3Utf8Read((const u8**)&zIn);
 30100      if( c!=0xfffd ){
 30101        WRITE_UTF8(zOut, c);
 30102      }
 30103    }
 30104    *zOut = 0;
 30105    return (int)(zOut - zStart);
 30106  }
 30107  #endif
 30108  
 30109  #ifndef SQLITE_OMIT_UTF16
 30110  /*
 30111  ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
 30112  ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
 30113  ** be freed by the calling function.
 30114  **
 30115  ** NULL is returned if there is an allocation error.
 30116  */
 30117  SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
 30118    Mem m;
 30119    memset(&m, 0, sizeof(m));
 30120    m.db = db;
 30121    sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
 30122    sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
 30123    if( db->mallocFailed ){
 30124      sqlite3VdbeMemRelease(&m);
 30125      m.z = 0;
 30126    }
 30127    assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
 30128    assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
 30129    assert( m.z || db->mallocFailed );
 30130    return m.z;
 30131  }
 30132  
 30133  /*
 30134  ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
 30135  ** Return the number of bytes in the first nChar unicode characters
 30136  ** in pZ.  nChar must be non-negative.
 30137  */
 30138  SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
 30139    int c;
 30140    unsigned char const *z = zIn;
 30141    int n = 0;
 30142    
 30143    if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
 30144      while( n<nChar ){
 30145        READ_UTF16BE(z, 1, c);
 30146        n++;
 30147      }
 30148    }else{
 30149      while( n<nChar ){
 30150        READ_UTF16LE(z, 1, c);
 30151        n++;
 30152      }
 30153    }
 30154    return (int)(z-(unsigned char const *)zIn);
 30155  }
 30156  
 30157  #if defined(SQLITE_TEST)
 30158  /*
 30159  ** This routine is called from the TCL test function "translate_selftest".
 30160  ** It checks that the primitives for serializing and deserializing
 30161  ** characters in each encoding are inverses of each other.
 30162  */
 30163  SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
 30164    unsigned int i, t;
 30165    unsigned char zBuf[20];
 30166    unsigned char *z;
 30167    int n;
 30168    unsigned int c;
 30169  
 30170    for(i=0; i<0x00110000; i++){
 30171      z = zBuf;
 30172      WRITE_UTF8(z, i);
 30173      n = (int)(z-zBuf);
 30174      assert( n>0 && n<=4 );
 30175      z[0] = 0;
 30176      z = zBuf;
 30177      c = sqlite3Utf8Read((const u8**)&z);
 30178      t = i;
 30179      if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
 30180      if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
 30181      assert( c==t );
 30182      assert( (z-zBuf)==n );
 30183    }
 30184    for(i=0; i<0x00110000; i++){
 30185      if( i>=0xD800 && i<0xE000 ) continue;
 30186      z = zBuf;
 30187      WRITE_UTF16LE(z, i);
 30188      n = (int)(z-zBuf);
 30189      assert( n>0 && n<=4 );
 30190      z[0] = 0;
 30191      z = zBuf;
 30192      READ_UTF16LE(z, 1, c);
 30193      assert( c==i );
 30194      assert( (z-zBuf)==n );
 30195    }
 30196    for(i=0; i<0x00110000; i++){
 30197      if( i>=0xD800 && i<0xE000 ) continue;
 30198      z = zBuf;
 30199      WRITE_UTF16BE(z, i);
 30200      n = (int)(z-zBuf);
 30201      assert( n>0 && n<=4 );
 30202      z[0] = 0;
 30203      z = zBuf;
 30204      READ_UTF16BE(z, 1, c);
 30205      assert( c==i );
 30206      assert( (z-zBuf)==n );
 30207    }
 30208  }
 30209  #endif /* SQLITE_TEST */
 30210  #endif /* SQLITE_OMIT_UTF16 */
 30211  
 30212  /************** End of utf.c *************************************************/
 30213  /************** Begin file util.c ********************************************/
 30214  /*
 30215  ** 2001 September 15
 30216  **
 30217  ** The author disclaims copyright to this source code.  In place of
 30218  ** a legal notice, here is a blessing:
 30219  **
 30220  **    May you do good and not evil.
 30221  **    May you find forgiveness for yourself and forgive others.
 30222  **    May you share freely, never taking more than you give.
 30223  **
 30224  *************************************************************************
 30225  ** Utility functions used throughout sqlite.
 30226  **
 30227  ** This file contains functions for allocating memory, comparing
 30228  ** strings, and stuff like that.
 30229  **
 30230  */
 30231  /* #include "sqliteInt.h" */
 30232  /* #include <stdarg.h> */
 30233  #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
 30234  # include <math.h>
 30235  #endif
 30236  
 30237  /*
 30238  ** Routine needed to support the testcase() macro.
 30239  */
 30240  #ifdef SQLITE_COVERAGE_TEST
 30241  SQLITE_PRIVATE void sqlite3Coverage(int x){
 30242    static unsigned dummy = 0;
 30243    dummy += (unsigned)x;
 30244  }
 30245  #endif
 30246  
 30247  /*
 30248  ** Give a callback to the test harness that can be used to simulate faults
 30249  ** in places where it is difficult or expensive to do so purely by means
 30250  ** of inputs.
 30251  **
 30252  ** The intent of the integer argument is to let the fault simulator know
 30253  ** which of multiple sqlite3FaultSim() calls has been hit.
 30254  **
 30255  ** Return whatever integer value the test callback returns, or return
 30256  ** SQLITE_OK if no test callback is installed.
 30257  */
 30258  #ifndef SQLITE_UNTESTABLE
 30259  SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
 30260    int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
 30261    return xCallback ? xCallback(iTest) : SQLITE_OK;
 30262  }
 30263  #endif
 30264  
 30265  #ifndef SQLITE_OMIT_FLOATING_POINT
 30266  /*
 30267  ** Return true if the floating point value is Not a Number (NaN).
 30268  **
 30269  ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
 30270  ** Otherwise, we have our own implementation that works on most systems.
 30271  */
 30272  SQLITE_PRIVATE int sqlite3IsNaN(double x){
 30273    int rc;   /* The value return */
 30274  #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
 30275    /*
 30276    ** Systems that support the isnan() library function should probably
 30277    ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
 30278    ** found that many systems do not have a working isnan() function so
 30279    ** this implementation is provided as an alternative.
 30280    **
 30281    ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
 30282    ** On the other hand, the use of -ffast-math comes with the following
 30283    ** warning:
 30284    **
 30285    **      This option [-ffast-math] should never be turned on by any
 30286    **      -O option since it can result in incorrect output for programs
 30287    **      which depend on an exact implementation of IEEE or ISO 
 30288    **      rules/specifications for math functions.
 30289    **
 30290    ** Under MSVC, this NaN test may fail if compiled with a floating-
 30291    ** point precision mode other than /fp:precise.  From the MSDN 
 30292    ** documentation:
 30293    **
 30294    **      The compiler [with /fp:precise] will properly handle comparisons 
 30295    **      involving NaN. For example, x != x evaluates to true if x is NaN 
 30296    **      ...
 30297    */
 30298  #ifdef __FAST_MATH__
 30299  # error SQLite will not work correctly with the -ffast-math option of GCC.
 30300  #endif
 30301    volatile double y = x;
 30302    volatile double z = y;
 30303    rc = (y!=z);
 30304  #else  /* if HAVE_ISNAN */
 30305    rc = isnan(x);
 30306  #endif /* HAVE_ISNAN */
 30307    testcase( rc );
 30308    return rc;
 30309  }
 30310  #endif /* SQLITE_OMIT_FLOATING_POINT */
 30311  
 30312  /*
 30313  ** Compute a string length that is limited to what can be stored in
 30314  ** lower 30 bits of a 32-bit signed integer.
 30315  **
 30316  ** The value returned will never be negative.  Nor will it ever be greater
 30317  ** than the actual length of the string.  For very long strings (greater
 30318  ** than 1GiB) the value returned might be less than the true string length.
 30319  */
 30320  SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 30321    if( z==0 ) return 0;
 30322    return 0x3fffffff & (int)strlen(z);
 30323  }
 30324  
 30325  /*
 30326  ** Return the declared type of a column.  Or return zDflt if the column 
 30327  ** has no declared type.
 30328  **
 30329  ** The column type is an extra string stored after the zero-terminator on
 30330  ** the column name if and only if the COLFLAG_HASTYPE flag is set.
 30331  */
 30332  SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
 30333    if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
 30334    return pCol->zName + strlen(pCol->zName) + 1;
 30335  }
 30336  
 30337  /*
 30338  ** Helper function for sqlite3Error() - called rarely.  Broken out into
 30339  ** a separate routine to avoid unnecessary register saves on entry to
 30340  ** sqlite3Error().
 30341  */
 30342  static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
 30343    if( db->pErr ) sqlite3ValueSetNull(db->pErr);
 30344    sqlite3SystemError(db, err_code);
 30345  }
 30346  
 30347  /*
 30348  ** Set the current error code to err_code and clear any prior error message.
 30349  ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
 30350  ** that would be appropriate.
 30351  */
 30352  SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
 30353    assert( db!=0 );
 30354    db->errCode = err_code;
 30355    if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
 30356  }
 30357  
 30358  /*
 30359  ** Load the sqlite3.iSysErrno field if that is an appropriate thing
 30360  ** to do based on the SQLite error code in rc.
 30361  */
 30362  SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
 30363    if( rc==SQLITE_IOERR_NOMEM ) return;
 30364    rc &= 0xff;
 30365    if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
 30366      db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
 30367    }
 30368  }
 30369  
 30370  /*
 30371  ** Set the most recent error code and error string for the sqlite
 30372  ** handle "db". The error code is set to "err_code".
 30373  **
 30374  ** If it is not NULL, string zFormat specifies the format of the
 30375  ** error string in the style of the printf functions: The following
 30376  ** format characters are allowed:
 30377  **
 30378  **      %s      Insert a string
 30379  **      %z      A string that should be freed after use
 30380  **      %d      Insert an integer
 30381  **      %T      Insert a token
 30382  **      %S      Insert the first element of a SrcList
 30383  **
 30384  ** zFormat and any string tokens that follow it are assumed to be
 30385  ** encoded in UTF-8.
 30386  **
 30387  ** To clear the most recent error for sqlite handle "db", sqlite3Error
 30388  ** should be called with err_code set to SQLITE_OK and zFormat set
 30389  ** to NULL.
 30390  */
 30391  SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
 30392    assert( db!=0 );
 30393    db->errCode = err_code;
 30394    sqlite3SystemError(db, err_code);
 30395    if( zFormat==0 ){
 30396      sqlite3Error(db, err_code);
 30397    }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
 30398      char *z;
 30399      va_list ap;
 30400      va_start(ap, zFormat);
 30401      z = sqlite3VMPrintf(db, zFormat, ap);
 30402      va_end(ap);
 30403      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
 30404    }
 30405  }
 30406  
 30407  /*
 30408  ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
 30409  ** The following formatting characters are allowed:
 30410  **
 30411  **      %s      Insert a string
 30412  **      %z      A string that should be freed after use
 30413  **      %d      Insert an integer
 30414  **      %T      Insert a token
 30415  **      %S      Insert the first element of a SrcList
 30416  **
 30417  ** This function should be used to report any error that occurs while
 30418  ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
 30419  ** last thing the sqlite3_prepare() function does is copy the error
 30420  ** stored by this function into the database handle using sqlite3Error().
 30421  ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
 30422  ** during statement execution (sqlite3_step() etc.).
 30423  */
 30424  SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
 30425    char *zMsg;
 30426    va_list ap;
 30427    sqlite3 *db = pParse->db;
 30428    va_start(ap, zFormat);
 30429    zMsg = sqlite3VMPrintf(db, zFormat, ap);
 30430    va_end(ap);
 30431    if( db->suppressErr ){
 30432      sqlite3DbFree(db, zMsg);
 30433    }else{
 30434      pParse->nErr++;
 30435      sqlite3DbFree(db, pParse->zErrMsg);
 30436      pParse->zErrMsg = zMsg;
 30437      pParse->rc = SQLITE_ERROR;
 30438    }
 30439  }
 30440  
 30441  /*
 30442  ** Convert an SQL-style quoted string into a normal string by removing
 30443  ** the quote characters.  The conversion is done in-place.  If the
 30444  ** input does not begin with a quote character, then this routine
 30445  ** is a no-op.
 30446  **
 30447  ** The input string must be zero-terminated.  A new zero-terminator
 30448  ** is added to the dequoted string.
 30449  **
 30450  ** The return value is -1 if no dequoting occurs or the length of the
 30451  ** dequoted string, exclusive of the zero terminator, if dequoting does
 30452  ** occur.
 30453  **
 30454  ** 2002-02-14: This routine is extended to remove MS-Access style
 30455  ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
 30456  ** "a-b-c".
 30457  */
 30458  SQLITE_PRIVATE void sqlite3Dequote(char *z){
 30459    char quote;
 30460    int i, j;
 30461    if( z==0 ) return;
 30462    quote = z[0];
 30463    if( !sqlite3Isquote(quote) ) return;
 30464    if( quote=='[' ) quote = ']';
 30465    for(i=1, j=0;; i++){
 30466      assert( z[i] );
 30467      if( z[i]==quote ){
 30468        if( z[i+1]==quote ){
 30469          z[j++] = quote;
 30470          i++;
 30471        }else{
 30472          break;
 30473        }
 30474      }else{
 30475        z[j++] = z[i];
 30476      }
 30477    }
 30478    z[j] = 0;
 30479  }
 30480  SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
 30481    assert( sqlite3Isquote(p->u.zToken[0]) );
 30482    p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
 30483    sqlite3Dequote(p->u.zToken);
 30484  }
 30485  
 30486  /*
 30487  ** Generate a Token object from a string
 30488  */
 30489  SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
 30490    p->z = z;
 30491    p->n = sqlite3Strlen30(z);
 30492  }
 30493  
 30494  /* Convenient short-hand */
 30495  #define UpperToLower sqlite3UpperToLower
 30496  
 30497  /*
 30498  ** Some systems have stricmp().  Others have strcasecmp().  Because
 30499  ** there is no consistency, we will define our own.
 30500  **
 30501  ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
 30502  ** sqlite3_strnicmp() APIs allow applications and extensions to compare
 30503  ** the contents of two buffers containing UTF-8 strings in a
 30504  ** case-independent fashion, using the same definition of "case
 30505  ** independence" that SQLite uses internally when comparing identifiers.
 30506  */
 30507  SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
 30508    if( zLeft==0 ){
 30509      return zRight ? -1 : 0;
 30510    }else if( zRight==0 ){
 30511      return 1;
 30512    }
 30513    return sqlite3StrICmp(zLeft, zRight);
 30514  }
 30515  SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
 30516    unsigned char *a, *b;
 30517    int c;
 30518    a = (unsigned char *)zLeft;
 30519    b = (unsigned char *)zRight;
 30520    for(;;){
 30521      c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
 30522      if( c || *a==0 ) break;
 30523      a++;
 30524      b++;
 30525    }
 30526    return c;
 30527  }
 30528  SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
 30529    register unsigned char *a, *b;
 30530    if( zLeft==0 ){
 30531      return zRight ? -1 : 0;
 30532    }else if( zRight==0 ){
 30533      return 1;
 30534    }
 30535    a = (unsigned char *)zLeft;
 30536    b = (unsigned char *)zRight;
 30537    while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
 30538    return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
 30539  }
 30540  
 30541  /*
 30542  ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
 30543  ** E==2 results in 100.  E==50 results in 1.0e50.
 30544  **
 30545  ** This routine only works for values of E between 1 and 341.
 30546  */
 30547  static LONGDOUBLE_TYPE sqlite3Pow10(int E){
 30548  #if defined(_MSC_VER)
 30549    static const LONGDOUBLE_TYPE x[] = {
 30550      1.0e+001,
 30551      1.0e+002,
 30552      1.0e+004,
 30553      1.0e+008,
 30554      1.0e+016,
 30555      1.0e+032,
 30556      1.0e+064,
 30557      1.0e+128,
 30558      1.0e+256
 30559    };
 30560    LONGDOUBLE_TYPE r = 1.0;
 30561    int i;
 30562    assert( E>=0 && E<=307 );
 30563    for(i=0; E!=0; i++, E >>=1){
 30564      if( E & 1 ) r *= x[i];
 30565    }
 30566    return r;
 30567  #else
 30568    LONGDOUBLE_TYPE x = 10.0;
 30569    LONGDOUBLE_TYPE r = 1.0;
 30570    while(1){
 30571      if( E & 1 ) r *= x;
 30572      E >>= 1;
 30573      if( E==0 ) break;
 30574      x *= x;
 30575    }
 30576    return r; 
 30577  #endif
 30578  }
 30579  
 30580  /*
 30581  ** The string z[] is an text representation of a real number.
 30582  ** Convert this string to a double and write it into *pResult.
 30583  **
 30584  ** The string z[] is length bytes in length (bytes, not characters) and
 30585  ** uses the encoding enc.  The string is not necessarily zero-terminated.
 30586  **
 30587  ** Return TRUE if the result is a valid real number (or integer) and FALSE
 30588  ** if the string is empty or contains extraneous text.  Valid numbers
 30589  ** are in one of these formats:
 30590  **
 30591  **    [+-]digits[E[+-]digits]
 30592  **    [+-]digits.[digits][E[+-]digits]
 30593  **    [+-].digits[E[+-]digits]
 30594  **
 30595  ** Leading and trailing whitespace is ignored for the purpose of determining
 30596  ** validity.
 30597  **
 30598  ** If some prefix of the input string is a valid number, this routine
 30599  ** returns FALSE but it still converts the prefix and writes the result
 30600  ** into *pResult.
 30601  */
 30602  SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
 30603  #ifndef SQLITE_OMIT_FLOATING_POINT
 30604    int incr;
 30605    const char *zEnd = z + length;
 30606    /* sign * significand * (10 ^ (esign * exponent)) */
 30607    int sign = 1;    /* sign of significand */
 30608    i64 s = 0;       /* significand */
 30609    int d = 0;       /* adjust exponent for shifting decimal point */
 30610    int esign = 1;   /* sign of exponent */
 30611    int e = 0;       /* exponent */
 30612    int eValid = 1;  /* True exponent is either not used or is well-formed */
 30613    double result;
 30614    int nDigits = 0;
 30615    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
 30616  
 30617    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 30618    *pResult = 0.0;   /* Default return value, in case of an error */
 30619  
 30620    if( enc==SQLITE_UTF8 ){
 30621      incr = 1;
 30622    }else{
 30623      int i;
 30624      incr = 2;
 30625      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 30626      for(i=3-enc; i<length && z[i]==0; i+=2){}
 30627      nonNum = i<length;
 30628      zEnd = &z[i^1];
 30629      z += (enc&1);
 30630    }
 30631  
 30632    /* skip leading spaces */
 30633    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 30634    if( z>=zEnd ) return 0;
 30635  
 30636    /* get sign of significand */
 30637    if( *z=='-' ){
 30638      sign = -1;
 30639      z+=incr;
 30640    }else if( *z=='+' ){
 30641      z+=incr;
 30642    }
 30643  
 30644    /* copy max significant digits to significand */
 30645    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
 30646      s = s*10 + (*z - '0');
 30647      z+=incr; nDigits++;
 30648    }
 30649  
 30650    /* skip non-significant significand digits
 30651    ** (increase exponent by d to shift decimal left) */
 30652    while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
 30653    if( z>=zEnd ) goto do_atof_calc;
 30654  
 30655    /* if decimal point is present */
 30656    if( *z=='.' ){
 30657      z+=incr;
 30658      /* copy digits from after decimal to significand
 30659      ** (decrease exponent by d to shift decimal right) */
 30660      while( z<zEnd && sqlite3Isdigit(*z) ){
 30661        if( s<((LARGEST_INT64-9)/10) ){
 30662          s = s*10 + (*z - '0');
 30663          d--;
 30664        }
 30665        z+=incr; nDigits++;
 30666      }
 30667    }
 30668    if( z>=zEnd ) goto do_atof_calc;
 30669  
 30670    /* if exponent is present */
 30671    if( *z=='e' || *z=='E' ){
 30672      z+=incr;
 30673      eValid = 0;
 30674  
 30675      /* This branch is needed to avoid a (harmless) buffer overread.  The 
 30676      ** special comment alerts the mutation tester that the correct answer
 30677      ** is obtained even if the branch is omitted */
 30678      if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
 30679  
 30680      /* get sign of exponent */
 30681      if( *z=='-' ){
 30682        esign = -1;
 30683        z+=incr;
 30684      }else if( *z=='+' ){
 30685        z+=incr;
 30686      }
 30687      /* copy digits to exponent */
 30688      while( z<zEnd && sqlite3Isdigit(*z) ){
 30689        e = e<10000 ? (e*10 + (*z - '0')) : 10000;
 30690        z+=incr;
 30691        eValid = 1;
 30692      }
 30693    }
 30694  
 30695    /* skip trailing spaces */
 30696    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 30697  
 30698  do_atof_calc:
 30699    /* adjust exponent by d, and update sign */
 30700    e = (e*esign) + d;
 30701    if( e<0 ) {
 30702      esign = -1;
 30703      e *= -1;
 30704    } else {
 30705      esign = 1;
 30706    }
 30707  
 30708    if( s==0 ) {
 30709      /* In the IEEE 754 standard, zero is signed. */
 30710      result = sign<0 ? -(double)0 : (double)0;
 30711    } else {
 30712      /* Attempt to reduce exponent.
 30713      **
 30714      ** Branches that are not required for the correct answer but which only
 30715      ** help to obtain the correct answer faster are marked with special
 30716      ** comments, as a hint to the mutation tester.
 30717      */
 30718      while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
 30719        if( esign>0 ){
 30720          if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
 30721          s *= 10;
 30722        }else{
 30723          if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
 30724          s /= 10;
 30725        }
 30726        e--;
 30727      }
 30728  
 30729      /* adjust the sign of significand */
 30730      s = sign<0 ? -s : s;
 30731  
 30732      if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
 30733        result = (double)s;
 30734      }else{
 30735        /* attempt to handle extremely small/large numbers better */
 30736        if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
 30737          if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
 30738            LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
 30739            if( esign<0 ){
 30740              result = s / scale;
 30741              result /= 1.0e+308;
 30742            }else{
 30743              result = s * scale;
 30744              result *= 1.0e+308;
 30745            }
 30746          }else{ assert( e>=342 );
 30747            if( esign<0 ){
 30748              result = 0.0*s;
 30749            }else{
 30750  #ifdef INFINITY
 30751              result = INFINITY*s;
 30752  #else
 30753              result = 1e308*1e308*s;  /* Infinity */
 30754  #endif
 30755            }
 30756          }
 30757        }else{
 30758          LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
 30759          if( esign<0 ){
 30760            result = s / scale;
 30761          }else{
 30762            result = s * scale;
 30763          }
 30764        }
 30765      }
 30766    }
 30767  
 30768    /* store the result */
 30769    *pResult = result;
 30770  
 30771    /* return true if number and no extra non-whitespace chracters after */
 30772    return z==zEnd && nDigits>0 && eValid && nonNum==0;
 30773  #else
 30774    return !sqlite3Atoi64(z, pResult, length, enc);
 30775  #endif /* SQLITE_OMIT_FLOATING_POINT */
 30776  }
 30777  
 30778  /*
 30779  ** Compare the 19-character string zNum against the text representation
 30780  ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
 30781  ** if zNum is less than, equal to, or greater than the string.
 30782  ** Note that zNum must contain exactly 19 characters.
 30783  **
 30784  ** Unlike memcmp() this routine is guaranteed to return the difference
 30785  ** in the values of the last digit if the only difference is in the
 30786  ** last digit.  So, for example,
 30787  **
 30788  **      compare2pow63("9223372036854775800", 1)
 30789  **
 30790  ** will return -8.
 30791  */
 30792  static int compare2pow63(const char *zNum, int incr){
 30793    int c = 0;
 30794    int i;
 30795                      /* 012345678901234567 */
 30796    const char *pow63 = "922337203685477580";
 30797    for(i=0; c==0 && i<18; i++){
 30798      c = (zNum[i*incr]-pow63[i])*10;
 30799    }
 30800    if( c==0 ){
 30801      c = zNum[18*incr] - '8';
 30802      testcase( c==(-1) );
 30803      testcase( c==0 );
 30804      testcase( c==(+1) );
 30805    }
 30806    return c;
 30807  }
 30808  
 30809  static int compare2pow64(const char *zNum, int incr){
 30810    int c = 0;
 30811    int i;
 30812                      /* 01234567890123456789 */
 30813    const char *pow64 = "18446744073709551615";
 30814    for(i=0; c==0 && i<20; i++){
 30815      c = (zNum[i*incr]-pow64[i])*10;
 30816    }
 30817    return c;
 30818  }
 30819  
 30820  /*
 30821  ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
 30822  ** routine does *not* accept hexadecimal notation.
 30823  **
 30824  ** Returns:
 30825  **
 30826  **     0    Successful transformation.  Fits in a 64-bit signed integer.
 30827  **     1    Excess non-space text after the integer value
 30828  **     2    Integer too large for a 64-bit signed integer or is malformed
 30829  **     3    Special case of 9223372036854775808
 30830  **
 30831  ** length is the number of bytes in the string (bytes, not characters).
 30832  ** The string is not necessarily zero-terminated.  The encoding is
 30833  ** given by enc.
 30834  */
 30835  SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
 30836    int incr;
 30837    u64 u = 0;
 30838    int neg = 0; /* assume positive */
 30839    int i;
 30840    int c = 0;
 30841    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
 30842    int rc;          /* Baseline return code */
 30843    const char *zStart;
 30844    const char *zEnd = zNum + length;
 30845    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 30846    if( enc==SQLITE_UTF8 ){
 30847      incr = 1;
 30848    }else{
 30849      incr = 2;
 30850      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 30851      for(i=3-enc; i<length && zNum[i]==0; i+=2){}
 30852      nonNum = i<length;
 30853      zEnd = &zNum[i^1];
 30854      zNum += (enc&1);
 30855    }
 30856    while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
 30857    if( zNum<zEnd ){
 30858      if( *zNum=='-' ){
 30859        neg = 1;
 30860        zNum+=incr;
 30861      }else if( *zNum=='+' ){
 30862        zNum+=incr;
 30863      }
 30864    }
 30865    zStart = zNum;
 30866    while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
 30867    for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
 30868      u = u*10 + c - '0';
 30869    }
 30870    testcase( i==18*incr );
 30871    testcase( i==19*incr );
 30872    testcase( i==20*incr );
 30873    if( u>LARGEST_INT64 ){
 30874      /* This test and assignment is needed only to suppress UB warnings
 30875      ** from clang and -fsanitize=undefined.  This test and assignment make
 30876      ** the code a little larger and slower, and no harm comes from omitting
 30877      ** them, but we must appaise the undefined-behavior pharisees. */
 30878      *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
 30879    }else if( neg ){
 30880      *pNum = -(i64)u;
 30881    }else{
 30882      *pNum = (i64)u;
 30883    }
 30884    rc = 0;
 30885    if( (i==0 && zStart==zNum)     /* No digits */
 30886     || nonNum                     /* UTF16 with high-order bytes non-zero */
 30887    ){
 30888      rc = 1;
 30889    }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
 30890      int jj = i;
 30891      do{
 30892        if( !sqlite3Isspace(zNum[jj]) ){
 30893          rc = 1;          /* Extra non-space text after the integer */
 30894          break;
 30895        }
 30896        jj += incr;
 30897      }while( &zNum[jj]<zEnd );
 30898    }
 30899    if( i<19*incr ){
 30900      /* Less than 19 digits, so we know that it fits in 64 bits */
 30901      assert( u<=LARGEST_INT64 );
 30902      return rc;
 30903    }else{
 30904      /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
 30905      c = i>19*incr ? 1 : compare2pow63(zNum, incr);
 30906      if( c<0 ){
 30907        /* zNum is less than 9223372036854775808 so it fits */
 30908        assert( u<=LARGEST_INT64 );
 30909        return rc;
 30910      }else{
 30911        *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
 30912        if( c>0 ){
 30913          /* zNum is greater than 9223372036854775808 so it overflows */
 30914          return 2;
 30915        }else{
 30916          /* zNum is exactly 9223372036854775808.  Fits if negative.  The
 30917          ** special case 2 overflow if positive */
 30918          assert( u-1==LARGEST_INT64 );
 30919          return neg ? rc : 3;
 30920        }
 30921      }
 30922    }
 30923  }
 30924  
 30925  /*
 30926  ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
 30927  ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
 30928  ** whereas sqlite3Atoi64() does not.
 30929  **
 30930  ** Returns:
 30931  **
 30932  **     0    Successful transformation.  Fits in a 64-bit signed integer.
 30933  **     1    Excess text after the integer value
 30934  **     2    Integer too large for a 64-bit signed integer or is malformed
 30935  **     3    Special case of 9223372036854775808
 30936  */
 30937  SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
 30938  #ifndef SQLITE_OMIT_HEX_INTEGER
 30939    if( z[0]=='0'
 30940     && (z[1]=='x' || z[1]=='X')
 30941    ){
 30942      u64 u = 0;
 30943      int i, k;
 30944      for(i=2; z[i]=='0'; i++){}
 30945      for(k=i; sqlite3Isxdigit(z[k]); k++){
 30946        u = u*16 + sqlite3HexToInt(z[k]);
 30947      }
 30948      memcpy(pOut, &u, 8);
 30949      return (z[k]==0 && k-i<=16) ? 0 : 2;
 30950    }else
 30951  #endif /* SQLITE_OMIT_HEX_INTEGER */
 30952    {
 30953      return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
 30954    }
 30955  }
 30956  
 30957  #ifdef UNUSED_FUNCTION
 30958  SQLITE_PRIVATE u32 sqlite3AtoU32(const char *zNum){
 30959    i64 value;
 30960    int rc = sqlite3Atoi64(zNum, &value, sqlite3Strlen30(zNum), SQLITE_UTF8);
 30961    if( rc || value < 0 || value > 0xffffffffLL ) value = 0;
 30962    return value;
 30963  }
 30964  #endif
 30965  
 30966  SQLITE_PRIVATE int sqlite3AtoU64(const char *zNum, u64 *pNum, int length, u8 enc){
 30967    int incr;
 30968    u64 u = 0;
 30969    int i;
 30970    int c = 0;
 30971    int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
 30972    int rc;          /* Baseline return code */
 30973    const char *zStart;
 30974    const char *zEnd = zNum + length;
 30975    assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
 30976    if( enc==SQLITE_UTF8 ){
 30977      incr = 1;
 30978    }else{
 30979      incr = 2;
 30980      assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
 30981      for(i=3-enc; i<length && zNum[i]==0; i+=2){}
 30982      nonNum = i<length;
 30983      zEnd = &zNum[i^1];
 30984      zNum += (enc&1);
 30985    }
 30986    while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
 30987    if( zNum<zEnd ){
 30988      if( *zNum=='-' ){
 30989        return 1;
 30990      }else if( *zNum=='+' ){
 30991        zNum+=incr;
 30992      }
 30993    }
 30994    zStart = zNum;
 30995    while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
 30996    for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
 30997      u = u*10 + c - '0';
 30998    }
 30999  
 31000    *pNum = u;
 31001    rc = 0;
 31002  
 31003    if( (i==0 && zStart==zNum)     /* No digits */
 31004     || nonNum                     /* UTF16 with high-order bytes non-zero */
 31005    ){
 31006      rc = 1;
 31007    }else if( &zNum[i]<zEnd ){     /* Extra bytes at the end */
 31008      int jj = i;
 31009      do{
 31010        if( !sqlite3Isspace(zNum[jj]) ){
 31011          rc = 1;          /* Extra non-space text after the integer */
 31012          break;
 31013        }
 31014        jj += incr;
 31015      }while( &zNum[jj]<zEnd );
 31016    }
 31017  
 31018    if( i<20*incr ){
 31019      /* Less than 20 digits, so we know that it fits in 64 bits */
 31020      return rc;
 31021    }else{
 31022      /* zNum is a 20-digit number.  Compare it against 18446744073709551615. */
 31023      c = i>20*incr ? 1 : compare2pow64(zNum, incr);
 31024      if( c<=0 ){
 31025        /* zNum is less than or equal to 18446744073709551615 so it fits */
 31026        return rc;
 31027      }else{
 31028        /* zNum is greater than 18446744073709551615 so it overflows */
 31029        return 2;
 31030      }
 31031    }
 31032  
 31033  }
 31034  
 31035  SQLITE_PRIVATE u64 atou64(const char *zNum){
 31036    u64 value;
 31037    int rc = sqlite3AtoU64(zNum, &value, sqlite3Strlen30(zNum), SQLITE_UTF8);
 31038    if( rc ) value = 0;
 31039    return value;
 31040  }
 31041  
 31042  SQLITE_PRIVATE int isnumeric(const char *str){
 31043    int found=0;
 31044    while( *str ){
 31045      if( *str<'0' || *str>'9' ) return 0;
 31046      found = 1;  /* at least 1 digit character */
 31047      str++;
 31048    }
 31049    return found;
 31050  }
 31051  
 31052  /*
 31053  ** If zNum represents an integer that will fit in 32-bits, then set
 31054  ** *pValue to that integer and return true.  Otherwise return false.
 31055  **
 31056  ** This routine accepts both decimal and hexadecimal notation for integers.
 31057  **
 31058  ** Any non-numeric characters that following zNum are ignored.
 31059  ** This is different from sqlite3Atoi64() which requires the
 31060  ** input number to be zero-terminated.
 31061  */
 31062  SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
 31063    sqlite_int64 v = 0;
 31064    int i, c;
 31065    int neg = 0;
 31066    if( zNum[0]=='-' ){
 31067      neg = 1;
 31068      zNum++;
 31069    }else if( zNum[0]=='+' ){
 31070      zNum++;
 31071    }
 31072  #ifndef SQLITE_OMIT_HEX_INTEGER
 31073    else if( zNum[0]=='0'
 31074          && (zNum[1]=='x' || zNum[1]=='X')
 31075          && sqlite3Isxdigit(zNum[2])
 31076    ){
 31077      u32 u = 0;
 31078      zNum += 2;
 31079      while( zNum[0]=='0' ) zNum++;
 31080      for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
 31081        u = u*16 + sqlite3HexToInt(zNum[i]);
 31082      }
 31083      if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
 31084        memcpy(pValue, &u, 4);
 31085        return 1;
 31086      }else{
 31087        return 0;
 31088      }
 31089    }
 31090  #endif
 31091    if( !sqlite3Isdigit(zNum[0]) ) return 0;
 31092    while( zNum[0]=='0' ) zNum++;
 31093    for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
 31094      v = v*10 + c;
 31095    }
 31096  
 31097    /* The longest decimal representation of a 32 bit integer is 10 digits:
 31098    **
 31099    **             1234567890
 31100    **     2^31 -> 2147483648
 31101    */
 31102    testcase( i==10 );
 31103    if( i>10 ){
 31104      return 0;
 31105    }
 31106    testcase( v-neg==2147483647 );
 31107    if( v-neg>2147483647 ){
 31108      return 0;
 31109    }
 31110    if( neg ){
 31111      v = -v;
 31112    }
 31113    *pValue = (int)v;
 31114    return 1;
 31115  }
 31116  
 31117  /*
 31118  ** Return a 32-bit integer value extracted from a string.  If the
 31119  ** string is not an integer, just return 0.
 31120  */
 31121  SQLITE_PRIVATE int sqlite3Atoi(const char *z){
 31122    int x = 0;
 31123    if( z ) sqlite3GetInt32(z, &x);
 31124    return x;
 31125  }
 31126  
 31127  /*
 31128  ** The variable-length integer encoding is as follows:
 31129  **
 31130  ** KEY:
 31131  **         A = 0xxxxxxx    7 bits of data and one flag bit
 31132  **         B = 1xxxxxxx    7 bits of data and one flag bit
 31133  **         C = xxxxxxxx    8 bits of data
 31134  **
 31135  **  7 bits - A
 31136  ** 14 bits - BA
 31137  ** 21 bits - BBA
 31138  ** 28 bits - BBBA
 31139  ** 35 bits - BBBBA
 31140  ** 42 bits - BBBBBA
 31141  ** 49 bits - BBBBBBA
 31142  ** 56 bits - BBBBBBBA
 31143  ** 64 bits - BBBBBBBBC
 31144  */
 31145  
 31146  /*
 31147  ** Write a 64-bit variable-length integer to memory starting at p[0].
 31148  ** The length of data write will be between 1 and 9 bytes.  The number
 31149  ** of bytes written is returned.
 31150  **
 31151  ** A variable-length integer consists of the lower 7 bits of each byte
 31152  ** for all bytes that have the 8th bit set and one byte with the 8th
 31153  ** bit clear.  Except, if we get to the 9th byte, it stores the full
 31154  ** 8 bits and is the last byte.
 31155  */
 31156  static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
 31157    int i, j, n;
 31158    u8 buf[10];
 31159    if( v & (((u64)0xff000000)<<32) ){
 31160      p[8] = (u8)v;
 31161      v >>= 8;
 31162      for(i=7; i>=0; i--){
 31163        p[i] = (u8)((v & 0x7f) | 0x80);
 31164        v >>= 7;
 31165      }
 31166      return 9;
 31167    }    
 31168    n = 0;
 31169    do{
 31170      buf[n++] = (u8)((v & 0x7f) | 0x80);
 31171      v >>= 7;
 31172    }while( v!=0 );
 31173    buf[0] &= 0x7f;
 31174    assert( n<=9 );
 31175    for(i=0, j=n-1; j>=0; j--, i++){
 31176      p[i] = buf[j];
 31177    }
 31178    return n;
 31179  }
 31180  SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
 31181    if( v<=0x7f ){
 31182      p[0] = v&0x7f;
 31183      return 1;
 31184    }
 31185    if( v<=0x3fff ){
 31186      p[0] = ((v>>7)&0x7f)|0x80;
 31187      p[1] = v&0x7f;
 31188      return 2;
 31189    }
 31190    return putVarint64(p,v);
 31191  }
 31192  
 31193  /*
 31194  ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
 31195  ** are defined here rather than simply putting the constant expressions
 31196  ** inline in order to work around bugs in the RVT compiler.
 31197  **
 31198  ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
 31199  **
 31200  ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
 31201  */
 31202  #define SLOT_2_0     0x001fc07f
 31203  #define SLOT_4_2_0   0xf01fc07f
 31204  
 31205  
 31206  /*
 31207  ** Read a 64-bit variable-length integer from memory starting at p[0].
 31208  ** Return the number of bytes read.  The value is stored in *v.
 31209  */
 31210  SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
 31211    u32 a,b,s;
 31212  
 31213    a = *p;
 31214    /* a: p0 (unmasked) */
 31215    if (!(a&0x80))
 31216    {
 31217      *v = a;
 31218      return 1;
 31219    }
 31220  
 31221    p++;
 31222    b = *p;
 31223    /* b: p1 (unmasked) */
 31224    if (!(b&0x80))
 31225    {
 31226      a &= 0x7f;
 31227      a = a<<7;
 31228      a |= b;
 31229      *v = a;
 31230      return 2;
 31231    }
 31232  
 31233    /* Verify that constants are precomputed correctly */
 31234    assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
 31235    assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
 31236  
 31237    p++;
 31238    a = a<<14;
 31239    a |= *p;
 31240    /* a: p0<<14 | p2 (unmasked) */
 31241    if (!(a&0x80))
 31242    {
 31243      a &= SLOT_2_0;
 31244      b &= 0x7f;
 31245      b = b<<7;
 31246      a |= b;
 31247      *v = a;
 31248      return 3;
 31249    }
 31250  
 31251    /* CSE1 from below */
 31252    a &= SLOT_2_0;
 31253    p++;
 31254    b = b<<14;
 31255    b |= *p;
 31256    /* b: p1<<14 | p3 (unmasked) */
 31257    if (!(b&0x80))
 31258    {
 31259      b &= SLOT_2_0;
 31260      /* moved CSE1 up */
 31261      /* a &= (0x7f<<14)|(0x7f); */
 31262      a = a<<7;
 31263      a |= b;
 31264      *v = a;
 31265      return 4;
 31266    }
 31267  
 31268    /* a: p0<<14 | p2 (masked) */
 31269    /* b: p1<<14 | p3 (unmasked) */
 31270    /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 31271    /* moved CSE1 up */
 31272    /* a &= (0x7f<<14)|(0x7f); */
 31273    b &= SLOT_2_0;
 31274    s = a;
 31275    /* s: p0<<14 | p2 (masked) */
 31276  
 31277    p++;
 31278    a = a<<14;
 31279    a |= *p;
 31280    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 31281    if (!(a&0x80))
 31282    {
 31283      /* we can skip these cause they were (effectively) done above
 31284      ** while calculating s */
 31285      /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 31286      /* b &= (0x7f<<14)|(0x7f); */
 31287      b = b<<7;
 31288      a |= b;
 31289      s = s>>18;
 31290      *v = ((u64)s)<<32 | a;
 31291      return 5;
 31292    }
 31293  
 31294    /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 31295    s = s<<7;
 31296    s |= b;
 31297    /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
 31298  
 31299    p++;
 31300    b = b<<14;
 31301    b |= *p;
 31302    /* b: p1<<28 | p3<<14 | p5 (unmasked) */
 31303    if (!(b&0x80))
 31304    {
 31305      /* we can skip this cause it was (effectively) done above in calc'ing s */
 31306      /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
 31307      a &= SLOT_2_0;
 31308      a = a<<7;
 31309      a |= b;
 31310      s = s>>18;
 31311      *v = ((u64)s)<<32 | a;
 31312      return 6;
 31313    }
 31314  
 31315    p++;
 31316    a = a<<14;
 31317    a |= *p;
 31318    /* a: p2<<28 | p4<<14 | p6 (unmasked) */
 31319    if (!(a&0x80))
 31320    {
 31321      a &= SLOT_4_2_0;
 31322      b &= SLOT_2_0;
 31323      b = b<<7;
 31324      a |= b;
 31325      s = s>>11;
 31326      *v = ((u64)s)<<32 | a;
 31327      return 7;
 31328    }
 31329  
 31330    /* CSE2 from below */
 31331    a &= SLOT_2_0;
 31332    p++;
 31333    b = b<<14;
 31334    b |= *p;
 31335    /* b: p3<<28 | p5<<14 | p7 (unmasked) */
 31336    if (!(b&0x80))
 31337    {
 31338      b &= SLOT_4_2_0;
 31339      /* moved CSE2 up */
 31340      /* a &= (0x7f<<14)|(0x7f); */
 31341      a = a<<7;
 31342      a |= b;
 31343      s = s>>4;
 31344      *v = ((u64)s)<<32 | a;
 31345      return 8;
 31346    }
 31347  
 31348    p++;
 31349    a = a<<15;
 31350    a |= *p;
 31351    /* a: p4<<29 | p6<<15 | p8 (unmasked) */
 31352  
 31353    /* moved CSE2 up */
 31354    /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
 31355    b &= SLOT_2_0;
 31356    b = b<<8;
 31357    a |= b;
 31358  
 31359    s = s<<4;
 31360    b = p[-4];
 31361    b &= 0x7f;
 31362    b = b>>3;
 31363    s |= b;
 31364  
 31365    *v = ((u64)s)<<32 | a;
 31366  
 31367    return 9;
 31368  }
 31369  
 31370  /*
 31371  ** Read a 32-bit variable-length integer from memory starting at p[0].
 31372  ** Return the number of bytes read.  The value is stored in *v.
 31373  **
 31374  ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
 31375  ** integer, then set *v to 0xffffffff.
 31376  **
 31377  ** A MACRO version, getVarint32, is provided which inlines the 
 31378  ** single-byte case.  All code should use the MACRO version as 
 31379  ** this function assumes the single-byte case has already been handled.
 31380  */
 31381  SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
 31382    u32 a,b;
 31383  
 31384    /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
 31385    ** by the getVarin32() macro */
 31386    a = *p;
 31387    /* a: p0 (unmasked) */
 31388  #ifndef getVarint32
 31389    if (!(a&0x80))
 31390    {
 31391      /* Values between 0 and 127 */
 31392      *v = a;
 31393      return 1;
 31394    }
 31395  #endif
 31396  
 31397    /* The 2-byte case */
 31398    p++;
 31399    b = *p;
 31400    /* b: p1 (unmasked) */
 31401    if (!(b&0x80))
 31402    {
 31403      /* Values between 128 and 16383 */
 31404      a &= 0x7f;
 31405      a = a<<7;
 31406      *v = a | b;
 31407      return 2;
 31408    }
 31409  
 31410    /* The 3-byte case */
 31411    p++;
 31412    a = a<<14;
 31413    a |= *p;
 31414    /* a: p0<<14 | p2 (unmasked) */
 31415    if (!(a&0x80))
 31416    {
 31417      /* Values between 16384 and 2097151 */
 31418      a &= (0x7f<<14)|(0x7f);
 31419      b &= 0x7f;
 31420      b = b<<7;
 31421      *v = a | b;
 31422      return 3;
 31423    }
 31424  
 31425    /* A 32-bit varint is used to store size information in btrees.
 31426    ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
 31427    ** A 3-byte varint is sufficient, for example, to record the size
 31428    ** of a 1048569-byte BLOB or string.
 31429    **
 31430    ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
 31431    ** rare larger cases can be handled by the slower 64-bit varint
 31432    ** routine.
 31433    */
 31434  #if 1
 31435    {
 31436      u64 v64;
 31437      u8 n;
 31438  
 31439      p -= 2;
 31440      n = sqlite3GetVarint(p, &v64);
 31441      assert( n>3 && n<=9 );
 31442      if( (v64 & SQLITE_MAX_U32)!=v64 ){
 31443        *v = 0xffffffff;
 31444      }else{
 31445        *v = (u32)v64;
 31446      }
 31447      return n;
 31448    }
 31449  
 31450  #else
 31451    /* For following code (kept for historical record only) shows an
 31452    ** unrolling for the 3- and 4-byte varint cases.  This code is
 31453    ** slightly faster, but it is also larger and much harder to test.
 31454    */
 31455    p++;
 31456    b = b<<14;
 31457    b |= *p;
 31458    /* b: p1<<14 | p3 (unmasked) */
 31459    if (!(b&0x80))
 31460    {
 31461      /* Values between 2097152 and 268435455 */
 31462      b &= (0x7f<<14)|(0x7f);
 31463      a &= (0x7f<<14)|(0x7f);
 31464      a = a<<7;
 31465      *v = a | b;
 31466      return 4;
 31467    }
 31468  
 31469    p++;
 31470    a = a<<14;
 31471    a |= *p;
 31472    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
 31473    if (!(a&0x80))
 31474    {
 31475      /* Values  between 268435456 and 34359738367 */
 31476      a &= SLOT_4_2_0;
 31477      b &= SLOT_4_2_0;
 31478      b = b<<7;
 31479      *v = a | b;
 31480      return 5;
 31481    }
 31482  
 31483    /* We can only reach this point when reading a corrupt database
 31484    ** file.  In that case we are not in any hurry.  Use the (relatively
 31485    ** slow) general-purpose sqlite3GetVarint() routine to extract the
 31486    ** value. */
 31487    {
 31488      u64 v64;
 31489      u8 n;
 31490  
 31491      p -= 4;
 31492      n = sqlite3GetVarint(p, &v64);
 31493      assert( n>5 && n<=9 );
 31494      *v = (u32)v64;
 31495      return n;
 31496    }
 31497  #endif
 31498  }
 31499  
 31500  /*
 31501  ** Return the number of bytes that will be needed to store the given
 31502  ** 64-bit integer.
 31503  */
 31504  SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
 31505    int i;
 31506    for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
 31507    return i;
 31508  }
 31509  
 31510  /*
 31511  ** Decode the varint in the first n bytes z[].  Write the integer value
 31512  ** into *pResult and return the number of bytes in the varint.
 31513  **
 31514  ** If the decode fails because there are not enough bytes in z[] then
 31515  ** return 0;
 31516  */
 31517  SQLITE_PRIVATE int sqlite4GetVarint64(
 31518    const unsigned char *z,
 31519    int n,
 31520    u64 *pResult
 31521  ){
 31522    unsigned int x;
 31523    if( n<1 ) return 0;
 31524    if( z[0]<=240 ){
 31525      *pResult = z[0];
 31526      return 1;
 31527    }
 31528    if( z[0]<=248 ){
 31529      if( n<2 ) return 0;
 31530      *pResult = (z[0]-241)*256 + z[1] + 240;
 31531      return 2;
 31532    }
 31533    if( n<z[0]-246 ) return 0;
 31534    if( z[0]==249 ){
 31535      *pResult = 2288 + 256*z[1] + z[2];
 31536      return 3;
 31537    }
 31538    if( z[0]==250 ){
 31539      *pResult = (z[1]<<16) + (z[2]<<8) + z[3];
 31540      return 4;
 31541    }
 31542    x = (z[1]<<24) + (z[2]<<16) + (z[3]<<8) + z[4];
 31543    if( z[0]==251 ){
 31544      *pResult = x;
 31545      return 5;
 31546    }
 31547    if( z[0]==252 ){
 31548      *pResult = (((u64)x)<<8) + z[5];
 31549      return 6;
 31550    }
 31551    if( z[0]==253 ){
 31552      *pResult = (((u64)x)<<16) + (z[5]<<8) + z[6];
 31553      return 7;
 31554    }
 31555    if( z[0]==254 ){
 31556      *pResult = (((u64)x)<<24) + (z[5]<<16) + (z[6]<<8) + z[7];
 31557      return 8;
 31558    }
 31559    *pResult = (((u64)x)<<32) +
 31560                 (0xffffffff & ((z[5]<<24) + (z[6]<<16) + (z[7]<<8) + z[8]));
 31561    return 9;
 31562  }
 31563  
 31564  /*
 31565  ** Write a 32-bit unsigned integer as 4 big-endian bytes.
 31566  */
 31567  static void varintWrite32(unsigned char *z, unsigned int y){
 31568    z[0] = (unsigned char)(y>>24);
 31569    z[1] = (unsigned char)(y>>16);
 31570    z[2] = (unsigned char)(y>>8);
 31571    z[3] = (unsigned char)(y);
 31572  }
 31573  
 31574  /*
 31575  ** Write a varint into z[].  The buffer z[] must be at least 9 characters
 31576  ** long to accommodate the largest possible varint.  Return the number of
 31577  ** bytes of z[] used.
 31578  */
 31579  SQLITE_PRIVATE int sqlite4PutVarint64(unsigned char *z, u64 x){
 31580    unsigned int w, y;
 31581    if( x<=240 ){
 31582      z[0] = (unsigned char)x;
 31583      return 1;
 31584    }
 31585    if( x<=2287 ){
 31586      y = (unsigned int)(x - 240);
 31587      z[0] = (unsigned char)(y/256 + 241);
 31588      z[1] = (unsigned char)(y%256);
 31589      return 2;
 31590    }
 31591    if( x<=67823 ){
 31592      y = (unsigned int)(x - 2288);
 31593      z[0] = 249;
 31594      z[1] = (unsigned char)(y/256);
 31595      z[2] = (unsigned char)(y%256);
 31596      return 3;
 31597    }
 31598    y = (unsigned int)x;
 31599    w = (unsigned int)(x>>32);
 31600    if( w==0 ){
 31601      if( y<=16777215 ){
 31602        z[0] = 250;
 31603        z[1] = (unsigned char)(y>>16);
 31604        z[2] = (unsigned char)(y>>8);
 31605        z[3] = (unsigned char)(y);
 31606        return 4;
 31607      }
 31608      z[0] = 251;
 31609      varintWrite32(z+1, y);
 31610      return 5;
 31611    }
 31612    if( w<=255 ){
 31613      z[0] = 252;
 31614      z[1] = (unsigned char)w;
 31615      varintWrite32(z+2, y);
 31616      return 6;
 31617    }
 31618    if( w<=65535 ){
 31619      z[0] = 253;
 31620      z[1] = (unsigned char)(w>>8);
 31621      z[2] = (unsigned char)w;
 31622      varintWrite32(z+3, y);
 31623      return 7;
 31624    }
 31625    if( w<=16777215 ){
 31626      z[0] = 254;
 31627      z[1] = (unsigned char)(w>>16);
 31628      z[2] = (unsigned char)(w>>8);
 31629      z[3] = (unsigned char)w;
 31630      varintWrite32(z+4, y);
 31631      return 8;
 31632    }
 31633    z[0] = 255;
 31634    varintWrite32(z+1, w);
 31635    varintWrite32(z+5, y);
 31636    return 9;
 31637  }
 31638  
 31639  #ifdef UNUSED_FUNCTION
 31640  /*
 31641  ** Return the number of bytes required to encode value v as a varint.
 31642  */
 31643  SQLITE_PRIVATE int sqlite4VarintLen(u64 v){
 31644    unsigned char aDummy[9];
 31645    return sqlite4PutVarint64(aDummy, v);
 31646  }
 31647  #endif
 31648  
 31649  /*
 31650  ** Read a varint from buffer z and set *pResult to the value read.
 31651  ** Return the number of bytes read from the buffer.
 31652  */
 31653  SQLITE_PRIVATE int sqlite4GetVarint32(const unsigned char *z, int n, u32 *pResult){
 31654    u64 value;
 31655    int ret = sqlite4GetVarint64(z, n, &value);
 31656    if( ret>0 ){
 31657      if( value > UINT32_MAX ){  // 0xffffffffLL
 31658        ret = -1;
 31659      } else {
 31660        *pResult = value;
 31661      }
 31662    }
 31663    return ret;
 31664  }
 31665  
 31666  #ifdef UNUSED_FUNCTION
 31667  /*
 31668  ** Encode v as a varint and write the result to buffer p. Return the
 31669  ** number of bytes written.
 31670  */
 31671  SQLITE_PRIVATE int sqlite4PutVarint32(unsigned char *p, u32 v){
 31672    return sqlite4PutVarint64(p, v);
 31673  }
 31674  #endif
 31675  
 31676  /*
 31677  ** Read or write a four-byte big-endian integer value.
 31678  */
 31679  SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
 31680  #if SQLITE_BYTEORDER==4321
 31681    u32 x;
 31682    memcpy(&x,p,4);
 31683    return x;
 31684  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
 31685    u32 x;
 31686    memcpy(&x,p,4);
 31687    return __builtin_bswap32(x);
 31688  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 31689    u32 x;
 31690    memcpy(&x,p,4);
 31691    return _byteswap_ulong(x);
 31692  #else
 31693    testcase( p[0]&0x80 );
 31694    return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
 31695  #endif
 31696  }
 31697  SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
 31698  #if SQLITE_BYTEORDER==4321
 31699    memcpy(p,&v,4);
 31700  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
 31701    u32 x = __builtin_bswap32(v);
 31702    memcpy(p,&x,4);
 31703  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 31704    u32 x = _byteswap_ulong(v);
 31705    memcpy(p,&x,4);
 31706  #else
 31707    p[0] = (u8)(v>>24);
 31708    p[1] = (u8)(v>>16);
 31709    p[2] = (u8)(v>>8);
 31710    p[3] = (u8)v;
 31711  #endif
 31712  }
 31713  
 31714  
 31715  
 31716  /*
 31717  ** Translate a single byte of Hex into an integer.
 31718  ** This routine only works if h really is a valid hexadecimal
 31719  ** character:  0..9a..fA..F
 31720  */
 31721  SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
 31722    assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
 31723  #ifdef SQLITE_ASCII
 31724    h += 9*(1&(h>>6));
 31725  #endif
 31726  #ifdef SQLITE_EBCDIC
 31727    h += 9*(1&~(h>>4));
 31728  #endif
 31729    return (u8)(h & 0xf);
 31730  }
 31731  
 31732  #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
 31733  /*
 31734  ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
 31735  ** value.  Return a pointer to its binary value.  Space to hold the
 31736  ** binary value has been obtained from malloc and must be freed by
 31737  ** the calling routine.
 31738  */
 31739  SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
 31740    char *zBlob;
 31741    int i;
 31742  
 31743    zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
 31744    n--;
 31745    if( zBlob ){
 31746      for(i=0; i<n; i+=2){
 31747        zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
 31748      }
 31749      zBlob[i/2] = 0;
 31750    }
 31751    return zBlob;
 31752  }
 31753  #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
 31754  
 31755  /*
 31756  ** Log an error that is an API call on a connection pointer that should
 31757  ** not have been used.  The "type" of connection pointer is given as the
 31758  ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
 31759  */
 31760  static void logBadConnection(const char *zType){
 31761    sqlite3_log(SQLITE_MISUSE, 
 31762       "API call with %s database connection pointer",
 31763       zType
 31764    );
 31765  }
 31766  
 31767  /*
 31768  ** Check to make sure we have a valid db pointer.  This test is not
 31769  ** foolproof but it does provide some measure of protection against
 31770  ** misuse of the interface such as passing in db pointers that are
 31771  ** NULL or which have been previously closed.  If this routine returns
 31772  ** 1 it means that the db pointer is valid and 0 if it should not be
 31773  ** dereferenced for any reason.  The calling function should invoke
 31774  ** SQLITE_MISUSE immediately.
 31775  **
 31776  ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
 31777  ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
 31778  ** open properly and is not fit for general use but which can be
 31779  ** used as an argument to sqlite3_errmsg() or sqlite3_close().
 31780  */
 31781  SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
 31782    u32 magic;
 31783    if( db==0 ){
 31784      logBadConnection("NULL");
 31785      return 0;
 31786    }
 31787    magic = db->magic;
 31788    if( magic!=SQLITE_MAGIC_OPEN ){
 31789      if( sqlite3SafetyCheckSickOrOk(db) ){
 31790        testcase( sqlite3GlobalConfig.xLog!=0 );
 31791        logBadConnection("unopened");
 31792      }
 31793      return 0;
 31794    }else{
 31795      return 1;
 31796    }
 31797  }
 31798  SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
 31799    u32 magic;
 31800    magic = db->magic;
 31801    if( magic!=SQLITE_MAGIC_SICK &&
 31802        magic!=SQLITE_MAGIC_OPEN &&
 31803        magic!=SQLITE_MAGIC_BUSY ){
 31804      testcase( sqlite3GlobalConfig.xLog!=0 );
 31805      logBadConnection("invalid");
 31806      return 0;
 31807    }else{
 31808      return 1;
 31809    }
 31810  }
 31811  
 31812  /*
 31813  ** Attempt to add, substract, or multiply the 64-bit signed value iB against
 31814  ** the other 64-bit signed integer at *pA and store the result in *pA.
 31815  ** Return 0 on success.  Or if the operation would have resulted in an
 31816  ** overflow, leave *pA unchanged and return 1.
 31817  */
 31818  SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
 31819  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 31820    return __builtin_add_overflow(*pA, iB, pA);
 31821  #else
 31822    i64 iA = *pA;
 31823    testcase( iA==0 ); testcase( iA==1 );
 31824    testcase( iB==-1 ); testcase( iB==0 );
 31825    if( iB>=0 ){
 31826      testcase( iA>0 && LARGEST_INT64 - iA == iB );
 31827      testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
 31828      if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
 31829    }else{
 31830      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
 31831      testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
 31832      if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
 31833    }
 31834    *pA += iB;
 31835    return 0; 
 31836  #endif
 31837  }
 31838  SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
 31839  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 31840    return __builtin_sub_overflow(*pA, iB, pA);
 31841  #else
 31842    testcase( iB==SMALLEST_INT64+1 );
 31843    if( iB==SMALLEST_INT64 ){
 31844      testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
 31845      if( (*pA)>=0 ) return 1;
 31846      *pA -= iB;
 31847      return 0;
 31848    }else{
 31849      return sqlite3AddInt64(pA, -iB);
 31850    }
 31851  #endif
 31852  }
 31853  SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
 31854  #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
 31855    return __builtin_mul_overflow(*pA, iB, pA);
 31856  #else
 31857    i64 iA = *pA;
 31858    if( iB>0 ){
 31859      if( iA>LARGEST_INT64/iB ) return 1;
 31860      if( iA<SMALLEST_INT64/iB ) return 1;
 31861    }else if( iB<0 ){
 31862      if( iA>0 ){
 31863        if( iB<SMALLEST_INT64/iA ) return 1;
 31864      }else if( iA<0 ){
 31865        if( iB==SMALLEST_INT64 ) return 1;
 31866        if( iA==SMALLEST_INT64 ) return 1;
 31867        if( -iA>LARGEST_INT64/-iB ) return 1;
 31868      }
 31869    }
 31870    *pA = iA*iB;
 31871    return 0;
 31872  #endif
 31873  }
 31874  
 31875  /*
 31876  ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
 31877  ** if the integer has a value of -2147483648, return +2147483647
 31878  */
 31879  SQLITE_PRIVATE int sqlite3AbsInt32(int x){
 31880    if( x>=0 ) return x;
 31881    if( x==(int)0x80000000 ) return 0x7fffffff;
 31882    return -x;
 31883  }
 31884  
 31885  #ifdef SQLITE_ENABLE_8_3_NAMES
 31886  /*
 31887  ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
 31888  ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
 31889  ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
 31890  ** three characters, then shorten the suffix on z[] to be the last three
 31891  ** characters of the original suffix.
 31892  **
 31893  ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
 31894  ** do the suffix shortening regardless of URI parameter.
 31895  **
 31896  ** Examples:
 31897  **
 31898  **     test.db-journal    =>   test.nal
 31899  **     test.db-wal        =>   test.wal
 31900  **     test.db-shm        =>   test.shm
 31901  **     test.db-mj7f3319fa =>   test.9fa
 31902  */
 31903  SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
 31904  #if SQLITE_ENABLE_8_3_NAMES<2
 31905    if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
 31906  #endif
 31907    {
 31908      int i, sz;
 31909      sz = sqlite3Strlen30(z);
 31910      for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
 31911      if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
 31912    }
 31913  }
 31914  #endif
 31915  
 31916  /* 
 31917  ** Find (an approximate) sum of two LogEst values.  This computation is
 31918  ** not a simple "+" operator because LogEst is stored as a logarithmic
 31919  ** value.
 31920  ** 
 31921  */
 31922  SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
 31923    static const unsigned char x[] = {
 31924       10, 10,                         /* 0,1 */
 31925        9, 9,                          /* 2,3 */
 31926        8, 8,                          /* 4,5 */
 31927        7, 7, 7,                       /* 6,7,8 */
 31928        6, 6, 6,                       /* 9,10,11 */
 31929        5, 5, 5,                       /* 12-14 */
 31930        4, 4, 4, 4,                    /* 15-18 */
 31931        3, 3, 3, 3, 3, 3,              /* 19-24 */
 31932        2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
 31933    };
 31934    if( a>=b ){
 31935      if( a>b+49 ) return a;
 31936      if( a>b+31 ) return a+1;
 31937      return a+x[a-b];
 31938    }else{
 31939      if( b>a+49 ) return b;
 31940      if( b>a+31 ) return b+1;
 31941      return b+x[b-a];
 31942    }
 31943  }
 31944  
 31945  /*
 31946  ** Convert an integer into a LogEst.  In other words, compute an
 31947  ** approximation for 10*log2(x).
 31948  */
 31949  SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
 31950    static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
 31951    LogEst y = 40;
 31952    if( x<8 ){
 31953      if( x<2 ) return 0;
 31954      while( x<8 ){  y -= 10; x <<= 1; }
 31955    }else{
 31956  #if GCC_VERSION>=5004000
 31957      int i = 60 - __builtin_clzll(x);
 31958      y += i*10;
 31959      x >>= i;
 31960  #else
 31961      while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
 31962      while( x>15 ){  y += 10; x >>= 1; }
 31963  #endif
 31964    }
 31965    return a[x&7] + y - 10;
 31966  }
 31967  
 31968  #ifndef SQLITE_OMIT_VIRTUALTABLE
 31969  /*
 31970  ** Convert a double into a LogEst
 31971  ** In other words, compute an approximation for 10*log2(x).
 31972  */
 31973  SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
 31974    u64 a;
 31975    LogEst e;
 31976    assert( sizeof(x)==8 && sizeof(a)==8 );
 31977    if( x<=1 ) return 0;
 31978    if( x<=2000000000 ) return sqlite3LogEst((u64)x);
 31979    memcpy(&a, &x, 8);
 31980    e = (a>>52) - 1022;
 31981    return e*10;
 31982  }
 31983  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 31984  
 31985  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 31986      defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
 31987      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 31988  /*
 31989  ** Convert a LogEst into an integer.
 31990  **
 31991  ** Note that this routine is only used when one or more of various
 31992  ** non-standard compile-time options is enabled.
 31993  */
 31994  SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 31995    u64 n;
 31996    n = x%10;
 31997    x /= 10;
 31998    if( n>=5 ) n -= 2;
 31999    else if( n>=1 ) n -= 1;
 32000  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
 32001      defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
 32002    if( x>60 ) return (u64)LARGEST_INT64;
 32003  #else
 32004    /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
 32005    ** possible to this routine is 310, resulting in a maximum x of 31 */
 32006    assert( x<=60 );
 32007  #endif
 32008    return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
 32009  }
 32010  #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
 32011  
 32012  /*
 32013  ** Add a new name/number pair to a VList.  This might require that the
 32014  ** VList object be reallocated, so return the new VList.  If an OOM
 32015  ** error occurs, the original VList returned and the
 32016  ** db->mallocFailed flag is set.
 32017  **
 32018  ** A VList is really just an array of integers.  To destroy a VList,
 32019  ** simply pass it to sqlite3DbFree().
 32020  **
 32021  ** The first integer is the number of integers allocated for the whole
 32022  ** VList.  The second integer is the number of integers actually used.
 32023  ** Each name/number pair is encoded by subsequent groups of 3 or more
 32024  ** integers.
 32025  **
 32026  ** Each name/number pair starts with two integers which are the numeric
 32027  ** value for the pair and the size of the name/number pair, respectively.
 32028  ** The text name overlays one or more following integers.  The text name
 32029  ** is always zero-terminated.
 32030  **
 32031  ** Conceptually:
 32032  **
 32033  **    struct VList {
 32034  **      int nAlloc;   // Number of allocated slots 
 32035  **      int nUsed;    // Number of used slots 
 32036  **      struct VListEntry {
 32037  **        int iValue;    // Value for this entry
 32038  **        int nSlot;     // Slots used by this entry
 32039  **        // ... variable name goes here
 32040  **      } a[0];
 32041  **    }
 32042  **
 32043  ** During code generation, pointers to the variable names within the
 32044  ** VList are taken.  When that happens, nAlloc is set to zero as an 
 32045  ** indication that the VList may never again be enlarged, since the
 32046  ** accompanying realloc() would invalidate the pointers.
 32047  */
 32048  SQLITE_PRIVATE VList *sqlite3VListAdd(
 32049    sqlite3 *db,           /* The database connection used for malloc() */
 32050    VList *pIn,            /* The input VList.  Might be NULL */
 32051    const char *zName,     /* Name of symbol to add */
 32052    int nName,             /* Bytes of text in zName */
 32053    int iVal               /* Value to associate with zName */
 32054  ){
 32055    int nInt;              /* number of sizeof(int) objects needed for zName */
 32056    char *z;               /* Pointer to where zName will be stored */
 32057    int i;                 /* Index in pIn[] where zName is stored */
 32058  
 32059    nInt = nName/4 + 3;
 32060    assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
 32061    if( pIn==0 || pIn[1]+nInt > pIn[0] ){
 32062      /* Enlarge the allocation */
 32063      int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
 32064      VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
 32065      if( pOut==0 ) return pIn;
 32066      if( pIn==0 ) pOut[1] = 2;
 32067      pIn = pOut;
 32068      pIn[0] = nAlloc;
 32069    }
 32070    i = pIn[1];
 32071    pIn[i] = iVal;
 32072    pIn[i+1] = nInt;
 32073    z = (char*)&pIn[i+2];
 32074    pIn[1] = i+nInt;
 32075    assert( pIn[1]<=pIn[0] );
 32076    memcpy(z, zName, nName);
 32077    z[nName] = 0;
 32078    return pIn;
 32079  }
 32080  
 32081  /*
 32082  ** Return a pointer to the name of a variable in the given VList that
 32083  ** has the value iVal.  Or return a NULL if there is no such variable in
 32084  ** the list
 32085  */
 32086  SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
 32087    int i, mx;
 32088    if( pIn==0 ) return 0;
 32089    mx = pIn[1];
 32090    i = 2;
 32091    do{
 32092      if( pIn[i]==iVal ) return (char*)&pIn[i+2];
 32093      i += pIn[i+1];
 32094    }while( i<mx );
 32095    return 0;
 32096  }
 32097  
 32098  /*
 32099  ** Return the number of the variable named zName, if it is in VList.
 32100  ** or return 0 if there is no such variable.
 32101  */
 32102  SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
 32103    int i, mx;
 32104    if( pIn==0 ) return 0;
 32105    mx = pIn[1];
 32106    i = 2;
 32107    do{
 32108      const char *z = (const char*)&pIn[i+2];
 32109      if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
 32110      i += pIn[i+1];
 32111    }while( i<mx );
 32112    return 0;
 32113  }
 32114  
 32115  /************** End of util.c ************************************************/
 32116  /************** Begin file hash.c ********************************************/
 32117  /*
 32118  ** 2001 September 22
 32119  **
 32120  ** The author disclaims copyright to this source code.  In place of
 32121  ** a legal notice, here is a blessing:
 32122  **
 32123  **    May you do good and not evil.
 32124  **    May you find forgiveness for yourself and forgive others.
 32125  **    May you share freely, never taking more than you give.
 32126  **
 32127  *************************************************************************
 32128  ** This is the implementation of generic hash-tables
 32129  ** used in SQLite.
 32130  */
 32131  /* #include "sqliteInt.h" */
 32132  /* #include <assert.h> */
 32133  
 32134  /* Turn bulk memory into a hash table object by initializing the
 32135  ** fields of the Hash structure.
 32136  **
 32137  ** "pNew" is a pointer to the hash table that is to be initialized.
 32138  */
 32139  SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
 32140    assert( pNew!=0 );
 32141    pNew->first = 0;
 32142    pNew->count = 0;
 32143    pNew->htsize = 0;
 32144    pNew->ht = 0;
 32145  }
 32146  
 32147  /* Remove all entries from a hash table.  Reclaim all memory.
 32148  ** Call this routine to delete a hash table or to reset a hash table
 32149  ** to the empty state.
 32150  */
 32151  SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
 32152    HashElem *elem;         /* For looping over all elements of the table */
 32153  
 32154    assert( pH!=0 );
 32155    elem = pH->first;
 32156    pH->first = 0;
 32157    sqlite3_free(pH->ht);
 32158    pH->ht = 0;
 32159    pH->htsize = 0;
 32160    while( elem ){
 32161      HashElem *next_elem = elem->next;
 32162      sqlite3_free(elem);
 32163      elem = next_elem;
 32164    }
 32165    pH->count = 0;
 32166  }
 32167  
 32168  /*
 32169  ** The hashing function.
 32170  */
 32171  static unsigned int strHash(const char *z){
 32172    unsigned int h = 0;
 32173    unsigned char c;
 32174    while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
 32175      /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
 32176      ** 0x9e3779b1 is 2654435761 which is the closest prime number to
 32177      ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
 32178      h += sqlite3UpperToLower[c];
 32179      h *= 0x9e3779b1;
 32180    }
 32181    return h;
 32182  }
 32183  
 32184  
 32185  /* Link pNew element into the hash table pH.  If pEntry!=0 then also
 32186  ** insert pNew into the pEntry hash bucket.
 32187  */
 32188  static void insertElement(
 32189    Hash *pH,              /* The complete hash table */
 32190    struct _ht *pEntry,    /* The entry into which pNew is inserted */
 32191    HashElem *pNew         /* The element to be inserted */
 32192  ){
 32193    HashElem *pHead;       /* First element already in pEntry */
 32194    if( pEntry ){
 32195      pHead = pEntry->count ? pEntry->chain : 0;
 32196      pEntry->count++;
 32197      pEntry->chain = pNew;
 32198    }else{
 32199      pHead = 0;
 32200    }
 32201    if( pHead ){
 32202      pNew->next = pHead;
 32203      pNew->prev = pHead->prev;
 32204      if( pHead->prev ){ pHead->prev->next = pNew; }
 32205      else             { pH->first = pNew; }
 32206      pHead->prev = pNew;
 32207    }else{
 32208      pNew->next = pH->first;
 32209      if( pH->first ){ pH->first->prev = pNew; }
 32210      pNew->prev = 0;
 32211      pH->first = pNew;
 32212    }
 32213  }
 32214  
 32215  
 32216  /* Resize the hash table so that it cantains "new_size" buckets.
 32217  **
 32218  ** The hash table might fail to resize if sqlite3_malloc() fails or
 32219  ** if the new size is the same as the prior size.
 32220  ** Return TRUE if the resize occurs and false if not.
 32221  */
 32222  static int rehash(Hash *pH, unsigned int new_size){
 32223    struct _ht *new_ht;            /* The new hash table */
 32224    HashElem *elem, *next_elem;    /* For looping over existing elements */
 32225  
 32226  #if SQLITE_MALLOC_SOFT_LIMIT>0
 32227    if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
 32228      new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
 32229    }
 32230    if( new_size==pH->htsize ) return 0;
 32231  #endif
 32232  
 32233    /* The inability to allocates space for a larger hash table is
 32234    ** a performance hit but it is not a fatal error.  So mark the
 32235    ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
 32236    ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
 32237    ** only zeroes the requested number of bytes whereas this module will
 32238    ** use the actual amount of space allocated for the hash table (which
 32239    ** may be larger than the requested amount).
 32240    */
 32241    sqlite3BeginBenignMalloc();
 32242    new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
 32243    sqlite3EndBenignMalloc();
 32244  
 32245    if( new_ht==0 ) return 0;
 32246    sqlite3_free(pH->ht);
 32247    pH->ht = new_ht;
 32248    pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
 32249    memset(new_ht, 0, new_size*sizeof(struct _ht));
 32250    for(elem=pH->first, pH->first=0; elem; elem = next_elem){
 32251      unsigned int h = strHash(elem->pKey) % new_size;
 32252      next_elem = elem->next;
 32253      insertElement(pH, &new_ht[h], elem);
 32254    }
 32255    return 1;
 32256  }
 32257  
 32258  /* This function (for internal use only) locates an element in an
 32259  ** hash table that matches the given key.  If no element is found,
 32260  ** a pointer to a static null element with HashElem.data==0 is returned.
 32261  ** If pH is not NULL, then the hash for this key is written to *pH.
 32262  */
 32263  static HashElem *findElementWithHash(
 32264    const Hash *pH,     /* The pH to be searched */
 32265    const char *pKey,   /* The key we are searching for */
 32266    unsigned int *pHash /* Write the hash value here */
 32267  ){
 32268    HashElem *elem;                /* Used to loop thru the element list */
 32269    int count;                     /* Number of elements left to test */
 32270    unsigned int h;                /* The computed hash */
 32271    static HashElem nullElement = { 0, 0, 0, 0 };
 32272  
 32273    if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
 32274      struct _ht *pEntry;
 32275      h = strHash(pKey) % pH->htsize;
 32276      pEntry = &pH->ht[h];
 32277      elem = pEntry->chain;
 32278      count = pEntry->count;
 32279    }else{
 32280      h = 0;
 32281      elem = pH->first;
 32282      count = pH->count;
 32283    }
 32284    if( pHash ) *pHash = h;
 32285    while( count-- ){
 32286      assert( elem!=0 );
 32287      if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
 32288        return elem;
 32289      }
 32290      elem = elem->next;
 32291    }
 32292    return &nullElement;
 32293  }
 32294  
 32295  /* Remove a single entry from the hash table given a pointer to that
 32296  ** element and a hash on the element's key.
 32297  */
 32298  static void removeElementGivenHash(
 32299    Hash *pH,         /* The pH containing "elem" */
 32300    HashElem* elem,   /* The element to be removed from the pH */
 32301    unsigned int h    /* Hash value for the element */
 32302  ){
 32303    struct _ht *pEntry;
 32304    if( elem->prev ){
 32305      elem->prev->next = elem->next; 
 32306    }else{
 32307      pH->first = elem->next;
 32308    }
 32309    if( elem->next ){
 32310      elem->next->prev = elem->prev;
 32311    }
 32312    if( pH->ht ){
 32313      pEntry = &pH->ht[h];
 32314      if( pEntry->chain==elem ){
 32315        pEntry->chain = elem->next;
 32316      }
 32317      pEntry->count--;
 32318      assert( pEntry->count>=0 );
 32319    }
 32320    sqlite3_free( elem );
 32321    pH->count--;
 32322    if( pH->count==0 ){
 32323      assert( pH->first==0 );
 32324      assert( pH->count==0 );
 32325      sqlite3HashClear(pH);
 32326    }
 32327  }
 32328  
 32329  /* Attempt to locate an element of the hash table pH with a key
 32330  ** that matches pKey.  Return the data for this element if it is
 32331  ** found, or NULL if there is no match.
 32332  */
 32333  SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
 32334    assert( pH!=0 );
 32335    assert( pKey!=0 );
 32336    return findElementWithHash(pH, pKey, 0)->data;
 32337  }
 32338  
 32339  /* Insert an element into the hash table pH.  The key is pKey
 32340  ** and the data is "data".
 32341  **
 32342  ** If no element exists with a matching key, then a new
 32343  ** element is created and NULL is returned.
 32344  **
 32345  ** If another element already exists with the same key, then the
 32346  ** new data replaces the old data and the old data is returned.
 32347  ** The key is not copied in this instance.  If a malloc fails, then
 32348  ** the new data is returned and the hash table is unchanged.
 32349  **
 32350  ** If the "data" parameter to this function is NULL, then the
 32351  ** element corresponding to "key" is removed from the hash table.
 32352  */
 32353  SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
 32354    unsigned int h;       /* the hash of the key modulo hash table size */
 32355    HashElem *elem;       /* Used to loop thru the element list */
 32356    HashElem *new_elem;   /* New element added to the pH */
 32357  
 32358    assert( pH!=0 );
 32359    assert( pKey!=0 );
 32360    elem = findElementWithHash(pH,pKey,&h);
 32361    if( elem->data ){
 32362      void *old_data = elem->data;
 32363      if( data==0 ){
 32364        removeElementGivenHash(pH,elem,h);
 32365      }else{
 32366        elem->data = data;
 32367        elem->pKey = pKey;
 32368      }
 32369      return old_data;
 32370    }
 32371    if( data==0 ) return 0;
 32372    new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
 32373    if( new_elem==0 ) return data;
 32374    new_elem->pKey = pKey;
 32375    new_elem->data = data;
 32376    pH->count++;
 32377    if( pH->count>=10 && pH->count > 2*pH->htsize ){
 32378      if( rehash(pH, pH->count*2) ){
 32379        assert( pH->htsize>0 );
 32380        h = strHash(pKey) % pH->htsize;
 32381      }
 32382    }
 32383    insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
 32384    return 0;
 32385  }
 32386  
 32387  /************** End of hash.c ************************************************/
 32388  /************** Begin file opcodes.c *****************************************/
 32389  /* Automatically generated.  Do not edit */
 32390  /* See the tool/mkopcodec.tcl script for details. */
 32391  #if !defined(SQLITE_OMIT_EXPLAIN) \
 32392   || defined(VDBE_PROFILE) \
 32393   || defined(SQLITE_DEBUG)
 32394  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
 32395  # define OpHelp(X) "\0" X
 32396  #else
 32397  # define OpHelp(X)
 32398  #endif
 32399  SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 32400   static const char *const azName[] = {
 32401      /*   0 */ "Savepoint"        OpHelp(""),
 32402      /*   1 */ "AutoCommit"       OpHelp(""),
 32403      /*   2 */ "Transaction"      OpHelp(""),
 32404      /*   3 */ "SorterNext"       OpHelp(""),
 32405      /*   4 */ "Prev"             OpHelp(""),
 32406      /*   5 */ "Next"             OpHelp(""),
 32407      /*   6 */ "Checkpoint"       OpHelp(""),
 32408      /*   7 */ "JournalMode"      OpHelp(""),
 32409      /*   8 */ "Vacuum"           OpHelp(""),
 32410      /*   9 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
 32411      /*  10 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
 32412      /*  11 */ "Goto"             OpHelp(""),
 32413      /*  12 */ "Gosub"            OpHelp(""),
 32414      /*  13 */ "InitCoroutine"    OpHelp(""),
 32415      /*  14 */ "Yield"            OpHelp(""),
 32416      /*  15 */ "MustBeInt"        OpHelp(""),
 32417      /*  16 */ "Jump"             OpHelp(""),
 32418      /*  17 */ "Once"             OpHelp(""),
 32419      /*  18 */ "If"               OpHelp(""),
 32420      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
 32421      /*  20 */ "IfNot"            OpHelp(""),
 32422      /*  21 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
 32423      /*  22 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
 32424      /*  23 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
 32425      /*  24 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
 32426      /*  25 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
 32427      /*  26 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
 32428      /*  27 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
 32429      /*  28 */ "NotFound"         OpHelp("key=r[P3@P4]"),
 32430      /*  29 */ "Found"            OpHelp("key=r[P3@P4]"),
 32431      /*  30 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
 32432      /*  31 */ "NotExists"        OpHelp("intkey=r[P3]"),
 32433      /*  32 */ "Last"             OpHelp(""),
 32434      /*  33 */ "IfSmaller"        OpHelp(""),
 32435      /*  34 */ "SorterSort"       OpHelp(""),
 32436      /*  35 */ "Sort"             OpHelp(""),
 32437      /*  36 */ "Rewind"           OpHelp(""),
 32438      /*  37 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
 32439      /*  38 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
 32440      /*  39 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
 32441      /*  40 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
 32442      /*  41 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
 32443      /*  42 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
 32444      /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
 32445      /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
 32446      /*  45 */ "Program"          OpHelp(""),
 32447      /*  46 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
 32448      /*  47 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
 32449      /*  48 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
 32450      /*  49 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
 32451      /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
 32452      /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
 32453      /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
 32454      /*  53 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
 32455      /*  54 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
 32456      /*  55 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
 32457      /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
 32458      /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
 32459      /*  58 */ "ElseNotEq"        OpHelp(""),
 32460      /*  59 */ "IncrVacuum"       OpHelp(""),
 32461      /*  60 */ "VNext"            OpHelp(""),
 32462      /*  61 */ "Init"             OpHelp("Start at P2"),
 32463      /*  62 */ "PureFunc0"        OpHelp(""),
 32464      /*  63 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
 32465      /*  64 */ "PureFunc"         OpHelp(""),
 32466      /*  65 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
 32467      /*  66 */ "Return"           OpHelp(""),
 32468      /*  67 */ "EndCoroutine"     OpHelp(""),
 32469      /*  68 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
 32470      /*  69 */ "Halt"             OpHelp(""),
 32471      /*  70 */ "Integer"          OpHelp("r[P2]=P1"),
 32472      /*  71 */ "Int64"            OpHelp("r[P2]=P4"),
 32473      /*  72 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
 32474      /*  73 */ "Null"             OpHelp("r[P2..P3]=NULL"),
 32475      /*  74 */ "SoftNull"         OpHelp("r[P1]=NULL"),
 32476      /*  75 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
 32477      /*  76 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
 32478      /*  77 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
 32479      /*  78 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
 32480      /*  79 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
 32481      /*  80 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
 32482      /*  81 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
 32483      /*  82 */ "CollSeq"          OpHelp(""),
 32484      /*  83 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
 32485      /*  84 */ "RealAffinity"     OpHelp(""),
 32486      /*  85 */ "Cast"             OpHelp("affinity(r[P1])"),
 32487      /*  86 */ "Permutation"      OpHelp(""),
 32488      /*  87 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
 32489      /*  88 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
 32490      /*  89 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
 32491      /*  90 */ "Column"           OpHelp("r[P3]=PX"),
 32492      /*  91 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
 32493      /*  92 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
 32494      /*  93 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
 32495      /*  94 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
 32496      /*  95 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
 32497      /*  96 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
 32498      /*  97 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
 32499      /*  98 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
 32500      /*  99 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
 32501      /* 100 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
 32502      /* 101 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
 32503      /* 102 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
 32504      /* 103 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
 32505      /* 104 */ "Count"            OpHelp("r[P2]=count()"),
 32506      /* 105 */ "ReadCookie"       OpHelp(""),
 32507      /* 106 */ "String8"          OpHelp("r[P2]='P4'"),
 32508      /* 107 */ "SetCookie"        OpHelp(""),
 32509      /* 108 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
 32510      /* 109 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
 32511      /* 110 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
 32512      /* 111 */ "OpenDup"          OpHelp(""),
 32513      /* 112 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
 32514      /* 113 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
 32515      /* 114 */ "SorterOpen"       OpHelp(""),
 32516      /* 115 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
 32517      /* 116 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
 32518      /* 117 */ "Close"            OpHelp(""),
 32519      /* 118 */ "ColumnsUsed"      OpHelp(""),
 32520      /* 119 */ "SeekHit"          OpHelp("seekHit=P2"),
 32521      /* 120 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
 32522      /* 121 */ "NewRowid"         OpHelp("r[P2]=rowid"),
 32523      /* 122 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
 32524      /* 123 */ "Delete"           OpHelp(""),
 32525      /* 124 */ "ResetCount"       OpHelp(""),
 32526      /* 125 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
 32527      /* 126 */ "SorterData"       OpHelp("r[P2]=data"),
 32528      /* 127 */ "RowData"          OpHelp("r[P2]=data"),
 32529      /* 128 */ "Rowid"            OpHelp("r[P2]=rowid"),
 32530      /* 129 */ "NullRow"          OpHelp(""),
 32531      /* 130 */ "SeekEnd"          OpHelp(""),
 32532      /* 131 */ "SorterInsert"     OpHelp("key=r[P2]"),
 32533      /* 132 */ "IdxInsert"        OpHelp("key=r[P2]"),
 32534      /* 133 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
 32535      /* 134 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
 32536      /* 135 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
 32537      /* 136 */ "Destroy"          OpHelp(""),
 32538      /* 137 */ "Clear"            OpHelp(""),
 32539      /* 138 */ "ResetSorter"      OpHelp(""),
 32540      /* 139 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
 32541      /* 140 */ "SqlExec"          OpHelp(""),
 32542      /* 141 */ "Real"             OpHelp("r[P2]=P4"),
 32543      /* 142 */ "ParseSchema"      OpHelp(""),
 32544      /* 143 */ "LoadAnalysis"     OpHelp(""),
 32545      /* 144 */ "DropTable"        OpHelp(""),
 32546      /* 145 */ "DropIndex"        OpHelp(""),
 32547      /* 146 */ "DropTrigger"      OpHelp(""),
 32548      /* 147 */ "IntegrityCk"      OpHelp(""),
 32549      /* 148 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
 32550      /* 149 */ "Param"            OpHelp(""),
 32551      /* 150 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
 32552      /* 151 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
 32553      /* 152 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
 32554      /* 153 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
 32555      /* 154 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
 32556      /* 155 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
 32557      /* 156 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
 32558      /* 157 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
 32559      /* 158 */ "Expire"           OpHelp(""),
 32560      /* 159 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
 32561      /* 160 */ "VBegin"           OpHelp(""),
 32562      /* 161 */ "VCreate"          OpHelp(""),
 32563      /* 162 */ "VDestroy"         OpHelp(""),
 32564      /* 163 */ "VOpen"            OpHelp(""),
 32565      /* 164 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
 32566      /* 165 */ "VRename"          OpHelp(""),
 32567      /* 166 */ "Pagecount"        OpHelp(""),
 32568      /* 167 */ "MaxPgcnt"         OpHelp(""),
 32569      /* 168 */ "Trace"            OpHelp(""),
 32570      /* 169 */ "CursorHint"       OpHelp(""),
 32571      /* 170 */ "Noop"             OpHelp(""),
 32572      /* 171 */ "Explain"          OpHelp(""),
 32573      /* 172 */ "Abortable"        OpHelp(""),
 32574    };
 32575    return azName[i];
 32576  }
 32577  #endif
 32578  
 32579  /************** End of opcodes.c *********************************************/
 32580  /************** Begin file os_unix.c *****************************************/
 32581  /*
 32582  ** 2004 May 22
 32583  **
 32584  ** The author disclaims copyright to this source code.  In place of
 32585  ** a legal notice, here is a blessing:
 32586  **
 32587  **    May you do good and not evil.
 32588  **    May you find forgiveness for yourself and forgive others.
 32589  **    May you share freely, never taking more than you give.
 32590  **
 32591  ******************************************************************************
 32592  **
 32593  ** This file contains the VFS implementation for unix-like operating systems
 32594  ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
 32595  **
 32596  ** There are actually several different VFS implementations in this file.
 32597  ** The differences are in the way that file locking is done.  The default
 32598  ** implementation uses Posix Advisory Locks.  Alternative implementations
 32599  ** use flock(), dot-files, various proprietary locking schemas, or simply
 32600  ** skip locking all together.
 32601  **
 32602  ** This source file is organized into divisions where the logic for various
 32603  ** subfunctions is contained within the appropriate division.  PLEASE
 32604  ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
 32605  ** in the correct division and should be clearly labeled.
 32606  **
 32607  ** The layout of divisions is as follows:
 32608  **
 32609  **   *  General-purpose declarations and utility functions.
 32610  **   *  Unique file ID logic used by VxWorks.
 32611  **   *  Various locking primitive implementations (all except proxy locking):
 32612  **      + for Posix Advisory Locks
 32613  **      + for no-op locks
 32614  **      + for dot-file locks
 32615  **      + for flock() locking
 32616  **      + for named semaphore locks (VxWorks only)
 32617  **      + for AFP filesystem locks (MacOSX only)
 32618  **   *  sqlite3_file methods not associated with locking.
 32619  **   *  Definitions of sqlite3_io_methods objects for all locking
 32620  **      methods plus "finder" functions for each locking method.
 32621  **   *  sqlite3_vfs method implementations.
 32622  **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
 32623  **   *  Definitions of sqlite3_vfs objects for all locking methods
 32624  **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
 32625  */
 32626  /* #include "sqliteInt.h" */
 32627  #if SQLITE_OS_UNIX              /* This file is used on unix only */
 32628  
 32629  /*
 32630  ** There are various methods for file locking used for concurrency
 32631  ** control:
 32632  **
 32633  **   1. POSIX locking (the default),
 32634  **   2. No locking,
 32635  **   3. Dot-file locking,
 32636  **   4. flock() locking,
 32637  **   5. AFP locking (OSX only),
 32638  **   6. Named POSIX semaphores (VXWorks only),
 32639  **   7. proxy locking. (OSX only)
 32640  **
 32641  ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
 32642  ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
 32643  ** selection of the appropriate locking style based on the filesystem
 32644  ** where the database is located.  
 32645  */
 32646  #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 32647  #  if defined(__APPLE__)
 32648  #    define SQLITE_ENABLE_LOCKING_STYLE 1
 32649  #  else
 32650  #    define SQLITE_ENABLE_LOCKING_STYLE 0
 32651  #  endif
 32652  #endif
 32653  
 32654  /* Use pread() and pwrite() if they are available */
 32655  #if defined(__APPLE__)
 32656  # define HAVE_PREAD 1
 32657  # define HAVE_PWRITE 1
 32658  #endif
 32659  #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
 32660  # undef USE_PREAD
 32661  # define USE_PREAD64 1
 32662  #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
 32663  # undef USE_PREAD64
 32664  # define USE_PREAD 1
 32665  #endif
 32666  
 32667  /*
 32668  ** standard include files.
 32669  */
 32670  #include <sys/types.h>
 32671  #include <sys/stat.h>
 32672  #include <fcntl.h>
 32673  #include <sys/ioctl.h>
 32674  #include <unistd.h>
 32675  /* #include <time.h> */
 32676  #include <sys/time.h>
 32677  #include <errno.h>
 32678  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 32679  # include <sys/mman.h>
 32680  #endif
 32681  
 32682  #if SQLITE_ENABLE_LOCKING_STYLE
 32683  /* # include <sys/ioctl.h> */
 32684  # include <sys/file.h>
 32685  # include <sys/param.h>
 32686  #endif /* SQLITE_ENABLE_LOCKING_STYLE */
 32687  
 32688  #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
 32689                             (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
 32690  #  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
 32691         && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
 32692  #    define HAVE_GETHOSTUUID 1
 32693  #  else
 32694  #    warning "gethostuuid() is disabled."
 32695  #  endif
 32696  #endif
 32697  
 32698  
 32699  #if OS_VXWORKS
 32700  /* # include <sys/ioctl.h> */
 32701  # include <semaphore.h>
 32702  # include <limits.h>
 32703  #endif /* OS_VXWORKS */
 32704  
 32705  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 32706  # include <sys/mount.h>
 32707  #endif
 32708  
 32709  #ifdef HAVE_UTIME
 32710  # include <utime.h>
 32711  #endif
 32712  
 32713  /*
 32714  ** Allowed values of unixFile.fsFlags
 32715  */
 32716  #define SQLITE_FSFLAGS_IS_MSDOS     0x1
 32717  
 32718  /*
 32719  ** If we are to be thread-safe, include the pthreads header.
 32720  */
 32721  #if SQLITE_THREADSAFE
 32722  /* # include <pthread.h> */
 32723  #endif
 32724  
 32725  /*
 32726  ** Default permissions when creating a new file
 32727  */
 32728  #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
 32729  # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
 32730  #endif
 32731  
 32732  /*
 32733  ** Default permissions when creating auto proxy dir
 32734  */
 32735  #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 32736  # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
 32737  #endif
 32738  
 32739  /*
 32740  ** Maximum supported path-length.
 32741  */
 32742  #define MAX_PATHNAME 512
 32743  
 32744  /*
 32745  ** Maximum supported symbolic links
 32746  */
 32747  #define SQLITE_MAX_SYMLINKS 100
 32748  
 32749  /* Always cast the getpid() return type for compatibility with
 32750  ** kernel modules in VxWorks. */
 32751  #define osGetpid(X) (pid_t)getpid()
 32752  
 32753  /*
 32754  ** Only set the lastErrno if the error code is a real error and not 
 32755  ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
 32756  */
 32757  #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
 32758  
 32759  /* Forward references */
 32760  typedef struct unixShm unixShm;               /* Connection shared memory */
 32761  typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
 32762  typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
 32763  typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
 32764  
 32765  /*
 32766  ** Sometimes, after a file handle is closed by SQLite, the file descriptor
 32767  ** cannot be closed immediately. In these cases, instances of the following
 32768  ** structure are used to store the file descriptor while waiting for an
 32769  ** opportunity to either close or reuse it.
 32770  */
 32771  struct UnixUnusedFd {
 32772    int fd;                   /* File descriptor to close */
 32773    int flags;                /* Flags this file descriptor was opened with */
 32774    UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
 32775  };
 32776  
 32777  /*
 32778  ** The unixFile structure is subclass of sqlite3_file specific to the unix
 32779  ** VFS implementations.
 32780  */
 32781  typedef struct unixFile unixFile;
 32782  struct unixFile {
 32783    sqlite3_io_methods const *pMethod;  /* Always the first entry */
 32784    sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
 32785    unixInodeInfo *pInode;              /* Info about locks on this inode */
 32786    int h;                              /* The file descriptor */
 32787    unsigned char eFileLock;            /* The type of lock held on this fd */
 32788    unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
 32789    int lastErrno;                      /* The unix errno from last I/O error */
 32790    void *lockingContext;               /* Locking style specific state */
 32791    UnixUnusedFd *pPreallocatedUnused;  /* Pre-allocated UnixUnusedFd */
 32792    const char *zPath;                  /* Name of the file */
 32793    unixShm *pShm;                      /* Shared memory segment information */
 32794    int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
 32795  #if SQLITE_MAX_MMAP_SIZE>0
 32796    int nFetchOut;                      /* Number of outstanding xFetch refs */
 32797    sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
 32798    sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
 32799    sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
 32800    void *pMapRegion;                   /* Memory mapped region */
 32801  #endif
 32802    int sectorSize;                     /* Device sector size */
 32803    int deviceCharacteristics;          /* Precomputed device characteristics */
 32804  #if SQLITE_ENABLE_LOCKING_STYLE
 32805    int openFlags;                      /* The flags specified at open() */
 32806  #endif
 32807  #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
 32808    unsigned fsFlags;                   /* cached details from statfs() */
 32809  #endif
 32810  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
 32811    unsigned iBusyTimeout;              /* Wait this many millisec on locks */
 32812  #endif
 32813  #if OS_VXWORKS
 32814    struct vxworksFileId *pId;          /* Unique file ID */
 32815  #endif
 32816  #ifdef SQLITE_DEBUG
 32817    /* The next group of variables are used to track whether or not the
 32818    ** transaction counter in bytes 24-27 of database files are updated
 32819    ** whenever any part of the database changes.  An assertion fault will
 32820    ** occur if a file is updated without also updating the transaction
 32821    ** counter.  This test is made to avoid new problems similar to the
 32822    ** one described by ticket #3584. 
 32823    */
 32824    unsigned char transCntrChng;   /* True if the transaction counter changed */
 32825    unsigned char dbUpdate;        /* True if any part of database file changed */
 32826    unsigned char inNormalWrite;   /* True if in a normal write operation */
 32827  
 32828  #endif
 32829  
 32830  #ifdef SQLITE_TEST
 32831    /* In test mode, increase the size of this structure a bit so that 
 32832    ** it is larger than the struct CrashFile defined in test6.c.
 32833    */
 32834    char aPadding[32];
 32835  #endif
 32836  };
 32837  
 32838  /* This variable holds the process id (pid) from when the xRandomness()
 32839  ** method was called.  If xOpen() is called from a different process id,
 32840  ** indicating that a fork() has occurred, the PRNG will be reset.
 32841  */
 32842  static pid_t randomnessPid = 0;
 32843  
 32844  /*
 32845  ** Allowed values for the unixFile.ctrlFlags bitmask:
 32846  */
 32847  #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
 32848  #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
 32849  #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
 32850  #ifndef SQLITE_DISABLE_DIRSYNC
 32851  # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
 32852  #else
 32853  # define UNIXFILE_DIRSYNC    0x00
 32854  #endif
 32855  #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 32856  #define UNIXFILE_DELETE      0x20     /* Delete on close */
 32857  #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
 32858  #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
 32859  
 32860  /*
 32861  ** Include code that is common to all os_*.c files
 32862  */
 32863  /************** Include os_common.h in the middle of os_unix.c ***************/
 32864  /************** Begin file os_common.h ***************************************/
 32865  /*
 32866  ** 2004 May 22
 32867  **
 32868  ** The author disclaims copyright to this source code.  In place of
 32869  ** a legal notice, here is a blessing:
 32870  **
 32871  **    May you do good and not evil.
 32872  **    May you find forgiveness for yourself and forgive others.
 32873  **    May you share freely, never taking more than you give.
 32874  **
 32875  ******************************************************************************
 32876  **
 32877  ** This file contains macros and a little bit of code that is common to
 32878  ** all of the platform-specific files (os_*.c) and is #included into those
 32879  ** files.
 32880  **
 32881  ** This file should be #included by the os_*.c files only.  It is not a
 32882  ** general purpose header file.
 32883  */
 32884  #ifndef _OS_COMMON_H_
 32885  #define _OS_COMMON_H_
 32886  
 32887  /*
 32888  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 32889  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 32890  ** switch.  The following code should catch this problem at compile-time.
 32891  */
 32892  #ifdef MEMORY_DEBUG
 32893  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 32894  #endif
 32895  
 32896  /*
 32897  ** Macros for performance tracing.  Normally turned off.  Only works
 32898  ** on i486 hardware.
 32899  */
 32900  #ifdef SQLITE_PERFORMANCE_TRACE
 32901  
 32902  /*
 32903  ** hwtime.h contains inline assembler code for implementing
 32904  ** high-performance timing routines.
 32905  */
 32906  /************** Include hwtime.h in the middle of os_common.h ****************/
 32907  /************** Begin file hwtime.h ******************************************/
 32908  /*
 32909  ** 2008 May 27
 32910  **
 32911  ** The author disclaims copyright to this source code.  In place of
 32912  ** a legal notice, here is a blessing:
 32913  **
 32914  **    May you do good and not evil.
 32915  **    May you find forgiveness for yourself and forgive others.
 32916  **    May you share freely, never taking more than you give.
 32917  **
 32918  ******************************************************************************
 32919  **
 32920  ** This file contains inline asm code for retrieving "high-performance"
 32921  ** counters for x86 class CPUs.
 32922  */
 32923  #ifndef SQLITE_HWTIME_H
 32924  #define SQLITE_HWTIME_H
 32925  
 32926  /*
 32927  ** The following routine only works on pentium-class (or newer) processors.
 32928  ** It uses the RDTSC opcode to read the cycle count value out of the
 32929  ** processor and returns that value.  This can be used for high-res
 32930  ** profiling.
 32931  */
 32932  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 32933        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 32934  
 32935    #if defined(__GNUC__)
 32936  
 32937    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 32938       unsigned int lo, hi;
 32939       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 32940       return (sqlite_uint64)hi << 32 | lo;
 32941    }
 32942  
 32943    #elif defined(_MSC_VER)
 32944  
 32945    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 32946       __asm {
 32947          rdtsc
 32948          ret       ; return value at EDX:EAX
 32949       }
 32950    }
 32951  
 32952    #endif
 32953  
 32954  #elif (defined(__GNUC__) && defined(__x86_64__))
 32955  
 32956    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 32957        unsigned long val;
 32958        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 32959        return val;
 32960    }
 32961   
 32962  #elif (defined(__GNUC__) && defined(__ppc__))
 32963  
 32964    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 32965        unsigned long long retval;
 32966        unsigned long junk;
 32967        __asm__ __volatile__ ("\n\
 32968            1:      mftbu   %1\n\
 32969                    mftb    %L0\n\
 32970                    mftbu   %0\n\
 32971                    cmpw    %0,%1\n\
 32972                    bne     1b"
 32973                    : "=r" (retval), "=r" (junk));
 32974        return retval;
 32975    }
 32976  
 32977  #else
 32978  
 32979    #error Need implementation of sqlite3Hwtime() for your platform.
 32980  
 32981    /*
 32982    ** To compile without implementing sqlite3Hwtime() for your platform,
 32983    ** you can remove the above #error and use the following
 32984    ** stub function.  You will lose timing support for many
 32985    ** of the debugging and testing utilities, but it should at
 32986    ** least compile and run.
 32987    */
 32988  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 32989  
 32990  #endif
 32991  
 32992  #endif /* !defined(SQLITE_HWTIME_H) */
 32993  
 32994  /************** End of hwtime.h **********************************************/
 32995  /************** Continuing where we left off in os_common.h ******************/
 32996  
 32997  static sqlite_uint64 g_start;
 32998  static sqlite_uint64 g_elapsed;
 32999  #define TIMER_START       g_start=sqlite3Hwtime()
 33000  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 33001  #define TIMER_ELAPSED     g_elapsed
 33002  #else
 33003  #define TIMER_START
 33004  #define TIMER_END
 33005  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 33006  #endif
 33007  
 33008  /*
 33009  ** If we compile with the SQLITE_TEST macro set, then the following block
 33010  ** of code will give us the ability to simulate a disk I/O error.  This
 33011  ** is used for testing the I/O recovery logic.
 33012  */
 33013  #if defined(SQLITE_TEST)
 33014  SQLITE_API extern int sqlite3_io_error_hit;
 33015  SQLITE_API extern int sqlite3_io_error_hardhit;
 33016  SQLITE_API extern int sqlite3_io_error_pending;
 33017  SQLITE_API extern int sqlite3_io_error_persist;
 33018  SQLITE_API extern int sqlite3_io_error_benign;
 33019  SQLITE_API extern int sqlite3_diskfull_pending;
 33020  SQLITE_API extern int sqlite3_diskfull;
 33021  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 33022  #define SimulateIOError(CODE)  \
 33023    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 33024         || sqlite3_io_error_pending-- == 1 )  \
 33025                { local_ioerr(); CODE; }
 33026  static void local_ioerr(){
 33027    IOTRACE(("IOERR\n"));
 33028    sqlite3_io_error_hit++;
 33029    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 33030  }
 33031  #define SimulateDiskfullError(CODE) \
 33032     if( sqlite3_diskfull_pending ){ \
 33033       if( sqlite3_diskfull_pending == 1 ){ \
 33034         local_ioerr(); \
 33035         sqlite3_diskfull = 1; \
 33036         sqlite3_io_error_hit = 1; \
 33037         CODE; \
 33038       }else{ \
 33039         sqlite3_diskfull_pending--; \
 33040       } \
 33041     }
 33042  #else
 33043  #define SimulateIOErrorBenign(X)
 33044  #define SimulateIOError(A)
 33045  #define SimulateDiskfullError(A)
 33046  #endif /* defined(SQLITE_TEST) */
 33047  
 33048  /*
 33049  ** When testing, keep a count of the number of open files.
 33050  */
 33051  #if defined(SQLITE_TEST)
 33052  SQLITE_API extern int sqlite3_open_file_count;
 33053  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 33054  #else
 33055  #define OpenCounter(X)
 33056  #endif /* defined(SQLITE_TEST) */
 33057  
 33058  #endif /* !defined(_OS_COMMON_H_) */
 33059  
 33060  /************** End of os_common.h *******************************************/
 33061  /************** Continuing where we left off in os_unix.c ********************/
 33062  
 33063  /*
 33064  ** Define various macros that are missing from some systems.
 33065  */
 33066  #ifndef O_LARGEFILE
 33067  # define O_LARGEFILE 0
 33068  #endif
 33069  #ifdef SQLITE_DISABLE_LFS
 33070  # undef O_LARGEFILE
 33071  # define O_LARGEFILE 0
 33072  #endif
 33073  #ifndef O_NOFOLLOW
 33074  # define O_NOFOLLOW 0
 33075  #endif
 33076  #ifndef O_BINARY
 33077  # define O_BINARY 0
 33078  #endif
 33079  
 33080  /*
 33081  ** The threadid macro resolves to the thread-id or to 0.  Used for
 33082  ** testing and debugging only.
 33083  */
 33084  #if SQLITE_THREADSAFE
 33085  #define threadid pthread_self()
 33086  #else
 33087  #define threadid 0
 33088  #endif
 33089  
 33090  /*
 33091  ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
 33092  */
 33093  #if !defined(HAVE_MREMAP)
 33094  # if defined(__linux__) && defined(_GNU_SOURCE)
 33095  #  define HAVE_MREMAP 1
 33096  # else
 33097  #  define HAVE_MREMAP 0
 33098  # endif
 33099  #endif
 33100  
 33101  /*
 33102  ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
 33103  ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
 33104  */
 33105  #ifdef __ANDROID__
 33106  # define lseek lseek64
 33107  #endif
 33108  
 33109  #ifdef __linux__
 33110  /*
 33111  ** Linux-specific IOCTL magic numbers used for controlling F2FS
 33112  */
 33113  #define F2FS_IOCTL_MAGIC        0xf5
 33114  #define F2FS_IOC_START_ATOMIC_WRITE     _IO(F2FS_IOCTL_MAGIC, 1)
 33115  #define F2FS_IOC_COMMIT_ATOMIC_WRITE    _IO(F2FS_IOCTL_MAGIC, 2)
 33116  #define F2FS_IOC_START_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 3)
 33117  #define F2FS_IOC_ABORT_VOLATILE_WRITE   _IO(F2FS_IOCTL_MAGIC, 5)
 33118  #define F2FS_IOC_GET_FEATURES           _IOR(F2FS_IOCTL_MAGIC, 12, u32)
 33119  #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
 33120  #endif /* __linux__ */
 33121  
 33122  
 33123  /*
 33124  ** Different Unix systems declare open() in different ways.  Same use
 33125  ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
 33126  ** The difference is important when using a pointer to the function.
 33127  **
 33128  ** The safest way to deal with the problem is to always use this wrapper
 33129  ** which always has the same well-defined interface.
 33130  */
 33131  static int posixOpen(const char *zFile, int flags, int mode){
 33132    return open(zFile, flags, mode);
 33133  }
 33134  
 33135  /* Forward reference */
 33136  static int openDirectory(const char*, int*);
 33137  static int unixGetpagesize(void);
 33138  
 33139  /*
 33140  ** Many system calls are accessed through pointer-to-functions so that
 33141  ** they may be overridden at runtime to facilitate fault injection during
 33142  ** testing and sandboxing.  The following array holds the names and pointers
 33143  ** to all overrideable system calls.
 33144  */
 33145  static struct unix_syscall {
 33146    const char *zName;            /* Name of the system call */
 33147    sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 33148    sqlite3_syscall_ptr pDefault; /* Default value */
 33149  } aSyscall[] = {
 33150    { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
 33151  #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
 33152  
 33153    { "close",        (sqlite3_syscall_ptr)close,      0  },
 33154  #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
 33155  
 33156    { "access",       (sqlite3_syscall_ptr)access,     0  },
 33157  #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
 33158  
 33159    { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
 33160  #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
 33161  
 33162    { "stat",         (sqlite3_syscall_ptr)stat,       0  },
 33163  #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
 33164  
 33165  /*
 33166  ** The DJGPP compiler environment looks mostly like Unix, but it
 33167  ** lacks the fcntl() system call.  So redefine fcntl() to be something
 33168  ** that always succeeds.  This means that locking does not occur under
 33169  ** DJGPP.  But it is DOS - what did you expect?
 33170  */
 33171  #ifdef __DJGPP__
 33172    { "fstat",        0,                 0  },
 33173  #define osFstat(a,b,c)    0
 33174  #else     
 33175    { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
 33176  #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
 33177  #endif
 33178  
 33179    { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
 33180  #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
 33181  
 33182    { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
 33183  #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
 33184  
 33185    { "read",         (sqlite3_syscall_ptr)read,       0  },
 33186  #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
 33187  
 33188  #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 33189    { "pread",        (sqlite3_syscall_ptr)pread,      0  },
 33190  #else
 33191    { "pread",        (sqlite3_syscall_ptr)0,          0  },
 33192  #endif
 33193  #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
 33194  
 33195  #if defined(USE_PREAD64)
 33196    { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
 33197  #else
 33198    { "pread64",      (sqlite3_syscall_ptr)0,          0  },
 33199  #endif
 33200  #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
 33201  
 33202    { "write",        (sqlite3_syscall_ptr)write,      0  },
 33203  #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
 33204  
 33205  #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
 33206    { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
 33207  #else
 33208    { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
 33209  #endif
 33210  #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
 33211                      aSyscall[12].pCurrent)
 33212  
 33213  #if defined(USE_PREAD64)
 33214    { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
 33215  #else
 33216    { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
 33217  #endif
 33218  #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
 33219                      aSyscall[13].pCurrent)
 33220  
 33221    { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
 33222  #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
 33223  
 33224  #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 33225    { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
 33226  #else
 33227    { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
 33228  #endif
 33229  #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
 33230  
 33231    { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
 33232  #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
 33233  
 33234    { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
 33235  #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
 33236  
 33237    { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
 33238  #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
 33239  
 33240    { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
 33241  #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
 33242  
 33243  #if defined(HAVE_FCHOWN)
 33244    { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
 33245  #else
 33246    { "fchown",       (sqlite3_syscall_ptr)0,               0 },
 33247  #endif
 33248  #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
 33249  
 33250  #if defined(HAVE_FCHOWN)
 33251    { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
 33252  #else
 33253    { "geteuid",      (sqlite3_syscall_ptr)0,               0 },
 33254  #endif
 33255  #define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
 33256  
 33257  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 33258    { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
 33259  #else
 33260    { "mmap",         (sqlite3_syscall_ptr)0,               0 },
 33261  #endif
 33262  #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
 33263  
 33264  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 33265    { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
 33266  #else
 33267    { "munmap",       (sqlite3_syscall_ptr)0,               0 },
 33268  #endif
 33269  #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
 33270  
 33271  #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 33272    { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
 33273  #else
 33274    { "mremap",       (sqlite3_syscall_ptr)0,               0 },
 33275  #endif
 33276  #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
 33277  
 33278  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 33279    { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
 33280  #else
 33281    { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
 33282  #endif
 33283  #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
 33284  
 33285  #if defined(HAVE_READLINK)
 33286    { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
 33287  #else
 33288    { "readlink",     (sqlite3_syscall_ptr)0,               0 },
 33289  #endif
 33290  #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
 33291  
 33292  #if defined(HAVE_LSTAT)
 33293    { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
 33294  #else
 33295    { "lstat",         (sqlite3_syscall_ptr)0,              0 },
 33296  #endif
 33297  #define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
 33298  
 33299  #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 33300  # ifdef __ANDROID__
 33301    { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
 33302  # else
 33303    { "ioctl",         (sqlite3_syscall_ptr)ioctl,          0 },
 33304  # endif
 33305  #else
 33306    { "ioctl",         (sqlite3_syscall_ptr)0,              0 },
 33307  #endif
 33308  #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
 33309  
 33310  }; /* End of the overrideable system calls */
 33311  
 33312  
 33313  /*
 33314  ** On some systems, calls to fchown() will trigger a message in a security
 33315  ** log if they come from non-root processes.  So avoid calling fchown() if
 33316  ** we are not running as root.
 33317  */
 33318  static int robustFchown(int fd, uid_t uid, gid_t gid){
 33319  #if defined(HAVE_FCHOWN)
 33320    return osGeteuid() ? 0 : osFchown(fd,uid,gid);
 33321  #else
 33322    return 0;
 33323  #endif
 33324  }
 33325  
 33326  /*
 33327  ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 33328  ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
 33329  ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 33330  ** system call named zName.
 33331  */
 33332  static int unixSetSystemCall(
 33333    sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 33334    const char *zName,            /* Name of system call to override */
 33335    sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 33336  ){
 33337    unsigned int i;
 33338    int rc = SQLITE_NOTFOUND;
 33339  
 33340    UNUSED_PARAMETER(pNotUsed);
 33341    if( zName==0 ){
 33342      /* If no zName is given, restore all system calls to their default
 33343      ** settings and return NULL
 33344      */
 33345      rc = SQLITE_OK;
 33346      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 33347        if( aSyscall[i].pDefault ){
 33348          aSyscall[i].pCurrent = aSyscall[i].pDefault;
 33349        }
 33350      }
 33351    }else{
 33352      /* If zName is specified, operate on only the one system call
 33353      ** specified.
 33354      */
 33355      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 33356        if( strcmp(zName, aSyscall[i].zName)==0 ){
 33357          if( aSyscall[i].pDefault==0 ){
 33358            aSyscall[i].pDefault = aSyscall[i].pCurrent;
 33359          }
 33360          rc = SQLITE_OK;
 33361          if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 33362          aSyscall[i].pCurrent = pNewFunc;
 33363          break;
 33364        }
 33365      }
 33366    }
 33367    return rc;
 33368  }
 33369  
 33370  /*
 33371  ** Return the value of a system call.  Return NULL if zName is not a
 33372  ** recognized system call name.  NULL is also returned if the system call
 33373  ** is currently undefined.
 33374  */
 33375  static sqlite3_syscall_ptr unixGetSystemCall(
 33376    sqlite3_vfs *pNotUsed,
 33377    const char *zName
 33378  ){
 33379    unsigned int i;
 33380  
 33381    UNUSED_PARAMETER(pNotUsed);
 33382    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 33383      if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 33384    }
 33385    return 0;
 33386  }
 33387  
 33388  /*
 33389  ** Return the name of the first system call after zName.  If zName==NULL
 33390  ** then return the name of the first system call.  Return NULL if zName
 33391  ** is the last system call or if zName is not the name of a valid
 33392  ** system call.
 33393  */
 33394  static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
 33395    int i = -1;
 33396  
 33397    UNUSED_PARAMETER(p);
 33398    if( zName ){
 33399      for(i=0; i<ArraySize(aSyscall)-1; i++){
 33400        if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 33401      }
 33402    }
 33403    for(i++; i<ArraySize(aSyscall); i++){
 33404      if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 33405    }
 33406    return 0;
 33407  }
 33408  
 33409  /*
 33410  ** Do not accept any file descriptor less than this value, in order to avoid
 33411  ** opening database file using file descriptors that are commonly used for 
 33412  ** standard input, output, and error.
 33413  */
 33414  #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
 33415  # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
 33416  #endif
 33417  
 33418  /*
 33419  ** Invoke open().  Do so multiple times, until it either succeeds or
 33420  ** fails for some reason other than EINTR.
 33421  **
 33422  ** If the file creation mode "m" is 0 then set it to the default for
 33423  ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
 33424  ** 0644) as modified by the system umask.  If m is not 0, then
 33425  ** make the file creation mode be exactly m ignoring the umask.
 33426  **
 33427  ** The m parameter will be non-zero only when creating -wal, -journal,
 33428  ** and -shm files.  We want those files to have *exactly* the same
 33429  ** permissions as their original database, unadulterated by the umask.
 33430  ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
 33431  ** transaction crashes and leaves behind hot journals, then any
 33432  ** process that is able to write to the database will also be able to
 33433  ** recover the hot journals.
 33434  */
 33435  static int robust_open(const char *z, int f, mode_t m){
 33436    int fd;
 33437    mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
 33438    while(1){
 33439  #if defined(O_CLOEXEC)
 33440      fd = osOpen(z,f|O_CLOEXEC,m2);
 33441  #else
 33442      fd = osOpen(z,f,m2);
 33443  #endif
 33444      if( fd<0 ){
 33445        if( errno==EINTR ) continue;
 33446        break;
 33447      }
 33448      if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
 33449      osClose(fd);
 33450      sqlite3_log(SQLITE_WARNING, 
 33451                  "attempt to open \"%s\" as file descriptor %d", z, fd);
 33452      fd = -1;
 33453      if( osOpen("/dev/null", f, m)<0 ) break;
 33454    }
 33455    if( fd>=0 ){
 33456      if( m!=0 ){
 33457        struct stat statbuf;
 33458        if( osFstat(fd, &statbuf)==0 
 33459         && statbuf.st_size==0
 33460         && (statbuf.st_mode&0777)!=m 
 33461        ){
 33462          osFchmod(fd, m);
 33463        }
 33464      }
 33465  #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
 33466      osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
 33467  #endif
 33468    }
 33469    return fd;
 33470  }
 33471  
 33472  /*
 33473  ** Helper functions to obtain and relinquish the global mutex. The
 33474  ** global mutex is used to protect the unixInodeInfo and
 33475  ** vxworksFileId objects used by this file, all of which may be 
 33476  ** shared by multiple threads.
 33477  **
 33478  ** Function unixMutexHeld() is used to assert() that the global mutex 
 33479  ** is held when required. This function is only used as part of assert() 
 33480  ** statements. e.g.
 33481  **
 33482  **   unixEnterMutex()
 33483  **     assert( unixMutexHeld() );
 33484  **   unixEnterLeave()
 33485  **
 33486  ** To prevent deadlock, the global unixBigLock must must be acquired
 33487  ** before the unixInodeInfo.pLockMutex mutex, if both are held.  It is
 33488  ** OK to get the pLockMutex without holding unixBigLock first, but if
 33489  ** that happens, the unixBigLock mutex must not be acquired until after
 33490  ** pLockMutex is released.
 33491  **
 33492  **      OK:     enter(unixBigLock),  enter(pLockInfo)
 33493  **      OK:     enter(unixBigLock)
 33494  **      OK:     enter(pLockInfo)
 33495  **   ERROR:     enter(pLockInfo), enter(unixBigLock)
 33496  */
 33497  static sqlite3_mutex *unixBigLock = 0;
 33498  static void unixEnterMutex(void){
 33499    assert( sqlite3_mutex_notheld(unixBigLock) );  /* Not a recursive mutex */
 33500    sqlite3_mutex_enter(unixBigLock);
 33501  }
 33502  static void unixLeaveMutex(void){
 33503    assert( sqlite3_mutex_held(unixBigLock) );
 33504    sqlite3_mutex_leave(unixBigLock);
 33505  }
 33506  #ifdef SQLITE_DEBUG
 33507  static int unixMutexHeld(void) {
 33508    return sqlite3_mutex_held(unixBigLock);
 33509  }
 33510  #endif
 33511  
 33512  
 33513  #ifdef SQLITE_HAVE_OS_TRACE
 33514  /*
 33515  ** Helper function for printing out trace information from debugging
 33516  ** binaries. This returns the string representation of the supplied
 33517  ** integer lock-type.
 33518  */
 33519  static const char *azFileLock(int eFileLock){
 33520    switch( eFileLock ){
 33521      case NO_LOCK: return "NONE";
 33522      case SHARED_LOCK: return "SHARED";
 33523      case RESERVED_LOCK: return "RESERVED";
 33524      case PENDING_LOCK: return "PENDING";
 33525      case EXCLUSIVE_LOCK: return "EXCLUSIVE";
 33526    }
 33527    return "ERROR";
 33528  }
 33529  #endif
 33530  
 33531  #ifdef SQLITE_LOCK_TRACE
 33532  /*
 33533  ** Print out information about all locking operations.
 33534  **
 33535  ** This routine is used for troubleshooting locks on multithreaded
 33536  ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
 33537  ** command-line option on the compiler.  This code is normally
 33538  ** turned off.
 33539  */
 33540  static int lockTrace(int fd, int op, struct flock *p){
 33541    char *zOpName, *zType;
 33542    int s;
 33543    int savedErrno;
 33544    if( op==F_GETLK ){
 33545      zOpName = "GETLK";
 33546    }else if( op==F_SETLK ){
 33547      zOpName = "SETLK";
 33548    }else{
 33549      s = osFcntl(fd, op, p);
 33550      sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
 33551      return s;
 33552    }
 33553    if( p->l_type==F_RDLCK ){
 33554      zType = "RDLCK";
 33555    }else if( p->l_type==F_WRLCK ){
 33556      zType = "WRLCK";
 33557    }else if( p->l_type==F_UNLCK ){
 33558      zType = "UNLCK";
 33559    }else{
 33560      assert( 0 );
 33561    }
 33562    assert( p->l_whence==SEEK_SET );
 33563    s = osFcntl(fd, op, p);
 33564    savedErrno = errno;
 33565    sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
 33566       threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
 33567       (int)p->l_pid, s);
 33568    if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
 33569      struct flock l2;
 33570      l2 = *p;
 33571      osFcntl(fd, F_GETLK, &l2);
 33572      if( l2.l_type==F_RDLCK ){
 33573        zType = "RDLCK";
 33574      }else if( l2.l_type==F_WRLCK ){
 33575        zType = "WRLCK";
 33576      }else if( l2.l_type==F_UNLCK ){
 33577        zType = "UNLCK";
 33578      }else{
 33579        assert( 0 );
 33580      }
 33581      sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
 33582         zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
 33583    }
 33584    errno = savedErrno;
 33585    return s;
 33586  }
 33587  #undef osFcntl
 33588  #define osFcntl lockTrace
 33589  #endif /* SQLITE_LOCK_TRACE */
 33590  
 33591  /*
 33592  ** Retry ftruncate() calls that fail due to EINTR
 33593  **
 33594  ** All calls to ftruncate() within this file should be made through
 33595  ** this wrapper.  On the Android platform, bypassing the logic below
 33596  ** could lead to a corrupt database.
 33597  */
 33598  static int robust_ftruncate(int h, sqlite3_int64 sz){
 33599    int rc;
 33600  #ifdef __ANDROID__
 33601    /* On Android, ftruncate() always uses 32-bit offsets, even if 
 33602    ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
 33603    ** truncate a file to any size larger than 2GiB. Silently ignore any
 33604    ** such attempts.  */
 33605    if( sz>(sqlite3_int64)0x7FFFFFFF ){
 33606      rc = SQLITE_OK;
 33607    }else
 33608  #endif
 33609    do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
 33610    return rc;
 33611  }
 33612  
 33613  /*
 33614  ** This routine translates a standard POSIX errno code into something
 33615  ** useful to the clients of the sqlite3 functions.  Specifically, it is
 33616  ** intended to translate a variety of "try again" errors into SQLITE_BUSY
 33617  ** and a variety of "please close the file descriptor NOW" errors into 
 33618  ** SQLITE_IOERR
 33619  ** 
 33620  ** Errors during initialization of locks, or file system support for locks,
 33621  ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
 33622  */
 33623  static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
 33624    assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
 33625            (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
 33626            (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
 33627            (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
 33628    switch (posixError) {
 33629    case EACCES: 
 33630    case EAGAIN:
 33631    case ETIMEDOUT:
 33632    case EBUSY:
 33633    case EINTR:
 33634    case ENOLCK:  
 33635      /* random NFS retry error, unless during file system support 
 33636       * introspection, in which it actually means what it says */
 33637      return SQLITE_BUSY;
 33638      
 33639    case EPERM: 
 33640      return SQLITE_PERM;
 33641      
 33642    default: 
 33643      return sqliteIOErr;
 33644    }
 33645  }
 33646  
 33647  
 33648  /******************************************************************************
 33649  ****************** Begin Unique File ID Utility Used By VxWorks ***************
 33650  **
 33651  ** On most versions of unix, we can get a unique ID for a file by concatenating
 33652  ** the device number and the inode number.  But this does not work on VxWorks.
 33653  ** On VxWorks, a unique file id must be based on the canonical filename.
 33654  **
 33655  ** A pointer to an instance of the following structure can be used as a
 33656  ** unique file ID in VxWorks.  Each instance of this structure contains
 33657  ** a copy of the canonical filename.  There is also a reference count.  
 33658  ** The structure is reclaimed when the number of pointers to it drops to
 33659  ** zero.
 33660  **
 33661  ** There are never very many files open at one time and lookups are not
 33662  ** a performance-critical path, so it is sufficient to put these
 33663  ** structures on a linked list.
 33664  */
 33665  struct vxworksFileId {
 33666    struct vxworksFileId *pNext;  /* Next in a list of them all */
 33667    int nRef;                     /* Number of references to this one */
 33668    int nName;                    /* Length of the zCanonicalName[] string */
 33669    char *zCanonicalName;         /* Canonical filename */
 33670  };
 33671  
 33672  #if OS_VXWORKS
 33673  /* 
 33674  ** All unique filenames are held on a linked list headed by this
 33675  ** variable:
 33676  */
 33677  static struct vxworksFileId *vxworksFileList = 0;
 33678  
 33679  /*
 33680  ** Simplify a filename into its canonical form
 33681  ** by making the following changes:
 33682  **
 33683  **  * removing any trailing and duplicate /
 33684  **  * convert /./ into just /
 33685  **  * convert /A/../ where A is any simple name into just /
 33686  **
 33687  ** Changes are made in-place.  Return the new name length.
 33688  **
 33689  ** The original filename is in z[0..n-1].  Return the number of
 33690  ** characters in the simplified name.
 33691  */
 33692  static int vxworksSimplifyName(char *z, int n){
 33693    int i, j;
 33694    while( n>1 && z[n-1]=='/' ){ n--; }
 33695    for(i=j=0; i<n; i++){
 33696      if( z[i]=='/' ){
 33697        if( z[i+1]=='/' ) continue;
 33698        if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
 33699          i += 1;
 33700          continue;
 33701        }
 33702        if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
 33703          while( j>0 && z[j-1]!='/' ){ j--; }
 33704          if( j>0 ){ j--; }
 33705          i += 2;
 33706          continue;
 33707        }
 33708      }
 33709      z[j++] = z[i];
 33710    }
 33711    z[j] = 0;
 33712    return j;
 33713  }
 33714  
 33715  /*
 33716  ** Find a unique file ID for the given absolute pathname.  Return
 33717  ** a pointer to the vxworksFileId object.  This pointer is the unique
 33718  ** file ID.
 33719  **
 33720  ** The nRef field of the vxworksFileId object is incremented before
 33721  ** the object is returned.  A new vxworksFileId object is created
 33722  ** and added to the global list if necessary.
 33723  **
 33724  ** If a memory allocation error occurs, return NULL.
 33725  */
 33726  static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
 33727    struct vxworksFileId *pNew;         /* search key and new file ID */
 33728    struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
 33729    int n;                              /* Length of zAbsoluteName string */
 33730  
 33731    assert( zAbsoluteName[0]=='/' );
 33732    n = (int)strlen(zAbsoluteName);
 33733    pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
 33734    if( pNew==0 ) return 0;
 33735    pNew->zCanonicalName = (char*)&pNew[1];
 33736    memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
 33737    n = vxworksSimplifyName(pNew->zCanonicalName, n);
 33738  
 33739    /* Search for an existing entry that matching the canonical name.
 33740    ** If found, increment the reference count and return a pointer to
 33741    ** the existing file ID.
 33742    */
 33743    unixEnterMutex();
 33744    for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
 33745      if( pCandidate->nName==n 
 33746       && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
 33747      ){
 33748         sqlite3_free(pNew);
 33749         pCandidate->nRef++;
 33750         unixLeaveMutex();
 33751         return pCandidate;
 33752      }
 33753    }
 33754  
 33755    /* No match was found.  We will make a new file ID */
 33756    pNew->nRef = 1;
 33757    pNew->nName = n;
 33758    pNew->pNext = vxworksFileList;
 33759    vxworksFileList = pNew;
 33760    unixLeaveMutex();
 33761    return pNew;
 33762  }
 33763  
 33764  /*
 33765  ** Decrement the reference count on a vxworksFileId object.  Free
 33766  ** the object when the reference count reaches zero.
 33767  */
 33768  static void vxworksReleaseFileId(struct vxworksFileId *pId){
 33769    unixEnterMutex();
 33770    assert( pId->nRef>0 );
 33771    pId->nRef--;
 33772    if( pId->nRef==0 ){
 33773      struct vxworksFileId **pp;
 33774      for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
 33775      assert( *pp==pId );
 33776      *pp = pId->pNext;
 33777      sqlite3_free(pId);
 33778    }
 33779    unixLeaveMutex();
 33780  }
 33781  #endif /* OS_VXWORKS */
 33782  /*************** End of Unique File ID Utility Used By VxWorks ****************
 33783  ******************************************************************************/
 33784  
 33785  
 33786  /******************************************************************************
 33787  *************************** Posix Advisory Locking ****************************
 33788  **
 33789  ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
 33790  ** section 6.5.2.2 lines 483 through 490 specify that when a process
 33791  ** sets or clears a lock, that operation overrides any prior locks set
 33792  ** by the same process.  It does not explicitly say so, but this implies
 33793  ** that it overrides locks set by the same process using a different
 33794  ** file descriptor.  Consider this test case:
 33795  **
 33796  **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
 33797  **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
 33798  **
 33799  ** Suppose ./file1 and ./file2 are really the same file (because
 33800  ** one is a hard or symbolic link to the other) then if you set
 33801  ** an exclusive lock on fd1, then try to get an exclusive lock
 33802  ** on fd2, it works.  I would have expected the second lock to
 33803  ** fail since there was already a lock on the file due to fd1.
 33804  ** But not so.  Since both locks came from the same process, the
 33805  ** second overrides the first, even though they were on different
 33806  ** file descriptors opened on different file names.
 33807  **
 33808  ** This means that we cannot use POSIX locks to synchronize file access
 33809  ** among competing threads of the same process.  POSIX locks will work fine
 33810  ** to synchronize access for threads in separate processes, but not
 33811  ** threads within the same process.
 33812  **
 33813  ** To work around the problem, SQLite has to manage file locks internally
 33814  ** on its own.  Whenever a new database is opened, we have to find the
 33815  ** specific inode of the database file (the inode is determined by the
 33816  ** st_dev and st_ino fields of the stat structure that fstat() fills in)
 33817  ** and check for locks already existing on that inode.  When locks are
 33818  ** created or removed, we have to look at our own internal record of the
 33819  ** locks to see if another thread has previously set a lock on that same
 33820  ** inode.
 33821  **
 33822  ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
 33823  ** For VxWorks, we have to use the alternative unique ID system based on
 33824  ** canonical filename and implemented in the previous division.)
 33825  **
 33826  ** The sqlite3_file structure for POSIX is no longer just an integer file
 33827  ** descriptor.  It is now a structure that holds the integer file
 33828  ** descriptor and a pointer to a structure that describes the internal
 33829  ** locks on the corresponding inode.  There is one locking structure
 33830  ** per inode, so if the same inode is opened twice, both unixFile structures
 33831  ** point to the same locking structure.  The locking structure keeps
 33832  ** a reference count (so we will know when to delete it) and a "cnt"
 33833  ** field that tells us its internal lock status.  cnt==0 means the
 33834  ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
 33835  ** cnt>0 means there are cnt shared locks on the file.
 33836  **
 33837  ** Any attempt to lock or unlock a file first checks the locking
 33838  ** structure.  The fcntl() system call is only invoked to set a 
 33839  ** POSIX lock if the internal lock structure transitions between
 33840  ** a locked and an unlocked state.
 33841  **
 33842  ** But wait:  there are yet more problems with POSIX advisory locks.
 33843  **
 33844  ** If you close a file descriptor that points to a file that has locks,
 33845  ** all locks on that file that are owned by the current process are
 33846  ** released.  To work around this problem, each unixInodeInfo object
 33847  ** maintains a count of the number of pending locks on tha inode.
 33848  ** When an attempt is made to close an unixFile, if there are
 33849  ** other unixFile open on the same inode that are holding locks, the call
 33850  ** to close() the file descriptor is deferred until all of the locks clear.
 33851  ** The unixInodeInfo structure keeps a list of file descriptors that need to
 33852  ** be closed and that list is walked (and cleared) when the last lock
 33853  ** clears.
 33854  **
 33855  ** Yet another problem:  LinuxThreads do not play well with posix locks.
 33856  **
 33857  ** Many older versions of linux use the LinuxThreads library which is
 33858  ** not posix compliant.  Under LinuxThreads, a lock created by thread
 33859  ** A cannot be modified or overridden by a different thread B.
 33860  ** Only thread A can modify the lock.  Locking behavior is correct
 33861  ** if the appliation uses the newer Native Posix Thread Library (NPTL)
 33862  ** on linux - with NPTL a lock created by thread A can override locks
 33863  ** in thread B.  But there is no way to know at compile-time which
 33864  ** threading library is being used.  So there is no way to know at
 33865  ** compile-time whether or not thread A can override locks on thread B.
 33866  ** One has to do a run-time check to discover the behavior of the
 33867  ** current process.
 33868  **
 33869  ** SQLite used to support LinuxThreads.  But support for LinuxThreads
 33870  ** was dropped beginning with version 3.7.0.  SQLite will still work with
 33871  ** LinuxThreads provided that (1) there is no more than one connection 
 33872  ** per database file in the same process and (2) database connections
 33873  ** do not move across threads.
 33874  */
 33875  
 33876  /*
 33877  ** An instance of the following structure serves as the key used
 33878  ** to locate a particular unixInodeInfo object.
 33879  */
 33880  struct unixFileId {
 33881    dev_t dev;                  /* Device number */
 33882  #if OS_VXWORKS
 33883    struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
 33884  #else
 33885    /* We are told that some versions of Android contain a bug that
 33886    ** sizes ino_t at only 32-bits instead of 64-bits. (See
 33887    ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
 33888    ** To work around this, always allocate 64-bits for the inode number.  
 33889    ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
 33890    ** but that should not be a big deal. */
 33891    /* WAS:  ino_t ino;   */
 33892    u64 ino;                   /* Inode number */
 33893  #endif
 33894  };
 33895  
 33896  /*
 33897  ** An instance of the following structure is allocated for each open
 33898  ** inode.
 33899  **
 33900  ** A single inode can have multiple file descriptors, so each unixFile
 33901  ** structure contains a pointer to an instance of this object and this
 33902  ** object keeps a count of the number of unixFile pointing to it.
 33903  **
 33904  ** Mutex rules:
 33905  **
 33906  **  (1) Only the pLockMutex mutex must be held in order to read or write
 33907  **      any of the locking fields:
 33908  **          nShared, nLock, eFileLock, bProcessLock, pUnused
 33909  **
 33910  **  (2) When nRef>0, then the following fields are unchanging and can
 33911  **      be read (but not written) without holding any mutex:
 33912  **          fileId, pLockMutex
 33913  **
 33914  **  (3) With the exceptions above, all the fields may only be read
 33915  **      or written while holding the global unixBigLock mutex.
 33916  **
 33917  ** Deadlock prevention:  The global unixBigLock mutex may not
 33918  ** be acquired while holding the pLockMutex mutex.  If both unixBigLock
 33919  ** and pLockMutex are needed, then unixBigLock must be acquired first.
 33920  */
 33921  struct unixInodeInfo {
 33922    struct unixFileId fileId;       /* The lookup key */
 33923    sqlite3_mutex *pLockMutex;      /* Hold this mutex for... */
 33924    int nShared;                      /* Number of SHARED locks held */
 33925    int nLock;                        /* Number of outstanding file locks */
 33926    unsigned char eFileLock;          /* One of SHARED_LOCK, RESERVED_LOCK etc. */
 33927    unsigned char bProcessLock;       /* An exclusive process lock is held */
 33928    UnixUnusedFd *pUnused;            /* Unused file descriptors to close */
 33929    int nRef;                       /* Number of pointers to this structure */
 33930    unixShmNode *pShmNode;          /* Shared memory associated with this inode */
 33931    unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
 33932    unixInodeInfo *pPrev;           /*    .... doubly linked */
 33933  #if SQLITE_ENABLE_LOCKING_STYLE
 33934    unsigned long long sharedByte;  /* for AFP simulated shared lock */
 33935  #endif
 33936  #if OS_VXWORKS
 33937    sem_t *pSem;                    /* Named POSIX semaphore */
 33938    char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
 33939  #endif
 33940  };
 33941  
 33942  /*
 33943  ** A lists of all unixInodeInfo objects.
 33944  **
 33945  ** Must hold unixBigLock in order to read or write this variable.
 33946  */
 33947  static unixInodeInfo *inodeList = 0;  /* All unixInodeInfo objects */
 33948  
 33949  #ifdef SQLITE_DEBUG
 33950  /*
 33951  ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
 33952  ** This routine is used only within assert() to help verify correct mutex
 33953  ** usage.
 33954  */
 33955  int unixFileMutexHeld(unixFile *pFile){
 33956    assert( pFile->pInode );
 33957    return sqlite3_mutex_held(pFile->pInode->pLockMutex);
 33958  }
 33959  int unixFileMutexNotheld(unixFile *pFile){
 33960    assert( pFile->pInode );
 33961    return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
 33962  }
 33963  #endif
 33964  
 33965  /*
 33966  **
 33967  ** This function - unixLogErrorAtLine(), is only ever called via the macro
 33968  ** unixLogError().
 33969  **
 33970  ** It is invoked after an error occurs in an OS function and errno has been
 33971  ** set. It logs a message using sqlite3_log() containing the current value of
 33972  ** errno and, if possible, the human-readable equivalent from strerror() or
 33973  ** strerror_r().
 33974  **
 33975  ** The first argument passed to the macro should be the error code that
 33976  ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
 33977  ** The two subsequent arguments should be the name of the OS function that
 33978  ** failed (e.g. "unlink", "open") and the associated file-system path,
 33979  ** if any.
 33980  */
 33981  #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
 33982  static int unixLogErrorAtLine(
 33983    int errcode,                    /* SQLite error code */
 33984    const char *zFunc,              /* Name of OS function that failed */
 33985    const char *zPath,              /* File path associated with error */
 33986    int iLine                       /* Source line number where error occurred */
 33987  ){
 33988    char *zErr;                     /* Message from strerror() or equivalent */
 33989    int iErrno = errno;             /* Saved syscall error number */
 33990  
 33991    /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
 33992    ** the strerror() function to obtain the human-readable error message
 33993    ** equivalent to errno. Otherwise, use strerror_r().
 33994    */ 
 33995  #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
 33996    char aErr[80];
 33997    memset(aErr, 0, sizeof(aErr));
 33998    zErr = aErr;
 33999  
 34000    /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
 34001    ** assume that the system provides the GNU version of strerror_r() that
 34002    ** returns a pointer to a buffer containing the error message. That pointer 
 34003    ** may point to aErr[], or it may point to some static storage somewhere. 
 34004    ** Otherwise, assume that the system provides the POSIX version of 
 34005    ** strerror_r(), which always writes an error message into aErr[].
 34006    **
 34007    ** If the code incorrectly assumes that it is the POSIX version that is
 34008    ** available, the error message will often be an empty string. Not a
 34009    ** huge problem. Incorrectly concluding that the GNU version is available 
 34010    ** could lead to a segfault though.
 34011    */
 34012  #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
 34013    zErr = 
 34014  # endif
 34015    strerror_r(iErrno, aErr, sizeof(aErr)-1);
 34016  
 34017  #elif SQLITE_THREADSAFE
 34018    /* This is a threadsafe build, but strerror_r() is not available. */
 34019    zErr = "";
 34020  #else
 34021    /* Non-threadsafe build, use strerror(). */
 34022    zErr = strerror(iErrno);
 34023  #endif
 34024  
 34025    if( zPath==0 ) zPath = "";
 34026    sqlite3_log(errcode,
 34027        "os_unix.c:%d: (%d) %s(%s) - %s",
 34028        iLine, iErrno, zFunc, zPath, zErr
 34029    );
 34030  
 34031    return errcode;
 34032  }
 34033  
 34034  /*
 34035  ** Close a file descriptor.
 34036  **
 34037  ** We assume that close() almost always works, since it is only in a
 34038  ** very sick application or on a very sick platform that it might fail.
 34039  ** If it does fail, simply leak the file descriptor, but do log the
 34040  ** error.
 34041  **
 34042  ** Note that it is not safe to retry close() after EINTR since the
 34043  ** file descriptor might have already been reused by another thread.
 34044  ** So we don't even try to recover from an EINTR.  Just log the error
 34045  ** and move on.
 34046  */
 34047  static void robust_close(unixFile *pFile, int h, int lineno){
 34048    if( osClose(h) ){
 34049      unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
 34050                         pFile ? pFile->zPath : 0, lineno);
 34051    }
 34052  }
 34053  
 34054  /*
 34055  ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
 34056  ** a convenient place to set a breakpoint.
 34057  */
 34058  static void storeLastErrno(unixFile *pFile, int error){
 34059    pFile->lastErrno = error;
 34060  }
 34061  
 34062  /*
 34063  ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
 34064  */ 
 34065  static void closePendingFds(unixFile *pFile){
 34066    unixInodeInfo *pInode = pFile->pInode;
 34067    UnixUnusedFd *p;
 34068    UnixUnusedFd *pNext;
 34069    assert( unixFileMutexHeld(pFile) );
 34070    for(p=pInode->pUnused; p; p=pNext){
 34071      pNext = p->pNext;
 34072      robust_close(pFile, p->fd, __LINE__);
 34073      sqlite3_free(p);
 34074    }
 34075    pInode->pUnused = 0;
 34076  }
 34077  
 34078  /*
 34079  ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
 34080  **
 34081  ** The global mutex must be held when this routine is called, but the mutex
 34082  ** on the inode being deleted must NOT be held.
 34083  */
 34084  static void releaseInodeInfo(unixFile *pFile){
 34085    unixInodeInfo *pInode = pFile->pInode;
 34086    assert( unixMutexHeld() );
 34087    assert( unixFileMutexNotheld(pFile) );
 34088    if( ALWAYS(pInode) ){
 34089      pInode->nRef--;
 34090      if( pInode->nRef==0 ){
 34091        assert( pInode->pShmNode==0 );
 34092        sqlite3_mutex_enter(pInode->pLockMutex);
 34093        closePendingFds(pFile);
 34094        sqlite3_mutex_leave(pInode->pLockMutex);
 34095        if( pInode->pPrev ){
 34096          assert( pInode->pPrev->pNext==pInode );
 34097          pInode->pPrev->pNext = pInode->pNext;
 34098        }else{
 34099          assert( inodeList==pInode );
 34100          inodeList = pInode->pNext;
 34101        }
 34102        if( pInode->pNext ){
 34103          assert( pInode->pNext->pPrev==pInode );
 34104          pInode->pNext->pPrev = pInode->pPrev;
 34105        }
 34106        sqlite3_mutex_free(pInode->pLockMutex);
 34107        sqlite3_free(pInode);
 34108      }
 34109    }
 34110  }
 34111  
 34112  /*
 34113  ** Given a file descriptor, locate the unixInodeInfo object that
 34114  ** describes that file descriptor.  Create a new one if necessary.  The
 34115  ** return value might be uninitialized if an error occurs.
 34116  **
 34117  ** The global mutex must held when calling this routine.
 34118  **
 34119  ** Return an appropriate error code.
 34120  */
 34121  static int findInodeInfo(
 34122    unixFile *pFile,               /* Unix file with file desc used in the key */
 34123    unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
 34124  ){
 34125    int rc;                        /* System call return code */
 34126    int fd;                        /* The file descriptor for pFile */
 34127    struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
 34128    struct stat statbuf;           /* Low-level file information */
 34129    unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
 34130  
 34131    assert( unixMutexHeld() );
 34132  
 34133    /* Get low-level information about the file that we can used to
 34134    ** create a unique name for the file.
 34135    */
 34136    fd = pFile->h;
 34137    rc = osFstat(fd, &statbuf);
 34138    if( rc!=0 ){
 34139      storeLastErrno(pFile, errno);
 34140  #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
 34141      if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
 34142  #endif
 34143      return SQLITE_IOERR;
 34144    }
 34145  
 34146  #ifdef __APPLE__
 34147    /* On OS X on an msdos filesystem, the inode number is reported
 34148    ** incorrectly for zero-size files.  See ticket #3260.  To work
 34149    ** around this problem (we consider it a bug in OS X, not SQLite)
 34150    ** we always increase the file size to 1 by writing a single byte
 34151    ** prior to accessing the inode number.  The one byte written is
 34152    ** an ASCII 'S' character which also happens to be the first byte
 34153    ** in the header of every SQLite database.  In this way, if there
 34154    ** is a race condition such that another thread has already populated
 34155    ** the first page of the database, no damage is done.
 34156    */
 34157    if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
 34158      do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
 34159      if( rc!=1 ){
 34160        storeLastErrno(pFile, errno);
 34161        return SQLITE_IOERR;
 34162      }
 34163      rc = osFstat(fd, &statbuf);
 34164      if( rc!=0 ){
 34165        storeLastErrno(pFile, errno);
 34166        return SQLITE_IOERR;
 34167      }
 34168    }
 34169  #endif
 34170  
 34171    memset(&fileId, 0, sizeof(fileId));
 34172    fileId.dev = statbuf.st_dev;
 34173  #if OS_VXWORKS
 34174    fileId.pId = pFile->pId;
 34175  #else
 34176    fileId.ino = (u64)statbuf.st_ino;
 34177  #endif
 34178    assert( unixMutexHeld() );
 34179    pInode = inodeList;
 34180    while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
 34181      pInode = pInode->pNext;
 34182    }
 34183    if( pInode==0 ){
 34184      pInode = sqlite3_malloc64( sizeof(*pInode) );
 34185      if( pInode==0 ){
 34186        return SQLITE_NOMEM_BKPT;
 34187      }
 34188      memset(pInode, 0, sizeof(*pInode));
 34189      memcpy(&pInode->fileId, &fileId, sizeof(fileId));
 34190      if( sqlite3GlobalConfig.bCoreMutex ){
 34191        pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 34192        if( pInode->pLockMutex==0 ){
 34193          sqlite3_free(pInode);
 34194          return SQLITE_NOMEM_BKPT;
 34195        }
 34196      }
 34197      pInode->nRef = 1;
 34198      assert( unixMutexHeld() );
 34199      pInode->pNext = inodeList;
 34200      pInode->pPrev = 0;
 34201      if( inodeList ) inodeList->pPrev = pInode;
 34202      inodeList = pInode;
 34203    }else{
 34204      pInode->nRef++;
 34205    }
 34206    *ppInode = pInode;
 34207    return SQLITE_OK;
 34208  }
 34209  
 34210  /*
 34211  ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
 34212  */
 34213  static int fileHasMoved(unixFile *pFile){
 34214  #if OS_VXWORKS
 34215    return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
 34216  #else
 34217    struct stat buf;
 34218    return pFile->pInode!=0 &&
 34219        (osStat(pFile->zPath, &buf)!=0 
 34220           || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
 34221  #endif
 34222  }
 34223  
 34224  
 34225  /*
 34226  ** Check a unixFile that is a database.  Verify the following:
 34227  **
 34228  ** (1) There is exactly one hard link on the file
 34229  ** (2) The file is not a symbolic link
 34230  ** (3) The file has not been renamed or unlinked
 34231  **
 34232  ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
 34233  */
 34234  static void verifyDbFile(unixFile *pFile){
 34235    struct stat buf;
 34236    int rc;
 34237  
 34238    /* These verifications occurs for the main database only */
 34239    if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
 34240  
 34241    rc = osFstat(pFile->h, &buf);
 34242    if( rc!=0 ){
 34243      sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
 34244      return;
 34245    }
 34246    if( buf.st_nlink==0 ){
 34247      sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
 34248      return;
 34249    }
 34250    if( buf.st_nlink>1 ){
 34251      sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
 34252      return;
 34253    }
 34254    if( fileHasMoved(pFile) ){
 34255      sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
 34256      return;
 34257    }
 34258  }
 34259  
 34260  
 34261  /*
 34262  ** This routine checks if there is a RESERVED lock held on the specified
 34263  ** file by this or any other process. If such a lock is held, set *pResOut
 34264  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 34265  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 34266  */
 34267  static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
 34268    int rc = SQLITE_OK;
 34269    int reserved = 0;
 34270    unixFile *pFile = (unixFile*)id;
 34271  
 34272    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 34273  
 34274    assert( pFile );
 34275    assert( pFile->eFileLock<=SHARED_LOCK );
 34276    sqlite3_mutex_enter(pFile->pInode->pLockMutex);
 34277  
 34278    /* Check if a thread in this process holds such a lock */
 34279    if( pFile->pInode->eFileLock>SHARED_LOCK ){
 34280      reserved = 1;
 34281    }
 34282  
 34283    /* Otherwise see if some other process holds it.
 34284    */
 34285  #ifndef __DJGPP__
 34286    if( !reserved && !pFile->pInode->bProcessLock ){
 34287      struct flock lock;
 34288      lock.l_whence = SEEK_SET;
 34289      lock.l_start = RESERVED_BYTE;
 34290      lock.l_len = 1;
 34291      lock.l_type = F_WRLCK;
 34292      if( osFcntl(pFile->h, F_GETLK, &lock) ){
 34293        rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
 34294        storeLastErrno(pFile, errno);
 34295      } else if( lock.l_type!=F_UNLCK ){
 34296        reserved = 1;
 34297      }
 34298    }
 34299  #endif
 34300    
 34301    sqlite3_mutex_leave(pFile->pInode->pLockMutex);
 34302    OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
 34303  
 34304    *pResOut = reserved;
 34305    return rc;
 34306  }
 34307  
 34308  /*
 34309  ** Set a posix-advisory-lock.
 34310  **
 34311  ** There are two versions of this routine.  If compiled with
 34312  ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
 34313  ** which is a pointer to a unixFile.  If the unixFile->iBusyTimeout
 34314  ** value is set, then it is the number of milliseconds to wait before
 34315  ** failing the lock.  The iBusyTimeout value is always reset back to
 34316  ** zero on each call.
 34317  **
 34318  ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
 34319  ** attempt to set the lock.
 34320  */
 34321  #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
 34322  # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
 34323  #else
 34324  static int osSetPosixAdvisoryLock(
 34325    int h,                /* The file descriptor on which to take the lock */
 34326    struct flock *pLock,  /* The description of the lock */
 34327    unixFile *pFile       /* Structure holding timeout value */
 34328  ){
 34329    int rc = osFcntl(h,F_SETLK,pLock);
 34330    while( rc<0 && pFile->iBusyTimeout>0 ){
 34331      /* On systems that support some kind of blocking file lock with a timeout,
 34332      ** make appropriate changes here to invoke that blocking file lock.  On
 34333      ** generic posix, however, there is no such API.  So we simply try the
 34334      ** lock once every millisecond until either the timeout expires, or until
 34335      ** the lock is obtained. */
 34336      usleep(1000);
 34337      rc = osFcntl(h,F_SETLK,pLock);
 34338      pFile->iBusyTimeout--;
 34339    }
 34340    return rc;
 34341  }
 34342  #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
 34343  
 34344  
 34345  /*
 34346  ** Attempt to set a system-lock on the file pFile.  The lock is 
 34347  ** described by pLock.
 34348  **
 34349  ** If the pFile was opened read/write from unix-excl, then the only lock
 34350  ** ever obtained is an exclusive lock, and it is obtained exactly once
 34351  ** the first time any lock is attempted.  All subsequent system locking
 34352  ** operations become no-ops.  Locking operations still happen internally,
 34353  ** in order to coordinate access between separate database connections
 34354  ** within this process, but all of that is handled in memory and the
 34355  ** operating system does not participate.
 34356  **
 34357  ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
 34358  ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
 34359  ** and is read-only.
 34360  **
 34361  ** Zero is returned if the call completes successfully, or -1 if a call
 34362  ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
 34363  */
 34364  static int unixFileLock(unixFile *pFile, struct flock *pLock){
 34365    int rc;
 34366    unixInodeInfo *pInode = pFile->pInode;
 34367    assert( pInode!=0 );
 34368    assert( sqlite3_mutex_held(pInode->pLockMutex) );
 34369    if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
 34370      if( pInode->bProcessLock==0 ){
 34371        struct flock lock;
 34372        assert( pInode->nLock==0 );
 34373        lock.l_whence = SEEK_SET;
 34374        lock.l_start = SHARED_FIRST;
 34375        lock.l_len = SHARED_SIZE;
 34376        lock.l_type = F_WRLCK;
 34377        rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
 34378        if( rc<0 ) return rc;
 34379        pInode->bProcessLock = 1;
 34380        pInode->nLock++;
 34381      }else{
 34382        rc = 0;
 34383      }
 34384    }else{
 34385      rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
 34386    }
 34387    return rc;
 34388  }
 34389  
 34390  /*
 34391  ** Lock the file with the lock specified by parameter eFileLock - one
 34392  ** of the following:
 34393  **
 34394  **     (1) SHARED_LOCK
 34395  **     (2) RESERVED_LOCK
 34396  **     (3) PENDING_LOCK
 34397  **     (4) EXCLUSIVE_LOCK
 34398  **
 34399  ** Sometimes when requesting one lock state, additional lock states
 34400  ** are inserted in between.  The locking might fail on one of the later
 34401  ** transitions leaving the lock state different from what it started but
 34402  ** still short of its goal.  The following chart shows the allowed
 34403  ** transitions and the inserted intermediate states:
 34404  **
 34405  **    UNLOCKED -> SHARED
 34406  **    SHARED -> RESERVED
 34407  **    SHARED -> (PENDING) -> EXCLUSIVE
 34408  **    RESERVED -> (PENDING) -> EXCLUSIVE
 34409  **    PENDING -> EXCLUSIVE
 34410  **
 34411  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 34412  ** routine to lower a locking level.
 34413  */
 34414  static int unixLock(sqlite3_file *id, int eFileLock){
 34415    /* The following describes the implementation of the various locks and
 34416    ** lock transitions in terms of the POSIX advisory shared and exclusive
 34417    ** lock primitives (called read-locks and write-locks below, to avoid
 34418    ** confusion with SQLite lock names). The algorithms are complicated
 34419    ** slightly in order to be compatible with Windows95 systems simultaneously
 34420    ** accessing the same database file, in case that is ever required.
 34421    **
 34422    ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
 34423    ** byte', each single bytes at well known offsets, and the 'shared byte
 34424    ** range', a range of 510 bytes at a well known offset.
 34425    **
 34426    ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
 34427    ** byte'.  If this is successful, 'shared byte range' is read-locked
 34428    ** and the lock on the 'pending byte' released.  (Legacy note:  When
 34429    ** SQLite was first developed, Windows95 systems were still very common,
 34430    ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
 34431    ** single randomly selected by from the 'shared byte range' is locked.
 34432    ** Windows95 is now pretty much extinct, but this work-around for the
 34433    ** lack of shared-locks on Windows95 lives on, for backwards
 34434    ** compatibility.)
 34435    **
 34436    ** A process may only obtain a RESERVED lock after it has a SHARED lock.
 34437    ** A RESERVED lock is implemented by grabbing a write-lock on the
 34438    ** 'reserved byte'. 
 34439    **
 34440    ** A process may only obtain a PENDING lock after it has obtained a
 34441    ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
 34442    ** on the 'pending byte'. This ensures that no new SHARED locks can be
 34443    ** obtained, but existing SHARED locks are allowed to persist. A process
 34444    ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
 34445    ** This property is used by the algorithm for rolling back a journal file
 34446    ** after a crash.
 34447    **
 34448    ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
 34449    ** implemented by obtaining a write-lock on the entire 'shared byte
 34450    ** range'. Since all other locks require a read-lock on one of the bytes
 34451    ** within this range, this ensures that no other locks are held on the
 34452    ** database. 
 34453    */
 34454    int rc = SQLITE_OK;
 34455    unixFile *pFile = (unixFile*)id;
 34456    unixInodeInfo *pInode;
 34457    struct flock lock;
 34458    int tErrno = 0;
 34459  
 34460    assert( pFile );
 34461    OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
 34462        azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 34463        azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
 34464        osGetpid(0)));
 34465  
 34466    /* If there is already a lock of this type or more restrictive on the
 34467    ** unixFile, do nothing. Don't use the end_lock: exit path, as
 34468    ** unixEnterMutex() hasn't been called yet.
 34469    */
 34470    if( pFile->eFileLock>=eFileLock ){
 34471      OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
 34472              azFileLock(eFileLock)));
 34473      return SQLITE_OK;
 34474    }
 34475  
 34476    /* Make sure the locking sequence is correct.
 34477    **  (1) We never move from unlocked to anything higher than shared lock.
 34478    **  (2) SQLite never explicitly requests a pendig lock.
 34479    **  (3) A shared lock is always held when a reserve lock is requested.
 34480    */
 34481    assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 34482    assert( eFileLock!=PENDING_LOCK );
 34483    assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 34484  
 34485    /* This mutex is needed because pFile->pInode is shared across threads
 34486    */
 34487    pInode = pFile->pInode;
 34488    sqlite3_mutex_enter(pInode->pLockMutex);
 34489  
 34490    /* If some thread using this PID has a lock via a different unixFile*
 34491    ** handle that precludes the requested lock, return BUSY.
 34492    */
 34493    if( (pFile->eFileLock!=pInode->eFileLock && 
 34494            (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 34495    ){
 34496      rc = SQLITE_BUSY;
 34497      goto end_lock;
 34498    }
 34499  
 34500    /* If a SHARED lock is requested, and some thread using this PID already
 34501    ** has a SHARED or RESERVED lock, then increment reference counts and
 34502    ** return SQLITE_OK.
 34503    */
 34504    if( eFileLock==SHARED_LOCK && 
 34505        (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 34506      assert( eFileLock==SHARED_LOCK );
 34507      assert( pFile->eFileLock==0 );
 34508      assert( pInode->nShared>0 );
 34509      pFile->eFileLock = SHARED_LOCK;
 34510      pInode->nShared++;
 34511      pInode->nLock++;
 34512      goto end_lock;
 34513    }
 34514  
 34515  
 34516    /* A PENDING lock is needed before acquiring a SHARED lock and before
 34517    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 34518    ** be released.
 34519    */
 34520    lock.l_len = 1L;
 34521    lock.l_whence = SEEK_SET;
 34522    if( eFileLock==SHARED_LOCK 
 34523        || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 34524    ){
 34525      lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
 34526      lock.l_start = PENDING_BYTE;
 34527      if( unixFileLock(pFile, &lock) ){
 34528        tErrno = errno;
 34529        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 34530        if( rc!=SQLITE_BUSY ){
 34531          storeLastErrno(pFile, tErrno);
 34532        }
 34533        goto end_lock;
 34534      }
 34535    }
 34536  
 34537  
 34538    /* If control gets to this point, then actually go ahead and make
 34539    ** operating system calls for the specified lock.
 34540    */
 34541    if( eFileLock==SHARED_LOCK ){
 34542      assert( pInode->nShared==0 );
 34543      assert( pInode->eFileLock==0 );
 34544      assert( rc==SQLITE_OK );
 34545  
 34546      /* Now get the read-lock */
 34547      lock.l_start = SHARED_FIRST;
 34548      lock.l_len = SHARED_SIZE;
 34549      if( unixFileLock(pFile, &lock) ){
 34550        tErrno = errno;
 34551        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 34552      }
 34553  
 34554      /* Drop the temporary PENDING lock */
 34555      lock.l_start = PENDING_BYTE;
 34556      lock.l_len = 1L;
 34557      lock.l_type = F_UNLCK;
 34558      if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
 34559        /* This could happen with a network mount */
 34560        tErrno = errno;
 34561        rc = SQLITE_IOERR_UNLOCK; 
 34562      }
 34563  
 34564      if( rc ){
 34565        if( rc!=SQLITE_BUSY ){
 34566          storeLastErrno(pFile, tErrno);
 34567        }
 34568        goto end_lock;
 34569      }else{
 34570        pFile->eFileLock = SHARED_LOCK;
 34571        pInode->nLock++;
 34572        pInode->nShared = 1;
 34573      }
 34574    }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 34575      /* We are trying for an exclusive lock but another thread in this
 34576      ** same process is still holding a shared lock. */
 34577      rc = SQLITE_BUSY;
 34578    }else{
 34579      /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 34580      ** assumed that there is a SHARED or greater lock on the file
 34581      ** already.
 34582      */
 34583      assert( 0!=pFile->eFileLock );
 34584      lock.l_type = F_WRLCK;
 34585  
 34586      assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
 34587      if( eFileLock==RESERVED_LOCK ){
 34588        lock.l_start = RESERVED_BYTE;
 34589        lock.l_len = 1L;
 34590      }else{
 34591        lock.l_start = SHARED_FIRST;
 34592        lock.l_len = SHARED_SIZE;
 34593      }
 34594  
 34595      if( unixFileLock(pFile, &lock) ){
 34596        tErrno = errno;
 34597        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 34598        if( rc!=SQLITE_BUSY ){
 34599          storeLastErrno(pFile, tErrno);
 34600        }
 34601      }
 34602    }
 34603    
 34604  
 34605  #ifdef SQLITE_DEBUG
 34606    /* Set up the transaction-counter change checking flags when
 34607    ** transitioning from a SHARED to a RESERVED lock.  The change
 34608    ** from SHARED to RESERVED marks the beginning of a normal
 34609    ** write operation (not a hot journal rollback).
 34610    */
 34611    if( rc==SQLITE_OK
 34612     && pFile->eFileLock<=SHARED_LOCK
 34613     && eFileLock==RESERVED_LOCK
 34614    ){
 34615      pFile->transCntrChng = 0;
 34616      pFile->dbUpdate = 0;
 34617      pFile->inNormalWrite = 1;
 34618    }
 34619  #endif
 34620  
 34621  
 34622    if( rc==SQLITE_OK ){
 34623      pFile->eFileLock = eFileLock;
 34624      pInode->eFileLock = eFileLock;
 34625    }else if( eFileLock==EXCLUSIVE_LOCK ){
 34626      pFile->eFileLock = PENDING_LOCK;
 34627      pInode->eFileLock = PENDING_LOCK;
 34628    }
 34629  
 34630  end_lock:
 34631    sqlite3_mutex_leave(pInode->pLockMutex);
 34632    OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
 34633        rc==SQLITE_OK ? "ok" : "failed"));
 34634    return rc;
 34635  }
 34636  
 34637  /*
 34638  ** Add the file descriptor used by file handle pFile to the corresponding
 34639  ** pUnused list.
 34640  */
 34641  static void setPendingFd(unixFile *pFile){
 34642    unixInodeInfo *pInode = pFile->pInode;
 34643    UnixUnusedFd *p = pFile->pPreallocatedUnused;
 34644    assert( unixFileMutexHeld(pFile) );
 34645    p->pNext = pInode->pUnused;
 34646    pInode->pUnused = p;
 34647    pFile->h = -1;
 34648    pFile->pPreallocatedUnused = 0;
 34649  }
 34650  
 34651  /*
 34652  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 34653  ** must be either NO_LOCK or SHARED_LOCK.
 34654  **
 34655  ** If the locking level of the file descriptor is already at or below
 34656  ** the requested locking level, this routine is a no-op.
 34657  ** 
 34658  ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
 34659  ** the byte range is divided into 2 parts and the first part is unlocked then
 34660  ** set to a read lock, then the other part is simply unlocked.  This works 
 34661  ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
 34662  ** remove the write lock on a region when a read lock is set.
 34663  */
 34664  static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
 34665    unixFile *pFile = (unixFile*)id;
 34666    unixInodeInfo *pInode;
 34667    struct flock lock;
 34668    int rc = SQLITE_OK;
 34669  
 34670    assert( pFile );
 34671    OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
 34672        pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 34673        osGetpid(0)));
 34674  
 34675    assert( eFileLock<=SHARED_LOCK );
 34676    if( pFile->eFileLock<=eFileLock ){
 34677      return SQLITE_OK;
 34678    }
 34679    pInode = pFile->pInode;
 34680    sqlite3_mutex_enter(pInode->pLockMutex);
 34681    assert( pInode->nShared!=0 );
 34682    if( pFile->eFileLock>SHARED_LOCK ){
 34683      assert( pInode->eFileLock==pFile->eFileLock );
 34684  
 34685  #ifdef SQLITE_DEBUG
 34686      /* When reducing a lock such that other processes can start
 34687      ** reading the database file again, make sure that the
 34688      ** transaction counter was updated if any part of the database
 34689      ** file changed.  If the transaction counter is not updated,
 34690      ** other connections to the same file might not realize that
 34691      ** the file has changed and hence might not know to flush their
 34692      ** cache.  The use of a stale cache can lead to database corruption.
 34693      */
 34694      pFile->inNormalWrite = 0;
 34695  #endif
 34696  
 34697      /* downgrading to a shared lock on NFS involves clearing the write lock
 34698      ** before establishing the readlock - to avoid a race condition we downgrade
 34699      ** the lock in 2 blocks, so that part of the range will be covered by a 
 34700      ** write lock until the rest is covered by a read lock:
 34701      **  1:   [WWWWW]
 34702      **  2:   [....W]
 34703      **  3:   [RRRRW]
 34704      **  4:   [RRRR.]
 34705      */
 34706      if( eFileLock==SHARED_LOCK ){
 34707  #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
 34708        (void)handleNFSUnlock;
 34709        assert( handleNFSUnlock==0 );
 34710  #endif
 34711  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 34712        if( handleNFSUnlock ){
 34713          int tErrno;               /* Error code from system call errors */
 34714          off_t divSize = SHARED_SIZE - 1;
 34715          
 34716          lock.l_type = F_UNLCK;
 34717          lock.l_whence = SEEK_SET;
 34718          lock.l_start = SHARED_FIRST;
 34719          lock.l_len = divSize;
 34720          if( unixFileLock(pFile, &lock)==(-1) ){
 34721            tErrno = errno;
 34722            rc = SQLITE_IOERR_UNLOCK;
 34723            storeLastErrno(pFile, tErrno);
 34724            goto end_unlock;
 34725          }
 34726          lock.l_type = F_RDLCK;
 34727          lock.l_whence = SEEK_SET;
 34728          lock.l_start = SHARED_FIRST;
 34729          lock.l_len = divSize;
 34730          if( unixFileLock(pFile, &lock)==(-1) ){
 34731            tErrno = errno;
 34732            rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
 34733            if( IS_LOCK_ERROR(rc) ){
 34734              storeLastErrno(pFile, tErrno);
 34735            }
 34736            goto end_unlock;
 34737          }
 34738          lock.l_type = F_UNLCK;
 34739          lock.l_whence = SEEK_SET;
 34740          lock.l_start = SHARED_FIRST+divSize;
 34741          lock.l_len = SHARED_SIZE-divSize;
 34742          if( unixFileLock(pFile, &lock)==(-1) ){
 34743            tErrno = errno;
 34744            rc = SQLITE_IOERR_UNLOCK;
 34745            storeLastErrno(pFile, tErrno);
 34746            goto end_unlock;
 34747          }
 34748        }else
 34749  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 34750        {
 34751          lock.l_type = F_RDLCK;
 34752          lock.l_whence = SEEK_SET;
 34753          lock.l_start = SHARED_FIRST;
 34754          lock.l_len = SHARED_SIZE;
 34755          if( unixFileLock(pFile, &lock) ){
 34756            /* In theory, the call to unixFileLock() cannot fail because another
 34757            ** process is holding an incompatible lock. If it does, this 
 34758            ** indicates that the other process is not following the locking
 34759            ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
 34760            ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
 34761            ** an assert to fail). */ 
 34762            rc = SQLITE_IOERR_RDLOCK;
 34763            storeLastErrno(pFile, errno);
 34764            goto end_unlock;
 34765          }
 34766        }
 34767      }
 34768      lock.l_type = F_UNLCK;
 34769      lock.l_whence = SEEK_SET;
 34770      lock.l_start = PENDING_BYTE;
 34771      lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
 34772      if( unixFileLock(pFile, &lock)==0 ){
 34773        pInode->eFileLock = SHARED_LOCK;
 34774      }else{
 34775        rc = SQLITE_IOERR_UNLOCK;
 34776        storeLastErrno(pFile, errno);
 34777        goto end_unlock;
 34778      }
 34779    }
 34780    if( eFileLock==NO_LOCK ){
 34781      /* Decrement the shared lock counter.  Release the lock using an
 34782      ** OS call only when all threads in this same process have released
 34783      ** the lock.
 34784      */
 34785      pInode->nShared--;
 34786      if( pInode->nShared==0 ){
 34787        lock.l_type = F_UNLCK;
 34788        lock.l_whence = SEEK_SET;
 34789        lock.l_start = lock.l_len = 0L;
 34790        if( unixFileLock(pFile, &lock)==0 ){
 34791          pInode->eFileLock = NO_LOCK;
 34792        }else{
 34793          rc = SQLITE_IOERR_UNLOCK;
 34794          storeLastErrno(pFile, errno);
 34795          pInode->eFileLock = NO_LOCK;
 34796          pFile->eFileLock = NO_LOCK;
 34797        }
 34798      }
 34799  
 34800      /* Decrement the count of locks against this same file.  When the
 34801      ** count reaches zero, close any other file descriptors whose close
 34802      ** was deferred because of outstanding locks.
 34803      */
 34804      pInode->nLock--;
 34805      assert( pInode->nLock>=0 );
 34806      if( pInode->nLock==0 ) closePendingFds(pFile);
 34807    }
 34808  
 34809  end_unlock:
 34810    sqlite3_mutex_leave(pInode->pLockMutex);
 34811    if( rc==SQLITE_OK ){
 34812      pFile->eFileLock = eFileLock;
 34813    }
 34814    return rc;
 34815  }
 34816  
 34817  /*
 34818  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 34819  ** must be either NO_LOCK or SHARED_LOCK.
 34820  **
 34821  ** If the locking level of the file descriptor is already at or below
 34822  ** the requested locking level, this routine is a no-op.
 34823  */
 34824  static int unixUnlock(sqlite3_file *id, int eFileLock){
 34825  #if SQLITE_MAX_MMAP_SIZE>0
 34826    assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
 34827  #endif
 34828    return posixUnlock(id, eFileLock, 0);
 34829  }
 34830  
 34831  #if SQLITE_MAX_MMAP_SIZE>0
 34832  static int unixMapfile(unixFile *pFd, i64 nByte);
 34833  static void unixUnmapfile(unixFile *pFd);
 34834  #endif
 34835  
 34836  /*
 34837  ** This function performs the parts of the "close file" operation 
 34838  ** common to all locking schemes. It closes the directory and file
 34839  ** handles, if they are valid, and sets all fields of the unixFile
 34840  ** structure to 0.
 34841  **
 34842  ** It is *not* necessary to hold the mutex when this routine is called,
 34843  ** even on VxWorks.  A mutex will be acquired on VxWorks by the
 34844  ** vxworksReleaseFileId() routine.
 34845  */
 34846  static int closeUnixFile(sqlite3_file *id){
 34847    unixFile *pFile = (unixFile*)id;
 34848  #if SQLITE_MAX_MMAP_SIZE>0
 34849    unixUnmapfile(pFile);
 34850  #endif
 34851    if( pFile->h>=0 ){
 34852      robust_close(pFile, pFile->h, __LINE__);
 34853      pFile->h = -1;
 34854    }
 34855  #if OS_VXWORKS
 34856    if( pFile->pId ){
 34857      if( pFile->ctrlFlags & UNIXFILE_DELETE ){
 34858        osUnlink(pFile->pId->zCanonicalName);
 34859      }
 34860      vxworksReleaseFileId(pFile->pId);
 34861      pFile->pId = 0;
 34862    }
 34863  #endif
 34864  #ifdef SQLITE_UNLINK_AFTER_CLOSE
 34865    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
 34866      osUnlink(pFile->zPath);
 34867      sqlite3_free(*(char**)&pFile->zPath);
 34868      pFile->zPath = 0;
 34869    }
 34870  #endif
 34871    OSTRACE(("CLOSE   %-3d\n", pFile->h));
 34872    OpenCounter(-1);
 34873    sqlite3_free(pFile->pPreallocatedUnused);
 34874    memset(pFile, 0, sizeof(unixFile));
 34875    return SQLITE_OK;
 34876  }
 34877  
 34878  /*
 34879  ** Close a file.
 34880  */
 34881  static int unixClose(sqlite3_file *id){
 34882    int rc = SQLITE_OK;
 34883    unixFile *pFile = (unixFile *)id;
 34884    unixInodeInfo *pInode = pFile->pInode;
 34885  
 34886    assert( pInode!=0 );
 34887    verifyDbFile(pFile);
 34888    unixUnlock(id, NO_LOCK);
 34889    assert( unixFileMutexNotheld(pFile) );
 34890    unixEnterMutex();
 34891  
 34892    /* unixFile.pInode is always valid here. Otherwise, a different close
 34893    ** routine (e.g. nolockClose()) would be called instead.
 34894    */
 34895    assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
 34896    sqlite3_mutex_enter(pInode->pLockMutex);
 34897    if( pInode->nLock ){
 34898      /* If there are outstanding locks, do not actually close the file just
 34899      ** yet because that would clear those locks.  Instead, add the file
 34900      ** descriptor to pInode->pUnused list.  It will be automatically closed 
 34901      ** when the last lock is cleared.
 34902      */
 34903      setPendingFd(pFile);
 34904    }
 34905    sqlite3_mutex_leave(pInode->pLockMutex);
 34906    releaseInodeInfo(pFile);
 34907    rc = closeUnixFile(id);
 34908    unixLeaveMutex();
 34909    return rc;
 34910  }
 34911  
 34912  /************** End of the posix advisory lock implementation *****************
 34913  ******************************************************************************/
 34914  
 34915  /******************************************************************************
 34916  ****************************** No-op Locking **********************************
 34917  **
 34918  ** Of the various locking implementations available, this is by far the
 34919  ** simplest:  locking is ignored.  No attempt is made to lock the database
 34920  ** file for reading or writing.
 34921  **
 34922  ** This locking mode is appropriate for use on read-only databases
 34923  ** (ex: databases that are burned into CD-ROM, for example.)  It can
 34924  ** also be used if the application employs some external mechanism to
 34925  ** prevent simultaneous access of the same database by two or more
 34926  ** database connections.  But there is a serious risk of database
 34927  ** corruption if this locking mode is used in situations where multiple
 34928  ** database connections are accessing the same database file at the same
 34929  ** time and one or more of those connections are writing.
 34930  */
 34931  
 34932  static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
 34933    UNUSED_PARAMETER(NotUsed);
 34934    *pResOut = 0;
 34935    return SQLITE_OK;
 34936  }
 34937  static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
 34938    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 34939    return SQLITE_OK;
 34940  }
 34941  static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
 34942    UNUSED_PARAMETER2(NotUsed, NotUsed2);
 34943    return SQLITE_OK;
 34944  }
 34945  
 34946  /*
 34947  ** Close the file.
 34948  */
 34949  static int nolockClose(sqlite3_file *id) {
 34950    return closeUnixFile(id);
 34951  }
 34952  
 34953  /******************* End of the no-op lock implementation *********************
 34954  ******************************************************************************/
 34955  
 34956  /******************************************************************************
 34957  ************************* Begin dot-file Locking ******************************
 34958  **
 34959  ** The dotfile locking implementation uses the existence of separate lock
 34960  ** files (really a directory) to control access to the database.  This works
 34961  ** on just about every filesystem imaginable.  But there are serious downsides:
 34962  **
 34963  **    (1)  There is zero concurrency.  A single reader blocks all other
 34964  **         connections from reading or writing the database.
 34965  **
 34966  **    (2)  An application crash or power loss can leave stale lock files
 34967  **         sitting around that need to be cleared manually.
 34968  **
 34969  ** Nevertheless, a dotlock is an appropriate locking mode for use if no
 34970  ** other locking strategy is available.
 34971  **
 34972  ** Dotfile locking works by creating a subdirectory in the same directory as
 34973  ** the database and with the same name but with a ".lock" extension added.
 34974  ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
 34975  ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
 34976  */
 34977  
 34978  /*
 34979  ** The file suffix added to the data base filename in order to create the
 34980  ** lock directory.
 34981  */
 34982  #define DOTLOCK_SUFFIX ".lock"
 34983  
 34984  /*
 34985  ** This routine checks if there is a RESERVED lock held on the specified
 34986  ** file by this or any other process. If such a lock is held, set *pResOut
 34987  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 34988  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 34989  **
 34990  ** In dotfile locking, either a lock exists or it does not.  So in this
 34991  ** variation of CheckReservedLock(), *pResOut is set to true if any lock
 34992  ** is held on the file and false if the file is unlocked.
 34993  */
 34994  static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
 34995    int rc = SQLITE_OK;
 34996    int reserved = 0;
 34997    unixFile *pFile = (unixFile*)id;
 34998  
 34999    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 35000    
 35001    assert( pFile );
 35002    reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
 35003    OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
 35004    *pResOut = reserved;
 35005    return rc;
 35006  }
 35007  
 35008  /*
 35009  ** Lock the file with the lock specified by parameter eFileLock - one
 35010  ** of the following:
 35011  **
 35012  **     (1) SHARED_LOCK
 35013  **     (2) RESERVED_LOCK
 35014  **     (3) PENDING_LOCK
 35015  **     (4) EXCLUSIVE_LOCK
 35016  **
 35017  ** Sometimes when requesting one lock state, additional lock states
 35018  ** are inserted in between.  The locking might fail on one of the later
 35019  ** transitions leaving the lock state different from what it started but
 35020  ** still short of its goal.  The following chart shows the allowed
 35021  ** transitions and the inserted intermediate states:
 35022  **
 35023  **    UNLOCKED -> SHARED
 35024  **    SHARED -> RESERVED
 35025  **    SHARED -> (PENDING) -> EXCLUSIVE
 35026  **    RESERVED -> (PENDING) -> EXCLUSIVE
 35027  **    PENDING -> EXCLUSIVE
 35028  **
 35029  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 35030  ** routine to lower a locking level.
 35031  **
 35032  ** With dotfile locking, we really only support state (4): EXCLUSIVE.
 35033  ** But we track the other locking levels internally.
 35034  */
 35035  static int dotlockLock(sqlite3_file *id, int eFileLock) {
 35036    unixFile *pFile = (unixFile*)id;
 35037    char *zLockFile = (char *)pFile->lockingContext;
 35038    int rc = SQLITE_OK;
 35039  
 35040  
 35041    /* If we have any lock, then the lock file already exists.  All we have
 35042    ** to do is adjust our internal record of the lock level.
 35043    */
 35044    if( pFile->eFileLock > NO_LOCK ){
 35045      pFile->eFileLock = eFileLock;
 35046      /* Always update the timestamp on the old file */
 35047  #ifdef HAVE_UTIME
 35048      utime(zLockFile, NULL);
 35049  #else
 35050      utimes(zLockFile, NULL);
 35051  #endif
 35052      return SQLITE_OK;
 35053    }
 35054    
 35055    /* grab an exclusive lock */
 35056    rc = osMkdir(zLockFile, 0777);
 35057    if( rc<0 ){
 35058      /* failed to open/create the lock directory */
 35059      int tErrno = errno;
 35060      if( EEXIST == tErrno ){
 35061        rc = SQLITE_BUSY;
 35062      } else {
 35063        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 35064        if( rc!=SQLITE_BUSY ){
 35065          storeLastErrno(pFile, tErrno);
 35066        }
 35067      }
 35068      return rc;
 35069    } 
 35070    
 35071    /* got it, set the type and return ok */
 35072    pFile->eFileLock = eFileLock;
 35073    return rc;
 35074  }
 35075  
 35076  /*
 35077  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 35078  ** must be either NO_LOCK or SHARED_LOCK.
 35079  **
 35080  ** If the locking level of the file descriptor is already at or below
 35081  ** the requested locking level, this routine is a no-op.
 35082  **
 35083  ** When the locking level reaches NO_LOCK, delete the lock file.
 35084  */
 35085  static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
 35086    unixFile *pFile = (unixFile*)id;
 35087    char *zLockFile = (char *)pFile->lockingContext;
 35088    int rc;
 35089  
 35090    assert( pFile );
 35091    OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
 35092             pFile->eFileLock, osGetpid(0)));
 35093    assert( eFileLock<=SHARED_LOCK );
 35094    
 35095    /* no-op if possible */
 35096    if( pFile->eFileLock==eFileLock ){
 35097      return SQLITE_OK;
 35098    }
 35099  
 35100    /* To downgrade to shared, simply update our internal notion of the
 35101    ** lock state.  No need to mess with the file on disk.
 35102    */
 35103    if( eFileLock==SHARED_LOCK ){
 35104      pFile->eFileLock = SHARED_LOCK;
 35105      return SQLITE_OK;
 35106    }
 35107    
 35108    /* To fully unlock the database, delete the lock file */
 35109    assert( eFileLock==NO_LOCK );
 35110    rc = osRmdir(zLockFile);
 35111    if( rc<0 ){
 35112      int tErrno = errno;
 35113      if( tErrno==ENOENT ){
 35114        rc = SQLITE_OK;
 35115      }else{
 35116        rc = SQLITE_IOERR_UNLOCK;
 35117        storeLastErrno(pFile, tErrno);
 35118      }
 35119      return rc; 
 35120    }
 35121    pFile->eFileLock = NO_LOCK;
 35122    return SQLITE_OK;
 35123  }
 35124  
 35125  /*
 35126  ** Close a file.  Make sure the lock has been released before closing.
 35127  */
 35128  static int dotlockClose(sqlite3_file *id) {
 35129    unixFile *pFile = (unixFile*)id;
 35130    assert( id!=0 );
 35131    dotlockUnlock(id, NO_LOCK);
 35132    sqlite3_free(pFile->lockingContext);
 35133    return closeUnixFile(id);
 35134  }
 35135  /****************** End of the dot-file lock implementation *******************
 35136  ******************************************************************************/
 35137  
 35138  /******************************************************************************
 35139  ************************** Begin flock Locking ********************************
 35140  **
 35141  ** Use the flock() system call to do file locking.
 35142  **
 35143  ** flock() locking is like dot-file locking in that the various
 35144  ** fine-grain locking levels supported by SQLite are collapsed into
 35145  ** a single exclusive lock.  In other words, SHARED, RESERVED, and
 35146  ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
 35147  ** still works when you do this, but concurrency is reduced since
 35148  ** only a single process can be reading the database at a time.
 35149  **
 35150  ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
 35151  */
 35152  #if SQLITE_ENABLE_LOCKING_STYLE
 35153  
 35154  /*
 35155  ** Retry flock() calls that fail with EINTR
 35156  */
 35157  #ifdef EINTR
 35158  static int robust_flock(int fd, int op){
 35159    int rc;
 35160    do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
 35161    return rc;
 35162  }
 35163  #else
 35164  # define robust_flock(a,b) flock(a,b)
 35165  #endif
 35166       
 35167  
 35168  /*
 35169  ** This routine checks if there is a RESERVED lock held on the specified
 35170  ** file by this or any other process. If such a lock is held, set *pResOut
 35171  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 35172  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 35173  */
 35174  static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
 35175    int rc = SQLITE_OK;
 35176    int reserved = 0;
 35177    unixFile *pFile = (unixFile*)id;
 35178    
 35179    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 35180    
 35181    assert( pFile );
 35182    
 35183    /* Check if a thread in this process holds such a lock */
 35184    if( pFile->eFileLock>SHARED_LOCK ){
 35185      reserved = 1;
 35186    }
 35187    
 35188    /* Otherwise see if some other process holds it. */
 35189    if( !reserved ){
 35190      /* attempt to get the lock */
 35191      int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
 35192      if( !lrc ){
 35193        /* got the lock, unlock it */
 35194        lrc = robust_flock(pFile->h, LOCK_UN);
 35195        if ( lrc ) {
 35196          int tErrno = errno;
 35197          /* unlock failed with an error */
 35198          lrc = SQLITE_IOERR_UNLOCK; 
 35199          storeLastErrno(pFile, tErrno);
 35200          rc = lrc;
 35201        }
 35202      } else {
 35203        int tErrno = errno;
 35204        reserved = 1;
 35205        /* someone else might have it reserved */
 35206        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
 35207        if( IS_LOCK_ERROR(lrc) ){
 35208          storeLastErrno(pFile, tErrno);
 35209          rc = lrc;
 35210        }
 35211      }
 35212    }
 35213    OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
 35214  
 35215  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 35216    if( (rc & 0xff) == SQLITE_IOERR ){
 35217      rc = SQLITE_OK;
 35218      reserved=1;
 35219    }
 35220  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 35221    *pResOut = reserved;
 35222    return rc;
 35223  }
 35224  
 35225  /*
 35226  ** Lock the file with the lock specified by parameter eFileLock - one
 35227  ** of the following:
 35228  **
 35229  **     (1) SHARED_LOCK
 35230  **     (2) RESERVED_LOCK
 35231  **     (3) PENDING_LOCK
 35232  **     (4) EXCLUSIVE_LOCK
 35233  **
 35234  ** Sometimes when requesting one lock state, additional lock states
 35235  ** are inserted in between.  The locking might fail on one of the later
 35236  ** transitions leaving the lock state different from what it started but
 35237  ** still short of its goal.  The following chart shows the allowed
 35238  ** transitions and the inserted intermediate states:
 35239  **
 35240  **    UNLOCKED -> SHARED
 35241  **    SHARED -> RESERVED
 35242  **    SHARED -> (PENDING) -> EXCLUSIVE
 35243  **    RESERVED -> (PENDING) -> EXCLUSIVE
 35244  **    PENDING -> EXCLUSIVE
 35245  **
 35246  ** flock() only really support EXCLUSIVE locks.  We track intermediate
 35247  ** lock states in the sqlite3_file structure, but all locks SHARED or
 35248  ** above are really EXCLUSIVE locks and exclude all other processes from
 35249  ** access the file.
 35250  **
 35251  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 35252  ** routine to lower a locking level.
 35253  */
 35254  static int flockLock(sqlite3_file *id, int eFileLock) {
 35255    int rc = SQLITE_OK;
 35256    unixFile *pFile = (unixFile*)id;
 35257  
 35258    assert( pFile );
 35259  
 35260    /* if we already have a lock, it is exclusive.  
 35261    ** Just adjust level and punt on outta here. */
 35262    if (pFile->eFileLock > NO_LOCK) {
 35263      pFile->eFileLock = eFileLock;
 35264      return SQLITE_OK;
 35265    }
 35266    
 35267    /* grab an exclusive lock */
 35268    
 35269    if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
 35270      int tErrno = errno;
 35271      /* didn't get, must be busy */
 35272      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
 35273      if( IS_LOCK_ERROR(rc) ){
 35274        storeLastErrno(pFile, tErrno);
 35275      }
 35276    } else {
 35277      /* got it, set the type and return ok */
 35278      pFile->eFileLock = eFileLock;
 35279    }
 35280    OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
 35281             rc==SQLITE_OK ? "ok" : "failed"));
 35282  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 35283    if( (rc & 0xff) == SQLITE_IOERR ){
 35284      rc = SQLITE_BUSY;
 35285    }
 35286  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 35287    return rc;
 35288  }
 35289  
 35290  
 35291  /*
 35292  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 35293  ** must be either NO_LOCK or SHARED_LOCK.
 35294  **
 35295  ** If the locking level of the file descriptor is already at or below
 35296  ** the requested locking level, this routine is a no-op.
 35297  */
 35298  static int flockUnlock(sqlite3_file *id, int eFileLock) {
 35299    unixFile *pFile = (unixFile*)id;
 35300    
 35301    assert( pFile );
 35302    OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
 35303             pFile->eFileLock, osGetpid(0)));
 35304    assert( eFileLock<=SHARED_LOCK );
 35305    
 35306    /* no-op if possible */
 35307    if( pFile->eFileLock==eFileLock ){
 35308      return SQLITE_OK;
 35309    }
 35310    
 35311    /* shared can just be set because we always have an exclusive */
 35312    if (eFileLock==SHARED_LOCK) {
 35313      pFile->eFileLock = eFileLock;
 35314      return SQLITE_OK;
 35315    }
 35316    
 35317    /* no, really, unlock. */
 35318    if( robust_flock(pFile->h, LOCK_UN) ){
 35319  #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
 35320      return SQLITE_OK;
 35321  #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
 35322      return SQLITE_IOERR_UNLOCK;
 35323    }else{
 35324      pFile->eFileLock = NO_LOCK;
 35325      return SQLITE_OK;
 35326    }
 35327  }
 35328  
 35329  /*
 35330  ** Close a file.
 35331  */
 35332  static int flockClose(sqlite3_file *id) {
 35333    assert( id!=0 );
 35334    flockUnlock(id, NO_LOCK);
 35335    return closeUnixFile(id);
 35336  }
 35337  
 35338  #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
 35339  
 35340  /******************* End of the flock lock implementation *********************
 35341  ******************************************************************************/
 35342  
 35343  /******************************************************************************
 35344  ************************ Begin Named Semaphore Locking ************************
 35345  **
 35346  ** Named semaphore locking is only supported on VxWorks.
 35347  **
 35348  ** Semaphore locking is like dot-lock and flock in that it really only
 35349  ** supports EXCLUSIVE locking.  Only a single process can read or write
 35350  ** the database file at a time.  This reduces potential concurrency, but
 35351  ** makes the lock implementation much easier.
 35352  */
 35353  #if OS_VXWORKS
 35354  
 35355  /*
 35356  ** This routine checks if there is a RESERVED lock held on the specified
 35357  ** file by this or any other process. If such a lock is held, set *pResOut
 35358  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 35359  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 35360  */
 35361  static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
 35362    int rc = SQLITE_OK;
 35363    int reserved = 0;
 35364    unixFile *pFile = (unixFile*)id;
 35365  
 35366    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 35367    
 35368    assert( pFile );
 35369  
 35370    /* Check if a thread in this process holds such a lock */
 35371    if( pFile->eFileLock>SHARED_LOCK ){
 35372      reserved = 1;
 35373    }
 35374    
 35375    /* Otherwise see if some other process holds it. */
 35376    if( !reserved ){
 35377      sem_t *pSem = pFile->pInode->pSem;
 35378  
 35379      if( sem_trywait(pSem)==-1 ){
 35380        int tErrno = errno;
 35381        if( EAGAIN != tErrno ){
 35382          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
 35383          storeLastErrno(pFile, tErrno);
 35384        } else {
 35385          /* someone else has the lock when we are in NO_LOCK */
 35386          reserved = (pFile->eFileLock < SHARED_LOCK);
 35387        }
 35388      }else{
 35389        /* we could have it if we want it */
 35390        sem_post(pSem);
 35391      }
 35392    }
 35393    OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
 35394  
 35395    *pResOut = reserved;
 35396    return rc;
 35397  }
 35398  
 35399  /*
 35400  ** Lock the file with the lock specified by parameter eFileLock - one
 35401  ** of the following:
 35402  **
 35403  **     (1) SHARED_LOCK
 35404  **     (2) RESERVED_LOCK
 35405  **     (3) PENDING_LOCK
 35406  **     (4) EXCLUSIVE_LOCK
 35407  **
 35408  ** Sometimes when requesting one lock state, additional lock states
 35409  ** are inserted in between.  The locking might fail on one of the later
 35410  ** transitions leaving the lock state different from what it started but
 35411  ** still short of its goal.  The following chart shows the allowed
 35412  ** transitions and the inserted intermediate states:
 35413  **
 35414  **    UNLOCKED -> SHARED
 35415  **    SHARED -> RESERVED
 35416  **    SHARED -> (PENDING) -> EXCLUSIVE
 35417  **    RESERVED -> (PENDING) -> EXCLUSIVE
 35418  **    PENDING -> EXCLUSIVE
 35419  **
 35420  ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
 35421  ** lock states in the sqlite3_file structure, but all locks SHARED or
 35422  ** above are really EXCLUSIVE locks and exclude all other processes from
 35423  ** access the file.
 35424  **
 35425  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 35426  ** routine to lower a locking level.
 35427  */
 35428  static int semXLock(sqlite3_file *id, int eFileLock) {
 35429    unixFile *pFile = (unixFile*)id;
 35430    sem_t *pSem = pFile->pInode->pSem;
 35431    int rc = SQLITE_OK;
 35432  
 35433    /* if we already have a lock, it is exclusive.  
 35434    ** Just adjust level and punt on outta here. */
 35435    if (pFile->eFileLock > NO_LOCK) {
 35436      pFile->eFileLock = eFileLock;
 35437      rc = SQLITE_OK;
 35438      goto sem_end_lock;
 35439    }
 35440    
 35441    /* lock semaphore now but bail out when already locked. */
 35442    if( sem_trywait(pSem)==-1 ){
 35443      rc = SQLITE_BUSY;
 35444      goto sem_end_lock;
 35445    }
 35446  
 35447    /* got it, set the type and return ok */
 35448    pFile->eFileLock = eFileLock;
 35449  
 35450   sem_end_lock:
 35451    return rc;
 35452  }
 35453  
 35454  /*
 35455  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 35456  ** must be either NO_LOCK or SHARED_LOCK.
 35457  **
 35458  ** If the locking level of the file descriptor is already at or below
 35459  ** the requested locking level, this routine is a no-op.
 35460  */
 35461  static int semXUnlock(sqlite3_file *id, int eFileLock) {
 35462    unixFile *pFile = (unixFile*)id;
 35463    sem_t *pSem = pFile->pInode->pSem;
 35464  
 35465    assert( pFile );
 35466    assert( pSem );
 35467    OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
 35468             pFile->eFileLock, osGetpid(0)));
 35469    assert( eFileLock<=SHARED_LOCK );
 35470    
 35471    /* no-op if possible */
 35472    if( pFile->eFileLock==eFileLock ){
 35473      return SQLITE_OK;
 35474    }
 35475    
 35476    /* shared can just be set because we always have an exclusive */
 35477    if (eFileLock==SHARED_LOCK) {
 35478      pFile->eFileLock = eFileLock;
 35479      return SQLITE_OK;
 35480    }
 35481    
 35482    /* no, really unlock. */
 35483    if ( sem_post(pSem)==-1 ) {
 35484      int rc, tErrno = errno;
 35485      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
 35486      if( IS_LOCK_ERROR(rc) ){
 35487        storeLastErrno(pFile, tErrno);
 35488      }
 35489      return rc; 
 35490    }
 35491    pFile->eFileLock = NO_LOCK;
 35492    return SQLITE_OK;
 35493  }
 35494  
 35495  /*
 35496   ** Close a file.
 35497   */
 35498  static int semXClose(sqlite3_file *id) {
 35499    if( id ){
 35500      unixFile *pFile = (unixFile*)id;
 35501      semXUnlock(id, NO_LOCK);
 35502      assert( pFile );
 35503      assert( unixFileMutexNotheld(pFile) );
 35504      unixEnterMutex();
 35505      releaseInodeInfo(pFile);
 35506      unixLeaveMutex();
 35507      closeUnixFile(id);
 35508    }
 35509    return SQLITE_OK;
 35510  }
 35511  
 35512  #endif /* OS_VXWORKS */
 35513  /*
 35514  ** Named semaphore locking is only available on VxWorks.
 35515  **
 35516  *************** End of the named semaphore lock implementation ****************
 35517  ******************************************************************************/
 35518  
 35519  
 35520  /******************************************************************************
 35521  *************************** Begin AFP Locking *********************************
 35522  **
 35523  ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
 35524  ** on Apple Macintosh computers - both OS9 and OSX.
 35525  **
 35526  ** Third-party implementations of AFP are available.  But this code here
 35527  ** only works on OSX.
 35528  */
 35529  
 35530  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35531  /*
 35532  ** The afpLockingContext structure contains all afp lock specific state
 35533  */
 35534  typedef struct afpLockingContext afpLockingContext;
 35535  struct afpLockingContext {
 35536    int reserved;
 35537    const char *dbPath;             /* Name of the open file */
 35538  };
 35539  
 35540  struct ByteRangeLockPB2
 35541  {
 35542    unsigned long long offset;        /* offset to first byte to lock */
 35543    unsigned long long length;        /* nbr of bytes to lock */
 35544    unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
 35545    unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
 35546    unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
 35547    int fd;                           /* file desc to assoc this lock with */
 35548  };
 35549  
 35550  #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
 35551  
 35552  /*
 35553  ** This is a utility for setting or clearing a bit-range lock on an
 35554  ** AFP filesystem.
 35555  ** 
 35556  ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
 35557  */
 35558  static int afpSetLock(
 35559    const char *path,              /* Name of the file to be locked or unlocked */
 35560    unixFile *pFile,               /* Open file descriptor on path */
 35561    unsigned long long offset,     /* First byte to be locked */
 35562    unsigned long long length,     /* Number of bytes to lock */
 35563    int setLockFlag                /* True to set lock.  False to clear lock */
 35564  ){
 35565    struct ByteRangeLockPB2 pb;
 35566    int err;
 35567    
 35568    pb.unLockFlag = setLockFlag ? 0 : 1;
 35569    pb.startEndFlag = 0;
 35570    pb.offset = offset;
 35571    pb.length = length; 
 35572    pb.fd = pFile->h;
 35573    
 35574    OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
 35575      (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
 35576      offset, length));
 35577    err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
 35578    if ( err==-1 ) {
 35579      int rc;
 35580      int tErrno = errno;
 35581      OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
 35582               path, tErrno, strerror(tErrno)));
 35583  #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
 35584      rc = SQLITE_BUSY;
 35585  #else
 35586      rc = sqliteErrorFromPosixError(tErrno,
 35587                      setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
 35588  #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
 35589      if( IS_LOCK_ERROR(rc) ){
 35590        storeLastErrno(pFile, tErrno);
 35591      }
 35592      return rc;
 35593    } else {
 35594      return SQLITE_OK;
 35595    }
 35596  }
 35597  
 35598  /*
 35599  ** This routine checks if there is a RESERVED lock held on the specified
 35600  ** file by this or any other process. If such a lock is held, set *pResOut
 35601  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 35602  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 35603  */
 35604  static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
 35605    int rc = SQLITE_OK;
 35606    int reserved = 0;
 35607    unixFile *pFile = (unixFile*)id;
 35608    afpLockingContext *context;
 35609    
 35610    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 35611    
 35612    assert( pFile );
 35613    context = (afpLockingContext *) pFile->lockingContext;
 35614    if( context->reserved ){
 35615      *pResOut = 1;
 35616      return SQLITE_OK;
 35617    }
 35618    sqlite3_mutex_enter(pFile->pInode->pLockMutex);
 35619    /* Check if a thread in this process holds such a lock */
 35620    if( pFile->pInode->eFileLock>SHARED_LOCK ){
 35621      reserved = 1;
 35622    }
 35623    
 35624    /* Otherwise see if some other process holds it.
 35625     */
 35626    if( !reserved ){
 35627      /* lock the RESERVED byte */
 35628      int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
 35629      if( SQLITE_OK==lrc ){
 35630        /* if we succeeded in taking the reserved lock, unlock it to restore
 35631        ** the original state */
 35632        lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 35633      } else {
 35634        /* if we failed to get the lock then someone else must have it */
 35635        reserved = 1;
 35636      }
 35637      if( IS_LOCK_ERROR(lrc) ){
 35638        rc=lrc;
 35639      }
 35640    }
 35641    
 35642    sqlite3_mutex_leave(pFile->pInode->pLockMutex);
 35643    OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
 35644    
 35645    *pResOut = reserved;
 35646    return rc;
 35647  }
 35648  
 35649  /*
 35650  ** Lock the file with the lock specified by parameter eFileLock - one
 35651  ** of the following:
 35652  **
 35653  **     (1) SHARED_LOCK
 35654  **     (2) RESERVED_LOCK
 35655  **     (3) PENDING_LOCK
 35656  **     (4) EXCLUSIVE_LOCK
 35657  **
 35658  ** Sometimes when requesting one lock state, additional lock states
 35659  ** are inserted in between.  The locking might fail on one of the later
 35660  ** transitions leaving the lock state different from what it started but
 35661  ** still short of its goal.  The following chart shows the allowed
 35662  ** transitions and the inserted intermediate states:
 35663  **
 35664  **    UNLOCKED -> SHARED
 35665  **    SHARED -> RESERVED
 35666  **    SHARED -> (PENDING) -> EXCLUSIVE
 35667  **    RESERVED -> (PENDING) -> EXCLUSIVE
 35668  **    PENDING -> EXCLUSIVE
 35669  **
 35670  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 35671  ** routine to lower a locking level.
 35672  */
 35673  static int afpLock(sqlite3_file *id, int eFileLock){
 35674    int rc = SQLITE_OK;
 35675    unixFile *pFile = (unixFile*)id;
 35676    unixInodeInfo *pInode = pFile->pInode;
 35677    afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 35678    
 35679    assert( pFile );
 35680    OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
 35681             azFileLock(eFileLock), azFileLock(pFile->eFileLock),
 35682             azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
 35683  
 35684    /* If there is already a lock of this type or more restrictive on the
 35685    ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
 35686    ** unixEnterMutex() hasn't been called yet.
 35687    */
 35688    if( pFile->eFileLock>=eFileLock ){
 35689      OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
 35690             azFileLock(eFileLock)));
 35691      return SQLITE_OK;
 35692    }
 35693  
 35694    /* Make sure the locking sequence is correct
 35695    **  (1) We never move from unlocked to anything higher than shared lock.
 35696    **  (2) SQLite never explicitly requests a pendig lock.
 35697    **  (3) A shared lock is always held when a reserve lock is requested.
 35698    */
 35699    assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
 35700    assert( eFileLock!=PENDING_LOCK );
 35701    assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
 35702    
 35703    /* This mutex is needed because pFile->pInode is shared across threads
 35704    */
 35705    pInode = pFile->pInode;
 35706    sqlite3_mutex_enter(pInode->pLockMutex);
 35707  
 35708    /* If some thread using this PID has a lock via a different unixFile*
 35709    ** handle that precludes the requested lock, return BUSY.
 35710    */
 35711    if( (pFile->eFileLock!=pInode->eFileLock && 
 35712         (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
 35713       ){
 35714      rc = SQLITE_BUSY;
 35715      goto afp_end_lock;
 35716    }
 35717    
 35718    /* If a SHARED lock is requested, and some thread using this PID already
 35719    ** has a SHARED or RESERVED lock, then increment reference counts and
 35720    ** return SQLITE_OK.
 35721    */
 35722    if( eFileLock==SHARED_LOCK && 
 35723       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
 35724      assert( eFileLock==SHARED_LOCK );
 35725      assert( pFile->eFileLock==0 );
 35726      assert( pInode->nShared>0 );
 35727      pFile->eFileLock = SHARED_LOCK;
 35728      pInode->nShared++;
 35729      pInode->nLock++;
 35730      goto afp_end_lock;
 35731    }
 35732      
 35733    /* A PENDING lock is needed before acquiring a SHARED lock and before
 35734    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
 35735    ** be released.
 35736    */
 35737    if( eFileLock==SHARED_LOCK 
 35738        || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
 35739    ){
 35740      int failed;
 35741      failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
 35742      if (failed) {
 35743        rc = failed;
 35744        goto afp_end_lock;
 35745      }
 35746    }
 35747    
 35748    /* If control gets to this point, then actually go ahead and make
 35749    ** operating system calls for the specified lock.
 35750    */
 35751    if( eFileLock==SHARED_LOCK ){
 35752      int lrc1, lrc2, lrc1Errno = 0;
 35753      long lk, mask;
 35754      
 35755      assert( pInode->nShared==0 );
 35756      assert( pInode->eFileLock==0 );
 35757          
 35758      mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
 35759      /* Now get the read-lock SHARED_LOCK */
 35760      /* note that the quality of the randomness doesn't matter that much */
 35761      lk = random(); 
 35762      pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
 35763      lrc1 = afpSetLock(context->dbPath, pFile, 
 35764            SHARED_FIRST+pInode->sharedByte, 1, 1);
 35765      if( IS_LOCK_ERROR(lrc1) ){
 35766        lrc1Errno = pFile->lastErrno;
 35767      }
 35768      /* Drop the temporary PENDING lock */
 35769      lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 35770      
 35771      if( IS_LOCK_ERROR(lrc1) ) {
 35772        storeLastErrno(pFile, lrc1Errno);
 35773        rc = lrc1;
 35774        goto afp_end_lock;
 35775      } else if( IS_LOCK_ERROR(lrc2) ){
 35776        rc = lrc2;
 35777        goto afp_end_lock;
 35778      } else if( lrc1 != SQLITE_OK ) {
 35779        rc = lrc1;
 35780      } else {
 35781        pFile->eFileLock = SHARED_LOCK;
 35782        pInode->nLock++;
 35783        pInode->nShared = 1;
 35784      }
 35785    }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
 35786      /* We are trying for an exclusive lock but another thread in this
 35787       ** same process is still holding a shared lock. */
 35788      rc = SQLITE_BUSY;
 35789    }else{
 35790      /* The request was for a RESERVED or EXCLUSIVE lock.  It is
 35791      ** assumed that there is a SHARED or greater lock on the file
 35792      ** already.
 35793      */
 35794      int failed = 0;
 35795      assert( 0!=pFile->eFileLock );
 35796      if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
 35797          /* Acquire a RESERVED lock */
 35798          failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
 35799        if( !failed ){
 35800          context->reserved = 1;
 35801        }
 35802      }
 35803      if (!failed && eFileLock == EXCLUSIVE_LOCK) {
 35804        /* Acquire an EXCLUSIVE lock */
 35805          
 35806        /* Remove the shared lock before trying the range.  we'll need to 
 35807        ** reestablish the shared lock if we can't get the  afpUnlock
 35808        */
 35809        if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
 35810                           pInode->sharedByte, 1, 0)) ){
 35811          int failed2 = SQLITE_OK;
 35812          /* now attemmpt to get the exclusive lock range */
 35813          failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
 35814                                 SHARED_SIZE, 1);
 35815          if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
 35816                         SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
 35817            /* Can't reestablish the shared lock.  Sqlite can't deal, this is
 35818            ** a critical I/O error
 35819            */
 35820            rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : 
 35821                 SQLITE_IOERR_LOCK;
 35822            goto afp_end_lock;
 35823          } 
 35824        }else{
 35825          rc = failed; 
 35826        }
 35827      }
 35828      if( failed ){
 35829        rc = failed;
 35830      }
 35831    }
 35832    
 35833    if( rc==SQLITE_OK ){
 35834      pFile->eFileLock = eFileLock;
 35835      pInode->eFileLock = eFileLock;
 35836    }else if( eFileLock==EXCLUSIVE_LOCK ){
 35837      pFile->eFileLock = PENDING_LOCK;
 35838      pInode->eFileLock = PENDING_LOCK;
 35839    }
 35840    
 35841  afp_end_lock:
 35842    sqlite3_mutex_leave(pInode->pLockMutex);
 35843    OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
 35844           rc==SQLITE_OK ? "ok" : "failed"));
 35845    return rc;
 35846  }
 35847  
 35848  /*
 35849  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 35850  ** must be either NO_LOCK or SHARED_LOCK.
 35851  **
 35852  ** If the locking level of the file descriptor is already at or below
 35853  ** the requested locking level, this routine is a no-op.
 35854  */
 35855  static int afpUnlock(sqlite3_file *id, int eFileLock) {
 35856    int rc = SQLITE_OK;
 35857    unixFile *pFile = (unixFile*)id;
 35858    unixInodeInfo *pInode;
 35859    afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
 35860    int skipShared = 0;
 35861  #ifdef SQLITE_TEST
 35862    int h = pFile->h;
 35863  #endif
 35864  
 35865    assert( pFile );
 35866    OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
 35867             pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
 35868             osGetpid(0)));
 35869  
 35870    assert( eFileLock<=SHARED_LOCK );
 35871    if( pFile->eFileLock<=eFileLock ){
 35872      return SQLITE_OK;
 35873    }
 35874    pInode = pFile->pInode;
 35875    sqlite3_mutex_enter(pInode->pLockMutex);
 35876    assert( pInode->nShared!=0 );
 35877    if( pFile->eFileLock>SHARED_LOCK ){
 35878      assert( pInode->eFileLock==pFile->eFileLock );
 35879      SimulateIOErrorBenign(1);
 35880      SimulateIOError( h=(-1) )
 35881      SimulateIOErrorBenign(0);
 35882      
 35883  #ifdef SQLITE_DEBUG
 35884      /* When reducing a lock such that other processes can start
 35885      ** reading the database file again, make sure that the
 35886      ** transaction counter was updated if any part of the database
 35887      ** file changed.  If the transaction counter is not updated,
 35888      ** other connections to the same file might not realize that
 35889      ** the file has changed and hence might not know to flush their
 35890      ** cache.  The use of a stale cache can lead to database corruption.
 35891      */
 35892      assert( pFile->inNormalWrite==0
 35893             || pFile->dbUpdate==0
 35894             || pFile->transCntrChng==1 );
 35895      pFile->inNormalWrite = 0;
 35896  #endif
 35897      
 35898      if( pFile->eFileLock==EXCLUSIVE_LOCK ){
 35899        rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
 35900        if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
 35901          /* only re-establish the shared lock if necessary */
 35902          int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 35903          rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
 35904        } else {
 35905          skipShared = 1;
 35906        }
 35907      }
 35908      if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
 35909        rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
 35910      } 
 35911      if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
 35912        rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
 35913        if( !rc ){ 
 35914          context->reserved = 0; 
 35915        }
 35916      }
 35917      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
 35918        pInode->eFileLock = SHARED_LOCK;
 35919      }
 35920    }
 35921    if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
 35922  
 35923      /* Decrement the shared lock counter.  Release the lock using an
 35924      ** OS call only when all threads in this same process have released
 35925      ** the lock.
 35926      */
 35927      unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
 35928      pInode->nShared--;
 35929      if( pInode->nShared==0 ){
 35930        SimulateIOErrorBenign(1);
 35931        SimulateIOError( h=(-1) )
 35932        SimulateIOErrorBenign(0);
 35933        if( !skipShared ){
 35934          rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
 35935        }
 35936        if( !rc ){
 35937          pInode->eFileLock = NO_LOCK;
 35938          pFile->eFileLock = NO_LOCK;
 35939        }
 35940      }
 35941      if( rc==SQLITE_OK ){
 35942        pInode->nLock--;
 35943        assert( pInode->nLock>=0 );
 35944        if( pInode->nLock==0 ) closePendingFds(pFile);
 35945      }
 35946    }
 35947    
 35948    sqlite3_mutex_leave(pInode->pLockMutex);
 35949    if( rc==SQLITE_OK ){
 35950      pFile->eFileLock = eFileLock;
 35951    }
 35952    return rc;
 35953  }
 35954  
 35955  /*
 35956  ** Close a file & cleanup AFP specific locking context 
 35957  */
 35958  static int afpClose(sqlite3_file *id) {
 35959    int rc = SQLITE_OK;
 35960    unixFile *pFile = (unixFile*)id;
 35961    assert( id!=0 );
 35962    afpUnlock(id, NO_LOCK);
 35963    assert( unixFileMutexNotheld(pFile) );
 35964    unixEnterMutex();
 35965    if( pFile->pInode ){
 35966      unixInodeInfo *pInode = pFile->pInode;
 35967      sqlite3_mutex_enter(pInode->pLockMutex);
 35968      if( pInode->nLock ){
 35969        /* If there are outstanding locks, do not actually close the file just
 35970        ** yet because that would clear those locks.  Instead, add the file
 35971        ** descriptor to pInode->aPending.  It will be automatically closed when
 35972        ** the last lock is cleared.
 35973        */
 35974        setPendingFd(pFile);
 35975      }
 35976      sqlite3_mutex_leave(pInode->pLockMutex);
 35977    }
 35978    releaseInodeInfo(pFile);
 35979    sqlite3_free(pFile->lockingContext);
 35980    rc = closeUnixFile(id);
 35981    unixLeaveMutex();
 35982    return rc;
 35983  }
 35984  
 35985  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 35986  /*
 35987  ** The code above is the AFP lock implementation.  The code is specific
 35988  ** to MacOSX and does not work on other unix platforms.  No alternative
 35989  ** is available.  If you don't compile for a mac, then the "unix-afp"
 35990  ** VFS is not available.
 35991  **
 35992  ********************* End of the AFP lock implementation **********************
 35993  ******************************************************************************/
 35994  
 35995  /******************************************************************************
 35996  *************************** Begin NFS Locking ********************************/
 35997  
 35998  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 35999  /*
 36000   ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 36001   ** must be either NO_LOCK or SHARED_LOCK.
 36002   **
 36003   ** If the locking level of the file descriptor is already at or below
 36004   ** the requested locking level, this routine is a no-op.
 36005   */
 36006  static int nfsUnlock(sqlite3_file *id, int eFileLock){
 36007    return posixUnlock(id, eFileLock, 1);
 36008  }
 36009  
 36010  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 36011  /*
 36012  ** The code above is the NFS lock implementation.  The code is specific
 36013  ** to MacOSX and does not work on other unix platforms.  No alternative
 36014  ** is available.  
 36015  **
 36016  ********************* End of the NFS lock implementation **********************
 36017  ******************************************************************************/
 36018  
 36019  /******************************************************************************
 36020  **************** Non-locking sqlite3_file methods *****************************
 36021  **
 36022  ** The next division contains implementations for all methods of the 
 36023  ** sqlite3_file object other than the locking methods.  The locking
 36024  ** methods were defined in divisions above (one locking method per
 36025  ** division).  Those methods that are common to all locking modes
 36026  ** are gather together into this division.
 36027  */
 36028  
 36029  /*
 36030  ** Seek to the offset passed as the second argument, then read cnt 
 36031  ** bytes into pBuf. Return the number of bytes actually read.
 36032  **
 36033  ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
 36034  ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
 36035  ** one system to another.  Since SQLite does not define USE_PREAD
 36036  ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
 36037  ** See tickets #2741 and #2681.
 36038  **
 36039  ** To avoid stomping the errno value on a failed read the lastErrno value
 36040  ** is set before returning.
 36041  */
 36042  static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
 36043    int got;
 36044    int prior = 0;
 36045  #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
 36046    i64 newOffset;
 36047  #endif
 36048    TIMER_START;
 36049    assert( cnt==(cnt&0x1ffff) );
 36050    assert( id->h>2 );
 36051    do{
 36052  #if defined(USE_PREAD)
 36053      got = osPread(id->h, pBuf, cnt, offset);
 36054      SimulateIOError( got = -1 );
 36055  #elif defined(USE_PREAD64)
 36056      got = osPread64(id->h, pBuf, cnt, offset);
 36057      SimulateIOError( got = -1 );
 36058  #else
 36059      newOffset = lseek(id->h, offset, SEEK_SET);
 36060      SimulateIOError( newOffset = -1 );
 36061      if( newOffset<0 ){
 36062        storeLastErrno((unixFile*)id, errno);
 36063        return -1;
 36064      }
 36065      got = osRead(id->h, pBuf, cnt);
 36066  #endif
 36067      if( got==cnt ) break;
 36068      if( got<0 ){
 36069        if( errno==EINTR ){ got = 1; continue; }
 36070        prior = 0;
 36071        storeLastErrno((unixFile*)id,  errno);
 36072        break;
 36073      }else if( got>0 ){
 36074        cnt -= got;
 36075        offset += got;
 36076        prior += got;
 36077        pBuf = (void*)(got + (char*)pBuf);
 36078      }
 36079    }while( got>0 );
 36080    TIMER_END;
 36081    OSTRACE(("READ    %-3d %5d %7lld %llu\n",
 36082              id->h, got+prior, offset-prior, TIMER_ELAPSED));
 36083    return got+prior;
 36084  }
 36085  
 36086  /*
 36087  ** Read data from a file into a buffer.  Return SQLITE_OK if all
 36088  ** bytes were read successfully and SQLITE_IOERR if anything goes
 36089  ** wrong.
 36090  */
 36091  static int unixRead(
 36092    sqlite3_file *id, 
 36093    void *pBuf, 
 36094    int amt,
 36095    sqlite3_int64 offset
 36096  ){
 36097    unixFile *pFile = (unixFile *)id;
 36098    int got;
 36099    assert( id );
 36100    assert( offset>=0 );
 36101    assert( amt>0 );
 36102  
 36103    /* If this is a database file (not a journal, master-journal or temp
 36104    ** file), the bytes in the locking range should never be read or written. */
 36105  #if 0
 36106    assert( pFile->pPreallocatedUnused==0
 36107         || offset>=PENDING_BYTE+512
 36108         || offset+amt<=PENDING_BYTE 
 36109    );
 36110  #endif
 36111  
 36112  #if SQLITE_MAX_MMAP_SIZE>0
 36113    /* Deal with as much of this read request as possible by transfering
 36114    ** data from the memory mapping using memcpy().  */
 36115    if( offset<pFile->mmapSize ){
 36116      if( offset+amt <= pFile->mmapSize ){
 36117        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 36118        return SQLITE_OK;
 36119      }else{
 36120        int nCopy = pFile->mmapSize - offset;
 36121        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 36122        pBuf = &((u8 *)pBuf)[nCopy];
 36123        amt -= nCopy;
 36124        offset += nCopy;
 36125      }
 36126    }
 36127  #endif
 36128  
 36129    got = seekAndRead(pFile, offset, pBuf, amt);
 36130    if( got==amt ){
 36131      return SQLITE_OK;
 36132    }else if( got<0 ){
 36133      /* lastErrno set by seekAndRead */
 36134      return SQLITE_IOERR_READ;
 36135    }else{
 36136      storeLastErrno(pFile, 0);   /* not a system error */
 36137      /* Unread parts of the buffer must be zero-filled */
 36138      memset(&((char*)pBuf)[got], 0, amt-got);
 36139      return SQLITE_IOERR_SHORT_READ;
 36140    }
 36141  }
 36142  
 36143  /*
 36144  ** Attempt to seek the file-descriptor passed as the first argument to
 36145  ** absolute offset iOff, then attempt to write nBuf bytes of data from
 36146  ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
 36147  ** return the actual number of bytes written (which may be less than
 36148  ** nBuf).
 36149  */
 36150  static int seekAndWriteFd(
 36151    int fd,                         /* File descriptor to write to */
 36152    i64 iOff,                       /* File offset to begin writing at */
 36153    const void *pBuf,               /* Copy data from this buffer to the file */
 36154    int nBuf,                       /* Size of buffer pBuf in bytes */
 36155    int *piErrno                    /* OUT: Error number if error occurs */
 36156  ){
 36157    int rc = 0;                     /* Value returned by system call */
 36158  
 36159    assert( nBuf==(nBuf&0x1ffff) );
 36160    assert( fd>2 );
 36161    assert( piErrno!=0 );
 36162    nBuf &= 0x1ffff;
 36163    TIMER_START;
 36164  
 36165  #if defined(USE_PREAD)
 36166    do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
 36167  #elif defined(USE_PREAD64)
 36168    do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
 36169  #else
 36170    do{
 36171      i64 iSeek = lseek(fd, iOff, SEEK_SET);
 36172      SimulateIOError( iSeek = -1 );
 36173      if( iSeek<0 ){
 36174        rc = -1;
 36175        break;
 36176      }
 36177      rc = osWrite(fd, pBuf, nBuf);
 36178    }while( rc<0 && errno==EINTR );
 36179  #endif
 36180  
 36181    TIMER_END;
 36182    OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
 36183  
 36184    if( rc<0 ) *piErrno = errno;
 36185    return rc;
 36186  }
 36187  
 36188  
 36189  /*
 36190  ** Seek to the offset in id->offset then read cnt bytes into pBuf.
 36191  ** Return the number of bytes actually read.  Update the offset.
 36192  **
 36193  ** To avoid stomping the errno value on a failed write the lastErrno value
 36194  ** is set before returning.
 36195  */
 36196  static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
 36197    return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
 36198  }
 36199  
 36200  
 36201  /*
 36202  ** Write data from a buffer into a file.  Return SQLITE_OK on success
 36203  ** or some other error code on failure.
 36204  */
 36205  static int unixWrite(
 36206    sqlite3_file *id, 
 36207    const void *pBuf, 
 36208    int amt,
 36209    sqlite3_int64 offset 
 36210  ){
 36211    unixFile *pFile = (unixFile*)id;
 36212    int wrote = 0;
 36213    assert( id );
 36214    assert( amt>0 );
 36215  
 36216    /* If this is a database file (not a journal, master-journal or temp
 36217    ** file), the bytes in the locking range should never be read or written. */
 36218  #if 0
 36219    assert( pFile->pPreallocatedUnused==0
 36220         || offset>=PENDING_BYTE+512
 36221         || offset+amt<=PENDING_BYTE 
 36222    );
 36223  #endif
 36224  
 36225  #ifdef SQLITE_DEBUG
 36226    /* If we are doing a normal write to a database file (as opposed to
 36227    ** doing a hot-journal rollback or a write to some file other than a
 36228    ** normal database file) then record the fact that the database
 36229    ** has changed.  If the transaction counter is modified, record that
 36230    ** fact too.
 36231    */
 36232    if( pFile->inNormalWrite ){
 36233      pFile->dbUpdate = 1;  /* The database has been modified */
 36234      if( offset<=24 && offset+amt>=27 ){
 36235        int rc;
 36236        char oldCntr[4];
 36237        SimulateIOErrorBenign(1);
 36238        rc = seekAndRead(pFile, 24, oldCntr, 4);
 36239        SimulateIOErrorBenign(0);
 36240        if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
 36241          pFile->transCntrChng = 1;  /* The transaction counter has changed */
 36242        }
 36243      }
 36244    }
 36245  #endif
 36246  
 36247  #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
 36248    /* Deal with as much of this write request as possible by transfering
 36249    ** data from the memory mapping using memcpy().  */
 36250    if( offset<pFile->mmapSize ){
 36251      if( offset+amt <= pFile->mmapSize ){
 36252        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 36253        return SQLITE_OK;
 36254      }else{
 36255        int nCopy = pFile->mmapSize - offset;
 36256        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 36257        pBuf = &((u8 *)pBuf)[nCopy];
 36258        amt -= nCopy;
 36259        offset += nCopy;
 36260      }
 36261    }
 36262  #endif
 36263   
 36264    while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
 36265      amt -= wrote;
 36266      offset += wrote;
 36267      pBuf = &((char*)pBuf)[wrote];
 36268    }
 36269    SimulateIOError(( wrote=(-1), amt=1 ));
 36270    SimulateDiskfullError(( wrote=0, amt=1 ));
 36271  
 36272    if( amt>wrote ){
 36273      if( wrote<0 && pFile->lastErrno!=ENOSPC ){
 36274        /* lastErrno set by seekAndWrite */
 36275        return SQLITE_IOERR_WRITE;
 36276      }else{
 36277        storeLastErrno(pFile, 0); /* not a system error */
 36278        return SQLITE_FULL;
 36279      }
 36280    }
 36281  
 36282    return SQLITE_OK;
 36283  }
 36284  
 36285  #ifdef SQLITE_TEST
 36286  /*
 36287  ** Count the number of fullsyncs and normal syncs.  This is used to test
 36288  ** that syncs and fullsyncs are occurring at the right times.
 36289  */
 36290  SQLITE_API int sqlite3_sync_count = 0;
 36291  SQLITE_API int sqlite3_fullsync_count = 0;
 36292  #endif
 36293  
 36294  /*
 36295  ** We do not trust systems to provide a working fdatasync().  Some do.
 36296  ** Others do no.  To be safe, we will stick with the (slightly slower)
 36297  ** fsync(). If you know that your system does support fdatasync() correctly,
 36298  ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
 36299  */
 36300  #if !defined(fdatasync) && !HAVE_FDATASYNC
 36301  # define fdatasync fsync
 36302  #endif
 36303  
 36304  /*
 36305  ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
 36306  ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
 36307  ** only available on Mac OS X.  But that could change.
 36308  */
 36309  #ifdef F_FULLFSYNC
 36310  # define HAVE_FULLFSYNC 1
 36311  #else
 36312  # define HAVE_FULLFSYNC 0
 36313  #endif
 36314  
 36315  
 36316  /*
 36317  ** The fsync() system call does not work as advertised on many
 36318  ** unix systems.  The following procedure is an attempt to make
 36319  ** it work better.
 36320  **
 36321  ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
 36322  ** for testing when we want to run through the test suite quickly.
 36323  ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
 36324  ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
 36325  ** or power failure will likely corrupt the database file.
 36326  **
 36327  ** SQLite sets the dataOnly flag if the size of the file is unchanged.
 36328  ** The idea behind dataOnly is that it should only write the file content
 36329  ** to disk, not the inode.  We only set dataOnly if the file size is 
 36330  ** unchanged since the file size is part of the inode.  However, 
 36331  ** Ted Ts'o tells us that fdatasync() will also write the inode if the
 36332  ** file size has changed.  The only real difference between fdatasync()
 36333  ** and fsync(), Ted tells us, is that fdatasync() will not flush the
 36334  ** inode if the mtime or owner or other inode attributes have changed.
 36335  ** We only care about the file size, not the other file attributes, so
 36336  ** as far as SQLite is concerned, an fdatasync() is always adequate.
 36337  ** So, we always use fdatasync() if it is available, regardless of
 36338  ** the value of the dataOnly flag.
 36339  */
 36340  static int full_fsync(int fd, int fullSync, int dataOnly){
 36341    int rc;
 36342  
 36343    /* The following "ifdef/elif/else/" block has the same structure as
 36344    ** the one below. It is replicated here solely to avoid cluttering 
 36345    ** up the real code with the UNUSED_PARAMETER() macros.
 36346    */
 36347  #ifdef SQLITE_NO_SYNC
 36348    UNUSED_PARAMETER(fd);
 36349    UNUSED_PARAMETER(fullSync);
 36350    UNUSED_PARAMETER(dataOnly);
 36351  #elif HAVE_FULLFSYNC
 36352    UNUSED_PARAMETER(dataOnly);
 36353  #else
 36354    UNUSED_PARAMETER(fullSync);
 36355    UNUSED_PARAMETER(dataOnly);
 36356  #endif
 36357  
 36358    /* Record the number of times that we do a normal fsync() and 
 36359    ** FULLSYNC.  This is used during testing to verify that this procedure
 36360    ** gets called with the correct arguments.
 36361    */
 36362  #ifdef SQLITE_TEST
 36363    if( fullSync ) sqlite3_fullsync_count++;
 36364    sqlite3_sync_count++;
 36365  #endif
 36366  
 36367    /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 36368    ** no-op.  But go ahead and call fstat() to validate the file
 36369    ** descriptor as we need a method to provoke a failure during
 36370    ** coverate testing.
 36371    */
 36372  #ifdef SQLITE_NO_SYNC
 36373    {
 36374      struct stat buf;
 36375      rc = osFstat(fd, &buf);
 36376    }
 36377  #elif HAVE_FULLFSYNC
 36378    if( fullSync ){
 36379      rc = osFcntl(fd, F_FULLFSYNC, 0);
 36380    }else{
 36381      rc = 1;
 36382    }
 36383    /* If the FULLFSYNC failed, fall back to attempting an fsync().
 36384    ** It shouldn't be possible for fullfsync to fail on the local 
 36385    ** file system (on OSX), so failure indicates that FULLFSYNC
 36386    ** isn't supported for this file system. So, attempt an fsync 
 36387    ** and (for now) ignore the overhead of a superfluous fcntl call.  
 36388    ** It'd be better to detect fullfsync support once and avoid 
 36389    ** the fcntl call every time sync is called.
 36390    */
 36391    if( rc ) rc = fsync(fd);
 36392  
 36393  #elif defined(__APPLE__)
 36394    /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
 36395    ** so currently we default to the macro that redefines fdatasync to fsync
 36396    */
 36397    rc = fsync(fd);
 36398  #else 
 36399    rc = fdatasync(fd);
 36400  #if OS_VXWORKS
 36401    if( rc==-1 && errno==ENOTSUP ){
 36402      rc = fsync(fd);
 36403    }
 36404  #endif /* OS_VXWORKS */
 36405  #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
 36406  
 36407    if( OS_VXWORKS && rc!= -1 ){
 36408      rc = 0;
 36409    }
 36410    return rc;
 36411  }
 36412  
 36413  /*
 36414  ** Open a file descriptor to the directory containing file zFilename.
 36415  ** If successful, *pFd is set to the opened file descriptor and
 36416  ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
 36417  ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
 36418  ** value.
 36419  **
 36420  ** The directory file descriptor is used for only one thing - to
 36421  ** fsync() a directory to make sure file creation and deletion events
 36422  ** are flushed to disk.  Such fsyncs are not needed on newer
 36423  ** journaling filesystems, but are required on older filesystems.
 36424  **
 36425  ** This routine can be overridden using the xSetSysCall interface.
 36426  ** The ability to override this routine was added in support of the
 36427  ** chromium sandbox.  Opening a directory is a security risk (we are
 36428  ** told) so making it overrideable allows the chromium sandbox to
 36429  ** replace this routine with a harmless no-op.  To make this routine
 36430  ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
 36431  ** *pFd set to a negative number.
 36432  **
 36433  ** If SQLITE_OK is returned, the caller is responsible for closing
 36434  ** the file descriptor *pFd using close().
 36435  */
 36436  static int openDirectory(const char *zFilename, int *pFd){
 36437    int ii;
 36438    int fd = -1;
 36439    char zDirname[MAX_PATHNAME+1];
 36440  
 36441    sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
 36442    for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
 36443    if( ii>0 ){
 36444      zDirname[ii] = '\0';
 36445    }else{
 36446      if( zDirname[0]!='/' ) zDirname[0] = '.';
 36447      zDirname[1] = 0;
 36448    }
 36449    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
 36450    if( fd>=0 ){
 36451      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
 36452    }
 36453    *pFd = fd;
 36454    if( fd>=0 ) return SQLITE_OK;
 36455    return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
 36456  }
 36457  
 36458  /*
 36459  ** Make sure all writes to a particular file are committed to disk.
 36460  **
 36461  ** If dataOnly==0 then both the file itself and its metadata (file
 36462  ** size, access time, etc) are synced.  If dataOnly!=0 then only the
 36463  ** file data is synced.
 36464  **
 36465  ** Under Unix, also make sure that the directory entry for the file
 36466  ** has been created by fsync-ing the directory that contains the file.
 36467  ** If we do not do this and we encounter a power failure, the directory
 36468  ** entry for the journal might not exist after we reboot.  The next
 36469  ** SQLite to access the file will not know that the journal exists (because
 36470  ** the directory entry for the journal was never created) and the transaction
 36471  ** will not roll back - possibly leading to database corruption.
 36472  */
 36473  static int unixSync(sqlite3_file *id, int flags){
 36474    int rc;
 36475    unixFile *pFile = (unixFile*)id;
 36476  
 36477    int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
 36478    int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
 36479  
 36480    /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 36481    assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 36482        || (flags&0x0F)==SQLITE_SYNC_FULL
 36483    );
 36484  
 36485    /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 36486    ** line is to test that doing so does not cause any problems.
 36487    */
 36488    SimulateDiskfullError( return SQLITE_FULL );
 36489  
 36490    assert( pFile );
 36491    OSTRACE(("SYNC    %-3d\n", pFile->h));
 36492    rc = full_fsync(pFile->h, isFullsync, isDataOnly);
 36493    SimulateIOError( rc=1 );
 36494    if( rc ){
 36495      storeLastErrno(pFile, errno);
 36496      return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
 36497    }
 36498  
 36499    /* Also fsync the directory containing the file if the DIRSYNC flag
 36500    ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
 36501    ** are unable to fsync a directory, so ignore errors on the fsync.
 36502    */
 36503    if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
 36504      int dirfd;
 36505      OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
 36506              HAVE_FULLFSYNC, isFullsync));
 36507      rc = osOpenDirectory(pFile->zPath, &dirfd);
 36508      if( rc==SQLITE_OK ){
 36509        full_fsync(dirfd, 0, 0);
 36510        robust_close(pFile, dirfd, __LINE__);
 36511      }else{
 36512        assert( rc==SQLITE_CANTOPEN );
 36513        rc = SQLITE_OK;
 36514      }
 36515      pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
 36516    }
 36517    return rc;
 36518  }
 36519  
 36520  /*
 36521  ** Truncate an open file to a specified size
 36522  */
 36523  static int unixTruncate(sqlite3_file *id, i64 nByte){
 36524    unixFile *pFile = (unixFile *)id;
 36525    int rc;
 36526    assert( pFile );
 36527    SimulateIOError( return SQLITE_IOERR_TRUNCATE );
 36528  
 36529    /* If the user has configured a chunk-size for this file, truncate the
 36530    ** file so that it consists of an integer number of chunks (i.e. the
 36531    ** actual file size after the operation may be larger than the requested
 36532    ** size).
 36533    */
 36534    if( pFile->szChunk>0 ){
 36535      nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 36536    }
 36537  
 36538    rc = robust_ftruncate(pFile->h, nByte);
 36539    if( rc ){
 36540      storeLastErrno(pFile, errno);
 36541      return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 36542    }else{
 36543  #ifdef SQLITE_DEBUG
 36544      /* If we are doing a normal write to a database file (as opposed to
 36545      ** doing a hot-journal rollback or a write to some file other than a
 36546      ** normal database file) and we truncate the file to zero length,
 36547      ** that effectively updates the change counter.  This might happen
 36548      ** when restoring a database using the backup API from a zero-length
 36549      ** source.
 36550      */
 36551      if( pFile->inNormalWrite && nByte==0 ){
 36552        pFile->transCntrChng = 1;
 36553      }
 36554  #endif
 36555  
 36556  #if SQLITE_MAX_MMAP_SIZE>0
 36557      /* If the file was just truncated to a size smaller than the currently
 36558      ** mapped region, reduce the effective mapping size as well. SQLite will
 36559      ** use read() and write() to access data beyond this point from now on.  
 36560      */
 36561      if( nByte<pFile->mmapSize ){
 36562        pFile->mmapSize = nByte;
 36563      }
 36564  #endif
 36565  
 36566      return SQLITE_OK;
 36567    }
 36568  }
 36569  
 36570  /*
 36571  ** Determine the current size of a file in bytes
 36572  */
 36573  static int unixFileSize(sqlite3_file *id, i64 *pSize){
 36574    int rc;
 36575    struct stat buf;
 36576    assert( id );
 36577    rc = osFstat(((unixFile*)id)->h, &buf);
 36578    SimulateIOError( rc=1 );
 36579    if( rc!=0 ){
 36580      storeLastErrno((unixFile*)id, errno);
 36581      return SQLITE_IOERR_FSTAT;
 36582    }
 36583    *pSize = buf.st_size;
 36584  
 36585    /* When opening a zero-size database, the findInodeInfo() procedure
 36586    ** writes a single byte into that file in order to work around a bug
 36587    ** in the OS-X msdos filesystem.  In order to avoid problems with upper
 36588    ** layers, we need to report this file size as zero even though it is
 36589    ** really 1.   Ticket #3260.
 36590    */
 36591    if( *pSize==1 ) *pSize = 0;
 36592  
 36593  
 36594    return SQLITE_OK;
 36595  }
 36596  
 36597  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 36598  /*
 36599  ** Handler for proxy-locking file-control verbs.  Defined below in the
 36600  ** proxying locking division.
 36601  */
 36602  static int proxyFileControl(sqlite3_file*,int,void*);
 36603  #endif
 36604  
 36605  /* 
 36606  ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
 36607  ** file-control operation.  Enlarge the database to nBytes in size
 36608  ** (rounded up to the next chunk-size).  If the database is already
 36609  ** nBytes or larger, this routine is a no-op.
 36610  */
 36611  static int fcntlSizeHint(unixFile *pFile, i64 nByte){
 36612    if( pFile->szChunk>0 ){
 36613      i64 nSize;                    /* Required file size */
 36614      struct stat buf;              /* Used to hold return values of fstat() */
 36615     
 36616      if( osFstat(pFile->h, &buf) ){
 36617        return SQLITE_IOERR_FSTAT;
 36618      }
 36619  
 36620      nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
 36621      if( nSize>(i64)buf.st_size ){
 36622  
 36623  #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
 36624        /* The code below is handling the return value of osFallocate() 
 36625        ** correctly. posix_fallocate() is defined to "returns zero on success, 
 36626        ** or an error number on  failure". See the manpage for details. */
 36627        int err;
 36628        do{
 36629          err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
 36630        }while( err==EINTR );
 36631        if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
 36632  #else
 36633        /* If the OS does not have posix_fallocate(), fake it. Write a 
 36634        ** single byte to the last byte in each block that falls entirely
 36635        ** within the extended region. Then, if required, a single byte
 36636        ** at offset (nSize-1), to set the size of the file correctly.
 36637        ** This is a similar technique to that used by glibc on systems
 36638        ** that do not have a real fallocate() call.
 36639        */
 36640        int nBlk = buf.st_blksize;  /* File-system block size */
 36641        int nWrite = 0;             /* Number of bytes written by seekAndWrite */
 36642        i64 iWrite;                 /* Next offset to write to */
 36643  
 36644        iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
 36645        assert( iWrite>=buf.st_size );
 36646        assert( ((iWrite+1)%nBlk)==0 );
 36647        for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
 36648          if( iWrite>=nSize ) iWrite = nSize - 1;
 36649          nWrite = seekAndWrite(pFile, iWrite, "", 1);
 36650          if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
 36651        }
 36652  #endif
 36653      }
 36654    }
 36655  
 36656  #if SQLITE_MAX_MMAP_SIZE>0
 36657    if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
 36658      int rc;
 36659      if( pFile->szChunk<=0 ){
 36660        if( robust_ftruncate(pFile->h, nByte) ){
 36661          storeLastErrno(pFile, errno);
 36662          return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
 36663        }
 36664      }
 36665  
 36666      rc = unixMapfile(pFile, nByte);
 36667      return rc;
 36668    }
 36669  #endif
 36670  
 36671    return SQLITE_OK;
 36672  }
 36673  
 36674  /*
 36675  ** If *pArg is initially negative then this is a query.  Set *pArg to
 36676  ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 36677  **
 36678  ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 36679  */
 36680  static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
 36681    if( *pArg<0 ){
 36682      *pArg = (pFile->ctrlFlags & mask)!=0;
 36683    }else if( (*pArg)==0 ){
 36684      pFile->ctrlFlags &= ~mask;
 36685    }else{
 36686      pFile->ctrlFlags |= mask;
 36687    }
 36688  }
 36689  
 36690  /* Forward declaration */
 36691  static int unixGetTempname(int nBuf, char *zBuf);
 36692  
 36693  /*
 36694  ** Information and control of an open file handle.
 36695  */
 36696  static int unixFileControl(sqlite3_file *id, int op, void *pArg){
 36697    unixFile *pFile = (unixFile*)id;
 36698    switch( op ){
 36699  #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 36700      case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
 36701        int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
 36702        return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
 36703      }
 36704      case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
 36705        int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
 36706        return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
 36707      }
 36708      case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
 36709        int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
 36710        return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
 36711      }
 36712  #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
 36713  
 36714      case SQLITE_FCNTL_LOCKSTATE: {
 36715        *(int*)pArg = pFile->eFileLock;
 36716        return SQLITE_OK;
 36717      }
 36718      case SQLITE_FCNTL_LAST_ERRNO: {
 36719        *(int*)pArg = pFile->lastErrno;
 36720        return SQLITE_OK;
 36721      }
 36722      case SQLITE_FCNTL_CHUNK_SIZE: {
 36723        pFile->szChunk = *(int *)pArg;
 36724        return SQLITE_OK;
 36725      }
 36726      case SQLITE_FCNTL_SIZE_HINT: {
 36727        int rc;
 36728        SimulateIOErrorBenign(1);
 36729        rc = fcntlSizeHint(pFile, *(i64 *)pArg);
 36730        SimulateIOErrorBenign(0);
 36731        return rc;
 36732      }
 36733      case SQLITE_FCNTL_PERSIST_WAL: {
 36734        unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
 36735        return SQLITE_OK;
 36736      }
 36737      case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 36738        unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
 36739        return SQLITE_OK;
 36740      }
 36741      case SQLITE_FCNTL_VFSNAME: {
 36742        *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 36743        return SQLITE_OK;
 36744      }
 36745      case SQLITE_FCNTL_TEMPFILENAME: {
 36746        char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
 36747        if( zTFile ){
 36748          unixGetTempname(pFile->pVfs->mxPathname, zTFile);
 36749          *(char**)pArg = zTFile;
 36750        }
 36751        return SQLITE_OK;
 36752      }
 36753      case SQLITE_FCNTL_HAS_MOVED: {
 36754        *(int*)pArg = fileHasMoved(pFile);
 36755        return SQLITE_OK;
 36756      }
 36757  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
 36758      case SQLITE_FCNTL_LOCK_TIMEOUT: {
 36759        pFile->iBusyTimeout = *(int*)pArg;
 36760        return SQLITE_OK;
 36761      }
 36762  #endif
 36763  #if SQLITE_MAX_MMAP_SIZE>0
 36764      case SQLITE_FCNTL_MMAP_SIZE: {
 36765        i64 newLimit = *(i64*)pArg;
 36766        int rc = SQLITE_OK;
 36767        if( newLimit>sqlite3GlobalConfig.mxMmap ){
 36768          newLimit = sqlite3GlobalConfig.mxMmap;
 36769        }
 36770  
 36771        /* The value of newLimit may be eventually cast to (size_t) and passed
 36772        ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
 36773        ** 64-bit type. */
 36774        if( newLimit>0 && sizeof(size_t)<8 ){
 36775          newLimit = (newLimit & 0x7FFFFFFF);
 36776        }
 36777  
 36778        *(i64*)pArg = pFile->mmapSizeMax;
 36779        if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 36780          pFile->mmapSizeMax = newLimit;
 36781          if( pFile->mmapSize>0 ){
 36782            unixUnmapfile(pFile);
 36783            rc = unixMapfile(pFile, -1);
 36784          }
 36785        }
 36786        return rc;
 36787      }
 36788  #endif
 36789  #ifdef SQLITE_DEBUG
 36790      /* The pager calls this method to signal that it has done
 36791      ** a rollback and that the database is therefore unchanged and
 36792      ** it hence it is OK for the transaction change counter to be
 36793      ** unchanged.
 36794      */
 36795      case SQLITE_FCNTL_DB_UNCHANGED: {
 36796        ((unixFile*)id)->dbUpdate = 0;
 36797        return SQLITE_OK;
 36798      }
 36799  #endif
 36800  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 36801      case SQLITE_FCNTL_SET_LOCKPROXYFILE:
 36802      case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
 36803        return proxyFileControl(id,op,pArg);
 36804      }
 36805  #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
 36806    }
 36807    return SQLITE_NOTFOUND;
 36808  }
 36809  
 36810  /*
 36811  ** If pFd->sectorSize is non-zero when this function is called, it is a
 36812  ** no-op. Otherwise, the values of pFd->sectorSize and 
 36813  ** pFd->deviceCharacteristics are set according to the file-system 
 36814  ** characteristics. 
 36815  **
 36816  ** There are two versions of this function. One for QNX and one for all
 36817  ** other systems.
 36818  */
 36819  #ifndef __QNXNTO__
 36820  static void setDeviceCharacteristics(unixFile *pFd){
 36821    assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
 36822    if( pFd->sectorSize==0 ){
 36823  #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 36824      int res;
 36825      u32 f = 0;
 36826  
 36827      /* Check for support for F2FS atomic batch writes. */
 36828      res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
 36829      if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
 36830        pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
 36831      }
 36832  #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
 36833  
 36834      /* Set the POWERSAFE_OVERWRITE flag if requested. */
 36835      if( pFd->ctrlFlags & UNIXFILE_PSOW ){
 36836        pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
 36837      }
 36838  
 36839      pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 36840    }
 36841  }
 36842  #else
 36843  #include <sys/dcmd_blk.h>
 36844  #include <sys/statvfs.h>
 36845  static void setDeviceCharacteristics(unixFile *pFile){
 36846    if( pFile->sectorSize == 0 ){
 36847      struct statvfs fsInfo;
 36848         
 36849      /* Set defaults for non-supported filesystems */
 36850      pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 36851      pFile->deviceCharacteristics = 0;
 36852      if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
 36853        return;
 36854      }
 36855  
 36856      if( !strcmp(fsInfo.f_basetype, "tmp") ) {
 36857        pFile->sectorSize = fsInfo.f_bsize;
 36858        pFile->deviceCharacteristics =
 36859          SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
 36860          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 36861                                        ** the write succeeds */
 36862          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 36863                                        ** so it is ordered */
 36864          0;
 36865      }else if( strstr(fsInfo.f_basetype, "etfs") ){
 36866        pFile->sectorSize = fsInfo.f_bsize;
 36867        pFile->deviceCharacteristics =
 36868          /* etfs cluster size writes are atomic */
 36869          (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
 36870          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 36871                                        ** the write succeeds */
 36872          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 36873                                        ** so it is ordered */
 36874          0;
 36875      }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
 36876        pFile->sectorSize = fsInfo.f_bsize;
 36877        pFile->deviceCharacteristics =
 36878          SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
 36879          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 36880                                        ** the write succeeds */
 36881          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 36882                                        ** so it is ordered */
 36883          0;
 36884      }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
 36885        pFile->sectorSize = fsInfo.f_bsize;
 36886        pFile->deviceCharacteristics =
 36887          /* full bitset of atomics from max sector size and smaller */
 36888          ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 36889          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 36890                                        ** so it is ordered */
 36891          0;
 36892      }else if( strstr(fsInfo.f_basetype, "dos") ){
 36893        pFile->sectorSize = fsInfo.f_bsize;
 36894        pFile->deviceCharacteristics =
 36895          /* full bitset of atomics from max sector size and smaller */
 36896          ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
 36897          SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
 36898                                        ** so it is ordered */
 36899          0;
 36900      }else{
 36901        pFile->deviceCharacteristics =
 36902          SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
 36903          SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
 36904                                        ** the write succeeds */
 36905          0;
 36906      }
 36907    }
 36908    /* Last chance verification.  If the sector size isn't a multiple of 512
 36909    ** then it isn't valid.*/
 36910    if( pFile->sectorSize % 512 != 0 ){
 36911      pFile->deviceCharacteristics = 0;
 36912      pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
 36913    }
 36914  }
 36915  #endif
 36916  
 36917  /*
 36918  ** Return the sector size in bytes of the underlying block device for
 36919  ** the specified file. This is almost always 512 bytes, but may be
 36920  ** larger for some devices.
 36921  **
 36922  ** SQLite code assumes this function cannot fail. It also assumes that
 36923  ** if two files are created in the same file-system directory (i.e.
 36924  ** a database and its journal file) that the sector size will be the
 36925  ** same for both.
 36926  */
 36927  static int unixSectorSize(sqlite3_file *id){
 36928    unixFile *pFd = (unixFile*)id;
 36929    setDeviceCharacteristics(pFd);
 36930    return pFd->sectorSize;
 36931  }
 36932  
 36933  /*
 36934  ** Return the device characteristics for the file.
 36935  **
 36936  ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
 36937  ** However, that choice is controversial since technically the underlying
 36938  ** file system does not always provide powersafe overwrites.  (In other
 36939  ** words, after a power-loss event, parts of the file that were never
 36940  ** written might end up being altered.)  However, non-PSOW behavior is very,
 36941  ** very rare.  And asserting PSOW makes a large reduction in the amount
 36942  ** of required I/O for journaling, since a lot of padding is eliminated.
 36943  **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
 36944  ** available to turn it off and URI query parameter available to turn it off.
 36945  */
 36946  static int unixDeviceCharacteristics(sqlite3_file *id){
 36947    unixFile *pFd = (unixFile*)id;
 36948    setDeviceCharacteristics(pFd);
 36949    return pFd->deviceCharacteristics;
 36950  }
 36951  
 36952  #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 36953  
 36954  /*
 36955  ** Return the system page size.
 36956  **
 36957  ** This function should not be called directly by other code in this file. 
 36958  ** Instead, it should be called via macro osGetpagesize().
 36959  */
 36960  static int unixGetpagesize(void){
 36961  #if OS_VXWORKS
 36962    return 1024;
 36963  #elif defined(_BSD_SOURCE)
 36964    return getpagesize();
 36965  #else
 36966    return (int)sysconf(_SC_PAGESIZE);
 36967  #endif
 36968  }
 36969  
 36970  #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
 36971  
 36972  #ifndef SQLITE_OMIT_WAL
 36973  
 36974  /*
 36975  ** Object used to represent an shared memory buffer.  
 36976  **
 36977  ** When multiple threads all reference the same wal-index, each thread
 36978  ** has its own unixShm object, but they all point to a single instance
 36979  ** of this unixShmNode object.  In other words, each wal-index is opened
 36980  ** only once per process.
 36981  **
 36982  ** Each unixShmNode object is connected to a single unixInodeInfo object.
 36983  ** We could coalesce this object into unixInodeInfo, but that would mean
 36984  ** every open file that does not use shared memory (in other words, most
 36985  ** open files) would have to carry around this extra information.  So
 36986  ** the unixInodeInfo object contains a pointer to this unixShmNode object
 36987  ** and the unixShmNode object is created only when needed.
 36988  **
 36989  ** unixMutexHeld() must be true when creating or destroying
 36990  ** this object or while reading or writing the following fields:
 36991  **
 36992  **      nRef
 36993  **
 36994  ** The following fields are read-only after the object is created:
 36995  ** 
 36996  **      hShm
 36997  **      zFilename
 36998  **
 36999  ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
 37000  ** unixMutexHeld() is true when reading or writing any other field
 37001  ** in this structure.
 37002  */
 37003  struct unixShmNode {
 37004    unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
 37005    sqlite3_mutex *pShmMutex;  /* Mutex to access this object */
 37006    char *zFilename;           /* Name of the mmapped file */
 37007    int hShm;                  /* Open file descriptor */
 37008    int szRegion;              /* Size of shared-memory regions */
 37009    u16 nRegion;               /* Size of array apRegion */
 37010    u8 isReadonly;             /* True if read-only */
 37011    u8 isUnlocked;             /* True if no DMS lock held */
 37012    char **apRegion;           /* Array of mapped shared-memory regions */
 37013    int nRef;                  /* Number of unixShm objects pointing to this */
 37014    unixShm *pFirst;           /* All unixShm objects pointing to this */
 37015  #ifdef SQLITE_DEBUG
 37016    u8 exclMask;               /* Mask of exclusive locks held */
 37017    u8 sharedMask;             /* Mask of shared locks held */
 37018    u8 nextShmId;              /* Next available unixShm.id value */
 37019  #endif
 37020  };
 37021  
 37022  /*
 37023  ** Structure used internally by this VFS to record the state of an
 37024  ** open shared memory connection.
 37025  **
 37026  ** The following fields are initialized when this object is created and
 37027  ** are read-only thereafter:
 37028  **
 37029  **    unixShm.pShmNode
 37030  **    unixShm.id
 37031  **
 37032  ** All other fields are read/write.  The unixShm.pShmNode->pShmMutex must
 37033  ** be held while accessing any read/write fields.
 37034  */
 37035  struct unixShm {
 37036    unixShmNode *pShmNode;     /* The underlying unixShmNode object */
 37037    unixShm *pNext;            /* Next unixShm with the same unixShmNode */
 37038    u8 hasMutex;               /* True if holding the unixShmNode->pShmMutex */
 37039    u8 id;                     /* Id of this connection within its unixShmNode */
 37040    u16 sharedMask;            /* Mask of shared locks held */
 37041    u16 exclMask;              /* Mask of exclusive locks held */
 37042  };
 37043  
 37044  /*
 37045  ** Constants used for locking
 37046  */
 37047  #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
 37048  #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 37049  
 37050  /*
 37051  ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
 37052  **
 37053  ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
 37054  ** otherwise.
 37055  */
 37056  static int unixShmSystemLock(
 37057    unixFile *pFile,       /* Open connection to the WAL file */
 37058    int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
 37059    int ofst,              /* First byte of the locking range */
 37060    int n                  /* Number of bytes to lock */
 37061  ){
 37062    unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
 37063    struct flock f;        /* The posix advisory locking structure */
 37064    int rc = SQLITE_OK;    /* Result code form fcntl() */
 37065  
 37066    /* Access to the unixShmNode object is serialized by the caller */
 37067    pShmNode = pFile->pInode->pShmNode;
 37068    assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
 37069    assert( pShmNode->nRef>0 || unixMutexHeld() );
 37070  
 37071    /* Shared locks never span more than one byte */
 37072    assert( n==1 || lockType!=F_RDLCK );
 37073  
 37074    /* Locks are within range */
 37075    assert( n>=1 && n<=SQLITE_SHM_NLOCK );
 37076  
 37077    if( pShmNode->hShm>=0 ){
 37078      /* Initialize the locking parameters */
 37079      f.l_type = lockType;
 37080      f.l_whence = SEEK_SET;
 37081      f.l_start = ofst;
 37082      f.l_len = n;
 37083      rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
 37084      rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
 37085    }
 37086  
 37087    /* Update the global lock state and do debug tracing */
 37088  #ifdef SQLITE_DEBUG
 37089    { u16 mask;
 37090    OSTRACE(("SHM-LOCK "));
 37091    mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
 37092    if( rc==SQLITE_OK ){
 37093      if( lockType==F_UNLCK ){
 37094        OSTRACE(("unlock %d ok", ofst));
 37095        pShmNode->exclMask &= ~mask;
 37096        pShmNode->sharedMask &= ~mask;
 37097      }else if( lockType==F_RDLCK ){
 37098        OSTRACE(("read-lock %d ok", ofst));
 37099        pShmNode->exclMask &= ~mask;
 37100        pShmNode->sharedMask |= mask;
 37101      }else{
 37102        assert( lockType==F_WRLCK );
 37103        OSTRACE(("write-lock %d ok", ofst));
 37104        pShmNode->exclMask |= mask;
 37105        pShmNode->sharedMask &= ~mask;
 37106      }
 37107    }else{
 37108      if( lockType==F_UNLCK ){
 37109        OSTRACE(("unlock %d failed", ofst));
 37110      }else if( lockType==F_RDLCK ){
 37111        OSTRACE(("read-lock failed"));
 37112      }else{
 37113        assert( lockType==F_WRLCK );
 37114        OSTRACE(("write-lock %d failed", ofst));
 37115      }
 37116    }
 37117    OSTRACE((" - afterwards %03x,%03x\n",
 37118             pShmNode->sharedMask, pShmNode->exclMask));
 37119    }
 37120  #endif
 37121  
 37122    return rc;        
 37123  }
 37124  
 37125  /*
 37126  ** Return the minimum number of 32KB shm regions that should be mapped at
 37127  ** a time, assuming that each mapping must be an integer multiple of the
 37128  ** current system page-size.
 37129  **
 37130  ** Usually, this is 1. The exception seems to be systems that are configured
 37131  ** to use 64KB pages - in this case each mapping must cover at least two
 37132  ** shm regions.
 37133  */
 37134  static int unixShmRegionPerMap(void){
 37135    int shmsz = 32*1024;            /* SHM region size */
 37136    int pgsz = osGetpagesize();   /* System page size */
 37137    assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
 37138    if( pgsz<shmsz ) return 1;
 37139    return pgsz/shmsz;
 37140  }
 37141  
 37142  /*
 37143  ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
 37144  **
 37145  ** This is not a VFS shared-memory method; it is a utility function called
 37146  ** by VFS shared-memory methods.
 37147  */
 37148  static void unixShmPurge(unixFile *pFd){
 37149    unixShmNode *p = pFd->pInode->pShmNode;
 37150    assert( unixMutexHeld() );
 37151    if( p && ALWAYS(p->nRef==0) ){
 37152      int nShmPerMap = unixShmRegionPerMap();
 37153      int i;
 37154      assert( p->pInode==pFd->pInode );
 37155      sqlite3_mutex_free(p->pShmMutex);
 37156      for(i=0; i<p->nRegion; i+=nShmPerMap){
 37157        if( p->hShm>=0 ){
 37158          osMunmap(p->apRegion[i], p->szRegion);
 37159        }else{
 37160          sqlite3_free(p->apRegion[i]);
 37161        }
 37162      }
 37163      sqlite3_free(p->apRegion);
 37164      if( p->hShm>=0 ){
 37165        robust_close(pFd, p->hShm, __LINE__);
 37166        p->hShm = -1;
 37167      }
 37168      p->pInode->pShmNode = 0;
 37169      sqlite3_free(p);
 37170    }
 37171  }
 37172  
 37173  /*
 37174  ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
 37175  ** take it now. Return SQLITE_OK if successful, or an SQLite error
 37176  ** code otherwise.
 37177  **
 37178  ** If the DMS cannot be locked because this is a readonly_shm=1 
 37179  ** connection and no other process already holds a lock, return
 37180  ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
 37181  */
 37182  static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
 37183    struct flock lock;
 37184    int rc = SQLITE_OK;
 37185  
 37186    /* Use F_GETLK to determine the locks other processes are holding
 37187    ** on the DMS byte. If it indicates that another process is holding
 37188    ** a SHARED lock, then this process may also take a SHARED lock
 37189    ** and proceed with opening the *-shm file. 
 37190    **
 37191    ** Or, if no other process is holding any lock, then this process
 37192    ** is the first to open it. In this case take an EXCLUSIVE lock on the
 37193    ** DMS byte and truncate the *-shm file to zero bytes in size. Then
 37194    ** downgrade to a SHARED lock on the DMS byte.
 37195    **
 37196    ** If another process is holding an EXCLUSIVE lock on the DMS byte,
 37197    ** return SQLITE_BUSY to the caller (it will try again). An earlier
 37198    ** version of this code attempted the SHARED lock at this point. But
 37199    ** this introduced a subtle race condition: if the process holding
 37200    ** EXCLUSIVE failed just before truncating the *-shm file, then this
 37201    ** process might open and use the *-shm file without truncating it.
 37202    ** And if the *-shm file has been corrupted by a power failure or
 37203    ** system crash, the database itself may also become corrupt.  */
 37204    lock.l_whence = SEEK_SET;
 37205    lock.l_start = UNIX_SHM_DMS;
 37206    lock.l_len = 1;
 37207    lock.l_type = F_WRLCK;
 37208    if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
 37209      rc = SQLITE_IOERR_LOCK;
 37210    }else if( lock.l_type==F_UNLCK ){
 37211      if( pShmNode->isReadonly ){
 37212        pShmNode->isUnlocked = 1;
 37213        rc = SQLITE_READONLY_CANTINIT;
 37214      }else{
 37215        rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
 37216        /* The first connection to attach must truncate the -shm file.  We
 37217        ** truncate to 3 bytes (an arbitrary small number, less than the
 37218        ** -shm header size) rather than 0 as a system debugging aid, to
 37219        ** help detect if a -shm file truncation is legitimate or is the work
 37220        ** or a rogue process. */
 37221        if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
 37222          rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
 37223        }
 37224      }
 37225    }else if( lock.l_type==F_WRLCK ){
 37226      rc = SQLITE_BUSY;
 37227    }
 37228  
 37229    if( rc==SQLITE_OK ){
 37230      assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
 37231      rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
 37232    }
 37233    return rc;
 37234  }
 37235  
 37236  /*
 37237  ** Open a shared-memory area associated with open database file pDbFd.  
 37238  ** This particular implementation uses mmapped files.
 37239  **
 37240  ** The file used to implement shared-memory is in the same directory
 37241  ** as the open database file and has the same name as the open database
 37242  ** file with the "-shm" suffix added.  For example, if the database file
 37243  ** is "/home/user1/config.db" then the file that is created and mmapped
 37244  ** for shared memory will be called "/home/user1/config.db-shm".  
 37245  **
 37246  ** Another approach to is to use files in /dev/shm or /dev/tmp or an
 37247  ** some other tmpfs mount. But if a file in a different directory
 37248  ** from the database file is used, then differing access permissions
 37249  ** or a chroot() might cause two different processes on the same
 37250  ** database to end up using different files for shared memory - 
 37251  ** meaning that their memory would not really be shared - resulting
 37252  ** in database corruption.  Nevertheless, this tmpfs file usage
 37253  ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
 37254  ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
 37255  ** option results in an incompatible build of SQLite;  builds of SQLite
 37256  ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
 37257  ** same database file at the same time, database corruption will likely
 37258  ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
 37259  ** "unsupported" and may go away in a future SQLite release.
 37260  **
 37261  ** When opening a new shared-memory file, if no other instances of that
 37262  ** file are currently open, in this process or in other processes, then
 37263  ** the file must be truncated to zero length or have its header cleared.
 37264  **
 37265  ** If the original database file (pDbFd) is using the "unix-excl" VFS
 37266  ** that means that an exclusive lock is held on the database file and
 37267  ** that no other processes are able to read or write the database.  In
 37268  ** that case, we do not really need shared memory.  No shared memory
 37269  ** file is created.  The shared memory will be simulated with heap memory.
 37270  */
 37271  static int unixOpenSharedMemory(unixFile *pDbFd){
 37272    struct unixShm *p = 0;          /* The connection to be opened */
 37273    struct unixShmNode *pShmNode;   /* The underlying mmapped file */
 37274    int rc = SQLITE_OK;             /* Result code */
 37275    unixInodeInfo *pInode;          /* The inode of fd */
 37276    char *zShm;             /* Name of the file used for SHM */
 37277    int nShmFilename;               /* Size of the SHM filename in bytes */
 37278  
 37279    /* Allocate space for the new unixShm object. */
 37280    p = sqlite3_malloc64( sizeof(*p) );
 37281    if( p==0 ) return SQLITE_NOMEM_BKPT;
 37282    memset(p, 0, sizeof(*p));
 37283    assert( pDbFd->pShm==0 );
 37284  
 37285    /* Check to see if a unixShmNode object already exists. Reuse an existing
 37286    ** one if present. Create a new one if necessary.
 37287    */
 37288    assert( unixFileMutexNotheld(pDbFd) );
 37289    unixEnterMutex();
 37290    pInode = pDbFd->pInode;
 37291    pShmNode = pInode->pShmNode;
 37292    if( pShmNode==0 ){
 37293      struct stat sStat;                 /* fstat() info for database file */
 37294  #ifndef SQLITE_SHM_DIRECTORY
 37295      const char *zBasePath = pDbFd->zPath;
 37296  #endif
 37297  
 37298      /* Call fstat() to figure out the permissions on the database file. If
 37299      ** a new *-shm file is created, an attempt will be made to create it
 37300      ** with the same permissions.
 37301      */
 37302      if( osFstat(pDbFd->h, &sStat) ){
 37303        rc = SQLITE_IOERR_FSTAT;
 37304        goto shm_open_err;
 37305      }
 37306  
 37307  #ifdef SQLITE_SHM_DIRECTORY
 37308      nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
 37309  #else
 37310      nShmFilename = 6 + (int)strlen(zBasePath);
 37311  #endif
 37312      pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
 37313      if( pShmNode==0 ){
 37314        rc = SQLITE_NOMEM_BKPT;
 37315        goto shm_open_err;
 37316      }
 37317      memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
 37318      zShm = pShmNode->zFilename = (char*)&pShmNode[1];
 37319  #ifdef SQLITE_SHM_DIRECTORY
 37320      sqlite3_snprintf(nShmFilename, zShm, 
 37321                       SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
 37322                       (u32)sStat.st_ino, (u32)sStat.st_dev);
 37323  #else
 37324      sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
 37325      sqlite3FileSuffix3(pDbFd->zPath, zShm);
 37326  #endif
 37327      pShmNode->hShm = -1;
 37328      pDbFd->pInode->pShmNode = pShmNode;
 37329      pShmNode->pInode = pDbFd->pInode;
 37330      if( sqlite3GlobalConfig.bCoreMutex ){
 37331        pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 37332        if( pShmNode->pShmMutex==0 ){
 37333          rc = SQLITE_NOMEM_BKPT;
 37334          goto shm_open_err;
 37335        }
 37336      }
 37337  
 37338      if( pInode->bProcessLock==0 ){
 37339        if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 37340          pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
 37341        }
 37342        if( pShmNode->hShm<0 ){
 37343          pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
 37344          if( pShmNode->hShm<0 ){
 37345            rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
 37346            goto shm_open_err;
 37347          }
 37348          pShmNode->isReadonly = 1;
 37349        }
 37350  
 37351        /* If this process is running as root, make sure that the SHM file
 37352        ** is owned by the same user that owns the original database.  Otherwise,
 37353        ** the original owner will not be able to connect.
 37354        */
 37355        robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
 37356  
 37357        rc = unixLockSharedMemory(pDbFd, pShmNode);
 37358        if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
 37359      }
 37360    }
 37361  
 37362    /* Make the new connection a child of the unixShmNode */
 37363    p->pShmNode = pShmNode;
 37364  #ifdef SQLITE_DEBUG
 37365    p->id = pShmNode->nextShmId++;
 37366  #endif
 37367    pShmNode->nRef++;
 37368    pDbFd->pShm = p;
 37369    unixLeaveMutex();
 37370  
 37371    /* The reference count on pShmNode has already been incremented under
 37372    ** the cover of the unixEnterMutex() mutex and the pointer from the
 37373    ** new (struct unixShm) object to the pShmNode has been set. All that is
 37374    ** left to do is to link the new object into the linked list starting
 37375    ** at pShmNode->pFirst. This must be done while holding the
 37376    ** pShmNode->pShmMutex.
 37377    */
 37378    sqlite3_mutex_enter(pShmNode->pShmMutex);
 37379    p->pNext = pShmNode->pFirst;
 37380    pShmNode->pFirst = p;
 37381    sqlite3_mutex_leave(pShmNode->pShmMutex);
 37382    return rc;
 37383  
 37384    /* Jump here on any error */
 37385  shm_open_err:
 37386    unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
 37387    sqlite3_free(p);
 37388    unixLeaveMutex();
 37389    return rc;
 37390  }
 37391  
 37392  /*
 37393  ** This function is called to obtain a pointer to region iRegion of the 
 37394  ** shared-memory associated with the database file fd. Shared-memory regions 
 37395  ** are numbered starting from zero. Each shared-memory region is szRegion 
 37396  ** bytes in size.
 37397  **
 37398  ** If an error occurs, an error code is returned and *pp is set to NULL.
 37399  **
 37400  ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
 37401  ** region has not been allocated (by any client, including one running in a
 37402  ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
 37403  ** bExtend is non-zero and the requested shared-memory region has not yet 
 37404  ** been allocated, it is allocated by this function.
 37405  **
 37406  ** If the shared-memory region has already been allocated or is allocated by
 37407  ** this call as described above, then it is mapped into this processes 
 37408  ** address space (if it is not already), *pp is set to point to the mapped 
 37409  ** memory and SQLITE_OK returned.
 37410  */
 37411  static int unixShmMap(
 37412    sqlite3_file *fd,               /* Handle open on database file */
 37413    int iRegion,                    /* Region to retrieve */
 37414    int szRegion,                   /* Size of regions */
 37415    int bExtend,                    /* True to extend file if necessary */
 37416    void volatile **pp              /* OUT: Mapped memory */
 37417  ){
 37418    unixFile *pDbFd = (unixFile*)fd;
 37419    unixShm *p;
 37420    unixShmNode *pShmNode;
 37421    int rc = SQLITE_OK;
 37422    int nShmPerMap = unixShmRegionPerMap();
 37423    int nReqRegion;
 37424  
 37425    /* If the shared-memory file has not yet been opened, open it now. */
 37426    if( pDbFd->pShm==0 ){
 37427      rc = unixOpenSharedMemory(pDbFd);
 37428      if( rc!=SQLITE_OK ) return rc;
 37429    }
 37430  
 37431    p = pDbFd->pShm;
 37432    pShmNode = p->pShmNode;
 37433    sqlite3_mutex_enter(pShmNode->pShmMutex);
 37434    if( pShmNode->isUnlocked ){
 37435      rc = unixLockSharedMemory(pDbFd, pShmNode);
 37436      if( rc!=SQLITE_OK ) goto shmpage_out;
 37437      pShmNode->isUnlocked = 0;
 37438    }
 37439    assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 37440    assert( pShmNode->pInode==pDbFd->pInode );
 37441    assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
 37442    assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
 37443  
 37444    /* Minimum number of regions required to be mapped. */
 37445    nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
 37446  
 37447    if( pShmNode->nRegion<nReqRegion ){
 37448      char **apNew;                      /* New apRegion[] array */
 37449      int nByte = nReqRegion*szRegion;   /* Minimum required file size */
 37450      struct stat sStat;                 /* Used by fstat() */
 37451  
 37452      pShmNode->szRegion = szRegion;
 37453  
 37454      if( pShmNode->hShm>=0 ){
 37455        /* The requested region is not mapped into this processes address space.
 37456        ** Check to see if it has been allocated (i.e. if the wal-index file is
 37457        ** large enough to contain the requested region).
 37458        */
 37459        if( osFstat(pShmNode->hShm, &sStat) ){
 37460          rc = SQLITE_IOERR_SHMSIZE;
 37461          goto shmpage_out;
 37462        }
 37463    
 37464        if( sStat.st_size<nByte ){
 37465          /* The requested memory region does not exist. If bExtend is set to
 37466          ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
 37467          */
 37468          if( !bExtend ){
 37469            goto shmpage_out;
 37470          }
 37471  
 37472          /* Alternatively, if bExtend is true, extend the file. Do this by
 37473          ** writing a single byte to the end of each (OS) page being
 37474          ** allocated or extended. Technically, we need only write to the
 37475          ** last page in order to extend the file. But writing to all new
 37476          ** pages forces the OS to allocate them immediately, which reduces
 37477          ** the chances of SIGBUS while accessing the mapped region later on.
 37478          */
 37479          else{
 37480            static const int pgsz = 4096;
 37481            int iPg;
 37482  
 37483            /* Write to the last byte of each newly allocated or extended page */
 37484            assert( (nByte % pgsz)==0 );
 37485            for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
 37486              int x = 0;
 37487              if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
 37488                const char *zFile = pShmNode->zFilename;
 37489                rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
 37490                goto shmpage_out;
 37491              }
 37492            }
 37493          }
 37494        }
 37495      }
 37496  
 37497      /* Map the requested memory region into this processes address space. */
 37498      apNew = (char **)sqlite3_realloc(
 37499          pShmNode->apRegion, nReqRegion*sizeof(char *)
 37500      );
 37501      if( !apNew ){
 37502        rc = SQLITE_IOERR_NOMEM_BKPT;
 37503        goto shmpage_out;
 37504      }
 37505      pShmNode->apRegion = apNew;
 37506      while( pShmNode->nRegion<nReqRegion ){
 37507        int nMap = szRegion*nShmPerMap;
 37508        int i;
 37509        void *pMem;
 37510        if( pShmNode->hShm>=0 ){
 37511          pMem = osMmap(0, nMap,
 37512              pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
 37513              MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
 37514          );
 37515          if( pMem==MAP_FAILED ){
 37516            rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
 37517            goto shmpage_out;
 37518          }
 37519        }else{
 37520          pMem = sqlite3_malloc64(nMap);
 37521          if( pMem==0 ){
 37522            rc = SQLITE_NOMEM_BKPT;
 37523            goto shmpage_out;
 37524          }
 37525          memset(pMem, 0, nMap);
 37526        }
 37527  
 37528        for(i=0; i<nShmPerMap; i++){
 37529          pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
 37530        }
 37531        pShmNode->nRegion += nShmPerMap;
 37532      }
 37533    }
 37534  
 37535  shmpage_out:
 37536    if( pShmNode->nRegion>iRegion ){
 37537      *pp = pShmNode->apRegion[iRegion];
 37538    }else{
 37539      *pp = 0;
 37540    }
 37541    if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
 37542    sqlite3_mutex_leave(pShmNode->pShmMutex);
 37543    return rc;
 37544  }
 37545  
 37546  /*
 37547  ** Change the lock state for a shared-memory segment.
 37548  **
 37549  ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
 37550  ** different here than in posix.  In xShmLock(), one can go from unlocked
 37551  ** to shared and back or from unlocked to exclusive and back.  But one may
 37552  ** not go from shared to exclusive or from exclusive to shared.
 37553  */
 37554  static int unixShmLock(
 37555    sqlite3_file *fd,          /* Database file holding the shared memory */
 37556    int ofst,                  /* First lock to acquire or release */
 37557    int n,                     /* Number of locks to acquire or release */
 37558    int flags                  /* What to do with the lock */
 37559  ){
 37560    unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
 37561    unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
 37562    unixShm *pX;                          /* For looping over all siblings */
 37563    unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
 37564    int rc = SQLITE_OK;                   /* Result code */
 37565    u16 mask;                             /* Mask of locks to take or release */
 37566  
 37567    assert( pShmNode==pDbFd->pInode->pShmNode );
 37568    assert( pShmNode->pInode==pDbFd->pInode );
 37569    assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 37570    assert( n>=1 );
 37571    assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 37572         || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 37573         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 37574         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 37575    assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 37576    assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
 37577    assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
 37578  
 37579    mask = (1<<(ofst+n)) - (1<<ofst);
 37580    assert( n>1 || mask==(1<<ofst) );
 37581    sqlite3_mutex_enter(pShmNode->pShmMutex);
 37582    if( flags & SQLITE_SHM_UNLOCK ){
 37583      u16 allMask = 0; /* Mask of locks held by siblings */
 37584  
 37585      /* See if any siblings hold this same lock */
 37586      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 37587        if( pX==p ) continue;
 37588        assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 37589        allMask |= pX->sharedMask;
 37590      }
 37591  
 37592      /* Unlock the system-level locks */
 37593      if( (mask & allMask)==0 ){
 37594        rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
 37595      }else{
 37596        rc = SQLITE_OK;
 37597      }
 37598  
 37599      /* Undo the local locks */
 37600      if( rc==SQLITE_OK ){
 37601        p->exclMask &= ~mask;
 37602        p->sharedMask &= ~mask;
 37603      } 
 37604    }else if( flags & SQLITE_SHM_SHARED ){
 37605      u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 37606  
 37607      /* Find out which shared locks are already held by sibling connections.
 37608      ** If any sibling already holds an exclusive lock, go ahead and return
 37609      ** SQLITE_BUSY.
 37610      */
 37611      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 37612        if( (pX->exclMask & mask)!=0 ){
 37613          rc = SQLITE_BUSY;
 37614          break;
 37615        }
 37616        allShared |= pX->sharedMask;
 37617      }
 37618  
 37619      /* Get shared locks at the system level, if necessary */
 37620      if( rc==SQLITE_OK ){
 37621        if( (allShared & mask)==0 ){
 37622          rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
 37623        }else{
 37624          rc = SQLITE_OK;
 37625        }
 37626      }
 37627  
 37628      /* Get the local shared locks */
 37629      if( rc==SQLITE_OK ){
 37630        p->sharedMask |= mask;
 37631      }
 37632    }else{
 37633      /* Make sure no sibling connections hold locks that will block this
 37634      ** lock.  If any do, return SQLITE_BUSY right away.
 37635      */
 37636      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 37637        if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 37638          rc = SQLITE_BUSY;
 37639          break;
 37640        }
 37641      }
 37642    
 37643      /* Get the exclusive locks at the system level.  Then if successful
 37644      ** also mark the local connection as being locked.
 37645      */
 37646      if( rc==SQLITE_OK ){
 37647        rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
 37648        if( rc==SQLITE_OK ){
 37649          assert( (p->sharedMask & mask)==0 );
 37650          p->exclMask |= mask;
 37651        }
 37652      }
 37653    }
 37654    sqlite3_mutex_leave(pShmNode->pShmMutex);
 37655    OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
 37656             p->id, osGetpid(0), p->sharedMask, p->exclMask));
 37657    return rc;
 37658  }
 37659  
 37660  /*
 37661  ** Implement a memory barrier or memory fence on shared memory.  
 37662  **
 37663  ** All loads and stores begun before the barrier must complete before
 37664  ** any load or store begun after the barrier.
 37665  */
 37666  static void unixShmBarrier(
 37667    sqlite3_file *fd                /* Database file holding the shared memory */
 37668  ){
 37669    UNUSED_PARAMETER(fd);
 37670    sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
 37671    assert( fd->pMethods->xLock==nolockLock 
 37672         || unixFileMutexNotheld((unixFile*)fd) 
 37673    );
 37674    unixEnterMutex();               /* Also mutex, for redundancy */
 37675    unixLeaveMutex();
 37676  }
 37677  
 37678  /*
 37679  ** Close a connection to shared-memory.  Delete the underlying 
 37680  ** storage if deleteFlag is true.
 37681  **
 37682  ** If there is no shared memory associated with the connection then this
 37683  ** routine is a harmless no-op.
 37684  */
 37685  static int unixShmUnmap(
 37686    sqlite3_file *fd,               /* The underlying database file */
 37687    int deleteFlag                  /* Delete shared-memory if true */
 37688  ){
 37689    unixShm *p;                     /* The connection to be closed */
 37690    unixShmNode *pShmNode;          /* The underlying shared-memory file */
 37691    unixShm **pp;                   /* For looping over sibling connections */
 37692    unixFile *pDbFd;                /* The underlying database file */
 37693  
 37694    pDbFd = (unixFile*)fd;
 37695    p = pDbFd->pShm;
 37696    if( p==0 ) return SQLITE_OK;
 37697    pShmNode = p->pShmNode;
 37698  
 37699    assert( pShmNode==pDbFd->pInode->pShmNode );
 37700    assert( pShmNode->pInode==pDbFd->pInode );
 37701  
 37702    /* Remove connection p from the set of connections associated
 37703    ** with pShmNode */
 37704    sqlite3_mutex_enter(pShmNode->pShmMutex);
 37705    for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 37706    *pp = p->pNext;
 37707  
 37708    /* Free the connection p */
 37709    sqlite3_free(p);
 37710    pDbFd->pShm = 0;
 37711    sqlite3_mutex_leave(pShmNode->pShmMutex);
 37712  
 37713    /* If pShmNode->nRef has reached 0, then close the underlying
 37714    ** shared-memory file, too */
 37715    assert( unixFileMutexNotheld(pDbFd) );
 37716    unixEnterMutex();
 37717    assert( pShmNode->nRef>0 );
 37718    pShmNode->nRef--;
 37719    if( pShmNode->nRef==0 ){
 37720      if( deleteFlag && pShmNode->hShm>=0 ){
 37721        osUnlink(pShmNode->zFilename);
 37722      }
 37723      unixShmPurge(pDbFd);
 37724    }
 37725    unixLeaveMutex();
 37726  
 37727    return SQLITE_OK;
 37728  }
 37729  
 37730  
 37731  #else
 37732  # define unixShmMap     0
 37733  # define unixShmLock    0
 37734  # define unixShmBarrier 0
 37735  # define unixShmUnmap   0
 37736  #endif /* #ifndef SQLITE_OMIT_WAL */
 37737  
 37738  #if SQLITE_MAX_MMAP_SIZE>0
 37739  /*
 37740  ** If it is currently memory mapped, unmap file pFd.
 37741  */
 37742  static void unixUnmapfile(unixFile *pFd){
 37743    assert( pFd->nFetchOut==0 );
 37744    if( pFd->pMapRegion ){
 37745      osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
 37746      pFd->pMapRegion = 0;
 37747      pFd->mmapSize = 0;
 37748      pFd->mmapSizeActual = 0;
 37749    }
 37750  }
 37751  
 37752  /*
 37753  ** Attempt to set the size of the memory mapping maintained by file 
 37754  ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
 37755  **
 37756  ** If successful, this function sets the following variables:
 37757  **
 37758  **       unixFile.pMapRegion
 37759  **       unixFile.mmapSize
 37760  **       unixFile.mmapSizeActual
 37761  **
 37762  ** If unsuccessful, an error message is logged via sqlite3_log() and
 37763  ** the three variables above are zeroed. In this case SQLite should
 37764  ** continue accessing the database using the xRead() and xWrite()
 37765  ** methods.
 37766  */
 37767  static void unixRemapfile(
 37768    unixFile *pFd,                  /* File descriptor object */
 37769    i64 nNew                        /* Required mapping size */
 37770  ){
 37771    const char *zErr = "mmap";
 37772    int h = pFd->h;                      /* File descriptor open on db file */
 37773    u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
 37774    i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
 37775    u8 *pNew = 0;                        /* Location of new mapping */
 37776    int flags = PROT_READ;               /* Flags to pass to mmap() */
 37777  
 37778    assert( pFd->nFetchOut==0 );
 37779    assert( nNew>pFd->mmapSize );
 37780    assert( nNew<=pFd->mmapSizeMax );
 37781    assert( nNew>0 );
 37782    assert( pFd->mmapSizeActual>=pFd->mmapSize );
 37783    assert( MAP_FAILED!=0 );
 37784  
 37785  #ifdef SQLITE_MMAP_READWRITE
 37786    if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
 37787  #endif
 37788  
 37789    if( pOrig ){
 37790  #if HAVE_MREMAP
 37791      i64 nReuse = pFd->mmapSize;
 37792  #else
 37793      const int szSyspage = osGetpagesize();
 37794      i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
 37795  #endif
 37796      u8 *pReq = &pOrig[nReuse];
 37797  
 37798      /* Unmap any pages of the existing mapping that cannot be reused. */
 37799      if( nReuse!=nOrig ){
 37800        osMunmap(pReq, nOrig-nReuse);
 37801      }
 37802  
 37803  #if HAVE_MREMAP
 37804      pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
 37805      zErr = "mremap";
 37806  #else
 37807      pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
 37808      if( pNew!=MAP_FAILED ){
 37809        if( pNew!=pReq ){
 37810          osMunmap(pNew, nNew - nReuse);
 37811          pNew = 0;
 37812        }else{
 37813          pNew = pOrig;
 37814        }
 37815      }
 37816  #endif
 37817  
 37818      /* The attempt to extend the existing mapping failed. Free it. */
 37819      if( pNew==MAP_FAILED || pNew==0 ){
 37820        osMunmap(pOrig, nReuse);
 37821      }
 37822    }
 37823  
 37824    /* If pNew is still NULL, try to create an entirely new mapping. */
 37825    if( pNew==0 ){
 37826      pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
 37827    }
 37828  
 37829    if( pNew==MAP_FAILED ){
 37830      pNew = 0;
 37831      nNew = 0;
 37832      unixLogError(SQLITE_OK, zErr, pFd->zPath);
 37833  
 37834      /* If the mmap() above failed, assume that all subsequent mmap() calls
 37835      ** will probably fail too. Fall back to using xRead/xWrite exclusively
 37836      ** in this case.  */
 37837      pFd->mmapSizeMax = 0;
 37838    }
 37839    pFd->pMapRegion = (void *)pNew;
 37840    pFd->mmapSize = pFd->mmapSizeActual = nNew;
 37841  }
 37842  
 37843  /*
 37844  ** Memory map or remap the file opened by file-descriptor pFd (if the file
 37845  ** is already mapped, the existing mapping is replaced by the new). Or, if 
 37846  ** there already exists a mapping for this file, and there are still 
 37847  ** outstanding xFetch() references to it, this function is a no-op.
 37848  **
 37849  ** If parameter nByte is non-negative, then it is the requested size of 
 37850  ** the mapping to create. Otherwise, if nByte is less than zero, then the 
 37851  ** requested size is the size of the file on disk. The actual size of the
 37852  ** created mapping is either the requested size or the value configured 
 37853  ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
 37854  **
 37855  ** SQLITE_OK is returned if no error occurs (even if the mapping is not
 37856  ** recreated as a result of outstanding references) or an SQLite error
 37857  ** code otherwise.
 37858  */
 37859  static int unixMapfile(unixFile *pFd, i64 nMap){
 37860    assert( nMap>=0 || pFd->nFetchOut==0 );
 37861    assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
 37862    if( pFd->nFetchOut>0 ) return SQLITE_OK;
 37863  
 37864    if( nMap<0 ){
 37865      struct stat statbuf;          /* Low-level file information */
 37866      if( osFstat(pFd->h, &statbuf) ){
 37867        return SQLITE_IOERR_FSTAT;
 37868      }
 37869      nMap = statbuf.st_size;
 37870    }
 37871    if( nMap>pFd->mmapSizeMax ){
 37872      nMap = pFd->mmapSizeMax;
 37873    }
 37874  
 37875    assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
 37876    if( nMap!=pFd->mmapSize ){
 37877      unixRemapfile(pFd, nMap);
 37878    }
 37879  
 37880    return SQLITE_OK;
 37881  }
 37882  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 37883  
 37884  /*
 37885  ** If possible, return a pointer to a mapping of file fd starting at offset
 37886  ** iOff. The mapping must be valid for at least nAmt bytes.
 37887  **
 37888  ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 37889  ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 37890  ** Finally, if an error does occur, return an SQLite error code. The final
 37891  ** value of *pp is undefined in this case.
 37892  **
 37893  ** If this function does return a pointer, the caller must eventually 
 37894  ** release the reference by calling unixUnfetch().
 37895  */
 37896  static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 37897  #if SQLITE_MAX_MMAP_SIZE>0
 37898    unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 37899  #endif
 37900    *pp = 0;
 37901  
 37902  #if SQLITE_MAX_MMAP_SIZE>0
 37903    if( pFd->mmapSizeMax>0 ){
 37904      if( pFd->pMapRegion==0 ){
 37905        int rc = unixMapfile(pFd, -1);
 37906        if( rc!=SQLITE_OK ) return rc;
 37907      }
 37908      if( pFd->mmapSize >= iOff+nAmt ){
 37909        *pp = &((u8 *)pFd->pMapRegion)[iOff];
 37910        pFd->nFetchOut++;
 37911      }
 37912    }
 37913  #endif
 37914    return SQLITE_OK;
 37915  }
 37916  
 37917  /*
 37918  ** If the third argument is non-NULL, then this function releases a 
 37919  ** reference obtained by an earlier call to unixFetch(). The second
 37920  ** argument passed to this function must be the same as the corresponding
 37921  ** argument that was passed to the unixFetch() invocation. 
 37922  **
 37923  ** Or, if the third argument is NULL, then this function is being called 
 37924  ** to inform the VFS layer that, according to POSIX, any existing mapping 
 37925  ** may now be invalid and should be unmapped.
 37926  */
 37927  static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 37928  #if SQLITE_MAX_MMAP_SIZE>0
 37929    unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
 37930    UNUSED_PARAMETER(iOff);
 37931  
 37932    /* If p==0 (unmap the entire file) then there must be no outstanding 
 37933    ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 37934    ** then there must be at least one outstanding.  */
 37935    assert( (p==0)==(pFd->nFetchOut==0) );
 37936  
 37937    /* If p!=0, it must match the iOff value. */
 37938    assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 37939  
 37940    if( p ){
 37941      pFd->nFetchOut--;
 37942    }else{
 37943      unixUnmapfile(pFd);
 37944    }
 37945  
 37946    assert( pFd->nFetchOut>=0 );
 37947  #else
 37948    UNUSED_PARAMETER(fd);
 37949    UNUSED_PARAMETER(p);
 37950    UNUSED_PARAMETER(iOff);
 37951  #endif
 37952    return SQLITE_OK;
 37953  }
 37954  
 37955  /*
 37956  ** Here ends the implementation of all sqlite3_file methods.
 37957  **
 37958  ********************** End sqlite3_file Methods *******************************
 37959  ******************************************************************************/
 37960  
 37961  /*
 37962  ** This division contains definitions of sqlite3_io_methods objects that
 37963  ** implement various file locking strategies.  It also contains definitions
 37964  ** of "finder" functions.  A finder-function is used to locate the appropriate
 37965  ** sqlite3_io_methods object for a particular database file.  The pAppData
 37966  ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
 37967  ** the correct finder-function for that VFS.
 37968  **
 37969  ** Most finder functions return a pointer to a fixed sqlite3_io_methods
 37970  ** object.  The only interesting finder-function is autolockIoFinder, which
 37971  ** looks at the filesystem type and tries to guess the best locking
 37972  ** strategy from that.
 37973  **
 37974  ** For finder-function F, two objects are created:
 37975  **
 37976  **    (1) The real finder-function named "FImpt()".
 37977  **
 37978  **    (2) A constant pointer to this function named just "F".
 37979  **
 37980  **
 37981  ** A pointer to the F pointer is used as the pAppData value for VFS
 37982  ** objects.  We have to do this instead of letting pAppData point
 37983  ** directly at the finder-function since C90 rules prevent a void*
 37984  ** from be cast into a function pointer.
 37985  **
 37986  **
 37987  ** Each instance of this macro generates two objects:
 37988  **
 37989  **   *  A constant sqlite3_io_methods object call METHOD that has locking
 37990  **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
 37991  **
 37992  **   *  An I/O method finder function called FINDER that returns a pointer
 37993  **      to the METHOD object in the previous bullet.
 37994  */
 37995  #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
 37996  static const sqlite3_io_methods METHOD = {                                   \
 37997     VERSION,                    /* iVersion */                                \
 37998     CLOSE,                      /* xClose */                                  \
 37999     unixRead,                   /* xRead */                                   \
 38000     unixWrite,                  /* xWrite */                                  \
 38001     unixTruncate,               /* xTruncate */                               \
 38002     unixSync,                   /* xSync */                                   \
 38003     unixFileSize,               /* xFileSize */                               \
 38004     LOCK,                       /* xLock */                                   \
 38005     UNLOCK,                     /* xUnlock */                                 \
 38006     CKLOCK,                     /* xCheckReservedLock */                      \
 38007     unixFileControl,            /* xFileControl */                            \
 38008     unixSectorSize,             /* xSectorSize */                             \
 38009     unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
 38010     SHMMAP,                     /* xShmMap */                                 \
 38011     unixShmLock,                /* xShmLock */                                \
 38012     unixShmBarrier,             /* xShmBarrier */                             \
 38013     unixShmUnmap,               /* xShmUnmap */                               \
 38014     unixFetch,                  /* xFetch */                                  \
 38015     unixUnfetch,                /* xUnfetch */                                \
 38016  };                                                                           \
 38017  static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
 38018    UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
 38019    return &METHOD;                                                            \
 38020  }                                                                            \
 38021  static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
 38022      = FINDER##Impl;
 38023  
 38024  /*
 38025  ** Here are all of the sqlite3_io_methods objects for each of the
 38026  ** locking strategies.  Functions that return pointers to these methods
 38027  ** are also created.
 38028  */
 38029  IOMETHODS(
 38030    posixIoFinder,            /* Finder function name */
 38031    posixIoMethods,           /* sqlite3_io_methods object name */
 38032    3,                        /* shared memory and mmap are enabled */
 38033    unixClose,                /* xClose method */
 38034    unixLock,                 /* xLock method */
 38035    unixUnlock,               /* xUnlock method */
 38036    unixCheckReservedLock,    /* xCheckReservedLock method */
 38037    unixShmMap                /* xShmMap method */
 38038  )
 38039  IOMETHODS(
 38040    nolockIoFinder,           /* Finder function name */
 38041    nolockIoMethods,          /* sqlite3_io_methods object name */
 38042    3,                        /* shared memory and mmap are enabled */
 38043    nolockClose,              /* xClose method */
 38044    nolockLock,               /* xLock method */
 38045    nolockUnlock,             /* xUnlock method */
 38046    nolockCheckReservedLock,  /* xCheckReservedLock method */
 38047    0                         /* xShmMap method */
 38048  )
 38049  IOMETHODS(
 38050    dotlockIoFinder,          /* Finder function name */
 38051    dotlockIoMethods,         /* sqlite3_io_methods object name */
 38052    1,                        /* shared memory is disabled */
 38053    dotlockClose,             /* xClose method */
 38054    dotlockLock,              /* xLock method */
 38055    dotlockUnlock,            /* xUnlock method */
 38056    dotlockCheckReservedLock, /* xCheckReservedLock method */
 38057    0                         /* xShmMap method */
 38058  )
 38059  
 38060  #if SQLITE_ENABLE_LOCKING_STYLE
 38061  IOMETHODS(
 38062    flockIoFinder,            /* Finder function name */
 38063    flockIoMethods,           /* sqlite3_io_methods object name */
 38064    1,                        /* shared memory is disabled */
 38065    flockClose,               /* xClose method */
 38066    flockLock,                /* xLock method */
 38067    flockUnlock,              /* xUnlock method */
 38068    flockCheckReservedLock,   /* xCheckReservedLock method */
 38069    0                         /* xShmMap method */
 38070  )
 38071  #endif
 38072  
 38073  #if OS_VXWORKS
 38074  IOMETHODS(
 38075    semIoFinder,              /* Finder function name */
 38076    semIoMethods,             /* sqlite3_io_methods object name */
 38077    1,                        /* shared memory is disabled */
 38078    semXClose,                /* xClose method */
 38079    semXLock,                 /* xLock method */
 38080    semXUnlock,               /* xUnlock method */
 38081    semXCheckReservedLock,    /* xCheckReservedLock method */
 38082    0                         /* xShmMap method */
 38083  )
 38084  #endif
 38085  
 38086  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 38087  IOMETHODS(
 38088    afpIoFinder,              /* Finder function name */
 38089    afpIoMethods,             /* sqlite3_io_methods object name */
 38090    1,                        /* shared memory is disabled */
 38091    afpClose,                 /* xClose method */
 38092    afpLock,                  /* xLock method */
 38093    afpUnlock,                /* xUnlock method */
 38094    afpCheckReservedLock,     /* xCheckReservedLock method */
 38095    0                         /* xShmMap method */
 38096  )
 38097  #endif
 38098  
 38099  /*
 38100  ** The proxy locking method is a "super-method" in the sense that it
 38101  ** opens secondary file descriptors for the conch and lock files and
 38102  ** it uses proxy, dot-file, AFP, and flock() locking methods on those
 38103  ** secondary files.  For this reason, the division that implements
 38104  ** proxy locking is located much further down in the file.  But we need
 38105  ** to go ahead and define the sqlite3_io_methods and finder function
 38106  ** for proxy locking here.  So we forward declare the I/O methods.
 38107  */
 38108  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 38109  static int proxyClose(sqlite3_file*);
 38110  static int proxyLock(sqlite3_file*, int);
 38111  static int proxyUnlock(sqlite3_file*, int);
 38112  static int proxyCheckReservedLock(sqlite3_file*, int*);
 38113  IOMETHODS(
 38114    proxyIoFinder,            /* Finder function name */
 38115    proxyIoMethods,           /* sqlite3_io_methods object name */
 38116    1,                        /* shared memory is disabled */
 38117    proxyClose,               /* xClose method */
 38118    proxyLock,                /* xLock method */
 38119    proxyUnlock,              /* xUnlock method */
 38120    proxyCheckReservedLock,   /* xCheckReservedLock method */
 38121    0                         /* xShmMap method */
 38122  )
 38123  #endif
 38124  
 38125  /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
 38126  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 38127  IOMETHODS(
 38128    nfsIoFinder,               /* Finder function name */
 38129    nfsIoMethods,              /* sqlite3_io_methods object name */
 38130    1,                         /* shared memory is disabled */
 38131    unixClose,                 /* xClose method */
 38132    unixLock,                  /* xLock method */
 38133    nfsUnlock,                 /* xUnlock method */
 38134    unixCheckReservedLock,     /* xCheckReservedLock method */
 38135    0                          /* xShmMap method */
 38136  )
 38137  #endif
 38138  
 38139  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 38140  /* 
 38141  ** This "finder" function attempts to determine the best locking strategy 
 38142  ** for the database file "filePath".  It then returns the sqlite3_io_methods
 38143  ** object that implements that strategy.
 38144  **
 38145  ** This is for MacOSX only.
 38146  */
 38147  static const sqlite3_io_methods *autolockIoFinderImpl(
 38148    const char *filePath,    /* name of the database file */
 38149    unixFile *pNew           /* open file object for the database file */
 38150  ){
 38151    static const struct Mapping {
 38152      const char *zFilesystem;              /* Filesystem type name */
 38153      const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
 38154    } aMap[] = {
 38155      { "hfs",    &posixIoMethods },
 38156      { "ufs",    &posixIoMethods },
 38157      { "afpfs",  &afpIoMethods },
 38158      { "smbfs",  &afpIoMethods },
 38159      { "webdav", &nolockIoMethods },
 38160      { 0, 0 }
 38161    };
 38162    int i;
 38163    struct statfs fsInfo;
 38164    struct flock lockInfo;
 38165  
 38166    if( !filePath ){
 38167      /* If filePath==NULL that means we are dealing with a transient file
 38168      ** that does not need to be locked. */
 38169      return &nolockIoMethods;
 38170    }
 38171    if( statfs(filePath, &fsInfo) != -1 ){
 38172      if( fsInfo.f_flags & MNT_RDONLY ){
 38173        return &nolockIoMethods;
 38174      }
 38175      for(i=0; aMap[i].zFilesystem; i++){
 38176        if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
 38177          return aMap[i].pMethods;
 38178        }
 38179      }
 38180    }
 38181  
 38182    /* Default case. Handles, amongst others, "nfs".
 38183    ** Test byte-range lock using fcntl(). If the call succeeds, 
 38184    ** assume that the file-system supports POSIX style locks. 
 38185    */
 38186    lockInfo.l_len = 1;
 38187    lockInfo.l_start = 0;
 38188    lockInfo.l_whence = SEEK_SET;
 38189    lockInfo.l_type = F_RDLCK;
 38190    if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 38191      if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
 38192        return &nfsIoMethods;
 38193      } else {
 38194        return &posixIoMethods;
 38195      }
 38196    }else{
 38197      return &dotlockIoMethods;
 38198    }
 38199  }
 38200  static const sqlite3_io_methods 
 38201    *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
 38202  
 38203  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 38204  
 38205  #if OS_VXWORKS
 38206  /*
 38207  ** This "finder" function for VxWorks checks to see if posix advisory
 38208  ** locking works.  If it does, then that is what is used.  If it does not
 38209  ** work, then fallback to named semaphore locking.
 38210  */
 38211  static const sqlite3_io_methods *vxworksIoFinderImpl(
 38212    const char *filePath,    /* name of the database file */
 38213    unixFile *pNew           /* the open file object */
 38214  ){
 38215    struct flock lockInfo;
 38216  
 38217    if( !filePath ){
 38218      /* If filePath==NULL that means we are dealing with a transient file
 38219      ** that does not need to be locked. */
 38220      return &nolockIoMethods;
 38221    }
 38222  
 38223    /* Test if fcntl() is supported and use POSIX style locks.
 38224    ** Otherwise fall back to the named semaphore method.
 38225    */
 38226    lockInfo.l_len = 1;
 38227    lockInfo.l_start = 0;
 38228    lockInfo.l_whence = SEEK_SET;
 38229    lockInfo.l_type = F_RDLCK;
 38230    if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
 38231      return &posixIoMethods;
 38232    }else{
 38233      return &semIoMethods;
 38234    }
 38235  }
 38236  static const sqlite3_io_methods 
 38237    *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
 38238  
 38239  #endif /* OS_VXWORKS */
 38240  
 38241  /*
 38242  ** An abstract type for a pointer to an IO method finder function:
 38243  */
 38244  typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
 38245  
 38246  
 38247  /****************************************************************************
 38248  **************************** sqlite3_vfs methods ****************************
 38249  **
 38250  ** This division contains the implementation of methods on the
 38251  ** sqlite3_vfs object.
 38252  */
 38253  
 38254  /*
 38255  ** Initialize the contents of the unixFile structure pointed to by pId.
 38256  */
 38257  static int fillInUnixFile(
 38258    sqlite3_vfs *pVfs,      /* Pointer to vfs object */
 38259    int h,                  /* Open file descriptor of file being opened */
 38260    sqlite3_file *pId,      /* Write to the unixFile structure here */
 38261    const char *zFilename,  /* Name of the file being opened */
 38262    int ctrlFlags           /* Zero or more UNIXFILE_* values */
 38263  ){
 38264    const sqlite3_io_methods *pLockingStyle;
 38265    unixFile *pNew = (unixFile *)pId;
 38266    int rc = SQLITE_OK;
 38267  
 38268    assert( pNew->pInode==NULL );
 38269  
 38270    /* No locking occurs in temporary files */
 38271    assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
 38272  
 38273    OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
 38274    pNew->h = h;
 38275    pNew->pVfs = pVfs;
 38276    pNew->zPath = zFilename;
 38277    pNew->ctrlFlags = (u8)ctrlFlags;
 38278  #if SQLITE_MAX_MMAP_SIZE>0
 38279    pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 38280  #endif
 38281    if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
 38282                             "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 38283      pNew->ctrlFlags |= UNIXFILE_PSOW;
 38284    }
 38285    if( strcmp(pVfs->zName,"unix-excl")==0 ){
 38286      pNew->ctrlFlags |= UNIXFILE_EXCL;
 38287    }
 38288  
 38289  #if OS_VXWORKS
 38290    pNew->pId = vxworksFindFileId(zFilename);
 38291    if( pNew->pId==0 ){
 38292      ctrlFlags |= UNIXFILE_NOLOCK;
 38293      rc = SQLITE_NOMEM_BKPT;
 38294    }
 38295  #endif
 38296  
 38297    if( ctrlFlags & UNIXFILE_NOLOCK ){
 38298      pLockingStyle = &nolockIoMethods;
 38299    }else{
 38300      pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
 38301  #if SQLITE_ENABLE_LOCKING_STYLE
 38302      /* Cache zFilename in the locking context (AFP and dotlock override) for
 38303      ** proxyLock activation is possible (remote proxy is based on db name)
 38304      ** zFilename remains valid until file is closed, to support */
 38305      pNew->lockingContext = (void*)zFilename;
 38306  #endif
 38307    }
 38308  
 38309    if( pLockingStyle == &posixIoMethods
 38310  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 38311      || pLockingStyle == &nfsIoMethods
 38312  #endif
 38313    ){
 38314      unixEnterMutex();
 38315      rc = findInodeInfo(pNew, &pNew->pInode);
 38316      if( rc!=SQLITE_OK ){
 38317        /* If an error occurred in findInodeInfo(), close the file descriptor
 38318        ** immediately, before releasing the mutex. findInodeInfo() may fail
 38319        ** in two scenarios:
 38320        **
 38321        **   (a) A call to fstat() failed.
 38322        **   (b) A malloc failed.
 38323        **
 38324        ** Scenario (b) may only occur if the process is holding no other
 38325        ** file descriptors open on the same file. If there were other file
 38326        ** descriptors on this file, then no malloc would be required by
 38327        ** findInodeInfo(). If this is the case, it is quite safe to close
 38328        ** handle h - as it is guaranteed that no posix locks will be released
 38329        ** by doing so.
 38330        **
 38331        ** If scenario (a) caused the error then things are not so safe. The
 38332        ** implicit assumption here is that if fstat() fails, things are in
 38333        ** such bad shape that dropping a lock or two doesn't matter much.
 38334        */
 38335        robust_close(pNew, h, __LINE__);
 38336        h = -1;
 38337      }
 38338      unixLeaveMutex();
 38339    }
 38340  
 38341  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 38342    else if( pLockingStyle == &afpIoMethods ){
 38343      /* AFP locking uses the file path so it needs to be included in
 38344      ** the afpLockingContext.
 38345      */
 38346      afpLockingContext *pCtx;
 38347      pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 38348      if( pCtx==0 ){
 38349        rc = SQLITE_NOMEM_BKPT;
 38350      }else{
 38351        /* NB: zFilename exists and remains valid until the file is closed
 38352        ** according to requirement F11141.  So we do not need to make a
 38353        ** copy of the filename. */
 38354        pCtx->dbPath = zFilename;
 38355        pCtx->reserved = 0;
 38356        srandomdev();
 38357        unixEnterMutex();
 38358        rc = findInodeInfo(pNew, &pNew->pInode);
 38359        if( rc!=SQLITE_OK ){
 38360          sqlite3_free(pNew->lockingContext);
 38361          robust_close(pNew, h, __LINE__);
 38362          h = -1;
 38363        }
 38364        unixLeaveMutex();        
 38365      }
 38366    }
 38367  #endif
 38368  
 38369    else if( pLockingStyle == &dotlockIoMethods ){
 38370      /* Dotfile locking uses the file path so it needs to be included in
 38371      ** the dotlockLockingContext 
 38372      */
 38373      char *zLockFile;
 38374      int nFilename;
 38375      assert( zFilename!=0 );
 38376      nFilename = (int)strlen(zFilename) + 6;
 38377      zLockFile = (char *)sqlite3_malloc64(nFilename);
 38378      if( zLockFile==0 ){
 38379        rc = SQLITE_NOMEM_BKPT;
 38380      }else{
 38381        sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
 38382      }
 38383      pNew->lockingContext = zLockFile;
 38384    }
 38385  
 38386  #if OS_VXWORKS
 38387    else if( pLockingStyle == &semIoMethods ){
 38388      /* Named semaphore locking uses the file path so it needs to be
 38389      ** included in the semLockingContext
 38390      */
 38391      unixEnterMutex();
 38392      rc = findInodeInfo(pNew, &pNew->pInode);
 38393      if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
 38394        char *zSemName = pNew->pInode->aSemName;
 38395        int n;
 38396        sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
 38397                         pNew->pId->zCanonicalName);
 38398        for( n=1; zSemName[n]; n++ )
 38399          if( zSemName[n]=='/' ) zSemName[n] = '_';
 38400        pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
 38401        if( pNew->pInode->pSem == SEM_FAILED ){
 38402          rc = SQLITE_NOMEM_BKPT;
 38403          pNew->pInode->aSemName[0] = '\0';
 38404        }
 38405      }
 38406      unixLeaveMutex();
 38407    }
 38408  #endif
 38409    
 38410    storeLastErrno(pNew, 0);
 38411  #if OS_VXWORKS
 38412    if( rc!=SQLITE_OK ){
 38413      if( h>=0 ) robust_close(pNew, h, __LINE__);
 38414      h = -1;
 38415      osUnlink(zFilename);
 38416      pNew->ctrlFlags |= UNIXFILE_DELETE;
 38417    }
 38418  #endif
 38419    if( rc!=SQLITE_OK ){
 38420      if( h>=0 ) robust_close(pNew, h, __LINE__);
 38421    }else{
 38422      pNew->pMethod = pLockingStyle;
 38423      OpenCounter(+1);
 38424      verifyDbFile(pNew);
 38425    }
 38426    return rc;
 38427  }
 38428  
 38429  /*
 38430  ** Return the name of a directory in which to put temporary files.
 38431  ** If no suitable temporary file directory can be found, return NULL.
 38432  */
 38433  static const char *unixTempFileDir(void){
 38434    static const char *azDirs[] = {
 38435       0,
 38436       0,
 38437       "/var/tmp",
 38438       "/usr/tmp",
 38439       "/tmp",
 38440       "."
 38441    };
 38442    unsigned int i = 0;
 38443    struct stat buf;
 38444    const char *zDir = sqlite3_temp_directory;
 38445  
 38446    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
 38447    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
 38448    while(1){
 38449      if( zDir!=0
 38450       && osStat(zDir, &buf)==0
 38451       && S_ISDIR(buf.st_mode)
 38452       && osAccess(zDir, 03)==0
 38453      ){
 38454        return zDir;
 38455      }
 38456      if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
 38457      zDir = azDirs[i++];
 38458    }
 38459    return 0;
 38460  }
 38461  
 38462  /*
 38463  ** Create a temporary file name in zBuf.  zBuf must be allocated
 38464  ** by the calling process and must be big enough to hold at least
 38465  ** pVfs->mxPathname bytes.
 38466  */
 38467  static int unixGetTempname(int nBuf, char *zBuf){
 38468    const char *zDir;
 38469    int iLimit = 0;
 38470  
 38471    /* It's odd to simulate an io-error here, but really this is just
 38472    ** using the io-error infrastructure to test that SQLite handles this
 38473    ** function failing. 
 38474    */
 38475    zBuf[0] = 0;
 38476    SimulateIOError( return SQLITE_IOERR );
 38477  
 38478    zDir = unixTempFileDir();
 38479    if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
 38480    do{
 38481      u64 r;
 38482      sqlite3_randomness(sizeof(r), &r);
 38483      assert( nBuf>2 );
 38484      zBuf[nBuf-2] = 0;
 38485      sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
 38486                       zDir, r, 0);
 38487      if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
 38488    }while( osAccess(zBuf,0)==0 );
 38489    return SQLITE_OK;
 38490  }
 38491  
 38492  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 38493  /*
 38494  ** Routine to transform a unixFile into a proxy-locking unixFile.
 38495  ** Implementation in the proxy-lock division, but used by unixOpen()
 38496  ** if SQLITE_PREFER_PROXY_LOCKING is defined.
 38497  */
 38498  static int proxyTransformUnixFile(unixFile*, const char*);
 38499  #endif
 38500  
 38501  /*
 38502  ** Search for an unused file descriptor that was opened on the database 
 38503  ** file (not a journal or master-journal file) identified by pathname
 38504  ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
 38505  ** argument to this function.
 38506  **
 38507  ** Such a file descriptor may exist if a database connection was closed
 38508  ** but the associated file descriptor could not be closed because some
 38509  ** other file descriptor open on the same file is holding a file-lock.
 38510  ** Refer to comments in the unixClose() function and the lengthy comment
 38511  ** describing "Posix Advisory Locking" at the start of this file for 
 38512  ** further details. Also, ticket #4018.
 38513  **
 38514  ** If a suitable file descriptor is found, then it is returned. If no
 38515  ** such file descriptor is located, -1 is returned.
 38516  */
 38517  static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
 38518    UnixUnusedFd *pUnused = 0;
 38519  
 38520    /* Do not search for an unused file descriptor on vxworks. Not because
 38521    ** vxworks would not benefit from the change (it might, we're not sure),
 38522    ** but because no way to test it is currently available. It is better 
 38523    ** not to risk breaking vxworks support for the sake of such an obscure 
 38524    ** feature.  */
 38525  #if !OS_VXWORKS
 38526    struct stat sStat;                   /* Results of stat() call */
 38527  
 38528    unixEnterMutex();
 38529  
 38530    /* A stat() call may fail for various reasons. If this happens, it is
 38531    ** almost certain that an open() call on the same path will also fail.
 38532    ** For this reason, if an error occurs in the stat() call here, it is
 38533    ** ignored and -1 is returned. The caller will try to open a new file
 38534    ** descriptor on the same path, fail, and return an error to SQLite.
 38535    **
 38536    ** Even if a subsequent open() call does succeed, the consequences of
 38537    ** not searching for a reusable file descriptor are not dire.  */
 38538    if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
 38539      unixInodeInfo *pInode;
 38540  
 38541      pInode = inodeList;
 38542      while( pInode && (pInode->fileId.dev!=sStat.st_dev
 38543                       || pInode->fileId.ino!=(u64)sStat.st_ino) ){
 38544         pInode = pInode->pNext;
 38545      }
 38546      if( pInode ){
 38547        UnixUnusedFd **pp;
 38548        assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
 38549        sqlite3_mutex_enter(pInode->pLockMutex);
 38550        for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
 38551        pUnused = *pp;
 38552        if( pUnused ){
 38553          *pp = pUnused->pNext;
 38554        }
 38555        sqlite3_mutex_leave(pInode->pLockMutex);
 38556      }
 38557    }
 38558    unixLeaveMutex();
 38559  #endif    /* if !OS_VXWORKS */
 38560    return pUnused;
 38561  }
 38562  
 38563  /*
 38564  ** Find the mode, uid and gid of file zFile. 
 38565  */
 38566  static int getFileMode(
 38567    const char *zFile,              /* File name */
 38568    mode_t *pMode,                  /* OUT: Permissions of zFile */
 38569    uid_t *pUid,                    /* OUT: uid of zFile. */
 38570    gid_t *pGid                     /* OUT: gid of zFile. */
 38571  ){
 38572    struct stat sStat;              /* Output of stat() on database file */
 38573    int rc = SQLITE_OK;
 38574    if( 0==osStat(zFile, &sStat) ){
 38575      *pMode = sStat.st_mode & 0777;
 38576      *pUid = sStat.st_uid;
 38577      *pGid = sStat.st_gid;
 38578    }else{
 38579      rc = SQLITE_IOERR_FSTAT;
 38580    }
 38581    return rc;
 38582  }
 38583  
 38584  /*
 38585  ** This function is called by unixOpen() to determine the unix permissions
 38586  ** to create new files with. If no error occurs, then SQLITE_OK is returned
 38587  ** and a value suitable for passing as the third argument to open(2) is
 38588  ** written to *pMode. If an IO error occurs, an SQLite error code is 
 38589  ** returned and the value of *pMode is not modified.
 38590  **
 38591  ** In most cases, this routine sets *pMode to 0, which will become
 38592  ** an indication to robust_open() to create the file using
 38593  ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
 38594  ** But if the file being opened is a WAL or regular journal file, then 
 38595  ** this function queries the file-system for the permissions on the 
 38596  ** corresponding database file and sets *pMode to this value. Whenever 
 38597  ** possible, WAL and journal files are created using the same permissions 
 38598  ** as the associated database file.
 38599  **
 38600  ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
 38601  ** original filename is unavailable.  But 8_3_NAMES is only used for
 38602  ** FAT filesystems and permissions do not matter there, so just use
 38603  ** the default permissions.
 38604  */
 38605  static int findCreateFileMode(
 38606    const char *zPath,              /* Path of file (possibly) being created */
 38607    int flags,                      /* Flags passed as 4th argument to xOpen() */
 38608    mode_t *pMode,                  /* OUT: Permissions to open file with */
 38609    uid_t *pUid,                    /* OUT: uid to set on the file */
 38610    gid_t *pGid                     /* OUT: gid to set on the file */
 38611  ){
 38612    int rc = SQLITE_OK;             /* Return Code */
 38613    *pMode = 0;
 38614    *pUid = 0;
 38615    *pGid = 0;
 38616    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 38617      char zDb[MAX_PATHNAME+1];     /* Database file path */
 38618      int nDb;                      /* Number of valid bytes in zDb */
 38619  
 38620      /* zPath is a path to a WAL or journal file. The following block derives
 38621      ** the path to the associated database file from zPath. This block handles
 38622      ** the following naming conventions:
 38623      **
 38624      **   "<path to db>-journal"
 38625      **   "<path to db>-wal"
 38626      **   "<path to db>-journalNN"
 38627      **   "<path to db>-walNN"
 38628      **
 38629      ** where NN is a decimal number. The NN naming schemes are 
 38630      ** used by the test_multiplex.c module.
 38631      */
 38632      nDb = sqlite3Strlen30(zPath) - 1; 
 38633      while( zPath[nDb]!='-' ){
 38634        /* In normal operation, the journal file name will always contain
 38635        ** a '-' character.  However in 8+3 filename mode, or if a corrupt
 38636        ** rollback journal specifies a master journal with a goofy name, then
 38637        ** the '-' might be missing. */
 38638        if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
 38639        nDb--;
 38640      }
 38641      memcpy(zDb, zPath, nDb);
 38642      zDb[nDb] = '\0';
 38643  
 38644      rc = getFileMode(zDb, pMode, pUid, pGid);
 38645    }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 38646      *pMode = 0600;
 38647    }else if( flags & SQLITE_OPEN_URI ){
 38648      /* If this is a main database file and the file was opened using a URI
 38649      ** filename, check for the "modeof" parameter. If present, interpret
 38650      ** its value as a filename and try to copy the mode, uid and gid from
 38651      ** that file.  */
 38652      const char *z = sqlite3_uri_parameter(zPath, "modeof");
 38653      if( z ){
 38654        rc = getFileMode(z, pMode, pUid, pGid);
 38655      }
 38656    }
 38657    return rc;
 38658  }
 38659  
 38660  /*
 38661  ** Open the file zPath.
 38662  ** 
 38663  ** Previously, the SQLite OS layer used three functions in place of this
 38664  ** one:
 38665  **
 38666  **     sqlite3OsOpenReadWrite();
 38667  **     sqlite3OsOpenReadOnly();
 38668  **     sqlite3OsOpenExclusive();
 38669  **
 38670  ** These calls correspond to the following combinations of flags:
 38671  **
 38672  **     ReadWrite() ->     (READWRITE | CREATE)
 38673  **     ReadOnly()  ->     (READONLY) 
 38674  **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
 38675  **
 38676  ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
 38677  ** true, the file was configured to be automatically deleted when the
 38678  ** file handle closed. To achieve the same effect using this new 
 38679  ** interface, add the DELETEONCLOSE flag to those specified above for 
 38680  ** OpenExclusive().
 38681  */
 38682  static int unixOpen(
 38683    sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
 38684    const char *zPath,           /* Pathname of file to be opened */
 38685    sqlite3_file *pFile,         /* The file descriptor to be filled in */
 38686    int flags,                   /* Input flags to control the opening */
 38687    int *pOutFlags               /* Output flags returned to SQLite core */
 38688  ){
 38689    unixFile *p = (unixFile *)pFile;
 38690    int fd = -1;                   /* File descriptor returned by open() */
 38691    int openFlags = 0;             /* Flags to pass to open() */
 38692    int eType = flags&0xFFFFFF00;  /* Type of file to open */
 38693    int noLock;                    /* True to omit locking primitives */
 38694    int rc = SQLITE_OK;            /* Function Return Code */
 38695    int ctrlFlags = 0;             /* UNIXFILE_* flags */
 38696  
 38697    int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 38698    int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 38699    int isCreate     = (flags & SQLITE_OPEN_CREATE);
 38700    int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 38701    int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 38702  #if SQLITE_ENABLE_LOCKING_STYLE
 38703    int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
 38704  #endif
 38705  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 38706    struct statfs fsInfo;
 38707  #endif
 38708  
 38709    /* If creating a master or main-file journal, this function will open
 38710    ** a file-descriptor on the directory too. The first time unixSync()
 38711    ** is called the directory file descriptor will be fsync()ed and close()d.
 38712    */
 38713    int isNewJrnl = (isCreate && (
 38714          eType==SQLITE_OPEN_MASTER_JOURNAL 
 38715       || eType==SQLITE_OPEN_MAIN_JOURNAL 
 38716       || eType==SQLITE_OPEN_WAL
 38717    ));
 38718  
 38719    /* If argument zPath is a NULL pointer, this function is required to open
 38720    ** a temporary file. Use this buffer to store the file name in.
 38721    */
 38722    char zTmpname[MAX_PATHNAME+2];
 38723    const char *zName = zPath;
 38724  
 38725    /* Check the following statements are true: 
 38726    **
 38727    **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
 38728    **   (b) if CREATE is set, then READWRITE must also be set, and
 38729    **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 38730    **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 38731    */
 38732    assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 38733    assert(isCreate==0 || isReadWrite);
 38734    assert(isExclusive==0 || isCreate);
 38735    assert(isDelete==0 || isCreate);
 38736  
 38737    /* The main DB, main journal, WAL file and master journal are never 
 38738    ** automatically deleted. Nor are they ever temporary files.  */
 38739    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 38740    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 38741    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 38742    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 38743  
 38744    /* Assert that the upper layer has set one of the "file-type" flags. */
 38745    assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
 38746         || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
 38747         || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
 38748         || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 38749    );
 38750  
 38751    /* Detect a pid change and reset the PRNG.  There is a race condition
 38752    ** here such that two or more threads all trying to open databases at
 38753    ** the same instant might all reset the PRNG.  But multiple resets
 38754    ** are harmless.
 38755    */
 38756    if( randomnessPid!=osGetpid(0) ){
 38757      randomnessPid = osGetpid(0);
 38758      sqlite3_randomness(0,0);
 38759    }
 38760    memset(p, 0, sizeof(unixFile));
 38761  
 38762    if( eType==SQLITE_OPEN_MAIN_DB ){
 38763      UnixUnusedFd *pUnused;
 38764      pUnused = findReusableFd(zName, flags);
 38765      if( pUnused ){
 38766        fd = pUnused->fd;
 38767      }else{
 38768        pUnused = sqlite3_malloc64(sizeof(*pUnused));
 38769        if( !pUnused ){
 38770          return SQLITE_NOMEM_BKPT;
 38771        }
 38772      }
 38773      p->pPreallocatedUnused = pUnused;
 38774  
 38775      /* Database filenames are double-zero terminated if they are not
 38776      ** URIs with parameters.  Hence, they can always be passed into
 38777      ** sqlite3_uri_parameter(). */
 38778      assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
 38779  
 38780    }else if( !zName ){
 38781      /* If zName is NULL, the upper layer is requesting a temp file. */
 38782      assert(isDelete && !isNewJrnl);
 38783      rc = unixGetTempname(pVfs->mxPathname, zTmpname);
 38784      if( rc!=SQLITE_OK ){
 38785        return rc;
 38786      }
 38787      zName = zTmpname;
 38788  
 38789      /* Generated temporary filenames are always double-zero terminated
 38790      ** for use by sqlite3_uri_parameter(). */
 38791      assert( zName[strlen(zName)+1]==0 );
 38792    }
 38793  
 38794    /* Determine the value of the flags parameter passed to POSIX function
 38795    ** open(). These must be calculated even if open() is not called, as
 38796    ** they may be stored as part of the file handle and used by the 
 38797    ** 'conch file' locking functions later on.  */
 38798    if( isReadonly )  openFlags |= O_RDONLY;
 38799    if( isReadWrite ) openFlags |= O_RDWR;
 38800    if( isCreate )    openFlags |= O_CREAT;
 38801    if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
 38802    openFlags |= (O_LARGEFILE|O_BINARY);
 38803  
 38804    if( fd<0 ){
 38805      mode_t openMode;              /* Permissions to create file with */
 38806      uid_t uid;                    /* Userid for the file */
 38807      gid_t gid;                    /* Groupid for the file */
 38808      rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
 38809      if( rc!=SQLITE_OK ){
 38810        assert( !p->pPreallocatedUnused );
 38811        assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
 38812        return rc;
 38813      }
 38814      fd = robust_open(zName, openFlags, openMode);
 38815      OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
 38816      assert( !isExclusive || (openFlags & O_CREAT)!=0 );
 38817      if( fd<0 ){
 38818        if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
 38819          /* If unable to create a journal because the directory is not
 38820          ** writable, change the error code to indicate that. */
 38821          rc = SQLITE_READONLY_DIRECTORY;
 38822        }else if( errno!=EISDIR && isReadWrite ){
 38823          /* Failed to open the file for read/write access. Try read-only. */
 38824          flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
 38825          openFlags &= ~(O_RDWR|O_CREAT);
 38826          flags |= SQLITE_OPEN_READONLY;
 38827          openFlags |= O_RDONLY;
 38828          isReadonly = 1;
 38829          fd = robust_open(zName, openFlags, openMode);
 38830        }
 38831      }
 38832      if( fd<0 ){
 38833        int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
 38834        if( rc==SQLITE_OK ) rc = rc2;
 38835        goto open_finished;
 38836      }
 38837  
 38838      /* If this process is running as root and if creating a new rollback
 38839      ** journal or WAL file, set the ownership of the journal or WAL to be
 38840      ** the same as the original database.
 38841      */
 38842      if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
 38843        robustFchown(fd, uid, gid);
 38844      }
 38845    }
 38846    assert( fd>=0 );
 38847    if( pOutFlags ){
 38848      *pOutFlags = flags;
 38849    }
 38850  
 38851    if( p->pPreallocatedUnused ){
 38852      p->pPreallocatedUnused->fd = fd;
 38853      p->pPreallocatedUnused->flags = flags;
 38854    }
 38855  
 38856    if( isDelete ){
 38857  #if OS_VXWORKS
 38858      zPath = zName;
 38859  #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
 38860      zPath = sqlite3_mprintf("%s", zName);
 38861      if( zPath==0 ){
 38862        robust_close(p, fd, __LINE__);
 38863        return SQLITE_NOMEM_BKPT;
 38864      }
 38865  #else
 38866      osUnlink(zName);
 38867  #endif
 38868    }
 38869  #if SQLITE_ENABLE_LOCKING_STYLE
 38870    else{
 38871      p->openFlags = openFlags;
 38872    }
 38873  #endif
 38874    
 38875  #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
 38876    if( fstatfs(fd, &fsInfo) == -1 ){
 38877      storeLastErrno(p, errno);
 38878      robust_close(p, fd, __LINE__);
 38879      return SQLITE_IOERR_ACCESS;
 38880    }
 38881    if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
 38882      ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 38883    }
 38884    if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
 38885      ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
 38886    }
 38887  #endif
 38888  
 38889    /* Set up appropriate ctrlFlags */
 38890    if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
 38891    if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
 38892    noLock = eType!=SQLITE_OPEN_MAIN_DB;
 38893    if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
 38894    if( isNewJrnl )               ctrlFlags |= UNIXFILE_DIRSYNC;
 38895    if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
 38896  
 38897  #if SQLITE_ENABLE_LOCKING_STYLE
 38898  #if SQLITE_PREFER_PROXY_LOCKING
 38899    isAutoProxy = 1;
 38900  #endif
 38901    if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
 38902      char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
 38903      int useProxy = 0;
 38904  
 38905      /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
 38906      ** never use proxy, NULL means use proxy for non-local files only.  */
 38907      if( envforce!=NULL ){
 38908        useProxy = atoi(envforce)>0;
 38909      }else{
 38910        useProxy = !(fsInfo.f_flags&MNT_LOCAL);
 38911      }
 38912      if( useProxy ){
 38913        rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 38914        if( rc==SQLITE_OK ){
 38915          rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
 38916          if( rc!=SQLITE_OK ){
 38917            /* Use unixClose to clean up the resources added in fillInUnixFile 
 38918            ** and clear all the structure's references.  Specifically, 
 38919            ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
 38920            */
 38921            unixClose(pFile);
 38922            return rc;
 38923          }
 38924        }
 38925        goto open_finished;
 38926      }
 38927    }
 38928  #endif
 38929    
 38930    assert( zPath==0 || zPath[0]=='/' 
 38931        || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL 
 38932    );
 38933    rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 38934  
 38935  open_finished:
 38936    if( rc!=SQLITE_OK ){
 38937      sqlite3_free(p->pPreallocatedUnused);
 38938    }
 38939    return rc;
 38940  }
 38941  
 38942  
 38943  /*
 38944  ** Delete the file at zPath. If the dirSync argument is true, fsync()
 38945  ** the directory after deleting the file.
 38946  */
 38947  static int unixDelete(
 38948    sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
 38949    const char *zPath,        /* Name of file to be deleted */
 38950    int dirSync               /* If true, fsync() directory after deleting file */
 38951  ){
 38952    int rc = SQLITE_OK;
 38953    UNUSED_PARAMETER(NotUsed);
 38954    SimulateIOError(return SQLITE_IOERR_DELETE);
 38955    if( osUnlink(zPath)==(-1) ){
 38956      if( errno==ENOENT
 38957  #if OS_VXWORKS
 38958          || osAccess(zPath,0)!=0
 38959  #endif
 38960      ){
 38961        rc = SQLITE_IOERR_DELETE_NOENT;
 38962      }else{
 38963        rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
 38964      }
 38965      return rc;
 38966    }
 38967  #ifndef SQLITE_DISABLE_DIRSYNC
 38968    if( (dirSync & 1)!=0 ){
 38969      int fd;
 38970      rc = osOpenDirectory(zPath, &fd);
 38971      if( rc==SQLITE_OK ){
 38972        if( full_fsync(fd,0,0) ){
 38973          rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
 38974        }
 38975        robust_close(0, fd, __LINE__);
 38976      }else{
 38977        assert( rc==SQLITE_CANTOPEN );
 38978        rc = SQLITE_OK;
 38979      }
 38980    }
 38981  #endif
 38982    return rc;
 38983  }
 38984  
 38985  /*
 38986  ** Test the existence of or access permissions of file zPath. The
 38987  ** test performed depends on the value of flags:
 38988  **
 38989  **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
 38990  **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
 38991  **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
 38992  **
 38993  ** Otherwise return 0.
 38994  */
 38995  static int unixAccess(
 38996    sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
 38997    const char *zPath,      /* Path of the file to examine */
 38998    int flags,              /* What do we want to learn about the zPath file? */
 38999    int *pResOut            /* Write result boolean here */
 39000  ){
 39001    UNUSED_PARAMETER(NotUsed);
 39002    SimulateIOError( return SQLITE_IOERR_ACCESS; );
 39003    assert( pResOut!=0 );
 39004  
 39005    /* The spec says there are three possible values for flags.  But only
 39006    ** two of them are actually used */
 39007    assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
 39008  
 39009    if( flags==SQLITE_ACCESS_EXISTS ){
 39010      struct stat buf;
 39011      *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
 39012    }else{
 39013      *pResOut = osAccess(zPath, W_OK|R_OK)==0;
 39014    }
 39015    return SQLITE_OK;
 39016  }
 39017  
 39018  /*
 39019  **
 39020  */
 39021  static int mkFullPathname(
 39022    const char *zPath,              /* Input path */
 39023    char *zOut,                     /* Output buffer */
 39024    int nOut                        /* Allocated size of buffer zOut */
 39025  ){
 39026    int nPath = sqlite3Strlen30(zPath);
 39027    int iOff = 0;
 39028    if( zPath[0]!='/' ){
 39029      if( osGetcwd(zOut, nOut-2)==0 ){
 39030        return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
 39031      }
 39032      iOff = sqlite3Strlen30(zOut);
 39033      zOut[iOff++] = '/';
 39034    }
 39035    if( (iOff+nPath+1)>nOut ){
 39036      /* SQLite assumes that xFullPathname() nul-terminates the output buffer
 39037      ** even if it returns an error.  */
 39038      zOut[iOff] = '\0';
 39039      return SQLITE_CANTOPEN_BKPT;
 39040    }
 39041    sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
 39042    return SQLITE_OK;
 39043  }
 39044  
 39045  /*
 39046  ** Turn a relative pathname into a full pathname. The relative path
 39047  ** is stored as a nul-terminated string in the buffer pointed to by
 39048  ** zPath. 
 39049  **
 39050  ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
 39051  ** (in this case, MAX_PATHNAME bytes). The full-path is written to
 39052  ** this buffer before returning.
 39053  */
 39054  static int unixFullPathname(
 39055    sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 39056    const char *zPath,            /* Possibly relative input path */
 39057    int nOut,                     /* Size of output buffer in bytes */
 39058    char *zOut                    /* Output buffer */
 39059  ){
 39060  #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
 39061    return mkFullPathname(zPath, zOut, nOut);
 39062  #else
 39063    int rc = SQLITE_OK;
 39064    int nByte;
 39065    int nLink = 1;                /* Number of symbolic links followed so far */
 39066    const char *zIn = zPath;      /* Input path for each iteration of loop */
 39067    char *zDel = 0;
 39068  
 39069    assert( pVfs->mxPathname==MAX_PATHNAME );
 39070    UNUSED_PARAMETER(pVfs);
 39071  
 39072    /* It's odd to simulate an io-error here, but really this is just
 39073    ** using the io-error infrastructure to test that SQLite handles this
 39074    ** function failing. This function could fail if, for example, the
 39075    ** current working directory has been unlinked.
 39076    */
 39077    SimulateIOError( return SQLITE_ERROR );
 39078  
 39079    do {
 39080  
 39081      /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
 39082      ** link, or false otherwise.  */
 39083      int bLink = 0;
 39084      struct stat buf;
 39085      if( osLstat(zIn, &buf)!=0 ){
 39086        if( errno!=ENOENT ){
 39087          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
 39088        }
 39089      }else{
 39090        bLink = S_ISLNK(buf.st_mode);
 39091      }
 39092  
 39093      if( bLink ){
 39094        if( zDel==0 ){
 39095          zDel = sqlite3_malloc(nOut);
 39096          if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
 39097        }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
 39098          rc = SQLITE_CANTOPEN_BKPT;
 39099        }
 39100  
 39101        if( rc==SQLITE_OK ){
 39102          nByte = osReadlink(zIn, zDel, nOut-1);
 39103          if( nByte<0 ){
 39104            rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
 39105          }else{
 39106            if( zDel[0]!='/' ){
 39107              int n;
 39108              for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
 39109              if( nByte+n+1>nOut ){
 39110                rc = SQLITE_CANTOPEN_BKPT;
 39111              }else{
 39112                memmove(&zDel[n], zDel, nByte+1);
 39113                memcpy(zDel, zIn, n);
 39114                nByte += n;
 39115              }
 39116            }
 39117            zDel[nByte] = '\0';
 39118          }
 39119        }
 39120  
 39121        zIn = zDel;
 39122      }
 39123  
 39124      assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
 39125      if( rc==SQLITE_OK && zIn!=zOut ){
 39126        rc = mkFullPathname(zIn, zOut, nOut);
 39127      }
 39128      if( bLink==0 ) break;
 39129      zIn = zOut;
 39130    }while( rc==SQLITE_OK );
 39131  
 39132    sqlite3_free(zDel);
 39133    return rc;
 39134  #endif   /* HAVE_READLINK && HAVE_LSTAT */
 39135  }
 39136  
 39137  
 39138  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 39139  /*
 39140  ** Interfaces for opening a shared library, finding entry points
 39141  ** within the shared library, and closing the shared library.
 39142  */
 39143  #include <dlfcn.h>
 39144  static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
 39145    UNUSED_PARAMETER(NotUsed);
 39146    return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
 39147  }
 39148  
 39149  /*
 39150  ** SQLite calls this function immediately after a call to unixDlSym() or
 39151  ** unixDlOpen() fails (returns a null pointer). If a more detailed error
 39152  ** message is available, it is written to zBufOut. If no error message
 39153  ** is available, zBufOut is left unmodified and SQLite uses a default
 39154  ** error message.
 39155  */
 39156  static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
 39157    const char *zErr;
 39158    UNUSED_PARAMETER(NotUsed);
 39159    unixEnterMutex();
 39160    zErr = dlerror();
 39161    if( zErr ){
 39162      sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
 39163    }
 39164    unixLeaveMutex();
 39165  }
 39166  static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
 39167    /* 
 39168    ** GCC with -pedantic-errors says that C90 does not allow a void* to be
 39169    ** cast into a pointer to a function.  And yet the library dlsym() routine
 39170    ** returns a void* which is really a pointer to a function.  So how do we
 39171    ** use dlsym() with -pedantic-errors?
 39172    **
 39173    ** Variable x below is defined to be a pointer to a function taking
 39174    ** parameters void* and const char* and returning a pointer to a function.
 39175    ** We initialize x by assigning it a pointer to the dlsym() function.
 39176    ** (That assignment requires a cast.)  Then we call the function that
 39177    ** x points to.  
 39178    **
 39179    ** This work-around is unlikely to work correctly on any system where
 39180    ** you really cannot cast a function pointer into void*.  But then, on the
 39181    ** other hand, dlsym() will not work on such a system either, so we have
 39182    ** not really lost anything.
 39183    */
 39184    void (*(*x)(void*,const char*))(void);
 39185    UNUSED_PARAMETER(NotUsed);
 39186    x = (void(*(*)(void*,const char*))(void))dlsym;
 39187    return (*x)(p, zSym);
 39188  }
 39189  static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
 39190    UNUSED_PARAMETER(NotUsed);
 39191    dlclose(pHandle);
 39192  }
 39193  #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 39194    #define unixDlOpen  0
 39195    #define unixDlError 0
 39196    #define unixDlSym   0
 39197    #define unixDlClose 0
 39198  #endif
 39199  
 39200  /*
 39201  ** Write nBuf bytes of random data to the supplied buffer zBuf.
 39202  */
 39203  static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
 39204    UNUSED_PARAMETER(NotUsed);
 39205    assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
 39206  
 39207    /* We have to initialize zBuf to prevent valgrind from reporting
 39208    ** errors.  The reports issued by valgrind are incorrect - we would
 39209    ** prefer that the randomness be increased by making use of the
 39210    ** uninitialized space in zBuf - but valgrind errors tend to worry
 39211    ** some users.  Rather than argue, it seems easier just to initialize
 39212    ** the whole array and silence valgrind, even if that means less randomness
 39213    ** in the random seed.
 39214    **
 39215    ** When testing, initializing zBuf[] to zero is all we do.  That means
 39216    ** that we always use the same random number sequence.  This makes the
 39217    ** tests repeatable.
 39218    */
 39219    memset(zBuf, 0, nBuf);
 39220    randomnessPid = osGetpid(0);  
 39221  #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
 39222    {
 39223      int fd, got;
 39224      fd = robust_open("/dev/urandom", O_RDONLY, 0);
 39225      if( fd<0 ){
 39226        time_t t;
 39227        time(&t);
 39228        memcpy(zBuf, &t, sizeof(t));
 39229        memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
 39230        assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
 39231        nBuf = sizeof(t) + sizeof(randomnessPid);
 39232      }else{
 39233        do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
 39234        robust_close(0, fd, __LINE__);
 39235      }
 39236    }
 39237  #endif
 39238    return nBuf;
 39239  }
 39240  
 39241  
 39242  /*
 39243  ** Sleep for a little while.  Return the amount of time slept.
 39244  ** The argument is the number of microseconds we want to sleep.
 39245  ** The return value is the number of microseconds of sleep actually
 39246  ** requested from the underlying operating system, a number which
 39247  ** might be greater than or equal to the argument, but not less
 39248  ** than the argument.
 39249  */
 39250  static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
 39251  #if OS_VXWORKS
 39252    struct timespec sp;
 39253  
 39254    sp.tv_sec = microseconds / 1000000;
 39255    sp.tv_nsec = (microseconds % 1000000) * 1000;
 39256    nanosleep(&sp, NULL);
 39257    UNUSED_PARAMETER(NotUsed);
 39258    return microseconds;
 39259  #elif defined(HAVE_USLEEP) && HAVE_USLEEP
 39260    usleep(microseconds);
 39261    UNUSED_PARAMETER(NotUsed);
 39262    return microseconds;
 39263  #else
 39264    int seconds = (microseconds+999999)/1000000;
 39265    sleep(seconds);
 39266    UNUSED_PARAMETER(NotUsed);
 39267    return seconds*1000000;
 39268  #endif
 39269  }
 39270  
 39271  /*
 39272  ** The following variable, if set to a non-zero value, is interpreted as
 39273  ** the number of seconds since 1970 and is used to set the result of
 39274  ** sqlite3OsCurrentTime() during testing.
 39275  */
 39276  #ifdef SQLITE_TEST
 39277  SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 39278  #endif
 39279  
 39280  /*
 39281  ** Find the current time (in Universal Coordinated Time).  Write into *piNow
 39282  ** the current time and date as a Julian Day number times 86_400_000.  In
 39283  ** other words, write into *piNow the number of milliseconds since the Julian
 39284  ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 39285  ** proleptic Gregorian calendar.
 39286  **
 39287  ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
 39288  ** cannot be found.
 39289  */
 39290  static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
 39291    static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 39292    int rc = SQLITE_OK;
 39293  #if defined(NO_GETTOD)
 39294    time_t t;
 39295    time(&t);
 39296    *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
 39297  #elif OS_VXWORKS
 39298    struct timespec sNow;
 39299    clock_gettime(CLOCK_REALTIME, &sNow);
 39300    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
 39301  #else
 39302    struct timeval sNow;
 39303    (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
 39304    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
 39305  #endif
 39306  
 39307  #ifdef SQLITE_TEST
 39308    if( sqlite3_current_time ){
 39309      *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 39310    }
 39311  #endif
 39312    UNUSED_PARAMETER(NotUsed);
 39313    return rc;
 39314  }
 39315  
 39316  #ifndef SQLITE_OMIT_DEPRECATED
 39317  /*
 39318  ** Find the current time (in Universal Coordinated Time).  Write the
 39319  ** current time and date as a Julian Day number into *prNow and
 39320  ** return 0.  Return 1 if the time and date cannot be found.
 39321  */
 39322  static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
 39323    sqlite3_int64 i = 0;
 39324    int rc;
 39325    UNUSED_PARAMETER(NotUsed);
 39326    rc = unixCurrentTimeInt64(0, &i);
 39327    *prNow = i/86400000.0;
 39328    return rc;
 39329  }
 39330  #else
 39331  # define unixCurrentTime 0
 39332  #endif
 39333  
 39334  /*
 39335  ** The xGetLastError() method is designed to return a better
 39336  ** low-level error message when operating-system problems come up
 39337  ** during SQLite operation.  Only the integer return code is currently
 39338  ** used.
 39339  */
 39340  static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 39341    UNUSED_PARAMETER(NotUsed);
 39342    UNUSED_PARAMETER(NotUsed2);
 39343    UNUSED_PARAMETER(NotUsed3);
 39344    return errno;
 39345  }
 39346  
 39347  
 39348  /*
 39349  ************************ End of sqlite3_vfs methods ***************************
 39350  ******************************************************************************/
 39351  
 39352  /******************************************************************************
 39353  ************************** Begin Proxy Locking ********************************
 39354  **
 39355  ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
 39356  ** other locking methods on secondary lock files.  Proxy locking is a
 39357  ** meta-layer over top of the primitive locking implemented above.  For
 39358  ** this reason, the division that implements of proxy locking is deferred
 39359  ** until late in the file (here) after all of the other I/O methods have
 39360  ** been defined - so that the primitive locking methods are available
 39361  ** as services to help with the implementation of proxy locking.
 39362  **
 39363  ****
 39364  **
 39365  ** The default locking schemes in SQLite use byte-range locks on the
 39366  ** database file to coordinate safe, concurrent access by multiple readers
 39367  ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
 39368  ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
 39369  ** as POSIX read & write locks over fixed set of locations (via fsctl),
 39370  ** on AFP and SMB only exclusive byte-range locks are available via fsctl
 39371  ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
 39372  ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
 39373  ** address in the shared range is taken for a SHARED lock, the entire
 39374  ** shared range is taken for an EXCLUSIVE lock):
 39375  **
 39376  **      PENDING_BYTE        0x40000000
 39377  **      RESERVED_BYTE       0x40000001
 39378  **      SHARED_RANGE        0x40000002 -> 0x40000200
 39379  **
 39380  ** This works well on the local file system, but shows a nearly 100x
 39381  ** slowdown in read performance on AFP because the AFP client disables
 39382  ** the read cache when byte-range locks are present.  Enabling the read
 39383  ** cache exposes a cache coherency problem that is present on all OS X
 39384  ** supported network file systems.  NFS and AFP both observe the
 39385  ** close-to-open semantics for ensuring cache coherency
 39386  ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
 39387  ** address the requirements for concurrent database access by multiple
 39388  ** readers and writers
 39389  ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
 39390  **
 39391  ** To address the performance and cache coherency issues, proxy file locking
 39392  ** changes the way database access is controlled by limiting access to a
 39393  ** single host at a time and moving file locks off of the database file
 39394  ** and onto a proxy file on the local file system.  
 39395  **
 39396  **
 39397  ** Using proxy locks
 39398  ** -----------------
 39399  **
 39400  ** C APIs
 39401  **
 39402  **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
 39403  **                       <proxy_path> | ":auto:");
 39404  **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
 39405  **                       &<proxy_path>);
 39406  **
 39407  **
 39408  ** SQL pragmas
 39409  **
 39410  **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
 39411  **  PRAGMA [database.]lock_proxy_file
 39412  **
 39413  ** Specifying ":auto:" means that if there is a conch file with a matching
 39414  ** host ID in it, the proxy path in the conch file will be used, otherwise
 39415  ** a proxy path based on the user's temp dir
 39416  ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
 39417  ** actual proxy file name is generated from the name and path of the
 39418  ** database file.  For example:
 39419  **
 39420  **       For database path "/Users/me/foo.db" 
 39421  **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
 39422  **
 39423  ** Once a lock proxy is configured for a database connection, it can not
 39424  ** be removed, however it may be switched to a different proxy path via
 39425  ** the above APIs (assuming the conch file is not being held by another
 39426  ** connection or process). 
 39427  **
 39428  **
 39429  ** How proxy locking works
 39430  ** -----------------------
 39431  **
 39432  ** Proxy file locking relies primarily on two new supporting files: 
 39433  **
 39434  **   *  conch file to limit access to the database file to a single host
 39435  **      at a time
 39436  **
 39437  **   *  proxy file to act as a proxy for the advisory locks normally
 39438  **      taken on the database
 39439  **
 39440  ** The conch file - to use a proxy file, sqlite must first "hold the conch"
 39441  ** by taking an sqlite-style shared lock on the conch file, reading the
 39442  ** contents and comparing the host's unique host ID (see below) and lock
 39443  ** proxy path against the values stored in the conch.  The conch file is
 39444  ** stored in the same directory as the database file and the file name
 39445  ** is patterned after the database file name as ".<databasename>-conch".
 39446  ** If the conch file does not exist, or its contents do not match the
 39447  ** host ID and/or proxy path, then the lock is escalated to an exclusive
 39448  ** lock and the conch file contents is updated with the host ID and proxy
 39449  ** path and the lock is downgraded to a shared lock again.  If the conch
 39450  ** is held by another process (with a shared lock), the exclusive lock
 39451  ** will fail and SQLITE_BUSY is returned.
 39452  **
 39453  ** The proxy file - a single-byte file used for all advisory file locks
 39454  ** normally taken on the database file.   This allows for safe sharing
 39455  ** of the database file for multiple readers and writers on the same
 39456  ** host (the conch ensures that they all use the same local lock file).
 39457  **
 39458  ** Requesting the lock proxy does not immediately take the conch, it is
 39459  ** only taken when the first request to lock database file is made.  
 39460  ** This matches the semantics of the traditional locking behavior, where
 39461  ** opening a connection to a database file does not take a lock on it.
 39462  ** The shared lock and an open file descriptor are maintained until 
 39463  ** the connection to the database is closed. 
 39464  **
 39465  ** The proxy file and the lock file are never deleted so they only need
 39466  ** to be created the first time they are used.
 39467  **
 39468  ** Configuration options
 39469  ** ---------------------
 39470  **
 39471  **  SQLITE_PREFER_PROXY_LOCKING
 39472  **
 39473  **       Database files accessed on non-local file systems are
 39474  **       automatically configured for proxy locking, lock files are
 39475  **       named automatically using the same logic as
 39476  **       PRAGMA lock_proxy_file=":auto:"
 39477  **    
 39478  **  SQLITE_PROXY_DEBUG
 39479  **
 39480  **       Enables the logging of error messages during host id file
 39481  **       retrieval and creation
 39482  **
 39483  **  LOCKPROXYDIR
 39484  **
 39485  **       Overrides the default directory used for lock proxy files that
 39486  **       are named automatically via the ":auto:" setting
 39487  **
 39488  **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
 39489  **
 39490  **       Permissions to use when creating a directory for storing the
 39491  **       lock proxy files, only used when LOCKPROXYDIR is not set.
 39492  **    
 39493  **    
 39494  ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
 39495  ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
 39496  ** force proxy locking to be used for every database file opened, and 0
 39497  ** will force automatic proxy locking to be disabled for all database
 39498  ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
 39499  ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
 39500  */
 39501  
 39502  /*
 39503  ** Proxy locking is only available on MacOSX 
 39504  */
 39505  #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 39506  
 39507  /*
 39508  ** The proxyLockingContext has the path and file structures for the remote 
 39509  ** and local proxy files in it
 39510  */
 39511  typedef struct proxyLockingContext proxyLockingContext;
 39512  struct proxyLockingContext {
 39513    unixFile *conchFile;         /* Open conch file */
 39514    char *conchFilePath;         /* Name of the conch file */
 39515    unixFile *lockProxy;         /* Open proxy lock file */
 39516    char *lockProxyPath;         /* Name of the proxy lock file */
 39517    char *dbPath;                /* Name of the open file */
 39518    int conchHeld;               /* 1 if the conch is held, -1 if lockless */
 39519    int nFails;                  /* Number of conch taking failures */
 39520    void *oldLockingContext;     /* Original lockingcontext to restore on close */
 39521    sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
 39522  };
 39523  
 39524  /* 
 39525  ** The proxy lock file path for the database at dbPath is written into lPath, 
 39526  ** which must point to valid, writable memory large enough for a maxLen length
 39527  ** file path. 
 39528  */
 39529  static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
 39530    int len;
 39531    int dbLen;
 39532    int i;
 39533  
 39534  #ifdef LOCKPROXYDIR
 39535    len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
 39536  #else
 39537  # ifdef _CS_DARWIN_USER_TEMP_DIR
 39538    {
 39539      if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
 39540        OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
 39541                 lPath, errno, osGetpid(0)));
 39542        return SQLITE_IOERR_LOCK;
 39543      }
 39544      len = strlcat(lPath, "sqliteplocks", maxLen);    
 39545    }
 39546  # else
 39547    len = strlcpy(lPath, "/tmp/", maxLen);
 39548  # endif
 39549  #endif
 39550  
 39551    if( lPath[len-1]!='/' ){
 39552      len = strlcat(lPath, "/", maxLen);
 39553    }
 39554    
 39555    /* transform the db path to a unique cache name */
 39556    dbLen = (int)strlen(dbPath);
 39557    for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
 39558      char c = dbPath[i];
 39559      lPath[i+len] = (c=='/')?'_':c;
 39560    }
 39561    lPath[i+len]='\0';
 39562    strlcat(lPath, ":auto:", maxLen);
 39563    OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
 39564    return SQLITE_OK;
 39565  }
 39566  
 39567  /* 
 39568   ** Creates the lock file and any missing directories in lockPath
 39569   */
 39570  static int proxyCreateLockPath(const char *lockPath){
 39571    int i, len;
 39572    char buf[MAXPATHLEN];
 39573    int start = 0;
 39574    
 39575    assert(lockPath!=NULL);
 39576    /* try to create all the intermediate directories */
 39577    len = (int)strlen(lockPath);
 39578    buf[0] = lockPath[0];
 39579    for( i=1; i<len; i++ ){
 39580      if( lockPath[i] == '/' && (i - start > 0) ){
 39581        /* only mkdir if leaf dir != "." or "/" or ".." */
 39582        if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
 39583           || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
 39584          buf[i]='\0';
 39585          if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
 39586            int err=errno;
 39587            if( err!=EEXIST ) {
 39588              OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
 39589                       "'%s' proxy lock path=%s pid=%d\n",
 39590                       buf, strerror(err), lockPath, osGetpid(0)));
 39591              return err;
 39592            }
 39593          }
 39594        }
 39595        start=i+1;
 39596      }
 39597      buf[i] = lockPath[i];
 39598    }
 39599    OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
 39600    return 0;
 39601  }
 39602  
 39603  /*
 39604  ** Create a new VFS file descriptor (stored in memory obtained from
 39605  ** sqlite3_malloc) and open the file named "path" in the file descriptor.
 39606  **
 39607  ** The caller is responsible not only for closing the file descriptor
 39608  ** but also for freeing the memory associated with the file descriptor.
 39609  */
 39610  static int proxyCreateUnixFile(
 39611      const char *path,        /* path for the new unixFile */
 39612      unixFile **ppFile,       /* unixFile created and returned by ref */
 39613      int islockfile           /* if non zero missing dirs will be created */
 39614  ) {
 39615    int fd = -1;
 39616    unixFile *pNew;
 39617    int rc = SQLITE_OK;
 39618    int openFlags = O_RDWR | O_CREAT;
 39619    sqlite3_vfs dummyVfs;
 39620    int terrno = 0;
 39621    UnixUnusedFd *pUnused = NULL;
 39622  
 39623    /* 1. first try to open/create the file
 39624    ** 2. if that fails, and this is a lock file (not-conch), try creating
 39625    ** the parent directories and then try again.
 39626    ** 3. if that fails, try to open the file read-only
 39627    ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
 39628    */
 39629    pUnused = findReusableFd(path, openFlags);
 39630    if( pUnused ){
 39631      fd = pUnused->fd;
 39632    }else{
 39633      pUnused = sqlite3_malloc64(sizeof(*pUnused));
 39634      if( !pUnused ){
 39635        return SQLITE_NOMEM_BKPT;
 39636      }
 39637    }
 39638    if( fd<0 ){
 39639      fd = robust_open(path, openFlags, 0);
 39640      terrno = errno;
 39641      if( fd<0 && errno==ENOENT && islockfile ){
 39642        if( proxyCreateLockPath(path) == SQLITE_OK ){
 39643          fd = robust_open(path, openFlags, 0);
 39644        }
 39645      }
 39646    }
 39647    if( fd<0 ){
 39648      openFlags = O_RDONLY;
 39649      fd = robust_open(path, openFlags, 0);
 39650      terrno = errno;
 39651    }
 39652    if( fd<0 ){
 39653      if( islockfile ){
 39654        return SQLITE_BUSY;
 39655      }
 39656      switch (terrno) {
 39657        case EACCES:
 39658          return SQLITE_PERM;
 39659        case EIO: 
 39660          return SQLITE_IOERR_LOCK; /* even though it is the conch */
 39661        default:
 39662          return SQLITE_CANTOPEN_BKPT;
 39663      }
 39664    }
 39665    
 39666    pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
 39667    if( pNew==NULL ){
 39668      rc = SQLITE_NOMEM_BKPT;
 39669      goto end_create_proxy;
 39670    }
 39671    memset(pNew, 0, sizeof(unixFile));
 39672    pNew->openFlags = openFlags;
 39673    memset(&dummyVfs, 0, sizeof(dummyVfs));
 39674    dummyVfs.pAppData = (void*)&autolockIoFinder;
 39675    dummyVfs.zName = "dummy";
 39676    pUnused->fd = fd;
 39677    pUnused->flags = openFlags;
 39678    pNew->pPreallocatedUnused = pUnused;
 39679    
 39680    rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
 39681    if( rc==SQLITE_OK ){
 39682      *ppFile = pNew;
 39683      return SQLITE_OK;
 39684    }
 39685  end_create_proxy:    
 39686    robust_close(pNew, fd, __LINE__);
 39687    sqlite3_free(pNew);
 39688    sqlite3_free(pUnused);
 39689    return rc;
 39690  }
 39691  
 39692  #ifdef SQLITE_TEST
 39693  /* simulate multiple hosts by creating unique hostid file paths */
 39694  SQLITE_API int sqlite3_hostid_num = 0;
 39695  #endif
 39696  
 39697  #define PROXY_HOSTIDLEN    16  /* conch file host id length */
 39698  
 39699  #ifdef HAVE_GETHOSTUUID
 39700  /* Not always defined in the headers as it ought to be */
 39701  extern int gethostuuid(uuid_t id, const struct timespec *wait);
 39702  #endif
 39703  
 39704  /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
 39705  ** bytes of writable memory.
 39706  */
 39707  static int proxyGetHostID(unsigned char *pHostID, int *pError){
 39708    assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
 39709    memset(pHostID, 0, PROXY_HOSTIDLEN);
 39710  #ifdef HAVE_GETHOSTUUID
 39711    {
 39712      struct timespec timeout = {1, 0}; /* 1 sec timeout */
 39713      if( gethostuuid(pHostID, &timeout) ){
 39714        int err = errno;
 39715        if( pError ){
 39716          *pError = err;
 39717        }
 39718        return SQLITE_IOERR;
 39719      }
 39720    }
 39721  #else
 39722    UNUSED_PARAMETER(pError);
 39723  #endif
 39724  #ifdef SQLITE_TEST
 39725    /* simulate multiple hosts by creating unique hostid file paths */
 39726    if( sqlite3_hostid_num != 0){
 39727      pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
 39728    }
 39729  #endif
 39730    
 39731    return SQLITE_OK;
 39732  }
 39733  
 39734  /* The conch file contains the header, host id and lock file path
 39735   */
 39736  #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
 39737  #define PROXY_HEADERLEN    1   /* conch file header length */
 39738  #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
 39739  #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
 39740  
 39741  /* 
 39742  ** Takes an open conch file, copies the contents to a new path and then moves 
 39743  ** it back.  The newly created file's file descriptor is assigned to the
 39744  ** conch file structure and finally the original conch file descriptor is 
 39745  ** closed.  Returns zero if successful.
 39746  */
 39747  static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
 39748    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 39749    unixFile *conchFile = pCtx->conchFile;
 39750    char tPath[MAXPATHLEN];
 39751    char buf[PROXY_MAXCONCHLEN];
 39752    char *cPath = pCtx->conchFilePath;
 39753    size_t readLen = 0;
 39754    size_t pathLen = 0;
 39755    char errmsg[64] = "";
 39756    int fd = -1;
 39757    int rc = -1;
 39758    UNUSED_PARAMETER(myHostID);
 39759  
 39760    /* create a new path by replace the trailing '-conch' with '-break' */
 39761    pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
 39762    if( pathLen>MAXPATHLEN || pathLen<6 || 
 39763       (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
 39764      sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
 39765      goto end_breaklock;
 39766    }
 39767    /* read the conch content */
 39768    readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
 39769    if( readLen<PROXY_PATHINDEX ){
 39770      sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
 39771      goto end_breaklock;
 39772    }
 39773    /* write it out to the temporary break file */
 39774    fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
 39775    if( fd<0 ){
 39776      sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
 39777      goto end_breaklock;
 39778    }
 39779    if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
 39780      sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
 39781      goto end_breaklock;
 39782    }
 39783    if( rename(tPath, cPath) ){
 39784      sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
 39785      goto end_breaklock;
 39786    }
 39787    rc = 0;
 39788    fprintf(stderr, "broke stale lock on %s\n", cPath);
 39789    robust_close(pFile, conchFile->h, __LINE__);
 39790    conchFile->h = fd;
 39791    conchFile->openFlags = O_RDWR | O_CREAT;
 39792  
 39793  end_breaklock:
 39794    if( rc ){
 39795      if( fd>=0 ){
 39796        osUnlink(tPath);
 39797        robust_close(pFile, fd, __LINE__);
 39798      }
 39799      fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
 39800    }
 39801    return rc;
 39802  }
 39803  
 39804  /* Take the requested lock on the conch file and break a stale lock if the 
 39805  ** host id matches.
 39806  */
 39807  static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
 39808    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 39809    unixFile *conchFile = pCtx->conchFile;
 39810    int rc = SQLITE_OK;
 39811    int nTries = 0;
 39812    struct timespec conchModTime;
 39813    
 39814    memset(&conchModTime, 0, sizeof(conchModTime));
 39815    do {
 39816      rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 39817      nTries ++;
 39818      if( rc==SQLITE_BUSY ){
 39819        /* If the lock failed (busy):
 39820         * 1st try: get the mod time of the conch, wait 0.5s and try again. 
 39821         * 2nd try: fail if the mod time changed or host id is different, wait 
 39822         *           10 sec and try again
 39823         * 3rd try: break the lock unless the mod time has changed.
 39824         */
 39825        struct stat buf;
 39826        if( osFstat(conchFile->h, &buf) ){
 39827          storeLastErrno(pFile, errno);
 39828          return SQLITE_IOERR_LOCK;
 39829        }
 39830        
 39831        if( nTries==1 ){
 39832          conchModTime = buf.st_mtimespec;
 39833          usleep(500000); /* wait 0.5 sec and try the lock again*/
 39834          continue;  
 39835        }
 39836  
 39837        assert( nTries>1 );
 39838        if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
 39839           conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
 39840          return SQLITE_BUSY;
 39841        }
 39842        
 39843        if( nTries==2 ){  
 39844          char tBuf[PROXY_MAXCONCHLEN];
 39845          int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
 39846          if( len<0 ){
 39847            storeLastErrno(pFile, errno);
 39848            return SQLITE_IOERR_LOCK;
 39849          }
 39850          if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
 39851            /* don't break the lock if the host id doesn't match */
 39852            if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
 39853              return SQLITE_BUSY;
 39854            }
 39855          }else{
 39856            /* don't break the lock on short read or a version mismatch */
 39857            return SQLITE_BUSY;
 39858          }
 39859          usleep(10000000); /* wait 10 sec and try the lock again */
 39860          continue; 
 39861        }
 39862        
 39863        assert( nTries==3 );
 39864        if( 0==proxyBreakConchLock(pFile, myHostID) ){
 39865          rc = SQLITE_OK;
 39866          if( lockType==EXCLUSIVE_LOCK ){
 39867            rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
 39868          }
 39869          if( !rc ){
 39870            rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
 39871          }
 39872        }
 39873      }
 39874    } while( rc==SQLITE_BUSY && nTries<3 );
 39875    
 39876    return rc;
 39877  }
 39878  
 39879  /* Takes the conch by taking a shared lock and read the contents conch, if 
 39880  ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
 39881  ** lockPath means that the lockPath in the conch file will be used if the 
 39882  ** host IDs match, or a new lock path will be generated automatically 
 39883  ** and written to the conch file.
 39884  */
 39885  static int proxyTakeConch(unixFile *pFile){
 39886    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
 39887    
 39888    if( pCtx->conchHeld!=0 ){
 39889      return SQLITE_OK;
 39890    }else{
 39891      unixFile *conchFile = pCtx->conchFile;
 39892      uuid_t myHostID;
 39893      int pError = 0;
 39894      char readBuf[PROXY_MAXCONCHLEN];
 39895      char lockPath[MAXPATHLEN];
 39896      char *tempLockPath = NULL;
 39897      int rc = SQLITE_OK;
 39898      int createConch = 0;
 39899      int hostIdMatch = 0;
 39900      int readLen = 0;
 39901      int tryOldLockPath = 0;
 39902      int forceNewLockPath = 0;
 39903      
 39904      OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
 39905               (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
 39906               osGetpid(0)));
 39907  
 39908      rc = proxyGetHostID(myHostID, &pError);
 39909      if( (rc&0xff)==SQLITE_IOERR ){
 39910        storeLastErrno(pFile, pError);
 39911        goto end_takeconch;
 39912      }
 39913      rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
 39914      if( rc!=SQLITE_OK ){
 39915        goto end_takeconch;
 39916      }
 39917      /* read the existing conch file */
 39918      readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
 39919      if( readLen<0 ){
 39920        /* I/O error: lastErrno set by seekAndRead */
 39921        storeLastErrno(pFile, conchFile->lastErrno);
 39922        rc = SQLITE_IOERR_READ;
 39923        goto end_takeconch;
 39924      }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
 39925               readBuf[0]!=(char)PROXY_CONCHVERSION ){
 39926        /* a short read or version format mismatch means we need to create a new 
 39927        ** conch file. 
 39928        */
 39929        createConch = 1;
 39930      }
 39931      /* if the host id matches and the lock path already exists in the conch
 39932      ** we'll try to use the path there, if we can't open that path, we'll 
 39933      ** retry with a new auto-generated path 
 39934      */
 39935      do { /* in case we need to try again for an :auto: named lock file */
 39936  
 39937        if( !createConch && !forceNewLockPath ){
 39938          hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
 39939                                    PROXY_HOSTIDLEN);
 39940          /* if the conch has data compare the contents */
 39941          if( !pCtx->lockProxyPath ){
 39942            /* for auto-named local lock file, just check the host ID and we'll
 39943             ** use the local lock file path that's already in there
 39944             */
 39945            if( hostIdMatch ){
 39946              size_t pathLen = (readLen - PROXY_PATHINDEX);
 39947              
 39948              if( pathLen>=MAXPATHLEN ){
 39949                pathLen=MAXPATHLEN-1;
 39950              }
 39951              memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
 39952              lockPath[pathLen] = 0;
 39953              tempLockPath = lockPath;
 39954              tryOldLockPath = 1;
 39955              /* create a copy of the lock path if the conch is taken */
 39956              goto end_takeconch;
 39957            }
 39958          }else if( hostIdMatch
 39959                 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
 39960                             readLen-PROXY_PATHINDEX)
 39961          ){
 39962            /* conch host and lock path match */
 39963            goto end_takeconch; 
 39964          }
 39965        }
 39966        
 39967        /* if the conch isn't writable and doesn't match, we can't take it */
 39968        if( (conchFile->openFlags&O_RDWR) == 0 ){
 39969          rc = SQLITE_BUSY;
 39970          goto end_takeconch;
 39971        }
 39972        
 39973        /* either the conch didn't match or we need to create a new one */
 39974        if( !pCtx->lockProxyPath ){
 39975          proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
 39976          tempLockPath = lockPath;
 39977          /* create a copy of the lock path _only_ if the conch is taken */
 39978        }
 39979        
 39980        /* update conch with host and path (this will fail if other process
 39981        ** has a shared lock already), if the host id matches, use the big
 39982        ** stick.
 39983        */
 39984        futimes(conchFile->h, NULL);
 39985        if( hostIdMatch && !createConch ){
 39986          if( conchFile->pInode && conchFile->pInode->nShared>1 ){
 39987            /* We are trying for an exclusive lock but another thread in this
 39988             ** same process is still holding a shared lock. */
 39989            rc = SQLITE_BUSY;
 39990          } else {          
 39991            rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
 39992          }
 39993        }else{
 39994          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
 39995        }
 39996        if( rc==SQLITE_OK ){
 39997          char writeBuffer[PROXY_MAXCONCHLEN];
 39998          int writeSize = 0;
 39999          
 40000          writeBuffer[0] = (char)PROXY_CONCHVERSION;
 40001          memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
 40002          if( pCtx->lockProxyPath!=NULL ){
 40003            strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
 40004                    MAXPATHLEN);
 40005          }else{
 40006            strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
 40007          }
 40008          writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
 40009          robust_ftruncate(conchFile->h, writeSize);
 40010          rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
 40011          full_fsync(conchFile->h,0,0);
 40012          /* If we created a new conch file (not just updated the contents of a 
 40013           ** valid conch file), try to match the permissions of the database 
 40014           */
 40015          if( rc==SQLITE_OK && createConch ){
 40016            struct stat buf;
 40017            int err = osFstat(pFile->h, &buf);
 40018            if( err==0 ){
 40019              mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
 40020                                          S_IROTH|S_IWOTH);
 40021              /* try to match the database file R/W permissions, ignore failure */
 40022  #ifndef SQLITE_PROXY_DEBUG
 40023              osFchmod(conchFile->h, cmode);
 40024  #else
 40025              do{
 40026                rc = osFchmod(conchFile->h, cmode);
 40027              }while( rc==(-1) && errno==EINTR );
 40028              if( rc!=0 ){
 40029                int code = errno;
 40030                fprintf(stderr, "fchmod %o FAILED with %d %s\n",
 40031                        cmode, code, strerror(code));
 40032              } else {
 40033                fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
 40034              }
 40035            }else{
 40036              int code = errno;
 40037              fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
 40038                      err, code, strerror(code));
 40039  #endif
 40040            }
 40041          }
 40042        }
 40043        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
 40044        
 40045      end_takeconch:
 40046        OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
 40047        if( rc==SQLITE_OK && pFile->openFlags ){
 40048          int fd;
 40049          if( pFile->h>=0 ){
 40050            robust_close(pFile, pFile->h, __LINE__);
 40051          }
 40052          pFile->h = -1;
 40053          fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
 40054          OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
 40055          if( fd>=0 ){
 40056            pFile->h = fd;
 40057          }else{
 40058            rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
 40059             during locking */
 40060          }
 40061        }
 40062        if( rc==SQLITE_OK && !pCtx->lockProxy ){
 40063          char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
 40064          rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
 40065          if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
 40066            /* we couldn't create the proxy lock file with the old lock file path
 40067             ** so try again via auto-naming 
 40068             */
 40069            forceNewLockPath = 1;
 40070            tryOldLockPath = 0;
 40071            continue; /* go back to the do {} while start point, try again */
 40072          }
 40073        }
 40074        if( rc==SQLITE_OK ){
 40075          /* Need to make a copy of path if we extracted the value
 40076           ** from the conch file or the path was allocated on the stack
 40077           */
 40078          if( tempLockPath ){
 40079            pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
 40080            if( !pCtx->lockProxyPath ){
 40081              rc = SQLITE_NOMEM_BKPT;
 40082            }
 40083          }
 40084        }
 40085        if( rc==SQLITE_OK ){
 40086          pCtx->conchHeld = 1;
 40087          
 40088          if( pCtx->lockProxy->pMethod == &afpIoMethods ){
 40089            afpLockingContext *afpCtx;
 40090            afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
 40091            afpCtx->dbPath = pCtx->lockProxyPath;
 40092          }
 40093        } else {
 40094          conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 40095        }
 40096        OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
 40097                 rc==SQLITE_OK?"ok":"failed"));
 40098        return rc;
 40099      } while (1); /* in case we need to retry the :auto: lock file - 
 40100                   ** we should never get here except via the 'continue' call. */
 40101    }
 40102  }
 40103  
 40104  /*
 40105  ** If pFile holds a lock on a conch file, then release that lock.
 40106  */
 40107  static int proxyReleaseConch(unixFile *pFile){
 40108    int rc = SQLITE_OK;         /* Subroutine return code */
 40109    proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
 40110    unixFile *conchFile;        /* Name of the conch file */
 40111  
 40112    pCtx = (proxyLockingContext *)pFile->lockingContext;
 40113    conchFile = pCtx->conchFile;
 40114    OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
 40115             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
 40116             osGetpid(0)));
 40117    if( pCtx->conchHeld>0 ){
 40118      rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
 40119    }
 40120    pCtx->conchHeld = 0;
 40121    OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
 40122             (rc==SQLITE_OK ? "ok" : "failed")));
 40123    return rc;
 40124  }
 40125  
 40126  /*
 40127  ** Given the name of a database file, compute the name of its conch file.
 40128  ** Store the conch filename in memory obtained from sqlite3_malloc64().
 40129  ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
 40130  ** or SQLITE_NOMEM if unable to obtain memory.
 40131  **
 40132  ** The caller is responsible for ensuring that the allocated memory
 40133  ** space is eventually freed.
 40134  **
 40135  ** *pConchPath is set to NULL if a memory allocation error occurs.
 40136  */
 40137  static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
 40138    int i;                        /* Loop counter */
 40139    int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
 40140    char *conchPath;              /* buffer in which to construct conch name */
 40141  
 40142    /* Allocate space for the conch filename and initialize the name to
 40143    ** the name of the original database file. */  
 40144    *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
 40145    if( conchPath==0 ){
 40146      return SQLITE_NOMEM_BKPT;
 40147    }
 40148    memcpy(conchPath, dbPath, len+1);
 40149    
 40150    /* now insert a "." before the last / character */
 40151    for( i=(len-1); i>=0; i-- ){
 40152      if( conchPath[i]=='/' ){
 40153        i++;
 40154        break;
 40155      }
 40156    }
 40157    conchPath[i]='.';
 40158    while ( i<len ){
 40159      conchPath[i+1]=dbPath[i];
 40160      i++;
 40161    }
 40162  
 40163    /* append the "-conch" suffix to the file */
 40164    memcpy(&conchPath[i+1], "-conch", 7);
 40165    assert( (int)strlen(conchPath) == len+7 );
 40166  
 40167    return SQLITE_OK;
 40168  }
 40169  
 40170  
 40171  /* Takes a fully configured proxy locking-style unix file and switches
 40172  ** the local lock file path 
 40173  */
 40174  static int switchLockProxyPath(unixFile *pFile, const char *path) {
 40175    proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 40176    char *oldPath = pCtx->lockProxyPath;
 40177    int rc = SQLITE_OK;
 40178  
 40179    if( pFile->eFileLock!=NO_LOCK ){
 40180      return SQLITE_BUSY;
 40181    }  
 40182  
 40183    /* nothing to do if the path is NULL, :auto: or matches the existing path */
 40184    if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
 40185      (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
 40186      return SQLITE_OK;
 40187    }else{
 40188      unixFile *lockProxy = pCtx->lockProxy;
 40189      pCtx->lockProxy=NULL;
 40190      pCtx->conchHeld = 0;
 40191      if( lockProxy!=NULL ){
 40192        rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
 40193        if( rc ) return rc;
 40194        sqlite3_free(lockProxy);
 40195      }
 40196      sqlite3_free(oldPath);
 40197      pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
 40198    }
 40199    
 40200    return rc;
 40201  }
 40202  
 40203  /*
 40204  ** pFile is a file that has been opened by a prior xOpen call.  dbPath
 40205  ** is a string buffer at least MAXPATHLEN+1 characters in size.
 40206  **
 40207  ** This routine find the filename associated with pFile and writes it
 40208  ** int dbPath.
 40209  */
 40210  static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
 40211  #if defined(__APPLE__)
 40212    if( pFile->pMethod == &afpIoMethods ){
 40213      /* afp style keeps a reference to the db path in the filePath field 
 40214      ** of the struct */
 40215      assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 40216      strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
 40217              MAXPATHLEN);
 40218    } else
 40219  #endif
 40220    if( pFile->pMethod == &dotlockIoMethods ){
 40221      /* dot lock style uses the locking context to store the dot lock
 40222      ** file path */
 40223      int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
 40224      memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
 40225    }else{
 40226      /* all other styles use the locking context to store the db file path */
 40227      assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
 40228      strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
 40229    }
 40230    return SQLITE_OK;
 40231  }
 40232  
 40233  /*
 40234  ** Takes an already filled in unix file and alters it so all file locking 
 40235  ** will be performed on the local proxy lock file.  The following fields
 40236  ** are preserved in the locking context so that they can be restored and 
 40237  ** the unix structure properly cleaned up at close time:
 40238  **  ->lockingContext
 40239  **  ->pMethod
 40240  */
 40241  static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
 40242    proxyLockingContext *pCtx;
 40243    char dbPath[MAXPATHLEN+1];       /* Name of the database file */
 40244    char *lockPath=NULL;
 40245    int rc = SQLITE_OK;
 40246    
 40247    if( pFile->eFileLock!=NO_LOCK ){
 40248      return SQLITE_BUSY;
 40249    }
 40250    proxyGetDbPathForUnixFile(pFile, dbPath);
 40251    if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
 40252      lockPath=NULL;
 40253    }else{
 40254      lockPath=(char *)path;
 40255    }
 40256    
 40257    OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
 40258             (lockPath ? lockPath : ":auto:"), osGetpid(0)));
 40259  
 40260    pCtx = sqlite3_malloc64( sizeof(*pCtx) );
 40261    if( pCtx==0 ){
 40262      return SQLITE_NOMEM_BKPT;
 40263    }
 40264    memset(pCtx, 0, sizeof(*pCtx));
 40265  
 40266    rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
 40267    if( rc==SQLITE_OK ){
 40268      rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
 40269      if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
 40270        /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
 40271        ** (c) the file system is read-only, then enable no-locking access.
 40272        ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
 40273        ** that openFlags will have only one of O_RDONLY or O_RDWR.
 40274        */
 40275        struct statfs fsInfo;
 40276        struct stat conchInfo;
 40277        int goLockless = 0;
 40278  
 40279        if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
 40280          int err = errno;
 40281          if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
 40282            goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
 40283          }
 40284        }
 40285        if( goLockless ){
 40286          pCtx->conchHeld = -1; /* read only FS/ lockless */
 40287          rc = SQLITE_OK;
 40288        }
 40289      }
 40290    }  
 40291    if( rc==SQLITE_OK && lockPath ){
 40292      pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
 40293    }
 40294  
 40295    if( rc==SQLITE_OK ){
 40296      pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
 40297      if( pCtx->dbPath==NULL ){
 40298        rc = SQLITE_NOMEM_BKPT;
 40299      }
 40300    }
 40301    if( rc==SQLITE_OK ){
 40302      /* all memory is allocated, proxys are created and assigned, 
 40303      ** switch the locking context and pMethod then return.
 40304      */
 40305      pCtx->oldLockingContext = pFile->lockingContext;
 40306      pFile->lockingContext = pCtx;
 40307      pCtx->pOldMethod = pFile->pMethod;
 40308      pFile->pMethod = &proxyIoMethods;
 40309    }else{
 40310      if( pCtx->conchFile ){ 
 40311        pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
 40312        sqlite3_free(pCtx->conchFile);
 40313      }
 40314      sqlite3DbFree(0, pCtx->lockProxyPath);
 40315      sqlite3_free(pCtx->conchFilePath); 
 40316      sqlite3_free(pCtx);
 40317    }
 40318    OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
 40319             (rc==SQLITE_OK ? "ok" : "failed")));
 40320    return rc;
 40321  }
 40322  
 40323  
 40324  /*
 40325  ** This routine handles sqlite3_file_control() calls that are specific
 40326  ** to proxy locking.
 40327  */
 40328  static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
 40329    switch( op ){
 40330      case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
 40331        unixFile *pFile = (unixFile*)id;
 40332        if( pFile->pMethod == &proxyIoMethods ){
 40333          proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
 40334          proxyTakeConch(pFile);
 40335          if( pCtx->lockProxyPath ){
 40336            *(const char **)pArg = pCtx->lockProxyPath;
 40337          }else{
 40338            *(const char **)pArg = ":auto: (not held)";
 40339          }
 40340        } else {
 40341          *(const char **)pArg = NULL;
 40342        }
 40343        return SQLITE_OK;
 40344      }
 40345      case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
 40346        unixFile *pFile = (unixFile*)id;
 40347        int rc = SQLITE_OK;
 40348        int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
 40349        if( pArg==NULL || (const char *)pArg==0 ){
 40350          if( isProxyStyle ){
 40351            /* turn off proxy locking - not supported.  If support is added for
 40352            ** switching proxy locking mode off then it will need to fail if
 40353            ** the journal mode is WAL mode. 
 40354            */
 40355            rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
 40356          }else{
 40357            /* turn off proxy locking - already off - NOOP */
 40358            rc = SQLITE_OK;
 40359          }
 40360        }else{
 40361          const char *proxyPath = (const char *)pArg;
 40362          if( isProxyStyle ){
 40363            proxyLockingContext *pCtx = 
 40364              (proxyLockingContext*)pFile->lockingContext;
 40365            if( !strcmp(pArg, ":auto:") 
 40366             || (pCtx->lockProxyPath &&
 40367                 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
 40368            ){
 40369              rc = SQLITE_OK;
 40370            }else{
 40371              rc = switchLockProxyPath(pFile, proxyPath);
 40372            }
 40373          }else{
 40374            /* turn on proxy file locking */
 40375            rc = proxyTransformUnixFile(pFile, proxyPath);
 40376          }
 40377        }
 40378        return rc;
 40379      }
 40380      default: {
 40381        assert( 0 );  /* The call assures that only valid opcodes are sent */
 40382      }
 40383    }
 40384    /*NOTREACHED*/
 40385    return SQLITE_ERROR;
 40386  }
 40387  
 40388  /*
 40389  ** Within this division (the proxying locking implementation) the procedures
 40390  ** above this point are all utilities.  The lock-related methods of the
 40391  ** proxy-locking sqlite3_io_method object follow.
 40392  */
 40393  
 40394  
 40395  /*
 40396  ** This routine checks if there is a RESERVED lock held on the specified
 40397  ** file by this or any other process. If such a lock is held, set *pResOut
 40398  ** to a non-zero value otherwise *pResOut is set to zero.  The return value
 40399  ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
 40400  */
 40401  static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
 40402    unixFile *pFile = (unixFile*)id;
 40403    int rc = proxyTakeConch(pFile);
 40404    if( rc==SQLITE_OK ){
 40405      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 40406      if( pCtx->conchHeld>0 ){
 40407        unixFile *proxy = pCtx->lockProxy;
 40408        return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
 40409      }else{ /* conchHeld < 0 is lockless */
 40410        pResOut=0;
 40411      }
 40412    }
 40413    return rc;
 40414  }
 40415  
 40416  /*
 40417  ** Lock the file with the lock specified by parameter eFileLock - one
 40418  ** of the following:
 40419  **
 40420  **     (1) SHARED_LOCK
 40421  **     (2) RESERVED_LOCK
 40422  **     (3) PENDING_LOCK
 40423  **     (4) EXCLUSIVE_LOCK
 40424  **
 40425  ** Sometimes when requesting one lock state, additional lock states
 40426  ** are inserted in between.  The locking might fail on one of the later
 40427  ** transitions leaving the lock state different from what it started but
 40428  ** still short of its goal.  The following chart shows the allowed
 40429  ** transitions and the inserted intermediate states:
 40430  **
 40431  **    UNLOCKED -> SHARED
 40432  **    SHARED -> RESERVED
 40433  **    SHARED -> (PENDING) -> EXCLUSIVE
 40434  **    RESERVED -> (PENDING) -> EXCLUSIVE
 40435  **    PENDING -> EXCLUSIVE
 40436  **
 40437  ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
 40438  ** routine to lower a locking level.
 40439  */
 40440  static int proxyLock(sqlite3_file *id, int eFileLock) {
 40441    unixFile *pFile = (unixFile*)id;
 40442    int rc = proxyTakeConch(pFile);
 40443    if( rc==SQLITE_OK ){
 40444      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 40445      if( pCtx->conchHeld>0 ){
 40446        unixFile *proxy = pCtx->lockProxy;
 40447        rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
 40448        pFile->eFileLock = proxy->eFileLock;
 40449      }else{
 40450        /* conchHeld < 0 is lockless */
 40451      }
 40452    }
 40453    return rc;
 40454  }
 40455  
 40456  
 40457  /*
 40458  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
 40459  ** must be either NO_LOCK or SHARED_LOCK.
 40460  **
 40461  ** If the locking level of the file descriptor is already at or below
 40462  ** the requested locking level, this routine is a no-op.
 40463  */
 40464  static int proxyUnlock(sqlite3_file *id, int eFileLock) {
 40465    unixFile *pFile = (unixFile*)id;
 40466    int rc = proxyTakeConch(pFile);
 40467    if( rc==SQLITE_OK ){
 40468      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 40469      if( pCtx->conchHeld>0 ){
 40470        unixFile *proxy = pCtx->lockProxy;
 40471        rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
 40472        pFile->eFileLock = proxy->eFileLock;
 40473      }else{
 40474        /* conchHeld < 0 is lockless */
 40475      }
 40476    }
 40477    return rc;
 40478  }
 40479  
 40480  /*
 40481  ** Close a file that uses proxy locks.
 40482  */
 40483  static int proxyClose(sqlite3_file *id) {
 40484    if( ALWAYS(id) ){
 40485      unixFile *pFile = (unixFile*)id;
 40486      proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
 40487      unixFile *lockProxy = pCtx->lockProxy;
 40488      unixFile *conchFile = pCtx->conchFile;
 40489      int rc = SQLITE_OK;
 40490      
 40491      if( lockProxy ){
 40492        rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
 40493        if( rc ) return rc;
 40494        rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
 40495        if( rc ) return rc;
 40496        sqlite3_free(lockProxy);
 40497        pCtx->lockProxy = 0;
 40498      }
 40499      if( conchFile ){
 40500        if( pCtx->conchHeld ){
 40501          rc = proxyReleaseConch(pFile);
 40502          if( rc ) return rc;
 40503        }
 40504        rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
 40505        if( rc ) return rc;
 40506        sqlite3_free(conchFile);
 40507      }
 40508      sqlite3DbFree(0, pCtx->lockProxyPath);
 40509      sqlite3_free(pCtx->conchFilePath);
 40510      sqlite3DbFree(0, pCtx->dbPath);
 40511      /* restore the original locking context and pMethod then close it */
 40512      pFile->lockingContext = pCtx->oldLockingContext;
 40513      pFile->pMethod = pCtx->pOldMethod;
 40514      sqlite3_free(pCtx);
 40515      return pFile->pMethod->xClose(id);
 40516    }
 40517    return SQLITE_OK;
 40518  }
 40519  
 40520  
 40521  
 40522  #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
 40523  /*
 40524  ** The proxy locking style is intended for use with AFP filesystems.
 40525  ** And since AFP is only supported on MacOSX, the proxy locking is also
 40526  ** restricted to MacOSX.
 40527  ** 
 40528  **
 40529  ******************* End of the proxy lock implementation **********************
 40530  ******************************************************************************/
 40531  
 40532  /*
 40533  ** Initialize the operating system interface.
 40534  **
 40535  ** This routine registers all VFS implementations for unix-like operating
 40536  ** systems.  This routine, and the sqlite3_os_end() routine that follows,
 40537  ** should be the only routines in this file that are visible from other
 40538  ** files.
 40539  **
 40540  ** This routine is called once during SQLite initialization and by a
 40541  ** single thread.  The memory allocation and mutex subsystems have not
 40542  ** necessarily been initialized when this routine is called, and so they
 40543  ** should not be used.
 40544  */
 40545  SQLITE_API int sqlite3_os_init(void){ 
 40546    /* 
 40547    ** The following macro defines an initializer for an sqlite3_vfs object.
 40548    ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
 40549    ** to the "finder" function.  (pAppData is a pointer to a pointer because
 40550    ** silly C90 rules prohibit a void* from being cast to a function pointer
 40551    ** and so we have to go through the intermediate pointer to avoid problems
 40552    ** when compiling with -pedantic-errors on GCC.)
 40553    **
 40554    ** The FINDER parameter to this macro is the name of the pointer to the
 40555    ** finder-function.  The finder-function returns a pointer to the
 40556    ** sqlite_io_methods object that implements the desired locking
 40557    ** behaviors.  See the division above that contains the IOMETHODS
 40558    ** macro for addition information on finder-functions.
 40559    **
 40560    ** Most finders simply return a pointer to a fixed sqlite3_io_methods
 40561    ** object.  But the "autolockIoFinder" available on MacOSX does a little
 40562    ** more than that; it looks at the filesystem type that hosts the 
 40563    ** database file and tries to choose an locking method appropriate for
 40564    ** that filesystem time.
 40565    */
 40566    #define UNIXVFS(VFSNAME, FINDER) {                        \
 40567      3,                    /* iVersion */                    \
 40568      sizeof(unixFile),     /* szOsFile */                    \
 40569      MAX_PATHNAME,         /* mxPathname */                  \
 40570      0,                    /* pNext */                       \
 40571      VFSNAME,              /* zName */                       \
 40572      (void*)&FINDER,       /* pAppData */                    \
 40573      unixOpen,             /* xOpen */                       \
 40574      unixDelete,           /* xDelete */                     \
 40575      unixAccess,           /* xAccess */                     \
 40576      unixFullPathname,     /* xFullPathname */               \
 40577      unixDlOpen,           /* xDlOpen */                     \
 40578      unixDlError,          /* xDlError */                    \
 40579      unixDlSym,            /* xDlSym */                      \
 40580      unixDlClose,          /* xDlClose */                    \
 40581      unixRandomness,       /* xRandomness */                 \
 40582      unixSleep,            /* xSleep */                      \
 40583      unixCurrentTime,      /* xCurrentTime */                \
 40584      unixGetLastError,     /* xGetLastError */               \
 40585      unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
 40586      unixSetSystemCall,    /* xSetSystemCall */              \
 40587      unixGetSystemCall,    /* xGetSystemCall */              \
 40588      unixNextSystemCall,   /* xNextSystemCall */             \
 40589    }
 40590  
 40591    /*
 40592    ** All default VFSes for unix are contained in the following array.
 40593    **
 40594    ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
 40595    ** by the SQLite core when the VFS is registered.  So the following
 40596    ** array cannot be const.
 40597    */
 40598    static sqlite3_vfs aVfs[] = {
 40599  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 40600      UNIXVFS("unix",          autolockIoFinder ),
 40601  #elif OS_VXWORKS
 40602      UNIXVFS("unix",          vxworksIoFinder ),
 40603  #else
 40604      UNIXVFS("unix",          posixIoFinder ),
 40605  #endif
 40606      UNIXVFS("unix-none",     nolockIoFinder ),
 40607      UNIXVFS("unix-dotfile",  dotlockIoFinder ),
 40608      UNIXVFS("unix-excl",     posixIoFinder ),
 40609  #if OS_VXWORKS
 40610      UNIXVFS("unix-namedsem", semIoFinder ),
 40611  #endif
 40612  #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
 40613      UNIXVFS("unix-posix",    posixIoFinder ),
 40614  #endif
 40615  #if SQLITE_ENABLE_LOCKING_STYLE
 40616      UNIXVFS("unix-flock",    flockIoFinder ),
 40617  #endif
 40618  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
 40619      UNIXVFS("unix-afp",      afpIoFinder ),
 40620      UNIXVFS("unix-nfs",      nfsIoFinder ),
 40621      UNIXVFS("unix-proxy",    proxyIoFinder ),
 40622  #endif
 40623    };
 40624    unsigned int i;          /* Loop counter */
 40625  
 40626    /* Double-check that the aSyscall[] array has been constructed
 40627    ** correctly.  See ticket [bb3a86e890c8e96ab] */
 40628    assert( ArraySize(aSyscall)==29 );
 40629  
 40630    /* Register all VFSes defined in the aVfs[] array */
 40631    for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
 40632      sqlite3_vfs_register(&aVfs[i], i==0);
 40633    }
 40634    unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
 40635    return SQLITE_OK; 
 40636  }
 40637  
 40638  /*
 40639  ** Shutdown the operating system interface.
 40640  **
 40641  ** Some operating systems might need to do some cleanup in this routine,
 40642  ** to release dynamically allocated objects.  But not on unix.
 40643  ** This routine is a no-op for unix.
 40644  */
 40645  SQLITE_API int sqlite3_os_end(void){ 
 40646    unixBigLock = 0;
 40647    return SQLITE_OK; 
 40648  }
 40649   
 40650  #endif /* SQLITE_OS_UNIX */
 40651  
 40652  /************** End of os_unix.c *********************************************/
 40653  /************** Begin file os_win.c ******************************************/
 40654  /*
 40655  ** 2004 May 22
 40656  **
 40657  ** The author disclaims copyright to this source code.  In place of
 40658  ** a legal notice, here is a blessing:
 40659  **
 40660  **    May you do good and not evil.
 40661  **    May you find forgiveness for yourself and forgive others.
 40662  **    May you share freely, never taking more than you give.
 40663  **
 40664  ******************************************************************************
 40665  **
 40666  ** This file contains code that is specific to Windows.
 40667  */
 40668  /* #include "sqliteInt.h" */
 40669  #if SQLITE_OS_WIN               /* This file is used for Windows only */
 40670  
 40671  /*
 40672  ** Include code that is common to all os_*.c files
 40673  */
 40674  /************** Include os_common.h in the middle of os_win.c ****************/
 40675  /************** Begin file os_common.h ***************************************/
 40676  /*
 40677  ** 2004 May 22
 40678  **
 40679  ** The author disclaims copyright to this source code.  In place of
 40680  ** a legal notice, here is a blessing:
 40681  **
 40682  **    May you do good and not evil.
 40683  **    May you find forgiveness for yourself and forgive others.
 40684  **    May you share freely, never taking more than you give.
 40685  **
 40686  ******************************************************************************
 40687  **
 40688  ** This file contains macros and a little bit of code that is common to
 40689  ** all of the platform-specific files (os_*.c) and is #included into those
 40690  ** files.
 40691  **
 40692  ** This file should be #included by the os_*.c files only.  It is not a
 40693  ** general purpose header file.
 40694  */
 40695  #ifndef _OS_COMMON_H_
 40696  #define _OS_COMMON_H_
 40697  
 40698  /*
 40699  ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
 40700  ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
 40701  ** switch.  The following code should catch this problem at compile-time.
 40702  */
 40703  #ifdef MEMORY_DEBUG
 40704  # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
 40705  #endif
 40706  
 40707  /*
 40708  ** Macros for performance tracing.  Normally turned off.  Only works
 40709  ** on i486 hardware.
 40710  */
 40711  #ifdef SQLITE_PERFORMANCE_TRACE
 40712  
 40713  /*
 40714  ** hwtime.h contains inline assembler code for implementing
 40715  ** high-performance timing routines.
 40716  */
 40717  /************** Include hwtime.h in the middle of os_common.h ****************/
 40718  /************** Begin file hwtime.h ******************************************/
 40719  /*
 40720  ** 2008 May 27
 40721  **
 40722  ** The author disclaims copyright to this source code.  In place of
 40723  ** a legal notice, here is a blessing:
 40724  **
 40725  **    May you do good and not evil.
 40726  **    May you find forgiveness for yourself and forgive others.
 40727  **    May you share freely, never taking more than you give.
 40728  **
 40729  ******************************************************************************
 40730  **
 40731  ** This file contains inline asm code for retrieving "high-performance"
 40732  ** counters for x86 class CPUs.
 40733  */
 40734  #ifndef SQLITE_HWTIME_H
 40735  #define SQLITE_HWTIME_H
 40736  
 40737  /*
 40738  ** The following routine only works on pentium-class (or newer) processors.
 40739  ** It uses the RDTSC opcode to read the cycle count value out of the
 40740  ** processor and returns that value.  This can be used for high-res
 40741  ** profiling.
 40742  */
 40743  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 40744        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 40745  
 40746    #if defined(__GNUC__)
 40747  
 40748    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 40749       unsigned int lo, hi;
 40750       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 40751       return (sqlite_uint64)hi << 32 | lo;
 40752    }
 40753  
 40754    #elif defined(_MSC_VER)
 40755  
 40756    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 40757       __asm {
 40758          rdtsc
 40759          ret       ; return value at EDX:EAX
 40760       }
 40761    }
 40762  
 40763    #endif
 40764  
 40765  #elif (defined(__GNUC__) && defined(__x86_64__))
 40766  
 40767    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 40768        unsigned long val;
 40769        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 40770        return val;
 40771    }
 40772   
 40773  #elif (defined(__GNUC__) && defined(__ppc__))
 40774  
 40775    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 40776        unsigned long long retval;
 40777        unsigned long junk;
 40778        __asm__ __volatile__ ("\n\
 40779            1:      mftbu   %1\n\
 40780                    mftb    %L0\n\
 40781                    mftbu   %0\n\
 40782                    cmpw    %0,%1\n\
 40783                    bne     1b"
 40784                    : "=r" (retval), "=r" (junk));
 40785        return retval;
 40786    }
 40787  
 40788  #else
 40789  
 40790    #error Need implementation of sqlite3Hwtime() for your platform.
 40791  
 40792    /*
 40793    ** To compile without implementing sqlite3Hwtime() for your platform,
 40794    ** you can remove the above #error and use the following
 40795    ** stub function.  You will lose timing support for many
 40796    ** of the debugging and testing utilities, but it should at
 40797    ** least compile and run.
 40798    */
 40799  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 40800  
 40801  #endif
 40802  
 40803  #endif /* !defined(SQLITE_HWTIME_H) */
 40804  
 40805  /************** End of hwtime.h **********************************************/
 40806  /************** Continuing where we left off in os_common.h ******************/
 40807  
 40808  static sqlite_uint64 g_start;
 40809  static sqlite_uint64 g_elapsed;
 40810  #define TIMER_START       g_start=sqlite3Hwtime()
 40811  #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
 40812  #define TIMER_ELAPSED     g_elapsed
 40813  #else
 40814  #define TIMER_START
 40815  #define TIMER_END
 40816  #define TIMER_ELAPSED     ((sqlite_uint64)0)
 40817  #endif
 40818  
 40819  /*
 40820  ** If we compile with the SQLITE_TEST macro set, then the following block
 40821  ** of code will give us the ability to simulate a disk I/O error.  This
 40822  ** is used for testing the I/O recovery logic.
 40823  */
 40824  #if defined(SQLITE_TEST)
 40825  SQLITE_API extern int sqlite3_io_error_hit;
 40826  SQLITE_API extern int sqlite3_io_error_hardhit;
 40827  SQLITE_API extern int sqlite3_io_error_pending;
 40828  SQLITE_API extern int sqlite3_io_error_persist;
 40829  SQLITE_API extern int sqlite3_io_error_benign;
 40830  SQLITE_API extern int sqlite3_diskfull_pending;
 40831  SQLITE_API extern int sqlite3_diskfull;
 40832  #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
 40833  #define SimulateIOError(CODE)  \
 40834    if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
 40835         || sqlite3_io_error_pending-- == 1 )  \
 40836                { local_ioerr(); CODE; }
 40837  static void local_ioerr(){
 40838    IOTRACE(("IOERR\n"));
 40839    sqlite3_io_error_hit++;
 40840    if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
 40841  }
 40842  #define SimulateDiskfullError(CODE) \
 40843     if( sqlite3_diskfull_pending ){ \
 40844       if( sqlite3_diskfull_pending == 1 ){ \
 40845         local_ioerr(); \
 40846         sqlite3_diskfull = 1; \
 40847         sqlite3_io_error_hit = 1; \
 40848         CODE; \
 40849       }else{ \
 40850         sqlite3_diskfull_pending--; \
 40851       } \
 40852     }
 40853  #else
 40854  #define SimulateIOErrorBenign(X)
 40855  #define SimulateIOError(A)
 40856  #define SimulateDiskfullError(A)
 40857  #endif /* defined(SQLITE_TEST) */
 40858  
 40859  /*
 40860  ** When testing, keep a count of the number of open files.
 40861  */
 40862  #if defined(SQLITE_TEST)
 40863  SQLITE_API extern int sqlite3_open_file_count;
 40864  #define OpenCounter(X)  sqlite3_open_file_count+=(X)
 40865  #else
 40866  #define OpenCounter(X)
 40867  #endif /* defined(SQLITE_TEST) */
 40868  
 40869  #endif /* !defined(_OS_COMMON_H_) */
 40870  
 40871  /************** End of os_common.h *******************************************/
 40872  /************** Continuing where we left off in os_win.c *********************/
 40873  
 40874  /*
 40875  ** Include the header file for the Windows VFS.
 40876  */
 40877  /* #include "os_win.h" */
 40878  
 40879  /*
 40880  ** Compiling and using WAL mode requires several APIs that are only
 40881  ** available in Windows platforms based on the NT kernel.
 40882  */
 40883  #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
 40884  #  error "WAL mode requires support from the Windows NT kernel, compile\
 40885   with SQLITE_OMIT_WAL."
 40886  #endif
 40887  
 40888  #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
 40889  #  error "Memory mapped files require support from the Windows NT kernel,\
 40890   compile with SQLITE_MAX_MMAP_SIZE=0."
 40891  #endif
 40892  
 40893  /*
 40894  ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
 40895  ** based on the sub-platform)?
 40896  */
 40897  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
 40898  #  define SQLITE_WIN32_HAS_ANSI
 40899  #endif
 40900  
 40901  /*
 40902  ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
 40903  ** based on the sub-platform)?
 40904  */
 40905  #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
 40906      !defined(SQLITE_WIN32_NO_WIDE)
 40907  #  define SQLITE_WIN32_HAS_WIDE
 40908  #endif
 40909  
 40910  /*
 40911  ** Make sure at least one set of Win32 APIs is available.
 40912  */
 40913  #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
 40914  #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
 40915   must be defined."
 40916  #endif
 40917  
 40918  /*
 40919  ** Define the required Windows SDK version constants if they are not
 40920  ** already available.
 40921  */
 40922  #ifndef NTDDI_WIN8
 40923  #  define NTDDI_WIN8                        0x06020000
 40924  #endif
 40925  
 40926  #ifndef NTDDI_WINBLUE
 40927  #  define NTDDI_WINBLUE                     0x06030000
 40928  #endif
 40929  
 40930  #ifndef NTDDI_WINTHRESHOLD
 40931  #  define NTDDI_WINTHRESHOLD                0x06040000
 40932  #endif
 40933  
 40934  /*
 40935  ** Check to see if the GetVersionEx[AW] functions are deprecated on the
 40936  ** target system.  GetVersionEx was first deprecated in Win8.1.
 40937  */
 40938  #ifndef SQLITE_WIN32_GETVERSIONEX
 40939  #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
 40940  #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
 40941  #  else
 40942  #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
 40943  #  endif
 40944  #endif
 40945  
 40946  /*
 40947  ** Check to see if the CreateFileMappingA function is supported on the
 40948  ** target system.  It is unavailable when using "mincore.lib" on Win10.
 40949  ** When compiling for Windows 10, always assume "mincore.lib" is in use.
 40950  */
 40951  #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
 40952  #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
 40953  #    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
 40954  #  else
 40955  #    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
 40956  #  endif
 40957  #endif
 40958  
 40959  /*
 40960  ** This constant should already be defined (in the "WinDef.h" SDK file).
 40961  */
 40962  #ifndef MAX_PATH
 40963  #  define MAX_PATH                      (260)
 40964  #endif
 40965  
 40966  /*
 40967  ** Maximum pathname length (in chars) for Win32.  This should normally be
 40968  ** MAX_PATH.
 40969  */
 40970  #ifndef SQLITE_WIN32_MAX_PATH_CHARS
 40971  #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
 40972  #endif
 40973  
 40974  /*
 40975  ** This constant should already be defined (in the "WinNT.h" SDK file).
 40976  */
 40977  #ifndef UNICODE_STRING_MAX_CHARS
 40978  #  define UNICODE_STRING_MAX_CHARS      (32767)
 40979  #endif
 40980  
 40981  /*
 40982  ** Maximum pathname length (in chars) for WinNT.  This should normally be
 40983  ** UNICODE_STRING_MAX_CHARS.
 40984  */
 40985  #ifndef SQLITE_WINNT_MAX_PATH_CHARS
 40986  #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
 40987  #endif
 40988  
 40989  /*
 40990  ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
 40991  ** characters, so we allocate 4 bytes per character assuming worst-case of
 40992  ** 4-bytes-per-character for UTF8.
 40993  */
 40994  #ifndef SQLITE_WIN32_MAX_PATH_BYTES
 40995  #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
 40996  #endif
 40997  
 40998  /*
 40999  ** Maximum pathname length (in bytes) for WinNT.  This should normally be
 41000  ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
 41001  */
 41002  #ifndef SQLITE_WINNT_MAX_PATH_BYTES
 41003  #  define SQLITE_WINNT_MAX_PATH_BYTES   \
 41004                              (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
 41005  #endif
 41006  
 41007  /*
 41008  ** Maximum error message length (in chars) for WinRT.
 41009  */
 41010  #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
 41011  #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
 41012  #endif
 41013  
 41014  /*
 41015  ** Returns non-zero if the character should be treated as a directory
 41016  ** separator.
 41017  */
 41018  #ifndef winIsDirSep
 41019  #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
 41020  #endif
 41021  
 41022  /*
 41023  ** This macro is used when a local variable is set to a value that is
 41024  ** [sometimes] not used by the code (e.g. via conditional compilation).
 41025  */
 41026  #ifndef UNUSED_VARIABLE_VALUE
 41027  #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
 41028  #endif
 41029  
 41030  /*
 41031  ** Returns the character that should be used as the directory separator.
 41032  */
 41033  #ifndef winGetDirSep
 41034  #  define winGetDirSep()                '\\'
 41035  #endif
 41036  
 41037  /*
 41038  ** Do we need to manually define the Win32 file mapping APIs for use with WAL
 41039  ** mode or memory mapped files (e.g. these APIs are available in the Windows
 41040  ** CE SDK; however, they are not present in the header file)?
 41041  */
 41042  #if SQLITE_WIN32_FILEMAPPING_API && \
 41043          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 41044  /*
 41045  ** Two of the file mapping APIs are different under WinRT.  Figure out which
 41046  ** set we need.
 41047  */
 41048  #if SQLITE_OS_WINRT
 41049  WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
 41050          LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
 41051  
 41052  WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
 41053  #else
 41054  #if defined(SQLITE_WIN32_HAS_ANSI)
 41055  WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
 41056          DWORD, DWORD, DWORD, LPCSTR);
 41057  #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
 41058  
 41059  #if defined(SQLITE_WIN32_HAS_WIDE)
 41060  WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
 41061          DWORD, DWORD, DWORD, LPCWSTR);
 41062  #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
 41063  
 41064  WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
 41065  #endif /* SQLITE_OS_WINRT */
 41066  
 41067  /*
 41068  ** These file mapping APIs are common to both Win32 and WinRT.
 41069  */
 41070  
 41071  WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
 41072  WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
 41073  #endif /* SQLITE_WIN32_FILEMAPPING_API */
 41074  
 41075  /*
 41076  ** Some Microsoft compilers lack this definition.
 41077  */
 41078  #ifndef INVALID_FILE_ATTRIBUTES
 41079  # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
 41080  #endif
 41081  
 41082  #ifndef FILE_FLAG_MASK
 41083  # define FILE_FLAG_MASK          (0xFF3C0000)
 41084  #endif
 41085  
 41086  #ifndef FILE_ATTRIBUTE_MASK
 41087  # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
 41088  #endif
 41089  
 41090  #ifndef SQLITE_OMIT_WAL
 41091  /* Forward references to structures used for WAL */
 41092  typedef struct winShm winShm;           /* A connection to shared-memory */
 41093  typedef struct winShmNode winShmNode;   /* A region of shared-memory */
 41094  #endif
 41095  
 41096  /*
 41097  ** WinCE lacks native support for file locking so we have to fake it
 41098  ** with some code of our own.
 41099  */
 41100  #if SQLITE_OS_WINCE
 41101  typedef struct winceLock {
 41102    int nReaders;       /* Number of reader locks obtained */
 41103    BOOL bPending;      /* Indicates a pending lock has been obtained */
 41104    BOOL bReserved;     /* Indicates a reserved lock has been obtained */
 41105    BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
 41106  } winceLock;
 41107  #endif
 41108  
 41109  /*
 41110  ** The winFile structure is a subclass of sqlite3_file* specific to the win32
 41111  ** portability layer.
 41112  */
 41113  typedef struct winFile winFile;
 41114  struct winFile {
 41115    const sqlite3_io_methods *pMethod; /*** Must be first ***/
 41116    sqlite3_vfs *pVfs;      /* The VFS used to open this file */
 41117    HANDLE h;               /* Handle for accessing the file */
 41118    u8 locktype;            /* Type of lock currently held on this file */
 41119    short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
 41120    u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
 41121    DWORD lastErrno;        /* The Windows errno from the last I/O error */
 41122  #ifndef SQLITE_OMIT_WAL
 41123    winShm *pShm;           /* Instance of shared memory on this file */
 41124  #endif
 41125    const char *zPath;      /* Full pathname of this file */
 41126    int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
 41127  #if SQLITE_OS_WINCE
 41128    LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
 41129    HANDLE hMutex;          /* Mutex used to control access to shared lock */
 41130    HANDLE hShared;         /* Shared memory segment used for locking */
 41131    winceLock local;        /* Locks obtained by this instance of winFile */
 41132    winceLock *shared;      /* Global shared lock memory for the file  */
 41133  #endif
 41134  #if SQLITE_MAX_MMAP_SIZE>0
 41135    int nFetchOut;                /* Number of outstanding xFetch references */
 41136    HANDLE hMap;                  /* Handle for accessing memory mapping */
 41137    void *pMapRegion;             /* Area memory mapped */
 41138    sqlite3_int64 mmapSize;       /* Size of mapped region */
 41139    sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
 41140  #endif
 41141  };
 41142  
 41143  /*
 41144  ** The winVfsAppData structure is used for the pAppData member for all of the
 41145  ** Win32 VFS variants.
 41146  */
 41147  typedef struct winVfsAppData winVfsAppData;
 41148  struct winVfsAppData {
 41149    const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
 41150    void *pAppData;                    /* The extra pAppData, if any. */
 41151    BOOL bNoLock;                      /* Non-zero if locking is disabled. */
 41152  };
 41153  
 41154  /*
 41155  ** Allowed values for winFile.ctrlFlags
 41156  */
 41157  #define WINFILE_RDONLY          0x02   /* Connection is read only */
 41158  #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
 41159  #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 41160  
 41161  /*
 41162   * The size of the buffer used by sqlite3_win32_write_debug().
 41163   */
 41164  #ifndef SQLITE_WIN32_DBG_BUF_SIZE
 41165  #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
 41166  #endif
 41167  
 41168  /*
 41169   * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
 41170   * various Win32 API heap functions instead of our own.
 41171   */
 41172  #ifdef SQLITE_WIN32_MALLOC
 41173  
 41174  /*
 41175   * If this is non-zero, an isolated heap will be created by the native Win32
 41176   * allocator subsystem; otherwise, the default process heap will be used.  This
 41177   * setting has no effect when compiling for WinRT.  By default, this is enabled
 41178   * and an isolated heap will be created to store all allocated data.
 41179   *
 41180   ******************************************************************************
 41181   * WARNING: It is important to note that when this setting is non-zero and the
 41182   *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
 41183   *          function), all data that was allocated using the isolated heap will
 41184   *          be freed immediately and any attempt to access any of that freed
 41185   *          data will almost certainly result in an immediate access violation.
 41186   ******************************************************************************
 41187   */
 41188  #ifndef SQLITE_WIN32_HEAP_CREATE
 41189  #  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
 41190  #endif
 41191  
 41192  /*
 41193   * This is the maximum possible initial size of the Win32-specific heap, in
 41194   * bytes.
 41195   */
 41196  #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
 41197  #  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
 41198  #endif
 41199  
 41200  /*
 41201   * This is the extra space for the initial size of the Win32-specific heap,
 41202   * in bytes.  This value may be zero.
 41203   */
 41204  #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
 41205  #  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
 41206  #endif
 41207  
 41208  /*
 41209   * Calculate the maximum legal cache size, in pages, based on the maximum
 41210   * possible initial heap size and the default page size, setting aside the
 41211   * needed extra space.
 41212   */
 41213  #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
 41214  #  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
 41215                                            (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
 41216                                           (SQLITE_DEFAULT_PAGE_SIZE))
 41217  #endif
 41218  
 41219  /*
 41220   * This is cache size used in the calculation of the initial size of the
 41221   * Win32-specific heap.  It cannot be negative.
 41222   */
 41223  #ifndef SQLITE_WIN32_CACHE_SIZE
 41224  #  if SQLITE_DEFAULT_CACHE_SIZE>=0
 41225  #    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
 41226  #  else
 41227  #    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
 41228  #  endif
 41229  #endif
 41230  
 41231  /*
 41232   * Make sure that the calculated cache size, in pages, cannot cause the
 41233   * initial size of the Win32-specific heap to exceed the maximum amount
 41234   * of memory that can be specified in the call to HeapCreate.
 41235   */
 41236  #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
 41237  #  undef SQLITE_WIN32_CACHE_SIZE
 41238  #  define SQLITE_WIN32_CACHE_SIZE       (2000)
 41239  #endif
 41240  
 41241  /*
 41242   * The initial size of the Win32-specific heap.  This value may be zero.
 41243   */
 41244  #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
 41245  #  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
 41246                                           (SQLITE_DEFAULT_PAGE_SIZE) + \
 41247                                           (SQLITE_WIN32_HEAP_INIT_EXTRA))
 41248  #endif
 41249  
 41250  /*
 41251   * The maximum size of the Win32-specific heap.  This value may be zero.
 41252   */
 41253  #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
 41254  #  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
 41255  #endif
 41256  
 41257  /*
 41258   * The extra flags to use in calls to the Win32 heap APIs.  This value may be
 41259   * zero for the default behavior.
 41260   */
 41261  #ifndef SQLITE_WIN32_HEAP_FLAGS
 41262  #  define SQLITE_WIN32_HEAP_FLAGS       (0)
 41263  #endif
 41264  
 41265  
 41266  /*
 41267  ** The winMemData structure stores information required by the Win32-specific
 41268  ** sqlite3_mem_methods implementation.
 41269  */
 41270  typedef struct winMemData winMemData;
 41271  struct winMemData {
 41272  #ifndef NDEBUG
 41273    u32 magic1;   /* Magic number to detect structure corruption. */
 41274  #endif
 41275    HANDLE hHeap; /* The handle to our heap. */
 41276    BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
 41277  #ifndef NDEBUG
 41278    u32 magic2;   /* Magic number to detect structure corruption. */
 41279  #endif
 41280  };
 41281  
 41282  #ifndef NDEBUG
 41283  #define WINMEM_MAGIC1     0x42b2830b
 41284  #define WINMEM_MAGIC2     0xbd4d7cf4
 41285  #endif
 41286  
 41287  static struct winMemData win_mem_data = {
 41288  #ifndef NDEBUG
 41289    WINMEM_MAGIC1,
 41290  #endif
 41291    NULL, FALSE
 41292  #ifndef NDEBUG
 41293    ,WINMEM_MAGIC2
 41294  #endif
 41295  };
 41296  
 41297  #ifndef NDEBUG
 41298  #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
 41299  #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
 41300  #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
 41301  #else
 41302  #define winMemAssertMagic()
 41303  #endif
 41304  
 41305  #define winMemGetDataPtr()  &win_mem_data
 41306  #define winMemGetHeap()     win_mem_data.hHeap
 41307  #define winMemGetOwned()    win_mem_data.bOwned
 41308  
 41309  static void *winMemMalloc(int nBytes);
 41310  static void winMemFree(void *pPrior);
 41311  static void *winMemRealloc(void *pPrior, int nBytes);
 41312  static int winMemSize(void *p);
 41313  static int winMemRoundup(int n);
 41314  static int winMemInit(void *pAppData);
 41315  static void winMemShutdown(void *pAppData);
 41316  
 41317  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
 41318  #endif /* SQLITE_WIN32_MALLOC */
 41319  
 41320  /*
 41321  ** The following variable is (normally) set once and never changes
 41322  ** thereafter.  It records whether the operating system is Win9x
 41323  ** or WinNT.
 41324  **
 41325  ** 0:   Operating system unknown.
 41326  ** 1:   Operating system is Win9x.
 41327  ** 2:   Operating system is WinNT.
 41328  **
 41329  ** In order to facilitate testing on a WinNT system, the test fixture
 41330  ** can manually set this value to 1 to emulate Win98 behavior.
 41331  */
 41332  #ifdef SQLITE_TEST
 41333  SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
 41334  #else
 41335  static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
 41336  #endif
 41337  
 41338  #ifndef SYSCALL
 41339  #  define SYSCALL sqlite3_syscall_ptr
 41340  #endif
 41341  
 41342  /*
 41343  ** This function is not available on Windows CE or WinRT.
 41344   */
 41345  
 41346  #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
 41347  #  define osAreFileApisANSI()       1
 41348  #endif
 41349  
 41350  /*
 41351  ** Many system calls are accessed through pointer-to-functions so that
 41352  ** they may be overridden at runtime to facilitate fault injection during
 41353  ** testing and sandboxing.  The following array holds the names and pointers
 41354  ** to all overrideable system calls.
 41355  */
 41356  static struct win_syscall {
 41357    const char *zName;            /* Name of the system call */
 41358    sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
 41359    sqlite3_syscall_ptr pDefault; /* Default value */
 41360  } aSyscall[] = {
 41361  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 41362    { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
 41363  #else
 41364    { "AreFileApisANSI",         (SYSCALL)0,                       0 },
 41365  #endif
 41366  
 41367  #ifndef osAreFileApisANSI
 41368  #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
 41369  #endif
 41370  
 41371  #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 41372    { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
 41373  #else
 41374    { "CharLowerW",              (SYSCALL)0,                       0 },
 41375  #endif
 41376  
 41377  #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
 41378  
 41379  #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
 41380    { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
 41381  #else
 41382    { "CharUpperW",              (SYSCALL)0,                       0 },
 41383  #endif
 41384  
 41385  #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
 41386  
 41387    { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
 41388  
 41389  #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
 41390  
 41391  #if defined(SQLITE_WIN32_HAS_ANSI)
 41392    { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
 41393  #else
 41394    { "CreateFileA",             (SYSCALL)0,                       0 },
 41395  #endif
 41396  
 41397  #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
 41398          LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
 41399  
 41400  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41401    { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
 41402  #else
 41403    { "CreateFileW",             (SYSCALL)0,                       0 },
 41404  #endif
 41405  
 41406  #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
 41407          LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
 41408  
 41409  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
 41410          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
 41411          SQLITE_WIN32_CREATEFILEMAPPINGA
 41412    { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
 41413  #else
 41414    { "CreateFileMappingA",      (SYSCALL)0,                       0 },
 41415  #endif
 41416  
 41417  #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 41418          DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
 41419  
 41420  #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 41421          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
 41422    { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
 41423  #else
 41424    { "CreateFileMappingW",      (SYSCALL)0,                       0 },
 41425  #endif
 41426  
 41427  #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
 41428          DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
 41429  
 41430  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41431    { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
 41432  #else
 41433    { "CreateMutexW",            (SYSCALL)0,                       0 },
 41434  #endif
 41435  
 41436  #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
 41437          LPCWSTR))aSyscall[8].pCurrent)
 41438  
 41439  #if defined(SQLITE_WIN32_HAS_ANSI)
 41440    { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
 41441  #else
 41442    { "DeleteFileA",             (SYSCALL)0,                       0 },
 41443  #endif
 41444  
 41445  #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
 41446  
 41447  #if defined(SQLITE_WIN32_HAS_WIDE)
 41448    { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
 41449  #else
 41450    { "DeleteFileW",             (SYSCALL)0,                       0 },
 41451  #endif
 41452  
 41453  #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
 41454  
 41455  #if SQLITE_OS_WINCE
 41456    { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
 41457  #else
 41458    { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
 41459  #endif
 41460  
 41461  #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 41462          LPFILETIME))aSyscall[11].pCurrent)
 41463  
 41464  #if SQLITE_OS_WINCE
 41465    { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
 41466  #else
 41467    { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
 41468  #endif
 41469  
 41470  #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
 41471          LPSYSTEMTIME))aSyscall[12].pCurrent)
 41472  
 41473    { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
 41474  
 41475  #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
 41476  
 41477  #if defined(SQLITE_WIN32_HAS_ANSI)
 41478    { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
 41479  #else
 41480    { "FormatMessageA",          (SYSCALL)0,                       0 },
 41481  #endif
 41482  
 41483  #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
 41484          DWORD,va_list*))aSyscall[14].pCurrent)
 41485  
 41486  #if defined(SQLITE_WIN32_HAS_WIDE)
 41487    { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
 41488  #else
 41489    { "FormatMessageW",          (SYSCALL)0,                       0 },
 41490  #endif
 41491  
 41492  #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
 41493          DWORD,va_list*))aSyscall[15].pCurrent)
 41494  
 41495  #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 41496    { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
 41497  #else
 41498    { "FreeLibrary",             (SYSCALL)0,                       0 },
 41499  #endif
 41500  
 41501  #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
 41502  
 41503    { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
 41504  
 41505  #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
 41506  
 41507  #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 41508    { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
 41509  #else
 41510    { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
 41511  #endif
 41512  
 41513  #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
 41514          LPDWORD))aSyscall[18].pCurrent)
 41515  
 41516  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41517    { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
 41518  #else
 41519    { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
 41520  #endif
 41521  
 41522  #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
 41523          LPDWORD))aSyscall[19].pCurrent)
 41524  
 41525  #if defined(SQLITE_WIN32_HAS_ANSI)
 41526    { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
 41527  #else
 41528    { "GetFileAttributesA",      (SYSCALL)0,                       0 },
 41529  #endif
 41530  
 41531  #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
 41532  
 41533  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41534    { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
 41535  #else
 41536    { "GetFileAttributesW",      (SYSCALL)0,                       0 },
 41537  #endif
 41538  
 41539  #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
 41540  
 41541  #if defined(SQLITE_WIN32_HAS_WIDE)
 41542    { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
 41543  #else
 41544    { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
 41545  #endif
 41546  
 41547  #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
 41548          LPVOID))aSyscall[22].pCurrent)
 41549  
 41550  #if !SQLITE_OS_WINRT
 41551    { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
 41552  #else
 41553    { "GetFileSize",             (SYSCALL)0,                       0 },
 41554  #endif
 41555  
 41556  #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
 41557  
 41558  #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
 41559    { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
 41560  #else
 41561    { "GetFullPathNameA",        (SYSCALL)0,                       0 },
 41562  #endif
 41563  
 41564  #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
 41565          LPSTR*))aSyscall[24].pCurrent)
 41566  
 41567  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41568    { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
 41569  #else
 41570    { "GetFullPathNameW",        (SYSCALL)0,                       0 },
 41571  #endif
 41572  
 41573  #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
 41574          LPWSTR*))aSyscall[25].pCurrent)
 41575  
 41576    { "GetLastError",            (SYSCALL)GetLastError,            0 },
 41577  
 41578  #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
 41579  
 41580  #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
 41581  #if SQLITE_OS_WINCE
 41582    /* The GetProcAddressA() routine is only available on Windows CE. */
 41583    { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
 41584  #else
 41585    /* All other Windows platforms expect GetProcAddress() to take
 41586    ** an ANSI string regardless of the _UNICODE setting */
 41587    { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
 41588  #endif
 41589  #else
 41590    { "GetProcAddressA",         (SYSCALL)0,                       0 },
 41591  #endif
 41592  
 41593  #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
 41594          LPCSTR))aSyscall[27].pCurrent)
 41595  
 41596  #if !SQLITE_OS_WINRT
 41597    { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
 41598  #else
 41599    { "GetSystemInfo",           (SYSCALL)0,                       0 },
 41600  #endif
 41601  
 41602  #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
 41603  
 41604    { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
 41605  
 41606  #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
 41607  
 41608  #if !SQLITE_OS_WINCE
 41609    { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
 41610  #else
 41611    { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
 41612  #endif
 41613  
 41614  #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
 41615          LPFILETIME))aSyscall[30].pCurrent)
 41616  
 41617  #if defined(SQLITE_WIN32_HAS_ANSI)
 41618    { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
 41619  #else
 41620    { "GetTempPathA",            (SYSCALL)0,                       0 },
 41621  #endif
 41622  
 41623  #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
 41624  
 41625  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
 41626    { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
 41627  #else
 41628    { "GetTempPathW",            (SYSCALL)0,                       0 },
 41629  #endif
 41630  
 41631  #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
 41632  
 41633  #if !SQLITE_OS_WINRT
 41634    { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
 41635  #else
 41636    { "GetTickCount",            (SYSCALL)0,                       0 },
 41637  #endif
 41638  
 41639  #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
 41640  
 41641  #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
 41642    { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
 41643  #else
 41644    { "GetVersionExA",           (SYSCALL)0,                       0 },
 41645  #endif
 41646  
 41647  #define osGetVersionExA ((BOOL(WINAPI*)( \
 41648          LPOSVERSIONINFOA))aSyscall[34].pCurrent)
 41649  
 41650  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 41651          SQLITE_WIN32_GETVERSIONEX
 41652    { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
 41653  #else
 41654    { "GetVersionExW",           (SYSCALL)0,                       0 },
 41655  #endif
 41656  
 41657  #define osGetVersionExW ((BOOL(WINAPI*)( \
 41658          LPOSVERSIONINFOW))aSyscall[35].pCurrent)
 41659  
 41660    { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
 41661  
 41662  #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
 41663          SIZE_T))aSyscall[36].pCurrent)
 41664  
 41665  #if !SQLITE_OS_WINRT
 41666    { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
 41667  #else
 41668    { "HeapCreate",              (SYSCALL)0,                       0 },
 41669  #endif
 41670  
 41671  #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
 41672          SIZE_T))aSyscall[37].pCurrent)
 41673  
 41674  #if !SQLITE_OS_WINRT
 41675    { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
 41676  #else
 41677    { "HeapDestroy",             (SYSCALL)0,                       0 },
 41678  #endif
 41679  
 41680  #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
 41681  
 41682    { "HeapFree",                (SYSCALL)HeapFree,                0 },
 41683  
 41684  #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
 41685  
 41686    { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
 41687  
 41688  #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
 41689          SIZE_T))aSyscall[40].pCurrent)
 41690  
 41691    { "HeapSize",                (SYSCALL)HeapSize,                0 },
 41692  
 41693  #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
 41694          LPCVOID))aSyscall[41].pCurrent)
 41695  
 41696  #if !SQLITE_OS_WINRT
 41697    { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
 41698  #else
 41699    { "HeapValidate",            (SYSCALL)0,                       0 },
 41700  #endif
 41701  
 41702  #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
 41703          LPCVOID))aSyscall[42].pCurrent)
 41704  
 41705  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 41706    { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
 41707  #else
 41708    { "HeapCompact",             (SYSCALL)0,                       0 },
 41709  #endif
 41710  
 41711  #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
 41712  
 41713  #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 41714    { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
 41715  #else
 41716    { "LoadLibraryA",            (SYSCALL)0,                       0 },
 41717  #endif
 41718  
 41719  #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
 41720  
 41721  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 41722          !defined(SQLITE_OMIT_LOAD_EXTENSION)
 41723    { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
 41724  #else
 41725    { "LoadLibraryW",            (SYSCALL)0,                       0 },
 41726  #endif
 41727  
 41728  #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
 41729  
 41730  #if !SQLITE_OS_WINRT
 41731    { "LocalFree",               (SYSCALL)LocalFree,               0 },
 41732  #else
 41733    { "LocalFree",               (SYSCALL)0,                       0 },
 41734  #endif
 41735  
 41736  #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
 41737  
 41738  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 41739    { "LockFile",                (SYSCALL)LockFile,                0 },
 41740  #else
 41741    { "LockFile",                (SYSCALL)0,                       0 },
 41742  #endif
 41743  
 41744  #ifndef osLockFile
 41745  #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 41746          DWORD))aSyscall[47].pCurrent)
 41747  #endif
 41748  
 41749  #if !SQLITE_OS_WINCE
 41750    { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
 41751  #else
 41752    { "LockFileEx",              (SYSCALL)0,                       0 },
 41753  #endif
 41754  
 41755  #ifndef osLockFileEx
 41756  #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
 41757          LPOVERLAPPED))aSyscall[48].pCurrent)
 41758  #endif
 41759  
 41760  #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
 41761          (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
 41762    { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
 41763  #else
 41764    { "MapViewOfFile",           (SYSCALL)0,                       0 },
 41765  #endif
 41766  
 41767  #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 41768          SIZE_T))aSyscall[49].pCurrent)
 41769  
 41770    { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
 41771  
 41772  #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
 41773          int))aSyscall[50].pCurrent)
 41774  
 41775    { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
 41776  
 41777  #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
 41778          LARGE_INTEGER*))aSyscall[51].pCurrent)
 41779  
 41780    { "ReadFile",                (SYSCALL)ReadFile,                0 },
 41781  
 41782  #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
 41783          LPOVERLAPPED))aSyscall[52].pCurrent)
 41784  
 41785    { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
 41786  
 41787  #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
 41788  
 41789  #if !SQLITE_OS_WINRT
 41790    { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
 41791  #else
 41792    { "SetFilePointer",          (SYSCALL)0,                       0 },
 41793  #endif
 41794  
 41795  #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
 41796          DWORD))aSyscall[54].pCurrent)
 41797  
 41798  #if !SQLITE_OS_WINRT
 41799    { "Sleep",                   (SYSCALL)Sleep,                   0 },
 41800  #else
 41801    { "Sleep",                   (SYSCALL)0,                       0 },
 41802  #endif
 41803  
 41804  #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
 41805  
 41806    { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
 41807  
 41808  #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
 41809          LPFILETIME))aSyscall[56].pCurrent)
 41810  
 41811  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 41812    { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
 41813  #else
 41814    { "UnlockFile",              (SYSCALL)0,                       0 },
 41815  #endif
 41816  
 41817  #ifndef osUnlockFile
 41818  #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 41819          DWORD))aSyscall[57].pCurrent)
 41820  #endif
 41821  
 41822  #if !SQLITE_OS_WINCE
 41823    { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
 41824  #else
 41825    { "UnlockFileEx",            (SYSCALL)0,                       0 },
 41826  #endif
 41827  
 41828  #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 41829          LPOVERLAPPED))aSyscall[58].pCurrent)
 41830  
 41831  #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
 41832    { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
 41833  #else
 41834    { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
 41835  #endif
 41836  
 41837  #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
 41838  
 41839    { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
 41840  
 41841  #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
 41842          LPCSTR,LPBOOL))aSyscall[60].pCurrent)
 41843  
 41844    { "WriteFile",               (SYSCALL)WriteFile,               0 },
 41845  
 41846  #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
 41847          LPOVERLAPPED))aSyscall[61].pCurrent)
 41848  
 41849  #if SQLITE_OS_WINRT
 41850    { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
 41851  #else
 41852    { "CreateEventExW",          (SYSCALL)0,                       0 },
 41853  #endif
 41854  
 41855  #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
 41856          DWORD,DWORD))aSyscall[62].pCurrent)
 41857  
 41858  #if !SQLITE_OS_WINRT
 41859    { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
 41860  #else
 41861    { "WaitForSingleObject",     (SYSCALL)0,                       0 },
 41862  #endif
 41863  
 41864  #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
 41865          DWORD))aSyscall[63].pCurrent)
 41866  
 41867  #if !SQLITE_OS_WINCE
 41868    { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
 41869  #else
 41870    { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
 41871  #endif
 41872  
 41873  #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
 41874          BOOL))aSyscall[64].pCurrent)
 41875  
 41876  #if SQLITE_OS_WINRT
 41877    { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
 41878  #else
 41879    { "SetFilePointerEx",        (SYSCALL)0,                       0 },
 41880  #endif
 41881  
 41882  #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
 41883          PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
 41884  
 41885  #if SQLITE_OS_WINRT
 41886    { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
 41887  #else
 41888    { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
 41889  #endif
 41890  
 41891  #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
 41892          FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
 41893  
 41894  #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 41895    { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
 41896  #else
 41897    { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
 41898  #endif
 41899  
 41900  #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
 41901          SIZE_T))aSyscall[67].pCurrent)
 41902  
 41903  #if SQLITE_OS_WINRT
 41904    { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
 41905  #else
 41906    { "CreateFile2",             (SYSCALL)0,                       0 },
 41907  #endif
 41908  
 41909  #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
 41910          LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
 41911  
 41912  #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 41913    { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
 41914  #else
 41915    { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
 41916  #endif
 41917  
 41918  #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
 41919          DWORD))aSyscall[69].pCurrent)
 41920  
 41921  #if SQLITE_OS_WINRT
 41922    { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
 41923  #else
 41924    { "GetTickCount64",          (SYSCALL)0,                       0 },
 41925  #endif
 41926  
 41927  #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
 41928  
 41929  #if SQLITE_OS_WINRT
 41930    { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
 41931  #else
 41932    { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
 41933  #endif
 41934  
 41935  #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
 41936          LPSYSTEM_INFO))aSyscall[71].pCurrent)
 41937  
 41938  #if defined(SQLITE_WIN32_HAS_ANSI)
 41939    { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
 41940  #else
 41941    { "OutputDebugStringA",      (SYSCALL)0,                       0 },
 41942  #endif
 41943  
 41944  #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
 41945  
 41946  #if defined(SQLITE_WIN32_HAS_WIDE)
 41947    { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
 41948  #else
 41949    { "OutputDebugStringW",      (SYSCALL)0,                       0 },
 41950  #endif
 41951  
 41952  #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
 41953  
 41954    { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
 41955  
 41956  #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
 41957  
 41958  #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
 41959    { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
 41960  #else
 41961    { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
 41962  #endif
 41963  
 41964  #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
 41965          LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
 41966  
 41967  /*
 41968  ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
 41969  **       is really just a macro that uses a compiler intrinsic (e.g. x64).
 41970  **       So do not try to make this is into a redefinable interface.
 41971  */
 41972  #if defined(InterlockedCompareExchange)
 41973    { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
 41974  
 41975  #define osInterlockedCompareExchange InterlockedCompareExchange
 41976  #else
 41977    { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
 41978  
 41979  #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
 41980          SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
 41981  #endif /* defined(InterlockedCompareExchange) */
 41982  
 41983  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 41984    { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
 41985  #else
 41986    { "UuidCreate",               (SYSCALL)0,                      0 },
 41987  #endif
 41988  
 41989  #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
 41990  
 41991  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 41992    { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
 41993  #else
 41994    { "UuidCreateSequential",     (SYSCALL)0,                      0 },
 41995  #endif
 41996  
 41997  #define osUuidCreateSequential \
 41998          ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
 41999  
 42000  #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
 42001    { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
 42002  #else
 42003    { "FlushViewOfFile",          (SYSCALL)0,                      0 },
 42004  #endif
 42005  
 42006  #define osFlushViewOfFile \
 42007          ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
 42008  
 42009  }; /* End of the overrideable system calls */
 42010  
 42011  /*
 42012  ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 42013  ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
 42014  ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
 42015  ** system call named zName.
 42016  */
 42017  static int winSetSystemCall(
 42018    sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
 42019    const char *zName,            /* Name of system call to override */
 42020    sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
 42021  ){
 42022    unsigned int i;
 42023    int rc = SQLITE_NOTFOUND;
 42024  
 42025    UNUSED_PARAMETER(pNotUsed);
 42026    if( zName==0 ){
 42027      /* If no zName is given, restore all system calls to their default
 42028      ** settings and return NULL
 42029      */
 42030      rc = SQLITE_OK;
 42031      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 42032        if( aSyscall[i].pDefault ){
 42033          aSyscall[i].pCurrent = aSyscall[i].pDefault;
 42034        }
 42035      }
 42036    }else{
 42037      /* If zName is specified, operate on only the one system call
 42038      ** specified.
 42039      */
 42040      for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 42041        if( strcmp(zName, aSyscall[i].zName)==0 ){
 42042          if( aSyscall[i].pDefault==0 ){
 42043            aSyscall[i].pDefault = aSyscall[i].pCurrent;
 42044          }
 42045          rc = SQLITE_OK;
 42046          if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
 42047          aSyscall[i].pCurrent = pNewFunc;
 42048          break;
 42049        }
 42050      }
 42051    }
 42052    return rc;
 42053  }
 42054  
 42055  /*
 42056  ** Return the value of a system call.  Return NULL if zName is not a
 42057  ** recognized system call name.  NULL is also returned if the system call
 42058  ** is currently undefined.
 42059  */
 42060  static sqlite3_syscall_ptr winGetSystemCall(
 42061    sqlite3_vfs *pNotUsed,
 42062    const char *zName
 42063  ){
 42064    unsigned int i;
 42065  
 42066    UNUSED_PARAMETER(pNotUsed);
 42067    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
 42068      if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
 42069    }
 42070    return 0;
 42071  }
 42072  
 42073  /*
 42074  ** Return the name of the first system call after zName.  If zName==NULL
 42075  ** then return the name of the first system call.  Return NULL if zName
 42076  ** is the last system call or if zName is not the name of a valid
 42077  ** system call.
 42078  */
 42079  static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
 42080    int i = -1;
 42081  
 42082    UNUSED_PARAMETER(p);
 42083    if( zName ){
 42084      for(i=0; i<ArraySize(aSyscall)-1; i++){
 42085        if( strcmp(zName, aSyscall[i].zName)==0 ) break;
 42086      }
 42087    }
 42088    for(i++; i<ArraySize(aSyscall); i++){
 42089      if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
 42090    }
 42091    return 0;
 42092  }
 42093  
 42094  #ifdef SQLITE_WIN32_MALLOC
 42095  /*
 42096  ** If a Win32 native heap has been configured, this function will attempt to
 42097  ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
 42098  ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
 42099  ** "pnLargest" argument, if non-zero, will be used to return the size of the
 42100  ** largest committed free block in the heap, in bytes.
 42101  */
 42102  SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
 42103    int rc = SQLITE_OK;
 42104    UINT nLargest = 0;
 42105    HANDLE hHeap;
 42106  
 42107    winMemAssertMagic();
 42108    hHeap = winMemGetHeap();
 42109    assert( hHeap!=0 );
 42110    assert( hHeap!=INVALID_HANDLE_VALUE );
 42111  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42112    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 42113  #endif
 42114  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 42115    if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
 42116      DWORD lastErrno = osGetLastError();
 42117      if( lastErrno==NO_ERROR ){
 42118        sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
 42119                    (void*)hHeap);
 42120        rc = SQLITE_NOMEM_BKPT;
 42121      }else{
 42122        sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
 42123                    osGetLastError(), (void*)hHeap);
 42124        rc = SQLITE_ERROR;
 42125      }
 42126    }
 42127  #else
 42128    sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
 42129                (void*)hHeap);
 42130    rc = SQLITE_NOTFOUND;
 42131  #endif
 42132    if( pnLargest ) *pnLargest = nLargest;
 42133    return rc;
 42134  }
 42135  
 42136  /*
 42137  ** If a Win32 native heap has been configured, this function will attempt to
 42138  ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
 42139  ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
 42140  ** be returned and no changes will be made to the Win32 native heap.
 42141  */
 42142  SQLITE_API int sqlite3_win32_reset_heap(){
 42143    int rc;
 42144    MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
 42145    MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
 42146    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 42147    MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
 42148    sqlite3_mutex_enter(pMaster);
 42149    sqlite3_mutex_enter(pMem);
 42150    winMemAssertMagic();
 42151    if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
 42152      /*
 42153      ** At this point, there should be no outstanding memory allocations on
 42154      ** the heap.  Also, since both the master and memsys locks are currently
 42155      ** being held by us, no other function (i.e. from another thread) should
 42156      ** be able to even access the heap.  Attempt to destroy and recreate our
 42157      ** isolated Win32 native heap now.
 42158      */
 42159      assert( winMemGetHeap()!=NULL );
 42160      assert( winMemGetOwned() );
 42161      assert( sqlite3_memory_used()==0 );
 42162      winMemShutdown(winMemGetDataPtr());
 42163      assert( winMemGetHeap()==NULL );
 42164      assert( !winMemGetOwned() );
 42165      assert( sqlite3_memory_used()==0 );
 42166      rc = winMemInit(winMemGetDataPtr());
 42167      assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
 42168      assert( rc!=SQLITE_OK || winMemGetOwned() );
 42169      assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
 42170    }else{
 42171      /*
 42172      ** The Win32 native heap cannot be modified because it may be in use.
 42173      */
 42174      rc = SQLITE_BUSY;
 42175    }
 42176    sqlite3_mutex_leave(pMem);
 42177    sqlite3_mutex_leave(pMaster);
 42178    return rc;
 42179  }
 42180  #endif /* SQLITE_WIN32_MALLOC */
 42181  
 42182  /*
 42183  ** This function outputs the specified (ANSI) string to the Win32 debugger
 42184  ** (if available).
 42185  */
 42186  
 42187  SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
 42188    char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
 42189    int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
 42190    if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
 42191    assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
 42192  #ifdef SQLITE_ENABLE_API_ARMOR
 42193    if( !zBuf ){
 42194      (void)SQLITE_MISUSE_BKPT;
 42195      return;
 42196    }
 42197  #endif
 42198  #if defined(SQLITE_WIN32_HAS_ANSI)
 42199    if( nMin>0 ){
 42200      memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 42201      memcpy(zDbgBuf, zBuf, nMin);
 42202      osOutputDebugStringA(zDbgBuf);
 42203    }else{
 42204      osOutputDebugStringA(zBuf);
 42205    }
 42206  #elif defined(SQLITE_WIN32_HAS_WIDE)
 42207    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 42208    if ( osMultiByteToWideChar(
 42209            osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
 42210            nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
 42211      return;
 42212    }
 42213    osOutputDebugStringW((LPCWSTR)zDbgBuf);
 42214  #else
 42215    if( nMin>0 ){
 42216      memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
 42217      memcpy(zDbgBuf, zBuf, nMin);
 42218      fprintf(stderr, "%s", zDbgBuf);
 42219    }else{
 42220      fprintf(stderr, "%s", zBuf);
 42221    }
 42222  #endif
 42223  }
 42224  
 42225  /*
 42226  ** The following routine suspends the current thread for at least ms
 42227  ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
 42228  */
 42229  #if SQLITE_OS_WINRT
 42230  static HANDLE sleepObj = NULL;
 42231  #endif
 42232  
 42233  SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
 42234  #if SQLITE_OS_WINRT
 42235    if ( sleepObj==NULL ){
 42236      sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
 42237                                  SYNCHRONIZE);
 42238    }
 42239    assert( sleepObj!=NULL );
 42240    osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
 42241  #else
 42242    osSleep(milliseconds);
 42243  #endif
 42244  }
 42245  
 42246  #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
 42247          SQLITE_THREADSAFE>0
 42248  SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
 42249    DWORD rc;
 42250    while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
 42251                                         TRUE))==WAIT_IO_COMPLETION ){}
 42252    return rc;
 42253  }
 42254  #endif
 42255  
 42256  /*
 42257  ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
 42258  ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
 42259  **
 42260  ** Here is an interesting observation:  Win95, Win98, and WinME lack
 42261  ** the LockFileEx() API.  But we can still statically link against that
 42262  ** API as long as we don't call it when running Win95/98/ME.  A call to
 42263  ** this routine is used to determine if the host is Win95/98/ME or
 42264  ** WinNT/2K/XP so that we will know whether or not we can safely call
 42265  ** the LockFileEx() API.
 42266  */
 42267  
 42268  #if !SQLITE_WIN32_GETVERSIONEX
 42269  # define osIsNT()  (1)
 42270  #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
 42271  # define osIsNT()  (1)
 42272  #elif !defined(SQLITE_WIN32_HAS_WIDE)
 42273  # define osIsNT()  (0)
 42274  #else
 42275  # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
 42276  #endif
 42277  
 42278  /*
 42279  ** This function determines if the machine is running a version of Windows
 42280  ** based on the NT kernel.
 42281  */
 42282  SQLITE_API int sqlite3_win32_is_nt(void){
 42283  #if SQLITE_OS_WINRT
 42284    /*
 42285    ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
 42286    **       kernel.
 42287    */
 42288    return 1;
 42289  #elif SQLITE_WIN32_GETVERSIONEX
 42290    if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
 42291  #if defined(SQLITE_WIN32_HAS_ANSI)
 42292      OSVERSIONINFOA sInfo;
 42293      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 42294      osGetVersionExA(&sInfo);
 42295      osInterlockedCompareExchange(&sqlite3_os_type,
 42296          (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
 42297  #elif defined(SQLITE_WIN32_HAS_WIDE)
 42298      OSVERSIONINFOW sInfo;
 42299      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 42300      osGetVersionExW(&sInfo);
 42301      osInterlockedCompareExchange(&sqlite3_os_type,
 42302          (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
 42303  #endif
 42304    }
 42305    return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
 42306  #elif SQLITE_TEST
 42307    return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
 42308  #else
 42309    /*
 42310    ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
 42311    **       deprecated are always assumed to be based on the NT kernel.
 42312    */
 42313    return 1;
 42314  #endif
 42315  }
 42316  
 42317  #ifdef SQLITE_WIN32_MALLOC
 42318  /*
 42319  ** Allocate nBytes of memory.
 42320  */
 42321  static void *winMemMalloc(int nBytes){
 42322    HANDLE hHeap;
 42323    void *p;
 42324  
 42325    winMemAssertMagic();
 42326    hHeap = winMemGetHeap();
 42327    assert( hHeap!=0 );
 42328    assert( hHeap!=INVALID_HANDLE_VALUE );
 42329  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42330    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 42331  #endif
 42332    assert( nBytes>=0 );
 42333    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 42334    if( !p ){
 42335      sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
 42336                  nBytes, osGetLastError(), (void*)hHeap);
 42337    }
 42338    return p;
 42339  }
 42340  
 42341  /*
 42342  ** Free memory.
 42343  */
 42344  static void winMemFree(void *pPrior){
 42345    HANDLE hHeap;
 42346  
 42347    winMemAssertMagic();
 42348    hHeap = winMemGetHeap();
 42349    assert( hHeap!=0 );
 42350    assert( hHeap!=INVALID_HANDLE_VALUE );
 42351  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42352    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 42353  #endif
 42354    if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
 42355    if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
 42356      sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
 42357                  pPrior, osGetLastError(), (void*)hHeap);
 42358    }
 42359  }
 42360  
 42361  /*
 42362  ** Change the size of an existing memory allocation
 42363  */
 42364  static void *winMemRealloc(void *pPrior, int nBytes){
 42365    HANDLE hHeap;
 42366    void *p;
 42367  
 42368    winMemAssertMagic();
 42369    hHeap = winMemGetHeap();
 42370    assert( hHeap!=0 );
 42371    assert( hHeap!=INVALID_HANDLE_VALUE );
 42372  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42373    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
 42374  #endif
 42375    assert( nBytes>=0 );
 42376    if( !pPrior ){
 42377      p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
 42378    }else{
 42379      p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
 42380    }
 42381    if( !p ){
 42382      sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
 42383                  pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
 42384                  (void*)hHeap);
 42385    }
 42386    return p;
 42387  }
 42388  
 42389  /*
 42390  ** Return the size of an outstanding allocation, in bytes.
 42391  */
 42392  static int winMemSize(void *p){
 42393    HANDLE hHeap;
 42394    SIZE_T n;
 42395  
 42396    winMemAssertMagic();
 42397    hHeap = winMemGetHeap();
 42398    assert( hHeap!=0 );
 42399    assert( hHeap!=INVALID_HANDLE_VALUE );
 42400  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42401    assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
 42402  #endif
 42403    if( !p ) return 0;
 42404    n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
 42405    if( n==(SIZE_T)-1 ){
 42406      sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
 42407                  p, osGetLastError(), (void*)hHeap);
 42408      return 0;
 42409    }
 42410    return (int)n;
 42411  }
 42412  
 42413  /*
 42414  ** Round up a request size to the next valid allocation size.
 42415  */
 42416  static int winMemRoundup(int n){
 42417    return n;
 42418  }
 42419  
 42420  /*
 42421  ** Initialize this module.
 42422  */
 42423  static int winMemInit(void *pAppData){
 42424    winMemData *pWinMemData = (winMemData *)pAppData;
 42425  
 42426    if( !pWinMemData ) return SQLITE_ERROR;
 42427    assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 42428    assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 42429  
 42430  #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
 42431    if( !pWinMemData->hHeap ){
 42432      DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
 42433      DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
 42434      if( dwMaximumSize==0 ){
 42435        dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
 42436      }else if( dwInitialSize>dwMaximumSize ){
 42437        dwInitialSize = dwMaximumSize;
 42438      }
 42439      pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
 42440                                        dwInitialSize, dwMaximumSize);
 42441      if( !pWinMemData->hHeap ){
 42442        sqlite3_log(SQLITE_NOMEM,
 42443            "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
 42444            osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
 42445            dwMaximumSize);
 42446        return SQLITE_NOMEM_BKPT;
 42447      }
 42448      pWinMemData->bOwned = TRUE;
 42449      assert( pWinMemData->bOwned );
 42450    }
 42451  #else
 42452    pWinMemData->hHeap = osGetProcessHeap();
 42453    if( !pWinMemData->hHeap ){
 42454      sqlite3_log(SQLITE_NOMEM,
 42455          "failed to GetProcessHeap (%lu)", osGetLastError());
 42456      return SQLITE_NOMEM_BKPT;
 42457    }
 42458    pWinMemData->bOwned = FALSE;
 42459    assert( !pWinMemData->bOwned );
 42460  #endif
 42461    assert( pWinMemData->hHeap!=0 );
 42462    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 42463  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42464    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 42465  #endif
 42466    return SQLITE_OK;
 42467  }
 42468  
 42469  /*
 42470  ** Deinitialize this module.
 42471  */
 42472  static void winMemShutdown(void *pAppData){
 42473    winMemData *pWinMemData = (winMemData *)pAppData;
 42474  
 42475    if( !pWinMemData ) return;
 42476    assert( pWinMemData->magic1==WINMEM_MAGIC1 );
 42477    assert( pWinMemData->magic2==WINMEM_MAGIC2 );
 42478  
 42479    if( pWinMemData->hHeap ){
 42480      assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
 42481  #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
 42482      assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
 42483  #endif
 42484      if( pWinMemData->bOwned ){
 42485        if( !osHeapDestroy(pWinMemData->hHeap) ){
 42486          sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
 42487                      osGetLastError(), (void*)pWinMemData->hHeap);
 42488        }
 42489        pWinMemData->bOwned = FALSE;
 42490      }
 42491      pWinMemData->hHeap = NULL;
 42492    }
 42493  }
 42494  
 42495  /*
 42496  ** Populate the low-level memory allocation function pointers in
 42497  ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
 42498  ** arguments specify the block of memory to manage.
 42499  **
 42500  ** This routine is only called by sqlite3_config(), and therefore
 42501  ** is not required to be threadsafe (it is not).
 42502  */
 42503  SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
 42504    static const sqlite3_mem_methods winMemMethods = {
 42505      winMemMalloc,
 42506      winMemFree,
 42507      winMemRealloc,
 42508      winMemSize,
 42509      winMemRoundup,
 42510      winMemInit,
 42511      winMemShutdown,
 42512      &win_mem_data
 42513    };
 42514    return &winMemMethods;
 42515  }
 42516  
 42517  SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 42518    sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
 42519  }
 42520  #endif /* SQLITE_WIN32_MALLOC */
 42521  
 42522  /*
 42523  ** Convert a UTF-8 string to Microsoft Unicode.
 42524  **
 42525  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42526  */
 42527  static LPWSTR winUtf8ToUnicode(const char *zText){
 42528    int nChar;
 42529    LPWSTR zWideText;
 42530  
 42531    nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
 42532    if( nChar==0 ){
 42533      return 0;
 42534    }
 42535    zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
 42536    if( zWideText==0 ){
 42537      return 0;
 42538    }
 42539    nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
 42540                                  nChar);
 42541    if( nChar==0 ){
 42542      sqlite3_free(zWideText);
 42543      zWideText = 0;
 42544    }
 42545    return zWideText;
 42546  }
 42547  
 42548  /*
 42549  ** Convert a Microsoft Unicode string to UTF-8.
 42550  **
 42551  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42552  */
 42553  static char *winUnicodeToUtf8(LPCWSTR zWideText){
 42554    int nByte;
 42555    char *zText;
 42556  
 42557    nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
 42558    if( nByte == 0 ){
 42559      return 0;
 42560    }
 42561    zText = sqlite3MallocZero( nByte );
 42562    if( zText==0 ){
 42563      return 0;
 42564    }
 42565    nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
 42566                                  0, 0);
 42567    if( nByte == 0 ){
 42568      sqlite3_free(zText);
 42569      zText = 0;
 42570    }
 42571    return zText;
 42572  }
 42573  
 42574  /*
 42575  ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
 42576  ** code page.
 42577  **
 42578  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42579  */
 42580  static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
 42581    int nByte;
 42582    LPWSTR zMbcsText;
 42583    int codepage = useAnsi ? CP_ACP : CP_OEMCP;
 42584  
 42585    nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
 42586                                  0)*sizeof(WCHAR);
 42587    if( nByte==0 ){
 42588      return 0;
 42589    }
 42590    zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
 42591    if( zMbcsText==0 ){
 42592      return 0;
 42593    }
 42594    nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
 42595                                  nByte);
 42596    if( nByte==0 ){
 42597      sqlite3_free(zMbcsText);
 42598      zMbcsText = 0;
 42599    }
 42600    return zMbcsText;
 42601  }
 42602  
 42603  /*
 42604  ** Convert a Microsoft Unicode string to a multi-byte character string,
 42605  ** using the ANSI or OEM code page.
 42606  **
 42607  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42608  */
 42609  static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
 42610    int nByte;
 42611    char *zText;
 42612    int codepage = useAnsi ? CP_ACP : CP_OEMCP;
 42613  
 42614    nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
 42615    if( nByte == 0 ){
 42616      return 0;
 42617    }
 42618    zText = sqlite3MallocZero( nByte );
 42619    if( zText==0 ){
 42620      return 0;
 42621    }
 42622    nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
 42623                                  nByte, 0, 0);
 42624    if( nByte == 0 ){
 42625      sqlite3_free(zText);
 42626      zText = 0;
 42627    }
 42628    return zText;
 42629  }
 42630  
 42631  /*
 42632  ** Convert a multi-byte character string to UTF-8.
 42633  **
 42634  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42635  */
 42636  static char *winMbcsToUtf8(const char *zText, int useAnsi){
 42637    char *zTextUtf8;
 42638    LPWSTR zTmpWide;
 42639  
 42640    zTmpWide = winMbcsToUnicode(zText, useAnsi);
 42641    if( zTmpWide==0 ){
 42642      return 0;
 42643    }
 42644    zTextUtf8 = winUnicodeToUtf8(zTmpWide);
 42645    sqlite3_free(zTmpWide);
 42646    return zTextUtf8;
 42647  }
 42648  
 42649  /*
 42650  ** Convert a UTF-8 string to a multi-byte character string.
 42651  **
 42652  ** Space to hold the returned string is obtained from sqlite3_malloc().
 42653  */
 42654  static char *winUtf8ToMbcs(const char *zText, int useAnsi){
 42655    char *zTextMbcs;
 42656    LPWSTR zTmpWide;
 42657  
 42658    zTmpWide = winUtf8ToUnicode(zText);
 42659    if( zTmpWide==0 ){
 42660      return 0;
 42661    }
 42662    zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
 42663    sqlite3_free(zTmpWide);
 42664    return zTextMbcs;
 42665  }
 42666  
 42667  /*
 42668  ** This is a public wrapper for the winUtf8ToUnicode() function.
 42669  */
 42670  SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
 42671  #ifdef SQLITE_ENABLE_API_ARMOR
 42672    if( !zText ){
 42673      (void)SQLITE_MISUSE_BKPT;
 42674      return 0;
 42675    }
 42676  #endif
 42677  #ifndef SQLITE_OMIT_AUTOINIT
 42678    if( sqlite3_initialize() ) return 0;
 42679  #endif
 42680    return winUtf8ToUnicode(zText);
 42681  }
 42682  
 42683  /*
 42684  ** This is a public wrapper for the winUnicodeToUtf8() function.
 42685  */
 42686  SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
 42687  #ifdef SQLITE_ENABLE_API_ARMOR
 42688    if( !zWideText ){
 42689      (void)SQLITE_MISUSE_BKPT;
 42690      return 0;
 42691    }
 42692  #endif
 42693  #ifndef SQLITE_OMIT_AUTOINIT
 42694    if( sqlite3_initialize() ) return 0;
 42695  #endif
 42696    return winUnicodeToUtf8(zWideText);
 42697  }
 42698  
 42699  /*
 42700  ** This is a public wrapper for the winMbcsToUtf8() function.
 42701  */
 42702  SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
 42703  #ifdef SQLITE_ENABLE_API_ARMOR
 42704    if( !zText ){
 42705      (void)SQLITE_MISUSE_BKPT;
 42706      return 0;
 42707    }
 42708  #endif
 42709  #ifndef SQLITE_OMIT_AUTOINIT
 42710    if( sqlite3_initialize() ) return 0;
 42711  #endif
 42712    return winMbcsToUtf8(zText, osAreFileApisANSI());
 42713  }
 42714  
 42715  /*
 42716  ** This is a public wrapper for the winMbcsToUtf8() function.
 42717  */
 42718  SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
 42719  #ifdef SQLITE_ENABLE_API_ARMOR
 42720    if( !zText ){
 42721      (void)SQLITE_MISUSE_BKPT;
 42722      return 0;
 42723    }
 42724  #endif
 42725  #ifndef SQLITE_OMIT_AUTOINIT
 42726    if( sqlite3_initialize() ) return 0;
 42727  #endif
 42728    return winMbcsToUtf8(zText, useAnsi);
 42729  }
 42730  
 42731  /*
 42732  ** This is a public wrapper for the winUtf8ToMbcs() function.
 42733  */
 42734  SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
 42735  #ifdef SQLITE_ENABLE_API_ARMOR
 42736    if( !zText ){
 42737      (void)SQLITE_MISUSE_BKPT;
 42738      return 0;
 42739    }
 42740  #endif
 42741  #ifndef SQLITE_OMIT_AUTOINIT
 42742    if( sqlite3_initialize() ) return 0;
 42743  #endif
 42744    return winUtf8ToMbcs(zText, osAreFileApisANSI());
 42745  }
 42746  
 42747  /*
 42748  ** This is a public wrapper for the winUtf8ToMbcs() function.
 42749  */
 42750  SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
 42751  #ifdef SQLITE_ENABLE_API_ARMOR
 42752    if( !zText ){
 42753      (void)SQLITE_MISUSE_BKPT;
 42754      return 0;
 42755    }
 42756  #endif
 42757  #ifndef SQLITE_OMIT_AUTOINIT
 42758    if( sqlite3_initialize() ) return 0;
 42759  #endif
 42760    return winUtf8ToMbcs(zText, useAnsi);
 42761  }
 42762  
 42763  /*
 42764  ** This function is the same as sqlite3_win32_set_directory (below); however,
 42765  ** it accepts a UTF-8 string.
 42766  */
 42767  SQLITE_API int sqlite3_win32_set_directory8(
 42768    unsigned long type, /* Identifier for directory being set or reset */
 42769    const char *zValue  /* New value for directory being set or reset */
 42770  ){
 42771    char **ppDirectory = 0;
 42772  #ifndef SQLITE_OMIT_AUTOINIT
 42773    int rc = sqlite3_initialize();
 42774    if( rc ) return rc;
 42775  #endif
 42776    if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
 42777      ppDirectory = &sqlite3_data_directory;
 42778    }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
 42779      ppDirectory = &sqlite3_temp_directory;
 42780    }
 42781    assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
 42782            || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
 42783    );
 42784    assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
 42785    if( ppDirectory ){
 42786      char *zCopy = 0;
 42787      if( zValue && zValue[0] ){
 42788        zCopy = sqlite3_mprintf("%s", zValue);
 42789        if ( zCopy==0 ){
 42790          return SQLITE_NOMEM_BKPT;
 42791        }
 42792      }
 42793      sqlite3_free(*ppDirectory);
 42794      *ppDirectory = zCopy;
 42795      return SQLITE_OK;
 42796    }
 42797    return SQLITE_ERROR;
 42798  }
 42799  
 42800  /*
 42801  ** This function is the same as sqlite3_win32_set_directory (below); however,
 42802  ** it accepts a UTF-16 string.
 42803  */
 42804  SQLITE_API int sqlite3_win32_set_directory16(
 42805    unsigned long type, /* Identifier for directory being set or reset */
 42806    const void *zValue  /* New value for directory being set or reset */
 42807  ){
 42808    int rc;
 42809    char *zUtf8 = 0;
 42810    if( zValue ){
 42811      zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
 42812      if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
 42813    }
 42814    rc = sqlite3_win32_set_directory8(type, zUtf8);
 42815    if( zUtf8 ) sqlite3_free(zUtf8);
 42816    return rc;
 42817  }
 42818  
 42819  /*
 42820  ** This function sets the data directory or the temporary directory based on
 42821  ** the provided arguments.  The type argument must be 1 in order to set the
 42822  ** data directory or 2 in order to set the temporary directory.  The zValue
 42823  ** argument is the name of the directory to use.  The return value will be
 42824  ** SQLITE_OK if successful.
 42825  */
 42826  SQLITE_API int sqlite3_win32_set_directory(
 42827    unsigned long type, /* Identifier for directory being set or reset */
 42828    void *zValue        /* New value for directory being set or reset */
 42829  ){
 42830    return sqlite3_win32_set_directory16(type, zValue);
 42831  }
 42832  
 42833  /*
 42834  ** The return value of winGetLastErrorMsg
 42835  ** is zero if the error message fits in the buffer, or non-zero
 42836  ** otherwise (if the message was truncated).
 42837  */
 42838  static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
 42839    /* FormatMessage returns 0 on failure.  Otherwise it
 42840    ** returns the number of TCHARs written to the output
 42841    ** buffer, excluding the terminating null char.
 42842    */
 42843    DWORD dwLen = 0;
 42844    char *zOut = 0;
 42845  
 42846    if( osIsNT() ){
 42847  #if SQLITE_OS_WINRT
 42848      WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
 42849      dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
 42850                               FORMAT_MESSAGE_IGNORE_INSERTS,
 42851                               NULL,
 42852                               lastErrno,
 42853                               0,
 42854                               zTempWide,
 42855                               SQLITE_WIN32_MAX_ERRMSG_CHARS,
 42856                               0);
 42857  #else
 42858      LPWSTR zTempWide = NULL;
 42859      dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 42860                               FORMAT_MESSAGE_FROM_SYSTEM |
 42861                               FORMAT_MESSAGE_IGNORE_INSERTS,
 42862                               NULL,
 42863                               lastErrno,
 42864                               0,
 42865                               (LPWSTR) &zTempWide,
 42866                               0,
 42867                               0);
 42868  #endif
 42869      if( dwLen > 0 ){
 42870        /* allocate a buffer and convert to UTF8 */
 42871        sqlite3BeginBenignMalloc();
 42872        zOut = winUnicodeToUtf8(zTempWide);
 42873        sqlite3EndBenignMalloc();
 42874  #if !SQLITE_OS_WINRT
 42875        /* free the system buffer allocated by FormatMessage */
 42876        osLocalFree(zTempWide);
 42877  #endif
 42878      }
 42879    }
 42880  #ifdef SQLITE_WIN32_HAS_ANSI
 42881    else{
 42882      char *zTemp = NULL;
 42883      dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
 42884                               FORMAT_MESSAGE_FROM_SYSTEM |
 42885                               FORMAT_MESSAGE_IGNORE_INSERTS,
 42886                               NULL,
 42887                               lastErrno,
 42888                               0,
 42889                               (LPSTR) &zTemp,
 42890                               0,
 42891                               0);
 42892      if( dwLen > 0 ){
 42893        /* allocate a buffer and convert to UTF8 */
 42894        sqlite3BeginBenignMalloc();
 42895        zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
 42896        sqlite3EndBenignMalloc();
 42897        /* free the system buffer allocated by FormatMessage */
 42898        osLocalFree(zTemp);
 42899      }
 42900    }
 42901  #endif
 42902    if( 0 == dwLen ){
 42903      sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
 42904    }else{
 42905      /* copy a maximum of nBuf chars to output buffer */
 42906      sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
 42907      /* free the UTF8 buffer */
 42908      sqlite3_free(zOut);
 42909    }
 42910    return 0;
 42911  }
 42912  
 42913  /*
 42914  **
 42915  ** This function - winLogErrorAtLine() - is only ever called via the macro
 42916  ** winLogError().
 42917  **
 42918  ** This routine is invoked after an error occurs in an OS function.
 42919  ** It logs a message using sqlite3_log() containing the current value of
 42920  ** error code and, if possible, the human-readable equivalent from
 42921  ** FormatMessage.
 42922  **
 42923  ** The first argument passed to the macro should be the error code that
 42924  ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
 42925  ** The two subsequent arguments should be the name of the OS function that
 42926  ** failed and the associated file-system path, if any.
 42927  */
 42928  #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
 42929  static int winLogErrorAtLine(
 42930    int errcode,                    /* SQLite error code */
 42931    DWORD lastErrno,                /* Win32 last error */
 42932    const char *zFunc,              /* Name of OS function that failed */
 42933    const char *zPath,              /* File path associated with error */
 42934    int iLine                       /* Source line number where error occurred */
 42935  ){
 42936    char zMsg[500];                 /* Human readable error text */
 42937    int i;                          /* Loop counter */
 42938  
 42939    zMsg[0] = 0;
 42940    winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
 42941    assert( errcode!=SQLITE_OK );
 42942    if( zPath==0 ) zPath = "";
 42943    for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
 42944    zMsg[i] = 0;
 42945    sqlite3_log(errcode,
 42946        "os_win.c:%d: (%lu) %s(%s) - %s",
 42947        iLine, lastErrno, zFunc, zPath, zMsg
 42948    );
 42949  
 42950    return errcode;
 42951  }
 42952  
 42953  /*
 42954  ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
 42955  ** will be retried following a locking error - probably caused by
 42956  ** antivirus software.  Also the initial delay before the first retry.
 42957  ** The delay increases linearly with each retry.
 42958  */
 42959  #ifndef SQLITE_WIN32_IOERR_RETRY
 42960  # define SQLITE_WIN32_IOERR_RETRY 10
 42961  #endif
 42962  #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
 42963  # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
 42964  #endif
 42965  static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
 42966  static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
 42967  
 42968  /*
 42969  ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
 42970  ** error code obtained via GetLastError() is eligible to be retried.  It
 42971  ** must accept the error code DWORD as its only argument and should return
 42972  ** non-zero if the error code is transient in nature and the operation
 42973  ** responsible for generating the original error might succeed upon being
 42974  ** retried.  The argument to this macro should be a variable.
 42975  **
 42976  ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
 42977  ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
 42978  ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
 42979  ** may be used to include additional error codes in the set that should
 42980  ** result in the failing I/O operation being retried by the caller.  If
 42981  ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
 42982  ** identical to those of the "winIoerrCanRetry1" macro.
 42983  */
 42984  #if !defined(winIoerrCanRetry1)
 42985  #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
 42986                                ((a)==ERROR_SHARING_VIOLATION)    || \
 42987                                ((a)==ERROR_LOCK_VIOLATION)       || \
 42988                                ((a)==ERROR_DEV_NOT_EXIST)        || \
 42989                                ((a)==ERROR_NETNAME_DELETED)      || \
 42990                                ((a)==ERROR_SEM_TIMEOUT)          || \
 42991                                ((a)==ERROR_NETWORK_UNREACHABLE))
 42992  #endif
 42993  
 42994  /*
 42995  ** If a ReadFile() or WriteFile() error occurs, invoke this routine
 42996  ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
 42997  ** to give up with an error.
 42998  */
 42999  static int winRetryIoerr(int *pnRetry, DWORD *pError){
 43000    DWORD e = osGetLastError();
 43001    if( *pnRetry>=winIoerrRetry ){
 43002      if( pError ){
 43003        *pError = e;
 43004      }
 43005      return 0;
 43006    }
 43007    if( winIoerrCanRetry1(e) ){
 43008      sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
 43009      ++*pnRetry;
 43010      return 1;
 43011    }
 43012  #if defined(winIoerrCanRetry2)
 43013    else if( winIoerrCanRetry2(e) ){
 43014      sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
 43015      ++*pnRetry;
 43016      return 1;
 43017    }
 43018  #endif
 43019    if( pError ){
 43020      *pError = e;
 43021    }
 43022    return 0;
 43023  }
 43024  
 43025  /*
 43026  ** Log a I/O error retry episode.
 43027  */
 43028  static void winLogIoerr(int nRetry, int lineno){
 43029    if( nRetry ){
 43030      sqlite3_log(SQLITE_NOTICE,
 43031        "delayed %dms for lock/sharing conflict at line %d",
 43032        winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
 43033      );
 43034    }
 43035  }
 43036  
 43037  /*
 43038  ** This #if does not rely on the SQLITE_OS_WINCE define because the
 43039  ** corresponding section in "date.c" cannot use it.
 43040  */
 43041  #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
 43042      (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
 43043  /*
 43044  ** The MSVC CRT on Windows CE may not have a localtime() function.
 43045  ** So define a substitute.
 43046  */
 43047  /* #  include <time.h> */
 43048  struct tm *__cdecl localtime(const time_t *t)
 43049  {
 43050    static struct tm y;
 43051    FILETIME uTm, lTm;
 43052    SYSTEMTIME pTm;
 43053    sqlite3_int64 t64;
 43054    t64 = *t;
 43055    t64 = (t64 + 11644473600)*10000000;
 43056    uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
 43057    uTm.dwHighDateTime= (DWORD)(t64 >> 32);
 43058    osFileTimeToLocalFileTime(&uTm,&lTm);
 43059    osFileTimeToSystemTime(&lTm,&pTm);
 43060    y.tm_year = pTm.wYear - 1900;
 43061    y.tm_mon = pTm.wMonth - 1;
 43062    y.tm_wday = pTm.wDayOfWeek;
 43063    y.tm_mday = pTm.wDay;
 43064    y.tm_hour = pTm.wHour;
 43065    y.tm_min = pTm.wMinute;
 43066    y.tm_sec = pTm.wSecond;
 43067    return &y;
 43068  }
 43069  #endif
 43070  
 43071  #if SQLITE_OS_WINCE
 43072  /*************************************************************************
 43073  ** This section contains code for WinCE only.
 43074  */
 43075  #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
 43076  
 43077  /*
 43078  ** Acquire a lock on the handle h
 43079  */
 43080  static void winceMutexAcquire(HANDLE h){
 43081     DWORD dwErr;
 43082     do {
 43083       dwErr = osWaitForSingleObject(h, INFINITE);
 43084     } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
 43085  }
 43086  /*
 43087  ** Release a lock acquired by winceMutexAcquire()
 43088  */
 43089  #define winceMutexRelease(h) ReleaseMutex(h)
 43090  
 43091  /*
 43092  ** Create the mutex and shared memory used for locking in the file
 43093  ** descriptor pFile
 43094  */
 43095  static int winceCreateLock(const char *zFilename, winFile *pFile){
 43096    LPWSTR zTok;
 43097    LPWSTR zName;
 43098    DWORD lastErrno;
 43099    BOOL bLogged = FALSE;
 43100    BOOL bInit = TRUE;
 43101  
 43102    zName = winUtf8ToUnicode(zFilename);
 43103    if( zName==0 ){
 43104      /* out of memory */
 43105      return SQLITE_IOERR_NOMEM_BKPT;
 43106    }
 43107  
 43108    /* Initialize the local lockdata */
 43109    memset(&pFile->local, 0, sizeof(pFile->local));
 43110  
 43111    /* Replace the backslashes from the filename and lowercase it
 43112    ** to derive a mutex name. */
 43113    zTok = osCharLowerW(zName);
 43114    for (;*zTok;zTok++){
 43115      if (*zTok == '\\') *zTok = '_';
 43116    }
 43117  
 43118    /* Create/open the named mutex */
 43119    pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
 43120    if (!pFile->hMutex){
 43121      pFile->lastErrno = osGetLastError();
 43122      sqlite3_free(zName);
 43123      return winLogError(SQLITE_IOERR, pFile->lastErrno,
 43124                         "winceCreateLock1", zFilename);
 43125    }
 43126  
 43127    /* Acquire the mutex before continuing */
 43128    winceMutexAcquire(pFile->hMutex);
 43129  
 43130    /* Since the names of named mutexes, semaphores, file mappings etc are
 43131    ** case-sensitive, take advantage of that by uppercasing the mutex name
 43132    ** and using that as the shared filemapping name.
 43133    */
 43134    osCharUpperW(zName);
 43135    pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
 43136                                          PAGE_READWRITE, 0, sizeof(winceLock),
 43137                                          zName);
 43138  
 43139    /* Set a flag that indicates we're the first to create the memory so it
 43140    ** must be zero-initialized */
 43141    lastErrno = osGetLastError();
 43142    if (lastErrno == ERROR_ALREADY_EXISTS){
 43143      bInit = FALSE;
 43144    }
 43145  
 43146    sqlite3_free(zName);
 43147  
 43148    /* If we succeeded in making the shared memory handle, map it. */
 43149    if( pFile->hShared ){
 43150      pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
 43151               FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
 43152      /* If mapping failed, close the shared memory handle and erase it */
 43153      if( !pFile->shared ){
 43154        pFile->lastErrno = osGetLastError();
 43155        winLogError(SQLITE_IOERR, pFile->lastErrno,
 43156                    "winceCreateLock2", zFilename);
 43157        bLogged = TRUE;
 43158        osCloseHandle(pFile->hShared);
 43159        pFile->hShared = NULL;
 43160      }
 43161    }
 43162  
 43163    /* If shared memory could not be created, then close the mutex and fail */
 43164    if( pFile->hShared==NULL ){
 43165      if( !bLogged ){
 43166        pFile->lastErrno = lastErrno;
 43167        winLogError(SQLITE_IOERR, pFile->lastErrno,
 43168                    "winceCreateLock3", zFilename);
 43169        bLogged = TRUE;
 43170      }
 43171      winceMutexRelease(pFile->hMutex);
 43172      osCloseHandle(pFile->hMutex);
 43173      pFile->hMutex = NULL;
 43174      return SQLITE_IOERR;
 43175    }
 43176  
 43177    /* Initialize the shared memory if we're supposed to */
 43178    if( bInit ){
 43179      memset(pFile->shared, 0, sizeof(winceLock));
 43180    }
 43181  
 43182    winceMutexRelease(pFile->hMutex);
 43183    return SQLITE_OK;
 43184  }
 43185  
 43186  /*
 43187  ** Destroy the part of winFile that deals with wince locks
 43188  */
 43189  static void winceDestroyLock(winFile *pFile){
 43190    if (pFile->hMutex){
 43191      /* Acquire the mutex */
 43192      winceMutexAcquire(pFile->hMutex);
 43193  
 43194      /* The following blocks should probably assert in debug mode, but they
 43195         are to cleanup in case any locks remained open */
 43196      if (pFile->local.nReaders){
 43197        pFile->shared->nReaders --;
 43198      }
 43199      if (pFile->local.bReserved){
 43200        pFile->shared->bReserved = FALSE;
 43201      }
 43202      if (pFile->local.bPending){
 43203        pFile->shared->bPending = FALSE;
 43204      }
 43205      if (pFile->local.bExclusive){
 43206        pFile->shared->bExclusive = FALSE;
 43207      }
 43208  
 43209      /* De-reference and close our copy of the shared memory handle */
 43210      osUnmapViewOfFile(pFile->shared);
 43211      osCloseHandle(pFile->hShared);
 43212  
 43213      /* Done with the mutex */
 43214      winceMutexRelease(pFile->hMutex);
 43215      osCloseHandle(pFile->hMutex);
 43216      pFile->hMutex = NULL;
 43217    }
 43218  }
 43219  
 43220  /*
 43221  ** An implementation of the LockFile() API of Windows for CE
 43222  */
 43223  static BOOL winceLockFile(
 43224    LPHANDLE phFile,
 43225    DWORD dwFileOffsetLow,
 43226    DWORD dwFileOffsetHigh,
 43227    DWORD nNumberOfBytesToLockLow,
 43228    DWORD nNumberOfBytesToLockHigh
 43229  ){
 43230    winFile *pFile = HANDLE_TO_WINFILE(phFile);
 43231    BOOL bReturn = FALSE;
 43232  
 43233    UNUSED_PARAMETER(dwFileOffsetHigh);
 43234    UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
 43235  
 43236    if (!pFile->hMutex) return TRUE;
 43237    winceMutexAcquire(pFile->hMutex);
 43238  
 43239    /* Wanting an exclusive lock? */
 43240    if (dwFileOffsetLow == (DWORD)SHARED_FIRST
 43241         && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
 43242      if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
 43243         pFile->shared->bExclusive = TRUE;
 43244         pFile->local.bExclusive = TRUE;
 43245         bReturn = TRUE;
 43246      }
 43247    }
 43248  
 43249    /* Want a read-only lock? */
 43250    else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
 43251             nNumberOfBytesToLockLow == 1){
 43252      if (pFile->shared->bExclusive == 0){
 43253        pFile->local.nReaders ++;
 43254        if (pFile->local.nReaders == 1){
 43255          pFile->shared->nReaders ++;
 43256        }
 43257        bReturn = TRUE;
 43258      }
 43259    }
 43260  
 43261    /* Want a pending lock? */
 43262    else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 43263             && nNumberOfBytesToLockLow == 1){
 43264      /* If no pending lock has been acquired, then acquire it */
 43265      if (pFile->shared->bPending == 0) {
 43266        pFile->shared->bPending = TRUE;
 43267        pFile->local.bPending = TRUE;
 43268        bReturn = TRUE;
 43269      }
 43270    }
 43271  
 43272    /* Want a reserved lock? */
 43273    else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 43274             && nNumberOfBytesToLockLow == 1){
 43275      if (pFile->shared->bReserved == 0) {
 43276        pFile->shared->bReserved = TRUE;
 43277        pFile->local.bReserved = TRUE;
 43278        bReturn = TRUE;
 43279      }
 43280    }
 43281  
 43282    winceMutexRelease(pFile->hMutex);
 43283    return bReturn;
 43284  }
 43285  
 43286  /*
 43287  ** An implementation of the UnlockFile API of Windows for CE
 43288  */
 43289  static BOOL winceUnlockFile(
 43290    LPHANDLE phFile,
 43291    DWORD dwFileOffsetLow,
 43292    DWORD dwFileOffsetHigh,
 43293    DWORD nNumberOfBytesToUnlockLow,
 43294    DWORD nNumberOfBytesToUnlockHigh
 43295  ){
 43296    winFile *pFile = HANDLE_TO_WINFILE(phFile);
 43297    BOOL bReturn = FALSE;
 43298  
 43299    UNUSED_PARAMETER(dwFileOffsetHigh);
 43300    UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
 43301  
 43302    if (!pFile->hMutex) return TRUE;
 43303    winceMutexAcquire(pFile->hMutex);
 43304  
 43305    /* Releasing a reader lock or an exclusive lock */
 43306    if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
 43307      /* Did we have an exclusive lock? */
 43308      if (pFile->local.bExclusive){
 43309        assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
 43310        pFile->local.bExclusive = FALSE;
 43311        pFile->shared->bExclusive = FALSE;
 43312        bReturn = TRUE;
 43313      }
 43314  
 43315      /* Did we just have a reader lock? */
 43316      else if (pFile->local.nReaders){
 43317        assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
 43318               || nNumberOfBytesToUnlockLow == 1);
 43319        pFile->local.nReaders --;
 43320        if (pFile->local.nReaders == 0)
 43321        {
 43322          pFile->shared->nReaders --;
 43323        }
 43324        bReturn = TRUE;
 43325      }
 43326    }
 43327  
 43328    /* Releasing a pending lock */
 43329    else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
 43330             && nNumberOfBytesToUnlockLow == 1){
 43331      if (pFile->local.bPending){
 43332        pFile->local.bPending = FALSE;
 43333        pFile->shared->bPending = FALSE;
 43334        bReturn = TRUE;
 43335      }
 43336    }
 43337    /* Releasing a reserved lock */
 43338    else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
 43339             && nNumberOfBytesToUnlockLow == 1){
 43340      if (pFile->local.bReserved) {
 43341        pFile->local.bReserved = FALSE;
 43342        pFile->shared->bReserved = FALSE;
 43343        bReturn = TRUE;
 43344      }
 43345    }
 43346  
 43347    winceMutexRelease(pFile->hMutex);
 43348    return bReturn;
 43349  }
 43350  /*
 43351  ** End of the special code for wince
 43352  *****************************************************************************/
 43353  #endif /* SQLITE_OS_WINCE */
 43354  
 43355  /*
 43356  ** Lock a file region.
 43357  */
 43358  static BOOL winLockFile(
 43359    LPHANDLE phFile,
 43360    DWORD flags,
 43361    DWORD offsetLow,
 43362    DWORD offsetHigh,
 43363    DWORD numBytesLow,
 43364    DWORD numBytesHigh
 43365  ){
 43366  #if SQLITE_OS_WINCE
 43367    /*
 43368    ** NOTE: Windows CE is handled differently here due its lack of the Win32
 43369    **       API LockFile.
 43370    */
 43371    return winceLockFile(phFile, offsetLow, offsetHigh,
 43372                         numBytesLow, numBytesHigh);
 43373  #else
 43374    if( osIsNT() ){
 43375      OVERLAPPED ovlp;
 43376      memset(&ovlp, 0, sizeof(OVERLAPPED));
 43377      ovlp.Offset = offsetLow;
 43378      ovlp.OffsetHigh = offsetHigh;
 43379      return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
 43380    }else{
 43381      return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 43382                        numBytesHigh);
 43383    }
 43384  #endif
 43385  }
 43386  
 43387  /*
 43388  ** Unlock a file region.
 43389   */
 43390  static BOOL winUnlockFile(
 43391    LPHANDLE phFile,
 43392    DWORD offsetLow,
 43393    DWORD offsetHigh,
 43394    DWORD numBytesLow,
 43395    DWORD numBytesHigh
 43396  ){
 43397  #if SQLITE_OS_WINCE
 43398    /*
 43399    ** NOTE: Windows CE is handled differently here due its lack of the Win32
 43400    **       API UnlockFile.
 43401    */
 43402    return winceUnlockFile(phFile, offsetLow, offsetHigh,
 43403                           numBytesLow, numBytesHigh);
 43404  #else
 43405    if( osIsNT() ){
 43406      OVERLAPPED ovlp;
 43407      memset(&ovlp, 0, sizeof(OVERLAPPED));
 43408      ovlp.Offset = offsetLow;
 43409      ovlp.OffsetHigh = offsetHigh;
 43410      return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
 43411    }else{
 43412      return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
 43413                          numBytesHigh);
 43414    }
 43415  #endif
 43416  }
 43417  
 43418  /*****************************************************************************
 43419  ** The next group of routines implement the I/O methods specified
 43420  ** by the sqlite3_io_methods object.
 43421  ******************************************************************************/
 43422  
 43423  /*
 43424  ** Some Microsoft compilers lack this definition.
 43425  */
 43426  #ifndef INVALID_SET_FILE_POINTER
 43427  # define INVALID_SET_FILE_POINTER ((DWORD)-1)
 43428  #endif
 43429  
 43430  /*
 43431  ** Move the current position of the file handle passed as the first
 43432  ** argument to offset iOffset within the file. If successful, return 0.
 43433  ** Otherwise, set pFile->lastErrno and return non-zero.
 43434  */
 43435  static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
 43436  #if !SQLITE_OS_WINRT
 43437    LONG upperBits;                 /* Most sig. 32 bits of new offset */
 43438    LONG lowerBits;                 /* Least sig. 32 bits of new offset */
 43439    DWORD dwRet;                    /* Value returned by SetFilePointer() */
 43440    DWORD lastErrno;                /* Value returned by GetLastError() */
 43441  
 43442    OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
 43443  
 43444    upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
 43445    lowerBits = (LONG)(iOffset & 0xffffffff);
 43446  
 43447    /* API oddity: If successful, SetFilePointer() returns a dword
 43448    ** containing the lower 32-bits of the new file-offset. Or, if it fails,
 43449    ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
 43450    ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
 43451    ** whether an error has actually occurred, it is also necessary to call
 43452    ** GetLastError().
 43453    */
 43454    dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
 43455  
 43456    if( (dwRet==INVALID_SET_FILE_POINTER
 43457        && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
 43458      pFile->lastErrno = lastErrno;
 43459      winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 43460                  "winSeekFile", pFile->zPath);
 43461      OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 43462      return 1;
 43463    }
 43464  
 43465    OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 43466    return 0;
 43467  #else
 43468    /*
 43469    ** Same as above, except that this implementation works for WinRT.
 43470    */
 43471  
 43472    LARGE_INTEGER x;                /* The new offset */
 43473    BOOL bRet;                      /* Value returned by SetFilePointerEx() */
 43474  
 43475    x.QuadPart = iOffset;
 43476    bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
 43477  
 43478    if(!bRet){
 43479      pFile->lastErrno = osGetLastError();
 43480      winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
 43481                  "winSeekFile", pFile->zPath);
 43482      OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
 43483      return 1;
 43484    }
 43485  
 43486    OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
 43487    return 0;
 43488  #endif
 43489  }
 43490  
 43491  #if SQLITE_MAX_MMAP_SIZE>0
 43492  /* Forward references to VFS helper methods used for memory mapped files */
 43493  static int winMapfile(winFile*, sqlite3_int64);
 43494  static int winUnmapfile(winFile*);
 43495  #endif
 43496  
 43497  /*
 43498  ** Close a file.
 43499  **
 43500  ** It is reported that an attempt to close a handle might sometimes
 43501  ** fail.  This is a very unreasonable result, but Windows is notorious
 43502  ** for being unreasonable so I do not doubt that it might happen.  If
 43503  ** the close fails, we pause for 100 milliseconds and try again.  As
 43504  ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
 43505  ** giving up and returning an error.
 43506  */
 43507  #define MX_CLOSE_ATTEMPT 3
 43508  static int winClose(sqlite3_file *id){
 43509    int rc, cnt = 0;
 43510    winFile *pFile = (winFile*)id;
 43511  
 43512    assert( id!=0 );
 43513  #ifndef SQLITE_OMIT_WAL
 43514    assert( pFile->pShm==0 );
 43515  #endif
 43516    assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
 43517    OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
 43518             osGetCurrentProcessId(), pFile, pFile->h));
 43519  
 43520  #if SQLITE_MAX_MMAP_SIZE>0
 43521    winUnmapfile(pFile);
 43522  #endif
 43523  
 43524    do{
 43525      rc = osCloseHandle(pFile->h);
 43526      /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
 43527    }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
 43528  #if SQLITE_OS_WINCE
 43529  #define WINCE_DELETION_ATTEMPTS 3
 43530    {
 43531      winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
 43532      if( pAppData==NULL || !pAppData->bNoLock ){
 43533        winceDestroyLock(pFile);
 43534      }
 43535    }
 43536    if( pFile->zDeleteOnClose ){
 43537      int cnt = 0;
 43538      while(
 43539             osDeleteFileW(pFile->zDeleteOnClose)==0
 43540          && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
 43541          && cnt++ < WINCE_DELETION_ATTEMPTS
 43542      ){
 43543         sqlite3_win32_sleep(100);  /* Wait a little before trying again */
 43544      }
 43545      sqlite3_free(pFile->zDeleteOnClose);
 43546    }
 43547  #endif
 43548    if( rc ){
 43549      pFile->h = NULL;
 43550    }
 43551    OpenCounter(-1);
 43552    OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
 43553             osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
 43554    return rc ? SQLITE_OK
 43555              : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
 43556                            "winClose", pFile->zPath);
 43557  }
 43558  
 43559  /*
 43560  ** Read data from a file into a buffer.  Return SQLITE_OK if all
 43561  ** bytes were read successfully and SQLITE_IOERR if anything goes
 43562  ** wrong.
 43563  */
 43564  static int winRead(
 43565    sqlite3_file *id,          /* File to read from */
 43566    void *pBuf,                /* Write content into this buffer */
 43567    int amt,                   /* Number of bytes to read */
 43568    sqlite3_int64 offset       /* Begin reading at this offset */
 43569  ){
 43570  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 43571    OVERLAPPED overlapped;          /* The offset for ReadFile. */
 43572  #endif
 43573    winFile *pFile = (winFile*)id;  /* file handle */
 43574    DWORD nRead;                    /* Number of bytes actually read from file */
 43575    int nRetry = 0;                 /* Number of retrys */
 43576  
 43577    assert( id!=0 );
 43578    assert( amt>0 );
 43579    assert( offset>=0 );
 43580    SimulateIOError(return SQLITE_IOERR_READ);
 43581    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
 43582             "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
 43583             pFile->h, pBuf, amt, offset, pFile->locktype));
 43584  
 43585  #if SQLITE_MAX_MMAP_SIZE>0
 43586    /* Deal with as much of this read request as possible by transfering
 43587    ** data from the memory mapping using memcpy().  */
 43588    if( offset<pFile->mmapSize ){
 43589      if( offset+amt <= pFile->mmapSize ){
 43590        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
 43591        OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43592                 osGetCurrentProcessId(), pFile, pFile->h));
 43593        return SQLITE_OK;
 43594      }else{
 43595        int nCopy = (int)(pFile->mmapSize - offset);
 43596        memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
 43597        pBuf = &((u8 *)pBuf)[nCopy];
 43598        amt -= nCopy;
 43599        offset += nCopy;
 43600      }
 43601    }
 43602  #endif
 43603  
 43604  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 43605    if( winSeekFile(pFile, offset) ){
 43606      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
 43607               osGetCurrentProcessId(), pFile, pFile->h));
 43608      return SQLITE_FULL;
 43609    }
 43610    while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
 43611  #else
 43612    memset(&overlapped, 0, sizeof(OVERLAPPED));
 43613    overlapped.Offset = (LONG)(offset & 0xffffffff);
 43614    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 43615    while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
 43616           osGetLastError()!=ERROR_HANDLE_EOF ){
 43617  #endif
 43618      DWORD lastErrno;
 43619      if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 43620      pFile->lastErrno = lastErrno;
 43621      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
 43622               osGetCurrentProcessId(), pFile, pFile->h));
 43623      return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
 43624                         "winRead", pFile->zPath);
 43625    }
 43626    winLogIoerr(nRetry, __LINE__);
 43627    if( nRead<(DWORD)amt ){
 43628      /* Unread parts of the buffer must be zero-filled */
 43629      memset(&((char*)pBuf)[nRead], 0, amt-nRead);
 43630      OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
 43631               osGetCurrentProcessId(), pFile, pFile->h));
 43632      return SQLITE_IOERR_SHORT_READ;
 43633    }
 43634  
 43635    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43636             osGetCurrentProcessId(), pFile, pFile->h));
 43637    return SQLITE_OK;
 43638  }
 43639  
 43640  /*
 43641  ** Write data from a buffer into a file.  Return SQLITE_OK on success
 43642  ** or some other error code on failure.
 43643  */
 43644  static int winWrite(
 43645    sqlite3_file *id,               /* File to write into */
 43646    const void *pBuf,               /* The bytes to be written */
 43647    int amt,                        /* Number of bytes to write */
 43648    sqlite3_int64 offset            /* Offset into the file to begin writing at */
 43649  ){
 43650    int rc = 0;                     /* True if error has occurred, else false */
 43651    winFile *pFile = (winFile*)id;  /* File handle */
 43652    int nRetry = 0;                 /* Number of retries */
 43653  
 43654    assert( amt>0 );
 43655    assert( pFile );
 43656    SimulateIOError(return SQLITE_IOERR_WRITE);
 43657    SimulateDiskfullError(return SQLITE_FULL);
 43658  
 43659    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
 43660             "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
 43661             pFile->h, pBuf, amt, offset, pFile->locktype));
 43662  
 43663  #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
 43664    /* Deal with as much of this write request as possible by transfering
 43665    ** data from the memory mapping using memcpy().  */
 43666    if( offset<pFile->mmapSize ){
 43667      if( offset+amt <= pFile->mmapSize ){
 43668        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
 43669        OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43670                 osGetCurrentProcessId(), pFile, pFile->h));
 43671        return SQLITE_OK;
 43672      }else{
 43673        int nCopy = (int)(pFile->mmapSize - offset);
 43674        memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
 43675        pBuf = &((u8 *)pBuf)[nCopy];
 43676        amt -= nCopy;
 43677        offset += nCopy;
 43678      }
 43679    }
 43680  #endif
 43681  
 43682  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 43683    rc = winSeekFile(pFile, offset);
 43684    if( rc==0 ){
 43685  #else
 43686    {
 43687  #endif
 43688  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 43689      OVERLAPPED overlapped;        /* The offset for WriteFile. */
 43690  #endif
 43691      u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
 43692      int nRem = amt;               /* Number of bytes yet to be written */
 43693      DWORD nWrite;                 /* Bytes written by each WriteFile() call */
 43694      DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
 43695  
 43696  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 43697      memset(&overlapped, 0, sizeof(OVERLAPPED));
 43698      overlapped.Offset = (LONG)(offset & 0xffffffff);
 43699      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 43700  #endif
 43701  
 43702      while( nRem>0 ){
 43703  #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
 43704        if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
 43705  #else
 43706        if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
 43707  #endif
 43708          if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
 43709          break;
 43710        }
 43711        assert( nWrite==0 || nWrite<=(DWORD)nRem );
 43712        if( nWrite==0 || nWrite>(DWORD)nRem ){
 43713          lastErrno = osGetLastError();
 43714          break;
 43715        }
 43716  #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
 43717        offset += nWrite;
 43718        overlapped.Offset = (LONG)(offset & 0xffffffff);
 43719        overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
 43720  #endif
 43721        aRem += nWrite;
 43722        nRem -= nWrite;
 43723      }
 43724      if( nRem>0 ){
 43725        pFile->lastErrno = lastErrno;
 43726        rc = 1;
 43727      }
 43728    }
 43729  
 43730    if( rc ){
 43731      if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
 43732         || ( pFile->lastErrno==ERROR_DISK_FULL )){
 43733        OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
 43734                 osGetCurrentProcessId(), pFile, pFile->h));
 43735        return winLogError(SQLITE_FULL, pFile->lastErrno,
 43736                           "winWrite1", pFile->zPath);
 43737      }
 43738      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
 43739               osGetCurrentProcessId(), pFile, pFile->h));
 43740      return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
 43741                         "winWrite2", pFile->zPath);
 43742    }else{
 43743      winLogIoerr(nRetry, __LINE__);
 43744    }
 43745    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43746             osGetCurrentProcessId(), pFile, pFile->h));
 43747    return SQLITE_OK;
 43748  }
 43749  
 43750  /*
 43751  ** Truncate an open file to a specified size
 43752  */
 43753  static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
 43754    winFile *pFile = (winFile*)id;  /* File handle object */
 43755    int rc = SQLITE_OK;             /* Return code for this function */
 43756    DWORD lastErrno;
 43757  #if SQLITE_MAX_MMAP_SIZE>0
 43758    sqlite3_int64 oldMmapSize;
 43759    if( pFile->nFetchOut>0 ){
 43760      /* File truncation is a no-op if there are outstanding memory mapped
 43761      ** pages.  This is because truncating the file means temporarily unmapping
 43762      ** the file, and that might delete memory out from under existing cursors.
 43763      **
 43764      ** This can result in incremental vacuum not truncating the file,
 43765      ** if there is an active read cursor when the incremental vacuum occurs.
 43766      ** No real harm comes of this - the database file is not corrupted,
 43767      ** though some folks might complain that the file is bigger than it
 43768      ** needs to be.
 43769      **
 43770      ** The only feasible work-around is to defer the truncation until after
 43771      ** all references to memory-mapped content are closed.  That is doable,
 43772      ** but involves adding a few branches in the common write code path which
 43773      ** could slow down normal operations slightly.  Hence, we have decided for
 43774      ** now to simply make trancations a no-op if there are pending reads.  We
 43775      ** can maybe revisit this decision in the future.
 43776      */
 43777      return SQLITE_OK;
 43778    }
 43779  #endif
 43780  
 43781    assert( pFile );
 43782    SimulateIOError(return SQLITE_IOERR_TRUNCATE);
 43783    OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
 43784             osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
 43785  
 43786    /* If the user has configured a chunk-size for this file, truncate the
 43787    ** file so that it consists of an integer number of chunks (i.e. the
 43788    ** actual file size after the operation may be larger than the requested
 43789    ** size).
 43790    */
 43791    if( pFile->szChunk>0 ){
 43792      nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
 43793    }
 43794  
 43795  #if SQLITE_MAX_MMAP_SIZE>0
 43796    if( pFile->pMapRegion ){
 43797      oldMmapSize = pFile->mmapSize;
 43798    }else{
 43799      oldMmapSize = 0;
 43800    }
 43801    winUnmapfile(pFile);
 43802  #endif
 43803  
 43804    /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
 43805    if( winSeekFile(pFile, nByte) ){
 43806      rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 43807                       "winTruncate1", pFile->zPath);
 43808    }else if( 0==osSetEndOfFile(pFile->h) &&
 43809              ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
 43810      pFile->lastErrno = lastErrno;
 43811      rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
 43812                       "winTruncate2", pFile->zPath);
 43813    }
 43814  
 43815  #if SQLITE_MAX_MMAP_SIZE>0
 43816    if( rc==SQLITE_OK && oldMmapSize>0 ){
 43817      if( oldMmapSize>nByte ){
 43818        winMapfile(pFile, -1);
 43819      }else{
 43820        winMapfile(pFile, oldMmapSize);
 43821      }
 43822    }
 43823  #endif
 43824  
 43825    OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
 43826             osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
 43827    return rc;
 43828  }
 43829  
 43830  #ifdef SQLITE_TEST
 43831  /*
 43832  ** Count the number of fullsyncs and normal syncs.  This is used to test
 43833  ** that syncs and fullsyncs are occuring at the right times.
 43834  */
 43835  SQLITE_API int sqlite3_sync_count = 0;
 43836  SQLITE_API int sqlite3_fullsync_count = 0;
 43837  #endif
 43838  
 43839  /*
 43840  ** Make sure all writes to a particular file are committed to disk.
 43841  */
 43842  static int winSync(sqlite3_file *id, int flags){
 43843  #ifndef SQLITE_NO_SYNC
 43844    /*
 43845    ** Used only when SQLITE_NO_SYNC is not defined.
 43846     */
 43847    BOOL rc;
 43848  #endif
 43849  #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
 43850      defined(SQLITE_HAVE_OS_TRACE)
 43851    /*
 43852    ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
 43853    ** OSTRACE() macros.
 43854     */
 43855    winFile *pFile = (winFile*)id;
 43856  #else
 43857    UNUSED_PARAMETER(id);
 43858  #endif
 43859  
 43860    assert( pFile );
 43861    /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
 43862    assert((flags&0x0F)==SQLITE_SYNC_NORMAL
 43863        || (flags&0x0F)==SQLITE_SYNC_FULL
 43864    );
 43865  
 43866    /* Unix cannot, but some systems may return SQLITE_FULL from here. This
 43867    ** line is to test that doing so does not cause any problems.
 43868    */
 43869    SimulateDiskfullError( return SQLITE_FULL );
 43870  
 43871    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
 43872             osGetCurrentProcessId(), pFile, pFile->h, flags,
 43873             pFile->locktype));
 43874  
 43875  #ifndef SQLITE_TEST
 43876    UNUSED_PARAMETER(flags);
 43877  #else
 43878    if( (flags&0x0F)==SQLITE_SYNC_FULL ){
 43879      sqlite3_fullsync_count++;
 43880    }
 43881    sqlite3_sync_count++;
 43882  #endif
 43883  
 43884    /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
 43885    ** no-op
 43886    */
 43887  #ifdef SQLITE_NO_SYNC
 43888    OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43889             osGetCurrentProcessId(), pFile, pFile->h));
 43890    return SQLITE_OK;
 43891  #else
 43892  #if SQLITE_MAX_MMAP_SIZE>0
 43893    if( pFile->pMapRegion ){
 43894      if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
 43895        OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
 43896                 "rc=SQLITE_OK\n", osGetCurrentProcessId(),
 43897                 pFile, pFile->pMapRegion));
 43898      }else{
 43899        pFile->lastErrno = osGetLastError();
 43900        OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
 43901                 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
 43902                 pFile, pFile->pMapRegion));
 43903        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 43904                           "winSync1", pFile->zPath);
 43905      }
 43906    }
 43907  #endif
 43908    rc = osFlushFileBuffers(pFile->h);
 43909    SimulateIOError( rc=FALSE );
 43910    if( rc ){
 43911      OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
 43912               osGetCurrentProcessId(), pFile, pFile->h));
 43913      return SQLITE_OK;
 43914    }else{
 43915      pFile->lastErrno = osGetLastError();
 43916      OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
 43917               osGetCurrentProcessId(), pFile, pFile->h));
 43918      return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
 43919                         "winSync2", pFile->zPath);
 43920    }
 43921  #endif
 43922  }
 43923  
 43924  /*
 43925  ** Determine the current size of a file in bytes
 43926  */
 43927  static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
 43928    winFile *pFile = (winFile*)id;
 43929    int rc = SQLITE_OK;
 43930  
 43931    assert( id!=0 );
 43932    assert( pSize!=0 );
 43933    SimulateIOError(return SQLITE_IOERR_FSTAT);
 43934    OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
 43935  
 43936  #if SQLITE_OS_WINRT
 43937    {
 43938      FILE_STANDARD_INFO info;
 43939      if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
 43940                                       &info, sizeof(info)) ){
 43941        *pSize = info.EndOfFile.QuadPart;
 43942      }else{
 43943        pFile->lastErrno = osGetLastError();
 43944        rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 43945                         "winFileSize", pFile->zPath);
 43946      }
 43947    }
 43948  #else
 43949    {
 43950      DWORD upperBits;
 43951      DWORD lowerBits;
 43952      DWORD lastErrno;
 43953  
 43954      lowerBits = osGetFileSize(pFile->h, &upperBits);
 43955      *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
 43956      if(   (lowerBits == INVALID_FILE_SIZE)
 43957         && ((lastErrno = osGetLastError())!=NO_ERROR) ){
 43958        pFile->lastErrno = lastErrno;
 43959        rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
 43960                         "winFileSize", pFile->zPath);
 43961      }
 43962    }
 43963  #endif
 43964    OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
 43965             pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
 43966    return rc;
 43967  }
 43968  
 43969  /*
 43970  ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
 43971  */
 43972  #ifndef LOCKFILE_FAIL_IMMEDIATELY
 43973  # define LOCKFILE_FAIL_IMMEDIATELY 1
 43974  #endif
 43975  
 43976  #ifndef LOCKFILE_EXCLUSIVE_LOCK
 43977  # define LOCKFILE_EXCLUSIVE_LOCK 2
 43978  #endif
 43979  
 43980  /*
 43981  ** Historically, SQLite has used both the LockFile and LockFileEx functions.
 43982  ** When the LockFile function was used, it was always expected to fail
 43983  ** immediately if the lock could not be obtained.  Also, it always expected to
 43984  ** obtain an exclusive lock.  These flags are used with the LockFileEx function
 43985  ** and reflect those expectations; therefore, they should not be changed.
 43986  */
 43987  #ifndef SQLITE_LOCKFILE_FLAGS
 43988  # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
 43989                                    LOCKFILE_EXCLUSIVE_LOCK)
 43990  #endif
 43991  
 43992  /*
 43993  ** Currently, SQLite never calls the LockFileEx function without wanting the
 43994  ** call to fail immediately if the lock cannot be obtained.
 43995  */
 43996  #ifndef SQLITE_LOCKFILEEX_FLAGS
 43997  # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
 43998  #endif
 43999  
 44000  /*
 44001  ** Acquire a reader lock.
 44002  ** Different API routines are called depending on whether or not this
 44003  ** is Win9x or WinNT.
 44004  */
 44005  static int winGetReadLock(winFile *pFile){
 44006    int res;
 44007    OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 44008    if( osIsNT() ){
 44009  #if SQLITE_OS_WINCE
 44010      /*
 44011      ** NOTE: Windows CE is handled differently here due its lack of the Win32
 44012      **       API LockFileEx.
 44013      */
 44014      res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
 44015  #else
 44016      res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
 44017                        SHARED_SIZE, 0);
 44018  #endif
 44019    }
 44020  #ifdef SQLITE_WIN32_HAS_ANSI
 44021    else{
 44022      int lk;
 44023      sqlite3_randomness(sizeof(lk), &lk);
 44024      pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
 44025      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 44026                        SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 44027    }
 44028  #endif
 44029    if( res == 0 ){
 44030      pFile->lastErrno = osGetLastError();
 44031      /* No need to log a failure to lock */
 44032    }
 44033    OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
 44034    return res;
 44035  }
 44036  
 44037  /*
 44038  ** Undo a readlock
 44039  */
 44040  static int winUnlockReadLock(winFile *pFile){
 44041    int res;
 44042    DWORD lastErrno;
 44043    OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
 44044    if( osIsNT() ){
 44045      res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 44046    }
 44047  #ifdef SQLITE_WIN32_HAS_ANSI
 44048    else{
 44049      res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
 44050    }
 44051  #endif
 44052    if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
 44053      pFile->lastErrno = lastErrno;
 44054      winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
 44055                  "winUnlockReadLock", pFile->zPath);
 44056    }
 44057    OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
 44058    return res;
 44059  }
 44060  
 44061  /*
 44062  ** Lock the file with the lock specified by parameter locktype - one
 44063  ** of the following:
 44064  **
 44065  **     (1) SHARED_LOCK
 44066  **     (2) RESERVED_LOCK
 44067  **     (3) PENDING_LOCK
 44068  **     (4) EXCLUSIVE_LOCK
 44069  **
 44070  ** Sometimes when requesting one lock state, additional lock states
 44071  ** are inserted in between.  The locking might fail on one of the later
 44072  ** transitions leaving the lock state different from what it started but
 44073  ** still short of its goal.  The following chart shows the allowed
 44074  ** transitions and the inserted intermediate states:
 44075  **
 44076  **    UNLOCKED -> SHARED
 44077  **    SHARED -> RESERVED
 44078  **    SHARED -> (PENDING) -> EXCLUSIVE
 44079  **    RESERVED -> (PENDING) -> EXCLUSIVE
 44080  **    PENDING -> EXCLUSIVE
 44081  **
 44082  ** This routine will only increase a lock.  The winUnlock() routine
 44083  ** erases all locks at once and returns us immediately to locking level 0.
 44084  ** It is not possible to lower the locking level one step at a time.  You
 44085  ** must go straight to locking level 0.
 44086  */
 44087  static int winLock(sqlite3_file *id, int locktype){
 44088    int rc = SQLITE_OK;    /* Return code from subroutines */
 44089    int res = 1;           /* Result of a Windows lock call */
 44090    int newLocktype;       /* Set pFile->locktype to this value before exiting */
 44091    int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
 44092    winFile *pFile = (winFile*)id;
 44093    DWORD lastErrno = NO_ERROR;
 44094  
 44095    assert( id!=0 );
 44096    OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 44097             pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 44098  
 44099    /* If there is already a lock of this type or more restrictive on the
 44100    ** OsFile, do nothing. Don't use the end_lock: exit path, as
 44101    ** sqlite3OsEnterMutex() hasn't been called yet.
 44102    */
 44103    if( pFile->locktype>=locktype ){
 44104      OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
 44105      return SQLITE_OK;
 44106    }
 44107  
 44108    /* Do not allow any kind of write-lock on a read-only database
 44109    */
 44110    if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
 44111      return SQLITE_IOERR_LOCK;
 44112    }
 44113  
 44114    /* Make sure the locking sequence is correct
 44115    */
 44116    assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
 44117    assert( locktype!=PENDING_LOCK );
 44118    assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
 44119  
 44120    /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
 44121    ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
 44122    ** the PENDING_LOCK byte is temporary.
 44123    */
 44124    newLocktype = pFile->locktype;
 44125    if( pFile->locktype==NO_LOCK
 44126     || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
 44127    ){
 44128      int cnt = 3;
 44129      while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
 44130                                           PENDING_BYTE, 0, 1, 0))==0 ){
 44131        /* Try 3 times to get the pending lock.  This is needed to work
 44132        ** around problems caused by indexing and/or anti-virus software on
 44133        ** Windows systems.
 44134        ** If you are using this code as a model for alternative VFSes, do not
 44135        ** copy this retry logic.  It is a hack intended for Windows only.
 44136        */
 44137        lastErrno = osGetLastError();
 44138        OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
 44139                 pFile->h, cnt, res));
 44140        if( lastErrno==ERROR_INVALID_HANDLE ){
 44141          pFile->lastErrno = lastErrno;
 44142          rc = SQLITE_IOERR_LOCK;
 44143          OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
 44144                   pFile->h, cnt, sqlite3ErrName(rc)));
 44145          return rc;
 44146        }
 44147        if( cnt ) sqlite3_win32_sleep(1);
 44148      }
 44149      gotPendingLock = res;
 44150      if( !res ){
 44151        lastErrno = osGetLastError();
 44152      }
 44153    }
 44154  
 44155    /* Acquire a shared lock
 44156    */
 44157    if( locktype==SHARED_LOCK && res ){
 44158      assert( pFile->locktype==NO_LOCK );
 44159      res = winGetReadLock(pFile);
 44160      if( res ){
 44161        newLocktype = SHARED_LOCK;
 44162      }else{
 44163        lastErrno = osGetLastError();
 44164      }
 44165    }
 44166  
 44167    /* Acquire a RESERVED lock
 44168    */
 44169    if( locktype==RESERVED_LOCK && res ){
 44170      assert( pFile->locktype==SHARED_LOCK );
 44171      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
 44172      if( res ){
 44173        newLocktype = RESERVED_LOCK;
 44174      }else{
 44175        lastErrno = osGetLastError();
 44176      }
 44177    }
 44178  
 44179    /* Acquire a PENDING lock
 44180    */
 44181    if( locktype==EXCLUSIVE_LOCK && res ){
 44182      newLocktype = PENDING_LOCK;
 44183      gotPendingLock = 0;
 44184    }
 44185  
 44186    /* Acquire an EXCLUSIVE lock
 44187    */
 44188    if( locktype==EXCLUSIVE_LOCK && res ){
 44189      assert( pFile->locktype>=SHARED_LOCK );
 44190      res = winUnlockReadLock(pFile);
 44191      res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
 44192                        SHARED_SIZE, 0);
 44193      if( res ){
 44194        newLocktype = EXCLUSIVE_LOCK;
 44195      }else{
 44196        lastErrno = osGetLastError();
 44197        winGetReadLock(pFile);
 44198      }
 44199    }
 44200  
 44201    /* If we are holding a PENDING lock that ought to be released, then
 44202    ** release it now.
 44203    */
 44204    if( gotPendingLock && locktype==SHARED_LOCK ){
 44205      winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 44206    }
 44207  
 44208    /* Update the state of the lock has held in the file descriptor then
 44209    ** return the appropriate result code.
 44210    */
 44211    if( res ){
 44212      rc = SQLITE_OK;
 44213    }else{
 44214      pFile->lastErrno = lastErrno;
 44215      rc = SQLITE_BUSY;
 44216      OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
 44217               pFile->h, locktype, newLocktype));
 44218    }
 44219    pFile->locktype = (u8)newLocktype;
 44220    OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
 44221             pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 44222    return rc;
 44223  }
 44224  
 44225  /*
 44226  ** This routine checks if there is a RESERVED lock held on the specified
 44227  ** file by this or any other process. If such a lock is held, return
 44228  ** non-zero, otherwise zero.
 44229  */
 44230  static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
 44231    int res;
 44232    winFile *pFile = (winFile*)id;
 44233  
 44234    SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
 44235    OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
 44236  
 44237    assert( id!=0 );
 44238    if( pFile->locktype>=RESERVED_LOCK ){
 44239      res = 1;
 44240      OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
 44241    }else{
 44242      res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
 44243      if( res ){
 44244        winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 44245      }
 44246      res = !res;
 44247      OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
 44248    }
 44249    *pResOut = res;
 44250    OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 44251             pFile->h, pResOut, *pResOut));
 44252    return SQLITE_OK;
 44253  }
 44254  
 44255  /*
 44256  ** Lower the locking level on file descriptor id to locktype.  locktype
 44257  ** must be either NO_LOCK or SHARED_LOCK.
 44258  **
 44259  ** If the locking level of the file descriptor is already at or below
 44260  ** the requested locking level, this routine is a no-op.
 44261  **
 44262  ** It is not possible for this routine to fail if the second argument
 44263  ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
 44264  ** might return SQLITE_IOERR;
 44265  */
 44266  static int winUnlock(sqlite3_file *id, int locktype){
 44267    int type;
 44268    winFile *pFile = (winFile*)id;
 44269    int rc = SQLITE_OK;
 44270    assert( pFile!=0 );
 44271    assert( locktype<=SHARED_LOCK );
 44272    OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
 44273             pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
 44274    type = pFile->locktype;
 44275    if( type>=EXCLUSIVE_LOCK ){
 44276      winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
 44277      if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
 44278        /* This should never happen.  We should always be able to
 44279        ** reacquire the read lock */
 44280        rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
 44281                         "winUnlock", pFile->zPath);
 44282      }
 44283    }
 44284    if( type>=RESERVED_LOCK ){
 44285      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
 44286    }
 44287    if( locktype==NO_LOCK && type>=SHARED_LOCK ){
 44288      winUnlockReadLock(pFile);
 44289    }
 44290    if( type>=PENDING_LOCK ){
 44291      winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
 44292    }
 44293    pFile->locktype = (u8)locktype;
 44294    OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
 44295             pFile->h, pFile->locktype, sqlite3ErrName(rc)));
 44296    return rc;
 44297  }
 44298  
 44299  /******************************************************************************
 44300  ****************************** No-op Locking **********************************
 44301  **
 44302  ** Of the various locking implementations available, this is by far the
 44303  ** simplest:  locking is ignored.  No attempt is made to lock the database
 44304  ** file for reading or writing.
 44305  **
 44306  ** This locking mode is appropriate for use on read-only databases
 44307  ** (ex: databases that are burned into CD-ROM, for example.)  It can
 44308  ** also be used if the application employs some external mechanism to
 44309  ** prevent simultaneous access of the same database by two or more
 44310  ** database connections.  But there is a serious risk of database
 44311  ** corruption if this locking mode is used in situations where multiple
 44312  ** database connections are accessing the same database file at the same
 44313  ** time and one or more of those connections are writing.
 44314  */
 44315  
 44316  static int winNolockLock(sqlite3_file *id, int locktype){
 44317    UNUSED_PARAMETER(id);
 44318    UNUSED_PARAMETER(locktype);
 44319    return SQLITE_OK;
 44320  }
 44321  
 44322  static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
 44323    UNUSED_PARAMETER(id);
 44324    UNUSED_PARAMETER(pResOut);
 44325    return SQLITE_OK;
 44326  }
 44327  
 44328  static int winNolockUnlock(sqlite3_file *id, int locktype){
 44329    UNUSED_PARAMETER(id);
 44330    UNUSED_PARAMETER(locktype);
 44331    return SQLITE_OK;
 44332  }
 44333  
 44334  /******************* End of the no-op lock implementation *********************
 44335  ******************************************************************************/
 44336  
 44337  /*
 44338  ** If *pArg is initially negative then this is a query.  Set *pArg to
 44339  ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
 44340  **
 44341  ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
 44342  */
 44343  static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
 44344    if( *pArg<0 ){
 44345      *pArg = (pFile->ctrlFlags & mask)!=0;
 44346    }else if( (*pArg)==0 ){
 44347      pFile->ctrlFlags &= ~mask;
 44348    }else{
 44349      pFile->ctrlFlags |= mask;
 44350    }
 44351  }
 44352  
 44353  /* Forward references to VFS helper methods used for temporary files */
 44354  static int winGetTempname(sqlite3_vfs *, char **);
 44355  static int winIsDir(const void *);
 44356  static BOOL winIsDriveLetterAndColon(const char *);
 44357  
 44358  /*
 44359  ** Control and query of the open file handle.
 44360  */
 44361  static int winFileControl(sqlite3_file *id, int op, void *pArg){
 44362    winFile *pFile = (winFile*)id;
 44363    OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
 44364    switch( op ){
 44365      case SQLITE_FCNTL_LOCKSTATE: {
 44366        *(int*)pArg = pFile->locktype;
 44367        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44368        return SQLITE_OK;
 44369      }
 44370      case SQLITE_FCNTL_LAST_ERRNO: {
 44371        *(int*)pArg = (int)pFile->lastErrno;
 44372        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44373        return SQLITE_OK;
 44374      }
 44375      case SQLITE_FCNTL_CHUNK_SIZE: {
 44376        pFile->szChunk = *(int *)pArg;
 44377        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44378        return SQLITE_OK;
 44379      }
 44380      case SQLITE_FCNTL_SIZE_HINT: {
 44381        if( pFile->szChunk>0 ){
 44382          sqlite3_int64 oldSz;
 44383          int rc = winFileSize(id, &oldSz);
 44384          if( rc==SQLITE_OK ){
 44385            sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
 44386            if( newSz>oldSz ){
 44387              SimulateIOErrorBenign(1);
 44388              rc = winTruncate(id, newSz);
 44389              SimulateIOErrorBenign(0);
 44390            }
 44391          }
 44392          OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 44393          return rc;
 44394        }
 44395        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44396        return SQLITE_OK;
 44397      }
 44398      case SQLITE_FCNTL_PERSIST_WAL: {
 44399        winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
 44400        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44401        return SQLITE_OK;
 44402      }
 44403      case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
 44404        winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
 44405        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44406        return SQLITE_OK;
 44407      }
 44408      case SQLITE_FCNTL_VFSNAME: {
 44409        *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
 44410        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44411        return SQLITE_OK;
 44412      }
 44413      case SQLITE_FCNTL_WIN32_AV_RETRY: {
 44414        int *a = (int*)pArg;
 44415        if( a[0]>0 ){
 44416          winIoerrRetry = a[0];
 44417        }else{
 44418          a[0] = winIoerrRetry;
 44419        }
 44420        if( a[1]>0 ){
 44421          winIoerrRetryDelay = a[1];
 44422        }else{
 44423          a[1] = winIoerrRetryDelay;
 44424        }
 44425        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44426        return SQLITE_OK;
 44427      }
 44428      case SQLITE_FCNTL_WIN32_GET_HANDLE: {
 44429        LPHANDLE phFile = (LPHANDLE)pArg;
 44430        *phFile = pFile->h;
 44431        OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
 44432        return SQLITE_OK;
 44433      }
 44434  #ifdef SQLITE_TEST
 44435      case SQLITE_FCNTL_WIN32_SET_HANDLE: {
 44436        LPHANDLE phFile = (LPHANDLE)pArg;
 44437        HANDLE hOldFile = pFile->h;
 44438        pFile->h = *phFile;
 44439        *phFile = hOldFile;
 44440        OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
 44441                 hOldFile, pFile->h));
 44442        return SQLITE_OK;
 44443      }
 44444  #endif
 44445      case SQLITE_FCNTL_TEMPFILENAME: {
 44446        char *zTFile = 0;
 44447        int rc = winGetTempname(pFile->pVfs, &zTFile);
 44448        if( rc==SQLITE_OK ){
 44449          *(char**)pArg = zTFile;
 44450        }
 44451        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 44452        return rc;
 44453      }
 44454  #if SQLITE_MAX_MMAP_SIZE>0
 44455      case SQLITE_FCNTL_MMAP_SIZE: {
 44456        i64 newLimit = *(i64*)pArg;
 44457        int rc = SQLITE_OK;
 44458        if( newLimit>sqlite3GlobalConfig.mxMmap ){
 44459          newLimit = sqlite3GlobalConfig.mxMmap;
 44460        }
 44461  
 44462        /* The value of newLimit may be eventually cast to (SIZE_T) and passed
 44463        ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
 44464        ** least a 64-bit type. */
 44465        if( newLimit>0 && sizeof(SIZE_T)<8 ){
 44466          newLimit = (newLimit & 0x7FFFFFFF);
 44467        }
 44468  
 44469        *(i64*)pArg = pFile->mmapSizeMax;
 44470        if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
 44471          pFile->mmapSizeMax = newLimit;
 44472          if( pFile->mmapSize>0 ){
 44473            winUnmapfile(pFile);
 44474            rc = winMapfile(pFile, -1);
 44475          }
 44476        }
 44477        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
 44478        return rc;
 44479      }
 44480  #endif
 44481    }
 44482    OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
 44483    return SQLITE_NOTFOUND;
 44484  }
 44485  
 44486  /*
 44487  ** Return the sector size in bytes of the underlying block device for
 44488  ** the specified file. This is almost always 512 bytes, but may be
 44489  ** larger for some devices.
 44490  **
 44491  ** SQLite code assumes this function cannot fail. It also assumes that
 44492  ** if two files are created in the same file-system directory (i.e.
 44493  ** a database and its journal file) that the sector size will be the
 44494  ** same for both.
 44495  */
 44496  static int winSectorSize(sqlite3_file *id){
 44497    (void)id;
 44498    return SQLITE_DEFAULT_SECTOR_SIZE;
 44499  }
 44500  
 44501  /*
 44502  ** Return a vector of device characteristics.
 44503  */
 44504  static int winDeviceCharacteristics(sqlite3_file *id){
 44505    winFile *p = (winFile*)id;
 44506    return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
 44507           ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
 44508  }
 44509  
 44510  /*
 44511  ** Windows will only let you create file view mappings
 44512  ** on allocation size granularity boundaries.
 44513  ** During sqlite3_os_init() we do a GetSystemInfo()
 44514  ** to get the granularity size.
 44515  */
 44516  static SYSTEM_INFO winSysInfo;
 44517  
 44518  #ifndef SQLITE_OMIT_WAL
 44519  
 44520  /*
 44521  ** Helper functions to obtain and relinquish the global mutex. The
 44522  ** global mutex is used to protect the winLockInfo objects used by
 44523  ** this file, all of which may be shared by multiple threads.
 44524  **
 44525  ** Function winShmMutexHeld() is used to assert() that the global mutex
 44526  ** is held when required. This function is only used as part of assert()
 44527  ** statements. e.g.
 44528  **
 44529  **   winShmEnterMutex()
 44530  **     assert( winShmMutexHeld() );
 44531  **   winShmLeaveMutex()
 44532  */
 44533  static sqlite3_mutex *winBigLock = 0;
 44534  static void winShmEnterMutex(void){
 44535    sqlite3_mutex_enter(winBigLock);
 44536  }
 44537  static void winShmLeaveMutex(void){
 44538    sqlite3_mutex_leave(winBigLock);
 44539  }
 44540  #ifndef NDEBUG
 44541  static int winShmMutexHeld(void) {
 44542    return sqlite3_mutex_held(winBigLock);
 44543  }
 44544  #endif
 44545  
 44546  /*
 44547  ** Object used to represent a single file opened and mmapped to provide
 44548  ** shared memory.  When multiple threads all reference the same
 44549  ** log-summary, each thread has its own winFile object, but they all
 44550  ** point to a single instance of this object.  In other words, each
 44551  ** log-summary is opened only once per process.
 44552  **
 44553  ** winShmMutexHeld() must be true when creating or destroying
 44554  ** this object or while reading or writing the following fields:
 44555  **
 44556  **      nRef
 44557  **      pNext
 44558  **
 44559  ** The following fields are read-only after the object is created:
 44560  **
 44561  **      fid
 44562  **      zFilename
 44563  **
 44564  ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
 44565  ** winShmMutexHeld() is true when reading or writing any other field
 44566  ** in this structure.
 44567  **
 44568  */
 44569  struct winShmNode {
 44570    sqlite3_mutex *mutex;      /* Mutex to access this object */
 44571    char *zFilename;           /* Name of the file */
 44572    winFile hFile;             /* File handle from winOpen */
 44573  
 44574    int szRegion;              /* Size of shared-memory regions */
 44575    int nRegion;               /* Size of array apRegion */
 44576    u8 isReadonly;             /* True if read-only */
 44577    u8 isUnlocked;             /* True if no DMS lock held */
 44578  
 44579    struct ShmRegion {
 44580      HANDLE hMap;             /* File handle from CreateFileMapping */
 44581      void *pMap;
 44582    } *aRegion;
 44583    DWORD lastErrno;           /* The Windows errno from the last I/O error */
 44584  
 44585    int nRef;                  /* Number of winShm objects pointing to this */
 44586    winShm *pFirst;            /* All winShm objects pointing to this */
 44587    winShmNode *pNext;         /* Next in list of all winShmNode objects */
 44588  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 44589    u8 nextShmId;              /* Next available winShm.id value */
 44590  #endif
 44591  };
 44592  
 44593  /*
 44594  ** A global array of all winShmNode objects.
 44595  **
 44596  ** The winShmMutexHeld() must be true while reading or writing this list.
 44597  */
 44598  static winShmNode *winShmNodeList = 0;
 44599  
 44600  /*
 44601  ** Structure used internally by this VFS to record the state of an
 44602  ** open shared memory connection.
 44603  **
 44604  ** The following fields are initialized when this object is created and
 44605  ** are read-only thereafter:
 44606  **
 44607  **    winShm.pShmNode
 44608  **    winShm.id
 44609  **
 44610  ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
 44611  ** while accessing any read/write fields.
 44612  */
 44613  struct winShm {
 44614    winShmNode *pShmNode;      /* The underlying winShmNode object */
 44615    winShm *pNext;             /* Next winShm with the same winShmNode */
 44616    u8 hasMutex;               /* True if holding the winShmNode mutex */
 44617    u16 sharedMask;            /* Mask of shared locks held */
 44618    u16 exclMask;              /* Mask of exclusive locks held */
 44619  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 44620    u8 id;                     /* Id of this connection with its winShmNode */
 44621  #endif
 44622  };
 44623  
 44624  /*
 44625  ** Constants used for locking
 44626  */
 44627  #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
 44628  #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
 44629  
 44630  /*
 44631  ** Apply advisory locks for all n bytes beginning at ofst.
 44632  */
 44633  #define WINSHM_UNLCK  1
 44634  #define WINSHM_RDLCK  2
 44635  #define WINSHM_WRLCK  3
 44636  static int winShmSystemLock(
 44637    winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
 44638    int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
 44639    int ofst,             /* Offset to first byte to be locked/unlocked */
 44640    int nByte             /* Number of bytes to lock or unlock */
 44641  ){
 44642    int rc = 0;           /* Result code form Lock/UnlockFileEx() */
 44643  
 44644    /* Access to the winShmNode object is serialized by the caller */
 44645    assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
 44646  
 44647    OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
 44648             pFile->hFile.h, lockType, ofst, nByte));
 44649  
 44650    /* Release/Acquire the system-level lock */
 44651    if( lockType==WINSHM_UNLCK ){
 44652      rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
 44653    }else{
 44654      /* Initialize the locking parameters */
 44655      DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
 44656      if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
 44657      rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
 44658    }
 44659  
 44660    if( rc!= 0 ){
 44661      rc = SQLITE_OK;
 44662    }else{
 44663      pFile->lastErrno =  osGetLastError();
 44664      rc = SQLITE_BUSY;
 44665    }
 44666  
 44667    OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
 44668             pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
 44669             "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
 44670  
 44671    return rc;
 44672  }
 44673  
 44674  /* Forward references to VFS methods */
 44675  static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
 44676  static int winDelete(sqlite3_vfs *,const char*,int);
 44677  
 44678  /*
 44679  ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
 44680  **
 44681  ** This is not a VFS shared-memory method; it is a utility function called
 44682  ** by VFS shared-memory methods.
 44683  */
 44684  static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
 44685    winShmNode **pp;
 44686    winShmNode *p;
 44687    assert( winShmMutexHeld() );
 44688    OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
 44689             osGetCurrentProcessId(), deleteFlag));
 44690    pp = &winShmNodeList;
 44691    while( (p = *pp)!=0 ){
 44692      if( p->nRef==0 ){
 44693        int i;
 44694        if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
 44695        for(i=0; i<p->nRegion; i++){
 44696          BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
 44697          OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
 44698                   osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 44699          UNUSED_VARIABLE_VALUE(bRc);
 44700          bRc = osCloseHandle(p->aRegion[i].hMap);
 44701          OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
 44702                   osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
 44703          UNUSED_VARIABLE_VALUE(bRc);
 44704        }
 44705        if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
 44706          SimulateIOErrorBenign(1);
 44707          winClose((sqlite3_file *)&p->hFile);
 44708          SimulateIOErrorBenign(0);
 44709        }
 44710        if( deleteFlag ){
 44711          SimulateIOErrorBenign(1);
 44712          sqlite3BeginBenignMalloc();
 44713          winDelete(pVfs, p->zFilename, 0);
 44714          sqlite3EndBenignMalloc();
 44715          SimulateIOErrorBenign(0);
 44716        }
 44717        *pp = p->pNext;
 44718        sqlite3_free(p->aRegion);
 44719        sqlite3_free(p);
 44720      }else{
 44721        pp = &p->pNext;
 44722      }
 44723    }
 44724  }
 44725  
 44726  /*
 44727  ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
 44728  ** take it now. Return SQLITE_OK if successful, or an SQLite error
 44729  ** code otherwise.
 44730  **
 44731  ** If the DMS cannot be locked because this is a readonly_shm=1
 44732  ** connection and no other process already holds a lock, return
 44733  ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
 44734  */
 44735  static int winLockSharedMemory(winShmNode *pShmNode){
 44736    int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
 44737  
 44738    if( rc==SQLITE_OK ){
 44739      if( pShmNode->isReadonly ){
 44740        pShmNode->isUnlocked = 1;
 44741        winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 44742        return SQLITE_READONLY_CANTINIT;
 44743      }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
 44744        winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 44745        return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
 44746                           "winLockSharedMemory", pShmNode->zFilename);
 44747      }
 44748    }
 44749  
 44750    if( rc==SQLITE_OK ){
 44751      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 44752    }
 44753  
 44754    return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
 44755  }
 44756  
 44757  /*
 44758  ** Open the shared-memory area associated with database file pDbFd.
 44759  **
 44760  ** When opening a new shared-memory file, if no other instances of that
 44761  ** file are currently open, in this process or in other processes, then
 44762  ** the file must be truncated to zero length or have its header cleared.
 44763  */
 44764  static int winOpenSharedMemory(winFile *pDbFd){
 44765    struct winShm *p;                  /* The connection to be opened */
 44766    winShmNode *pShmNode = 0;          /* The underlying mmapped file */
 44767    int rc = SQLITE_OK;                /* Result code */
 44768    winShmNode *pNew;                  /* Newly allocated winShmNode */
 44769    int nName;                         /* Size of zName in bytes */
 44770  
 44771    assert( pDbFd->pShm==0 );    /* Not previously opened */
 44772  
 44773    /* Allocate space for the new sqlite3_shm object.  Also speculatively
 44774    ** allocate space for a new winShmNode and filename.
 44775    */
 44776    p = sqlite3MallocZero( sizeof(*p) );
 44777    if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
 44778    nName = sqlite3Strlen30(pDbFd->zPath);
 44779    pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
 44780    if( pNew==0 ){
 44781      sqlite3_free(p);
 44782      return SQLITE_IOERR_NOMEM_BKPT;
 44783    }
 44784    pNew->zFilename = (char*)&pNew[1];
 44785    sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
 44786    sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
 44787  
 44788    /* Look to see if there is an existing winShmNode that can be used.
 44789    ** If no matching winShmNode currently exists, create a new one.
 44790    */
 44791    winShmEnterMutex();
 44792    for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
 44793      /* TBD need to come up with better match here.  Perhaps
 44794      ** use FILE_ID_BOTH_DIR_INFO Structure.
 44795      */
 44796      if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
 44797    }
 44798    if( pShmNode ){
 44799      sqlite3_free(pNew);
 44800    }else{
 44801      int inFlags = SQLITE_OPEN_WAL;
 44802      int outFlags = 0;
 44803  
 44804      pShmNode = pNew;
 44805      pNew = 0;
 44806      ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
 44807      pShmNode->pNext = winShmNodeList;
 44808      winShmNodeList = pShmNode;
 44809  
 44810      if( sqlite3GlobalConfig.bCoreMutex ){
 44811        pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
 44812        if( pShmNode->mutex==0 ){
 44813          rc = SQLITE_IOERR_NOMEM_BKPT;
 44814          goto shm_open_err;
 44815        }
 44816      }
 44817  
 44818      if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
 44819        inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
 44820      }else{
 44821        inFlags |= SQLITE_OPEN_READONLY;
 44822      }
 44823      rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
 44824                   (sqlite3_file*)&pShmNode->hFile,
 44825                   inFlags, &outFlags);
 44826      if( rc!=SQLITE_OK ){
 44827        rc = winLogError(rc, osGetLastError(), "winOpenShm",
 44828                         pShmNode->zFilename);
 44829        goto shm_open_err;
 44830      }
 44831      if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
 44832  
 44833      rc = winLockSharedMemory(pShmNode);
 44834      if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
 44835    }
 44836  
 44837    /* Make the new connection a child of the winShmNode */
 44838    p->pShmNode = pShmNode;
 44839  #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
 44840    p->id = pShmNode->nextShmId++;
 44841  #endif
 44842    pShmNode->nRef++;
 44843    pDbFd->pShm = p;
 44844    winShmLeaveMutex();
 44845  
 44846    /* The reference count on pShmNode has already been incremented under
 44847    ** the cover of the winShmEnterMutex() mutex and the pointer from the
 44848    ** new (struct winShm) object to the pShmNode has been set. All that is
 44849    ** left to do is to link the new object into the linked list starting
 44850    ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
 44851    ** mutex.
 44852    */
 44853    sqlite3_mutex_enter(pShmNode->mutex);
 44854    p->pNext = pShmNode->pFirst;
 44855    pShmNode->pFirst = p;
 44856    sqlite3_mutex_leave(pShmNode->mutex);
 44857    return rc;
 44858  
 44859    /* Jump here on any error */
 44860  shm_open_err:
 44861    winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
 44862    winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
 44863    sqlite3_free(p);
 44864    sqlite3_free(pNew);
 44865    winShmLeaveMutex();
 44866    return rc;
 44867  }
 44868  
 44869  /*
 44870  ** Close a connection to shared-memory.  Delete the underlying
 44871  ** storage if deleteFlag is true.
 44872  */
 44873  static int winShmUnmap(
 44874    sqlite3_file *fd,          /* Database holding shared memory */
 44875    int deleteFlag             /* Delete after closing if true */
 44876  ){
 44877    winFile *pDbFd;       /* Database holding shared-memory */
 44878    winShm *p;            /* The connection to be closed */
 44879    winShmNode *pShmNode; /* The underlying shared-memory file */
 44880    winShm **pp;          /* For looping over sibling connections */
 44881  
 44882    pDbFd = (winFile*)fd;
 44883    p = pDbFd->pShm;
 44884    if( p==0 ) return SQLITE_OK;
 44885    pShmNode = p->pShmNode;
 44886  
 44887    /* Remove connection p from the set of connections associated
 44888    ** with pShmNode */
 44889    sqlite3_mutex_enter(pShmNode->mutex);
 44890    for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
 44891    *pp = p->pNext;
 44892  
 44893    /* Free the connection p */
 44894    sqlite3_free(p);
 44895    pDbFd->pShm = 0;
 44896    sqlite3_mutex_leave(pShmNode->mutex);
 44897  
 44898    /* If pShmNode->nRef has reached 0, then close the underlying
 44899    ** shared-memory file, too */
 44900    winShmEnterMutex();
 44901    assert( pShmNode->nRef>0 );
 44902    pShmNode->nRef--;
 44903    if( pShmNode->nRef==0 ){
 44904      winShmPurge(pDbFd->pVfs, deleteFlag);
 44905    }
 44906    winShmLeaveMutex();
 44907  
 44908    return SQLITE_OK;
 44909  }
 44910  
 44911  /*
 44912  ** Change the lock state for a shared-memory segment.
 44913  */
 44914  static int winShmLock(
 44915    sqlite3_file *fd,          /* Database file holding the shared memory */
 44916    int ofst,                  /* First lock to acquire or release */
 44917    int n,                     /* Number of locks to acquire or release */
 44918    int flags                  /* What to do with the lock */
 44919  ){
 44920    winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
 44921    winShm *p = pDbFd->pShm;              /* The shared memory being locked */
 44922    winShm *pX;                           /* For looping over all siblings */
 44923    winShmNode *pShmNode = p->pShmNode;
 44924    int rc = SQLITE_OK;                   /* Result code */
 44925    u16 mask;                             /* Mask of locks to take or release */
 44926  
 44927    assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
 44928    assert( n>=1 );
 44929    assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
 44930         || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
 44931         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
 44932         || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
 44933    assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
 44934  
 44935    mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
 44936    assert( n>1 || mask==(1<<ofst) );
 44937    sqlite3_mutex_enter(pShmNode->mutex);
 44938    if( flags & SQLITE_SHM_UNLOCK ){
 44939      u16 allMask = 0; /* Mask of locks held by siblings */
 44940  
 44941      /* See if any siblings hold this same lock */
 44942      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 44943        if( pX==p ) continue;
 44944        assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
 44945        allMask |= pX->sharedMask;
 44946      }
 44947  
 44948      /* Unlock the system-level locks */
 44949      if( (mask & allMask)==0 ){
 44950        rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
 44951      }else{
 44952        rc = SQLITE_OK;
 44953      }
 44954  
 44955      /* Undo the local locks */
 44956      if( rc==SQLITE_OK ){
 44957        p->exclMask &= ~mask;
 44958        p->sharedMask &= ~mask;
 44959      }
 44960    }else if( flags & SQLITE_SHM_SHARED ){
 44961      u16 allShared = 0;  /* Union of locks held by connections other than "p" */
 44962  
 44963      /* Find out which shared locks are already held by sibling connections.
 44964      ** If any sibling already holds an exclusive lock, go ahead and return
 44965      ** SQLITE_BUSY.
 44966      */
 44967      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 44968        if( (pX->exclMask & mask)!=0 ){
 44969          rc = SQLITE_BUSY;
 44970          break;
 44971        }
 44972        allShared |= pX->sharedMask;
 44973      }
 44974  
 44975      /* Get shared locks at the system level, if necessary */
 44976      if( rc==SQLITE_OK ){
 44977        if( (allShared & mask)==0 ){
 44978          rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
 44979        }else{
 44980          rc = SQLITE_OK;
 44981        }
 44982      }
 44983  
 44984      /* Get the local shared locks */
 44985      if( rc==SQLITE_OK ){
 44986        p->sharedMask |= mask;
 44987      }
 44988    }else{
 44989      /* Make sure no sibling connections hold locks that will block this
 44990      ** lock.  If any do, return SQLITE_BUSY right away.
 44991      */
 44992      for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
 44993        if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
 44994          rc = SQLITE_BUSY;
 44995          break;
 44996        }
 44997      }
 44998  
 44999      /* Get the exclusive locks at the system level.  Then if successful
 45000      ** also mark the local connection as being locked.
 45001      */
 45002      if( rc==SQLITE_OK ){
 45003        rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
 45004        if( rc==SQLITE_OK ){
 45005          assert( (p->sharedMask & mask)==0 );
 45006          p->exclMask |= mask;
 45007        }
 45008      }
 45009    }
 45010    sqlite3_mutex_leave(pShmNode->mutex);
 45011    OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
 45012             osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
 45013             sqlite3ErrName(rc)));
 45014    return rc;
 45015  }
 45016  
 45017  /*
 45018  ** Implement a memory barrier or memory fence on shared memory.
 45019  **
 45020  ** All loads and stores begun before the barrier must complete before
 45021  ** any load or store begun after the barrier.
 45022  */
 45023  static void winShmBarrier(
 45024    sqlite3_file *fd          /* Database holding the shared memory */
 45025  ){
 45026    UNUSED_PARAMETER(fd);
 45027    sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
 45028    winShmEnterMutex();       /* Also mutex, for redundancy */
 45029    winShmLeaveMutex();
 45030  }
 45031  
 45032  /*
 45033  ** This function is called to obtain a pointer to region iRegion of the
 45034  ** shared-memory associated with the database file fd. Shared-memory regions
 45035  ** are numbered starting from zero. Each shared-memory region is szRegion
 45036  ** bytes in size.
 45037  **
 45038  ** If an error occurs, an error code is returned and *pp is set to NULL.
 45039  **
 45040  ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
 45041  ** region has not been allocated (by any client, including one running in a
 45042  ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
 45043  ** isWrite is non-zero and the requested shared-memory region has not yet
 45044  ** been allocated, it is allocated by this function.
 45045  **
 45046  ** If the shared-memory region has already been allocated or is allocated by
 45047  ** this call as described above, then it is mapped into this processes
 45048  ** address space (if it is not already), *pp is set to point to the mapped
 45049  ** memory and SQLITE_OK returned.
 45050  */
 45051  static int winShmMap(
 45052    sqlite3_file *fd,               /* Handle open on database file */
 45053    int iRegion,                    /* Region to retrieve */
 45054    int szRegion,                   /* Size of regions */
 45055    int isWrite,                    /* True to extend file if necessary */
 45056    void volatile **pp              /* OUT: Mapped memory */
 45057  ){
 45058    winFile *pDbFd = (winFile*)fd;
 45059    winShm *pShm = pDbFd->pShm;
 45060    winShmNode *pShmNode;
 45061    DWORD protect = PAGE_READWRITE;
 45062    DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
 45063    int rc = SQLITE_OK;
 45064  
 45065    if( !pShm ){
 45066      rc = winOpenSharedMemory(pDbFd);
 45067      if( rc!=SQLITE_OK ) return rc;
 45068      pShm = pDbFd->pShm;
 45069    }
 45070    pShmNode = pShm->pShmNode;
 45071  
 45072    sqlite3_mutex_enter(pShmNode->mutex);
 45073    if( pShmNode->isUnlocked ){
 45074      rc = winLockSharedMemory(pShmNode);
 45075      if( rc!=SQLITE_OK ) goto shmpage_out;
 45076      pShmNode->isUnlocked = 0;
 45077    }
 45078    assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
 45079  
 45080    if( pShmNode->nRegion<=iRegion ){
 45081      struct ShmRegion *apNew;           /* New aRegion[] array */
 45082      int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
 45083      sqlite3_int64 sz;                  /* Current size of wal-index file */
 45084  
 45085      pShmNode->szRegion = szRegion;
 45086  
 45087      /* The requested region is not mapped into this processes address space.
 45088      ** Check to see if it has been allocated (i.e. if the wal-index file is
 45089      ** large enough to contain the requested region).
 45090      */
 45091      rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
 45092      if( rc!=SQLITE_OK ){
 45093        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 45094                         "winShmMap1", pDbFd->zPath);
 45095        goto shmpage_out;
 45096      }
 45097  
 45098      if( sz<nByte ){
 45099        /* The requested memory region does not exist. If isWrite is set to
 45100        ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
 45101        **
 45102        ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
 45103        ** the requested memory region.
 45104        */
 45105        if( !isWrite ) goto shmpage_out;
 45106        rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
 45107        if( rc!=SQLITE_OK ){
 45108          rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
 45109                           "winShmMap2", pDbFd->zPath);
 45110          goto shmpage_out;
 45111        }
 45112      }
 45113  
 45114      /* Map the requested memory region into this processes address space. */
 45115      apNew = (struct ShmRegion *)sqlite3_realloc64(
 45116          pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
 45117      );
 45118      if( !apNew ){
 45119        rc = SQLITE_IOERR_NOMEM_BKPT;
 45120        goto shmpage_out;
 45121      }
 45122      pShmNode->aRegion = apNew;
 45123  
 45124      if( pShmNode->isReadonly ){
 45125        protect = PAGE_READONLY;
 45126        flags = FILE_MAP_READ;
 45127      }
 45128  
 45129      while( pShmNode->nRegion<=iRegion ){
 45130        HANDLE hMap = NULL;         /* file-mapping handle */
 45131        void *pMap = 0;             /* Mapped memory region */
 45132  
 45133  #if SQLITE_OS_WINRT
 45134        hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
 45135            NULL, protect, nByte, NULL
 45136        );
 45137  #elif defined(SQLITE_WIN32_HAS_WIDE)
 45138        hMap = osCreateFileMappingW(pShmNode->hFile.h,
 45139            NULL, protect, 0, nByte, NULL
 45140        );
 45141  #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
 45142        hMap = osCreateFileMappingA(pShmNode->hFile.h,
 45143            NULL, protect, 0, nByte, NULL
 45144        );
 45145  #endif
 45146        OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
 45147                 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
 45148                 hMap ? "ok" : "failed"));
 45149        if( hMap ){
 45150          int iOffset = pShmNode->nRegion*szRegion;
 45151          int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 45152  #if SQLITE_OS_WINRT
 45153          pMap = osMapViewOfFileFromApp(hMap, flags,
 45154              iOffset - iOffsetShift, szRegion + iOffsetShift
 45155          );
 45156  #else
 45157          pMap = osMapViewOfFile(hMap, flags,
 45158              0, iOffset - iOffsetShift, szRegion + iOffsetShift
 45159          );
 45160  #endif
 45161          OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
 45162                   osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
 45163                   szRegion, pMap ? "ok" : "failed"));
 45164        }
 45165        if( !pMap ){
 45166          pShmNode->lastErrno = osGetLastError();
 45167          rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
 45168                           "winShmMap3", pDbFd->zPath);
 45169          if( hMap ) osCloseHandle(hMap);
 45170          goto shmpage_out;
 45171        }
 45172  
 45173        pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
 45174        pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
 45175        pShmNode->nRegion++;
 45176      }
 45177    }
 45178  
 45179  shmpage_out:
 45180    if( pShmNode->nRegion>iRegion ){
 45181      int iOffset = iRegion*szRegion;
 45182      int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
 45183      char *p = (char *)pShmNode->aRegion[iRegion].pMap;
 45184      *pp = (void *)&p[iOffsetShift];
 45185    }else{
 45186      *pp = 0;
 45187    }
 45188    if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
 45189    sqlite3_mutex_leave(pShmNode->mutex);
 45190    return rc;
 45191  }
 45192  
 45193  #else
 45194  # define winShmMap     0
 45195  # define winShmLock    0
 45196  # define winShmBarrier 0
 45197  # define winShmUnmap   0
 45198  #endif /* #ifndef SQLITE_OMIT_WAL */
 45199  
 45200  /*
 45201  ** Cleans up the mapped region of the specified file, if any.
 45202  */
 45203  #if SQLITE_MAX_MMAP_SIZE>0
 45204  static int winUnmapfile(winFile *pFile){
 45205    assert( pFile!=0 );
 45206    OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
 45207             "mmapSize=%lld, mmapSizeMax=%lld\n",
 45208             osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
 45209             pFile->mmapSize, pFile->mmapSizeMax));
 45210    if( pFile->pMapRegion ){
 45211      if( !osUnmapViewOfFile(pFile->pMapRegion) ){
 45212        pFile->lastErrno = osGetLastError();
 45213        OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
 45214                 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
 45215                 pFile->pMapRegion));
 45216        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 45217                           "winUnmapfile1", pFile->zPath);
 45218      }
 45219      pFile->pMapRegion = 0;
 45220      pFile->mmapSize = 0;
 45221    }
 45222    if( pFile->hMap!=NULL ){
 45223      if( !osCloseHandle(pFile->hMap) ){
 45224        pFile->lastErrno = osGetLastError();
 45225        OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
 45226                 osGetCurrentProcessId(), pFile, pFile->hMap));
 45227        return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
 45228                           "winUnmapfile2", pFile->zPath);
 45229      }
 45230      pFile->hMap = NULL;
 45231    }
 45232    OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 45233             osGetCurrentProcessId(), pFile));
 45234    return SQLITE_OK;
 45235  }
 45236  
 45237  /*
 45238  ** Memory map or remap the file opened by file-descriptor pFd (if the file
 45239  ** is already mapped, the existing mapping is replaced by the new). Or, if
 45240  ** there already exists a mapping for this file, and there are still
 45241  ** outstanding xFetch() references to it, this function is a no-op.
 45242  **
 45243  ** If parameter nByte is non-negative, then it is the requested size of
 45244  ** the mapping to create. Otherwise, if nByte is less than zero, then the
 45245  ** requested size is the size of the file on disk. The actual size of the
 45246  ** created mapping is either the requested size or the value configured
 45247  ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
 45248  **
 45249  ** SQLITE_OK is returned if no error occurs (even if the mapping is not
 45250  ** recreated as a result of outstanding references) or an SQLite error
 45251  ** code otherwise.
 45252  */
 45253  static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
 45254    sqlite3_int64 nMap = nByte;
 45255    int rc;
 45256  
 45257    assert( nMap>=0 || pFd->nFetchOut==0 );
 45258    OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
 45259             osGetCurrentProcessId(), pFd, nByte));
 45260  
 45261    if( pFd->nFetchOut>0 ) return SQLITE_OK;
 45262  
 45263    if( nMap<0 ){
 45264      rc = winFileSize((sqlite3_file*)pFd, &nMap);
 45265      if( rc ){
 45266        OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
 45267                 osGetCurrentProcessId(), pFd));
 45268        return SQLITE_IOERR_FSTAT;
 45269      }
 45270    }
 45271    if( nMap>pFd->mmapSizeMax ){
 45272      nMap = pFd->mmapSizeMax;
 45273    }
 45274    nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
 45275  
 45276    if( nMap==0 && pFd->mmapSize>0 ){
 45277      winUnmapfile(pFd);
 45278    }
 45279    if( nMap!=pFd->mmapSize ){
 45280      void *pNew = 0;
 45281      DWORD protect = PAGE_READONLY;
 45282      DWORD flags = FILE_MAP_READ;
 45283  
 45284      winUnmapfile(pFd);
 45285  #ifdef SQLITE_MMAP_READWRITE
 45286      if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
 45287        protect = PAGE_READWRITE;
 45288        flags |= FILE_MAP_WRITE;
 45289      }
 45290  #endif
 45291  #if SQLITE_OS_WINRT
 45292      pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
 45293  #elif defined(SQLITE_WIN32_HAS_WIDE)
 45294      pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
 45295                                  (DWORD)((nMap>>32) & 0xffffffff),
 45296                                  (DWORD)(nMap & 0xffffffff), NULL);
 45297  #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
 45298      pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
 45299                                  (DWORD)((nMap>>32) & 0xffffffff),
 45300                                  (DWORD)(nMap & 0xffffffff), NULL);
 45301  #endif
 45302      if( pFd->hMap==NULL ){
 45303        pFd->lastErrno = osGetLastError();
 45304        rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 45305                         "winMapfile1", pFd->zPath);
 45306        /* Log the error, but continue normal operation using xRead/xWrite */
 45307        OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
 45308                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 45309        return SQLITE_OK;
 45310      }
 45311      assert( (nMap % winSysInfo.dwPageSize)==0 );
 45312      assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
 45313  #if SQLITE_OS_WINRT
 45314      pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
 45315  #else
 45316      pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
 45317  #endif
 45318      if( pNew==NULL ){
 45319        osCloseHandle(pFd->hMap);
 45320        pFd->hMap = NULL;
 45321        pFd->lastErrno = osGetLastError();
 45322        rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
 45323                         "winMapfile2", pFd->zPath);
 45324        /* Log the error, but continue normal operation using xRead/xWrite */
 45325        OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
 45326                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 45327        return SQLITE_OK;
 45328      }
 45329      pFd->pMapRegion = pNew;
 45330      pFd->mmapSize = nMap;
 45331    }
 45332  
 45333    OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 45334             osGetCurrentProcessId(), pFd));
 45335    return SQLITE_OK;
 45336  }
 45337  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 45338  
 45339  /*
 45340  ** If possible, return a pointer to a mapping of file fd starting at offset
 45341  ** iOff. The mapping must be valid for at least nAmt bytes.
 45342  **
 45343  ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
 45344  ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
 45345  ** Finally, if an error does occur, return an SQLite error code. The final
 45346  ** value of *pp is undefined in this case.
 45347  **
 45348  ** If this function does return a pointer, the caller must eventually
 45349  ** release the reference by calling winUnfetch().
 45350  */
 45351  static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 45352  #if SQLITE_MAX_MMAP_SIZE>0
 45353    winFile *pFd = (winFile*)fd;   /* The underlying database file */
 45354  #endif
 45355    *pp = 0;
 45356  
 45357    OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
 45358             osGetCurrentProcessId(), fd, iOff, nAmt, pp));
 45359  
 45360  #if SQLITE_MAX_MMAP_SIZE>0
 45361    if( pFd->mmapSizeMax>0 ){
 45362      if( pFd->pMapRegion==0 ){
 45363        int rc = winMapfile(pFd, -1);
 45364        if( rc!=SQLITE_OK ){
 45365          OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
 45366                   osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
 45367          return rc;
 45368        }
 45369      }
 45370      if( pFd->mmapSize >= iOff+nAmt ){
 45371        *pp = &((u8 *)pFd->pMapRegion)[iOff];
 45372        pFd->nFetchOut++;
 45373      }
 45374    }
 45375  #endif
 45376  
 45377    OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
 45378             osGetCurrentProcessId(), fd, pp, *pp));
 45379    return SQLITE_OK;
 45380  }
 45381  
 45382  /*
 45383  ** If the third argument is non-NULL, then this function releases a
 45384  ** reference obtained by an earlier call to winFetch(). The second
 45385  ** argument passed to this function must be the same as the corresponding
 45386  ** argument that was passed to the winFetch() invocation.
 45387  **
 45388  ** Or, if the third argument is NULL, then this function is being called
 45389  ** to inform the VFS layer that, according to POSIX, any existing mapping
 45390  ** may now be invalid and should be unmapped.
 45391  */
 45392  static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
 45393  #if SQLITE_MAX_MMAP_SIZE>0
 45394    winFile *pFd = (winFile*)fd;   /* The underlying database file */
 45395  
 45396    /* If p==0 (unmap the entire file) then there must be no outstanding
 45397    ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
 45398    ** then there must be at least one outstanding.  */
 45399    assert( (p==0)==(pFd->nFetchOut==0) );
 45400  
 45401    /* If p!=0, it must match the iOff value. */
 45402    assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
 45403  
 45404    OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
 45405             osGetCurrentProcessId(), pFd, iOff, p));
 45406  
 45407    if( p ){
 45408      pFd->nFetchOut--;
 45409    }else{
 45410      /* FIXME:  If Windows truly always prevents truncating or deleting a
 45411      ** file while a mapping is held, then the following winUnmapfile() call
 45412      ** is unnecessary can be omitted - potentially improving
 45413      ** performance.  */
 45414      winUnmapfile(pFd);
 45415    }
 45416  
 45417    assert( pFd->nFetchOut>=0 );
 45418  #endif
 45419  
 45420    OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
 45421             osGetCurrentProcessId(), fd));
 45422    return SQLITE_OK;
 45423  }
 45424  
 45425  /*
 45426  ** Here ends the implementation of all sqlite3_file methods.
 45427  **
 45428  ********************** End sqlite3_file Methods *******************************
 45429  ******************************************************************************/
 45430  
 45431  /*
 45432  ** This vector defines all the methods that can operate on an
 45433  ** sqlite3_file for win32.
 45434  */
 45435  static const sqlite3_io_methods winIoMethod = {
 45436    3,                              /* iVersion */
 45437    winClose,                       /* xClose */
 45438    winRead,                        /* xRead */
 45439    winWrite,                       /* xWrite */
 45440    winTruncate,                    /* xTruncate */
 45441    winSync,                        /* xSync */
 45442    winFileSize,                    /* xFileSize */
 45443    winLock,                        /* xLock */
 45444    winUnlock,                      /* xUnlock */
 45445    winCheckReservedLock,           /* xCheckReservedLock */
 45446    winFileControl,                 /* xFileControl */
 45447    winSectorSize,                  /* xSectorSize */
 45448    winDeviceCharacteristics,       /* xDeviceCharacteristics */
 45449    winShmMap,                      /* xShmMap */
 45450    winShmLock,                     /* xShmLock */
 45451    winShmBarrier,                  /* xShmBarrier */
 45452    winShmUnmap,                    /* xShmUnmap */
 45453    winFetch,                       /* xFetch */
 45454    winUnfetch                      /* xUnfetch */
 45455  };
 45456  
 45457  /*
 45458  ** This vector defines all the methods that can operate on an
 45459  ** sqlite3_file for win32 without performing any locking.
 45460  */
 45461  static const sqlite3_io_methods winIoNolockMethod = {
 45462    3,                              /* iVersion */
 45463    winClose,                       /* xClose */
 45464    winRead,                        /* xRead */
 45465    winWrite,                       /* xWrite */
 45466    winTruncate,                    /* xTruncate */
 45467    winSync,                        /* xSync */
 45468    winFileSize,                    /* xFileSize */
 45469    winNolockLock,                  /* xLock */
 45470    winNolockUnlock,                /* xUnlock */
 45471    winNolockCheckReservedLock,     /* xCheckReservedLock */
 45472    winFileControl,                 /* xFileControl */
 45473    winSectorSize,                  /* xSectorSize */
 45474    winDeviceCharacteristics,       /* xDeviceCharacteristics */
 45475    winShmMap,                      /* xShmMap */
 45476    winShmLock,                     /* xShmLock */
 45477    winShmBarrier,                  /* xShmBarrier */
 45478    winShmUnmap,                    /* xShmUnmap */
 45479    winFetch,                       /* xFetch */
 45480    winUnfetch                      /* xUnfetch */
 45481  };
 45482  
 45483  static winVfsAppData winAppData = {
 45484    &winIoMethod,       /* pMethod */
 45485    0,                  /* pAppData */
 45486    0                   /* bNoLock */
 45487  };
 45488  
 45489  static winVfsAppData winNolockAppData = {
 45490    &winIoNolockMethod, /* pMethod */
 45491    0,                  /* pAppData */
 45492    1                   /* bNoLock */
 45493  };
 45494  
 45495  /****************************************************************************
 45496  **************************** sqlite3_vfs methods ****************************
 45497  **
 45498  ** This division contains the implementation of methods on the
 45499  ** sqlite3_vfs object.
 45500  */
 45501  
 45502  #if defined(__CYGWIN__)
 45503  /*
 45504  ** Convert a filename from whatever the underlying operating system
 45505  ** supports for filenames into UTF-8.  Space to hold the result is
 45506  ** obtained from malloc and must be freed by the calling function.
 45507  */
 45508  static char *winConvertToUtf8Filename(const void *zFilename){
 45509    char *zConverted = 0;
 45510    if( osIsNT() ){
 45511      zConverted = winUnicodeToUtf8(zFilename);
 45512    }
 45513  #ifdef SQLITE_WIN32_HAS_ANSI
 45514    else{
 45515      zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
 45516    }
 45517  #endif
 45518    /* caller will handle out of memory */
 45519    return zConverted;
 45520  }
 45521  #endif
 45522  
 45523  /*
 45524  ** Convert a UTF-8 filename into whatever form the underlying
 45525  ** operating system wants filenames in.  Space to hold the result
 45526  ** is obtained from malloc and must be freed by the calling
 45527  ** function.
 45528  */
 45529  static void *winConvertFromUtf8Filename(const char *zFilename){
 45530    void *zConverted = 0;
 45531    if( osIsNT() ){
 45532      zConverted = winUtf8ToUnicode(zFilename);
 45533    }
 45534  #ifdef SQLITE_WIN32_HAS_ANSI
 45535    else{
 45536      zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
 45537    }
 45538  #endif
 45539    /* caller will handle out of memory */
 45540    return zConverted;
 45541  }
 45542  
 45543  /*
 45544  ** This function returns non-zero if the specified UTF-8 string buffer
 45545  ** ends with a directory separator character or one was successfully
 45546  ** added to it.
 45547  */
 45548  static int winMakeEndInDirSep(int nBuf, char *zBuf){
 45549    if( zBuf ){
 45550      int nLen = sqlite3Strlen30(zBuf);
 45551      if( nLen>0 ){
 45552        if( winIsDirSep(zBuf[nLen-1]) ){
 45553          return 1;
 45554        }else if( nLen+1<nBuf ){
 45555          zBuf[nLen] = winGetDirSep();
 45556          zBuf[nLen+1] = '\0';
 45557          return 1;
 45558        }
 45559      }
 45560    }
 45561    return 0;
 45562  }
 45563  
 45564  /*
 45565  ** Create a temporary file name and store the resulting pointer into pzBuf.
 45566  ** The pointer returned in pzBuf must be freed via sqlite3_free().
 45567  */
 45568  static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
 45569    static char zChars[] =
 45570      "abcdefghijklmnopqrstuvwxyz"
 45571      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 45572      "0123456789";
 45573    size_t i, j;
 45574    int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
 45575    int nMax, nBuf, nDir, nLen;
 45576    char *zBuf;
 45577  
 45578    /* It's odd to simulate an io-error here, but really this is just
 45579    ** using the io-error infrastructure to test that SQLite handles this
 45580    ** function failing.
 45581    */
 45582    SimulateIOError( return SQLITE_IOERR );
 45583  
 45584    /* Allocate a temporary buffer to store the fully qualified file
 45585    ** name for the temporary file.  If this fails, we cannot continue.
 45586    */
 45587    nMax = pVfs->mxPathname; nBuf = nMax + 2;
 45588    zBuf = sqlite3MallocZero( nBuf );
 45589    if( !zBuf ){
 45590      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45591      return SQLITE_IOERR_NOMEM_BKPT;
 45592    }
 45593  
 45594    /* Figure out the effective temporary directory.  First, check if one
 45595    ** has been explicitly set by the application; otherwise, use the one
 45596    ** configured by the operating system.
 45597    */
 45598    nDir = nMax - (nPre + 15);
 45599    assert( nDir>0 );
 45600    if( sqlite3_temp_directory ){
 45601      int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
 45602      if( nDirLen>0 ){
 45603        if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
 45604          nDirLen++;
 45605        }
 45606        if( nDirLen>nDir ){
 45607          sqlite3_free(zBuf);
 45608          OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 45609          return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
 45610        }
 45611        sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
 45612      }
 45613    }
 45614  #if defined(__CYGWIN__)
 45615    else{
 45616      static const char *azDirs[] = {
 45617         0, /* getenv("SQLITE_TMPDIR") */
 45618         0, /* getenv("TMPDIR") */
 45619         0, /* getenv("TMP") */
 45620         0, /* getenv("TEMP") */
 45621         0, /* getenv("USERPROFILE") */
 45622         "/var/tmp",
 45623         "/usr/tmp",
 45624         "/tmp",
 45625         ".",
 45626         0        /* List terminator */
 45627      };
 45628      unsigned int i;
 45629      const char *zDir = 0;
 45630  
 45631      if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
 45632      if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
 45633      if( !azDirs[2] ) azDirs[2] = getenv("TMP");
 45634      if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
 45635      if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
 45636      for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
 45637        void *zConverted;
 45638        if( zDir==0 ) continue;
 45639        /* If the path starts with a drive letter followed by the colon
 45640        ** character, assume it is already a native Win32 path; otherwise,
 45641        ** it must be converted to a native Win32 path via the Cygwin API
 45642        ** prior to using it.
 45643        */
 45644        if( winIsDriveLetterAndColon(zDir) ){
 45645          zConverted = winConvertFromUtf8Filename(zDir);
 45646          if( !zConverted ){
 45647            sqlite3_free(zBuf);
 45648            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45649            return SQLITE_IOERR_NOMEM_BKPT;
 45650          }
 45651          if( winIsDir(zConverted) ){
 45652            sqlite3_snprintf(nMax, zBuf, "%s", zDir);
 45653            sqlite3_free(zConverted);
 45654            break;
 45655          }
 45656          sqlite3_free(zConverted);
 45657        }else{
 45658          zConverted = sqlite3MallocZero( nMax+1 );
 45659          if( !zConverted ){
 45660            sqlite3_free(zBuf);
 45661            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45662            return SQLITE_IOERR_NOMEM_BKPT;
 45663          }
 45664          if( cygwin_conv_path(
 45665                  osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
 45666                  zConverted, nMax+1)<0 ){
 45667            sqlite3_free(zConverted);
 45668            sqlite3_free(zBuf);
 45669            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
 45670            return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
 45671                               "winGetTempname2", zDir);
 45672          }
 45673          if( winIsDir(zConverted) ){
 45674            /* At this point, we know the candidate directory exists and should
 45675            ** be used.  However, we may need to convert the string containing
 45676            ** its name into UTF-8 (i.e. if it is UTF-16 right now).
 45677            */
 45678            char *zUtf8 = winConvertToUtf8Filename(zConverted);
 45679            if( !zUtf8 ){
 45680              sqlite3_free(zConverted);
 45681              sqlite3_free(zBuf);
 45682              OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45683              return SQLITE_IOERR_NOMEM_BKPT;
 45684            }
 45685            sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 45686            sqlite3_free(zUtf8);
 45687            sqlite3_free(zConverted);
 45688            break;
 45689          }
 45690          sqlite3_free(zConverted);
 45691        }
 45692      }
 45693    }
 45694  #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 45695    else if( osIsNT() ){
 45696      char *zMulti;
 45697      LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
 45698      if( !zWidePath ){
 45699        sqlite3_free(zBuf);
 45700        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45701        return SQLITE_IOERR_NOMEM_BKPT;
 45702      }
 45703      if( osGetTempPathW(nMax, zWidePath)==0 ){
 45704        sqlite3_free(zWidePath);
 45705        sqlite3_free(zBuf);
 45706        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 45707        return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 45708                           "winGetTempname2", 0);
 45709      }
 45710      zMulti = winUnicodeToUtf8(zWidePath);
 45711      if( zMulti ){
 45712        sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
 45713        sqlite3_free(zMulti);
 45714        sqlite3_free(zWidePath);
 45715      }else{
 45716        sqlite3_free(zWidePath);
 45717        sqlite3_free(zBuf);
 45718        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45719        return SQLITE_IOERR_NOMEM_BKPT;
 45720      }
 45721    }
 45722  #ifdef SQLITE_WIN32_HAS_ANSI
 45723    else{
 45724      char *zUtf8;
 45725      char *zMbcsPath = sqlite3MallocZero( nMax );
 45726      if( !zMbcsPath ){
 45727        sqlite3_free(zBuf);
 45728        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45729        return SQLITE_IOERR_NOMEM_BKPT;
 45730      }
 45731      if( osGetTempPathA(nMax, zMbcsPath)==0 ){
 45732        sqlite3_free(zBuf);
 45733        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
 45734        return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
 45735                           "winGetTempname3", 0);
 45736      }
 45737      zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
 45738      if( zUtf8 ){
 45739        sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
 45740        sqlite3_free(zUtf8);
 45741      }else{
 45742        sqlite3_free(zBuf);
 45743        OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
 45744        return SQLITE_IOERR_NOMEM_BKPT;
 45745      }
 45746    }
 45747  #endif /* SQLITE_WIN32_HAS_ANSI */
 45748  #endif /* !SQLITE_OS_WINRT */
 45749  
 45750    /*
 45751    ** Check to make sure the temporary directory ends with an appropriate
 45752    ** separator.  If it does not and there is not enough space left to add
 45753    ** one, fail.
 45754    */
 45755    if( !winMakeEndInDirSep(nDir+1, zBuf) ){
 45756      sqlite3_free(zBuf);
 45757      OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 45758      return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
 45759    }
 45760  
 45761    /*
 45762    ** Check that the output buffer is large enough for the temporary file
 45763    ** name in the following format:
 45764    **
 45765    **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
 45766    **
 45767    ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
 45768    ** account for the space used by the 15 character random suffix and the
 45769    ** two trailing NUL characters.  The final directory separator character
 45770    ** has already added if it was not already present.
 45771    */
 45772    nLen = sqlite3Strlen30(zBuf);
 45773    if( (nLen + nPre + 17) > nBuf ){
 45774      sqlite3_free(zBuf);
 45775      OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
 45776      return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
 45777    }
 45778  
 45779    sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
 45780  
 45781    j = sqlite3Strlen30(zBuf);
 45782    sqlite3_randomness(15, &zBuf[j]);
 45783    for(i=0; i<15; i++, j++){
 45784      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
 45785    }
 45786    zBuf[j] = 0;
 45787    zBuf[j+1] = 0;
 45788    *pzBuf = zBuf;
 45789  
 45790    OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
 45791    return SQLITE_OK;
 45792  }
 45793  
 45794  /*
 45795  ** Return TRUE if the named file is really a directory.  Return false if
 45796  ** it is something other than a directory, or if there is any kind of memory
 45797  ** allocation failure.
 45798  */
 45799  static int winIsDir(const void *zConverted){
 45800    DWORD attr;
 45801    int rc = 0;
 45802    DWORD lastErrno;
 45803  
 45804    if( osIsNT() ){
 45805      int cnt = 0;
 45806      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 45807      memset(&sAttrData, 0, sizeof(sAttrData));
 45808      while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 45809                               GetFileExInfoStandard,
 45810                               &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 45811      if( !rc ){
 45812        return 0; /* Invalid name? */
 45813      }
 45814      attr = sAttrData.dwFileAttributes;
 45815  #if SQLITE_OS_WINCE==0
 45816    }else{
 45817      attr = osGetFileAttributesA((char*)zConverted);
 45818  #endif
 45819    }
 45820    return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
 45821  }
 45822  
 45823  /* forward reference */
 45824  static int winAccess(
 45825    sqlite3_vfs *pVfs,         /* Not used on win32 */
 45826    const char *zFilename,     /* Name of file to check */
 45827    int flags,                 /* Type of test to make on this file */
 45828    int *pResOut               /* OUT: Result */
 45829  );
 45830  
 45831  /*
 45832  ** Open a file.
 45833  */
 45834  static int winOpen(
 45835    sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
 45836    const char *zName,        /* Name of the file (UTF-8) */
 45837    sqlite3_file *id,         /* Write the SQLite file handle here */
 45838    int flags,                /* Open mode flags */
 45839    int *pOutFlags            /* Status return flags */
 45840  ){
 45841    HANDLE h;
 45842    DWORD lastErrno = 0;
 45843    DWORD dwDesiredAccess;
 45844    DWORD dwShareMode;
 45845    DWORD dwCreationDisposition;
 45846    DWORD dwFlagsAndAttributes = 0;
 45847  #if SQLITE_OS_WINCE
 45848    int isTemp = 0;
 45849  #endif
 45850    winVfsAppData *pAppData;
 45851    winFile *pFile = (winFile*)id;
 45852    void *zConverted;              /* Filename in OS encoding */
 45853    const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
 45854    int cnt = 0;
 45855  
 45856    /* If argument zPath is a NULL pointer, this function is required to open
 45857    ** a temporary file. Use this buffer to store the file name in.
 45858    */
 45859    char *zTmpname = 0; /* For temporary filename, if necessary. */
 45860  
 45861    int rc = SQLITE_OK;            /* Function Return Code */
 45862  #if !defined(NDEBUG) || SQLITE_OS_WINCE
 45863    int eType = flags&0xFFFFFF00;  /* Type of file to open */
 45864  #endif
 45865  
 45866    int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
 45867    int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
 45868    int isCreate     = (flags & SQLITE_OPEN_CREATE);
 45869    int isReadonly   = (flags & SQLITE_OPEN_READONLY);
 45870    int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
 45871  
 45872  #ifndef NDEBUG
 45873    int isOpenJournal = (isCreate && (
 45874          eType==SQLITE_OPEN_MASTER_JOURNAL
 45875       || eType==SQLITE_OPEN_MAIN_JOURNAL
 45876       || eType==SQLITE_OPEN_WAL
 45877    ));
 45878  #endif
 45879  
 45880    OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
 45881             zUtf8Name, id, flags, pOutFlags));
 45882  
 45883    /* Check the following statements are true:
 45884    **
 45885    **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
 45886    **   (b) if CREATE is set, then READWRITE must also be set, and
 45887    **   (c) if EXCLUSIVE is set, then CREATE must also be set.
 45888    **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
 45889    */
 45890    assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
 45891    assert(isCreate==0 || isReadWrite);
 45892    assert(isExclusive==0 || isCreate);
 45893    assert(isDelete==0 || isCreate);
 45894  
 45895    /* The main DB, main journal, WAL file and master journal are never
 45896    ** automatically deleted. Nor are they ever temporary files.  */
 45897    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
 45898    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
 45899    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
 45900    assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 45901  
 45902    /* Assert that the upper layer has set one of the "file-type" flags. */
 45903    assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
 45904         || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
 45905         || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
 45906         || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
 45907    );
 45908  
 45909    assert( pFile!=0 );
 45910    memset(pFile, 0, sizeof(winFile));
 45911    pFile->h = INVALID_HANDLE_VALUE;
 45912  
 45913  #if SQLITE_OS_WINRT
 45914    if( !zUtf8Name && !sqlite3_temp_directory ){
 45915      sqlite3_log(SQLITE_ERROR,
 45916          "sqlite3_temp_directory variable should be set for WinRT");
 45917    }
 45918  #endif
 45919  
 45920    /* If the second argument to this function is NULL, generate a
 45921    ** temporary file name to use
 45922    */
 45923    if( !zUtf8Name ){
 45924      assert( isDelete && !isOpenJournal );
 45925      rc = winGetTempname(pVfs, &zTmpname);
 45926      if( rc!=SQLITE_OK ){
 45927        OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
 45928        return rc;
 45929      }
 45930      zUtf8Name = zTmpname;
 45931    }
 45932  
 45933    /* Database filenames are double-zero terminated if they are not
 45934    ** URIs with parameters.  Hence, they can always be passed into
 45935    ** sqlite3_uri_parameter().
 45936    */
 45937    assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
 45938         zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
 45939  
 45940    /* Convert the filename to the system encoding. */
 45941    zConverted = winConvertFromUtf8Filename(zUtf8Name);
 45942    if( zConverted==0 ){
 45943      sqlite3_free(zTmpname);
 45944      OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
 45945      return SQLITE_IOERR_NOMEM_BKPT;
 45946    }
 45947  
 45948    if( winIsDir(zConverted) ){
 45949      sqlite3_free(zConverted);
 45950      sqlite3_free(zTmpname);
 45951      OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
 45952      return SQLITE_CANTOPEN_ISDIR;
 45953    }
 45954  
 45955    if( isReadWrite ){
 45956      dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
 45957    }else{
 45958      dwDesiredAccess = GENERIC_READ;
 45959    }
 45960  
 45961    /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
 45962    ** created. SQLite doesn't use it to indicate "exclusive access"
 45963    ** as it is usually understood.
 45964    */
 45965    if( isExclusive ){
 45966      /* Creates a new file, only if it does not already exist. */
 45967      /* If the file exists, it fails. */
 45968      dwCreationDisposition = CREATE_NEW;
 45969    }else if( isCreate ){
 45970      /* Open existing file, or create if it doesn't exist */
 45971      dwCreationDisposition = OPEN_ALWAYS;
 45972    }else{
 45973      /* Opens a file, only if it exists. */
 45974      dwCreationDisposition = OPEN_EXISTING;
 45975    }
 45976  
 45977    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
 45978  
 45979    if( isDelete ){
 45980  #if SQLITE_OS_WINCE
 45981      dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
 45982      isTemp = 1;
 45983  #else
 45984      dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
 45985                                 | FILE_ATTRIBUTE_HIDDEN
 45986                                 | FILE_FLAG_DELETE_ON_CLOSE;
 45987  #endif
 45988    }else{
 45989      dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
 45990    }
 45991    /* Reports from the internet are that performance is always
 45992    ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
 45993  #if SQLITE_OS_WINCE
 45994    dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
 45995  #endif
 45996  
 45997    if( osIsNT() ){
 45998  #if SQLITE_OS_WINRT
 45999      CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
 46000      extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
 46001      extendedParameters.dwFileAttributes =
 46002              dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
 46003      extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
 46004      extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
 46005      extendedParameters.lpSecurityAttributes = NULL;
 46006      extendedParameters.hTemplateFile = NULL;
 46007      do{
 46008        h = osCreateFile2((LPCWSTR)zConverted,
 46009                          dwDesiredAccess,
 46010                          dwShareMode,
 46011                          dwCreationDisposition,
 46012                          &extendedParameters);
 46013        if( h!=INVALID_HANDLE_VALUE ) break;
 46014        if( isReadWrite ){
 46015          int rc2, isRO = 0;
 46016          sqlite3BeginBenignMalloc();
 46017          rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 46018          sqlite3EndBenignMalloc();
 46019          if( rc2==SQLITE_OK && isRO ) break;
 46020        }
 46021      }while( winRetryIoerr(&cnt, &lastErrno) );
 46022  #else
 46023      do{
 46024        h = osCreateFileW((LPCWSTR)zConverted,
 46025                          dwDesiredAccess,
 46026                          dwShareMode, NULL,
 46027                          dwCreationDisposition,
 46028                          dwFlagsAndAttributes,
 46029                          NULL);
 46030        if( h!=INVALID_HANDLE_VALUE ) break;
 46031        if( isReadWrite ){
 46032          int rc2, isRO = 0;
 46033          sqlite3BeginBenignMalloc();
 46034          rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 46035          sqlite3EndBenignMalloc();
 46036          if( rc2==SQLITE_OK && isRO ) break;
 46037        }
 46038      }while( winRetryIoerr(&cnt, &lastErrno) );
 46039  #endif
 46040    }
 46041  #ifdef SQLITE_WIN32_HAS_ANSI
 46042    else{
 46043      do{
 46044        h = osCreateFileA((LPCSTR)zConverted,
 46045                          dwDesiredAccess,
 46046                          dwShareMode, NULL,
 46047                          dwCreationDisposition,
 46048                          dwFlagsAndAttributes,
 46049                          NULL);
 46050        if( h!=INVALID_HANDLE_VALUE ) break;
 46051        if( isReadWrite ){
 46052          int rc2, isRO = 0;
 46053          sqlite3BeginBenignMalloc();
 46054          rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
 46055          sqlite3EndBenignMalloc();
 46056          if( rc2==SQLITE_OK && isRO ) break;
 46057        }
 46058      }while( winRetryIoerr(&cnt, &lastErrno) );
 46059    }
 46060  #endif
 46061    winLogIoerr(cnt, __LINE__);
 46062  
 46063    OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
 46064             dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 46065  
 46066    if( h==INVALID_HANDLE_VALUE ){
 46067      sqlite3_free(zConverted);
 46068      sqlite3_free(zTmpname);
 46069      if( isReadWrite && !isExclusive ){
 46070        return winOpen(pVfs, zName, id,
 46071           ((flags|SQLITE_OPEN_READONLY) &
 46072                       ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
 46073           pOutFlags);
 46074      }else{
 46075        pFile->lastErrno = lastErrno;
 46076        winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
 46077        return SQLITE_CANTOPEN_BKPT;
 46078      }
 46079    }
 46080  
 46081    if( pOutFlags ){
 46082      if( isReadWrite ){
 46083        *pOutFlags = SQLITE_OPEN_READWRITE;
 46084      }else{
 46085        *pOutFlags = SQLITE_OPEN_READONLY;
 46086      }
 46087    }
 46088  
 46089    OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
 46090             "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
 46091             *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
 46092  
 46093    pAppData = (winVfsAppData*)pVfs->pAppData;
 46094  
 46095  #if SQLITE_OS_WINCE
 46096    {
 46097      if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
 46098           && ((pAppData==NULL) || !pAppData->bNoLock)
 46099           && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
 46100      ){
 46101        osCloseHandle(h);
 46102        sqlite3_free(zConverted);
 46103        sqlite3_free(zTmpname);
 46104        OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
 46105        return rc;
 46106      }
 46107    }
 46108    if( isTemp ){
 46109      pFile->zDeleteOnClose = zConverted;
 46110    }else
 46111  #endif
 46112    {
 46113      sqlite3_free(zConverted);
 46114    }
 46115  
 46116    sqlite3_free(zTmpname);
 46117    pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
 46118    pFile->pVfs = pVfs;
 46119    pFile->h = h;
 46120    if( isReadonly ){
 46121      pFile->ctrlFlags |= WINFILE_RDONLY;
 46122    }
 46123    if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
 46124      pFile->ctrlFlags |= WINFILE_PSOW;
 46125    }
 46126    pFile->lastErrno = NO_ERROR;
 46127    pFile->zPath = zName;
 46128  #if SQLITE_MAX_MMAP_SIZE>0
 46129    pFile->hMap = NULL;
 46130    pFile->pMapRegion = 0;
 46131    pFile->mmapSize = 0;
 46132    pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
 46133  #endif
 46134  
 46135    OpenCounter(+1);
 46136    return rc;
 46137  }
 46138  
 46139  /*
 46140  ** Delete the named file.
 46141  **
 46142  ** Note that Windows does not allow a file to be deleted if some other
 46143  ** process has it open.  Sometimes a virus scanner or indexing program
 46144  ** will open a journal file shortly after it is created in order to do
 46145  ** whatever it does.  While this other process is holding the
 46146  ** file open, we will be unable to delete it.  To work around this
 46147  ** problem, we delay 100 milliseconds and try to delete again.  Up
 46148  ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
 46149  ** up and returning an error.
 46150  */
 46151  static int winDelete(
 46152    sqlite3_vfs *pVfs,          /* Not used on win32 */
 46153    const char *zFilename,      /* Name of file to delete */
 46154    int syncDir                 /* Not used on win32 */
 46155  ){
 46156    int cnt = 0;
 46157    int rc;
 46158    DWORD attr;
 46159    DWORD lastErrno = 0;
 46160    void *zConverted;
 46161    UNUSED_PARAMETER(pVfs);
 46162    UNUSED_PARAMETER(syncDir);
 46163  
 46164    SimulateIOError(return SQLITE_IOERR_DELETE);
 46165    OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
 46166  
 46167    zConverted = winConvertFromUtf8Filename(zFilename);
 46168    if( zConverted==0 ){
 46169      OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 46170      return SQLITE_IOERR_NOMEM_BKPT;
 46171    }
 46172    if( osIsNT() ){
 46173      do {
 46174  #if SQLITE_OS_WINRT
 46175        WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 46176        memset(&sAttrData, 0, sizeof(sAttrData));
 46177        if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
 46178                                    &sAttrData) ){
 46179          attr = sAttrData.dwFileAttributes;
 46180        }else{
 46181          lastErrno = osGetLastError();
 46182          if( lastErrno==ERROR_FILE_NOT_FOUND
 46183           || lastErrno==ERROR_PATH_NOT_FOUND ){
 46184            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 46185          }else{
 46186            rc = SQLITE_ERROR;
 46187          }
 46188          break;
 46189        }
 46190  #else
 46191        attr = osGetFileAttributesW(zConverted);
 46192  #endif
 46193        if ( attr==INVALID_FILE_ATTRIBUTES ){
 46194          lastErrno = osGetLastError();
 46195          if( lastErrno==ERROR_FILE_NOT_FOUND
 46196           || lastErrno==ERROR_PATH_NOT_FOUND ){
 46197            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 46198          }else{
 46199            rc = SQLITE_ERROR;
 46200          }
 46201          break;
 46202        }
 46203        if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 46204          rc = SQLITE_ERROR; /* Files only. */
 46205          break;
 46206        }
 46207        if ( osDeleteFileW(zConverted) ){
 46208          rc = SQLITE_OK; /* Deleted OK. */
 46209          break;
 46210        }
 46211        if ( !winRetryIoerr(&cnt, &lastErrno) ){
 46212          rc = SQLITE_ERROR; /* No more retries. */
 46213          break;
 46214        }
 46215      } while(1);
 46216    }
 46217  #ifdef SQLITE_WIN32_HAS_ANSI
 46218    else{
 46219      do {
 46220        attr = osGetFileAttributesA(zConverted);
 46221        if ( attr==INVALID_FILE_ATTRIBUTES ){
 46222          lastErrno = osGetLastError();
 46223          if( lastErrno==ERROR_FILE_NOT_FOUND
 46224           || lastErrno==ERROR_PATH_NOT_FOUND ){
 46225            rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
 46226          }else{
 46227            rc = SQLITE_ERROR;
 46228          }
 46229          break;
 46230        }
 46231        if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
 46232          rc = SQLITE_ERROR; /* Files only. */
 46233          break;
 46234        }
 46235        if ( osDeleteFileA(zConverted) ){
 46236          rc = SQLITE_OK; /* Deleted OK. */
 46237          break;
 46238        }
 46239        if ( !winRetryIoerr(&cnt, &lastErrno) ){
 46240          rc = SQLITE_ERROR; /* No more retries. */
 46241          break;
 46242        }
 46243      } while(1);
 46244    }
 46245  #endif
 46246    if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
 46247      rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
 46248    }else{
 46249      winLogIoerr(cnt, __LINE__);
 46250    }
 46251    sqlite3_free(zConverted);
 46252    OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
 46253    return rc;
 46254  }
 46255  
 46256  /*
 46257  ** Check the existence and status of a file.
 46258  */
 46259  static int winAccess(
 46260    sqlite3_vfs *pVfs,         /* Not used on win32 */
 46261    const char *zFilename,     /* Name of file to check */
 46262    int flags,                 /* Type of test to make on this file */
 46263    int *pResOut               /* OUT: Result */
 46264  ){
 46265    DWORD attr;
 46266    int rc = 0;
 46267    DWORD lastErrno = 0;
 46268    void *zConverted;
 46269    UNUSED_PARAMETER(pVfs);
 46270  
 46271    SimulateIOError( return SQLITE_IOERR_ACCESS; );
 46272    OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
 46273             zFilename, flags, pResOut));
 46274  
 46275    zConverted = winConvertFromUtf8Filename(zFilename);
 46276    if( zConverted==0 ){
 46277      OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
 46278      return SQLITE_IOERR_NOMEM_BKPT;
 46279    }
 46280    if( osIsNT() ){
 46281      int cnt = 0;
 46282      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
 46283      memset(&sAttrData, 0, sizeof(sAttrData));
 46284      while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
 46285                               GetFileExInfoStandard,
 46286                               &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
 46287      if( rc ){
 46288        /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
 46289        ** as if it does not exist.
 46290        */
 46291        if(    flags==SQLITE_ACCESS_EXISTS
 46292            && sAttrData.nFileSizeHigh==0
 46293            && sAttrData.nFileSizeLow==0 ){
 46294          attr = INVALID_FILE_ATTRIBUTES;
 46295        }else{
 46296          attr = sAttrData.dwFileAttributes;
 46297        }
 46298      }else{
 46299        winLogIoerr(cnt, __LINE__);
 46300        if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
 46301          sqlite3_free(zConverted);
 46302          return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
 46303                             zFilename);
 46304        }else{
 46305          attr = INVALID_FILE_ATTRIBUTES;
 46306        }
 46307      }
 46308    }
 46309  #ifdef SQLITE_WIN32_HAS_ANSI
 46310    else{
 46311      attr = osGetFileAttributesA((char*)zConverted);
 46312    }
 46313  #endif
 46314    sqlite3_free(zConverted);
 46315    switch( flags ){
 46316      case SQLITE_ACCESS_READ:
 46317      case SQLITE_ACCESS_EXISTS:
 46318        rc = attr!=INVALID_FILE_ATTRIBUTES;
 46319        break;
 46320      case SQLITE_ACCESS_READWRITE:
 46321        rc = attr!=INVALID_FILE_ATTRIBUTES &&
 46322               (attr & FILE_ATTRIBUTE_READONLY)==0;
 46323        break;
 46324      default:
 46325        assert(!"Invalid flags argument");
 46326    }
 46327    *pResOut = rc;
 46328    OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
 46329             zFilename, pResOut, *pResOut));
 46330    return SQLITE_OK;
 46331  }
 46332  
 46333  /*
 46334  ** Returns non-zero if the specified path name starts with a drive letter
 46335  ** followed by a colon character.
 46336  */
 46337  static BOOL winIsDriveLetterAndColon(
 46338    const char *zPathname
 46339  ){
 46340    return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
 46341  }
 46342  
 46343  /*
 46344  ** Returns non-zero if the specified path name should be used verbatim.  If
 46345  ** non-zero is returned from this function, the calling function must simply
 46346  ** use the provided path name verbatim -OR- resolve it into a full path name
 46347  ** using the GetFullPathName Win32 API function (if available).
 46348  */
 46349  static BOOL winIsVerbatimPathname(
 46350    const char *zPathname
 46351  ){
 46352    /*
 46353    ** If the path name starts with a forward slash or a backslash, it is either
 46354    ** a legal UNC name, a volume relative path, or an absolute path name in the
 46355    ** "Unix" format on Windows.  There is no easy way to differentiate between
 46356    ** the final two cases; therefore, we return the safer return value of TRUE
 46357    ** so that callers of this function will simply use it verbatim.
 46358    */
 46359    if ( winIsDirSep(zPathname[0]) ){
 46360      return TRUE;
 46361    }
 46362  
 46363    /*
 46364    ** If the path name starts with a letter and a colon it is either a volume
 46365    ** relative path or an absolute path.  Callers of this function must not
 46366    ** attempt to treat it as a relative path name (i.e. they should simply use
 46367    ** it verbatim).
 46368    */
 46369    if ( winIsDriveLetterAndColon(zPathname) ){
 46370      return TRUE;
 46371    }
 46372  
 46373    /*
 46374    ** If we get to this point, the path name should almost certainly be a purely
 46375    ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
 46376    */
 46377    return FALSE;
 46378  }
 46379  
 46380  /*
 46381  ** Turn a relative pathname into a full pathname.  Write the full
 46382  ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
 46383  ** bytes in size.
 46384  */
 46385  static int winFullPathname(
 46386    sqlite3_vfs *pVfs,            /* Pointer to vfs object */
 46387    const char *zRelative,        /* Possibly relative input path */
 46388    int nFull,                    /* Size of output buffer in bytes */
 46389    char *zFull                   /* Output buffer */
 46390  ){
 46391  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 46392    DWORD nByte;
 46393    void *zConverted;
 46394    char *zOut;
 46395  #endif
 46396  
 46397    /* If this path name begins with "/X:", where "X" is any alphabetic
 46398    ** character, discard the initial "/" from the pathname.
 46399    */
 46400    if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
 46401      zRelative++;
 46402    }
 46403  
 46404  #if defined(__CYGWIN__)
 46405    SimulateIOError( return SQLITE_ERROR );
 46406    UNUSED_PARAMETER(nFull);
 46407    assert( nFull>=pVfs->mxPathname );
 46408    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 46409      /*
 46410      ** NOTE: We are dealing with a relative path name and the data
 46411      **       directory has been set.  Therefore, use it as the basis
 46412      **       for converting the relative path name to an absolute
 46413      **       one by prepending the data directory and a slash.
 46414      */
 46415      char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 46416      if( !zOut ){
 46417        return SQLITE_IOERR_NOMEM_BKPT;
 46418      }
 46419      if( cygwin_conv_path(
 46420              (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
 46421              CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
 46422        sqlite3_free(zOut);
 46423        return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 46424                           "winFullPathname1", zRelative);
 46425      }else{
 46426        char *zUtf8 = winConvertToUtf8Filename(zOut);
 46427        if( !zUtf8 ){
 46428          sqlite3_free(zOut);
 46429          return SQLITE_IOERR_NOMEM_BKPT;
 46430        }
 46431        sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 46432                         sqlite3_data_directory, winGetDirSep(), zUtf8);
 46433        sqlite3_free(zUtf8);
 46434        sqlite3_free(zOut);
 46435      }
 46436    }else{
 46437      char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
 46438      if( !zOut ){
 46439        return SQLITE_IOERR_NOMEM_BKPT;
 46440      }
 46441      if( cygwin_conv_path(
 46442              (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
 46443              zRelative, zOut, pVfs->mxPathname+1)<0 ){
 46444        sqlite3_free(zOut);
 46445        return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
 46446                           "winFullPathname2", zRelative);
 46447      }else{
 46448        char *zUtf8 = winConvertToUtf8Filename(zOut);
 46449        if( !zUtf8 ){
 46450          sqlite3_free(zOut);
 46451          return SQLITE_IOERR_NOMEM_BKPT;
 46452        }
 46453        sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
 46454        sqlite3_free(zUtf8);
 46455        sqlite3_free(zOut);
 46456      }
 46457    }
 46458    return SQLITE_OK;
 46459  #endif
 46460  
 46461  #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
 46462    SimulateIOError( return SQLITE_ERROR );
 46463    /* WinCE has no concept of a relative pathname, or so I am told. */
 46464    /* WinRT has no way to convert a relative path to an absolute one. */
 46465    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 46466      /*
 46467      ** NOTE: We are dealing with a relative path name and the data
 46468      **       directory has been set.  Therefore, use it as the basis
 46469      **       for converting the relative path name to an absolute
 46470      **       one by prepending the data directory and a backslash.
 46471      */
 46472      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 46473                       sqlite3_data_directory, winGetDirSep(), zRelative);
 46474    }else{
 46475      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
 46476    }
 46477    return SQLITE_OK;
 46478  #endif
 46479  
 46480  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
 46481    /* It's odd to simulate an io-error here, but really this is just
 46482    ** using the io-error infrastructure to test that SQLite handles this
 46483    ** function failing. This function could fail if, for example, the
 46484    ** current working directory has been unlinked.
 46485    */
 46486    SimulateIOError( return SQLITE_ERROR );
 46487    if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
 46488      /*
 46489      ** NOTE: We are dealing with a relative path name and the data
 46490      **       directory has been set.  Therefore, use it as the basis
 46491      **       for converting the relative path name to an absolute
 46492      **       one by prepending the data directory and a backslash.
 46493      */
 46494      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
 46495                       sqlite3_data_directory, winGetDirSep(), zRelative);
 46496      return SQLITE_OK;
 46497    }
 46498    zConverted = winConvertFromUtf8Filename(zRelative);
 46499    if( zConverted==0 ){
 46500      return SQLITE_IOERR_NOMEM_BKPT;
 46501    }
 46502    if( osIsNT() ){
 46503      LPWSTR zTemp;
 46504      nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
 46505      if( nByte==0 ){
 46506        sqlite3_free(zConverted);
 46507        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 46508                           "winFullPathname1", zRelative);
 46509      }
 46510      nByte += 3;
 46511      zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 46512      if( zTemp==0 ){
 46513        sqlite3_free(zConverted);
 46514        return SQLITE_IOERR_NOMEM_BKPT;
 46515      }
 46516      nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
 46517      if( nByte==0 ){
 46518        sqlite3_free(zConverted);
 46519        sqlite3_free(zTemp);
 46520        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 46521                           "winFullPathname2", zRelative);
 46522      }
 46523      sqlite3_free(zConverted);
 46524      zOut = winUnicodeToUtf8(zTemp);
 46525      sqlite3_free(zTemp);
 46526    }
 46527  #ifdef SQLITE_WIN32_HAS_ANSI
 46528    else{
 46529      char *zTemp;
 46530      nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
 46531      if( nByte==0 ){
 46532        sqlite3_free(zConverted);
 46533        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 46534                           "winFullPathname3", zRelative);
 46535      }
 46536      nByte += 3;
 46537      zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
 46538      if( zTemp==0 ){
 46539        sqlite3_free(zConverted);
 46540        return SQLITE_IOERR_NOMEM_BKPT;
 46541      }
 46542      nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
 46543      if( nByte==0 ){
 46544        sqlite3_free(zConverted);
 46545        sqlite3_free(zTemp);
 46546        return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
 46547                           "winFullPathname4", zRelative);
 46548      }
 46549      sqlite3_free(zConverted);
 46550      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
 46551      sqlite3_free(zTemp);
 46552    }
 46553  #endif
 46554    if( zOut ){
 46555      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
 46556      sqlite3_free(zOut);
 46557      return SQLITE_OK;
 46558    }else{
 46559      return SQLITE_IOERR_NOMEM_BKPT;
 46560    }
 46561  #endif
 46562  }
 46563  
 46564  #ifndef SQLITE_OMIT_LOAD_EXTENSION
 46565  /*
 46566  ** Interfaces for opening a shared library, finding entry points
 46567  ** within the shared library, and closing the shared library.
 46568  */
 46569  static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
 46570    HANDLE h;
 46571  #if defined(__CYGWIN__)
 46572    int nFull = pVfs->mxPathname+1;
 46573    char *zFull = sqlite3MallocZero( nFull );
 46574    void *zConverted = 0;
 46575    if( zFull==0 ){
 46576      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 46577      return 0;
 46578    }
 46579    if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
 46580      sqlite3_free(zFull);
 46581      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 46582      return 0;
 46583    }
 46584    zConverted = winConvertFromUtf8Filename(zFull);
 46585    sqlite3_free(zFull);
 46586  #else
 46587    void *zConverted = winConvertFromUtf8Filename(zFilename);
 46588    UNUSED_PARAMETER(pVfs);
 46589  #endif
 46590    if( zConverted==0 ){
 46591      OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
 46592      return 0;
 46593    }
 46594    if( osIsNT() ){
 46595  #if SQLITE_OS_WINRT
 46596      h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
 46597  #else
 46598      h = osLoadLibraryW((LPCWSTR)zConverted);
 46599  #endif
 46600    }
 46601  #ifdef SQLITE_WIN32_HAS_ANSI
 46602    else{
 46603      h = osLoadLibraryA((char*)zConverted);
 46604    }
 46605  #endif
 46606    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
 46607    sqlite3_free(zConverted);
 46608    return (void*)h;
 46609  }
 46610  static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
 46611    UNUSED_PARAMETER(pVfs);
 46612    winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
 46613  }
 46614  static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
 46615    FARPROC proc;
 46616    UNUSED_PARAMETER(pVfs);
 46617    proc = osGetProcAddressA((HANDLE)pH, zSym);
 46618    OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
 46619             (void*)pH, zSym, (void*)proc));
 46620    return (void(*)(void))proc;
 46621  }
 46622  static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
 46623    UNUSED_PARAMETER(pVfs);
 46624    osFreeLibrary((HANDLE)pHandle);
 46625    OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
 46626  }
 46627  #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
 46628    #define winDlOpen  0
 46629    #define winDlError 0
 46630    #define winDlSym   0
 46631    #define winDlClose 0
 46632  #endif
 46633  
 46634  /* State information for the randomness gatherer. */
 46635  typedef struct EntropyGatherer EntropyGatherer;
 46636  struct EntropyGatherer {
 46637    unsigned char *a;   /* Gather entropy into this buffer */
 46638    int na;             /* Size of a[] in bytes */
 46639    int i;              /* XOR next input into a[i] */
 46640    int nXor;           /* Number of XOR operations done */
 46641  };
 46642  
 46643  #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
 46644  /* Mix sz bytes of entropy into p. */
 46645  static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
 46646    int j, k;
 46647    for(j=0, k=p->i; j<sz; j++){
 46648      p->a[k++] ^= x[j];
 46649      if( k>=p->na ) k = 0;
 46650    }
 46651    p->i = k;
 46652    p->nXor += sz;
 46653  }
 46654  #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
 46655  
 46656  /*
 46657  ** Write up to nBuf bytes of randomness into zBuf.
 46658  */
 46659  static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 46660  #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
 46661    UNUSED_PARAMETER(pVfs);
 46662    memset(zBuf, 0, nBuf);
 46663    return nBuf;
 46664  #else
 46665    EntropyGatherer e;
 46666    UNUSED_PARAMETER(pVfs);
 46667    memset(zBuf, 0, nBuf);
 46668    e.a = (unsigned char*)zBuf;
 46669    e.na = nBuf;
 46670    e.nXor = 0;
 46671    e.i = 0;
 46672    {
 46673      SYSTEMTIME x;
 46674      osGetSystemTime(&x);
 46675      xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
 46676    }
 46677    {
 46678      DWORD pid = osGetCurrentProcessId();
 46679      xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
 46680    }
 46681  #if SQLITE_OS_WINRT
 46682    {
 46683      ULONGLONG cnt = osGetTickCount64();
 46684      xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
 46685    }
 46686  #else
 46687    {
 46688      DWORD cnt = osGetTickCount();
 46689      xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
 46690    }
 46691  #endif /* SQLITE_OS_WINRT */
 46692    {
 46693      LARGE_INTEGER i;
 46694      osQueryPerformanceCounter(&i);
 46695      xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
 46696    }
 46697  #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
 46698    {
 46699      UUID id;
 46700      memset(&id, 0, sizeof(UUID));
 46701      osUuidCreate(&id);
 46702      xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 46703      memset(&id, 0, sizeof(UUID));
 46704      osUuidCreateSequential(&id);
 46705      xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
 46706    }
 46707  #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
 46708    return e.nXor>nBuf ? nBuf : e.nXor;
 46709  #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
 46710  }
 46711  
 46712  
 46713  /*
 46714  ** Sleep for a little while.  Return the amount of time slept.
 46715  */
 46716  static int winSleep(sqlite3_vfs *pVfs, int microsec){
 46717    sqlite3_win32_sleep((microsec+999)/1000);
 46718    UNUSED_PARAMETER(pVfs);
 46719    return ((microsec+999)/1000)*1000;
 46720  }
 46721  
 46722  /*
 46723  ** The following variable, if set to a non-zero value, is interpreted as
 46724  ** the number of seconds since 1970 and is used to set the result of
 46725  ** sqlite3OsCurrentTime() during testing.
 46726  */
 46727  #ifdef SQLITE_TEST
 46728  SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
 46729  #endif
 46730  
 46731  /*
 46732  ** Find the current time (in Universal Coordinated Time).  Write into *piNow
 46733  ** the current time and date as a Julian Day number times 86_400_000.  In
 46734  ** other words, write into *piNow the number of milliseconds since the Julian
 46735  ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 46736  ** proleptic Gregorian calendar.
 46737  **
 46738  ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
 46739  ** cannot be found.
 46740  */
 46741  static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
 46742    /* FILETIME structure is a 64-bit value representing the number of
 46743       100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
 46744    */
 46745    FILETIME ft;
 46746    static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
 46747  #ifdef SQLITE_TEST
 46748    static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
 46749  #endif
 46750    /* 2^32 - to avoid use of LL and warnings in gcc */
 46751    static const sqlite3_int64 max32BitValue =
 46752        (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
 46753        (sqlite3_int64)294967296;
 46754  
 46755  #if SQLITE_OS_WINCE
 46756    SYSTEMTIME time;
 46757    osGetSystemTime(&time);
 46758    /* if SystemTimeToFileTime() fails, it returns zero. */
 46759    if (!osSystemTimeToFileTime(&time,&ft)){
 46760      return SQLITE_ERROR;
 46761    }
 46762  #else
 46763    osGetSystemTimeAsFileTime( &ft );
 46764  #endif
 46765  
 46766    *piNow = winFiletimeEpoch +
 46767              ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
 46768                 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
 46769  
 46770  #ifdef SQLITE_TEST
 46771    if( sqlite3_current_time ){
 46772      *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
 46773    }
 46774  #endif
 46775    UNUSED_PARAMETER(pVfs);
 46776    return SQLITE_OK;
 46777  }
 46778  
 46779  /*
 46780  ** Find the current time (in Universal Coordinated Time).  Write the
 46781  ** current time and date as a Julian Day number into *prNow and
 46782  ** return 0.  Return 1 if the time and date cannot be found.
 46783  */
 46784  static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
 46785    int rc;
 46786    sqlite3_int64 i;
 46787    rc = winCurrentTimeInt64(pVfs, &i);
 46788    if( !rc ){
 46789      *prNow = i/86400000.0;
 46790    }
 46791    return rc;
 46792  }
 46793  
 46794  /*
 46795  ** The idea is that this function works like a combination of
 46796  ** GetLastError() and FormatMessage() on Windows (or errno and
 46797  ** strerror_r() on Unix). After an error is returned by an OS
 46798  ** function, SQLite calls this function with zBuf pointing to
 46799  ** a buffer of nBuf bytes. The OS layer should populate the
 46800  ** buffer with a nul-terminated UTF-8 encoded error message
 46801  ** describing the last IO error to have occurred within the calling
 46802  ** thread.
 46803  **
 46804  ** If the error message is too large for the supplied buffer,
 46805  ** it should be truncated. The return value of xGetLastError
 46806  ** is zero if the error message fits in the buffer, or non-zero
 46807  ** otherwise (if the message was truncated). If non-zero is returned,
 46808  ** then it is not necessary to include the nul-terminator character
 46809  ** in the output buffer.
 46810  **
 46811  ** Not supplying an error message will have no adverse effect
 46812  ** on SQLite. It is fine to have an implementation that never
 46813  ** returns an error message:
 46814  **
 46815  **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 46816  **     assert(zBuf[0]=='\0');
 46817  **     return 0;
 46818  **   }
 46819  **
 46820  ** However if an error message is supplied, it will be incorporated
 46821  ** by sqlite into the error message available to the user using
 46822  ** sqlite3_errmsg(), possibly making IO errors easier to debug.
 46823  */
 46824  static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
 46825    DWORD e = osGetLastError();
 46826    UNUSED_PARAMETER(pVfs);
 46827    if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
 46828    return e;
 46829  }
 46830  
 46831  /*
 46832  ** Initialize and deinitialize the operating system interface.
 46833  */
 46834  SQLITE_API int sqlite3_os_init(void){
 46835    static sqlite3_vfs winVfs = {
 46836      3,                     /* iVersion */
 46837      sizeof(winFile),       /* szOsFile */
 46838      SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
 46839      0,                     /* pNext */
 46840      "win32",               /* zName */
 46841      &winAppData,           /* pAppData */
 46842      winOpen,               /* xOpen */
 46843      winDelete,             /* xDelete */
 46844      winAccess,             /* xAccess */
 46845      winFullPathname,       /* xFullPathname */
 46846      winDlOpen,             /* xDlOpen */
 46847      winDlError,            /* xDlError */
 46848      winDlSym,              /* xDlSym */
 46849      winDlClose,            /* xDlClose */
 46850      winRandomness,         /* xRandomness */
 46851      winSleep,              /* xSleep */
 46852      winCurrentTime,        /* xCurrentTime */
 46853      winGetLastError,       /* xGetLastError */
 46854      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 46855      winSetSystemCall,      /* xSetSystemCall */
 46856      winGetSystemCall,      /* xGetSystemCall */
 46857      winNextSystemCall,     /* xNextSystemCall */
 46858    };
 46859  #if defined(SQLITE_WIN32_HAS_WIDE)
 46860    static sqlite3_vfs winLongPathVfs = {
 46861      3,                     /* iVersion */
 46862      sizeof(winFile),       /* szOsFile */
 46863      SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
 46864      0,                     /* pNext */
 46865      "win32-longpath",      /* zName */
 46866      &winAppData,           /* pAppData */
 46867      winOpen,               /* xOpen */
 46868      winDelete,             /* xDelete */
 46869      winAccess,             /* xAccess */
 46870      winFullPathname,       /* xFullPathname */
 46871      winDlOpen,             /* xDlOpen */
 46872      winDlError,            /* xDlError */
 46873      winDlSym,              /* xDlSym */
 46874      winDlClose,            /* xDlClose */
 46875      winRandomness,         /* xRandomness */
 46876      winSleep,              /* xSleep */
 46877      winCurrentTime,        /* xCurrentTime */
 46878      winGetLastError,       /* xGetLastError */
 46879      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 46880      winSetSystemCall,      /* xSetSystemCall */
 46881      winGetSystemCall,      /* xGetSystemCall */
 46882      winNextSystemCall,     /* xNextSystemCall */
 46883    };
 46884  #endif
 46885    static sqlite3_vfs winNolockVfs = {
 46886      3,                     /* iVersion */
 46887      sizeof(winFile),       /* szOsFile */
 46888      SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
 46889      0,                     /* pNext */
 46890      "win32-none",          /* zName */
 46891      &winNolockAppData,     /* pAppData */
 46892      winOpen,               /* xOpen */
 46893      winDelete,             /* xDelete */
 46894      winAccess,             /* xAccess */
 46895      winFullPathname,       /* xFullPathname */
 46896      winDlOpen,             /* xDlOpen */
 46897      winDlError,            /* xDlError */
 46898      winDlSym,              /* xDlSym */
 46899      winDlClose,            /* xDlClose */
 46900      winRandomness,         /* xRandomness */
 46901      winSleep,              /* xSleep */
 46902      winCurrentTime,        /* xCurrentTime */
 46903      winGetLastError,       /* xGetLastError */
 46904      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 46905      winSetSystemCall,      /* xSetSystemCall */
 46906      winGetSystemCall,      /* xGetSystemCall */
 46907      winNextSystemCall,     /* xNextSystemCall */
 46908    };
 46909  #if defined(SQLITE_WIN32_HAS_WIDE)
 46910    static sqlite3_vfs winLongPathNolockVfs = {
 46911      3,                     /* iVersion */
 46912      sizeof(winFile),       /* szOsFile */
 46913      SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
 46914      0,                     /* pNext */
 46915      "win32-longpath-none", /* zName */
 46916      &winNolockAppData,     /* pAppData */
 46917      winOpen,               /* xOpen */
 46918      winDelete,             /* xDelete */
 46919      winAccess,             /* xAccess */
 46920      winFullPathname,       /* xFullPathname */
 46921      winDlOpen,             /* xDlOpen */
 46922      winDlError,            /* xDlError */
 46923      winDlSym,              /* xDlSym */
 46924      winDlClose,            /* xDlClose */
 46925      winRandomness,         /* xRandomness */
 46926      winSleep,              /* xSleep */
 46927      winCurrentTime,        /* xCurrentTime */
 46928      winGetLastError,       /* xGetLastError */
 46929      winCurrentTimeInt64,   /* xCurrentTimeInt64 */
 46930      winSetSystemCall,      /* xSetSystemCall */
 46931      winGetSystemCall,      /* xGetSystemCall */
 46932      winNextSystemCall,     /* xNextSystemCall */
 46933    };
 46934  #endif
 46935  
 46936    /* Double-check that the aSyscall[] array has been constructed
 46937    ** correctly.  See ticket [bb3a86e890c8e96ab] */
 46938    assert( ArraySize(aSyscall)==80 );
 46939  
 46940    /* get memory map allocation granularity */
 46941    memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
 46942  #if SQLITE_OS_WINRT
 46943    osGetNativeSystemInfo(&winSysInfo);
 46944  #else
 46945    osGetSystemInfo(&winSysInfo);
 46946  #endif
 46947    assert( winSysInfo.dwAllocationGranularity>0 );
 46948    assert( winSysInfo.dwPageSize>0 );
 46949  
 46950    sqlite3_vfs_register(&winVfs, 1);
 46951  
 46952  #if defined(SQLITE_WIN32_HAS_WIDE)
 46953    sqlite3_vfs_register(&winLongPathVfs, 0);
 46954  #endif
 46955  
 46956    sqlite3_vfs_register(&winNolockVfs, 0);
 46957  
 46958  #if defined(SQLITE_WIN32_HAS_WIDE)
 46959    sqlite3_vfs_register(&winLongPathNolockVfs, 0);
 46960  #endif
 46961  
 46962  #ifndef SQLITE_OMIT_WAL
 46963    winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
 46964  #endif
 46965  
 46966    return SQLITE_OK;
 46967  }
 46968  
 46969  SQLITE_API int sqlite3_os_end(void){
 46970  #if SQLITE_OS_WINRT
 46971    if( sleepObj!=NULL ){
 46972      osCloseHandle(sleepObj);
 46973      sleepObj = NULL;
 46974    }
 46975  #endif
 46976  
 46977  #ifndef SQLITE_OMIT_WAL
 46978    winBigLock = 0;
 46979  #endif
 46980  
 46981    return SQLITE_OK;
 46982  }
 46983  
 46984  #endif /* SQLITE_OS_WIN */
 46985  
 46986  /************** End of os_win.c **********************************************/
 46987  /************** Begin file memdb.c *******************************************/
 46988  /*
 46989  ** 2016-09-07
 46990  **
 46991  ** The author disclaims copyright to this source code.  In place of
 46992  ** a legal notice, here is a blessing:
 46993  **
 46994  **    May you do good and not evil.
 46995  **    May you find forgiveness for yourself and forgive others.
 46996  **    May you share freely, never taking more than you give.
 46997  **
 46998  ******************************************************************************
 46999  **
 47000  ** This file implements an in-memory VFS. A database is held as a contiguous
 47001  ** block of memory.
 47002  **
 47003  ** This file also implements interface sqlite3_serialize() and
 47004  ** sqlite3_deserialize().
 47005  */
 47006  /* #include "sqliteInt.h" */
 47007  #ifdef SQLITE_ENABLE_DESERIALIZE
 47008  
 47009  /*
 47010  ** Forward declaration of objects used by this utility
 47011  */
 47012  typedef struct sqlite3_vfs MemVfs;
 47013  typedef struct MemFile MemFile;
 47014  
 47015  /* Access to a lower-level VFS that (might) implement dynamic loading,
 47016  ** access to randomness, etc.
 47017  */
 47018  #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
 47019  
 47020  /* An open file */
 47021  struct MemFile {
 47022    sqlite3_file base;              /* IO methods */
 47023    sqlite3_int64 sz;               /* Size of the file */
 47024    sqlite3_int64 szAlloc;          /* Space allocated to aData */
 47025    sqlite3_int64 szMax;            /* Maximum allowed size of the file */
 47026    unsigned char *aData;           /* content of the file */
 47027    int nMmap;                      /* Number of memory mapped pages */
 47028    unsigned mFlags;                /* Flags */
 47029    int eLock;                      /* Most recent lock against this file */
 47030  };
 47031  
 47032  /*
 47033  ** Methods for MemFile
 47034  */
 47035  static int memdbClose(sqlite3_file*);
 47036  static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
 47037  static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
 47038  static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
 47039  static int memdbSync(sqlite3_file*, int flags);
 47040  static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
 47041  static int memdbLock(sqlite3_file*, int);
 47042  /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
 47043  static int memdbFileControl(sqlite3_file*, int op, void *pArg);
 47044  /* static int memdbSectorSize(sqlite3_file*); // not used */
 47045  static int memdbDeviceCharacteristics(sqlite3_file*);
 47046  static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
 47047  static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
 47048  
 47049  /*
 47050  ** Methods for MemVfs
 47051  */
 47052  static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
 47053  /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
 47054  static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
 47055  static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
 47056  static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
 47057  static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
 47058  static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
 47059  static void memdbDlClose(sqlite3_vfs*, void*);
 47060  static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
 47061  static int memdbSleep(sqlite3_vfs*, int microseconds);
 47062  /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
 47063  static int memdbGetLastError(sqlite3_vfs*, int, char *);
 47064  static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
 47065  
 47066  static sqlite3_vfs memdb_vfs = {
 47067    2,                           /* iVersion */
 47068    0,                           /* szOsFile (set when registered) */
 47069    1024,                        /* mxPathname */
 47070    0,                           /* pNext */
 47071    "memdb",                     /* zName */
 47072    0,                           /* pAppData (set when registered) */ 
 47073    memdbOpen,                   /* xOpen */
 47074    0, /* memdbDelete, */        /* xDelete */
 47075    memdbAccess,                 /* xAccess */
 47076    memdbFullPathname,           /* xFullPathname */
 47077    memdbDlOpen,                 /* xDlOpen */
 47078    memdbDlError,                /* xDlError */
 47079    memdbDlSym,                  /* xDlSym */
 47080    memdbDlClose,                /* xDlClose */
 47081    memdbRandomness,             /* xRandomness */
 47082    memdbSleep,                  /* xSleep */
 47083    0, /* memdbCurrentTime, */   /* xCurrentTime */
 47084    memdbGetLastError,           /* xGetLastError */
 47085    memdbCurrentTimeInt64        /* xCurrentTimeInt64 */
 47086  };
 47087  
 47088  static const sqlite3_io_methods memdb_io_methods = {
 47089    3,                              /* iVersion */
 47090    memdbClose,                      /* xClose */
 47091    memdbRead,                       /* xRead */
 47092    memdbWrite,                      /* xWrite */
 47093    memdbTruncate,                   /* xTruncate */
 47094    memdbSync,                       /* xSync */
 47095    memdbFileSize,                   /* xFileSize */
 47096    memdbLock,                       /* xLock */
 47097    memdbLock,                       /* xUnlock - same as xLock in this case */ 
 47098    0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
 47099    memdbFileControl,                /* xFileControl */
 47100    0, /* memdbSectorSize,*/         /* xSectorSize */
 47101    memdbDeviceCharacteristics,      /* xDeviceCharacteristics */
 47102    0,                               /* xShmMap */
 47103    0,                               /* xShmLock */
 47104    0,                               /* xShmBarrier */
 47105    0,                               /* xShmUnmap */
 47106    memdbFetch,                      /* xFetch */
 47107    memdbUnfetch                     /* xUnfetch */
 47108  };
 47109  
 47110  
 47111  
 47112  /*
 47113  ** Close an memdb-file.
 47114  **
 47115  ** The pData pointer is owned by the application, so there is nothing
 47116  ** to free.
 47117  */
 47118  static int memdbClose(sqlite3_file *pFile){
 47119    MemFile *p = (MemFile *)pFile;
 47120    if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
 47121    return SQLITE_OK;
 47122  }
 47123  
 47124  /*
 47125  ** Read data from an memdb-file.
 47126  */
 47127  static int memdbRead(
 47128    sqlite3_file *pFile, 
 47129    void *zBuf, 
 47130    int iAmt, 
 47131    sqlite_int64 iOfst
 47132  ){
 47133    MemFile *p = (MemFile *)pFile;
 47134    if( iOfst+iAmt>p->sz ){
 47135      memset(zBuf, 0, iAmt);
 47136      if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
 47137      return SQLITE_IOERR_SHORT_READ;
 47138    }
 47139    memcpy(zBuf, p->aData+iOfst, iAmt);
 47140    return SQLITE_OK;
 47141  }
 47142  
 47143  /*
 47144  ** Try to enlarge the memory allocation to hold at least sz bytes
 47145  */
 47146  static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
 47147    unsigned char *pNew;
 47148    if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
 47149      return SQLITE_FULL;
 47150    }
 47151    if( newSz>p->szMax ){
 47152      return SQLITE_FULL;
 47153    }
 47154    newSz *= 2;
 47155    if( newSz>p->szMax ) newSz = p->szMax;
 47156    pNew = sqlite3_realloc64(p->aData, newSz);
 47157    if( pNew==0 ) return SQLITE_NOMEM;
 47158    p->aData = pNew;
 47159    p->szAlloc = newSz;
 47160    return SQLITE_OK;
 47161  }
 47162  
 47163  /*
 47164  ** Write data to an memdb-file.
 47165  */
 47166  static int memdbWrite(
 47167    sqlite3_file *pFile,
 47168    const void *z,
 47169    int iAmt,
 47170    sqlite_int64 iOfst
 47171  ){
 47172    MemFile *p = (MemFile *)pFile;
 47173    if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
 47174    if( iOfst+iAmt>p->sz ){
 47175      int rc;
 47176      if( iOfst+iAmt>p->szAlloc
 47177       && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
 47178      ){
 47179        return rc;
 47180      }
 47181      if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
 47182      p->sz = iOfst+iAmt;
 47183    }
 47184    memcpy(p->aData+iOfst, z, iAmt);
 47185    return SQLITE_OK;
 47186  }
 47187  
 47188  /*
 47189  ** Truncate an memdb-file.
 47190  **
 47191  ** In rollback mode (which is always the case for memdb, as it does not
 47192  ** support WAL mode) the truncate() method is only used to reduce
 47193  ** the size of a file, never to increase the size.
 47194  */
 47195  static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
 47196    MemFile *p = (MemFile *)pFile;
 47197    if( NEVER(size>p->sz) ) return SQLITE_FULL;
 47198    p->sz = size; 
 47199    return SQLITE_OK;
 47200  }
 47201  
 47202  /*
 47203  ** Sync an memdb-file.
 47204  */
 47205  static int memdbSync(sqlite3_file *pFile, int flags){
 47206    return SQLITE_OK;
 47207  }
 47208  
 47209  /*
 47210  ** Return the current file-size of an memdb-file.
 47211  */
 47212  static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
 47213    MemFile *p = (MemFile *)pFile;
 47214    *pSize = p->sz;
 47215    return SQLITE_OK;
 47216  }
 47217  
 47218  /*
 47219  ** Lock an memdb-file.
 47220  */
 47221  static int memdbLock(sqlite3_file *pFile, int eLock){
 47222    MemFile *p = (MemFile *)pFile;
 47223    if( eLock>SQLITE_LOCK_SHARED 
 47224     && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
 47225    ){
 47226      return SQLITE_READONLY;
 47227    }
 47228    p->eLock = eLock;
 47229    return SQLITE_OK;
 47230  }
 47231  
 47232  #if 0 /* Never used because memdbAccess() always returns false */
 47233  /*
 47234  ** Check if another file-handle holds a RESERVED lock on an memdb-file.
 47235  */
 47236  static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
 47237    *pResOut = 0;
 47238    return SQLITE_OK;
 47239  }
 47240  #endif
 47241  
 47242  /*
 47243  ** File control method. For custom operations on an memdb-file.
 47244  */
 47245  static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
 47246    MemFile *p = (MemFile *)pFile;
 47247    int rc = SQLITE_NOTFOUND;
 47248    if( op==SQLITE_FCNTL_VFSNAME ){
 47249      *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
 47250      rc = SQLITE_OK;
 47251    }
 47252    if( op==SQLITE_FCNTL_SIZE_LIMIT ){
 47253      sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
 47254      if( iLimit<p->sz ){
 47255        if( iLimit<0 ){
 47256          iLimit = p->szMax;
 47257        }else{
 47258          iLimit = p->sz;
 47259        }
 47260      }
 47261      p->szMax = iLimit;
 47262      *(sqlite3_int64*)pArg = iLimit;
 47263      rc = SQLITE_OK;
 47264    }
 47265    return rc;
 47266  }
 47267  
 47268  #if 0  /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
 47269  /*
 47270  ** Return the sector-size in bytes for an memdb-file.
 47271  */
 47272  static int memdbSectorSize(sqlite3_file *pFile){
 47273    return 1024;
 47274  }
 47275  #endif
 47276  
 47277  /*
 47278  ** Return the device characteristic flags supported by an memdb-file.
 47279  */
 47280  static int memdbDeviceCharacteristics(sqlite3_file *pFile){
 47281    return SQLITE_IOCAP_ATOMIC | 
 47282           SQLITE_IOCAP_POWERSAFE_OVERWRITE |
 47283           SQLITE_IOCAP_SAFE_APPEND |
 47284           SQLITE_IOCAP_SEQUENTIAL;
 47285  }
 47286  
 47287  /* Fetch a page of a memory-mapped file */
 47288  static int memdbFetch(
 47289    sqlite3_file *pFile,
 47290    sqlite3_int64 iOfst,
 47291    int iAmt,
 47292    void **pp
 47293  ){
 47294    MemFile *p = (MemFile *)pFile;
 47295    if( iOfst+iAmt>p->sz ){
 47296      *pp = 0;
 47297    }else{
 47298      p->nMmap++;
 47299      *pp = (void*)(p->aData + iOfst);
 47300    }
 47301    return SQLITE_OK;
 47302  }
 47303  
 47304  /* Release a memory-mapped page */
 47305  static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
 47306    MemFile *p = (MemFile *)pFile;
 47307    p->nMmap--;
 47308    return SQLITE_OK;
 47309  }
 47310  
 47311  /*
 47312  ** Open an mem file handle.
 47313  */
 47314  static int memdbOpen(
 47315    sqlite3_vfs *pVfs,
 47316    const char *zName,
 47317    sqlite3_file *pFile,
 47318    int flags,
 47319    int *pOutFlags
 47320  ){
 47321    MemFile *p = (MemFile*)pFile;
 47322    if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
 47323      return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
 47324    }
 47325    memset(p, 0, sizeof(*p));
 47326    p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
 47327    assert( pOutFlags!=0 );  /* True because flags==SQLITE_OPEN_MAIN_DB */
 47328    *pOutFlags = flags | SQLITE_OPEN_MEMORY;
 47329    p->base.pMethods = &memdb_io_methods;
 47330    p->szMax = sqlite3GlobalConfig.mxMemdbSize;
 47331    return SQLITE_OK;
 47332  }
 47333  
 47334  #if 0 /* Only used to delete rollback journals, master journals, and WAL
 47335        ** files, none of which exist in memdb.  So this routine is never used */
 47336  /*
 47337  ** Delete the file located at zPath. If the dirSync argument is true,
 47338  ** ensure the file-system modifications are synced to disk before
 47339  ** returning.
 47340  */
 47341  static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 47342    return SQLITE_IOERR_DELETE;
 47343  }
 47344  #endif
 47345  
 47346  /*
 47347  ** Test for access permissions. Return true if the requested permission
 47348  ** is available, or false otherwise.
 47349  **
 47350  ** With memdb, no files ever exist on disk.  So always return false.
 47351  */
 47352  static int memdbAccess(
 47353    sqlite3_vfs *pVfs, 
 47354    const char *zPath, 
 47355    int flags, 
 47356    int *pResOut
 47357  ){
 47358    *pResOut = 0;
 47359    return SQLITE_OK;
 47360  }
 47361  
 47362  /*
 47363  ** Populate buffer zOut with the full canonical pathname corresponding
 47364  ** to the pathname in zPath. zOut is guaranteed to point to a buffer
 47365  ** of at least (INST_MAX_PATHNAME+1) bytes.
 47366  */
 47367  static int memdbFullPathname(
 47368    sqlite3_vfs *pVfs, 
 47369    const char *zPath, 
 47370    int nOut, 
 47371    char *zOut
 47372  ){
 47373    sqlite3_snprintf(nOut, zOut, "%s", zPath);
 47374    return SQLITE_OK;
 47375  }
 47376  
 47377  /*
 47378  ** Open the dynamic library located at zPath and return a handle.
 47379  */
 47380  static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 47381    return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
 47382  }
 47383  
 47384  /*
 47385  ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
 47386  ** utf-8 string describing the most recent error encountered associated 
 47387  ** with dynamic libraries.
 47388  */
 47389  static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
 47390    ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
 47391  }
 47392  
 47393  /*
 47394  ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
 47395  */
 47396  static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
 47397    return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
 47398  }
 47399  
 47400  /*
 47401  ** Close the dynamic library handle pHandle.
 47402  */
 47403  static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
 47404    ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
 47405  }
 47406  
 47407  /*
 47408  ** Populate the buffer pointed to by zBufOut with nByte bytes of 
 47409  ** random data.
 47410  */
 47411  static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 47412    return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
 47413  }
 47414  
 47415  /*
 47416  ** Sleep for nMicro microseconds. Return the number of microseconds 
 47417  ** actually slept.
 47418  */
 47419  static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
 47420    return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
 47421  }
 47422  
 47423  #if 0  /* Never used.  Modern cores only call xCurrentTimeInt64() */
 47424  /*
 47425  ** Return the current time as a Julian Day number in *pTimeOut.
 47426  */
 47427  static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
 47428    return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
 47429  }
 47430  #endif
 47431  
 47432  static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
 47433    return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
 47434  }
 47435  static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
 47436    return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
 47437  }
 47438  
 47439  /*
 47440  ** Translate a database connection pointer and schema name into a
 47441  ** MemFile pointer.
 47442  */
 47443  static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
 47444    MemFile *p = 0;
 47445    int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
 47446    if( rc ) return 0;
 47447    if( p->base.pMethods!=&memdb_io_methods ) return 0;
 47448    return p;
 47449  }
 47450  
 47451  /*
 47452  ** Return the serialization of a database
 47453  */
 47454  SQLITE_API unsigned char *sqlite3_serialize(
 47455    sqlite3 *db,              /* The database connection */
 47456    const char *zSchema,      /* Which database within the connection */
 47457    sqlite3_int64 *piSize,    /* Write size here, if not NULL */
 47458    unsigned int mFlags       /* Maybe SQLITE_SERIALIZE_NOCOPY */
 47459  ){
 47460    MemFile *p;
 47461    int iDb;
 47462    Btree *pBt;
 47463    sqlite3_int64 sz;
 47464    int szPage = 0;
 47465    sqlite3_stmt *pStmt = 0;
 47466    unsigned char *pOut;
 47467    char *zSql;
 47468    int rc;
 47469  
 47470  #ifdef SQLITE_ENABLE_API_ARMOR
 47471    if( !sqlite3SafetyCheckOk(db) ){
 47472      (void)SQLITE_MISUSE_BKPT;
 47473      return 0;
 47474    }
 47475  #endif
 47476  
 47477    if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
 47478    p = memdbFromDbSchema(db, zSchema);
 47479    iDb = sqlite3FindDbName(db, zSchema);
 47480    if( piSize ) *piSize = -1;
 47481    if( iDb<0 ) return 0;
 47482    if( p ){
 47483      if( piSize ) *piSize = p->sz;
 47484      if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
 47485        pOut = p->aData;
 47486      }else{
 47487        pOut = sqlite3_malloc64( p->sz );
 47488        if( pOut ) memcpy(pOut, p->aData, p->sz);
 47489      }
 47490      return pOut;
 47491    }
 47492    pBt = db->aDb[iDb].pBt;
 47493    if( pBt==0 ) return 0;
 47494    szPage = sqlite3BtreeGetPageSize(pBt);
 47495    zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
 47496    rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
 47497    sqlite3_free(zSql);
 47498    if( rc ) return 0;
 47499    rc = sqlite3_step(pStmt);
 47500    if( rc!=SQLITE_ROW ){
 47501      pOut = 0;
 47502    }else{
 47503      sz = sqlite3_column_int64(pStmt, 0)*szPage;
 47504      if( piSize ) *piSize = sz;
 47505      if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
 47506        pOut = 0;
 47507      }else{
 47508        pOut = sqlite3_malloc64( sz );
 47509        if( pOut ){
 47510          int nPage = sqlite3_column_int(pStmt, 0);
 47511          Pager *pPager = sqlite3BtreePager(pBt);
 47512          int pgno;
 47513          for(pgno=1; pgno<=nPage; pgno++){
 47514            DbPage *pPage = 0;
 47515            unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
 47516            rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
 47517            if( rc==SQLITE_OK ){
 47518              memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
 47519            }else{
 47520              memset(pTo, 0, szPage);
 47521            }
 47522            sqlite3PagerUnref(pPage);       
 47523          }
 47524        }
 47525      }
 47526    }
 47527    sqlite3_finalize(pStmt);
 47528    return pOut;
 47529  }
 47530  
 47531  /* Convert zSchema to a MemDB and initialize its content.
 47532  */
 47533  SQLITE_API int sqlite3_deserialize(
 47534    sqlite3 *db,            /* The database connection */
 47535    const char *zSchema,    /* Which DB to reopen with the deserialization */
 47536    unsigned char *pData,   /* The serialized database content */
 47537    sqlite3_int64 szDb,     /* Number bytes in the deserialization */
 47538    sqlite3_int64 szBuf,    /* Total size of buffer pData[] */
 47539    unsigned mFlags         /* Zero or more SQLITE_DESERIALIZE_* flags */
 47540  ){
 47541    MemFile *p;
 47542    char *zSql;
 47543    sqlite3_stmt *pStmt = 0;
 47544    int rc;
 47545    int iDb;
 47546  
 47547  #ifdef SQLITE_ENABLE_API_ARMOR
 47548    if( !sqlite3SafetyCheckOk(db) ){
 47549      return SQLITE_MISUSE_BKPT;
 47550    }
 47551    if( szDb<0 ) return SQLITE_MISUSE_BKPT;
 47552    if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
 47553  #endif
 47554  
 47555    sqlite3_mutex_enter(db->mutex);
 47556    if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
 47557    iDb = sqlite3FindDbName(db, zSchema);
 47558    if( iDb<0 ){
 47559      rc = SQLITE_ERROR;
 47560      goto end_deserialize;
 47561    }    
 47562    zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
 47563    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
 47564    sqlite3_free(zSql);
 47565    if( rc ) goto end_deserialize;
 47566    db->init.iDb = (u8)iDb;
 47567    db->init.reopenMemdb = 1;
 47568    rc = sqlite3_step(pStmt);
 47569    db->init.reopenMemdb = 0;
 47570    if( rc!=SQLITE_DONE ){
 47571      rc = SQLITE_ERROR;
 47572      goto end_deserialize;
 47573    }
 47574    p = memdbFromDbSchema(db, zSchema);
 47575    if( p==0 ){
 47576      rc = SQLITE_ERROR;
 47577    }else{
 47578      p->aData = pData;
 47579      p->sz = szDb;
 47580      p->szAlloc = szBuf;
 47581      p->szMax = szBuf;
 47582      if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
 47583        p->szMax = sqlite3GlobalConfig.mxMemdbSize;
 47584      }
 47585      p->mFlags = mFlags;
 47586      rc = SQLITE_OK;
 47587    }
 47588  
 47589  end_deserialize:
 47590    sqlite3_finalize(pStmt);
 47591    sqlite3_mutex_leave(db->mutex);
 47592    return rc;
 47593  }
 47594  
 47595  /* 
 47596  ** This routine is called when the extension is loaded.
 47597  ** Register the new VFS.
 47598  */
 47599  SQLITE_PRIVATE int sqlite3MemdbInit(void){
 47600    sqlite3_vfs *pLower = sqlite3_vfs_find(0);
 47601    int sz = pLower->szOsFile;
 47602    memdb_vfs.pAppData = pLower;
 47603    /* In all known configurations of SQLite, the size of a default
 47604    ** sqlite3_file is greater than the size of a memdb sqlite3_file.
 47605    ** Should that ever change, remove the following NEVER() */
 47606    if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
 47607    memdb_vfs.szOsFile = sz;
 47608    return sqlite3_vfs_register(&memdb_vfs, 0);
 47609  }
 47610  #endif /* SQLITE_ENABLE_DESERIALIZE */
 47611  
 47612  /************** End of memdb.c ***********************************************/
 47613  /************** Begin file bitvec.c ******************************************/
 47614  /*
 47615  ** 2008 February 16
 47616  **
 47617  ** The author disclaims copyright to this source code.  In place of
 47618  ** a legal notice, here is a blessing:
 47619  **
 47620  **    May you do good and not evil.
 47621  **    May you find forgiveness for yourself and forgive others.
 47622  **    May you share freely, never taking more than you give.
 47623  **
 47624  *************************************************************************
 47625  ** This file implements an object that represents a fixed-length
 47626  ** bitmap.  Bits are numbered starting with 1.
 47627  **
 47628  ** A bitmap is used to record which pages of a database file have been
 47629  ** journalled during a transaction, or which pages have the "dont-write"
 47630  ** property.  Usually only a few pages are meet either condition.
 47631  ** So the bitmap is usually sparse and has low cardinality.
 47632  ** But sometimes (for example when during a DROP of a large table) most
 47633  ** or all of the pages in a database can get journalled.  In those cases, 
 47634  ** the bitmap becomes dense with high cardinality.  The algorithm needs 
 47635  ** to handle both cases well.
 47636  **
 47637  ** The size of the bitmap is fixed when the object is created.
 47638  **
 47639  ** All bits are clear when the bitmap is created.  Individual bits
 47640  ** may be set or cleared one at a time.
 47641  **
 47642  ** Test operations are about 100 times more common that set operations.
 47643  ** Clear operations are exceedingly rare.  There are usually between
 47644  ** 5 and 500 set operations per Bitvec object, though the number of sets can
 47645  ** sometimes grow into tens of thousands or larger.  The size of the
 47646  ** Bitvec object is the number of pages in the database file at the
 47647  ** start of a transaction, and is thus usually less than a few thousand,
 47648  ** but can be as large as 2 billion for a really big database.
 47649  */
 47650  /* #include "sqliteInt.h" */
 47651  
 47652  /* Size of the Bitvec structure in bytes. */
 47653  #define BITVEC_SZ        512
 47654  
 47655  /* Round the union size down to the nearest pointer boundary, since that's how 
 47656  ** it will be aligned within the Bitvec struct. */
 47657  #define BITVEC_USIZE \
 47658      (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
 47659  
 47660  /* Type of the array "element" for the bitmap representation. 
 47661  ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
 47662  ** Setting this to the "natural word" size of your CPU may improve
 47663  ** performance. */
 47664  #define BITVEC_TELEM     u8
 47665  /* Size, in bits, of the bitmap element. */
 47666  #define BITVEC_SZELEM    8
 47667  /* Number of elements in a bitmap array. */
 47668  #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
 47669  /* Number of bits in the bitmap array. */
 47670  #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
 47671  
 47672  /* Number of u32 values in hash table. */
 47673  #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
 47674  /* Maximum number of entries in hash table before 
 47675  ** sub-dividing and re-hashing. */
 47676  #define BITVEC_MXHASH    (BITVEC_NINT/2)
 47677  /* Hashing function for the aHash representation.
 47678  ** Empirical testing showed that the *37 multiplier 
 47679  ** (an arbitrary prime)in the hash function provided 
 47680  ** no fewer collisions than the no-op *1. */
 47681  #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
 47682  
 47683  #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
 47684  
 47685  
 47686  /*
 47687  ** A bitmap is an instance of the following structure.
 47688  **
 47689  ** This bitmap records the existence of zero or more bits
 47690  ** with values between 1 and iSize, inclusive.
 47691  **
 47692  ** There are three possible representations of the bitmap.
 47693  ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
 47694  ** bitmap.  The least significant bit is bit 1.
 47695  **
 47696  ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
 47697  ** a hash table that will hold up to BITVEC_MXHASH distinct values.
 47698  **
 47699  ** Otherwise, the value i is redirected into one of BITVEC_NPTR
 47700  ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
 47701  ** handles up to iDivisor separate values of i.  apSub[0] holds
 47702  ** values between 1 and iDivisor.  apSub[1] holds values between
 47703  ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
 47704  ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
 47705  ** to hold deal with values between 1 and iDivisor.
 47706  */
 47707  struct Bitvec {
 47708    u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
 47709    u32 nSet;       /* Number of bits that are set - only valid for aHash
 47710                    ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
 47711                    ** this would be 125. */
 47712    u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
 47713                    /* Should >=0 for apSub element. */
 47714                    /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
 47715                    /* For a BITVEC_SZ of 512, this would be 34,359,739. */
 47716    union {
 47717      BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
 47718      u32 aHash[BITVEC_NINT];      /* Hash table representation */
 47719      Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
 47720    } u;
 47721  };
 47722  
 47723  /*
 47724  ** Create a new bitmap object able to handle bits between 0 and iSize,
 47725  ** inclusive.  Return a pointer to the new object.  Return NULL if 
 47726  ** malloc fails.
 47727  */
 47728  SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
 47729    Bitvec *p;
 47730    assert( sizeof(*p)==BITVEC_SZ );
 47731    p = sqlite3MallocZero( sizeof(*p) );
 47732    if( p ){
 47733      p->iSize = iSize;
 47734    }
 47735    return p;
 47736  }
 47737  
 47738  /*
 47739  ** Check to see if the i-th bit is set.  Return true or false.
 47740  ** If p is NULL (if the bitmap has not been created) or if
 47741  ** i is out of range, then return false.
 47742  */
 47743  SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
 47744    assert( p!=0 );
 47745    i--;
 47746    if( i>=p->iSize ) return 0;
 47747    while( p->iDivisor ){
 47748      u32 bin = i/p->iDivisor;
 47749      i = i%p->iDivisor;
 47750      p = p->u.apSub[bin];
 47751      if (!p) {
 47752        return 0;
 47753      }
 47754    }
 47755    if( p->iSize<=BITVEC_NBIT ){
 47756      return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
 47757    } else{
 47758      u32 h = BITVEC_HASH(i++);
 47759      while( p->u.aHash[h] ){
 47760        if( p->u.aHash[h]==i ) return 1;
 47761        h = (h+1) % BITVEC_NINT;
 47762      }
 47763      return 0;
 47764    }
 47765  }
 47766  SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
 47767    return p!=0 && sqlite3BitvecTestNotNull(p,i);
 47768  }
 47769  
 47770  /*
 47771  ** Set the i-th bit.  Return 0 on success and an error code if
 47772  ** anything goes wrong.
 47773  **
 47774  ** This routine might cause sub-bitmaps to be allocated.  Failing
 47775  ** to get the memory needed to hold the sub-bitmap is the only
 47776  ** that can go wrong with an insert, assuming p and i are valid.
 47777  **
 47778  ** The calling function must ensure that p is a valid Bitvec object
 47779  ** and that the value for "i" is within range of the Bitvec object.
 47780  ** Otherwise the behavior is undefined.
 47781  */
 47782  SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
 47783    u32 h;
 47784    if( p==0 ) return SQLITE_OK;
 47785    assert( i>0 );
 47786    assert( i<=p->iSize );
 47787    i--;
 47788    while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
 47789      u32 bin = i/p->iDivisor;
 47790      i = i%p->iDivisor;
 47791      if( p->u.apSub[bin]==0 ){
 47792        p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
 47793        if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
 47794      }
 47795      p = p->u.apSub[bin];
 47796    }
 47797    if( p->iSize<=BITVEC_NBIT ){
 47798      p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
 47799      return SQLITE_OK;
 47800    }
 47801    h = BITVEC_HASH(i++);
 47802    /* if there wasn't a hash collision, and this doesn't */
 47803    /* completely fill the hash, then just add it without */
 47804    /* worring about sub-dividing and re-hashing. */
 47805    if( !p->u.aHash[h] ){
 47806      if (p->nSet<(BITVEC_NINT-1)) {
 47807        goto bitvec_set_end;
 47808      } else {
 47809        goto bitvec_set_rehash;
 47810      }
 47811    }
 47812    /* there was a collision, check to see if it's already */
 47813    /* in hash, if not, try to find a spot for it */
 47814    do {
 47815      if( p->u.aHash[h]==i ) return SQLITE_OK;
 47816      h++;
 47817      if( h>=BITVEC_NINT ) h = 0;
 47818    } while( p->u.aHash[h] );
 47819    /* we didn't find it in the hash.  h points to the first */
 47820    /* available free spot. check to see if this is going to */
 47821    /* make our hash too "full".  */
 47822  bitvec_set_rehash:
 47823    if( p->nSet>=BITVEC_MXHASH ){
 47824      unsigned int j;
 47825      int rc;
 47826      u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
 47827      if( aiValues==0 ){
 47828        return SQLITE_NOMEM_BKPT;
 47829      }else{
 47830        memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 47831        memset(p->u.apSub, 0, sizeof(p->u.apSub));
 47832        p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
 47833        rc = sqlite3BitvecSet(p, i);
 47834        for(j=0; j<BITVEC_NINT; j++){
 47835          if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
 47836        }
 47837        sqlite3StackFree(0, aiValues);
 47838        return rc;
 47839      }
 47840    }
 47841  bitvec_set_end:
 47842    p->nSet++;
 47843    p->u.aHash[h] = i;
 47844    return SQLITE_OK;
 47845  }
 47846  
 47847  /*
 47848  ** Clear the i-th bit.
 47849  **
 47850  ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
 47851  ** that BitvecClear can use to rebuilt its hash table.
 47852  */
 47853  SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
 47854    if( p==0 ) return;
 47855    assert( i>0 );
 47856    i--;
 47857    while( p->iDivisor ){
 47858      u32 bin = i/p->iDivisor;
 47859      i = i%p->iDivisor;
 47860      p = p->u.apSub[bin];
 47861      if (!p) {
 47862        return;
 47863      }
 47864    }
 47865    if( p->iSize<=BITVEC_NBIT ){
 47866      p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
 47867    }else{
 47868      unsigned int j;
 47869      u32 *aiValues = pBuf;
 47870      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
 47871      memset(p->u.aHash, 0, sizeof(p->u.aHash));
 47872      p->nSet = 0;
 47873      for(j=0; j<BITVEC_NINT; j++){
 47874        if( aiValues[j] && aiValues[j]!=(i+1) ){
 47875          u32 h = BITVEC_HASH(aiValues[j]-1);
 47876          p->nSet++;
 47877          while( p->u.aHash[h] ){
 47878            h++;
 47879            if( h>=BITVEC_NINT ) h = 0;
 47880          }
 47881          p->u.aHash[h] = aiValues[j];
 47882        }
 47883      }
 47884    }
 47885  }
 47886  
 47887  /*
 47888  ** Destroy a bitmap object.  Reclaim all memory used.
 47889  */
 47890  SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
 47891    if( p==0 ) return;
 47892    if( p->iDivisor ){
 47893      unsigned int i;
 47894      for(i=0; i<BITVEC_NPTR; i++){
 47895        sqlite3BitvecDestroy(p->u.apSub[i]);
 47896      }
 47897    }
 47898    sqlite3_free(p);
 47899  }
 47900  
 47901  /*
 47902  ** Return the value of the iSize parameter specified when Bitvec *p
 47903  ** was created.
 47904  */
 47905  SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
 47906    return p->iSize;
 47907  }
 47908  
 47909  #ifndef SQLITE_UNTESTABLE
 47910  /*
 47911  ** Let V[] be an array of unsigned characters sufficient to hold
 47912  ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
 47913  ** Then the following macros can be used to set, clear, or test
 47914  ** individual bits within V.
 47915  */
 47916  #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
 47917  #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
 47918  #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
 47919  
 47920  /*
 47921  ** This routine runs an extensive test of the Bitvec code.
 47922  **
 47923  ** The input is an array of integers that acts as a program
 47924  ** to test the Bitvec.  The integers are opcodes followed
 47925  ** by 0, 1, or 3 operands, depending on the opcode.  Another
 47926  ** opcode follows immediately after the last operand.
 47927  **
 47928  ** There are 6 opcodes numbered from 0 through 5.  0 is the
 47929  ** "halt" opcode and causes the test to end.
 47930  **
 47931  **    0          Halt and return the number of errors
 47932  **    1 N S X    Set N bits beginning with S and incrementing by X
 47933  **    2 N S X    Clear N bits beginning with S and incrementing by X
 47934  **    3 N        Set N randomly chosen bits
 47935  **    4 N        Clear N randomly chosen bits
 47936  **    5 N S X    Set N bits from S increment X in array only, not in bitvec
 47937  **
 47938  ** The opcodes 1 through 4 perform set and clear operations are performed
 47939  ** on both a Bitvec object and on a linear array of bits obtained from malloc.
 47940  ** Opcode 5 works on the linear array only, not on the Bitvec.
 47941  ** Opcode 5 is used to deliberately induce a fault in order to
 47942  ** confirm that error detection works.
 47943  **
 47944  ** At the conclusion of the test the linear array is compared
 47945  ** against the Bitvec object.  If there are any differences,
 47946  ** an error is returned.  If they are the same, zero is returned.
 47947  **
 47948  ** If a memory allocation error occurs, return -1.
 47949  */
 47950  SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
 47951    Bitvec *pBitvec = 0;
 47952    unsigned char *pV = 0;
 47953    int rc = -1;
 47954    int i, nx, pc, op;
 47955    void *pTmpSpace;
 47956  
 47957    /* Allocate the Bitvec to be tested and a linear array of
 47958    ** bits to act as the reference */
 47959    pBitvec = sqlite3BitvecCreate( sz );
 47960    pV = sqlite3MallocZero( (sz+7)/8 + 1 );
 47961    pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
 47962    if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
 47963  
 47964    /* NULL pBitvec tests */
 47965    sqlite3BitvecSet(0, 1);
 47966    sqlite3BitvecClear(0, 1, pTmpSpace);
 47967  
 47968    /* Run the program */
 47969    pc = 0;
 47970    while( (op = aOp[pc])!=0 ){
 47971      switch( op ){
 47972        case 1:
 47973        case 2:
 47974        case 5: {
 47975          nx = 4;
 47976          i = aOp[pc+2] - 1;
 47977          aOp[pc+2] += aOp[pc+3];
 47978          break;
 47979        }
 47980        case 3:
 47981        case 4: 
 47982        default: {
 47983          nx = 2;
 47984          sqlite3_randomness(sizeof(i), &i);
 47985          break;
 47986        }
 47987      }
 47988      if( (--aOp[pc+1]) > 0 ) nx = 0;
 47989      pc += nx;
 47990      i = (i & 0x7fffffff)%sz;
 47991      if( (op & 1)!=0 ){
 47992        SETBIT(pV, (i+1));
 47993        if( op!=5 ){
 47994          if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
 47995        }
 47996      }else{
 47997        CLEARBIT(pV, (i+1));
 47998        sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
 47999      }
 48000    }
 48001  
 48002    /* Test to make sure the linear array exactly matches the
 48003    ** Bitvec object.  Start with the assumption that they do
 48004    ** match (rc==0).  Change rc to non-zero if a discrepancy
 48005    ** is found.
 48006    */
 48007    rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
 48008            + sqlite3BitvecTest(pBitvec, 0)
 48009            + (sqlite3BitvecSize(pBitvec) - sz);
 48010    for(i=1; i<=sz; i++){
 48011      if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
 48012        rc = i;
 48013        break;
 48014      }
 48015    }
 48016  
 48017    /* Free allocated structure */
 48018  bitvec_end:
 48019    sqlite3_free(pTmpSpace);
 48020    sqlite3_free(pV);
 48021    sqlite3BitvecDestroy(pBitvec);
 48022    return rc;
 48023  }
 48024  #endif /* SQLITE_UNTESTABLE */
 48025  
 48026  /************** End of bitvec.c **********************************************/
 48027  /************** Begin file pcache.c ******************************************/
 48028  /*
 48029  ** 2008 August 05
 48030  **
 48031  ** The author disclaims copyright to this source code.  In place of
 48032  ** a legal notice, here is a blessing:
 48033  **
 48034  **    May you do good and not evil.
 48035  **    May you find forgiveness for yourself and forgive others.
 48036  **    May you share freely, never taking more than you give.
 48037  **
 48038  *************************************************************************
 48039  ** This file implements that page cache.
 48040  */
 48041  /* #include "sqliteInt.h" */
 48042  
 48043  /*
 48044  ** A complete page cache is an instance of this structure.  Every
 48045  ** entry in the cache holds a single page of the database file.  The
 48046  ** btree layer only operates on the cached copy of the database pages.
 48047  **
 48048  ** A page cache entry is "clean" if it exactly matches what is currently
 48049  ** on disk.  A page is "dirty" if it has been modified and needs to be
 48050  ** persisted to disk.
 48051  **
 48052  ** pDirty, pDirtyTail, pSynced:
 48053  **   All dirty pages are linked into the doubly linked list using
 48054  **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
 48055  **   such that p was added to the list more recently than p->pDirtyNext.
 48056  **   PCache.pDirty points to the first (newest) element in the list and
 48057  **   pDirtyTail to the last (oldest).
 48058  **
 48059  **   The PCache.pSynced variable is used to optimize searching for a dirty
 48060  **   page to eject from the cache mid-transaction. It is better to eject
 48061  **   a page that does not require a journal sync than one that does. 
 48062  **   Therefore, pSynced is maintained so that it *almost* always points
 48063  **   to either the oldest page in the pDirty/pDirtyTail list that has a
 48064  **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
 48065  **   (so that the right page to eject can be found by following pDirtyPrev
 48066  **   pointers).
 48067  */
 48068  struct PCache {
 48069    PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
 48070    PgHdr *pSynced;                     /* Last synced page in dirty page list */
 48071    int nRefSum;                        /* Sum of ref counts over all pages */
 48072    int szCache;                        /* Configured cache size */
 48073    int szSpill;                        /* Size before spilling occurs */
 48074    int szPage;                         /* Size of every page in this cache */
 48075    int szExtra;                        /* Size of extra space for each page */
 48076    u8 bPurgeable;                      /* True if pages are on backing store */
 48077    u8 eCreate;                         /* eCreate value for for xFetch() */
 48078    int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
 48079    void *pStress;                      /* Argument to xStress */
 48080    sqlite3_pcache *pCache;             /* Pluggable cache module */
 48081  };
 48082  
 48083  /********************************** Test and Debug Logic **********************/
 48084  /*
 48085  ** Debug tracing macros.  Enable by by changing the "0" to "1" and
 48086  ** recompiling.
 48087  **
 48088  ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
 48089  ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
 48090  ** is displayed for many operations, resulting in a lot of output.
 48091  */
 48092  #if defined(SQLITE_DEBUG) && 0
 48093    int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
 48094    int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
 48095  # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
 48096    void pcacheDump(PCache *pCache){
 48097      int N;
 48098      int i, j;
 48099      sqlite3_pcache_page *pLower;
 48100      PgHdr *pPg;
 48101      unsigned char *a;
 48102    
 48103      if( sqlite3PcacheTrace<2 ) return;
 48104      if( pCache->pCache==0 ) return;
 48105      N = sqlite3PcachePagecount(pCache);
 48106      if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
 48107      for(i=1; i<=N; i++){
 48108         pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
 48109         if( pLower==0 ) continue;
 48110         pPg = (PgHdr*)pLower->pExtra;
 48111         printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
 48112         a = (unsigned char *)pLower->pBuf;
 48113         for(j=0; j<12; j++) printf("%02x", a[j]);
 48114         printf("\n");
 48115         if( pPg->pPage==0 ){
 48116           sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
 48117         }
 48118      }
 48119    }
 48120    #else
 48121  # define pcacheTrace(X)
 48122  # define pcacheDump(X)
 48123  #endif
 48124  
 48125  /*
 48126  ** Check invariants on a PgHdr entry.  Return true if everything is OK.
 48127  ** Return false if any invariant is violated.
 48128  **
 48129  ** This routine is for use inside of assert() statements only.  For
 48130  ** example:
 48131  **
 48132  **          assert( sqlite3PcachePageSanity(pPg) );
 48133  */
 48134  #ifdef SQLITE_DEBUG
 48135  SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
 48136    PCache *pCache;
 48137    assert( pPg!=0 );
 48138    assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
 48139    pCache = pPg->pCache;
 48140    assert( pCache!=0 );      /* Every page has an associated PCache */
 48141    if( pPg->flags & PGHDR_CLEAN ){
 48142      assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
 48143      assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
 48144      assert( pCache->pDirtyTail!=pPg );
 48145    }
 48146    /* WRITEABLE pages must also be DIRTY */
 48147    if( pPg->flags & PGHDR_WRITEABLE ){
 48148      assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
 48149    }
 48150    /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
 48151    ** for example, when using the sqlite3PagerDontWrite() optimization:
 48152    **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
 48153    **    (2)  Page X moved to freelist, WRITEABLE is cleared
 48154    **    (3)  Page X reused, WRITEABLE is set again
 48155    ** If NEED_SYNC had been cleared in step 2, then it would not be reset
 48156    ** in step 3, and page might be written into the database without first
 48157    ** syncing the rollback journal, which might cause corruption on a power
 48158    ** loss.
 48159    **
 48160    ** Another example is when the database page size is smaller than the
 48161    ** disk sector size.  When any page of a sector is journalled, all pages
 48162    ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
 48163    ** in case they are later modified, since all pages in the same sector
 48164    ** must be journalled and synced before any of those pages can be safely
 48165    ** written.
 48166    */
 48167    return 1;
 48168  }
 48169  #endif /* SQLITE_DEBUG */
 48170  
 48171  
 48172  /********************************** Linked List Management ********************/
 48173  
 48174  /* Allowed values for second argument to pcacheManageDirtyList() */
 48175  #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
 48176  #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
 48177  #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
 48178  
 48179  /*
 48180  ** Manage pPage's participation on the dirty list.  Bits of the addRemove
 48181  ** argument determines what operation to do.  The 0x01 bit means first
 48182  ** remove pPage from the dirty list.  The 0x02 means add pPage back to
 48183  ** the dirty list.  Doing both moves pPage to the front of the dirty list.
 48184  */
 48185  static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
 48186    PCache *p = pPage->pCache;
 48187  
 48188    pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
 48189                  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
 48190                  pPage->pgno));
 48191    if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
 48192      assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
 48193      assert( pPage->pDirtyPrev || pPage==p->pDirty );
 48194    
 48195      /* Update the PCache1.pSynced variable if necessary. */
 48196      if( p->pSynced==pPage ){
 48197        p->pSynced = pPage->pDirtyPrev;
 48198      }
 48199    
 48200      if( pPage->pDirtyNext ){
 48201        pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
 48202      }else{
 48203        assert( pPage==p->pDirtyTail );
 48204        p->pDirtyTail = pPage->pDirtyPrev;
 48205      }
 48206      if( pPage->pDirtyPrev ){
 48207        pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
 48208      }else{
 48209        /* If there are now no dirty pages in the cache, set eCreate to 2. 
 48210        ** This is an optimization that allows sqlite3PcacheFetch() to skip
 48211        ** searching for a dirty page to eject from the cache when it might
 48212        ** otherwise have to.  */
 48213        assert( pPage==p->pDirty );
 48214        p->pDirty = pPage->pDirtyNext;
 48215        assert( p->bPurgeable || p->eCreate==2 );
 48216        if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
 48217          assert( p->bPurgeable==0 || p->eCreate==1 );
 48218          p->eCreate = 2;
 48219        }
 48220      }
 48221    }
 48222    if( addRemove & PCACHE_DIRTYLIST_ADD ){
 48223      pPage->pDirtyPrev = 0;
 48224      pPage->pDirtyNext = p->pDirty;
 48225      if( pPage->pDirtyNext ){
 48226        assert( pPage->pDirtyNext->pDirtyPrev==0 );
 48227        pPage->pDirtyNext->pDirtyPrev = pPage;
 48228      }else{
 48229        p->pDirtyTail = pPage;
 48230        if( p->bPurgeable ){
 48231          assert( p->eCreate==2 );
 48232          p->eCreate = 1;
 48233        }
 48234      }
 48235      p->pDirty = pPage;
 48236  
 48237      /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
 48238      ** pSynced to point to it. Checking the NEED_SYNC flag is an 
 48239      ** optimization, as if pSynced points to a page with the NEED_SYNC
 48240      ** flag set sqlite3PcacheFetchStress() searches through all newer 
 48241      ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
 48242      if( !p->pSynced 
 48243       && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
 48244      ){
 48245        p->pSynced = pPage;
 48246      }
 48247    }
 48248    pcacheDump(p);
 48249  }
 48250  
 48251  /*
 48252  ** Wrapper around the pluggable caches xUnpin method. If the cache is
 48253  ** being used for an in-memory database, this function is a no-op.
 48254  */
 48255  static void pcacheUnpin(PgHdr *p){
 48256    if( p->pCache->bPurgeable ){
 48257      pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
 48258      sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
 48259      pcacheDump(p->pCache);
 48260    }
 48261  }
 48262  
 48263  /*
 48264  ** Compute the number of pages of cache requested.   p->szCache is the
 48265  ** cache size requested by the "PRAGMA cache_size" statement.
 48266  */
 48267  static int numberOfCachePages(PCache *p){
 48268    if( p->szCache>=0 ){
 48269      /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
 48270      ** suggested cache size is set to N. */
 48271      return p->szCache;
 48272    }else{
 48273      /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
 48274      ** the number of cache pages is adjusted to use approximately abs(N*1024)
 48275      ** bytes of memory. */
 48276      return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
 48277    }
 48278  }
 48279  
 48280  /*************************************************** General Interfaces ******
 48281  **
 48282  ** Initialize and shutdown the page cache subsystem. Neither of these 
 48283  ** functions are threadsafe.
 48284  */
 48285  SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
 48286    if( sqlite3GlobalConfig.pcache2.xInit==0 ){
 48287      /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
 48288      ** built-in default page cache is used instead of the application defined
 48289      ** page cache. */
 48290      sqlite3PCacheSetDefault();
 48291    }
 48292    return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
 48293  }
 48294  SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
 48295    if( sqlite3GlobalConfig.pcache2.xShutdown ){
 48296      /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
 48297      sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
 48298    }
 48299  }
 48300  
 48301  /*
 48302  ** Return the size in bytes of a PCache object.
 48303  */
 48304  SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
 48305  
 48306  /*
 48307  ** Create a new PCache object. Storage space to hold the object
 48308  ** has already been allocated and is passed in as the p pointer. 
 48309  ** The caller discovers how much space needs to be allocated by 
 48310  ** calling sqlite3PcacheSize().
 48311  **
 48312  ** szExtra is some extra space allocated for each page.  The first
 48313  ** 8 bytes of the extra space will be zeroed as the page is allocated,
 48314  ** but remaining content will be uninitialized.  Though it is opaque
 48315  ** to this module, the extra space really ends up being the MemPage
 48316  ** structure in the pager.
 48317  */
 48318  SQLITE_PRIVATE int sqlite3PcacheOpen(
 48319    int szPage,                  /* Size of every page */
 48320    int szExtra,                 /* Extra space associated with each page */
 48321    int bPurgeable,              /* True if pages are on backing store */
 48322    int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
 48323    void *pStress,               /* Argument to xStress */
 48324    PCache *p                    /* Preallocated space for the PCache */
 48325  ){
 48326    memset(p, 0, sizeof(PCache));
 48327    p->szPage = 1;
 48328    p->szExtra = szExtra;
 48329    assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
 48330    p->bPurgeable = bPurgeable;
 48331    p->eCreate = 2;
 48332    p->xStress = xStress;
 48333    p->pStress = pStress;
 48334    p->szCache = 100;
 48335    p->szSpill = 1;
 48336    pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
 48337    return sqlite3PcacheSetPageSize(p, szPage);
 48338  }
 48339  
 48340  /*
 48341  ** Change the page size for PCache object. The caller must ensure that there
 48342  ** are no outstanding page references when this function is called.
 48343  */
 48344  SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
 48345    assert( pCache->nRefSum==0 && pCache->pDirty==0 );
 48346    if( pCache->szPage ){
 48347      sqlite3_pcache *pNew;
 48348      pNew = sqlite3GlobalConfig.pcache2.xCreate(
 48349                  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
 48350                  pCache->bPurgeable
 48351      );
 48352      if( pNew==0 ) return SQLITE_NOMEM_BKPT;
 48353      sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
 48354      if( pCache->pCache ){
 48355        sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 48356      }
 48357      pCache->pCache = pNew;
 48358      pCache->szPage = szPage;
 48359      pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
 48360    }
 48361    return SQLITE_OK;
 48362  }
 48363  
 48364  /*
 48365  ** Try to obtain a page from the cache.
 48366  **
 48367  ** This routine returns a pointer to an sqlite3_pcache_page object if
 48368  ** such an object is already in cache, or if a new one is created.
 48369  ** This routine returns a NULL pointer if the object was not in cache
 48370  ** and could not be created.
 48371  **
 48372  ** The createFlags should be 0 to check for existing pages and should
 48373  ** be 3 (not 1, but 3) to try to create a new page.
 48374  **
 48375  ** If the createFlag is 0, then NULL is always returned if the page
 48376  ** is not already in the cache.  If createFlag is 1, then a new page
 48377  ** is created only if that can be done without spilling dirty pages
 48378  ** and without exceeding the cache size limit.
 48379  **
 48380  ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
 48381  ** initialize the sqlite3_pcache_page object and convert it into a
 48382  ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
 48383  ** routines are split this way for performance reasons. When separated
 48384  ** they can both (usually) operate without having to push values to
 48385  ** the stack on entry and pop them back off on exit, which saves a
 48386  ** lot of pushing and popping.
 48387  */
 48388  SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
 48389    PCache *pCache,       /* Obtain the page from this cache */
 48390    Pgno pgno,            /* Page number to obtain */
 48391    int createFlag        /* If true, create page if it does not exist already */
 48392  ){
 48393    int eCreate;
 48394    sqlite3_pcache_page *pRes;
 48395  
 48396    assert( pCache!=0 );
 48397    assert( pCache->pCache!=0 );
 48398    assert( createFlag==3 || createFlag==0 );
 48399    assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
 48400  
 48401    /* eCreate defines what to do if the page does not exist.
 48402    **    0     Do not allocate a new page.  (createFlag==0)
 48403    **    1     Allocate a new page if doing so is inexpensive.
 48404    **          (createFlag==1 AND bPurgeable AND pDirty)
 48405    **    2     Allocate a new page even it doing so is difficult.
 48406    **          (createFlag==1 AND !(bPurgeable AND pDirty)
 48407    */
 48408    eCreate = createFlag & pCache->eCreate;
 48409    assert( eCreate==0 || eCreate==1 || eCreate==2 );
 48410    assert( createFlag==0 || pCache->eCreate==eCreate );
 48411    assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
 48412    pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
 48413    pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
 48414                 createFlag?" create":"",pRes));
 48415    return pRes;
 48416  }
 48417  
 48418  /*
 48419  ** If the sqlite3PcacheFetch() routine is unable to allocate a new
 48420  ** page because no clean pages are available for reuse and the cache
 48421  ** size limit has been reached, then this routine can be invoked to 
 48422  ** try harder to allocate a page.  This routine might invoke the stress
 48423  ** callback to spill dirty pages to the journal.  It will then try to
 48424  ** allocate the new page and will only fail to allocate a new page on
 48425  ** an OOM error.
 48426  **
 48427  ** This routine should be invoked only after sqlite3PcacheFetch() fails.
 48428  */
 48429  SQLITE_PRIVATE int sqlite3PcacheFetchStress(
 48430    PCache *pCache,                 /* Obtain the page from this cache */
 48431    Pgno pgno,                      /* Page number to obtain */
 48432    sqlite3_pcache_page **ppPage    /* Write result here */
 48433  ){
 48434    PgHdr *pPg;
 48435    if( pCache->eCreate==2 ) return 0;
 48436  
 48437    if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
 48438      /* Find a dirty page to write-out and recycle. First try to find a 
 48439      ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
 48440      ** cleared), but if that is not possible settle for any other 
 48441      ** unreferenced dirty page.
 48442      **
 48443      ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
 48444      ** flag is currently referenced, then the following may leave pSynced
 48445      ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
 48446      ** cleared). This is Ok, as pSynced is just an optimization.  */
 48447      for(pPg=pCache->pSynced; 
 48448          pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
 48449          pPg=pPg->pDirtyPrev
 48450      );
 48451      pCache->pSynced = pPg;
 48452      if( !pPg ){
 48453        for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
 48454      }
 48455      if( pPg ){
 48456        int rc;
 48457  #ifdef SQLITE_LOG_CACHE_SPILL
 48458        sqlite3_log(SQLITE_FULL, 
 48459                    "spill page %d making room for %d - cache used: %d/%d",
 48460                    pPg->pgno, pgno,
 48461                    sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
 48462                  numberOfCachePages(pCache));
 48463  #endif
 48464        pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
 48465        rc = pCache->xStress(pCache->pStress, pPg);
 48466        pcacheDump(pCache);
 48467        if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
 48468          return rc;
 48469        }
 48470      }
 48471    }
 48472    *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
 48473    return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
 48474  }
 48475  
 48476  /*
 48477  ** This is a helper routine for sqlite3PcacheFetchFinish()
 48478  **
 48479  ** In the uncommon case where the page being fetched has not been
 48480  ** initialized, this routine is invoked to do the initialization.
 48481  ** This routine is broken out into a separate function since it
 48482  ** requires extra stack manipulation that can be avoided in the common
 48483  ** case.
 48484  */
 48485  static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
 48486    PCache *pCache,             /* Obtain the page from this cache */
 48487    Pgno pgno,                  /* Page number obtained */
 48488    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
 48489  ){
 48490    PgHdr *pPgHdr;
 48491    assert( pPage!=0 );
 48492    pPgHdr = (PgHdr*)pPage->pExtra;
 48493    assert( pPgHdr->pPage==0 );
 48494    memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
 48495    pPgHdr->pPage = pPage;
 48496    pPgHdr->pData = pPage->pBuf;
 48497    pPgHdr->pExtra = (void *)&pPgHdr[1];
 48498    memset(pPgHdr->pExtra, 0, 8);
 48499    pPgHdr->pCache = pCache;
 48500    pPgHdr->pgno = pgno;
 48501    pPgHdr->flags = PGHDR_CLEAN;
 48502    return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
 48503  }
 48504  
 48505  /*
 48506  ** This routine converts the sqlite3_pcache_page object returned by
 48507  ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
 48508  ** must be called after sqlite3PcacheFetch() in order to get a usable
 48509  ** result.
 48510  */
 48511  SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
 48512    PCache *pCache,             /* Obtain the page from this cache */
 48513    Pgno pgno,                  /* Page number obtained */
 48514    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
 48515  ){
 48516    PgHdr *pPgHdr;
 48517  
 48518    assert( pPage!=0 );
 48519    pPgHdr = (PgHdr *)pPage->pExtra;
 48520  
 48521    if( !pPgHdr->pPage ){
 48522      return pcacheFetchFinishWithInit(pCache, pgno, pPage);
 48523    }
 48524    pCache->nRefSum++;
 48525    pPgHdr->nRef++;
 48526    assert( sqlite3PcachePageSanity(pPgHdr) );
 48527    return pPgHdr;
 48528  }
 48529  
 48530  /*
 48531  ** Decrement the reference count on a page. If the page is clean and the
 48532  ** reference count drops to 0, then it is made eligible for recycling.
 48533  */
 48534  SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
 48535    assert( p->nRef>0 );
 48536    p->pCache->nRefSum--;
 48537    if( (--p->nRef)==0 ){
 48538      if( p->flags&PGHDR_CLEAN ){
 48539        pcacheUnpin(p);
 48540      }else{
 48541        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
 48542      }
 48543    }
 48544  }
 48545  
 48546  /*
 48547  ** Increase the reference count of a supplied page by 1.
 48548  */
 48549  SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
 48550    assert(p->nRef>0);
 48551    assert( sqlite3PcachePageSanity(p) );
 48552    p->nRef++;
 48553    p->pCache->nRefSum++;
 48554  }
 48555  
 48556  /*
 48557  ** Drop a page from the cache. There must be exactly one reference to the
 48558  ** page. This function deletes that reference, so after it returns the
 48559  ** page pointed to by p is invalid.
 48560  */
 48561  SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
 48562    assert( p->nRef==1 );
 48563    assert( sqlite3PcachePageSanity(p) );
 48564    if( p->flags&PGHDR_DIRTY ){
 48565      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
 48566    }
 48567    p->pCache->nRefSum--;
 48568    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
 48569  }
 48570  
 48571  /*
 48572  ** Make sure the page is marked as dirty. If it isn't dirty already,
 48573  ** make it so.
 48574  */
 48575  SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
 48576    assert( p->nRef>0 );
 48577    assert( sqlite3PcachePageSanity(p) );
 48578    if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
 48579      p->flags &= ~PGHDR_DONT_WRITE;
 48580      if( p->flags & PGHDR_CLEAN ){
 48581        p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
 48582        pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
 48583        assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
 48584        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
 48585      }
 48586      assert( sqlite3PcachePageSanity(p) );
 48587    }
 48588  }
 48589  
 48590  /*
 48591  ** Make sure the page is marked as clean. If it isn't clean already,
 48592  ** make it so.
 48593  */
 48594  SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
 48595    assert( sqlite3PcachePageSanity(p) );
 48596    assert( (p->flags & PGHDR_DIRTY)!=0 );
 48597    assert( (p->flags & PGHDR_CLEAN)==0 );
 48598    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
 48599    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
 48600    p->flags |= PGHDR_CLEAN;
 48601    pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
 48602    assert( sqlite3PcachePageSanity(p) );
 48603    if( p->nRef==0 ){
 48604      pcacheUnpin(p);
 48605    }
 48606  }
 48607  
 48608  /*
 48609  ** Make every page in the cache clean.
 48610  */
 48611  SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
 48612    PgHdr *p;
 48613    pcacheTrace(("%p.CLEAN-ALL\n",pCache));
 48614    while( (p = pCache->pDirty)!=0 ){
 48615      sqlite3PcacheMakeClean(p);
 48616    }
 48617  }
 48618  
 48619  /*
 48620  ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
 48621  */
 48622  SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
 48623    PgHdr *p;
 48624    pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
 48625    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 48626      p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
 48627    }
 48628    pCache->pSynced = pCache->pDirtyTail;
 48629  }
 48630  
 48631  /*
 48632  ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
 48633  */
 48634  SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
 48635    PgHdr *p;
 48636    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 48637      p->flags &= ~PGHDR_NEED_SYNC;
 48638    }
 48639    pCache->pSynced = pCache->pDirtyTail;
 48640  }
 48641  
 48642  /*
 48643  ** Change the page number of page p to newPgno. 
 48644  */
 48645  SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
 48646    PCache *pCache = p->pCache;
 48647    assert( p->nRef>0 );
 48648    assert( newPgno>0 );
 48649    assert( sqlite3PcachePageSanity(p) );
 48650    pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
 48651    sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
 48652    p->pgno = newPgno;
 48653    if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
 48654      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
 48655    }
 48656  }
 48657  
 48658  /*
 48659  ** Drop every cache entry whose page number is greater than "pgno". The
 48660  ** caller must ensure that there are no outstanding references to any pages
 48661  ** other than page 1 with a page number greater than pgno.
 48662  **
 48663  ** If there is a reference to page 1 and the pgno parameter passed to this
 48664  ** function is 0, then the data area associated with page 1 is zeroed, but
 48665  ** the page object is not dropped.
 48666  */
 48667  SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
 48668    if( pCache->pCache ){
 48669      PgHdr *p;
 48670      PgHdr *pNext;
 48671      pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
 48672      for(p=pCache->pDirty; p; p=pNext){
 48673        pNext = p->pDirtyNext;
 48674        /* This routine never gets call with a positive pgno except right
 48675        ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
 48676        ** it must be that pgno==0.
 48677        */
 48678        assert( p->pgno>0 );
 48679        if( p->pgno>pgno ){
 48680          assert( p->flags&PGHDR_DIRTY );
 48681          sqlite3PcacheMakeClean(p);
 48682        }
 48683      }
 48684      if( pgno==0 && pCache->nRefSum ){
 48685        sqlite3_pcache_page *pPage1;
 48686        pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
 48687        if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
 48688                               ** pCache->nRefSum>0 */
 48689          memset(pPage1->pBuf, 0, pCache->szPage);
 48690          pgno = 1;
 48691        }
 48692      }
 48693      sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
 48694    }
 48695  }
 48696  
 48697  /*
 48698  ** Close a cache.
 48699  */
 48700  SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
 48701    assert( pCache->pCache!=0 );
 48702    pcacheTrace(("%p.CLOSE\n",pCache));
 48703    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 48704  }
 48705  
 48706  /* 
 48707  ** Discard the contents of the cache.
 48708  */
 48709  SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
 48710    sqlite3PcacheTruncate(pCache, 0);
 48711  }
 48712  
 48713  /*
 48714  ** Merge two lists of pages connected by pDirty and in pgno order.
 48715  ** Do not bother fixing the pDirtyPrev pointers.
 48716  */
 48717  static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
 48718    PgHdr result, *pTail;
 48719    pTail = &result;
 48720    assert( pA!=0 && pB!=0 );
 48721    for(;;){
 48722      if( pA->pgno<pB->pgno ){
 48723        pTail->pDirty = pA;
 48724        pTail = pA;
 48725        pA = pA->pDirty;
 48726        if( pA==0 ){
 48727          pTail->pDirty = pB;
 48728          break;
 48729        }
 48730      }else{
 48731        pTail->pDirty = pB;
 48732        pTail = pB;
 48733        pB = pB->pDirty;
 48734        if( pB==0 ){
 48735          pTail->pDirty = pA;
 48736          break;
 48737        }
 48738      }
 48739    }
 48740    return result.pDirty;
 48741  }
 48742  
 48743  /*
 48744  ** Sort the list of pages in accending order by pgno.  Pages are
 48745  ** connected by pDirty pointers.  The pDirtyPrev pointers are
 48746  ** corrupted by this sort.
 48747  **
 48748  ** Since there cannot be more than 2^31 distinct pages in a database,
 48749  ** there cannot be more than 31 buckets required by the merge sorter.
 48750  ** One extra bucket is added to catch overflow in case something
 48751  ** ever changes to make the previous sentence incorrect.
 48752  */
 48753  #define N_SORT_BUCKET  32
 48754  static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
 48755    PgHdr *a[N_SORT_BUCKET], *p;
 48756    int i;
 48757    memset(a, 0, sizeof(a));
 48758    while( pIn ){
 48759      p = pIn;
 48760      pIn = p->pDirty;
 48761      p->pDirty = 0;
 48762      for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
 48763        if( a[i]==0 ){
 48764          a[i] = p;
 48765          break;
 48766        }else{
 48767          p = pcacheMergeDirtyList(a[i], p);
 48768          a[i] = 0;
 48769        }
 48770      }
 48771      if( NEVER(i==N_SORT_BUCKET-1) ){
 48772        /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
 48773        ** the input list.  But that is impossible.
 48774        */
 48775        a[i] = pcacheMergeDirtyList(a[i], p);
 48776      }
 48777    }
 48778    p = a[0];
 48779    for(i=1; i<N_SORT_BUCKET; i++){
 48780      if( a[i]==0 ) continue;
 48781      p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
 48782    }
 48783    return p;
 48784  }
 48785  
 48786  /*
 48787  ** Return a list of all dirty pages in the cache, sorted by page number.
 48788  */
 48789  SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
 48790    PgHdr *p;
 48791    for(p=pCache->pDirty; p; p=p->pDirtyNext){
 48792      p->pDirty = p->pDirtyNext;
 48793    }
 48794    return pcacheSortDirtyList(pCache->pDirty);
 48795  }
 48796  
 48797  /* 
 48798  ** Return the total number of references to all pages held by the cache.
 48799  **
 48800  ** This is not the total number of pages referenced, but the sum of the
 48801  ** reference count for all pages.
 48802  */
 48803  SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
 48804    return pCache->nRefSum;
 48805  }
 48806  
 48807  /*
 48808  ** Return the number of references to the page supplied as an argument.
 48809  */
 48810  SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
 48811    return p->nRef;
 48812  }
 48813  
 48814  /* 
 48815  ** Return the total number of pages in the cache.
 48816  */
 48817  SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
 48818    assert( pCache->pCache!=0 );
 48819    return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
 48820  }
 48821  
 48822  #ifdef SQLITE_TEST
 48823  /*
 48824  ** Get the suggested cache-size value.
 48825  */
 48826  SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
 48827    return numberOfCachePages(pCache);
 48828  }
 48829  #endif
 48830  
 48831  /*
 48832  ** Set the suggested cache-size value.
 48833  */
 48834  SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
 48835    assert( pCache->pCache!=0 );
 48836    pCache->szCache = mxPage;
 48837    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
 48838                                           numberOfCachePages(pCache));
 48839  }
 48840  
 48841  /*
 48842  ** Set the suggested cache-spill value.  Make no changes if if the
 48843  ** argument is zero.  Return the effective cache-spill size, which will
 48844  ** be the larger of the szSpill and szCache.
 48845  */
 48846  SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
 48847    int res;
 48848    assert( p->pCache!=0 );
 48849    if( mxPage ){
 48850      if( mxPage<0 ){
 48851        mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
 48852      }
 48853      p->szSpill = mxPage;
 48854    }
 48855    res = numberOfCachePages(p);
 48856    if( res<p->szSpill ) res = p->szSpill; 
 48857    return res;
 48858  }
 48859  
 48860  /*
 48861  ** Free up as much memory as possible from the page cache.
 48862  */
 48863  SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
 48864    assert( pCache->pCache!=0 );
 48865    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
 48866  }
 48867  
 48868  /*
 48869  ** Return the size of the header added by this middleware layer
 48870  ** in the page-cache hierarchy.
 48871  */
 48872  SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
 48873  
 48874  /*
 48875  ** Return the number of dirty pages currently in the cache, as a percentage
 48876  ** of the configured cache size.
 48877  */
 48878  SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
 48879    PgHdr *pDirty;
 48880    int nDirty = 0;
 48881    int nCache = numberOfCachePages(pCache);
 48882    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
 48883    return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
 48884  }
 48885  
 48886  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 48887  /* 
 48888  ** Return true if there are one or more dirty pages in the cache. Else false.
 48889  */
 48890  SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
 48891    return (pCache->pDirty!=0);
 48892  }
 48893  #endif
 48894  
 48895  #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 48896  /*
 48897  ** For all dirty pages currently in the cache, invoke the specified
 48898  ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
 48899  ** defined.
 48900  */
 48901  SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
 48902    PgHdr *pDirty;
 48903    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
 48904      xIter(pDirty);
 48905    }
 48906  }
 48907  #endif
 48908  
 48909  /************** End of pcache.c **********************************************/
 48910  /************** Begin file pcache1.c *****************************************/
 48911  /*
 48912  ** 2008 November 05
 48913  **
 48914  ** The author disclaims copyright to this source code.  In place of
 48915  ** a legal notice, here is a blessing:
 48916  **
 48917  **    May you do good and not evil.
 48918  **    May you find forgiveness for yourself and forgive others.
 48919  **    May you share freely, never taking more than you give.
 48920  **
 48921  *************************************************************************
 48922  **
 48923  ** This file implements the default page cache implementation (the
 48924  ** sqlite3_pcache interface). It also contains part of the implementation
 48925  ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
 48926  ** If the default page cache implementation is overridden, then neither of
 48927  ** these two features are available.
 48928  **
 48929  ** A Page cache line looks like this:
 48930  **
 48931  **  -------------------------------------------------------------
 48932  **  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
 48933  **  -------------------------------------------------------------
 48934  **
 48935  ** The database page content is up front (so that buffer overreads tend to
 48936  ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
 48937  ** is the extension added by the btree.c module containing information such
 48938  ** as the database page number and how that database page is used.  PgHdr
 48939  ** is added by the pcache.c layer and contains information used to keep track
 48940  ** of which pages are "dirty".  PgHdr1 is an extension added by this
 48941  ** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
 48942  ** PgHdr1 contains information needed to look up a page by its page number.
 48943  ** The superclass sqlite3_pcache_page.pBuf points to the start of the
 48944  ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
 48945  **
 48946  ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
 48947  ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
 48948  ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
 48949  ** size can vary according to architecture, compile-time options, and
 48950  ** SQLite library version number.
 48951  **
 48952  ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
 48953  ** using a separate memory allocation from the database page content.  This
 48954  ** seeks to overcome the "clownshoe" problem (also called "internal
 48955  ** fragmentation" in academic literature) of allocating a few bytes more
 48956  ** than a power of two with the memory allocator rounding up to the next
 48957  ** power of two, and leaving the rounded-up space unused.
 48958  **
 48959  ** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
 48960  ** with this module.  Information is passed back and forth as PgHdr1 pointers.
 48961  **
 48962  ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
 48963  ** The btree.c module deals with pointers to MemPage objects.
 48964  **
 48965  ** SOURCE OF PAGE CACHE MEMORY:
 48966  **
 48967  ** Memory for a page might come from any of three sources:
 48968  **
 48969  **    (1)  The general-purpose memory allocator - sqlite3Malloc()
 48970  **    (2)  Global page-cache memory provided using sqlite3_config() with
 48971  **         SQLITE_CONFIG_PAGECACHE.
 48972  **    (3)  PCache-local bulk allocation.
 48973  **
 48974  ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
 48975  ** that is allocated when the page cache is created.  The size of the local
 48976  ** bulk allocation can be adjusted using 
 48977  **
 48978  **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
 48979  **
 48980  ** If N is positive, then N pages worth of memory are allocated using a single
 48981  ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
 48982  ** Or if N is negative, then -1024*N bytes of memory are allocated and used
 48983  ** for as many pages as can be accomodated.
 48984  **
 48985  ** Only one of (2) or (3) can be used.  Once the memory available to (2) or
 48986  ** (3) is exhausted, subsequent allocations fail over to the general-purpose
 48987  ** memory allocator (1).
 48988  **
 48989  ** Earlier versions of SQLite used only methods (1) and (2).  But experiments
 48990  ** show that method (3) with N==100 provides about a 5% performance boost for
 48991  ** common workloads.
 48992  */
 48993  /* #include "sqliteInt.h" */
 48994  
 48995  typedef struct PCache1 PCache1;
 48996  typedef struct PgHdr1 PgHdr1;
 48997  typedef struct PgFreeslot PgFreeslot;
 48998  typedef struct PGroup PGroup;
 48999  
 49000  /*
 49001  ** Each cache entry is represented by an instance of the following 
 49002  ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
 49003  ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
 49004  ** in memory.
 49005  **
 49006  ** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
 49007  ** but causes a 2-byte gap in the structure for most architectures (since 
 49008  ** pointers must be either 4 or 8-byte aligned). As this structure is located
 49009  ** in memory directly after the associated page data, if the database is
 49010  ** corrupt, code at the b-tree layer may overread the page buffer and 
 49011  ** read part of this structure before the corruption is detected. This
 49012  ** can cause a valgrind error if the unitialized gap is accessed. Using u16
 49013  ** ensures there is no such gap, and therefore no bytes of unitialized memory
 49014  ** in the structure.
 49015  */
 49016  struct PgHdr1 {
 49017    sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
 49018    unsigned int iKey;             /* Key value (page number) */
 49019    u16 isBulkLocal;               /* This page from bulk local storage */
 49020    u16 isAnchor;                  /* This is the PGroup.lru element */
 49021    PgHdr1 *pNext;                 /* Next in hash table chain */
 49022    PCache1 *pCache;               /* Cache that currently owns this page */
 49023    PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
 49024    PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
 49025                                   /* NB: pLruPrev is only valid if pLruNext!=0 */
 49026  };
 49027  
 49028  /*
 49029  ** A page is pinned if it is not on the LRU list.  To be "pinned" means
 49030  ** that the page is in active use and must not be deallocated.
 49031  */
 49032  #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
 49033  #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
 49034  
 49035  /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
 49036  ** of one or more PCaches that are able to recycle each other's unpinned
 49037  ** pages when they are under memory pressure.  A PGroup is an instance of
 49038  ** the following object.
 49039  **
 49040  ** This page cache implementation works in one of two modes:
 49041  **
 49042  **   (1)  Every PCache is the sole member of its own PGroup.  There is
 49043  **        one PGroup per PCache.
 49044  **
 49045  **   (2)  There is a single global PGroup that all PCaches are a member
 49046  **        of.
 49047  **
 49048  ** Mode 1 uses more memory (since PCache instances are not able to rob
 49049  ** unused pages from other PCaches) but it also operates without a mutex,
 49050  ** and is therefore often faster.  Mode 2 requires a mutex in order to be
 49051  ** threadsafe, but recycles pages more efficiently.
 49052  **
 49053  ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
 49054  ** PGroup which is the pcache1.grp global variable and its mutex is
 49055  ** SQLITE_MUTEX_STATIC_LRU.
 49056  */
 49057  struct PGroup {
 49058    sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
 49059    unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
 49060    unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
 49061    unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
 49062    unsigned int nPurgeable;       /* Number of purgeable pages allocated */
 49063    PgHdr1 lru;                    /* The beginning and end of the LRU list */
 49064  };
 49065  
 49066  /* Each page cache is an instance of the following object.  Every
 49067  ** open database file (including each in-memory database and each
 49068  ** temporary or transient database) has a single page cache which
 49069  ** is an instance of this object.
 49070  **
 49071  ** Pointers to structures of this type are cast and returned as 
 49072  ** opaque sqlite3_pcache* handles.
 49073  */
 49074  struct PCache1 {
 49075    /* Cache configuration parameters. Page size (szPage) and the purgeable
 49076    ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
 49077    ** cache is created and are never changed thereafter. nMax may be 
 49078    ** modified at any time by a call to the pcache1Cachesize() method.
 49079    ** The PGroup mutex must be held when accessing nMax.
 49080    */
 49081    PGroup *pGroup;                     /* PGroup this cache belongs to */
 49082    unsigned int *pnPurgeable;          /* Pointer to pGroup->nPurgeable */
 49083    int szPage;                         /* Size of database content section */
 49084    int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
 49085    int szAlloc;                        /* Total size of one pcache line */
 49086    int bPurgeable;                     /* True if cache is purgeable */
 49087    unsigned int nMin;                  /* Minimum number of pages reserved */
 49088    unsigned int nMax;                  /* Configured "cache_size" value */
 49089    unsigned int n90pct;                /* nMax*9/10 */
 49090    unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
 49091    unsigned int nPurgeableDummy;       /* pnPurgeable points here when not used*/
 49092  
 49093    /* Hash table of all pages. The following variables may only be accessed
 49094    ** when the accessor is holding the PGroup mutex.
 49095    */
 49096    unsigned int nRecyclable;           /* Number of pages in the LRU list */
 49097    unsigned int nPage;                 /* Total number of pages in apHash */
 49098    unsigned int nHash;                 /* Number of slots in apHash[] */
 49099    PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
 49100    PgHdr1 *pFree;                      /* List of unused pcache-local pages */
 49101    void *pBulk;                        /* Bulk memory used by pcache-local */
 49102  };
 49103  
 49104  /*
 49105  ** Free slots in the allocator used to divide up the global page cache
 49106  ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
 49107  */
 49108  struct PgFreeslot {
 49109    PgFreeslot *pNext;  /* Next free slot */
 49110  };
 49111  
 49112  /*
 49113  ** Global data used by this cache.
 49114  */
 49115  static SQLITE_WSD struct PCacheGlobal {
 49116    PGroup grp;                    /* The global PGroup for mode (2) */
 49117  
 49118    /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
 49119    ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
 49120    ** fixed at sqlite3_initialize() time and do not require mutex protection.
 49121    ** The nFreeSlot and pFree values do require mutex protection.
 49122    */
 49123    int isInit;                    /* True if initialized */
 49124    int separateCache;             /* Use a new PGroup for each PCache */
 49125    int nInitPage;                 /* Initial bulk allocation size */   
 49126    int szSlot;                    /* Size of each free slot */
 49127    int nSlot;                     /* The number of pcache slots */
 49128    int nReserve;                  /* Try to keep nFreeSlot above this */
 49129    void *pStart, *pEnd;           /* Bounds of global page cache memory */
 49130    /* Above requires no mutex.  Use mutex below for variable that follow. */
 49131    sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
 49132    PgFreeslot *pFree;             /* Free page blocks */
 49133    int nFreeSlot;                 /* Number of unused pcache slots */
 49134    /* The following value requires a mutex to change.  We skip the mutex on
 49135    ** reading because (1) most platforms read a 32-bit integer atomically and
 49136    ** (2) even if an incorrect value is read, no great harm is done since this
 49137    ** is really just an optimization. */
 49138    int bUnderPressure;            /* True if low on PAGECACHE memory */
 49139  } pcache1_g;
 49140  
 49141  /*
 49142  ** All code in this file should access the global structure above via the
 49143  ** alias "pcache1". This ensures that the WSD emulation is used when
 49144  ** compiling for systems that do not support real WSD.
 49145  */
 49146  #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
 49147  
 49148  /*
 49149  ** Macros to enter and leave the PCache LRU mutex.
 49150  */
 49151  #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
 49152  # define pcache1EnterMutex(X)  assert((X)->mutex==0)
 49153  # define pcache1LeaveMutex(X)  assert((X)->mutex==0)
 49154  # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
 49155  #else
 49156  # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
 49157  # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
 49158  # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
 49159  #endif
 49160  
 49161  /******************************************************************************/
 49162  /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
 49163  
 49164  
 49165  /*
 49166  ** This function is called during initialization if a static buffer is 
 49167  ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
 49168  ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
 49169  ** enough to contain 'n' buffers of 'sz' bytes each.
 49170  **
 49171  ** This routine is called from sqlite3_initialize() and so it is guaranteed
 49172  ** to be serialized already.  There is no need for further mutexing.
 49173  */
 49174  SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
 49175    if( pcache1.isInit ){
 49176      PgFreeslot *p;
 49177      if( pBuf==0 ) sz = n = 0;
 49178      if( n==0 ) sz = 0;
 49179      sz = ROUNDDOWN8(sz);
 49180      pcache1.szSlot = sz;
 49181      pcache1.nSlot = pcache1.nFreeSlot = n;
 49182      pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
 49183      pcache1.pStart = pBuf;
 49184      pcache1.pFree = 0;
 49185      pcache1.bUnderPressure = 0;
 49186      while( n-- ){
 49187        p = (PgFreeslot*)pBuf;
 49188        p->pNext = pcache1.pFree;
 49189        pcache1.pFree = p;
 49190        pBuf = (void*)&((char*)pBuf)[sz];
 49191      }
 49192      pcache1.pEnd = pBuf;
 49193    }
 49194  }
 49195  
 49196  /*
 49197  ** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
 49198  ** true if pCache->pFree ends up containing one or more free pages.
 49199  */
 49200  static int pcache1InitBulk(PCache1 *pCache){
 49201    i64 szBulk;
 49202    char *zBulk;
 49203    if( pcache1.nInitPage==0 ) return 0;
 49204    /* Do not bother with a bulk allocation if the cache size very small */
 49205    if( pCache->nMax<3 ) return 0;
 49206    sqlite3BeginBenignMalloc();
 49207    if( pcache1.nInitPage>0 ){
 49208      szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
 49209    }else{
 49210      szBulk = -1024 * (i64)pcache1.nInitPage;
 49211    }
 49212    if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
 49213      szBulk = pCache->szAlloc*(i64)pCache->nMax;
 49214    }
 49215    zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
 49216    sqlite3EndBenignMalloc();
 49217    if( zBulk ){
 49218      int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
 49219      do{
 49220        PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
 49221        pX->page.pBuf = zBulk;
 49222        pX->page.pExtra = &pX[1];
 49223        pX->isBulkLocal = 1;
 49224        pX->isAnchor = 0;
 49225        pX->pNext = pCache->pFree;
 49226        pX->pLruPrev = 0;           /* Initializing this saves a valgrind error */
 49227        pCache->pFree = pX;
 49228        zBulk += pCache->szAlloc;
 49229      }while( --nBulk );
 49230    }
 49231    return pCache->pFree!=0;
 49232  }
 49233  
 49234  /*
 49235  ** Malloc function used within this file to allocate space from the buffer
 49236  ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
 49237  ** such buffer exists or there is no space left in it, this function falls 
 49238  ** back to sqlite3Malloc().
 49239  **
 49240  ** Multiple threads can run this routine at the same time.  Global variables
 49241  ** in pcache1 need to be protected via mutex.
 49242  */
 49243  static void *pcache1Alloc(int nByte){
 49244    void *p = 0;
 49245    assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 49246    if( nByte<=pcache1.szSlot ){
 49247      sqlite3_mutex_enter(pcache1.mutex);
 49248      p = (PgHdr1 *)pcache1.pFree;
 49249      if( p ){
 49250        pcache1.pFree = pcache1.pFree->pNext;
 49251        pcache1.nFreeSlot--;
 49252        pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 49253        assert( pcache1.nFreeSlot>=0 );
 49254        sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
 49255        sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
 49256      }
 49257      sqlite3_mutex_leave(pcache1.mutex);
 49258    }
 49259    if( p==0 ){
 49260      /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
 49261      ** it from sqlite3Malloc instead.
 49262      */
 49263      p = sqlite3Malloc(nByte);
 49264  #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 49265      if( p ){
 49266        int sz = sqlite3MallocSize(p);
 49267        sqlite3_mutex_enter(pcache1.mutex);
 49268        sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
 49269        sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
 49270        sqlite3_mutex_leave(pcache1.mutex);
 49271      }
 49272  #endif
 49273      sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 49274    }
 49275    return p;
 49276  }
 49277  
 49278  /*
 49279  ** Free an allocated buffer obtained from pcache1Alloc().
 49280  */
 49281  static void pcache1Free(void *p){
 49282    if( p==0 ) return;
 49283    if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
 49284      PgFreeslot *pSlot;
 49285      sqlite3_mutex_enter(pcache1.mutex);
 49286      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
 49287      pSlot = (PgFreeslot*)p;
 49288      pSlot->pNext = pcache1.pFree;
 49289      pcache1.pFree = pSlot;
 49290      pcache1.nFreeSlot++;
 49291      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
 49292      assert( pcache1.nFreeSlot<=pcache1.nSlot );
 49293      sqlite3_mutex_leave(pcache1.mutex);
 49294    }else{
 49295      assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 49296      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 49297  #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
 49298      {
 49299        int nFreed = 0;
 49300        nFreed = sqlite3MallocSize(p);
 49301        sqlite3_mutex_enter(pcache1.mutex);
 49302        sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
 49303        sqlite3_mutex_leave(pcache1.mutex);
 49304      }
 49305  #endif
 49306      sqlite3_free(p);
 49307    }
 49308  }
 49309  
 49310  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 49311  /*
 49312  ** Return the size of a pcache allocation
 49313  */
 49314  static int pcache1MemSize(void *p){
 49315    if( p>=pcache1.pStart && p<pcache1.pEnd ){
 49316      return pcache1.szSlot;
 49317    }else{
 49318      int iSize;
 49319      assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
 49320      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
 49321      iSize = sqlite3MallocSize(p);
 49322      sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
 49323      return iSize;
 49324    }
 49325  }
 49326  #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 49327  
 49328  /*
 49329  ** Allocate a new page object initially associated with cache pCache.
 49330  */
 49331  static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
 49332    PgHdr1 *p = 0;
 49333    void *pPg;
 49334  
 49335    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 49336    if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
 49337      p = pCache->pFree;
 49338      pCache->pFree = p->pNext;
 49339      p->pNext = 0;
 49340    }else{
 49341  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 49342      /* The group mutex must be released before pcache1Alloc() is called. This
 49343      ** is because it might call sqlite3_release_memory(), which assumes that 
 49344      ** this mutex is not held. */
 49345      assert( pcache1.separateCache==0 );
 49346      assert( pCache->pGroup==&pcache1.grp );
 49347      pcache1LeaveMutex(pCache->pGroup);
 49348  #endif
 49349      if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
 49350  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 49351      pPg = pcache1Alloc(pCache->szPage);
 49352      p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
 49353      if( !pPg || !p ){
 49354        pcache1Free(pPg);
 49355        sqlite3_free(p);
 49356        pPg = 0;
 49357      }
 49358  #else
 49359      pPg = pcache1Alloc(pCache->szAlloc);
 49360      p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
 49361  #endif
 49362      if( benignMalloc ){ sqlite3EndBenignMalloc(); }
 49363  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 49364      pcache1EnterMutex(pCache->pGroup);
 49365  #endif
 49366      if( pPg==0 ) return 0;
 49367      p->page.pBuf = pPg;
 49368      p->page.pExtra = &p[1];
 49369      p->isBulkLocal = 0;
 49370      p->isAnchor = 0;
 49371    }
 49372    (*pCache->pnPurgeable)++;
 49373    return p;
 49374  }
 49375  
 49376  /*
 49377  ** Free a page object allocated by pcache1AllocPage().
 49378  */
 49379  static void pcache1FreePage(PgHdr1 *p){
 49380    PCache1 *pCache;
 49381    assert( p!=0 );
 49382    pCache = p->pCache;
 49383    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
 49384    if( p->isBulkLocal ){
 49385      p->pNext = pCache->pFree;
 49386      pCache->pFree = p;
 49387    }else{
 49388      pcache1Free(p->page.pBuf);
 49389  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 49390      sqlite3_free(p);
 49391  #endif
 49392    }
 49393    (*pCache->pnPurgeable)--;
 49394  }
 49395  
 49396  /*
 49397  ** Malloc function used by SQLite to obtain space from the buffer configured
 49398  ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
 49399  ** exists, this function falls back to sqlite3Malloc().
 49400  */
 49401  SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
 49402    /* During rebalance operations on a corrupt database file, it is sometimes
 49403    ** (rarely) possible to overread the temporary page buffer by a few bytes.
 49404    ** Enlarge the allocation slightly so that this does not cause problems. */
 49405    return pcache1Alloc(sz);
 49406  }
 49407  
 49408  /*
 49409  ** Free an allocated buffer obtained from sqlite3PageMalloc().
 49410  */
 49411  SQLITE_PRIVATE void sqlite3PageFree(void *p){
 49412    pcache1Free(p);
 49413  }
 49414  
 49415  
 49416  /*
 49417  ** Return true if it desirable to avoid allocating a new page cache
 49418  ** entry.
 49419  **
 49420  ** If memory was allocated specifically to the page cache using
 49421  ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
 49422  ** it is desirable to avoid allocating a new page cache entry because
 49423  ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
 49424  ** for all page cache needs and we should not need to spill the
 49425  ** allocation onto the heap.
 49426  **
 49427  ** Or, the heap is used for all page cache memory but the heap is
 49428  ** under memory pressure, then again it is desirable to avoid
 49429  ** allocating a new page cache entry in order to avoid stressing
 49430  ** the heap even further.
 49431  */
 49432  static int pcache1UnderMemoryPressure(PCache1 *pCache){
 49433    if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
 49434      return pcache1.bUnderPressure;
 49435    }else{
 49436      return sqlite3HeapNearlyFull();
 49437    }
 49438  }
 49439  
 49440  /******************************************************************************/
 49441  /******** General Implementation Functions ************************************/
 49442  
 49443  /*
 49444  ** This function is used to resize the hash table used by the cache passed
 49445  ** as the first argument.
 49446  **
 49447  ** The PCache mutex must be held when this function is called.
 49448  */
 49449  static void pcache1ResizeHash(PCache1 *p){
 49450    PgHdr1 **apNew;
 49451    unsigned int nNew;
 49452    unsigned int i;
 49453  
 49454    assert( sqlite3_mutex_held(p->pGroup->mutex) );
 49455  
 49456    nNew = p->nHash*2;
 49457    if( nNew<256 ){
 49458      nNew = 256;
 49459    }
 49460  
 49461    pcache1LeaveMutex(p->pGroup);
 49462    if( p->nHash ){ sqlite3BeginBenignMalloc(); }
 49463    apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
 49464    if( p->nHash ){ sqlite3EndBenignMalloc(); }
 49465    pcache1EnterMutex(p->pGroup);
 49466    if( apNew ){
 49467      for(i=0; i<p->nHash; i++){
 49468        PgHdr1 *pPage;
 49469        PgHdr1 *pNext = p->apHash[i];
 49470        while( (pPage = pNext)!=0 ){
 49471          unsigned int h = pPage->iKey % nNew;
 49472          pNext = pPage->pNext;
 49473          pPage->pNext = apNew[h];
 49474          apNew[h] = pPage;
 49475        }
 49476      }
 49477      sqlite3_free(p->apHash);
 49478      p->apHash = apNew;
 49479      p->nHash = nNew;
 49480    }
 49481  }
 49482  
 49483  /*
 49484  ** This function is used internally to remove the page pPage from the 
 49485  ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
 49486  ** LRU list, then this function is a no-op.
 49487  **
 49488  ** The PGroup mutex must be held when this function is called.
 49489  */
 49490  static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
 49491    assert( pPage!=0 );
 49492    assert( PAGE_IS_UNPINNED(pPage) );
 49493    assert( pPage->pLruNext );
 49494    assert( pPage->pLruPrev );
 49495    assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
 49496    pPage->pLruPrev->pLruNext = pPage->pLruNext;
 49497    pPage->pLruNext->pLruPrev = pPage->pLruPrev;
 49498    pPage->pLruNext = 0;
 49499    /* pPage->pLruPrev = 0;
 49500    ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
 49501    assert( pPage->isAnchor==0 );
 49502    assert( pPage->pCache->pGroup->lru.isAnchor==1 );
 49503    pPage->pCache->nRecyclable--;
 49504    return pPage;
 49505  }
 49506  
 49507  
 49508  /*
 49509  ** Remove the page supplied as an argument from the hash table 
 49510  ** (PCache1.apHash structure) that it is currently stored in.
 49511  ** Also free the page if freePage is true.
 49512  **
 49513  ** The PGroup mutex must be held when this function is called.
 49514  */
 49515  static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
 49516    unsigned int h;
 49517    PCache1 *pCache = pPage->pCache;
 49518    PgHdr1 **pp;
 49519  
 49520    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 49521    h = pPage->iKey % pCache->nHash;
 49522    for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
 49523    *pp = (*pp)->pNext;
 49524  
 49525    pCache->nPage--;
 49526    if( freeFlag ) pcache1FreePage(pPage);
 49527  }
 49528  
 49529  /*
 49530  ** If there are currently more than nMaxPage pages allocated, try
 49531  ** to recycle pages to reduce the number allocated to nMaxPage.
 49532  */
 49533  static void pcache1EnforceMaxPage(PCache1 *pCache){
 49534    PGroup *pGroup = pCache->pGroup;
 49535    PgHdr1 *p;
 49536    assert( sqlite3_mutex_held(pGroup->mutex) );
 49537    while( pGroup->nPurgeable>pGroup->nMaxPage
 49538        && (p=pGroup->lru.pLruPrev)->isAnchor==0
 49539    ){
 49540      assert( p->pCache->pGroup==pGroup );
 49541      assert( PAGE_IS_UNPINNED(p) );
 49542      pcache1PinPage(p);
 49543      pcache1RemoveFromHash(p, 1);
 49544    }
 49545    if( pCache->nPage==0 && pCache->pBulk ){
 49546      sqlite3_free(pCache->pBulk);
 49547      pCache->pBulk = pCache->pFree = 0;
 49548    }
 49549  }
 49550  
 49551  /*
 49552  ** Discard all pages from cache pCache with a page number (key value) 
 49553  ** greater than or equal to iLimit. Any pinned pages that meet this 
 49554  ** criteria are unpinned before they are discarded.
 49555  **
 49556  ** The PCache mutex must be held when this function is called.
 49557  */
 49558  static void pcache1TruncateUnsafe(
 49559    PCache1 *pCache,             /* The cache to truncate */
 49560    unsigned int iLimit          /* Drop pages with this pgno or larger */
 49561  ){
 49562    TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
 49563    unsigned int h, iStop;
 49564    assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
 49565    assert( pCache->iMaxKey >= iLimit );
 49566    assert( pCache->nHash > 0 );
 49567    if( pCache->iMaxKey - iLimit < pCache->nHash ){
 49568      /* If we are just shaving the last few pages off the end of the
 49569      ** cache, then there is no point in scanning the entire hash table.
 49570      ** Only scan those hash slots that might contain pages that need to
 49571      ** be removed. */
 49572      h = iLimit % pCache->nHash;
 49573      iStop = pCache->iMaxKey % pCache->nHash;
 49574      TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
 49575    }else{
 49576      /* This is the general case where many pages are being removed.
 49577      ** It is necessary to scan the entire hash table */
 49578      h = pCache->nHash/2;
 49579      iStop = h - 1;
 49580    }
 49581    for(;;){
 49582      PgHdr1 **pp;
 49583      PgHdr1 *pPage;
 49584      assert( h<pCache->nHash );
 49585      pp = &pCache->apHash[h]; 
 49586      while( (pPage = *pp)!=0 ){
 49587        if( pPage->iKey>=iLimit ){
 49588          pCache->nPage--;
 49589          *pp = pPage->pNext;
 49590          if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
 49591          pcache1FreePage(pPage);
 49592        }else{
 49593          pp = &pPage->pNext;
 49594          TESTONLY( if( nPage>=0 ) nPage++; )
 49595        }
 49596      }
 49597      if( h==iStop ) break;
 49598      h = (h+1) % pCache->nHash;
 49599    }
 49600    assert( nPage<0 || pCache->nPage==(unsigned)nPage );
 49601  }
 49602  
 49603  /******************************************************************************/
 49604  /******** sqlite3_pcache Methods **********************************************/
 49605  
 49606  /*
 49607  ** Implementation of the sqlite3_pcache.xInit method.
 49608  */
 49609  static int pcache1Init(void *NotUsed){
 49610    UNUSED_PARAMETER(NotUsed);
 49611    assert( pcache1.isInit==0 );
 49612    memset(&pcache1, 0, sizeof(pcache1));
 49613  
 49614  
 49615    /*
 49616    ** The pcache1.separateCache variable is true if each PCache has its own
 49617    ** private PGroup (mode-1).  pcache1.separateCache is false if the single
 49618    ** PGroup in pcache1.grp is used for all page caches (mode-2).
 49619    **
 49620    **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
 49621    **
 49622    **   *  Use a unified cache in single-threaded applications that have
 49623    **      configured a start-time buffer for use as page-cache memory using
 49624    **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL 
 49625    **      pBuf argument.
 49626    **
 49627    **   *  Otherwise use separate caches (mode-1)
 49628    */
 49629  #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
 49630    pcache1.separateCache = 0;
 49631  #elif SQLITE_THREADSAFE
 49632    pcache1.separateCache = sqlite3GlobalConfig.pPage==0
 49633                            || sqlite3GlobalConfig.bCoreMutex>0;
 49634  #else
 49635    pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
 49636  #endif
 49637  
 49638  #if SQLITE_THREADSAFE
 49639    if( sqlite3GlobalConfig.bCoreMutex ){
 49640      pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
 49641      pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
 49642    }
 49643  #endif
 49644    if( pcache1.separateCache
 49645     && sqlite3GlobalConfig.nPage!=0
 49646     && sqlite3GlobalConfig.pPage==0
 49647    ){
 49648      pcache1.nInitPage = sqlite3GlobalConfig.nPage;
 49649    }else{
 49650      pcache1.nInitPage = 0;
 49651    }
 49652    pcache1.grp.mxPinned = 10;
 49653    pcache1.isInit = 1;
 49654    return SQLITE_OK;
 49655  }
 49656  
 49657  /*
 49658  ** Implementation of the sqlite3_pcache.xShutdown method.
 49659  ** Note that the static mutex allocated in xInit does 
 49660  ** not need to be freed.
 49661  */
 49662  static void pcache1Shutdown(void *NotUsed){
 49663    UNUSED_PARAMETER(NotUsed);
 49664    assert( pcache1.isInit!=0 );
 49665    memset(&pcache1, 0, sizeof(pcache1));
 49666  }
 49667  
 49668  /* forward declaration */
 49669  static void pcache1Destroy(sqlite3_pcache *p);
 49670  
 49671  /*
 49672  ** Implementation of the sqlite3_pcache.xCreate method.
 49673  **
 49674  ** Allocate a new cache.
 49675  */
 49676  static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
 49677    PCache1 *pCache;      /* The newly created page cache */
 49678    PGroup *pGroup;       /* The group the new page cache will belong to */
 49679    int sz;               /* Bytes of memory required to allocate the new cache */
 49680  
 49681    assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
 49682    assert( szExtra < 300 );
 49683  
 49684    sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
 49685    pCache = (PCache1 *)sqlite3MallocZero(sz);
 49686    if( pCache ){
 49687      if( pcache1.separateCache ){
 49688        pGroup = (PGroup*)&pCache[1];
 49689        pGroup->mxPinned = 10;
 49690      }else{
 49691        pGroup = &pcache1.grp;
 49692      }
 49693      if( pGroup->lru.isAnchor==0 ){
 49694        pGroup->lru.isAnchor = 1;
 49695        pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
 49696      }
 49697      pCache->pGroup = pGroup;
 49698      pCache->szPage = szPage;
 49699      pCache->szExtra = szExtra;
 49700      pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
 49701      pCache->bPurgeable = (bPurgeable ? 1 : 0);
 49702      pcache1EnterMutex(pGroup);
 49703      pcache1ResizeHash(pCache);
 49704      if( bPurgeable ){
 49705        pCache->nMin = 10;
 49706        pGroup->nMinPage += pCache->nMin;
 49707        pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 49708        pCache->pnPurgeable = &pGroup->nPurgeable;
 49709      }else{
 49710        pCache->pnPurgeable = &pCache->nPurgeableDummy;
 49711      }
 49712      pcache1LeaveMutex(pGroup);
 49713      if( pCache->nHash==0 ){
 49714        pcache1Destroy((sqlite3_pcache*)pCache);
 49715        pCache = 0;
 49716      }
 49717    }
 49718    return (sqlite3_pcache *)pCache;
 49719  }
 49720  
 49721  /*
 49722  ** Implementation of the sqlite3_pcache.xCachesize method. 
 49723  **
 49724  ** Configure the cache_size limit for a cache.
 49725  */
 49726  static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
 49727    PCache1 *pCache = (PCache1 *)p;
 49728    if( pCache->bPurgeable ){
 49729      PGroup *pGroup = pCache->pGroup;
 49730      pcache1EnterMutex(pGroup);
 49731      pGroup->nMaxPage += (nMax - pCache->nMax);
 49732      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 49733      pCache->nMax = nMax;
 49734      pCache->n90pct = pCache->nMax*9/10;
 49735      pcache1EnforceMaxPage(pCache);
 49736      pcache1LeaveMutex(pGroup);
 49737    }
 49738  }
 49739  
 49740  /*
 49741  ** Implementation of the sqlite3_pcache.xShrink method. 
 49742  **
 49743  ** Free up as much memory as possible.
 49744  */
 49745  static void pcache1Shrink(sqlite3_pcache *p){
 49746    PCache1 *pCache = (PCache1*)p;
 49747    if( pCache->bPurgeable ){
 49748      PGroup *pGroup = pCache->pGroup;
 49749      int savedMaxPage;
 49750      pcache1EnterMutex(pGroup);
 49751      savedMaxPage = pGroup->nMaxPage;
 49752      pGroup->nMaxPage = 0;
 49753      pcache1EnforceMaxPage(pCache);
 49754      pGroup->nMaxPage = savedMaxPage;
 49755      pcache1LeaveMutex(pGroup);
 49756    }
 49757  }
 49758  
 49759  /*
 49760  ** Implementation of the sqlite3_pcache.xPagecount method. 
 49761  */
 49762  static int pcache1Pagecount(sqlite3_pcache *p){
 49763    int n;
 49764    PCache1 *pCache = (PCache1*)p;
 49765    pcache1EnterMutex(pCache->pGroup);
 49766    n = pCache->nPage;
 49767    pcache1LeaveMutex(pCache->pGroup);
 49768    return n;
 49769  }
 49770  
 49771  
 49772  /*
 49773  ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
 49774  ** in the header of the pcache1Fetch() procedure.
 49775  **
 49776  ** This steps are broken out into a separate procedure because they are
 49777  ** usually not needed, and by avoiding the stack initialization required
 49778  ** for these steps, the main pcache1Fetch() procedure can run faster.
 49779  */
 49780  static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 49781    PCache1 *pCache, 
 49782    unsigned int iKey, 
 49783    int createFlag
 49784  ){
 49785    unsigned int nPinned;
 49786    PGroup *pGroup = pCache->pGroup;
 49787    PgHdr1 *pPage = 0;
 49788  
 49789    /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
 49790    assert( pCache->nPage >= pCache->nRecyclable );
 49791    nPinned = pCache->nPage - pCache->nRecyclable;
 49792    assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
 49793    assert( pCache->n90pct == pCache->nMax*9/10 );
 49794    if( createFlag==1 && (
 49795          nPinned>=pGroup->mxPinned
 49796       || nPinned>=pCache->n90pct
 49797       || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
 49798    )){
 49799      return 0;
 49800    }
 49801  
 49802    if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
 49803    assert( pCache->nHash>0 && pCache->apHash );
 49804  
 49805    /* Step 4. Try to recycle a page. */
 49806    if( pCache->bPurgeable
 49807     && !pGroup->lru.pLruPrev->isAnchor
 49808     && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
 49809    ){
 49810      PCache1 *pOther;
 49811      pPage = pGroup->lru.pLruPrev;
 49812      assert( PAGE_IS_UNPINNED(pPage) );
 49813      pcache1RemoveFromHash(pPage, 0);
 49814      pcache1PinPage(pPage);
 49815      pOther = pPage->pCache;
 49816      if( pOther->szAlloc != pCache->szAlloc ){
 49817        pcache1FreePage(pPage);
 49818        pPage = 0;
 49819      }else{
 49820        pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
 49821      }
 49822    }
 49823  
 49824    /* Step 5. If a usable page buffer has still not been found, 
 49825    ** attempt to allocate a new one. 
 49826    */
 49827    if( !pPage ){
 49828      pPage = pcache1AllocPage(pCache, createFlag==1);
 49829    }
 49830  
 49831    if( pPage ){
 49832      unsigned int h = iKey % pCache->nHash;
 49833      pCache->nPage++;
 49834      pPage->iKey = iKey;
 49835      pPage->pNext = pCache->apHash[h];
 49836      pPage->pCache = pCache;
 49837      pPage->pLruNext = 0;
 49838      /* pPage->pLruPrev = 0;
 49839      ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
 49840      *(void **)pPage->page.pExtra = 0;
 49841      pCache->apHash[h] = pPage;
 49842      if( iKey>pCache->iMaxKey ){
 49843        pCache->iMaxKey = iKey;
 49844      }
 49845    }
 49846    return pPage;
 49847  }
 49848  
 49849  /*
 49850  ** Implementation of the sqlite3_pcache.xFetch method. 
 49851  **
 49852  ** Fetch a page by key value.
 49853  **
 49854  ** Whether or not a new page may be allocated by this function depends on
 49855  ** the value of the createFlag argument.  0 means do not allocate a new
 49856  ** page.  1 means allocate a new page if space is easily available.  2 
 49857  ** means to try really hard to allocate a new page.
 49858  **
 49859  ** For a non-purgeable cache (a cache used as the storage for an in-memory
 49860  ** database) there is really no difference between createFlag 1 and 2.  So
 49861  ** the calling function (pcache.c) will never have a createFlag of 1 on
 49862  ** a non-purgeable cache.
 49863  **
 49864  ** There are three different approaches to obtaining space for a page,
 49865  ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
 49866  **
 49867  **   1. Regardless of the value of createFlag, the cache is searched for a 
 49868  **      copy of the requested page. If one is found, it is returned.
 49869  **
 49870  **   2. If createFlag==0 and the page is not already in the cache, NULL is
 49871  **      returned.
 49872  **
 49873  **   3. If createFlag is 1, and the page is not already in the cache, then
 49874  **      return NULL (do not allocate a new page) if any of the following
 49875  **      conditions are true:
 49876  **
 49877  **       (a) the number of pages pinned by the cache is greater than
 49878  **           PCache1.nMax, or
 49879  **
 49880  **       (b) the number of pages pinned by the cache is greater than
 49881  **           the sum of nMax for all purgeable caches, less the sum of 
 49882  **           nMin for all other purgeable caches, or
 49883  **
 49884  **   4. If none of the first three conditions apply and the cache is marked
 49885  **      as purgeable, and if one of the following is true:
 49886  **
 49887  **       (a) The number of pages allocated for the cache is already 
 49888  **           PCache1.nMax, or
 49889  **
 49890  **       (b) The number of pages allocated for all purgeable caches is
 49891  **           already equal to or greater than the sum of nMax for all
 49892  **           purgeable caches,
 49893  **
 49894  **       (c) The system is under memory pressure and wants to avoid
 49895  **           unnecessary pages cache entry allocations
 49896  **
 49897  **      then attempt to recycle a page from the LRU list. If it is the right
 49898  **      size, return the recycled buffer. Otherwise, free the buffer and
 49899  **      proceed to step 5. 
 49900  **
 49901  **   5. Otherwise, allocate and return a new page buffer.
 49902  **
 49903  ** There are two versions of this routine.  pcache1FetchWithMutex() is
 49904  ** the general case.  pcache1FetchNoMutex() is a faster implementation for
 49905  ** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
 49906  ** invokes the appropriate routine.
 49907  */
 49908  static PgHdr1 *pcache1FetchNoMutex(
 49909    sqlite3_pcache *p, 
 49910    unsigned int iKey, 
 49911    int createFlag
 49912  ){
 49913    PCache1 *pCache = (PCache1 *)p;
 49914    PgHdr1 *pPage = 0;
 49915  
 49916    /* Step 1: Search the hash table for an existing entry. */
 49917    pPage = pCache->apHash[iKey % pCache->nHash];
 49918    while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
 49919  
 49920    /* Step 2: If the page was found in the hash table, then return it.
 49921    ** If the page was not in the hash table and createFlag is 0, abort.
 49922    ** Otherwise (page not in hash and createFlag!=0) continue with
 49923    ** subsequent steps to try to create the page. */
 49924    if( pPage ){
 49925      if( PAGE_IS_UNPINNED(pPage) ){
 49926        return pcache1PinPage(pPage);
 49927      }else{
 49928        return pPage;
 49929      }
 49930    }else if( createFlag ){
 49931      /* Steps 3, 4, and 5 implemented by this subroutine */
 49932      return pcache1FetchStage2(pCache, iKey, createFlag);
 49933    }else{
 49934      return 0;
 49935    }
 49936  }
 49937  #if PCACHE1_MIGHT_USE_GROUP_MUTEX
 49938  static PgHdr1 *pcache1FetchWithMutex(
 49939    sqlite3_pcache *p, 
 49940    unsigned int iKey, 
 49941    int createFlag
 49942  ){
 49943    PCache1 *pCache = (PCache1 *)p;
 49944    PgHdr1 *pPage;
 49945  
 49946    pcache1EnterMutex(pCache->pGroup);
 49947    pPage = pcache1FetchNoMutex(p, iKey, createFlag);
 49948    assert( pPage==0 || pCache->iMaxKey>=iKey );
 49949    pcache1LeaveMutex(pCache->pGroup);
 49950    return pPage;
 49951  }
 49952  #endif
 49953  static sqlite3_pcache_page *pcache1Fetch(
 49954    sqlite3_pcache *p, 
 49955    unsigned int iKey, 
 49956    int createFlag
 49957  ){
 49958  #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
 49959    PCache1 *pCache = (PCache1 *)p;
 49960  #endif
 49961  
 49962    assert( offsetof(PgHdr1,page)==0 );
 49963    assert( pCache->bPurgeable || createFlag!=1 );
 49964    assert( pCache->bPurgeable || pCache->nMin==0 );
 49965    assert( pCache->bPurgeable==0 || pCache->nMin==10 );
 49966    assert( pCache->nMin==0 || pCache->bPurgeable );
 49967    assert( pCache->nHash>0 );
 49968  #if PCACHE1_MIGHT_USE_GROUP_MUTEX
 49969    if( pCache->pGroup->mutex ){
 49970      return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
 49971    }else
 49972  #endif
 49973    {
 49974      return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
 49975    }
 49976  }
 49977  
 49978  
 49979  /*
 49980  ** Implementation of the sqlite3_pcache.xUnpin method.
 49981  **
 49982  ** Mark a page as unpinned (eligible for asynchronous recycling).
 49983  */
 49984  static void pcache1Unpin(
 49985    sqlite3_pcache *p, 
 49986    sqlite3_pcache_page *pPg, 
 49987    int reuseUnlikely
 49988  ){
 49989    PCache1 *pCache = (PCache1 *)p;
 49990    PgHdr1 *pPage = (PgHdr1 *)pPg;
 49991    PGroup *pGroup = pCache->pGroup;
 49992   
 49993    assert( pPage->pCache==pCache );
 49994    pcache1EnterMutex(pGroup);
 49995  
 49996    /* It is an error to call this function if the page is already 
 49997    ** part of the PGroup LRU list.
 49998    */
 49999    assert( pPage->pLruNext==0 );
 50000    assert( PAGE_IS_PINNED(pPage) );
 50001  
 50002    if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
 50003      pcache1RemoveFromHash(pPage, 1);
 50004    }else{
 50005      /* Add the page to the PGroup LRU list. */
 50006      PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
 50007      pPage->pLruPrev = &pGroup->lru;
 50008      (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
 50009      *ppFirst = pPage;
 50010      pCache->nRecyclable++;
 50011    }
 50012  
 50013    pcache1LeaveMutex(pCache->pGroup);
 50014  }
 50015  
 50016  /*
 50017  ** Implementation of the sqlite3_pcache.xRekey method. 
 50018  */
 50019  static void pcache1Rekey(
 50020    sqlite3_pcache *p,
 50021    sqlite3_pcache_page *pPg,
 50022    unsigned int iOld,
 50023    unsigned int iNew
 50024  ){
 50025    PCache1 *pCache = (PCache1 *)p;
 50026    PgHdr1 *pPage = (PgHdr1 *)pPg;
 50027    PgHdr1 **pp;
 50028    unsigned int h; 
 50029    assert( pPage->iKey==iOld );
 50030    assert( pPage->pCache==pCache );
 50031  
 50032    pcache1EnterMutex(pCache->pGroup);
 50033  
 50034    h = iOld%pCache->nHash;
 50035    pp = &pCache->apHash[h];
 50036    while( (*pp)!=pPage ){
 50037      pp = &(*pp)->pNext;
 50038    }
 50039    *pp = pPage->pNext;
 50040  
 50041    h = iNew%pCache->nHash;
 50042    pPage->iKey = iNew;
 50043    pPage->pNext = pCache->apHash[h];
 50044    pCache->apHash[h] = pPage;
 50045    if( iNew>pCache->iMaxKey ){
 50046      pCache->iMaxKey = iNew;
 50047    }
 50048  
 50049    pcache1LeaveMutex(pCache->pGroup);
 50050  }
 50051  
 50052  /*
 50053  ** Implementation of the sqlite3_pcache.xTruncate method. 
 50054  **
 50055  ** Discard all unpinned pages in the cache with a page number equal to
 50056  ** or greater than parameter iLimit. Any pinned pages with a page number
 50057  ** equal to or greater than iLimit are implicitly unpinned.
 50058  */
 50059  static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
 50060    PCache1 *pCache = (PCache1 *)p;
 50061    pcache1EnterMutex(pCache->pGroup);
 50062    if( iLimit<=pCache->iMaxKey ){
 50063      pcache1TruncateUnsafe(pCache, iLimit);
 50064      pCache->iMaxKey = iLimit-1;
 50065    }
 50066    pcache1LeaveMutex(pCache->pGroup);
 50067  }
 50068  
 50069  /*
 50070  ** Implementation of the sqlite3_pcache.xDestroy method. 
 50071  **
 50072  ** Destroy a cache allocated using pcache1Create().
 50073  */
 50074  static void pcache1Destroy(sqlite3_pcache *p){
 50075    PCache1 *pCache = (PCache1 *)p;
 50076    PGroup *pGroup = pCache->pGroup;
 50077    assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
 50078    pcache1EnterMutex(pGroup);
 50079    if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
 50080    assert( pGroup->nMaxPage >= pCache->nMax );
 50081    pGroup->nMaxPage -= pCache->nMax;
 50082    assert( pGroup->nMinPage >= pCache->nMin );
 50083    pGroup->nMinPage -= pCache->nMin;
 50084    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
 50085    pcache1EnforceMaxPage(pCache);
 50086    pcache1LeaveMutex(pGroup);
 50087    sqlite3_free(pCache->pBulk);
 50088    sqlite3_free(pCache->apHash);
 50089    sqlite3_free(pCache);
 50090  }
 50091  
 50092  /*
 50093  ** This function is called during initialization (sqlite3_initialize()) to
 50094  ** install the default pluggable cache module, assuming the user has not
 50095  ** already provided an alternative.
 50096  */
 50097  SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
 50098    static const sqlite3_pcache_methods2 defaultMethods = {
 50099      1,                       /* iVersion */
 50100      0,                       /* pArg */
 50101      pcache1Init,             /* xInit */
 50102      pcache1Shutdown,         /* xShutdown */
 50103      pcache1Create,           /* xCreate */
 50104      pcache1Cachesize,        /* xCachesize */
 50105      pcache1Pagecount,        /* xPagecount */
 50106      pcache1Fetch,            /* xFetch */
 50107      pcache1Unpin,            /* xUnpin */
 50108      pcache1Rekey,            /* xRekey */
 50109      pcache1Truncate,         /* xTruncate */
 50110      pcache1Destroy,          /* xDestroy */
 50111      pcache1Shrink            /* xShrink */
 50112    };
 50113    sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
 50114  }
 50115  
 50116  /*
 50117  ** Return the size of the header on each page of this PCACHE implementation.
 50118  */
 50119  SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
 50120  
 50121  /*
 50122  ** Return the global mutex used by this PCACHE implementation.  The
 50123  ** sqlite3_status() routine needs access to this mutex.
 50124  */
 50125  SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
 50126    return pcache1.mutex;
 50127  }
 50128  
 50129  #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
 50130  /*
 50131  ** This function is called to free superfluous dynamically allocated memory
 50132  ** held by the pager system. Memory in use by any SQLite pager allocated
 50133  ** by the current thread may be sqlite3_free()ed.
 50134  **
 50135  ** nReq is the number of bytes of memory required. Once this much has
 50136  ** been released, the function returns. The return value is the total number 
 50137  ** of bytes of memory released.
 50138  */
 50139  SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
 50140    int nFree = 0;
 50141    assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
 50142    assert( sqlite3_mutex_notheld(pcache1.mutex) );
 50143    if( sqlite3GlobalConfig.pPage==0 ){
 50144      PgHdr1 *p;
 50145      pcache1EnterMutex(&pcache1.grp);
 50146      while( (nReq<0 || nFree<nReq)
 50147         &&  (p=pcache1.grp.lru.pLruPrev)!=0
 50148         &&  p->isAnchor==0
 50149      ){
 50150        nFree += pcache1MemSize(p->page.pBuf);
 50151  #ifdef SQLITE_PCACHE_SEPARATE_HEADER
 50152        nFree += sqlite3MemSize(p);
 50153  #endif
 50154        assert( PAGE_IS_UNPINNED(p) );
 50155        pcache1PinPage(p);
 50156        pcache1RemoveFromHash(p, 1);
 50157      }
 50158      pcache1LeaveMutex(&pcache1.grp);
 50159    }
 50160    return nFree;
 50161  }
 50162  #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
 50163  
 50164  #ifdef SQLITE_TEST
 50165  /*
 50166  ** This function is used by test procedures to inspect the internal state
 50167  ** of the global cache.
 50168  */
 50169  SQLITE_PRIVATE void sqlite3PcacheStats(
 50170    int *pnCurrent,      /* OUT: Total number of pages cached */
 50171    int *pnMax,          /* OUT: Global maximum cache size */
 50172    int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
 50173    int *pnRecyclable    /* OUT: Total number of pages available for recycling */
 50174  ){
 50175    PgHdr1 *p;
 50176    int nRecyclable = 0;
 50177    for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
 50178      assert( PAGE_IS_UNPINNED(p) );
 50179      nRecyclable++;
 50180    }
 50181    *pnCurrent = pcache1.grp.nPurgeable;
 50182    *pnMax = (int)pcache1.grp.nMaxPage;
 50183    *pnMin = (int)pcache1.grp.nMinPage;
 50184    *pnRecyclable = nRecyclable;
 50185  }
 50186  #endif
 50187  
 50188  /************** End of pcache1.c *********************************************/
 50189  /************** Begin file rowset.c ******************************************/
 50190  /*
 50191  ** 2008 December 3
 50192  **
 50193  ** The author disclaims copyright to this source code.  In place of
 50194  ** a legal notice, here is a blessing:
 50195  **
 50196  **    May you do good and not evil.
 50197  **    May you find forgiveness for yourself and forgive others.
 50198  **    May you share freely, never taking more than you give.
 50199  **
 50200  *************************************************************************
 50201  **
 50202  ** This module implements an object we call a "RowSet".
 50203  **
 50204  ** The RowSet object is a collection of rowids.  Rowids
 50205  ** are inserted into the RowSet in an arbitrary order.  Inserts
 50206  ** can be intermixed with tests to see if a given rowid has been
 50207  ** previously inserted into the RowSet.
 50208  **
 50209  ** After all inserts are finished, it is possible to extract the
 50210  ** elements of the RowSet in sorted order.  Once this extraction
 50211  ** process has started, no new elements may be inserted.
 50212  **
 50213  ** Hence, the primitive operations for a RowSet are:
 50214  **
 50215  **    CREATE
 50216  **    INSERT
 50217  **    TEST
 50218  **    SMALLEST
 50219  **    DESTROY
 50220  **
 50221  ** The CREATE and DESTROY primitives are the constructor and destructor,
 50222  ** obviously.  The INSERT primitive adds a new element to the RowSet.
 50223  ** TEST checks to see if an element is already in the RowSet.  SMALLEST
 50224  ** extracts the least value from the RowSet.
 50225  **
 50226  ** The INSERT primitive might allocate additional memory.  Memory is
 50227  ** allocated in chunks so most INSERTs do no allocation.  There is an 
 50228  ** upper bound on the size of allocated memory.  No memory is freed
 50229  ** until DESTROY.
 50230  **
 50231  ** The TEST primitive includes a "batch" number.  The TEST primitive
 50232  ** will only see elements that were inserted before the last change
 50233  ** in the batch number.  In other words, if an INSERT occurs between
 50234  ** two TESTs where the TESTs have the same batch nubmer, then the
 50235  ** value added by the INSERT will not be visible to the second TEST.
 50236  ** The initial batch number is zero, so if the very first TEST contains
 50237  ** a non-zero batch number, it will see all prior INSERTs.
 50238  **
 50239  ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
 50240  ** that is attempted.
 50241  **
 50242  ** The cost of an INSERT is roughly constant.  (Sometimes new memory
 50243  ** has to be allocated on an INSERT.)  The cost of a TEST with a new
 50244  ** batch number is O(NlogN) where N is the number of elements in the RowSet.
 50245  ** The cost of a TEST using the same batch number is O(logN).  The cost
 50246  ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
 50247  ** primitives are constant time.  The cost of DESTROY is O(N).
 50248  **
 50249  ** TEST and SMALLEST may not be used by the same RowSet.  This used to
 50250  ** be possible, but the feature was not used, so it was removed in order
 50251  ** to simplify the code.
 50252  */
 50253  /* #include "sqliteInt.h" */
 50254  
 50255  
 50256  /*
 50257  ** Target size for allocation chunks.
 50258  */
 50259  #define ROWSET_ALLOCATION_SIZE 1024
 50260  
 50261  /*
 50262  ** The number of rowset entries per allocation chunk.
 50263  */
 50264  #define ROWSET_ENTRY_PER_CHUNK  \
 50265                         ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
 50266  
 50267  /*
 50268  ** Each entry in a RowSet is an instance of the following object.
 50269  **
 50270  ** This same object is reused to store a linked list of trees of RowSetEntry
 50271  ** objects.  In that alternative use, pRight points to the next entry
 50272  ** in the list, pLeft points to the tree, and v is unused.  The
 50273  ** RowSet.pForest value points to the head of this forest list.
 50274  */
 50275  struct RowSetEntry {            
 50276    i64 v;                        /* ROWID value for this entry */
 50277    struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
 50278    struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
 50279  };
 50280  
 50281  /*
 50282  ** RowSetEntry objects are allocated in large chunks (instances of the
 50283  ** following structure) to reduce memory allocation overhead.  The
 50284  ** chunks are kept on a linked list so that they can be deallocated
 50285  ** when the RowSet is destroyed.
 50286  */
 50287  struct RowSetChunk {
 50288    struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
 50289    struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
 50290  };
 50291  
 50292  /*
 50293  ** A RowSet in an instance of the following structure.
 50294  **
 50295  ** A typedef of this structure if found in sqliteInt.h.
 50296  */
 50297  struct RowSet {
 50298    struct RowSetChunk *pChunk;    /* List of all chunk allocations */
 50299    sqlite3 *db;                   /* The database connection */
 50300    struct RowSetEntry *pEntry;    /* List of entries using pRight */
 50301    struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
 50302    struct RowSetEntry *pFresh;    /* Source of new entry objects */
 50303    struct RowSetEntry *pForest;   /* List of binary trees of entries */
 50304    u16 nFresh;                    /* Number of objects on pFresh */
 50305    u16 rsFlags;                   /* Various flags */
 50306    int iBatch;                    /* Current insert batch */
 50307  };
 50308  
 50309  /*
 50310  ** Allowed values for RowSet.rsFlags
 50311  */
 50312  #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
 50313  #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
 50314  
 50315  /*
 50316  ** Allocate a RowSet object.  Return NULL if a memory allocation
 50317  ** error occurs.
 50318  */
 50319  SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
 50320    RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
 50321    if( p ){
 50322      int N = sqlite3DbMallocSize(db, p);
 50323      p->pChunk = 0;
 50324      p->db = db;
 50325      p->pEntry = 0;
 50326      p->pLast = 0;
 50327      p->pForest = 0;
 50328      p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
 50329      p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
 50330      p->rsFlags = ROWSET_SORTED;
 50331      p->iBatch = 0;
 50332    }
 50333    return p;
 50334  }
 50335  
 50336  /*
 50337  ** Deallocate all chunks from a RowSet.  This frees all memory that
 50338  ** the RowSet has allocated over its lifetime.  This routine is
 50339  ** the destructor for the RowSet.
 50340  */
 50341  SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
 50342    RowSet *p = (RowSet*)pArg;
 50343    struct RowSetChunk *pChunk, *pNextChunk;
 50344    for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
 50345      pNextChunk = pChunk->pNextChunk;
 50346      sqlite3DbFree(p->db, pChunk);
 50347    }
 50348    p->pChunk = 0;
 50349    p->nFresh = 0;
 50350    p->pEntry = 0;
 50351    p->pLast = 0;
 50352    p->pForest = 0;
 50353    p->rsFlags = ROWSET_SORTED;
 50354  }
 50355  
 50356  /*
 50357  ** Deallocate all chunks from a RowSet.  This frees all memory that
 50358  ** the RowSet has allocated over its lifetime.  This routine is
 50359  ** the destructor for the RowSet.
 50360  */
 50361  SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
 50362    sqlite3RowSetClear(pArg);
 50363    sqlite3DbFree(((RowSet*)pArg)->db, pArg);
 50364  }
 50365  
 50366  /*
 50367  ** Allocate a new RowSetEntry object that is associated with the
 50368  ** given RowSet.  Return a pointer to the new and completely uninitialized
 50369  ** objected.
 50370  **
 50371  ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
 50372  ** routine returns NULL.
 50373  */
 50374  static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
 50375    assert( p!=0 );
 50376    if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
 50377      /* We could allocate a fresh RowSetEntry each time one is needed, but it
 50378      ** is more efficient to pull a preallocated entry from the pool */
 50379      struct RowSetChunk *pNew;
 50380      pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
 50381      if( pNew==0 ){
 50382        return 0;
 50383      }
 50384      pNew->pNextChunk = p->pChunk;
 50385      p->pChunk = pNew;
 50386      p->pFresh = pNew->aEntry;
 50387      p->nFresh = ROWSET_ENTRY_PER_CHUNK;
 50388    }
 50389    p->nFresh--;
 50390    return p->pFresh++;
 50391  }
 50392  
 50393  /*
 50394  ** Insert a new value into a RowSet.
 50395  **
 50396  ** The mallocFailed flag of the database connection is set if a
 50397  ** memory allocation fails.
 50398  */
 50399  SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
 50400    struct RowSetEntry *pEntry;  /* The new entry */
 50401    struct RowSetEntry *pLast;   /* The last prior entry */
 50402  
 50403    /* This routine is never called after sqlite3RowSetNext() */
 50404    assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
 50405  
 50406    pEntry = rowSetEntryAlloc(p);
 50407    if( pEntry==0 ) return;
 50408    pEntry->v = rowid;
 50409    pEntry->pRight = 0;
 50410    pLast = p->pLast;
 50411    if( pLast ){
 50412      if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
 50413        /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
 50414        ** where possible */
 50415        p->rsFlags &= ~ROWSET_SORTED;
 50416      }
 50417      pLast->pRight = pEntry;
 50418    }else{
 50419      p->pEntry = pEntry;
 50420    }
 50421    p->pLast = pEntry;
 50422  }
 50423  
 50424  /*
 50425  ** Merge two lists of RowSetEntry objects.  Remove duplicates.
 50426  **
 50427  ** The input lists are connected via pRight pointers and are 
 50428  ** assumed to each already be in sorted order.
 50429  */
 50430  static struct RowSetEntry *rowSetEntryMerge(
 50431    struct RowSetEntry *pA,    /* First sorted list to be merged */
 50432    struct RowSetEntry *pB     /* Second sorted list to be merged */
 50433  ){
 50434    struct RowSetEntry head;
 50435    struct RowSetEntry *pTail;
 50436  
 50437    pTail = &head;
 50438    assert( pA!=0 && pB!=0 );
 50439    for(;;){
 50440      assert( pA->pRight==0 || pA->v<=pA->pRight->v );
 50441      assert( pB->pRight==0 || pB->v<=pB->pRight->v );
 50442      if( pA->v<=pB->v ){
 50443        if( pA->v<pB->v ) pTail = pTail->pRight = pA;
 50444        pA = pA->pRight;
 50445        if( pA==0 ){
 50446          pTail->pRight = pB;
 50447          break;
 50448        }
 50449      }else{
 50450        pTail = pTail->pRight = pB;
 50451        pB = pB->pRight;
 50452        if( pB==0 ){
 50453          pTail->pRight = pA;
 50454          break;
 50455        }
 50456      }
 50457    }
 50458    return head.pRight;
 50459  }
 50460  
 50461  /*
 50462  ** Sort all elements on the list of RowSetEntry objects into order of
 50463  ** increasing v.
 50464  */ 
 50465  static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
 50466    unsigned int i;
 50467    struct RowSetEntry *pNext, *aBucket[40];
 50468  
 50469    memset(aBucket, 0, sizeof(aBucket));
 50470    while( pIn ){
 50471      pNext = pIn->pRight;
 50472      pIn->pRight = 0;
 50473      for(i=0; aBucket[i]; i++){
 50474        pIn = rowSetEntryMerge(aBucket[i], pIn);
 50475        aBucket[i] = 0;
 50476      }
 50477      aBucket[i] = pIn;
 50478      pIn = pNext;
 50479    }
 50480    pIn = aBucket[0];
 50481    for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
 50482      if( aBucket[i]==0 ) continue;
 50483      pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
 50484    }
 50485    return pIn;
 50486  }
 50487  
 50488  
 50489  /*
 50490  ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
 50491  ** Convert this tree into a linked list connected by the pRight pointers
 50492  ** and return pointers to the first and last elements of the new list.
 50493  */
 50494  static void rowSetTreeToList(
 50495    struct RowSetEntry *pIn,         /* Root of the input tree */
 50496    struct RowSetEntry **ppFirst,    /* Write head of the output list here */
 50497    struct RowSetEntry **ppLast      /* Write tail of the output list here */
 50498  ){
 50499    assert( pIn!=0 );
 50500    if( pIn->pLeft ){
 50501      struct RowSetEntry *p;
 50502      rowSetTreeToList(pIn->pLeft, ppFirst, &p);
 50503      p->pRight = pIn;
 50504    }else{
 50505      *ppFirst = pIn;
 50506    }
 50507    if( pIn->pRight ){
 50508      rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
 50509    }else{
 50510      *ppLast = pIn;
 50511    }
 50512    assert( (*ppLast)->pRight==0 );
 50513  }
 50514  
 50515  
 50516  /*
 50517  ** Convert a sorted list of elements (connected by pRight) into a binary
 50518  ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
 50519  ** node taken from the head of *ppList.  A depth of 2 means a tree with
 50520  ** three nodes.  And so forth.
 50521  **
 50522  ** Use as many entries from the input list as required and update the
 50523  ** *ppList to point to the unused elements of the list.  If the input
 50524  ** list contains too few elements, then construct an incomplete tree
 50525  ** and leave *ppList set to NULL.
 50526  **
 50527  ** Return a pointer to the root of the constructed binary tree.
 50528  */
 50529  static struct RowSetEntry *rowSetNDeepTree(
 50530    struct RowSetEntry **ppList,
 50531    int iDepth
 50532  ){
 50533    struct RowSetEntry *p;         /* Root of the new tree */
 50534    struct RowSetEntry *pLeft;     /* Left subtree */
 50535    if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
 50536      /* Prevent unnecessary deep recursion when we run out of entries */
 50537      return 0; 
 50538    }
 50539    if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
 50540      /* This branch causes a *balanced* tree to be generated.  A valid tree
 50541      ** is still generated without this branch, but the tree is wildly
 50542      ** unbalanced and inefficient. */
 50543      pLeft = rowSetNDeepTree(ppList, iDepth-1);
 50544      p = *ppList;
 50545      if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
 50546        /* It is safe to always return here, but the resulting tree
 50547        ** would be unbalanced */
 50548        return pLeft;
 50549      }
 50550      p->pLeft = pLeft;
 50551      *ppList = p->pRight;
 50552      p->pRight = rowSetNDeepTree(ppList, iDepth-1);
 50553    }else{
 50554      p = *ppList;
 50555      *ppList = p->pRight;
 50556      p->pLeft = p->pRight = 0;
 50557    }
 50558    return p;
 50559  }
 50560  
 50561  /*
 50562  ** Convert a sorted list of elements into a binary tree. Make the tree
 50563  ** as deep as it needs to be in order to contain the entire list.
 50564  */
 50565  static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
 50566    int iDepth;           /* Depth of the tree so far */
 50567    struct RowSetEntry *p;       /* Current tree root */
 50568    struct RowSetEntry *pLeft;   /* Left subtree */
 50569  
 50570    assert( pList!=0 );
 50571    p = pList;
 50572    pList = p->pRight;
 50573    p->pLeft = p->pRight = 0;
 50574    for(iDepth=1; pList; iDepth++){
 50575      pLeft = p;
 50576      p = pList;
 50577      pList = p->pRight;
 50578      p->pLeft = pLeft;
 50579      p->pRight = rowSetNDeepTree(&pList, iDepth);
 50580    }
 50581    return p;
 50582  }
 50583  
 50584  /*
 50585  ** Extract the smallest element from the RowSet.
 50586  ** Write the element into *pRowid.  Return 1 on success.  Return
 50587  ** 0 if the RowSet is already empty.
 50588  **
 50589  ** After this routine has been called, the sqlite3RowSetInsert()
 50590  ** routine may not be called again.
 50591  **
 50592  ** This routine may not be called after sqlite3RowSetTest() has
 50593  ** been used.  Older versions of RowSet allowed that, but as the
 50594  ** capability was not used by the code generator, it was removed
 50595  ** for code economy.
 50596  */
 50597  SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
 50598    assert( p!=0 );
 50599    assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
 50600  
 50601    /* Merge the forest into a single sorted list on first call */
 50602    if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
 50603      if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
 50604        p->pEntry = rowSetEntrySort(p->pEntry);
 50605      }
 50606      p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
 50607    }
 50608  
 50609    /* Return the next entry on the list */
 50610    if( p->pEntry ){
 50611      *pRowid = p->pEntry->v;
 50612      p->pEntry = p->pEntry->pRight;
 50613      if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
 50614        /* Free memory immediately, rather than waiting on sqlite3_finalize() */
 50615        sqlite3RowSetClear(p);
 50616      }
 50617      return 1;
 50618    }else{
 50619      return 0;
 50620    }
 50621  }
 50622  
 50623  /*
 50624  ** Check to see if element iRowid was inserted into the rowset as
 50625  ** part of any insert batch prior to iBatch.  Return 1 or 0.
 50626  **
 50627  ** If this is the first test of a new batch and if there exist entries
 50628  ** on pRowSet->pEntry, then sort those entries into the forest at
 50629  ** pRowSet->pForest so that they can be tested.
 50630  */
 50631  SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
 50632    struct RowSetEntry *p, *pTree;
 50633  
 50634    /* This routine is never called after sqlite3RowSetNext() */
 50635    assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
 50636  
 50637    /* Sort entries into the forest on the first test of a new batch.
 50638    ** To save unnecessary work, only do this when the batch number changes.
 50639    */
 50640    if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
 50641      p = pRowSet->pEntry;
 50642      if( p ){
 50643        struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
 50644        if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
 50645          /* Only sort the current set of entiries if they need it */
 50646          p = rowSetEntrySort(p);
 50647        }
 50648        for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 50649          ppPrevTree = &pTree->pRight;
 50650          if( pTree->pLeft==0 ){
 50651            pTree->pLeft = rowSetListToTree(p);
 50652            break;
 50653          }else{
 50654            struct RowSetEntry *pAux, *pTail;
 50655            rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
 50656            pTree->pLeft = 0;
 50657            p = rowSetEntryMerge(pAux, p);
 50658          }
 50659        }
 50660        if( pTree==0 ){
 50661          *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
 50662          if( pTree ){
 50663            pTree->v = 0;
 50664            pTree->pRight = 0;
 50665            pTree->pLeft = rowSetListToTree(p);
 50666          }
 50667        }
 50668        pRowSet->pEntry = 0;
 50669        pRowSet->pLast = 0;
 50670        pRowSet->rsFlags |= ROWSET_SORTED;
 50671      }
 50672      pRowSet->iBatch = iBatch;
 50673    }
 50674  
 50675    /* Test to see if the iRowid value appears anywhere in the forest.
 50676    ** Return 1 if it does and 0 if not.
 50677    */
 50678    for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
 50679      p = pTree->pLeft;
 50680      while( p ){
 50681        if( p->v<iRowid ){
 50682          p = p->pRight;
 50683        }else if( p->v>iRowid ){
 50684          p = p->pLeft;
 50685        }else{
 50686          return 1;
 50687        }
 50688      }
 50689    }
 50690    return 0;
 50691  }
 50692  
 50693  /************** End of rowset.c **********************************************/
 50694  /************** Begin file pager.c *******************************************/
 50695  /*
 50696  ** 2001 September 15
 50697  **
 50698  ** The author disclaims copyright to this source code.  In place of
 50699  ** a legal notice, here is a blessing:
 50700  **
 50701  **    May you do good and not evil.
 50702  **    May you find forgiveness for yourself and forgive others.
 50703  **    May you share freely, never taking more than you give.
 50704  **
 50705  *************************************************************************
 50706  ** This is the implementation of the page cache subsystem or "pager".
 50707  ** 
 50708  ** The pager is used to access a database disk file.  It implements
 50709  ** atomic commit and rollback through the use of a journal file that
 50710  ** is separate from the database file.  The pager also implements file
 50711  ** locking to prevent two processes from writing the same database
 50712  ** file simultaneously, or one process from reading the database while
 50713  ** another is writing.
 50714  */
 50715  #ifndef SQLITE_OMIT_DISKIO
 50716  /* #include "sqliteInt.h" */
 50717  /************** Include wal.h in the middle of pager.c ***********************/
 50718  /************** Begin file wal.h *********************************************/
 50719  /*
 50720  ** 2010 February 1
 50721  **
 50722  ** The author disclaims copyright to this source code.  In place of
 50723  ** a legal notice, here is a blessing:
 50724  **
 50725  **    May you do good and not evil.
 50726  **    May you find forgiveness for yourself and forgive others.
 50727  **    May you share freely, never taking more than you give.
 50728  **
 50729  *************************************************************************
 50730  ** This header file defines the interface to the write-ahead logging 
 50731  ** system. Refer to the comments below and the header comment attached to 
 50732  ** the implementation of each function in log.c for further details.
 50733  */
 50734  
 50735  #ifndef SQLITE_WAL_H
 50736  #define SQLITE_WAL_H
 50737  
 50738  /* #include "sqliteInt.h" */
 50739  
 50740  /* Macros for extracting appropriate sync flags for either transaction
 50741  ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
 50742  */
 50743  #define WAL_SYNC_FLAGS(X)   ((X)&0x03)
 50744  #define CKPT_SYNC_FLAGS(X)  (((X)>>2)&0x03)
 50745  
 50746  #ifdef SQLITE_OMIT_WAL
 50747  # define sqlite3WalOpen(w,x,y,z)                 0
 50748  # define sqlite3WalLimit(x,y)
 50749  # define sqlite3WalClose(v,w,x,y,z)              0
 50750  # define sqlite3WalBeginReadTransaction(y,z)     0
 50751  # define sqlite3WalEndReadTransaction(z)
 50752  # define sqlite3WalDbsize(y)                     0
 50753  # define sqlite3WalBeginWriteTransaction(y)      0
 50754  # define sqlite3WalEndWriteTransaction(x)        0
 50755  # define sqlite3WalUndo(x,y,z)                   0
 50756  # define sqlite3WalSavepoint(y,z)
 50757  # define sqlite3WalSavepointUndo(y,z)            0
 50758  # define sqlite3WalFrames(u,v,w,x,y,z)           0
 50759  # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
 50760  # define sqlite3WalCallback(z)                   0
 50761  # define sqlite3WalExclusiveMode(y,z)            0
 50762  # define sqlite3WalHeapMemory(z)                 0
 50763  # define sqlite3WalFramesize(z)                  0
 50764  # define sqlite3WalFindFrame(x,y,z)              0
 50765  # define sqlite3WalFile(x)                       0
 50766  #else
 50767  
 50768  #define WAL_SAVEPOINT_NDATA 4
 50769  
 50770  /* Connection to a write-ahead log (WAL) file. 
 50771  ** There is one object of this type for each pager. 
 50772  */
 50773  typedef struct Wal Wal;
 50774  
 50775  /* Open and close a connection to a write-ahead log. */
 50776  SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, lmdb*, Wal**);
 50777  SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
 50778  
 50779  /* Set the limiting size of a WAL file. */
 50780  SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
 50781  
 50782  /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
 50783  ** snapshot is like a read-transaction.  It is the state of the database
 50784  ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
 50785  ** preserves the current state even if the other threads or processes
 50786  ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
 50787  ** transaction and releases the lock.
 50788  */
 50789  SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
 50790  SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
 50791  
 50792  /* Read a page from the write-ahead log, if it is present. */
 50793  SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
 50794  SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
 50795  
 50796  /* If the WAL is not empty, return the size of the database. */
 50797  SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
 50798  
 50799  /* Obtain or release the WRITER lock. */
 50800  SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
 50801  SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
 50802  
 50803  /* Undo any frames written (but not committed) to the log */
 50804  SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
 50805  
 50806  /* Return an integer that records the current (uncommitted) write
 50807  ** position in the WAL */
 50808  SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
 50809  
 50810  /* Move the write position of the WAL back to iFrame.  Called in
 50811  ** response to a ROLLBACK TO command. */
 50812  SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
 50813  
 50814  /* Write a frame or frames to the log. */
 50815  SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
 50816  
 50817  /* Copy pages from the log to the database file */ 
 50818  SQLITE_PRIVATE int sqlite3WalCheckpoint(
 50819    Wal *pWal,                      /* Write-ahead log connection */
 50820    sqlite3 *db,                    /* Check this handle's interrupt flag */
 50821    int eMode,                      /* One of PASSIVE, FULL and RESTART */
 50822    int (*xBusy)(void*),            /* Function to call when busy */
 50823    void *pBusyArg,                 /* Context argument for xBusyHandler */
 50824    int sync_flags,                 /* Flags to sync db file with (or 0) */
 50825    int nBuf,                       /* Size of buffer nBuf */
 50826    u8 *zBuf,                       /* Temporary buffer to use */
 50827    int *pnLog,                     /* OUT: Number of frames in WAL */
 50828    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 50829  );
 50830  
 50831  /* Return the value to pass to a sqlite3_wal_hook callback, the
 50832  ** number of frames in the WAL at the point of the last commit since
 50833  ** sqlite3WalCallback() was called.  If no commits have occurred since
 50834  ** the last call, then return 0.
 50835  */
 50836  SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
 50837  
 50838  /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
 50839  ** by the pager layer on the database file.
 50840  */
 50841  SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
 50842  
 50843  /* Return true if the argument is non-NULL and the WAL module is using
 50844  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 50845  ** WAL module is using shared-memory, return false. 
 50846  */
 50847  SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
 50848  
 50849  #ifdef SQLITE_ENABLE_SNAPSHOT
 50850  SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
 50851  SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
 50852  SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
 50853  SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
 50854  SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
 50855  #endif
 50856  
 50857  #ifdef SQLITE_ENABLE_ZIPVFS
 50858  /* If the WAL file is not empty, return the number of bytes of content
 50859  ** stored in each frame (i.e. the db page-size when the WAL was created).
 50860  */
 50861  SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
 50862  #endif
 50863  
 50864  /* Return the sqlite3_file object for the WAL file */
 50865  SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
 50866  
 50867  #endif /* ifndef SQLITE_OMIT_WAL */
 50868  #endif /* SQLITE_WAL_H */
 50869  
 50870  /************** End of wal.h *************************************************/
 50871  /************** Continuing where we left off in pager.c **********************/
 50872  
 50873  
 50874  /******************* NOTES ON THE DESIGN OF THE PAGER ************************
 50875  **
 50876  ** This comment block describes invariants that hold when using a rollback
 50877  ** journal.  These invariants do not apply for journal_mode=WAL,
 50878  ** journal_mode=MEMORY, or journal_mode=OFF.
 50879  **
 50880  ** Within this comment block, a page is deemed to have been synced
 50881  ** automatically as soon as it is written when PRAGMA synchronous=OFF.
 50882  ** Otherwise, the page is not synced until the xSync method of the VFS
 50883  ** is called successfully on the file containing the page.
 50884  **
 50885  ** Definition:  A page of the database file is said to be "overwriteable" if
 50886  ** one or more of the following are true about the page:
 50887  ** 
 50888  **     (a)  The original content of the page as it was at the beginning of
 50889  **          the transaction has been written into the rollback journal and
 50890  **          synced.
 50891  ** 
 50892  **     (b)  The page was a freelist leaf page at the start of the transaction.
 50893  ** 
 50894  **     (c)  The page number is greater than the largest page that existed in
 50895  **          the database file at the start of the transaction.
 50896  ** 
 50897  ** (1) A page of the database file is never overwritten unless one of the
 50898  **     following are true:
 50899  ** 
 50900  **     (a) The page and all other pages on the same sector are overwriteable.
 50901  ** 
 50902  **     (b) The atomic page write optimization is enabled, and the entire
 50903  **         transaction other than the update of the transaction sequence
 50904  **         number consists of a single page change.
 50905  ** 
 50906  ** (2) The content of a page written into the rollback journal exactly matches
 50907  **     both the content in the database when the rollback journal was written
 50908  **     and the content in the database at the beginning of the current
 50909  **     transaction.
 50910  ** 
 50911  ** (3) Writes to the database file are an integer multiple of the page size
 50912  **     in length and are aligned on a page boundary.
 50913  ** 
 50914  ** (4) Reads from the database file are either aligned on a page boundary and
 50915  **     an integer multiple of the page size in length or are taken from the
 50916  **     first 100 bytes of the database file.
 50917  ** 
 50918  ** (5) All writes to the database file are synced prior to the rollback journal
 50919  **     being deleted, truncated, or zeroed.
 50920  ** 
 50921  ** (6) If a master journal file is used, then all writes to the database file
 50922  **     are synced prior to the master journal being deleted.
 50923  ** 
 50924  ** Definition: Two databases (or the same database at two points it time)
 50925  ** are said to be "logically equivalent" if they give the same answer to
 50926  ** all queries.  Note in particular the content of freelist leaf
 50927  ** pages can be changed arbitrarily without affecting the logical equivalence
 50928  ** of the database.
 50929  ** 
 50930  ** (7) At any time, if any subset, including the empty set and the total set,
 50931  **     of the unsynced changes to a rollback journal are removed and the 
 50932  **     journal is rolled back, the resulting database file will be logically
 50933  **     equivalent to the database file at the beginning of the transaction.
 50934  ** 
 50935  ** (8) When a transaction is rolled back, the xTruncate method of the VFS
 50936  **     is called to restore the database file to the same size it was at
 50937  **     the beginning of the transaction.  (In some VFSes, the xTruncate
 50938  **     method is a no-op, but that does not change the fact the SQLite will
 50939  **     invoke it.)
 50940  ** 
 50941  ** (9) Whenever the database file is modified, at least one bit in the range
 50942  **     of bytes from 24 through 39 inclusive will be changed prior to releasing
 50943  **     the EXCLUSIVE lock, thus signaling other connections on the same
 50944  **     database to flush their caches.
 50945  **
 50946  ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
 50947  **      than one billion transactions.
 50948  **
 50949  ** (11) A database file is well-formed at the beginning and at the conclusion
 50950  **      of every transaction.
 50951  **
 50952  ** (12) An EXCLUSIVE lock is held on the database file when writing to
 50953  **      the database file.
 50954  **
 50955  ** (13) A SHARED lock is held on the database file while reading any
 50956  **      content out of the database file.
 50957  **
 50958  ******************************************************************************/
 50959  
 50960  /*
 50961  ** Macros for troubleshooting.  Normally turned off
 50962  */
 50963  #if DEBUGPRINT
 50964  #define DEBUGBRANCHES
 50965  int sqlite3PagerTrace=1;  /* True to enable tracing */
 50966  #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
 50967  #else
 50968  #define PAGERTRACE(X)
 50969  #endif
 50970  
 50971  #ifdef DEBUGBRANCHES
 50972  #define DEBUGERROR
 50973  #define BRANCHTRACE(X, ...)   sqlite3DebugPrintf("BRANCH TRACE - " X "\n", ##__VA_ARGS__);
 50974  #else
 50975  #define BRANCHTRACE(X, ...)
 50976  #endif
 50977  
 50978  #ifdef DEBUGERROR
 50979  #define BRANCHERROR(X)        sqlite3DebugPrintf X;
 50980  #else
 50981  #define BRANCHERROR(X)
 50982  #endif
 50983  
 50984  #ifdef DEBUGBRANCHES
 50985  unsigned char * to_hex(unsigned char *buf, int size) {
 50986    static unsigned char *result = NULL;
 50987    char *p;
 50988    int i;
 50989    result = sqlite3_realloc(result, (size * 3) + 1);
 50990    if( result ){
 50991      p = (char*)result;
 50992      for( i=0; i<size; i++ ){
 50993        sprintf(p, " %02x", buf[i]);
 50994        p += 3;
 50995      }
 50996    }
 50997    return result;
 50998  }
 50999  #endif
 51000  
 51001  /*
 51002  ** The following two macros are used within the PAGERTRACE() macros above
 51003  ** to print out file-descriptors. 
 51004  **
 51005  ** PAGERID() takes a pointer to a Pager struct as its argument. The
 51006  ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
 51007  ** struct as its argument.
 51008  */
 51009  #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
 51010  #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
 51011  
 51012  /*
 51013  ** The Pager.eState variable stores the current 'state' of a pager. A
 51014  ** pager may be in any one of the seven states shown in the following
 51015  ** state diagram.
 51016  **
 51017  **                            OPEN <------+------+
 51018  **                              |         |      |
 51019  **                              V         |      |
 51020  **               +---------> READER-------+      |
 51021  **               |              |                |
 51022  **               |              V                |
 51023  **               |<-------WRITER_LOCKED------> ERROR
 51024  **               |              |                ^  
 51025  **               |              V                |
 51026  **               |<------WRITER_CACHEMOD-------->|
 51027  **               |              |                |
 51028  **               |              V                |
 51029  **               |<-------WRITER_DBMOD---------->|
 51030  **               |              |                |
 51031  **               |              V                |
 51032  **               +<------WRITER_FINISHED-------->+
 51033  **
 51034  **
 51035  ** List of state transitions and the C [function] that performs each:
 51036  ** 
 51037  **   OPEN              -> READER              [sqlite3PagerSharedLock]
 51038  **   READER            -> OPEN                [pager_unlock]
 51039  **
 51040  **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
 51041  **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
 51042  **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
 51043  **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
 51044  **   WRITER_***        -> READER              [pager_end_transaction]
 51045  **
 51046  **   WRITER_***        -> ERROR               [pager_error]
 51047  **   ERROR             -> OPEN                [pager_unlock]
 51048  ** 
 51049  **
 51050  **  OPEN:
 51051  **
 51052  **    The pager starts up in this state. Nothing is guaranteed in this
 51053  **    state - the file may or may not be locked and the database size is
 51054  **    unknown. The database may not be read or written.
 51055  **
 51056  **    * No read or write transaction is active.
 51057  **    * Any lock, or no lock at all, may be held on the database file.
 51058  **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
 51059  **
 51060  **  READER:
 51061  **
 51062  **    In this state all the requirements for reading the database in 
 51063  **    rollback (non-WAL) mode are met. Unless the pager is (or recently
 51064  **    was) in exclusive-locking mode, a user-level read transaction is 
 51065  **    open. The database size is known in this state.
 51066  **
 51067  **    A connection running with locking_mode=normal enters this state when
 51068  **    it opens a read-transaction on the database and returns to state
 51069  **    OPEN after the read-transaction is completed. However a connection
 51070  **    running in locking_mode=exclusive (including temp databases) remains in
 51071  **    this state even after the read-transaction is closed. The only way
 51072  **    a locking_mode=exclusive connection can transition from READER to OPEN
 51073  **    is via the ERROR state (see below).
 51074  ** 
 51075  **    * A read transaction may be active (but a write-transaction cannot).
 51076  **    * A SHARED or greater lock is held on the database file.
 51077  **    * The dbSize variable may be trusted (even if a user-level read 
 51078  **      transaction is not active). The dbOrigSize and dbFileSize variables
 51079  **      may not be trusted at this point.
 51080  **    * If the database is a WAL database, then the WAL connection is open.
 51081  **    * Even if a read-transaction is not open, it is guaranteed that 
 51082  **      there is no hot-journal in the file-system.
 51083  **
 51084  **  WRITER_LOCKED:
 51085  **
 51086  **    The pager moves to this state from READER when a write-transaction
 51087  **    is first opened on the database. In WRITER_LOCKED state, all locks 
 51088  **    required to start a write-transaction are held, but no actual 
 51089  **    modifications to the cache or database have taken place.
 51090  **
 51091  **    In rollback mode, a RESERVED or (if the transaction was opened with 
 51092  **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
 51093  **    moving to this state, but the journal file is not written to or opened 
 51094  **    to in this state. If the transaction is committed or rolled back while 
 51095  **    in WRITER_LOCKED state, all that is required is to unlock the database 
 51096  **    file.
 51097  **
 51098  **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
 51099  **    If the connection is running with locking_mode=exclusive, an attempt
 51100  **    is made to obtain an EXCLUSIVE lock on the database file.
 51101  **
 51102  **    * A write transaction is active.
 51103  **    * If the connection is open in rollback-mode, a RESERVED or greater 
 51104  **      lock is held on the database file.
 51105  **    * If the connection is open in WAL-mode, a WAL write transaction
 51106  **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
 51107  **      called).
 51108  **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
 51109  **    * The contents of the pager cache have not been modified.
 51110  **    * The journal file may or may not be open.
 51111  **    * Nothing (not even the first header) has been written to the journal.
 51112  **
 51113  **  WRITER_CACHEMOD:
 51114  **
 51115  **    A pager moves from WRITER_LOCKED state to this state when a page is
 51116  **    first modified by the upper layer. In rollback mode the journal file
 51117  **    is opened (if it is not already open) and a header written to the
 51118  **    start of it. The database file on disk has not been modified.
 51119  **
 51120  **    * A write transaction is active.
 51121  **    * A RESERVED or greater lock is held on the database file.
 51122  **    * The journal file is open and the first header has been written 
 51123  **      to it, but the header has not been synced to disk.
 51124  **    * The contents of the page cache have been modified.
 51125  **
 51126  **  WRITER_DBMOD:
 51127  **
 51128  **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
 51129  **    when it modifies the contents of the database file. WAL connections
 51130  **    never enter this state (since they do not modify the database file,
 51131  **    just the log file).
 51132  **
 51133  **    * A write transaction is active.
 51134  **    * An EXCLUSIVE or greater lock is held on the database file.
 51135  **    * The journal file is open and the first header has been written 
 51136  **      and synced to disk.
 51137  **    * The contents of the page cache have been modified (and possibly
 51138  **      written to disk).
 51139  **
 51140  **  WRITER_FINISHED:
 51141  **
 51142  **    It is not possible for a WAL connection to enter this state.
 51143  **
 51144  **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
 51145  **    state after the entire transaction has been successfully written into the
 51146  **    database file. In this state the transaction may be committed simply
 51147  **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
 51148  **    not possible to modify the database further. At this point, the upper 
 51149  **    layer must either commit or rollback the transaction.
 51150  **
 51151  **    * A write transaction is active.
 51152  **    * An EXCLUSIVE or greater lock is held on the database file.
 51153  **    * All writing and syncing of journal and database data has finished.
 51154  **      If no error occurred, all that remains is to finalize the journal to
 51155  **      commit the transaction. If an error did occur, the caller will need
 51156  **      to rollback the transaction. 
 51157  **
 51158  **  ERROR:
 51159  **
 51160  **    The ERROR state is entered when an IO or disk-full error (including
 51161  **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
 51162  **    difficult to be sure that the in-memory pager state (cache contents, 
 51163  **    db size etc.) are consistent with the contents of the file-system.
 51164  **
 51165  **    Temporary pager files may enter the ERROR state, but in-memory pagers
 51166  **    cannot.
 51167  **
 51168  **    For example, if an IO error occurs while performing a rollback, 
 51169  **    the contents of the page-cache may be left in an inconsistent state.
 51170  **    At this point it would be dangerous to change back to READER state
 51171  **    (as usually happens after a rollback). Any subsequent readers might
 51172  **    report database corruption (due to the inconsistent cache), and if
 51173  **    they upgrade to writers, they may inadvertently corrupt the database
 51174  **    file. To avoid this hazard, the pager switches into the ERROR state
 51175  **    instead of READER following such an error.
 51176  **
 51177  **    Once it has entered the ERROR state, any attempt to use the pager
 51178  **    to read or write data returns an error. Eventually, once all 
 51179  **    outstanding transactions have been abandoned, the pager is able to
 51180  **    transition back to OPEN state, discarding the contents of the 
 51181  **    page-cache and any other in-memory state at the same time. Everything
 51182  **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
 51183  **    when a read-transaction is next opened on the pager (transitioning
 51184  **    the pager into READER state). At that point the system has recovered 
 51185  **    from the error.
 51186  **
 51187  **    Specifically, the pager jumps into the ERROR state if:
 51188  **
 51189  **      1. An error occurs while attempting a rollback. This happens in
 51190  **         function sqlite3PagerRollback().
 51191  **
 51192  **      2. An error occurs while attempting to finalize a journal file
 51193  **         following a commit in function sqlite3PagerCommitPhaseTwo().
 51194  **
 51195  **      3. An error occurs while attempting to write to the journal or
 51196  **         database file in function pagerStress() in order to free up
 51197  **         memory.
 51198  **
 51199  **    In other cases, the error is returned to the b-tree layer. The b-tree
 51200  **    layer then attempts a rollback operation. If the error condition 
 51201  **    persists, the pager enters the ERROR state via condition (1) above.
 51202  **
 51203  **    Condition (3) is necessary because it can be triggered by a read-only
 51204  **    statement executed within a transaction. In this case, if the error
 51205  **    code were simply returned to the user, the b-tree layer would not
 51206  **    automatically attempt a rollback, as it assumes that an error in a
 51207  **    read-only statement cannot leave the pager in an internally inconsistent 
 51208  **    state.
 51209  **
 51210  **    * The Pager.errCode variable is set to something other than SQLITE_OK.
 51211  **    * There are one or more outstanding references to pages (after the
 51212  **      last reference is dropped the pager should move back to OPEN state).
 51213  **    * The pager is not an in-memory pager.
 51214  **    
 51215  **
 51216  ** Notes:
 51217  **
 51218  **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
 51219  **     connection is open in WAL mode. A WAL connection is always in one
 51220  **     of the first four states.
 51221  **
 51222  **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
 51223  **     state. There are two exceptions: immediately after exclusive-mode has
 51224  **     been turned on (and before any read or write transactions are 
 51225  **     executed), and when the pager is leaving the "error state".
 51226  **
 51227  **   * See also: assert_pager_state().
 51228  */
 51229  #define PAGER_OPEN                  0
 51230  #define PAGER_READER                1
 51231  #define PAGER_WRITER_LOCKED         2
 51232  #define PAGER_WRITER_CACHEMOD       3
 51233  #define PAGER_WRITER_DBMOD          4
 51234  #define PAGER_WRITER_FINISHED       5
 51235  #define PAGER_ERROR                 6
 51236  
 51237  /*
 51238  ** The Pager.eLock variable is almost always set to one of the 
 51239  ** following locking-states, according to the lock currently held on
 51240  ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 51241  ** This variable is kept up to date as locks are taken and released by
 51242  ** the pagerLockDb() and pagerUnlockDb() wrappers.
 51243  **
 51244  ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
 51245  ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
 51246  ** the operation was successful. In these circumstances pagerLockDb() and
 51247  ** pagerUnlockDb() take a conservative approach - eLock is always updated
 51248  ** when unlocking the file, and only updated when locking the file if the
 51249  ** VFS call is successful. This way, the Pager.eLock variable may be set
 51250  ** to a less exclusive (lower) value than the lock that is actually held
 51251  ** at the system level, but it is never set to a more exclusive value.
 51252  **
 51253  ** This is usually safe. If an xUnlock fails or appears to fail, there may 
 51254  ** be a few redundant xLock() calls or a lock may be held for longer than
 51255  ** required, but nothing really goes wrong.
 51256  **
 51257  ** The exception is when the database file is unlocked as the pager moves
 51258  ** from ERROR to OPEN state. At this point there may be a hot-journal file 
 51259  ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
 51260  ** transition, by the same pager or any other). If the call to xUnlock()
 51261  ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
 51262  ** can confuse the call to xCheckReservedLock() call made later as part
 51263  ** of hot-journal detection.
 51264  **
 51265  ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
 51266  ** lock held by this process or any others". So xCheckReservedLock may 
 51267  ** return true because the caller itself is holding an EXCLUSIVE lock (but
 51268  ** doesn't know it because of a previous error in xUnlock). If this happens
 51269  ** a hot-journal may be mistaken for a journal being created by an active
 51270  ** transaction in another process, causing SQLite to read from the database
 51271  ** without rolling it back.
 51272  **
 51273  ** To work around this, if a call to xUnlock() fails when unlocking the
 51274  ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
 51275  ** is only changed back to a real locking state after a successful call
 51276  ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
 51277  ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
 51278  ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
 51279  ** lock on the database file before attempting to roll it back. See function
 51280  ** PagerSharedLock() for more detail.
 51281  **
 51282  ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
 51283  ** PAGER_OPEN state.
 51284  */
 51285  #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
 51286  
 51287  /*
 51288  ** A macro used for invoking the codec if there is one
 51289  */
 51290  #ifdef SQLITE_HAS_CODEC
 51291  # define CODEC1(P,D,N,X,E) \
 51292      if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
 51293  # define CODEC2(P,D,N,X,E,O) \
 51294      if( P->xCodec==0 ){ O=(char*)D; }else \
 51295      if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
 51296  #else
 51297  # define CODEC1(P,D,N,X,E)   /* NO-OP */
 51298  # define CODEC2(P,D,N,X,E,O) O=(char*)D
 51299  #endif
 51300  
 51301  /*
 51302  ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
 51303  ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 51304  ** This could conceivably cause corruption following a power failure on
 51305  ** such a system. This is currently an undocumented limit.
 51306  */
 51307  #define MAX_SECTOR_SIZE 0x10000
 51308  
 51309  
 51310  /*
 51311  ** An instance of the following structure is allocated for each active
 51312  ** savepoint and statement transaction in the system. All such structures
 51313  ** are stored in the Pager.aSavepoint[] array, which is allocated and
 51314  ** resized using sqlite3Realloc().
 51315  **
 51316  ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
 51317  ** set to 0. If a journal-header is written into the main journal while
 51318  ** the savepoint is active, then iHdrOffset is set to the byte offset 
 51319  ** immediately following the last journal record written into the main
 51320  ** journal before the journal-header. This is required during savepoint
 51321  ** rollback (see pagerPlaybackSavepoint()).
 51322  */
 51323  typedef struct PagerSavepoint PagerSavepoint;
 51324  struct PagerSavepoint {
 51325    i64 iOffset;                 /* Starting offset in main journal */
 51326    i64 iHdrOffset;              /* See above */
 51327    Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
 51328    Pgno nOrig;                  /* Original number of pages in file */
 51329    Pgno iSubRec;                /* Index of first record in sub-journal */
 51330  #ifndef SQLITE_OMIT_WAL
 51331    u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
 51332  #endif
 51333  };
 51334  
 51335  /*
 51336  ** Bits of the Pager.doNotSpill flag.  See further description below.
 51337  */
 51338  #define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
 51339  #define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
 51340  #define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
 51341  
 51342  /*
 51343  ** An open page cache is an instance of struct Pager. A description of
 51344  ** some of the more important member variables follows:
 51345  **
 51346  ** eState
 51347  **
 51348  **   The current 'state' of the pager object. See the comment and state
 51349  **   diagram above for a description of the pager state.
 51350  **
 51351  ** eLock
 51352  **
 51353  **   For a real on-disk database, the current lock held on the database file -
 51354  **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 51355  **
 51356  **   For a temporary or in-memory database (neither of which require any
 51357  **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
 51358  **   databases always have Pager.exclusiveMode==1, this tricks the pager
 51359  **   logic into thinking that it already has all the locks it will ever
 51360  **   need (and no reason to release them).
 51361  **
 51362  **   In some (obscure) circumstances, this variable may also be set to
 51363  **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
 51364  **   details.
 51365  **
 51366  ** changeCountDone
 51367  **
 51368  **   This boolean variable is used to make sure that the change-counter 
 51369  **   (the 4-byte header field at byte offset 24 of the database file) is 
 51370  **   not updated more often than necessary. 
 51371  **
 51372  **   It is set to true when the change-counter field is updated, which 
 51373  **   can only happen if an exclusive lock is held on the database file.
 51374  **   It is cleared (set to false) whenever an exclusive lock is 
 51375  **   relinquished on the database file. Each time a transaction is committed,
 51376  **   The changeCountDone flag is inspected. If it is true, the work of
 51377  **   updating the change-counter is omitted for the current transaction.
 51378  **
 51379  **   This mechanism means that when running in exclusive mode, a connection 
 51380  **   need only update the change-counter once, for the first transaction
 51381  **   committed.
 51382  **
 51383  ** setMaster
 51384  **
 51385  **   When PagerCommitPhaseOne() is called to commit a transaction, it may
 51386  **   (or may not) specify a master-journal name to be written into the 
 51387  **   journal file before it is synced to disk.
 51388  **
 51389  **   Whether or not a journal file contains a master-journal pointer affects 
 51390  **   the way in which the journal file is finalized after the transaction is 
 51391  **   committed or rolled back when running in "journal_mode=PERSIST" mode.
 51392  **   If a journal file does not contain a master-journal pointer, it is
 51393  **   finalized by overwriting the first journal header with zeroes. If
 51394  **   it does contain a master-journal pointer the journal file is finalized 
 51395  **   by truncating it to zero bytes, just as if the connection were 
 51396  **   running in "journal_mode=truncate" mode.
 51397  **
 51398  **   Journal files that contain master journal pointers cannot be finalized
 51399  **   simply by overwriting the first journal-header with zeroes, as the
 51400  **   master journal pointer could interfere with hot-journal rollback of any
 51401  **   subsequently interrupted transaction that reuses the journal file.
 51402  **
 51403  **   The flag is cleared as soon as the journal file is finalized (either
 51404  **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
 51405  **   journal file from being successfully finalized, the setMaster flag
 51406  **   is cleared anyway (and the pager will move to ERROR state).
 51407  **
 51408  ** doNotSpill
 51409  **
 51410  **   This variables control the behavior of cache-spills  (calls made by
 51411  **   the pcache module to the pagerStress() routine to write cached data
 51412  **   to the file-system in order to free up memory).
 51413  **
 51414  **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
 51415  **   writing to the database from pagerStress() is disabled altogether.
 51416  **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
 51417  **   comes up during savepoint rollback that requires the pcache module
 51418  **   to allocate a new page to prevent the journal file from being written
 51419  **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
 51420  **   case is a user preference.
 51421  ** 
 51422  **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
 51423  **   pagerStress() is permitted, but syncing the journal file is not.
 51424  **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
 51425  **   is larger than the database page-size in order to prevent a journal sync
 51426  **   from happening in between the journalling of two pages on the same sector. 
 51427  **
 51428  ** subjInMemory
 51429  **
 51430  **   This is a boolean variable. If true, then any required sub-journal
 51431  **   is opened as an in-memory journal file. If false, then in-memory
 51432  **   sub-journals are only used for in-memory pager files.
 51433  **
 51434  **   This variable is updated by the upper layer each time a new 
 51435  **   write-transaction is opened.
 51436  **
 51437  ** dbSize, dbOrigSize, dbFileSize
 51438  **
 51439  **   Variable dbSize is set to the number of pages in the database file.
 51440  **   It is valid in PAGER_READER and higher states (all states except for
 51441  **   OPEN and ERROR). 
 51442  **
 51443  **   dbSize is set based on the size of the database file, which may be 
 51444  **   larger than the size of the database (the value stored at offset
 51445  **   28 of the database header by the btree). If the size of the file
 51446  **   is not an integer multiple of the page-size, the value stored in
 51447  **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
 51448  **   Except, any file that is greater than 0 bytes in size is considered
 51449  **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
 51450  **   to dbSize==1).
 51451  **
 51452  **   During a write-transaction, if pages with page-numbers greater than
 51453  **   dbSize are modified in the cache, dbSize is updated accordingly.
 51454  **   Similarly, if the database is truncated using PagerTruncateImage(), 
 51455  **   dbSize is updated.
 51456  **
 51457  **   Variables dbOrigSize and dbFileSize are valid in states 
 51458  **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
 51459  **   variable at the start of the transaction. It is used during rollback,
 51460  **   and to determine whether or not pages need to be journalled before
 51461  **   being modified.
 51462  **
 51463  **   Throughout a write-transaction, dbFileSize contains the size of
 51464  **   the file on disk in pages. It is set to a copy of dbSize when the
 51465  **   write-transaction is first opened, and updated when VFS calls are made
 51466  **   to write or truncate the database file on disk. 
 51467  **
 51468  **   The only reason the dbFileSize variable is required is to suppress 
 51469  **   unnecessary calls to xTruncate() after committing a transaction. If, 
 51470  **   when a transaction is committed, the dbFileSize variable indicates 
 51471  **   that the database file is larger than the database image (Pager.dbSize), 
 51472  **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
 51473  **   to measure the database file on disk, and then truncates it if required.
 51474  **   dbFileSize is not used when rolling back a transaction. In this case
 51475  **   pager_truncate() is called unconditionally (which means there may be
 51476  **   a call to xFilesize() that is not strictly required). In either case,
 51477  **   pager_truncate() may cause the file to become smaller or larger.
 51478  **
 51479  ** dbHintSize
 51480  **
 51481  **   The dbHintSize variable is used to limit the number of calls made to
 51482  **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
 51483  **
 51484  **   dbHintSize is set to a copy of the dbSize variable when a
 51485  **   write-transaction is opened (at the same time as dbFileSize and
 51486  **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
 51487  **   dbHintSize is increased to the number of pages that correspond to the
 51488  **   size-hint passed to the method call. See pager_write_pagelist() for 
 51489  **   details.
 51490  **
 51491  ** errCode
 51492  **
 51493  **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
 51494  **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
 51495  **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
 51496  **   sub-codes.
 51497  **
 51498  ** syncFlags, walSyncFlags
 51499  **
 51500  **   syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
 51501  **   syncFlags is used for rollback mode.  walSyncFlags is used for WAL mode
 51502  **   and contains the flags used to sync the checkpoint operations in the
 51503  **   lower two bits, and sync flags used for transaction commits in the WAL
 51504  **   file in bits 0x04 and 0x08.  In other words, to get the correct sync flags
 51505  **   for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
 51506  **   sync flags for transaction commit, use ((walSyncFlags>>2)&0x03).  Note
 51507  **   that with synchronous=NORMAL in WAL mode, transaction commit is not synced
 51508  **   meaning that the 0x04 and 0x08 bits are both zero.
 51509  */
 51510  struct Pager {
 51511    sqlite3_vfs *pVfs;          /* OS functions to use for IO */
 51512    u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
 51513    u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
 51514    u8 useJournal;              /* Use a rollback journal on this file */
 51515    u8 noSync;                  /* Do not sync the journal if true */
 51516    u8 fullSync;                /* Do extra syncs of the journal for robustness */
 51517    u8 extraSync;               /* sync directory after journal delete */
 51518    u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
 51519    u8 walSyncFlags;            /* See description above */
 51520    u8 tempFile;                /* zFilename is a temporary or immutable file */
 51521    u8 noLock;                  /* Do not lock (except in WAL mode) */
 51522    u8 readOnly;                /* True for a read-only database */
 51523    u8 memDb;                   /* True to inhibit all file I/O */
 51524  
 51525    /**************************************************************************
 51526    ** The following block contains those class members that change during
 51527    ** routine operation.  Class members not in this block are either fixed
 51528    ** when the pager is first created or else only change when there is a
 51529    ** significant mode change (such as changing the page_size, locking_mode,
 51530    ** or the journal_mode).  From another view, these class members describe
 51531    ** the "state" of the pager, while other class members describe the
 51532    ** "configuration" of the pager.
 51533    */
 51534    u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
 51535    u8 eLock;                   /* Current lock held on database file */
 51536    u8 changeCountDone;         /* Set after incrementing the change-counter */
 51537    u8 setMaster;               /* True if a m-j name has been written to jrnl */
 51538    u8 doNotSpill;              /* Do not spill the cache when non-zero */
 51539    u8 subjInMemory;            /* True to use in-memory sub-journals */
 51540    u8 bUseFetch;               /* True to use xFetch() */
 51541    u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
 51542    Pgno dbSize;                /* Number of pages in the database */
 51543    Pgno dbOrigSize;            /* dbSize before the current transaction */
 51544    Pgno dbFileSize;            /* Number of pages in the database file */
 51545    Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
 51546    int errCode;                /* One of several kinds of errors */
 51547    int nRec;                   /* Pages journalled since last j-header written */
 51548    u32 cksumInit;              /* Quasi-random value added to every checksum */
 51549    u32 nSubRec;                /* Number of records written to sub-journal */
 51550    Bitvec *pInJournal;         /* One bit for each page in the database file */
 51551    sqlite3_file *fd;           /* File descriptor for database */
 51552    sqlite3_file *jfd;          /* File descriptor for main journal */
 51553    sqlite3_file *sjfd;         /* File descriptor for sub-journal */
 51554    i64 journalOff;             /* Current write offset in the journal file */
 51555    i64 journalHdr;             /* Byte offset to previous journal header */
 51556    sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
 51557    PagerSavepoint *aSavepoint; /* Array of active savepoints */
 51558    int nSavepoint;             /* Number of elements in aSavepoint[] */
 51559    u32 iDataVersion;           /* Changes whenever database content changes */
 51560    char dbFileVers[16];        /* Changes whenever database file changes */
 51561  
 51562    int nMmapOut;               /* Number of mmap pages currently outstanding */
 51563    sqlite3_int64 szMmap;       /* Desired maximum mmap size */
 51564    PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
 51565    /*
 51566    ** End of the routinely-changing class members
 51567    ***************************************************************************/
 51568  
 51569    u16 nExtra;                 /* Add this many bytes to each in-memory page */
 51570    i16 nReserve;               /* Number of unused bytes at end of each page */
 51571    u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
 51572    u32 sectorSize;             /* Assumed sector size during rollback */
 51573    int pageSize;               /* Number of bytes in a page */
 51574    Pgno mxPgno;                /* Maximum allowed size of the database */
 51575    i64 journalSizeLimit;       /* Size limit for persistent journal files */
 51576    char *zFilename;            /* Name of the database file */
 51577    char *zJournal;             /* Name of the journal file */
 51578    int (*xBusyHandler)(void*); /* Function to call when busy */
 51579    void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
 51580    int aStat[4];               /* Total cache hits, misses, writes, spills */
 51581  #ifdef SQLITE_TEST
 51582    int nRead;                  /* Database pages read */
 51583  #endif
 51584    void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
 51585    int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
 51586  #ifdef SQLITE_HAS_CODEC
 51587    void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
 51588    void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
 51589    void (*xCodecFree)(void*);             /* Destructor for the codec */
 51590    void *pCodec;               /* First argument to xCodec... methods */
 51591  #endif
 51592    char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
 51593    PCache *pPCache;            /* Pointer to page cache object */
 51594  #ifndef SQLITE_OMIT_WAL
 51595    Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
 51596    char *zWal;                 /* File name for write-ahead log */
 51597  #endif
 51598    /*
 51599    ** Branch support members
 51600    ***************************************************************************/
 51601    u8 useBranches;              /* ... */
 51602    i64 max_db_size;             /* ... */
 51603    lmdb *lmdb;                  /* ... */
 51604  };
 51605  
 51606  /*
 51607  ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
 51608  ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
 51609  ** or CACHE_WRITE to sqlite3_db_status().
 51610  */
 51611  #define PAGER_STAT_HIT   0
 51612  #define PAGER_STAT_MISS  1
 51613  #define PAGER_STAT_WRITE 2
 51614  #define PAGER_STAT_SPILL 3
 51615  
 51616  /*
 51617  ** The following global variables hold counters used for
 51618  ** testing purposes only.  These variables do not exist in
 51619  ** a non-testing build.  These variables are not thread-safe.
 51620  */
 51621  #ifdef SQLITE_TEST
 51622  SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
 51623  SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
 51624  SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
 51625  # define PAGER_INCR(v)  v++
 51626  #else
 51627  # define PAGER_INCR(v)
 51628  #endif
 51629  
 51630  
 51631  
 51632  /*
 51633  ** Journal files begin with the following magic string.  The data
 51634  ** was obtained from /dev/random.  It is used only as a sanity check.
 51635  **
 51636  ** Since version 2.8.0, the journal format contains additional sanity
 51637  ** checking information.  If the power fails while the journal is being
 51638  ** written, semi-random garbage data might appear in the journal
 51639  ** file after power is restored.  If an attempt is then made
 51640  ** to roll the journal back, the database could be corrupted.  The additional
 51641  ** sanity checking data is an attempt to discover the garbage in the
 51642  ** journal and ignore it.
 51643  **
 51644  ** The sanity checking information for the new journal format consists
 51645  ** of a 32-bit checksum on each page of data.  The checksum covers both
 51646  ** the page number and the pPager->pageSize bytes of data for the page.
 51647  ** This cksum is initialized to a 32-bit random value that appears in the
 51648  ** journal file right after the header.  The random initializer is important,
 51649  ** because garbage data that appears at the end of a journal is likely
 51650  ** data that was once in other files that have now been deleted.  If the
 51651  ** garbage data came from an obsolete journal file, the checksums might
 51652  ** be correct.  But by initializing the checksum to random value which
 51653  ** is different for every journal, we minimize that risk.
 51654  */
 51655  static const unsigned char aJournalMagic[] = {
 51656    0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
 51657  };
 51658  
 51659  /*
 51660  ** The size of the of each page record in the journal is given by
 51661  ** the following macro.
 51662  */
 51663  #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
 51664  
 51665  /*
 51666  ** The journal header size for this pager. This is usually the same 
 51667  ** size as a single disk sector. See also setSectorSize().
 51668  */
 51669  #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
 51670  
 51671  /*
 51672  ** The macro MEMDB is true if we are dealing with an in-memory database.
 51673  ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
 51674  ** the value of MEMDB will be a constant and the compiler will optimize
 51675  ** out code that would never execute.
 51676  */
 51677  #ifdef SQLITE_OMIT_MEMORYDB
 51678  # define MEMDB 0
 51679  #else
 51680  # define MEMDB pPager->memDb
 51681  #endif
 51682  
 51683  /*
 51684  ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
 51685  ** interfaces to access the database using memory-mapped I/O.
 51686  */
 51687  #if SQLITE_MAX_MMAP_SIZE>0
 51688  # define USEFETCH(x) ((x)->bUseFetch)
 51689  #else
 51690  # define USEFETCH(x) 0
 51691  #endif
 51692  
 51693  /*
 51694  ** The maximum legal page number is (2^31 - 1).
 51695  */
 51696  #define PAGER_MAX_PGNO 2147483647
 51697  
 51698  /*
 51699  ** The argument to this macro is a file descriptor (type sqlite3_file*).
 51700  ** Return 0 if it is not open, or non-zero (but not 1) if it is.
 51701  **
 51702  ** This is so that expressions can be written as:
 51703  **
 51704  **   if( isOpen(pPager->jfd) ){ ...
 51705  **
 51706  ** instead of
 51707  **
 51708  **   if( pPager->jfd->pMethods ){ ...
 51709  */
 51710  #define isOpen(pFd) ((pFd)->pMethods!=0)
 51711  
 51712  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 51713  /*
 51714  ** Return true if page pgno can be read directly from the database file
 51715  ** by the b-tree layer. This is the case if:
 51716  **
 51717  **   * the database file is open,
 51718  **   * there are no dirty pages in the cache, and
 51719  **   * the desired page is not currently in the wal file.
 51720  */
 51721  SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
 51722    if( pPager->fd->pMethods==0 ) return 0;
 51723    if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
 51724  #ifndef SQLITE_OMIT_WAL
 51725    if( pPager->pWal ){
 51726      u32 iRead = 0;
 51727      int rc;
 51728      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
 51729      return (rc==SQLITE_OK && iRead==0);
 51730    }
 51731  #endif
 51732    return 1;
 51733  }
 51734  #endif
 51735  
 51736  #ifndef SQLITE_OMIT_WAL
 51737  # define pagerUseWal(x) ((x)->pWal!=0)
 51738  #else
 51739  # define pagerUseWal(x) 0
 51740  # define pagerRollbackWal(x) 0
 51741  # define pagerWalFrames(v,w,x,y) 0
 51742  # define pagerOpenWalIfPresent(z) SQLITE_OK
 51743  # define pagerBeginReadTransaction(z) SQLITE_OK
 51744  #endif
 51745  
 51746  #ifndef NDEBUG 
 51747  /*
 51748  ** Usage:
 51749  **
 51750  **   assert( assert_pager_state(pPager) );
 51751  **
 51752  ** This function runs many asserts to try to find inconsistencies in
 51753  ** the internal state of the Pager object.
 51754  */
 51755  static int assert_pager_state(Pager *p){
 51756    Pager *pPager = p;
 51757  
 51758    /* State must be valid. */
 51759    assert( p->eState==PAGER_OPEN
 51760         || p->eState==PAGER_READER
 51761         || p->eState==PAGER_WRITER_LOCKED
 51762         || p->eState==PAGER_WRITER_CACHEMOD
 51763         || p->eState==PAGER_WRITER_DBMOD
 51764         || p->eState==PAGER_WRITER_FINISHED
 51765         || p->eState==PAGER_ERROR
 51766    );
 51767  
 51768    /* Regardless of the current state, a temp-file connection always behaves
 51769    ** as if it has an exclusive lock on the database file. It never updates
 51770    ** the change-counter field, so the changeCountDone flag is always set.
 51771    */
 51772    assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
 51773    assert( p->tempFile==0 || pPager->changeCountDone );
 51774  
 51775    /* If the useJournal flag is clear, the journal-mode must be "OFF". 
 51776    ** And if the journal-mode is "OFF", the journal file must not be open.
 51777    */
 51778    assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
 51779    assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
 51780  
 51781    /* Check that MEMDB implies noSync. And an in-memory journal. Since 
 51782    ** this means an in-memory pager performs no IO at all, it cannot encounter 
 51783    ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
 51784    ** a journal file. (although the in-memory journal implementation may 
 51785    ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
 51786    ** is therefore not possible for an in-memory pager to enter the ERROR 
 51787    ** state.
 51788    */
 51789    if( MEMDB ){
 51790      assert( !isOpen(p->fd) );
 51791      assert( p->noSync );
 51792      assert( p->journalMode==PAGER_JOURNALMODE_OFF 
 51793           || p->journalMode==PAGER_JOURNALMODE_MEMORY 
 51794      );
 51795      assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
 51796      assert( pagerUseWal(p)==0 );
 51797    }
 51798  
 51799    /* If changeCountDone is set, a RESERVED lock or greater must be held
 51800    ** on the file.
 51801    */
 51802    assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
 51803    assert( p->eLock!=PENDING_LOCK );
 51804  
 51805    switch( p->eState ){
 51806      case PAGER_OPEN:
 51807        assert( !MEMDB );
 51808        assert( pPager->errCode==SQLITE_OK );
 51809        assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
 51810        break;
 51811  
 51812      case PAGER_READER:
 51813        assert( pPager->errCode==SQLITE_OK );
 51814        assert( p->eLock!=UNKNOWN_LOCK );
 51815        assert( p->eLock>=SHARED_LOCK );
 51816        break;
 51817  
 51818      case PAGER_WRITER_LOCKED:
 51819        assert( p->eLock!=UNKNOWN_LOCK );
 51820        assert( pPager->errCode==SQLITE_OK );
 51821        if( !pagerUseWal(pPager) ){
 51822          assert( p->eLock>=RESERVED_LOCK );
 51823        }
 51824        assert( pPager->dbSize==pPager->dbOrigSize );
 51825        assert( pPager->dbOrigSize==pPager->dbFileSize );
 51826        assert( pPager->dbOrigSize==pPager->dbHintSize );
 51827        assert( pPager->setMaster==0 );
 51828        break;
 51829  
 51830      case PAGER_WRITER_CACHEMOD:
 51831        assert( p->eLock!=UNKNOWN_LOCK );
 51832        assert( pPager->errCode==SQLITE_OK );
 51833        if( !pagerUseWal(pPager) ){
 51834          /* It is possible that if journal_mode=wal here that neither the
 51835          ** journal file nor the WAL file are open. This happens during
 51836          ** a rollback transaction that switches from journal_mode=off
 51837          ** to journal_mode=wal.
 51838          */
 51839          assert( p->eLock>=RESERVED_LOCK );
 51840          assert( isOpen(p->jfd) 
 51841               || p->journalMode==PAGER_JOURNALMODE_OFF 
 51842               || p->journalMode==PAGER_JOURNALMODE_WAL 
 51843          );
 51844        }
 51845        assert( pPager->dbOrigSize==pPager->dbFileSize );
 51846        assert( pPager->dbOrigSize==pPager->dbHintSize );
 51847        break;
 51848  
 51849      case PAGER_WRITER_DBMOD:
 51850        assert( p->eLock==EXCLUSIVE_LOCK );
 51851        assert( pPager->errCode==SQLITE_OK );
 51852        assert( !pagerUseWal(pPager) );
 51853        assert( p->eLock>=EXCLUSIVE_LOCK );
 51854        assert( isOpen(p->jfd) 
 51855             || p->journalMode==PAGER_JOURNALMODE_OFF 
 51856             || p->journalMode==PAGER_JOURNALMODE_WAL 
 51857             || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 51858        );
 51859        assert( pPager->dbOrigSize<=pPager->dbHintSize );
 51860        break;
 51861  
 51862      case PAGER_WRITER_FINISHED:
 51863        assert( p->eLock==EXCLUSIVE_LOCK );
 51864        assert( pPager->errCode==SQLITE_OK );
 51865        assert( !pagerUseWal(pPager) );
 51866        assert( isOpen(p->jfd) 
 51867             || p->journalMode==PAGER_JOURNALMODE_OFF 
 51868             || p->journalMode==PAGER_JOURNALMODE_WAL 
 51869             || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 51870        );
 51871        break;
 51872  
 51873      case PAGER_ERROR:
 51874        /* There must be at least one outstanding reference to the pager if
 51875        ** in ERROR state. Otherwise the pager should have already dropped
 51876        ** back to OPEN state.
 51877        */
 51878        assert( pPager->errCode!=SQLITE_OK );
 51879        assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
 51880        break;
 51881    }
 51882  
 51883    return 1;
 51884  }
 51885  #endif /* ifndef NDEBUG */
 51886  
 51887  #ifdef SQLITE_DEBUG 
 51888  /*
 51889  ** Return a pointer to a human readable string in a static buffer
 51890  ** containing the state of the Pager object passed as an argument. This
 51891  ** is intended to be used within debuggers. For example, as an alternative
 51892  ** to "print *pPager" in gdb:
 51893  **
 51894  ** (gdb) printf "%s", print_pager_state(pPager)
 51895  **
 51896  ** This routine has external linkage in order to suppress compiler warnings
 51897  ** about an unused function.  It is enclosed within SQLITE_DEBUG and so does
 51898  ** not appear in normal builds.
 51899  */
 51900  char *print_pager_state(Pager *p){
 51901    static char zRet[1024];
 51902  
 51903    sqlite3_snprintf(1024, zRet,
 51904        "Filename:      %s\n"
 51905        "State:         %s errCode=%d\n"
 51906        "Lock:          %s\n"
 51907        "Locking mode:  locking_mode=%s\n"
 51908        "Journal mode:  journal_mode=%s\n"
 51909        "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
 51910        "Journal:       journalOff=%lld journalHdr=%lld\n"
 51911        "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
 51912        , p->zFilename
 51913        , p->eState==PAGER_OPEN            ? "OPEN" :
 51914          p->eState==PAGER_READER          ? "READER" :
 51915          p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
 51916          p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
 51917          p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
 51918          p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
 51919          p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
 51920        , (int)p->errCode
 51921        , p->eLock==NO_LOCK         ? "NO_LOCK" :
 51922          p->eLock==RESERVED_LOCK   ? "RESERVED" :
 51923          p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
 51924          p->eLock==SHARED_LOCK     ? "SHARED" :
 51925          p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
 51926        , p->exclusiveMode ? "exclusive" : "normal"
 51927        , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
 51928          p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
 51929          p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
 51930          p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
 51931          p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
 51932          p->journalMode==PAGER_JOURNALMODE_BRANCHES ? "branches" :
 51933          p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
 51934        , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
 51935        , p->journalOff, p->journalHdr
 51936        , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
 51937    );
 51938  
 51939    return zRet;
 51940  }
 51941  #endif
 51942  
 51943  /* Forward references to the various page getters */
 51944  static int getPageNormal(Pager*,Pgno,DbPage**,int);
 51945  static int getPageError(Pager*,Pgno,DbPage**,int);
 51946  #if SQLITE_MAX_MMAP_SIZE>0
 51947  static int getPageMMap(Pager*,Pgno,DbPage**,int);
 51948  #endif
 51949  
 51950  /*
 51951  ** Set the Pager.xGet method for the appropriate routine used to fetch
 51952  ** content from the pager.
 51953  */
 51954  static void setGetterMethod(Pager *pPager){
 51955    if( pPager->errCode ){
 51956      pPager->xGet = getPageError;
 51957  #if SQLITE_MAX_MMAP_SIZE>0
 51958    }else if( USEFETCH(pPager)
 51959  #ifdef SQLITE_HAS_CODEC
 51960     && pPager->xCodec==0
 51961  #endif
 51962    ){
 51963      pPager->xGet = getPageMMap;
 51964  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 51965    }else{
 51966      pPager->xGet = getPageNormal;
 51967    }
 51968  }
 51969  
 51970  /*
 51971  ** Return true if it is necessary to write page *pPg into the sub-journal.
 51972  ** A page needs to be written into the sub-journal if there exists one
 51973  ** or more open savepoints for which:
 51974  **
 51975  **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
 51976  **   * The bit corresponding to the page-number is not set in
 51977  **     PagerSavepoint.pInSavepoint.
 51978  */
 51979  static int subjRequiresPage(PgHdr *pPg){
 51980    Pager *pPager = pPg->pPager;
 51981    PagerSavepoint *p;
 51982    Pgno pgno = pPg->pgno;
 51983    int i;
 51984    for(i=0; i<pPager->nSavepoint; i++){
 51985      p = &pPager->aSavepoint[i];
 51986      if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
 51987        return 1;
 51988      }
 51989    }
 51990    return 0;
 51991  }
 51992  
 51993  #ifdef SQLITE_DEBUG
 51994  /*
 51995  ** Return true if the page is already in the journal file.
 51996  */
 51997  static int pageInJournal(Pager *pPager, PgHdr *pPg){
 51998    return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
 51999  }
 52000  #endif
 52001  
 52002  /*
 52003  ** Read a 32-bit integer from the given file descriptor.  Store the integer
 52004  ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
 52005  ** error code is something goes wrong.
 52006  **
 52007  ** All values are stored on disk as big-endian.
 52008  */
 52009  static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
 52010    unsigned char ac[4];
 52011    int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
 52012    if( rc==SQLITE_OK ){
 52013      *pRes = sqlite3Get4byte(ac);
 52014    }
 52015    return rc;
 52016  }
 52017  
 52018  /*
 52019  ** Write a 32-bit integer into a string buffer in big-endian byte order.
 52020  */
 52021  #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
 52022  
 52023  
 52024  /*
 52025  ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
 52026  ** on success or an error code is something goes wrong.
 52027  */
 52028  static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
 52029    char ac[4];
 52030    put32bits(ac, val);
 52031    return sqlite3OsWrite(fd, ac, 4, offset);
 52032  }
 52033  
 52034  /*
 52035  ** Unlock the database file to level eLock, which must be either NO_LOCK
 52036  ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
 52037  ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
 52038  **
 52039  ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
 52040  ** called, do not modify it. See the comment above the #define of 
 52041  ** UNKNOWN_LOCK for an explanation of this.
 52042  */
 52043  static int pagerUnlockDb(Pager *pPager, int eLock){
 52044    int rc = SQLITE_OK;
 52045  
 52046    assert( !pPager->exclusiveMode || pPager->eLock==eLock );
 52047    assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
 52048    assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
 52049    if( isOpen(pPager->fd) ){
 52050      assert( pPager->eLock>=eLock );
 52051      rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
 52052      if( pPager->eLock!=UNKNOWN_LOCK ){
 52053        pPager->eLock = (u8)eLock;
 52054      }
 52055      IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
 52056    }
 52057    return rc;
 52058  }
 52059  
 52060  /*
 52061  ** Lock the database file to level eLock, which must be either SHARED_LOCK,
 52062  ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
 52063  ** Pager.eLock variable to the new locking state. 
 52064  **
 52065  ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
 52066  ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
 52067  ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
 52068  ** of this.
 52069  */
 52070  static int pagerLockDb(Pager *pPager, int eLock){
 52071    int rc = SQLITE_OK;
 52072  
 52073    assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
 52074    if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
 52075      rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
 52076      if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
 52077        pPager->eLock = (u8)eLock;
 52078        IOTRACE(("LOCK %p %d\n", pPager, eLock))
 52079      }
 52080    }
 52081    return rc;
 52082  }
 52083  
 52084  /*
 52085  ** This function determines whether or not the atomic-write or
 52086  ** atomic-batch-write optimizations can be used with this pager. The
 52087  ** atomic-write optimization can be used if:
 52088  **
 52089  **  (a) the value returned by OsDeviceCharacteristics() indicates that
 52090  **      a database page may be written atomically, and
 52091  **  (b) the value returned by OsSectorSize() is less than or equal
 52092  **      to the page size.
 52093  **
 52094  ** If it can be used, then the value returned is the size of the journal 
 52095  ** file when it contains rollback data for exactly one page.
 52096  **
 52097  ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
 52098  ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
 52099  ** returned in this case.
 52100  **
 52101  ** If neither optimization can be used, 0 is returned.
 52102  */
 52103  static int jrnlBufferSize(Pager *pPager){
 52104    assert( !MEMDB );
 52105  
 52106  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 52107   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 52108    int dc;                           /* Device characteristics */
 52109  
 52110    assert( isOpen(pPager->fd) );
 52111    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
 52112  #else
 52113    UNUSED_PARAMETER(pPager);
 52114  #endif
 52115  
 52116  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 52117    if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
 52118      return -1;
 52119    }
 52120  #endif
 52121  
 52122  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 52123    {
 52124      int nSector = pPager->sectorSize;
 52125      int szPage = pPager->pageSize;
 52126  
 52127      assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 52128      assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 52129      if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
 52130        return 0;
 52131      }
 52132    }
 52133  
 52134    return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
 52135  #endif
 52136  
 52137    return 0;
 52138  }
 52139  
 52140  /*
 52141  ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
 52142  ** on the cache using a hash function.  This is used for testing
 52143  ** and debugging only.
 52144  */
 52145  #ifdef SQLITE_CHECK_PAGES
 52146  /*
 52147  ** Return a 32-bit hash of the page data for pPage.
 52148  */
 52149  static u32 pager_datahash(int nByte, unsigned char *pData){
 52150    u32 hash = 0;
 52151    int i;
 52152    for(i=0; i<nByte; i++){
 52153      hash = (hash*1039) + pData[i];
 52154    }
 52155    return hash;
 52156  }
 52157  static u32 pager_pagehash(PgHdr *pPage){
 52158    return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
 52159  }
 52160  static void pager_set_pagehash(PgHdr *pPage){
 52161    pPage->pageHash = pager_pagehash(pPage);
 52162  }
 52163  
 52164  /*
 52165  ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
 52166  ** is defined, and NDEBUG is not defined, an assert() statement checks
 52167  ** that the page is either dirty or still matches the calculated page-hash.
 52168  */
 52169  #define CHECK_PAGE(x) checkPage(x)
 52170  static void checkPage(PgHdr *pPg){
 52171    Pager *pPager = pPg->pPager;
 52172    assert( pPager->eState!=PAGER_ERROR );
 52173    assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
 52174  }
 52175  
 52176  #else
 52177  #define pager_datahash(X,Y)  0
 52178  #define pager_pagehash(X)  0
 52179  #define pager_set_pagehash(X)
 52180  #define CHECK_PAGE(x)
 52181  #endif  /* SQLITE_CHECK_PAGES */
 52182  
 52183  /*
 52184  ** When this is called the journal file for pager pPager must be open.
 52185  ** This function attempts to read a master journal file name from the 
 52186  ** end of the file and, if successful, copies it into memory supplied 
 52187  ** by the caller. See comments above writeMasterJournal() for the format
 52188  ** used to store a master journal file name at the end of a journal file.
 52189  **
 52190  ** zMaster must point to a buffer of at least nMaster bytes allocated by
 52191  ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
 52192  ** enough space to write the master journal name). If the master journal
 52193  ** name in the journal is longer than nMaster bytes (including a
 52194  ** nul-terminator), then this is handled as if no master journal name
 52195  ** were present in the journal.
 52196  **
 52197  ** If a master journal file name is present at the end of the journal
 52198  ** file, then it is copied into the buffer pointed to by zMaster. A
 52199  ** nul-terminator byte is appended to the buffer following the master
 52200  ** journal file name.
 52201  **
 52202  ** If it is determined that no master journal file name is present 
 52203  ** zMaster[0] is set to 0 and SQLITE_OK returned.
 52204  **
 52205  ** If an error occurs while reading from the journal file, an SQLite
 52206  ** error code is returned.
 52207  */
 52208  static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
 52209    int rc;                    /* Return code */
 52210    u32 len;                   /* Length in bytes of master journal name */
 52211    i64 szJ;                   /* Total size in bytes of journal file pJrnl */
 52212    u32 cksum;                 /* MJ checksum value read from journal */
 52213    u32 u;                     /* Unsigned loop counter */
 52214    unsigned char aMagic[8];   /* A buffer to hold the magic header */
 52215    zMaster[0] = '\0';
 52216  
 52217    if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
 52218     || szJ<16
 52219     || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
 52220     || len>=nMaster 
 52221     || len>szJ-16
 52222     || len==0 
 52223     || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
 52224     || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
 52225     || memcmp(aMagic, aJournalMagic, 8)
 52226     || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
 52227    ){
 52228      return rc;
 52229    }
 52230  
 52231    /* See if the checksum matches the master journal name */
 52232    for(u=0; u<len; u++){
 52233      cksum -= zMaster[u];
 52234    }
 52235    if( cksum ){
 52236      /* If the checksum doesn't add up, then one or more of the disk sectors
 52237      ** containing the master journal filename is corrupted. This means
 52238      ** definitely roll back, so just return SQLITE_OK and report a (nul)
 52239      ** master-journal filename.
 52240      */
 52241      len = 0;
 52242    }
 52243    zMaster[len] = '\0';
 52244     
 52245    return SQLITE_OK;
 52246  }
 52247  
 52248  /*
 52249  ** Return the offset of the sector boundary at or immediately 
 52250  ** following the value in pPager->journalOff, assuming a sector 
 52251  ** size of pPager->sectorSize bytes.
 52252  **
 52253  ** i.e for a sector size of 512:
 52254  **
 52255  **   Pager.journalOff          Return value
 52256  **   ---------------------------------------
 52257  **   0                         0
 52258  **   512                       512
 52259  **   100                       512
 52260  **   2000                      2048
 52261  ** 
 52262  */
 52263  static i64 journalHdrOffset(Pager *pPager){
 52264    i64 offset = 0;
 52265    i64 c = pPager->journalOff;
 52266    if( c ){
 52267      offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
 52268    }
 52269    assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
 52270    assert( offset>=c );
 52271    assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
 52272    return offset;
 52273  }
 52274  
 52275  /*
 52276  ** The journal file must be open when this function is called.
 52277  **
 52278  ** This function is a no-op if the journal file has not been written to
 52279  ** within the current transaction (i.e. if Pager.journalOff==0).
 52280  **
 52281  ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
 52282  ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
 52283  ** zero the 28-byte header at the start of the journal file. In either case, 
 52284  ** if the pager is not in no-sync mode, sync the journal file immediately 
 52285  ** after writing or truncating it.
 52286  **
 52287  ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
 52288  ** following the truncation or zeroing described above the size of the 
 52289  ** journal file in bytes is larger than this value, then truncate the
 52290  ** journal file to Pager.journalSizeLimit bytes. The journal file does
 52291  ** not need to be synced following this operation.
 52292  **
 52293  ** If an IO error occurs, abandon processing and return the IO error code.
 52294  ** Otherwise, return SQLITE_OK.
 52295  */
 52296  static int zeroJournalHdr(Pager *pPager, int doTruncate){
 52297    int rc = SQLITE_OK;                               /* Return code */
 52298    assert( isOpen(pPager->jfd) );
 52299    assert( !sqlite3JournalIsInMemory(pPager->jfd) );
 52300    if( pPager->journalOff ){
 52301      const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
 52302  
 52303      IOTRACE(("JZEROHDR %p\n", pPager))
 52304      if( doTruncate || iLimit==0 ){
 52305        rc = sqlite3OsTruncate(pPager->jfd, 0);
 52306      }else{
 52307        static const char zeroHdr[28] = {0};
 52308        rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
 52309      }
 52310      if( rc==SQLITE_OK && !pPager->noSync ){
 52311        rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
 52312      }
 52313  
 52314      /* At this point the transaction is committed but the write lock 
 52315      ** is still held on the file. If there is a size limit configured for 
 52316      ** the persistent journal and the journal file currently consumes more
 52317      ** space than that limit allows for, truncate it now. There is no need
 52318      ** to sync the file following this operation.
 52319      */
 52320      if( rc==SQLITE_OK && iLimit>0 ){
 52321        i64 sz;
 52322        rc = sqlite3OsFileSize(pPager->jfd, &sz);
 52323        if( rc==SQLITE_OK && sz>iLimit ){
 52324          rc = sqlite3OsTruncate(pPager->jfd, iLimit);
 52325        }
 52326      }
 52327    }
 52328    return rc;
 52329  }
 52330  
 52331  /*
 52332  ** The journal file must be open when this routine is called. A journal
 52333  ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
 52334  ** current location.
 52335  **
 52336  ** The format for the journal header is as follows:
 52337  ** - 8 bytes: Magic identifying journal format.
 52338  ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
 52339  ** - 4 bytes: Random number used for page hash.
 52340  ** - 4 bytes: Initial database page count.
 52341  ** - 4 bytes: Sector size used by the process that wrote this journal.
 52342  ** - 4 bytes: Database page size.
 52343  ** 
 52344  ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
 52345  */
 52346  static int writeJournalHdr(Pager *pPager){
 52347    int rc = SQLITE_OK;                 /* Return code */
 52348    char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
 52349    u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
 52350    u32 nWrite;                         /* Bytes of header sector written */
 52351    int ii;                             /* Loop counter */
 52352  
 52353    assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 52354  
 52355    if( nHeader>JOURNAL_HDR_SZ(pPager) ){
 52356      nHeader = JOURNAL_HDR_SZ(pPager);
 52357    }
 52358  
 52359    /* If there are active savepoints and any of them were created 
 52360    ** since the most recent journal header was written, update the 
 52361    ** PagerSavepoint.iHdrOffset fields now.
 52362    */
 52363    for(ii=0; ii<pPager->nSavepoint; ii++){
 52364      if( pPager->aSavepoint[ii].iHdrOffset==0 ){
 52365        pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
 52366      }
 52367    }
 52368  
 52369    pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
 52370  
 52371    /* 
 52372    ** Write the nRec Field - the number of page records that follow this
 52373    ** journal header. Normally, zero is written to this value at this time.
 52374    ** After the records are added to the journal (and the journal synced, 
 52375    ** if in full-sync mode), the zero is overwritten with the true number
 52376    ** of records (see syncJournal()).
 52377    **
 52378    ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
 52379    ** reading the journal this value tells SQLite to assume that the
 52380    ** rest of the journal file contains valid page records. This assumption
 52381    ** is dangerous, as if a failure occurred whilst writing to the journal
 52382    ** file it may contain some garbage data. There are two scenarios
 52383    ** where this risk can be ignored:
 52384    **
 52385    **   * When the pager is in no-sync mode. Corruption can follow a
 52386    **     power failure in this case anyway.
 52387    **
 52388    **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
 52389    **     that garbage data is never appended to the journal file.
 52390    */
 52391    assert( isOpen(pPager->fd) || pPager->noSync );
 52392    if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
 52393     || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
 52394    ){
 52395      memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 52396      put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
 52397    }else{
 52398      memset(zHeader, 0, sizeof(aJournalMagic)+4);
 52399    }
 52400  
 52401    /* The random check-hash initializer */ 
 52402    sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
 52403    put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
 52404    /* The initial database size */
 52405    put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
 52406    /* The assumed sector size for this process */
 52407    put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
 52408  
 52409    /* The page size */
 52410    put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
 52411  
 52412    /* Initializing the tail of the buffer is not necessary.  Everything
 52413    ** works find if the following memset() is omitted.  But initializing
 52414    ** the memory prevents valgrind from complaining, so we are willing to
 52415    ** take the performance hit.
 52416    */
 52417    memset(&zHeader[sizeof(aJournalMagic)+20], 0,
 52418           nHeader-(sizeof(aJournalMagic)+20));
 52419  
 52420    /* In theory, it is only necessary to write the 28 bytes that the 
 52421    ** journal header consumes to the journal file here. Then increment the 
 52422    ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
 52423    ** record is written to the following sector (leaving a gap in the file
 52424    ** that will be implicitly filled in by the OS).
 52425    **
 52426    ** However it has been discovered that on some systems this pattern can 
 52427    ** be significantly slower than contiguously writing data to the file,
 52428    ** even if that means explicitly writing data to the block of 
 52429    ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
 52430    ** is done. 
 52431    **
 52432    ** The loop is required here in case the sector-size is larger than the 
 52433    ** database page size. Since the zHeader buffer is only Pager.pageSize
 52434    ** bytes in size, more than one call to sqlite3OsWrite() may be required
 52435    ** to populate the entire journal header sector.
 52436    */ 
 52437    for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
 52438      IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
 52439      rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
 52440      assert( pPager->journalHdr <= pPager->journalOff );
 52441      pPager->journalOff += nHeader;
 52442    }
 52443  
 52444    return rc;
 52445  }
 52446  
 52447  /*
 52448  ** The journal file must be open when this is called. A journal header file
 52449  ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
 52450  ** file. The current location in the journal file is given by
 52451  ** pPager->journalOff. See comments above function writeJournalHdr() for
 52452  ** a description of the journal header format.
 52453  **
 52454  ** If the header is read successfully, *pNRec is set to the number of
 52455  ** page records following this header and *pDbSize is set to the size of the
 52456  ** database before the transaction began, in pages. Also, pPager->cksumInit
 52457  ** is set to the value read from the journal header. SQLITE_OK is returned
 52458  ** in this case.
 52459  **
 52460  ** If the journal header file appears to be corrupted, SQLITE_DONE is
 52461  ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
 52462  ** cannot be read from the journal file an error code is returned.
 52463  */
 52464  static int readJournalHdr(
 52465    Pager *pPager,               /* Pager object */
 52466    int isHot,
 52467    i64 journalSize,             /* Size of the open journal file in bytes */
 52468    u32 *pNRec,                  /* OUT: Value read from the nRec field */
 52469    u32 *pDbSize                 /* OUT: Value of original database size field */
 52470  ){
 52471    int rc;                      /* Return code */
 52472    unsigned char aMagic[8];     /* A buffer to hold the magic header */
 52473    i64 iHdrOff;                 /* Offset of journal header being read */
 52474  
 52475    assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
 52476  
 52477    /* Advance Pager.journalOff to the start of the next sector. If the
 52478    ** journal file is too small for there to be a header stored at this
 52479    ** point, return SQLITE_DONE.
 52480    */
 52481    pPager->journalOff = journalHdrOffset(pPager);
 52482    if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
 52483      return SQLITE_DONE;
 52484    }
 52485    iHdrOff = pPager->journalOff;
 52486  
 52487    /* Read in the first 8 bytes of the journal header. If they do not match
 52488    ** the  magic string found at the start of each journal header, return
 52489    ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
 52490    ** proceed.
 52491    */
 52492    if( isHot || iHdrOff!=pPager->journalHdr ){
 52493      rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
 52494      if( rc ){
 52495        return rc;
 52496      }
 52497      if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
 52498        return SQLITE_DONE;
 52499      }
 52500    }
 52501  
 52502    /* Read the first three 32-bit fields of the journal header: The nRec
 52503    ** field, the checksum-initializer and the database size at the start
 52504    ** of the transaction. Return an error code if anything goes wrong.
 52505    */
 52506    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
 52507     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
 52508     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
 52509    ){
 52510      return rc;
 52511    }
 52512  
 52513    if( pPager->journalOff==0 ){
 52514      u32 iPageSize;               /* Page-size field of journal header */
 52515      u32 iSectorSize;             /* Sector-size field of journal header */
 52516  
 52517      /* Read the page-size and sector-size journal header fields. */
 52518      if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
 52519       || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
 52520      ){
 52521        return rc;
 52522      }
 52523  
 52524      /* Versions of SQLite prior to 3.5.8 set the page-size field of the
 52525      ** journal header to zero. In this case, assume that the Pager.pageSize
 52526      ** variable is already set to the correct page size.
 52527      */
 52528      if( iPageSize==0 ){
 52529        iPageSize = pPager->pageSize;
 52530      }
 52531  
 52532      /* Check that the values read from the page-size and sector-size fields
 52533      ** are within range. To be 'in range', both values need to be a power
 52534      ** of two greater than or equal to 512 or 32, and not greater than their 
 52535      ** respective compile time maximum limits.
 52536      */
 52537      if( iPageSize<512                  || iSectorSize<32
 52538       || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
 52539       || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
 52540      ){
 52541        /* If the either the page-size or sector-size in the journal-header is 
 52542        ** invalid, then the process that wrote the journal-header must have 
 52543        ** crashed before the header was synced. In this case stop reading 
 52544        ** the journal file here.
 52545        */
 52546        return SQLITE_DONE;
 52547      }
 52548  
 52549      /* Update the page-size to match the value read from the journal. 
 52550      ** Use a testcase() macro to make sure that malloc failure within 
 52551      ** PagerSetPagesize() is tested.
 52552      */
 52553      rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
 52554      testcase( rc!=SQLITE_OK );
 52555  
 52556      /* Update the assumed sector-size to match the value used by 
 52557      ** the process that created this journal. If this journal was
 52558      ** created by a process other than this one, then this routine
 52559      ** is being called from within pager_playback(). The local value
 52560      ** of Pager.sectorSize is restored at the end of that routine.
 52561      */
 52562      pPager->sectorSize = iSectorSize;
 52563    }
 52564  
 52565    pPager->journalOff += JOURNAL_HDR_SZ(pPager);
 52566    return rc;
 52567  }
 52568  
 52569  
 52570  /*
 52571  ** Write the supplied master journal name into the journal file for pager
 52572  ** pPager at the current location. The master journal name must be the last
 52573  ** thing written to a journal file. If the pager is in full-sync mode, the
 52574  ** journal file descriptor is advanced to the next sector boundary before
 52575  ** anything is written. The format is:
 52576  **
 52577  **   + 4 bytes: PAGER_MJ_PGNO.
 52578  **   + N bytes: Master journal filename in utf-8.
 52579  **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
 52580  **   + 4 bytes: Master journal name checksum.
 52581  **   + 8 bytes: aJournalMagic[].
 52582  **
 52583  ** The master journal page checksum is the sum of the bytes in the master
 52584  ** journal name, where each byte is interpreted as a signed 8-bit integer.
 52585  **
 52586  ** If zMaster is a NULL pointer (occurs for a single database transaction), 
 52587  ** this call is a no-op.
 52588  */
 52589  static int writeMasterJournal(Pager *pPager, const char *zMaster){
 52590    int rc;                          /* Return code */
 52591    int nMaster;                     /* Length of string zMaster */
 52592    i64 iHdrOff;                     /* Offset of header in journal file */
 52593    i64 jrnlSize;                    /* Size of journal file on disk */
 52594    u32 cksum = 0;                   /* Checksum of string zMaster */
 52595  
 52596    assert( pPager->setMaster==0 );
 52597    assert( !pagerUseWal(pPager) );
 52598  
 52599    if( !zMaster 
 52600     || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 52601     || !isOpen(pPager->jfd)
 52602    ){
 52603      return SQLITE_OK;
 52604    }
 52605    pPager->setMaster = 1;
 52606    assert( pPager->journalHdr <= pPager->journalOff );
 52607  
 52608    /* Calculate the length in bytes and the checksum of zMaster */
 52609    for(nMaster=0; zMaster[nMaster]; nMaster++){
 52610      cksum += zMaster[nMaster];
 52611    }
 52612  
 52613    /* If in full-sync mode, advance to the next disk sector before writing
 52614    ** the master journal name. This is in case the previous page written to
 52615    ** the journal has already been synced.
 52616    */
 52617    if( pPager->fullSync ){
 52618      pPager->journalOff = journalHdrOffset(pPager);
 52619    }
 52620    iHdrOff = pPager->journalOff;
 52621  
 52622    /* Write the master journal data to the end of the journal file. If
 52623    ** an error occurs, return the error code to the caller.
 52624    */
 52625    if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
 52626     || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
 52627     || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
 52628     || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
 52629     || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
 52630                                   iHdrOff+4+nMaster+8)))
 52631    ){
 52632      return rc;
 52633    }
 52634    pPager->journalOff += (nMaster+20);
 52635  
 52636    /* If the pager is in peristent-journal mode, then the physical 
 52637    ** journal-file may extend past the end of the master-journal name
 52638    ** and 8 bytes of magic data just written to the file. This is 
 52639    ** dangerous because the code to rollback a hot-journal file
 52640    ** will not be able to find the master-journal name to determine 
 52641    ** whether or not the journal is hot. 
 52642    **
 52643    ** Easiest thing to do in this scenario is to truncate the journal 
 52644    ** file to the required size.
 52645    */ 
 52646    if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
 52647     && jrnlSize>pPager->journalOff
 52648    ){
 52649      rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
 52650    }
 52651    return rc;
 52652  }
 52653  
 52654  /*
 52655  ** Discard the entire contents of the in-memory page-cache.
 52656  */
 52657  static void pager_reset(Pager *pPager){
 52658    BRANCHTRACE("pager_reset");
 52659    pPager->iDataVersion++;
 52660    sqlite3BackupRestart(pPager->pBackup);
 52661    sqlite3PcacheClear(pPager->pPCache);
 52662  }
 52663  
 52664  /*
 52665  ** Return the pPager->iDataVersion value
 52666  */
 52667  SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
 52668    return pPager->iDataVersion;
 52669  }
 52670  
 52671  /*
 52672  ** Free all structures in the Pager.aSavepoint[] array and set both
 52673  ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
 52674  ** if it is open and the pager is not in exclusive mode.
 52675  */
 52676  static void releaseAllSavepoints(Pager *pPager){
 52677    int ii;               /* Iterator for looping through Pager.aSavepoint */
 52678    for(ii=0; ii<pPager->nSavepoint; ii++){
 52679      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 52680    }
 52681    if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
 52682      sqlite3OsClose(pPager->sjfd);
 52683    }
 52684    sqlite3_free(pPager->aSavepoint);
 52685    pPager->aSavepoint = 0;
 52686    pPager->nSavepoint = 0;
 52687    pPager->nSubRec = 0;
 52688  }
 52689  
 52690  /*
 52691  ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
 52692  ** bitvecs of all open savepoints. Return SQLITE_OK if successful
 52693  ** or SQLITE_NOMEM if a malloc failure occurs.
 52694  */
 52695  static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
 52696    int ii;                   /* Loop counter */
 52697    int rc = SQLITE_OK;       /* Result code */
 52698  
 52699    for(ii=0; ii<pPager->nSavepoint; ii++){
 52700      PagerSavepoint *p = &pPager->aSavepoint[ii];
 52701      if( pgno<=p->nOrig ){
 52702        rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
 52703        testcase( rc==SQLITE_NOMEM );
 52704        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 52705      }
 52706    }
 52707    return rc;
 52708  }
 52709  
 52710  /*
 52711  ** This function is a no-op if the pager is in exclusive mode and not
 52712  ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
 52713  ** state.
 52714  **
 52715  ** If the pager is not in exclusive-access mode, the database file is
 52716  ** completely unlocked. If the file is unlocked and the file-system does
 52717  ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
 52718  ** closed (if it is open).
 52719  **
 52720  ** If the pager is in ERROR state when this function is called, the 
 52721  ** contents of the pager cache are discarded before switching back to 
 52722  ** the OPEN state. Regardless of whether the pager is in exclusive-mode
 52723  ** or not, any journal file left in the file-system will be treated
 52724  ** as a hot-journal and rolled back the next time a read-transaction
 52725  ** is opened (by this or by any other connection).
 52726  */
 52727  static void pager_unlock(Pager *pPager){
 52728  
 52729    BRANCHTRACE("pager_unlock");
 52730  
 52731    assert( pPager->eState==PAGER_READER 
 52732         || pPager->eState==PAGER_OPEN 
 52733         || pPager->eState==PAGER_ERROR 
 52734    );
 52735  
 52736    sqlite3BitvecDestroy(pPager->pInJournal);
 52737    pPager->pInJournal = 0;
 52738    releaseAllSavepoints(pPager);
 52739  
 52740    if( pagerUseWal(pPager) ){
 52741      assert( !isOpen(pPager->jfd) );
 52742      sqlite3WalEndReadTransaction(pPager->pWal);
 52743      pPager->eState = PAGER_OPEN;
 52744    }else if( !pPager->exclusiveMode ){
 52745      int rc;                       /* Error code returned by pagerUnlockDb() */
 52746      int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
 52747  
 52748      /* If the operating system support deletion of open files, then
 52749      ** close the journal file when dropping the database lock.  Otherwise
 52750      ** another connection with journal_mode=delete might delete the file
 52751      ** out from under us.
 52752      */
 52753      assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
 52754      assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
 52755      assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
 52756      assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
 52757      assert( (PAGER_JOURNALMODE_BRANCHES & 5)!=1 );
 52758      assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 52759      assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
 52760      if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
 52761       || 1!=(pPager->journalMode & 5)
 52762      ){
 52763        sqlite3OsClose(pPager->jfd);
 52764      }
 52765  
 52766      /* If the pager is in the ERROR state and the call to unlock the database
 52767      ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
 52768      ** above the #define for UNKNOWN_LOCK for an explanation of why this
 52769      ** is necessary.
 52770      */
 52771      rc = pagerUnlockDb(pPager, NO_LOCK);
 52772      if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
 52773        pPager->eLock = UNKNOWN_LOCK;
 52774      }
 52775  
 52776      /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
 52777      ** without clearing the error code. This is intentional - the error
 52778      ** code is cleared and the cache reset in the block below.
 52779      */
 52780      assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
 52781      pPager->changeCountDone = 0;
 52782      pPager->eState = PAGER_OPEN;
 52783    }
 52784  
 52785    /* If Pager.errCode is set, the contents of the pager cache cannot be
 52786    ** trusted. Now that there are no outstanding references to the pager,
 52787    ** it can safely move back to PAGER_OPEN state. This happens in both
 52788    ** normal and exclusive-locking mode.
 52789    */
 52790    assert( pPager->errCode==SQLITE_OK || !MEMDB );
 52791    if( pPager->errCode ){
 52792      if( pPager->tempFile==0 ){
 52793        pager_reset(pPager);
 52794        pPager->changeCountDone = 0;
 52795        pPager->eState = PAGER_OPEN;
 52796      }else{
 52797        pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
 52798      }
 52799      if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 52800      pPager->errCode = SQLITE_OK;
 52801      setGetterMethod(pPager);
 52802    }
 52803  
 52804    pPager->journalOff = 0;
 52805    pPager->journalHdr = 0;
 52806    pPager->setMaster = 0;
 52807  }
 52808  
 52809  /*
 52810  ** This function is called whenever an IOERR or FULL error that requires
 52811  ** the pager to transition into the ERROR state may ahve occurred.
 52812  ** The first argument is a pointer to the pager structure, the second 
 52813  ** the error-code about to be returned by a pager API function. The 
 52814  ** value returned is a copy of the second argument to this function. 
 52815  **
 52816  ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
 52817  ** IOERR sub-codes, the pager enters the ERROR state and the error code
 52818  ** is stored in Pager.errCode. While the pager remains in the ERROR state,
 52819  ** all major API calls on the Pager will immediately return Pager.errCode.
 52820  **
 52821  ** The ERROR state indicates that the contents of the pager-cache 
 52822  ** cannot be trusted. This state can be cleared by completely discarding 
 52823  ** the contents of the pager-cache. If a transaction was active when
 52824  ** the persistent error occurred, then the rollback journal may need
 52825  ** to be replayed to restore the contents of the database file (as if
 52826  ** it were a hot-journal).
 52827  */
 52828  static int pager_error(Pager *pPager, int rc){
 52829    int rc2 = rc & 0xff;
 52830    assert( rc==SQLITE_OK || !MEMDB );
 52831    assert(
 52832         pPager->errCode==SQLITE_FULL ||
 52833         pPager->errCode==SQLITE_OK ||
 52834         (pPager->errCode & 0xff)==SQLITE_IOERR
 52835    );
 52836    if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
 52837      pPager->errCode = rc;
 52838      pPager->eState = PAGER_ERROR;
 52839      setGetterMethod(pPager);
 52840    }
 52841    return rc;
 52842  }
 52843  
 52844  static int pager_truncate(Pager *pPager, Pgno nPage);
 52845  
 52846  /*
 52847  ** The write transaction open on pPager is being committed (bCommit==1)
 52848  ** or rolled back (bCommit==0).
 52849  **
 52850  ** Return TRUE if and only if all dirty pages should be flushed to disk.
 52851  **
 52852  ** Rules:
 52853  **
 52854  **   *  For non-TEMP databases, always sync to disk.  This is necessary
 52855  **      for transactions to be durable.
 52856  **
 52857  **   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
 52858  **      file has been created already (via a spill on pagerStress()) and
 52859  **      when the number of dirty pages in memory exceeds 25% of the total
 52860  **      cache size.
 52861  */
 52862  static int pagerFlushOnCommit(Pager *pPager, int bCommit){
 52863    if( pPager->tempFile==0 ) return 1;
 52864    if( !bCommit ) return 0;
 52865    if( !isOpen(pPager->fd) ) return 0;
 52866    return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
 52867  }
 52868  
 52869  /*
 52870  ** This routine ends a transaction. A transaction is usually ended by 
 52871  ** either a COMMIT or a ROLLBACK operation. This routine may be called 
 52872  ** after rollback of a hot-journal, or if an error occurs while opening
 52873  ** the journal file or writing the very first journal-header of a
 52874  ** database transaction.
 52875  ** 
 52876  ** This routine is never called in PAGER_ERROR state. If it is called
 52877  ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
 52878  ** exclusive than a RESERVED lock, it is a no-op.
 52879  **
 52880  ** Otherwise, any active savepoints are released.
 52881  **
 52882  ** If the journal file is open, then it is "finalized". Once a journal 
 52883  ** file has been finalized it is not possible to use it to roll back a 
 52884  ** transaction. Nor will it be considered to be a hot-journal by this
 52885  ** or any other database connection. Exactly how a journal is finalized
 52886  ** depends on whether or not the pager is running in exclusive mode and
 52887  ** the current journal-mode (Pager.journalMode value), as follows:
 52888  **
 52889  **   journalMode==MEMORY
 52890  **     Journal file descriptor is simply closed. This destroys an 
 52891  **     in-memory journal.
 52892  **
 52893  **   journalMode==TRUNCATE
 52894  **     Journal file is truncated to zero bytes in size.
 52895  **
 52896  **   journalMode==PERSIST
 52897  **     The first 28 bytes of the journal file are zeroed. This invalidates
 52898  **     the first journal header in the file, and hence the entire journal
 52899  **     file. An invalid journal file cannot be rolled back.
 52900  **
 52901  **   journalMode==DELETE
 52902  **     The journal file is closed and deleted using sqlite3OsDelete().
 52903  **
 52904  **     If the pager is running in exclusive mode, this method of finalizing
 52905  **     the journal file is never used. Instead, if the journalMode is
 52906  **     DELETE and the pager is in exclusive mode, the method described under
 52907  **     journalMode==PERSIST is used instead.
 52908  **
 52909  ** After the journal is finalized, the pager moves to PAGER_READER state.
 52910  ** If running in non-exclusive rollback mode, the lock on the file is 
 52911  ** downgraded to a SHARED_LOCK.
 52912  **
 52913  ** SQLITE_OK is returned if no error occurs. If an error occurs during
 52914  ** any of the IO operations to finalize the journal file or unlock the
 52915  ** database then the IO error code is returned to the user. If the 
 52916  ** operation to finalize the journal file fails, then the code still
 52917  ** tries to unlock the database file if not in exclusive mode. If the
 52918  ** unlock operation fails as well, then the first error code related
 52919  ** to the first error encountered (the journal finalization one) is
 52920  ** returned.
 52921  */
 52922  static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
 52923    int rc = SQLITE_OK;      /* Error code from journal finalization operation */
 52924    int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
 52925  
 52926    BRANCHTRACE("pager_end_transaction");
 52927  
 52928    /* Do nothing if the pager does not have an open write transaction
 52929    ** or at least a RESERVED lock. This function may be called when there
 52930    ** is no write-transaction active but a RESERVED or greater lock is
 52931    ** held under two circumstances:
 52932    **
 52933    **   1. After a successful hot-journal rollback, it is called with
 52934    **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
 52935    **
 52936    **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
 52937    **      lock switches back to locking_mode=normal and then executes a
 52938    **      read-transaction, this function is called with eState==PAGER_READER 
 52939    **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
 52940    */
 52941    assert( assert_pager_state(pPager) );
 52942    assert( pPager->eState!=PAGER_ERROR );
 52943    if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
 52944      return SQLITE_OK;
 52945    }
 52946  
 52947    releaseAllSavepoints(pPager);
 52948    assert( isOpen(pPager->jfd) || pPager->pInJournal==0 
 52949        || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
 52950    );
 52951    if( isOpen(pPager->jfd) ){
 52952      assert( !pagerUseWal(pPager) );
 52953  
 52954      /* Finalize the journal file. */
 52955      if( sqlite3JournalIsInMemory(pPager->jfd) ){
 52956        /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
 52957        sqlite3OsClose(pPager->jfd);
 52958      }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
 52959        if( pPager->journalOff==0 ){
 52960          rc = SQLITE_OK;
 52961        }else{
 52962          rc = sqlite3OsTruncate(pPager->jfd, 0);
 52963          if( rc==SQLITE_OK && pPager->fullSync ){
 52964            /* Make sure the new file size is written into the inode right away.
 52965            ** Otherwise the journal might resurrect following a power loss and
 52966            ** cause the last transaction to roll back.  See
 52967            ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
 52968            */
 52969            rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
 52970          }
 52971        }
 52972        pPager->journalOff = 0;
 52973      }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 52974        || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
 52975      ){
 52976        rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
 52977        pPager->journalOff = 0;
 52978      }else{
 52979        /* This branch may be executed with Pager.journalMode==MEMORY if
 52980        ** a hot-journal was just rolled back. In this case the journal
 52981        ** file should be closed and deleted. If this connection writes to
 52982        ** the database file, it will do so using an in-memory journal.
 52983        */
 52984        int bDelete = !pPager->tempFile;
 52985        assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
 52986        assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
 52987             || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
 52988             || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 52989        );
 52990        sqlite3OsClose(pPager->jfd);
 52991        if( bDelete ){
 52992          rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
 52993        }
 52994      }
 52995    }
 52996  
 52997  #ifdef SQLITE_CHECK_PAGES
 52998    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
 52999    if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
 53000      PgHdr *p = sqlite3PagerLookup(pPager, 1);
 53001      if( p ){
 53002        p->pageHash = 0;
 53003        sqlite3PagerUnrefNotNull(p);
 53004      }
 53005    }
 53006  #endif
 53007  
 53008    sqlite3BitvecDestroy(pPager->pInJournal);
 53009    pPager->pInJournal = 0;
 53010    pPager->nRec = 0;
 53011    if( rc==SQLITE_OK ){
 53012      if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
 53013        sqlite3PcacheCleanAll(pPager->pPCache);
 53014      }else{
 53015        sqlite3PcacheClearWritable(pPager->pPCache);
 53016      }
 53017      sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
 53018    }
 53019  
 53020    if( pagerUseWal(pPager) ){
 53021      /* Drop the WAL write-lock, if any. Also, if the connection was in 
 53022      ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
 53023      ** lock held on the database file.
 53024      */
 53025      rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
 53026      assert( rc2==SQLITE_OK );
 53027    }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
 53028      /* This branch is taken when committing a transaction in rollback-journal
 53029      ** mode if the database file on disk is larger than the database image.
 53030      ** At this point the journal has been finalized and the transaction 
 53031      ** successfully committed, but the EXCLUSIVE lock is still held on the
 53032      ** file. So it is safe to truncate the database file to its minimum
 53033      ** required size.  */
 53034      assert( pPager->eLock==EXCLUSIVE_LOCK );
 53035      rc = pager_truncate(pPager, pPager->dbSize);
 53036    }
 53037  
 53038    if( rc==SQLITE_OK && bCommit ){
 53039      rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
 53040      if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 53041    }
 53042  
 53043    if( !pPager->exclusiveMode 
 53044     && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
 53045    ){
 53046      rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
 53047      pPager->changeCountDone = 0;
 53048    }
 53049    pPager->eState = PAGER_READER;
 53050    pPager->setMaster = 0;
 53051  
 53052    return (rc==SQLITE_OK?rc2:rc);
 53053  }
 53054  
 53055  /*
 53056  ** Execute a rollback if a transaction is active and unlock the 
 53057  ** database file. 
 53058  **
 53059  ** If the pager has already entered the ERROR state, do not attempt 
 53060  ** the rollback at this time. Instead, pager_unlock() is called. The
 53061  ** call to pager_unlock() will discard all in-memory pages, unlock
 53062  ** the database file and move the pager back to OPEN state. If this 
 53063  ** means that there is a hot-journal left in the file-system, the next 
 53064  ** connection to obtain a shared lock on the pager (which may be this one) 
 53065  ** will roll it back.
 53066  **
 53067  ** If the pager has not already entered the ERROR state, but an IO or
 53068  ** malloc error occurs during a rollback, then this will itself cause 
 53069  ** the pager to enter the ERROR state. Which will be cleared by the
 53070  ** call to pager_unlock(), as described above.
 53071  */
 53072  static void pagerUnlockAndRollback(Pager *pPager){
 53073    BRANCHTRACE("pagerUnlockAndRollback");
 53074    if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
 53075      assert( assert_pager_state(pPager) );
 53076      if( pPager->eState>=PAGER_WRITER_LOCKED ){
 53077        sqlite3BeginBenignMalloc();
 53078        sqlite3PagerRollback(pPager);
 53079        sqlite3EndBenignMalloc();
 53080      }else if( !pPager->exclusiveMode ){
 53081        assert( pPager->eState==PAGER_READER );
 53082        pager_end_transaction(pPager, 0, 0);
 53083      }
 53084    }
 53085    pager_unlock(pPager);
 53086  }
 53087  
 53088  /*
 53089  ** Parameter aData must point to a buffer of pPager->pageSize bytes
 53090  ** of data. Compute and return a checksum based ont the contents of the 
 53091  ** page of data and the current value of pPager->cksumInit.
 53092  **
 53093  ** This is not a real checksum. It is really just the sum of the 
 53094  ** random initial value (pPager->cksumInit) and every 200th byte
 53095  ** of the page data, starting with byte offset (pPager->pageSize%200).
 53096  ** Each byte is interpreted as an 8-bit unsigned integer.
 53097  **
 53098  ** Changing the formula used to compute this checksum results in an
 53099  ** incompatible journal file format.
 53100  **
 53101  ** If journal corruption occurs due to a power failure, the most likely 
 53102  ** scenario is that one end or the other of the record will be changed. 
 53103  ** It is much less likely that the two ends of the journal record will be
 53104  ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
 53105  ** though fast and simple, catches the mostly likely kind of corruption.
 53106  */
 53107  static u32 pager_cksum(Pager *pPager, const u8 *aData){
 53108    u32 cksum = pPager->cksumInit;         /* Checksum value to return */
 53109    int i = pPager->pageSize-200;          /* Loop counter */
 53110    while( i>0 ){
 53111      cksum += aData[i];
 53112      i -= 200;
 53113    }
 53114    return cksum;
 53115  }
 53116  
 53117  /*
 53118  ** Report the current page size and number of reserved bytes back
 53119  ** to the codec.
 53120  */
 53121  #ifdef SQLITE_HAS_CODEC
 53122  static void pagerReportSize(Pager *pPager){
 53123    if( pPager->xCodecSizeChng ){
 53124      pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
 53125                             (int)pPager->nReserve);
 53126    }
 53127  }
 53128  #else
 53129  # define pagerReportSize(X)     /* No-op if we do not support a codec */
 53130  #endif
 53131  
 53132  #ifdef SQLITE_HAS_CODEC
 53133  /*
 53134  ** Make sure the number of reserved bits is the same in the destination
 53135  ** pager as it is in the source.  This comes up when a VACUUM changes the
 53136  ** number of reserved bits to the "optimal" amount.
 53137  */
 53138  SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
 53139    if( pDest->nReserve!=pSrc->nReserve ){
 53140      pDest->nReserve = pSrc->nReserve;
 53141      pagerReportSize(pDest);
 53142    }
 53143  }
 53144  #endif
 53145  
 53146  /*
 53147  ** Read a single page from either the journal file (if isMainJrnl==1) or
 53148  ** from the sub-journal (if isMainJrnl==0) and playback that page.
 53149  ** The page begins at offset *pOffset into the file. The *pOffset
 53150  ** value is increased to the start of the next page in the journal.
 53151  **
 53152  ** The main rollback journal uses checksums - the statement journal does 
 53153  ** not.
 53154  **
 53155  ** If the page number of the page record read from the (sub-)journal file
 53156  ** is greater than the current value of Pager.dbSize, then playback is
 53157  ** skipped and SQLITE_OK is returned.
 53158  **
 53159  ** If pDone is not NULL, then it is a record of pages that have already
 53160  ** been played back.  If the page at *pOffset has already been played back
 53161  ** (if the corresponding pDone bit is set) then skip the playback.
 53162  ** Make sure the pDone bit corresponding to the *pOffset page is set
 53163  ** prior to returning.
 53164  **
 53165  ** If the page record is successfully read from the (sub-)journal file
 53166  ** and played back, then SQLITE_OK is returned. If an IO error occurs
 53167  ** while reading the record from the (sub-)journal file or while writing
 53168  ** to the database file, then the IO error code is returned. If data
 53169  ** is successfully read from the (sub-)journal file but appears to be
 53170  ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
 53171  ** two circumstances:
 53172  ** 
 53173  **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
 53174  **   * If the record is being rolled back from the main journal file
 53175  **     and the checksum field does not match the record content.
 53176  **
 53177  ** Neither of these two scenarios are possible during a savepoint rollback.
 53178  **
 53179  ** If this is a savepoint rollback, then memory may have to be dynamically
 53180  ** allocated by this function. If this is the case and an allocation fails,
 53181  ** SQLITE_NOMEM is returned.
 53182  */
 53183  static int pager_playback_one_page(
 53184    Pager *pPager,                /* The pager being played back */
 53185    i64 *pOffset,                 /* Offset of record to playback */
 53186    Bitvec *pDone,                /* Bitvec of pages already played back */
 53187    int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
 53188    int isSavepnt                 /* True for a savepoint rollback */
 53189  ){
 53190    int rc;
 53191    PgHdr *pPg;                   /* An existing page in the cache */
 53192    Pgno pgno;                    /* The page number of a page in journal */
 53193    u32 cksum;                    /* Checksum used for sanity checking */
 53194    char *aData;                  /* Temporary storage for the page */
 53195    sqlite3_file *jfd;            /* The file descriptor for the journal file */
 53196    int isSynced;                 /* True if journal page is synced */
 53197  #ifdef SQLITE_HAS_CODEC
 53198    /* The jrnlEnc flag is true if Journal pages should be passed through
 53199    ** the codec.  It is false for pure in-memory journals. */
 53200    const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
 53201  #endif
 53202  
 53203    BRANCHTRACE("pager_playback_one_page");
 53204  
 53205    assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
 53206    assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
 53207    assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
 53208    assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
 53209  
 53210    aData = pPager->pTmpSpace;
 53211    assert( aData );         /* Temp storage must have already been allocated */
 53212    assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
 53213  
 53214    /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
 53215    ** or savepoint rollback done at the request of the caller) or this is
 53216    ** a hot-journal rollback. If it is a hot-journal rollback, the pager
 53217    ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
 53218    ** only reads from the main journal, not the sub-journal.
 53219    */
 53220    assert( pPager->eState>=PAGER_WRITER_CACHEMOD
 53221         || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
 53222    );
 53223    assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
 53224  
 53225    /* Read the page number and page data from the journal or sub-journal
 53226    ** file. Return an error code to the caller if an IO error occurs.
 53227    */
 53228    jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
 53229    rc = read32bits(jfd, *pOffset, &pgno);
 53230    if( rc!=SQLITE_OK ) return rc;
 53231    rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
 53232    if( rc!=SQLITE_OK ) return rc;
 53233    *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
 53234  
 53235    /* Sanity checking on the page.  This is more important that I originally
 53236    ** thought.  If a power failure occurs while the journal is being written,
 53237    ** it could cause invalid data to be written into the journal.  We need to
 53238    ** detect this invalid data (with high probability) and ignore it.
 53239    */
 53240    if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
 53241      assert( !isSavepnt );
 53242      return SQLITE_DONE;
 53243    }
 53244    if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
 53245      return SQLITE_OK;
 53246    }
 53247    if( isMainJrnl ){
 53248      rc = read32bits(jfd, (*pOffset)-4, &cksum);
 53249      if( rc ) return rc;
 53250      if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
 53251        return SQLITE_DONE;
 53252      }
 53253    }
 53254  
 53255    /* If this page has already been played back before during the current
 53256    ** rollback, then don't bother to play it back again.
 53257    */
 53258    if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
 53259      return rc;
 53260    }
 53261  
 53262    /* When playing back page 1, restore the nReserve setting
 53263    */
 53264    if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
 53265      pPager->nReserve = ((u8*)aData)[20];
 53266      pagerReportSize(pPager);
 53267    }
 53268  
 53269    /* If the pager is in CACHEMOD state, then there must be a copy of this
 53270    ** page in the pager cache. In this case just update the pager cache,
 53271    ** not the database file. The page is left marked dirty in this case.
 53272    **
 53273    ** An exception to the above rule: If the database is in no-sync mode
 53274    ** and a page is moved during an incremental vacuum then the page may
 53275    ** not be in the pager cache. Later: if a malloc() or IO error occurs
 53276    ** during a Movepage() call, then the page may not be in the cache
 53277    ** either. So the condition described in the above paragraph is not
 53278    ** assert()able.
 53279    **
 53280    ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
 53281    ** pager cache if it exists and the main file. The page is then marked 
 53282    ** not dirty. Since this code is only executed in PAGER_OPEN state for
 53283    ** a hot-journal rollback, it is guaranteed that the page-cache is empty
 53284    ** if the pager is in OPEN state.
 53285    **
 53286    ** Ticket #1171:  The statement journal might contain page content that is
 53287    ** different from the page content at the start of the transaction.
 53288    ** This occurs when a page is changed prior to the start of a statement
 53289    ** then changed again within the statement.  When rolling back such a
 53290    ** statement we must not write to the original database unless we know
 53291    ** for certain that original page contents are synced into the main rollback
 53292    ** journal.  Otherwise, a power loss might leave modified data in the
 53293    ** database file without an entry in the rollback journal that can
 53294    ** restore the database to its original form.  Two conditions must be
 53295    ** met before writing to the database files. (1) the database must be
 53296    ** locked.  (2) we know that the original page content is fully synced
 53297    ** in the main journal either because the page is not in cache or else
 53298    ** the page is marked as needSync==0.
 53299    **
 53300    ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
 53301    ** is possible to fail a statement on a database that does not yet exist.
 53302    ** Do not attempt to write if database file has never been opened.
 53303    */
 53304    if( pagerUseWal(pPager) ){
 53305      pPg = 0;
 53306    }else{
 53307      pPg = sqlite3PagerLookup(pPager, pgno);
 53308    }
 53309    assert( pPg || !MEMDB );
 53310    assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
 53311    PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
 53312             PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
 53313             (isMainJrnl?"main-journal":"sub-journal")
 53314    ));
 53315    if( isMainJrnl ){
 53316      isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
 53317    }else{
 53318      isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
 53319    }
 53320    if( isOpen(pPager->fd)
 53321     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 53322     && isSynced
 53323    ){
 53324      i64 ofst = (pgno-1)*(i64)pPager->pageSize;
 53325      testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
 53326      assert( !pagerUseWal(pPager) );
 53327  
 53328      /* Write the data read from the journal back into the database file.
 53329      ** This is usually safe even for an encrypted database - as the data
 53330      ** was encrypted before it was written to the journal file. The exception
 53331      ** is if the data was just read from an in-memory sub-journal. In that
 53332      ** case it must be encrypted here before it is copied into the database
 53333      ** file.  */
 53334  #ifdef SQLITE_HAS_CODEC
 53335      if( !jrnlEnc ){
 53336        CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
 53337        rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 53338        CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
 53339      }else
 53340  #endif
 53341      rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 53342  
 53343      if( pgno>pPager->dbFileSize ){
 53344        pPager->dbFileSize = pgno;
 53345      }
 53346      if( pPager->pBackup ){
 53347  #ifdef SQLITE_HAS_CODEC
 53348        if( jrnlEnc ){
 53349          CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
 53350          sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 53351          CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
 53352        }else
 53353  #endif
 53354        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
 53355      }
 53356    }else if( !isMainJrnl && pPg==0 ){
 53357      /* If this is a rollback of a savepoint and data was not written to
 53358      ** the database and the page is not in-memory, there is a potential
 53359      ** problem. When the page is next fetched by the b-tree layer, it 
 53360      ** will be read from the database file, which may or may not be 
 53361      ** current. 
 53362      **
 53363      ** There are a couple of different ways this can happen. All are quite
 53364      ** obscure. When running in synchronous mode, this can only happen 
 53365      ** if the page is on the free-list at the start of the transaction, then
 53366      ** populated, then moved using sqlite3PagerMovepage().
 53367      **
 53368      ** The solution is to add an in-memory page to the cache containing
 53369      ** the data just read from the sub-journal. Mark the page as dirty 
 53370      ** and if the pager requires a journal-sync, then mark the page as 
 53371      ** requiring a journal-sync before it is written.
 53372      */
 53373      assert( isSavepnt );
 53374      assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
 53375      pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
 53376      rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
 53377      assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
 53378      pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
 53379      if( rc!=SQLITE_OK ) return rc;
 53380      sqlite3PcacheMakeDirty(pPg);
 53381    }
 53382    if( pPg ){
 53383      /* No page should ever be explicitly rolled back that is in use, except
 53384      ** for page 1 which is held in use in order to keep the lock on the
 53385      ** database active. However such a page may be rolled back as a result
 53386      ** of an internal error resulting in an automatic call to
 53387      ** sqlite3PagerRollback().
 53388      */
 53389      void *pData;
 53390      pData = pPg->pData;
 53391      memcpy(pData, (u8*)aData, pPager->pageSize);
 53392      pPager->xReiniter(pPg);
 53393      /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
 53394      ** that call was dangerous and had no detectable benefit since the cache
 53395      ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
 53396      ** has been removed. */
 53397      pager_set_pagehash(pPg);
 53398  
 53399      /* If this was page 1, then restore the value of Pager.dbFileVers.
 53400      ** Do this before any decoding. */
 53401      if( pgno==1 ){
 53402        memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
 53403      }
 53404  
 53405      /* Decode the page just read from disk */
 53406  #if SQLITE_HAS_CODEC
 53407      if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
 53408  #endif
 53409      sqlite3PcacheRelease(pPg);
 53410    }
 53411    return rc;
 53412  }
 53413  
 53414  /*
 53415  ** Parameter zMaster is the name of a master journal file. A single journal
 53416  ** file that referred to the master journal file has just been rolled back.
 53417  ** This routine checks if it is possible to delete the master journal file,
 53418  ** and does so if it is.
 53419  **
 53420  ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
 53421  ** available for use within this function.
 53422  **
 53423  ** When a master journal file is created, it is populated with the names 
 53424  ** of all of its child journals, one after another, formatted as utf-8 
 53425  ** encoded text. The end of each child journal file is marked with a 
 53426  ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
 53427  ** file for a transaction involving two databases might be:
 53428  **
 53429  **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
 53430  **
 53431  ** A master journal file may only be deleted once all of its child 
 53432  ** journals have been rolled back.
 53433  **
 53434  ** This function reads the contents of the master-journal file into 
 53435  ** memory and loops through each of the child journal names. For
 53436  ** each child journal, it checks if:
 53437  **
 53438  **   * if the child journal exists, and if so
 53439  **   * if the child journal contains a reference to master journal 
 53440  **     file zMaster
 53441  **
 53442  ** If a child journal can be found that matches both of the criteria
 53443  ** above, this function returns without doing anything. Otherwise, if
 53444  ** no such child journal can be found, file zMaster is deleted from
 53445  ** the file-system using sqlite3OsDelete().
 53446  **
 53447  ** If an IO error within this function, an error code is returned. This
 53448  ** function allocates memory by calling sqlite3Malloc(). If an allocation
 53449  ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
 53450  ** occur, SQLITE_OK is returned.
 53451  **
 53452  ** TODO: This function allocates a single block of memory to load
 53453  ** the entire contents of the master journal file. This could be
 53454  ** a couple of kilobytes or so - potentially larger than the page 
 53455  ** size.
 53456  */
 53457  static int pager_delmaster(Pager *pPager, const char *zMaster){
 53458    sqlite3_vfs *pVfs = pPager->pVfs;
 53459    int rc;                   /* Return code */
 53460    sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
 53461    sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
 53462    char *zMasterJournal = 0; /* Contents of master journal file */
 53463    i64 nMasterJournal;       /* Size of master journal file */
 53464    char *zJournal;           /* Pointer to one journal within MJ file */
 53465    char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
 53466    int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
 53467  
 53468    /* Allocate space for both the pJournal and pMaster file descriptors.
 53469    ** If successful, open the master journal file for reading.
 53470    */
 53471    pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
 53472    pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
 53473    if( !pMaster ){
 53474      rc = SQLITE_NOMEM_BKPT;
 53475    }else{
 53476      const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
 53477      rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
 53478    }
 53479    if( rc!=SQLITE_OK ) goto delmaster_out;
 53480  
 53481    /* Load the entire master journal file into space obtained from
 53482    ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
 53483    ** sufficient space (in zMasterPtr) to hold the names of master
 53484    ** journal files extracted from regular rollback-journals.
 53485    */
 53486    rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
 53487    if( rc!=SQLITE_OK ) goto delmaster_out;
 53488    nMasterPtr = pVfs->mxPathname+1;
 53489    zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
 53490    if( !zMasterJournal ){
 53491      rc = SQLITE_NOMEM_BKPT;
 53492      goto delmaster_out;
 53493    }
 53494    zMasterPtr = &zMasterJournal[nMasterJournal+1];
 53495    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
 53496    if( rc!=SQLITE_OK ) goto delmaster_out;
 53497    zMasterJournal[nMasterJournal] = 0;
 53498  
 53499    zJournal = zMasterJournal;
 53500    while( (zJournal-zMasterJournal)<nMasterJournal ){
 53501      int exists;
 53502      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
 53503      if( rc!=SQLITE_OK ){
 53504        goto delmaster_out;
 53505      }
 53506      if( exists ){
 53507        /* One of the journals pointed to by the master journal exists.
 53508        ** Open it and check if it points at the master journal. If
 53509        ** so, return without deleting the master journal file.
 53510        */
 53511        int c;
 53512        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
 53513        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
 53514        if( rc!=SQLITE_OK ){
 53515          goto delmaster_out;
 53516        }
 53517  
 53518        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
 53519        sqlite3OsClose(pJournal);
 53520        if( rc!=SQLITE_OK ){
 53521          goto delmaster_out;
 53522        }
 53523  
 53524        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
 53525        if( c ){
 53526          /* We have a match. Do not delete the master journal file. */
 53527          goto delmaster_out;
 53528        }
 53529      }
 53530      zJournal += (sqlite3Strlen30(zJournal)+1);
 53531    }
 53532   
 53533    sqlite3OsClose(pMaster);
 53534    rc = sqlite3OsDelete(pVfs, zMaster, 0);
 53535  
 53536  delmaster_out:
 53537    sqlite3_free(zMasterJournal);
 53538    if( pMaster ){
 53539      sqlite3OsClose(pMaster);
 53540      assert( !isOpen(pJournal) );
 53541      sqlite3_free(pMaster);
 53542    }
 53543    return rc;
 53544  }
 53545  
 53546  
 53547  /*
 53548  ** This function is used to change the actual size of the database 
 53549  ** file in the file-system. This only happens when committing a transaction,
 53550  ** or rolling back a transaction (including rolling back a hot-journal).
 53551  **
 53552  ** If the main database file is not open, or the pager is not in either
 53553  ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
 53554  ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
 53555  ** If the file on disk is currently larger than nPage pages, then use the VFS
 53556  ** xTruncate() method to truncate it.
 53557  **
 53558  ** Or, it might be the case that the file on disk is smaller than 
 53559  ** nPage pages. Some operating system implementations can get confused if 
 53560  ** you try to truncate a file to some size that is larger than it 
 53561  ** currently is, so detect this case and write a single zero byte to 
 53562  ** the end of the new file instead.
 53563  **
 53564  ** If successful, return SQLITE_OK. If an IO error occurs while modifying
 53565  ** the database file, return the error code to the caller.
 53566  */
 53567  static int pager_truncate(Pager *pPager, Pgno nPage){
 53568    int rc = SQLITE_OK;
 53569    assert( pPager->eState!=PAGER_ERROR );
 53570    assert( pPager->eState!=PAGER_READER );
 53571    
 53572    BRANCHTRACE("pager_truncate nPage=%d", nPage);
 53573  
 53574    if( isOpen(pPager->fd) 
 53575     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
 53576    ){
 53577      i64 currentSize, newSize;
 53578      int szPage = pPager->pageSize;
 53579      assert( pPager->eLock==EXCLUSIVE_LOCK );
 53580      /* TODO: Is it safe to use Pager.dbFileSize here? */
 53581      rc = sqlite3OsFileSize(pPager->fd, &currentSize);
 53582      newSize = szPage*(i64)nPage;
 53583      if( rc==SQLITE_OK && currentSize!=newSize ){
 53584        if( currentSize>newSize ){
 53585          rc = sqlite3OsTruncate(pPager->fd, newSize);
 53586        }else if( (currentSize+szPage)<=newSize ){
 53587          char *pTmp = pPager->pTmpSpace;
 53588          memset(pTmp, 0, szPage);
 53589          testcase( (newSize-szPage) == currentSize );
 53590          testcase( (newSize-szPage) >  currentSize );
 53591          rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
 53592        }
 53593        if( rc==SQLITE_OK ){
 53594          pPager->dbFileSize = nPage;
 53595        }
 53596      }
 53597    }
 53598    return rc;
 53599  }
 53600  
 53601  /*
 53602  ** Return a sanitized version of the sector-size of OS file pFile. The
 53603  ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
 53604  */
 53605  SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
 53606    int iRet = sqlite3OsSectorSize(pFile);
 53607    if( iRet<32 ){
 53608      iRet = 512;
 53609    }else if( iRet>MAX_SECTOR_SIZE ){
 53610      assert( MAX_SECTOR_SIZE>=512 );
 53611      iRet = MAX_SECTOR_SIZE;
 53612    }
 53613    BRANCHTRACE("sqlite3SectorSize = %d bytes", iRet);
 53614    return iRet;
 53615  }
 53616  
 53617  /*
 53618  ** Set the value of the Pager.sectorSize variable for the given
 53619  ** pager based on the value returned by the xSectorSize method
 53620  ** of the open database file. The sector size will be used 
 53621  ** to determine the size and alignment of journal header and 
 53622  ** master journal pointers within created journal files.
 53623  **
 53624  ** For temporary files the effective sector size is always 512 bytes.
 53625  **
 53626  ** Otherwise, for non-temporary files, the effective sector size is
 53627  ** the value returned by the xSectorSize() method rounded up to 32 if
 53628  ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
 53629  ** is greater than MAX_SECTOR_SIZE.
 53630  **
 53631  ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
 53632  ** the effective sector size to its minimum value (512).  The purpose of
 53633  ** pPager->sectorSize is to define the "blast radius" of bytes that
 53634  ** might change if a crash occurs while writing to a single byte in
 53635  ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
 53636  ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
 53637  ** size.  For backwards compatibility of the rollback journal file format,
 53638  ** we cannot reduce the effective sector size below 512.
 53639  */
 53640  static void setSectorSize(Pager *pPager){
 53641    assert( isOpen(pPager->fd) || pPager->tempFile );
 53642  
 53643    if( pPager->tempFile
 53644     || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
 53645                SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
 53646    ){
 53647      /* Sector size doesn't matter for temporary files. Also, the file
 53648      ** may not have been opened yet, in which case the OsSectorSize()
 53649      ** call will segfault. */
 53650      pPager->sectorSize = 512;
 53651    }else{
 53652      pPager->sectorSize = sqlite3SectorSize(pPager->fd);
 53653    }
 53654  }
 53655  
 53656  /*
 53657  ** Playback the journal and thus restore the database file to
 53658  ** the state it was in before we started making changes.  
 53659  **
 53660  ** The journal file format is as follows: 
 53661  **
 53662  **  (1)  8 byte prefix.  A copy of aJournalMagic[].
 53663  **  (2)  4 byte big-endian integer which is the number of valid page records
 53664  **       in the journal.  If this value is 0xffffffff, then compute the
 53665  **       number of page records from the journal size.
 53666  **  (3)  4 byte big-endian integer which is the initial value for the 
 53667  **       sanity checksum.
 53668  **  (4)  4 byte integer which is the number of pages to truncate the
 53669  **       database to during a rollback.
 53670  **  (5)  4 byte big-endian integer which is the sector size.  The header
 53671  **       is this many bytes in size.
 53672  **  (6)  4 byte big-endian integer which is the page size.
 53673  **  (7)  zero padding out to the next sector size.
 53674  **  (8)  Zero or more pages instances, each as follows:
 53675  **        +  4 byte page number.
 53676  **        +  pPager->pageSize bytes of data.
 53677  **        +  4 byte checksum
 53678  **
 53679  ** When we speak of the journal header, we mean the first 7 items above.
 53680  ** Each entry in the journal is an instance of the 8th item.
 53681  **
 53682  ** Call the value from the second bullet "nRec".  nRec is the number of
 53683  ** valid page entries in the journal.  In most cases, you can compute the
 53684  ** value of nRec from the size of the journal file.  But if a power
 53685  ** failure occurred while the journal was being written, it could be the
 53686  ** case that the size of the journal file had already been increased but
 53687  ** the extra entries had not yet made it safely to disk.  In such a case,
 53688  ** the value of nRec computed from the file size would be too large.  For
 53689  ** that reason, we always use the nRec value in the header.
 53690  **
 53691  ** If the nRec value is 0xffffffff it means that nRec should be computed
 53692  ** from the file size.  This value is used when the user selects the
 53693  ** no-sync option for the journal.  A power failure could lead to corruption
 53694  ** in this case.  But for things like temporary table (which will be
 53695  ** deleted when the power is restored) we don't care.  
 53696  **
 53697  ** If the file opened as the journal file is not a well-formed
 53698  ** journal file then all pages up to the first corrupted page are rolled
 53699  ** back (or no pages if the journal header is corrupted). The journal file
 53700  ** is then deleted and SQLITE_OK returned, just as if no corruption had
 53701  ** been encountered.
 53702  **
 53703  ** If an I/O or malloc() error occurs, the journal-file is not deleted
 53704  ** and an error code is returned.
 53705  **
 53706  ** The isHot parameter indicates that we are trying to rollback a journal
 53707  ** that might be a hot journal.  Or, it could be that the journal is 
 53708  ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
 53709  ** If the journal really is hot, reset the pager cache prior rolling
 53710  ** back any content.  If the journal is merely persistent, no reset is
 53711  ** needed.
 53712  */
 53713  static int pager_playback(Pager *pPager, int isHot){
 53714    sqlite3_vfs *pVfs = pPager->pVfs;
 53715    i64 szJ;                 /* Size of the journal file in bytes */
 53716    u32 nRec;                /* Number of Records in the journal */
 53717    u32 u;                   /* Unsigned loop counter */
 53718    Pgno mxPg = 0;           /* Size of the original file in pages */
 53719    int rc;                  /* Result code of a subroutine */
 53720    int res = 1;             /* Value returned by sqlite3OsAccess() */
 53721    char *zMaster = 0;       /* Name of master journal file if any */
 53722    int needPagerReset;      /* True to reset page prior to first page rollback */
 53723    int nPlayback = 0;       /* Total number of pages restored from journal */
 53724    u32 savedPageSize = pPager->pageSize;
 53725  
 53726    BRANCHTRACE("pager_playback");
 53727  
 53728    /* Figure out how many records are in the journal.  Abort early if
 53729    ** the journal is empty.
 53730    */
 53731    assert( isOpen(pPager->jfd) );
 53732    rc = sqlite3OsFileSize(pPager->jfd, &szJ);
 53733    if( rc!=SQLITE_OK ){
 53734      goto end_playback;
 53735    }
 53736  
 53737    /* Read the master journal name from the journal, if it is present.
 53738    ** If a master journal file name is specified, but the file is not
 53739    ** present on disk, then the journal is not hot and does not need to be
 53740    ** played back.
 53741    **
 53742    ** TODO: Technically the following is an error because it assumes that
 53743    ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
 53744    ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
 53745    ** mxPathname is 512, which is the same as the minimum allowable value
 53746    ** for pageSize.
 53747    */
 53748    zMaster = pPager->pTmpSpace;
 53749    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 53750    if( rc==SQLITE_OK && zMaster[0] ){
 53751      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 53752    }
 53753    zMaster = 0;
 53754    if( rc!=SQLITE_OK || !res ){
 53755      goto end_playback;
 53756    }
 53757    pPager->journalOff = 0;
 53758    needPagerReset = isHot;
 53759  
 53760    /* This loop terminates either when a readJournalHdr() or 
 53761    ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
 53762    ** occurs. 
 53763    */
 53764    while( 1 ){
 53765      /* Read the next journal header from the journal file.  If there are
 53766      ** not enough bytes left in the journal file for a complete header, or
 53767      ** it is corrupted, then a process must have failed while writing it.
 53768      ** This indicates nothing more needs to be rolled back.
 53769      */
 53770      rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
 53771      if( rc!=SQLITE_OK ){ 
 53772        if( rc==SQLITE_DONE ){
 53773          rc = SQLITE_OK;
 53774        }
 53775        goto end_playback;
 53776      }
 53777  
 53778      /* If nRec is 0xffffffff, then this journal was created by a process
 53779      ** working in no-sync mode. This means that the rest of the journal
 53780      ** file consists of pages, there are no more journal headers. Compute
 53781      ** the value of nRec based on this assumption.
 53782      */
 53783      if( nRec==0xffffffff ){
 53784        assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
 53785        nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
 53786      }
 53787  
 53788      /* If nRec is 0 and this rollback is of a transaction created by this
 53789      ** process and if this is the final header in the journal, then it means
 53790      ** that this part of the journal was being filled but has not yet been
 53791      ** synced to disk.  Compute the number of pages based on the remaining
 53792      ** size of the file.
 53793      **
 53794      ** The third term of the test was added to fix ticket #2565.
 53795      ** When rolling back a hot journal, nRec==0 always means that the next
 53796      ** chunk of the journal contains zero pages to be rolled back.  But
 53797      ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
 53798      ** the journal, it means that the journal might contain additional
 53799      ** pages that need to be rolled back and that the number of pages 
 53800      ** should be computed based on the journal file size.
 53801      */
 53802      if( nRec==0 && !isHot &&
 53803          pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
 53804        nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
 53805      }
 53806  
 53807      /* If this is the first header read from the journal, truncate the
 53808      ** database file back to its original size.
 53809      */
 53810      if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
 53811        rc = pager_truncate(pPager, mxPg);
 53812        if( rc!=SQLITE_OK ){
 53813          goto end_playback;
 53814        }
 53815        pPager->dbSize = mxPg;
 53816      }
 53817  
 53818      /* Copy original pages out of the journal and back into the 
 53819      ** database file and/or page cache.
 53820      */
 53821      for(u=0; u<nRec; u++){
 53822        if( needPagerReset ){
 53823          pager_reset(pPager);
 53824          needPagerReset = 0;
 53825        }
 53826        rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
 53827        if( rc==SQLITE_OK ){
 53828          nPlayback++;
 53829        }else{
 53830          if( rc==SQLITE_DONE ){
 53831            pPager->journalOff = szJ;
 53832            break;
 53833          }else if( rc==SQLITE_IOERR_SHORT_READ ){
 53834            /* If the journal has been truncated, simply stop reading and
 53835            ** processing the journal. This might happen if the journal was
 53836            ** not completely written and synced prior to a crash.  In that
 53837            ** case, the database should have never been written in the
 53838            ** first place so it is OK to simply abandon the rollback. */
 53839            rc = SQLITE_OK;
 53840            goto end_playback;
 53841          }else{
 53842            /* If we are unable to rollback, quit and return the error
 53843            ** code.  This will cause the pager to enter the error state
 53844            ** so that no further harm will be done.  Perhaps the next
 53845            ** process to come along will be able to rollback the database.
 53846            */
 53847            goto end_playback;
 53848          }
 53849        }
 53850      }
 53851    }
 53852    /*NOTREACHED*/
 53853    assert( 0 );
 53854  
 53855  end_playback:
 53856    if( rc==SQLITE_OK ){
 53857      rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
 53858    }
 53859    /* Following a rollback, the database file should be back in its original
 53860    ** state prior to the start of the transaction, so invoke the
 53861    ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
 53862    ** assertion that the transaction counter was modified.
 53863    */
 53864  #ifdef SQLITE_DEBUG
 53865    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
 53866  #endif
 53867  
 53868    /* If this playback is happening automatically as a result of an IO or 
 53869    ** malloc error that occurred after the change-counter was updated but 
 53870    ** before the transaction was committed, then the change-counter 
 53871    ** modification may just have been reverted. If this happens in exclusive 
 53872    ** mode, then subsequent transactions performed by the connection will not
 53873    ** update the change-counter at all. This may lead to cache inconsistency
 53874    ** problems for other processes at some point in the future. So, just
 53875    ** in case this has happened, clear the changeCountDone flag now.
 53876    */
 53877    pPager->changeCountDone = pPager->tempFile;
 53878  
 53879    if( rc==SQLITE_OK ){
 53880      zMaster = pPager->pTmpSpace;
 53881      rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
 53882      testcase( rc!=SQLITE_OK );
 53883    }
 53884    if( rc==SQLITE_OK
 53885     && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
 53886    ){
 53887      rc = sqlite3PagerSync(pPager, 0);
 53888    }
 53889    if( rc==SQLITE_OK ){
 53890      rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
 53891      testcase( rc!=SQLITE_OK );
 53892    }
 53893    if( rc==SQLITE_OK && zMaster[0] && res ){
 53894      /* If there was a master journal and this routine will return success,
 53895      ** see if it is possible to delete the master journal.
 53896      */
 53897      rc = pager_delmaster(pPager, zMaster);
 53898      testcase( rc!=SQLITE_OK );
 53899    }
 53900    if( isHot && nPlayback ){
 53901      sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
 53902                  nPlayback, pPager->zJournal);
 53903    }
 53904  
 53905    /* The Pager.sectorSize variable may have been updated while rolling
 53906    ** back a journal created by a process with a different sector size
 53907    ** value. Reset it to the correct value for this process.
 53908    */
 53909    setSectorSize(pPager);
 53910    return rc;
 53911  }
 53912  
 53913  
 53914  /*
 53915  ** Read the content for page pPg out of the database file (or out of
 53916  ** the WAL if that is where the most recent copy if found) into 
 53917  ** pPg->pData. A shared lock or greater must be held on the database
 53918  ** file before this function is called.
 53919  **
 53920  ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
 53921  ** the value read from the database file.
 53922  **
 53923  ** If an IO error occurs, then the IO error is returned to the caller.
 53924  ** Otherwise, SQLITE_OK is returned.
 53925  */
 53926  static int readDbPage(PgHdr *pPg){
 53927    Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
 53928    int rc = SQLITE_OK;          /* Return code */
 53929  
 53930  #ifndef SQLITE_OMIT_WAL
 53931    u32 iFrame = 0;              /* Frame of WAL containing pgno */
 53932  
 53933    BRANCHTRACE("readDbPage pgno=%d pageSize=%d", pPg->pgno, pPager->pageSize);
 53934  
 53935    assert( pPager->eState>=PAGER_READER && !MEMDB );
 53936    assert( isOpen(pPager->fd) );
 53937  
 53938    if( pPager->useBranches ){
 53939      rc = sqlite3BranchReadPage(pPager->lmdb, pPg->pgno, pPager->pageSize, pPg->pData);
 53940      BRANCHTRACE("sqlite3BranchReadPage returned %d", rc);
 53941      if( rc ) return rc;
 53942    } else if( pagerUseWal(pPager) ){
 53943      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
 53944      if( rc ) return rc;
 53945    }
 53946    if( iFrame ){
 53947      rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
 53948    }else if(!pPager->useBranches)
 53949  #endif
 53950    {
 53951      i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
 53952      rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
 53953      if( rc==SQLITE_IOERR_SHORT_READ ){
 53954        rc = SQLITE_OK;
 53955      }
 53956    }
 53957  
 53958    if( pPg->pgno==1 ){
 53959      if( rc ){
 53960        /* If the read is unsuccessful, set the dbFileVers[] to something
 53961        ** that will never be a valid file version.  dbFileVers[] is a copy
 53962        ** of bytes 24..39 of the database.  Bytes 28..31 should always be
 53963        ** zero or the size of the database in page. Bytes 32..35 and 35..39
 53964        ** should be page numbers which are never 0xffffffff.  So filling
 53965        ** pPager->dbFileVers[] with all 0xff bytes should suffice.
 53966        **
 53967        ** For an encrypted database, the situation is more complex:  bytes
 53968        ** 24..39 of the database are white noise.  But the probability of
 53969        ** white noise equaling 16 bytes of 0xff is vanishingly small so
 53970        ** we should still be ok.
 53971        */
 53972        memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
 53973      }else{
 53974        u8 *dbFileVers = &((u8*)pPg->pData)[24];
 53975        memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
 53976      }
 53977    }
 53978    CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
 53979  
 53980    PAGER_INCR(sqlite3_pager_readdb_count);
 53981    PAGER_INCR(pPager->nRead);
 53982    IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
 53983    PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
 53984                 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
 53985  
 53986    return rc;
 53987  }
 53988  
 53989  /*
 53990  ** Update the value of the change-counter at offsets 24 and 92 in
 53991  ** the header and the sqlite version number at offset 96.
 53992  **
 53993  ** This is an unconditional update.  See also the pager_incr_changecounter()
 53994  ** routine which only updates the change-counter if the update is actually
 53995  ** needed, as determined by the pPager->changeCountDone state variable.
 53996  */
 53997  static void pager_write_changecounter(PgHdr *pPg){
 53998    u32 change_counter;
 53999  
 54000    /* Increment the value just read and write it back to byte 24. */
 54001    change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
 54002    put32bits(((char*)pPg->pData)+24, change_counter);
 54003  
 54004    /* Also store the SQLite version number in bytes 96..99 and in
 54005    ** bytes 92..95 store the change counter for which the version number
 54006    ** is valid. */
 54007    put32bits(((char*)pPg->pData)+92, change_counter);
 54008    put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
 54009  }
 54010  
 54011  #ifndef SQLITE_OMIT_WAL
 54012  /*
 54013  ** This function is invoked once for each page that has already been 
 54014  ** written into the log file when a WAL transaction is rolled back.
 54015  ** Parameter iPg is the page number of said page. The pCtx argument 
 54016  ** is actually a pointer to the Pager structure.
 54017  **
 54018  ** If page iPg is present in the cache, and has no outstanding references,
 54019  ** it is discarded. Otherwise, if there are one or more outstanding
 54020  ** references, the page content is reloaded from the database. If the
 54021  ** attempt to reload content from the database is required and fails, 
 54022  ** return an SQLite error code. Otherwise, SQLITE_OK.
 54023  */
 54024  static int pagerUndoCallback(void *pCtx, Pgno iPg){
 54025    int rc = SQLITE_OK;
 54026    Pager *pPager = (Pager *)pCtx;
 54027    PgHdr *pPg;
 54028  
 54029    assert( pagerUseWal(pPager) );
 54030    pPg = sqlite3PagerLookup(pPager, iPg);
 54031    if( pPg ){
 54032      if( sqlite3PcachePageRefcount(pPg)==1 ){
 54033        sqlite3PcacheDrop(pPg);
 54034      }else{
 54035        rc = readDbPage(pPg);
 54036        if( rc==SQLITE_OK ){
 54037          pPager->xReiniter(pPg);
 54038        }
 54039        sqlite3PagerUnrefNotNull(pPg);
 54040      }
 54041    }
 54042  
 54043    /* Normally, if a transaction is rolled back, any backup processes are
 54044    ** updated as data is copied out of the rollback journal and into the
 54045    ** database. This is not generally possible with a WAL database, as
 54046    ** rollback involves simply truncating the log file. Therefore, if one
 54047    ** or more frames have already been written to the log (and therefore 
 54048    ** also copied into the backup databases) as part of this transaction,
 54049    ** the backups must be restarted.
 54050    */
 54051    sqlite3BackupRestart(pPager->pBackup);
 54052  
 54053    return rc;
 54054  }
 54055  
 54056  /*
 54057  ** This function is called to rollback a transaction on a WAL database.
 54058  */
 54059  static int pagerRollbackWal(Pager *pPager){
 54060    int rc;                         /* Return Code */
 54061    PgHdr *pList;                   /* List of dirty pages to revert */
 54062  
 54063    BRANCHTRACE("pagerRollbackWal");
 54064  
 54065    /* For all pages in the cache that are currently dirty or have already
 54066    ** been written (but not committed) to the log file, do one of the 
 54067    ** following:
 54068    **
 54069    **   + Discard the cached page (if refcount==0), or
 54070    **   + Reload page content from the database (if refcount>0).
 54071    */
 54072    pPager->dbSize = pPager->dbOrigSize;
 54073    rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
 54074    pList = sqlite3PcacheDirtyList(pPager->pPCache);
 54075    while( pList && rc==SQLITE_OK ){
 54076      PgHdr *pNext = pList->pDirty;
 54077      rc = pagerUndoCallback((void *)pPager, pList->pgno);
 54078      pList = pNext;
 54079    }
 54080  
 54081    return rc;
 54082  }
 54083  
 54084  /*
 54085  ** This function is a wrapper around sqlite3WalFrames(). As well as logging
 54086  ** the contents of the list of pages headed by pList (connected by pDirty),
 54087  ** this function notifies any active backup processes that the pages have
 54088  ** changed. 
 54089  **
 54090  ** The list of pages passed into this routine is always sorted by page number.
 54091  ** Hence, if page 1 appears anywhere on the list, it will be the first page.
 54092  */ 
 54093  static int pagerWalFrames(
 54094    Pager *pPager,                  /* Pager object */
 54095    PgHdr *pList,                   /* List of frames to log */
 54096    Pgno nTruncate,                 /* Database size after this commit */
 54097    int isCommit                    /* True if this is a commit */
 54098  ){
 54099    int rc;                         /* Return code */
 54100    int nList;                      /* Number of pages in pList */
 54101    PgHdr *p;                       /* For looping over pages */
 54102  
 54103    BRANCHTRACE("pagerWalFrames");
 54104  
 54105    assert( pPager->pWal );
 54106    assert( pList );
 54107  #ifdef SQLITE_DEBUG
 54108    /* Verify that the page list is in accending order */
 54109    for(p=pList; p && p->pDirty; p=p->pDirty){
 54110      assert( p->pgno < p->pDirty->pgno );
 54111    }
 54112  #endif
 54113  
 54114    assert( pList->pDirty==0 || isCommit );
 54115    if( isCommit ){
 54116      /* If a WAL transaction is being committed, there is no point in writing
 54117      ** any pages with page numbers greater than nTruncate into the WAL file.
 54118      ** They will never be read by any client. So remove them from the pDirty
 54119      ** list here. */
 54120      PgHdr **ppNext = &pList;
 54121      nList = 0;
 54122      for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
 54123        if( p->pgno<=nTruncate ){
 54124          ppNext = &p->pDirty;
 54125          nList++;
 54126        }
 54127      }
 54128      assert( pList );
 54129    }else{
 54130      nList = 1;
 54131    }
 54132    pPager->aStat[PAGER_STAT_WRITE] += nList;
 54133  
 54134    if( pPager->useBranches ){
 54135      rc = sqlite3BranchWritePages(pPager->lmdb, pList, nTruncate, isCommit);
 54136      //if( rc==SQLITE_OK && isCommit ){
 54137      //  rc = sqlite3BranchCommitTransaction(pPager->lmdb, 1);
 54138      //}
 54139    } else {
 54140      if( pList->pgno==1 ) pager_write_changecounter(pList);
 54141      rc = sqlite3WalFrames(pPager->pWal, 
 54142          pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
 54143      );
 54144    }
 54145    if( rc==SQLITE_OK && pPager->pBackup ){
 54146      for(p=pList; p; p=p->pDirty){
 54147        sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
 54148      }
 54149    }
 54150  
 54151  #ifdef SQLITE_CHECK_PAGES
 54152    pList = sqlite3PcacheDirtyList(pPager->pPCache);
 54153    for(p=pList; p; p=p->pDirty){
 54154      pager_set_pagehash(p);
 54155    }
 54156  #endif
 54157  
 54158    return rc;
 54159  }
 54160  
 54161  /*
 54162  ** Begin a read transaction on the WAL.
 54163  **
 54164  ** This routine used to be called "pagerOpenSnapshot()" because it essentially
 54165  ** makes a snapshot of the database at the current point in time and preserves
 54166  ** that snapshot for use by the reader in spite of concurrently changes by
 54167  ** other writers or checkpointers.
 54168  */
 54169  static int pagerBeginReadTransaction(Pager *pPager){
 54170    int rc;                         /* Return code */
 54171    int changed = 0;                /* True if cache must be reset */
 54172  
 54173    BRANCHTRACE("pagerBeginReadTransaction");
 54174  
 54175    assert( pagerUseWal(pPager) );
 54176    assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 54177  
 54178    /* sqlite3WalEndReadTransaction() was not called for the previous
 54179    ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
 54180    ** are in locking_mode=NORMAL and EndRead() was previously called,
 54181    ** the duplicate call is harmless.
 54182    */
 54183    sqlite3WalEndReadTransaction(pPager->pWal);
 54184  
 54185    rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
 54186    if( rc!=SQLITE_OK || changed ){
 54187      pager_reset(pPager);
 54188      if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 54189    }
 54190  
 54191    return rc;
 54192  }
 54193  #endif
 54194  
 54195  /*
 54196  ** This function is called as part of the transition from PAGER_OPEN
 54197  ** to PAGER_READER state to determine the size of the database file
 54198  ** in pages (assuming the page size currently stored in Pager.pageSize).
 54199  **
 54200  ** If no error occurs, SQLITE_OK is returned and the size of the database
 54201  ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
 54202  ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
 54203  */
 54204  static int pagerPagecount(Pager *pPager, Pgno *pnPage){
 54205    Pgno nPage;                     /* Value to return via *pnPage */
 54206  
 54207    /* Query the WAL sub-system for the database size. The WalDbsize()
 54208    ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
 54209    ** if the database size is not available. The database size is not
 54210    ** available from the WAL sub-system if the log file is empty or
 54211    ** contains no valid committed transactions.
 54212    */
 54213    assert( pPager->eState==PAGER_OPEN );
 54214    assert( pPager->eLock>=SHARED_LOCK );
 54215    assert( isOpen(pPager->fd) );
 54216    assert( pPager->tempFile==0 );
 54217    nPage = sqlite3WalDbsize(pPager->pWal);
 54218  
 54219    /* If the number of pages in the database is not available from the
 54220    ** WAL sub-system, determine the page count based on the size of
 54221    ** the database file.  If the size of the database file is not an
 54222    ** integer multiple of the page-size, round up the result.
 54223    */
 54224    if( nPage==0 && ALWAYS(isOpen(pPager->fd)) && !pPager->useBranches ){
 54225      i64 n = 0;                    /* Size of db file in bytes */
 54226      int rc = sqlite3OsFileSize(pPager->fd, &n);
 54227      if( rc!=SQLITE_OK ){
 54228        return rc;
 54229      }
 54230      nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
 54231    }
 54232  
 54233    BRANCHTRACE("pagerPagecount returning %d", nPage);
 54234  
 54235    /* If the current number of pages in the file is greater than the
 54236    ** configured maximum pager number, increase the allowed limit so
 54237    ** that the file can be read.
 54238    */
 54239    if( nPage>pPager->mxPgno ){
 54240      pPager->mxPgno = (Pgno)nPage;
 54241    }
 54242  
 54243    *pnPage = nPage;
 54244    return SQLITE_OK;
 54245  }
 54246  
 54247  #ifndef SQLITE_OMIT_WAL
 54248  /*
 54249  ** Check if the *-wal file that corresponds to the database opened by pPager
 54250  ** exists if the database is not empy, or verify that the *-wal file does
 54251  ** not exist (by deleting it) if the database file is empty.
 54252  **
 54253  ** If the database is not empty and the *-wal file exists, open the pager
 54254  ** in WAL mode.  If the database is empty or if no *-wal file exists and
 54255  ** if no error occurs, make sure Pager.journalMode is not set to
 54256  ** PAGER_JOURNALMODE_WAL.
 54257  **
 54258  ** Return SQLITE_OK or an error code.
 54259  **
 54260  ** The caller must hold a SHARED lock on the database file to call this
 54261  ** function. Because an EXCLUSIVE lock on the db file is required to delete 
 54262  ** a WAL on a none-empty database, this ensures there is no race condition 
 54263  ** between the xAccess() below and an xDelete() being executed by some 
 54264  ** other connection.
 54265  */
 54266  static int pagerOpenWalIfPresent(Pager *pPager){
 54267    int rc = SQLITE_OK;
 54268    assert( pPager->eState==PAGER_OPEN );
 54269    assert( pPager->eLock>=SHARED_LOCK );
 54270  
 54271    BRANCHTRACE("pagerOpenWalIfPresent");
 54272  
 54273    if( !pPager->tempFile ){
 54274      int isWal;                    /* True if WAL file exists */
 54275      rc = sqlite3OsAccess(
 54276          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
 54277      );
 54278      if( rc==SQLITE_OK ){
 54279        if( isWal ){
 54280          Pgno nPage;                   /* Size of the database file */
 54281  
 54282          rc = pagerPagecount(pPager, &nPage);
 54283          if( rc ) return rc;
 54284          if( nPage==0 ){
 54285            rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
 54286          }else{
 54287            testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
 54288            rc = sqlite3PagerOpenWal(pPager, 0);
 54289          }
 54290        }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
 54291          pPager->journalMode = PAGER_JOURNALMODE_DELETE;
 54292        }
 54293      }
 54294    }
 54295    return rc;
 54296  }
 54297  #endif
 54298  
 54299  /*
 54300  ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
 54301  ** the entire master journal file. The case pSavepoint==NULL occurs when 
 54302  ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
 54303  ** savepoint.
 54304  **
 54305  ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
 54306  ** being rolled back), then the rollback consists of up to three stages,
 54307  ** performed in the order specified:
 54308  **
 54309  **   * Pages are played back from the main journal starting at byte
 54310  **     offset PagerSavepoint.iOffset and continuing to 
 54311  **     PagerSavepoint.iHdrOffset, or to the end of the main journal
 54312  **     file if PagerSavepoint.iHdrOffset is zero.
 54313  **
 54314  **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
 54315  **     back starting from the journal header immediately following 
 54316  **     PagerSavepoint.iHdrOffset to the end of the main journal file.
 54317  **
 54318  **   * Pages are then played back from the sub-journal file, starting
 54319  **     with the PagerSavepoint.iSubRec and continuing to the end of
 54320  **     the journal file.
 54321  **
 54322  ** Throughout the rollback process, each time a page is rolled back, the
 54323  ** corresponding bit is set in a bitvec structure (variable pDone in the
 54324  ** implementation below). This is used to ensure that a page is only
 54325  ** rolled back the first time it is encountered in either journal.
 54326  **
 54327  ** If pSavepoint is NULL, then pages are only played back from the main
 54328  ** journal file. There is no need for a bitvec in this case.
 54329  **
 54330  ** In either case, before playback commences the Pager.dbSize variable
 54331  ** is reset to the value that it held at the start of the savepoint 
 54332  ** (or transaction). No page with a page-number greater than this value
 54333  ** is played back. If one is encountered it is simply skipped.
 54334  */
 54335  static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
 54336    i64 szJ;                 /* Effective size of the main journal */
 54337    i64 iHdrOff;             /* End of first segment of main-journal records */
 54338    int rc = SQLITE_OK;      /* Return code */
 54339    Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
 54340  
 54341    assert( pPager->eState!=PAGER_ERROR );
 54342    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 54343  
 54344    /* Allocate a bitvec to use to store the set of pages rolled back */
 54345    if( pSavepoint ){
 54346      pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
 54347      if( !pDone ){
 54348        return SQLITE_NOMEM_BKPT;
 54349      }
 54350    }
 54351  
 54352    /* Set the database size back to the value it was before the savepoint 
 54353    ** being reverted was opened.
 54354    */
 54355    pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
 54356    pPager->changeCountDone = pPager->tempFile;
 54357  
 54358    if( !pSavepoint && pagerUseWal(pPager) ){
 54359      return pagerRollbackWal(pPager);
 54360    }
 54361  
 54362    /* Use pPager->journalOff as the effective size of the main rollback
 54363    ** journal.  The actual file might be larger than this in
 54364    ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
 54365    ** past pPager->journalOff is off-limits to us.
 54366    */
 54367    szJ = pPager->journalOff;
 54368    assert( pagerUseWal(pPager)==0 || szJ==0 );
 54369  
 54370    /* Begin by rolling back records from the main journal starting at
 54371    ** PagerSavepoint.iOffset and continuing to the next journal header.
 54372    ** There might be records in the main journal that have a page number
 54373    ** greater than the current database size (pPager->dbSize) but those
 54374    ** will be skipped automatically.  Pages are added to pDone as they
 54375    ** are played back.
 54376    */
 54377    if( pSavepoint && !pagerUseWal(pPager) ){
 54378      iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
 54379      pPager->journalOff = pSavepoint->iOffset;
 54380      while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
 54381        rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 54382      }
 54383      assert( rc!=SQLITE_DONE );
 54384    }else{
 54385      pPager->journalOff = 0;
 54386    }
 54387  
 54388    /* Continue rolling back records out of the main journal starting at
 54389    ** the first journal header seen and continuing until the effective end
 54390    ** of the main journal file.  Continue to skip out-of-range pages and
 54391    ** continue adding pages rolled back to pDone.
 54392    */
 54393    while( rc==SQLITE_OK && pPager->journalOff<szJ ){
 54394      u32 ii;            /* Loop counter */
 54395      u32 nJRec = 0;     /* Number of Journal Records */
 54396      u32 dummy;
 54397      rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
 54398      assert( rc!=SQLITE_DONE );
 54399  
 54400      /*
 54401      ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
 54402      ** test is related to ticket #2565.  See the discussion in the
 54403      ** pager_playback() function for additional information.
 54404      */
 54405      if( nJRec==0 
 54406       && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
 54407      ){
 54408        nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
 54409      }
 54410      for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
 54411        rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
 54412      }
 54413      assert( rc!=SQLITE_DONE );
 54414    }
 54415    assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
 54416  
 54417    /* Finally,  rollback pages from the sub-journal.  Page that were
 54418    ** previously rolled back out of the main journal (and are hence in pDone)
 54419    ** will be skipped.  Out-of-range pages are also skipped.
 54420    */
 54421    if( pSavepoint ){
 54422      u32 ii;            /* Loop counter */
 54423      i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
 54424  
 54425      if( pagerUseWal(pPager) ){
 54426        rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
 54427      }
 54428      for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
 54429        assert( offset==(i64)ii*(4+pPager->pageSize) );
 54430        rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
 54431      }
 54432      assert( rc!=SQLITE_DONE );
 54433    }
 54434  
 54435    sqlite3BitvecDestroy(pDone);
 54436    if( rc==SQLITE_OK ){
 54437      pPager->journalOff = szJ;
 54438    }
 54439  
 54440    return rc;
 54441  }
 54442  
 54443  /*
 54444  ** Change the maximum number of in-memory pages that are allowed
 54445  ** before attempting to recycle clean and unused pages.
 54446  */
 54447  SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
 54448    sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
 54449  }
 54450  
 54451  /*
 54452  ** Change the maximum number of in-memory pages that are allowed
 54453  ** before attempting to spill pages to journal.
 54454  */
 54455  SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
 54456    return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
 54457  }
 54458  
 54459  /*
 54460  ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
 54461  */
 54462  static void pagerFixMaplimit(Pager *pPager){
 54463  #if SQLITE_MAX_MMAP_SIZE>0
 54464    sqlite3_file *fd = pPager->fd;
 54465    if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
 54466      sqlite3_int64 sz;
 54467      sz = pPager->szMmap;
 54468      pPager->bUseFetch = (sz>0);
 54469      setGetterMethod(pPager);
 54470      sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
 54471    }
 54472  #endif
 54473  }
 54474  
 54475  /*
 54476  ** Change the maximum size of any memory mapping made of the database file.
 54477  */
 54478  SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
 54479    pPager->szMmap = szMmap;
 54480    pagerFixMaplimit(pPager);
 54481  }
 54482  
 54483  /*
 54484  ** Free as much memory as possible from the pager.
 54485  */
 54486  SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
 54487    sqlite3PcacheShrink(pPager->pPCache);
 54488  }
 54489  
 54490  /*
 54491  ** Adjust settings of the pager to those specified in the pgFlags parameter.
 54492  **
 54493  ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
 54494  ** of the database to damage due to OS crashes or power failures by
 54495  ** changing the number of syncs()s when writing the journals.
 54496  ** There are four levels:
 54497  **
 54498  **    OFF       sqlite3OsSync() is never called.  This is the default
 54499  **              for temporary and transient files.
 54500  **
 54501  **    NORMAL    The journal is synced once before writes begin on the
 54502  **              database.  This is normally adequate protection, but
 54503  **              it is theoretically possible, though very unlikely,
 54504  **              that an inopertune power failure could leave the journal
 54505  **              in a state which would cause damage to the database
 54506  **              when it is rolled back.
 54507  **
 54508  **    FULL      The journal is synced twice before writes begin on the
 54509  **              database (with some additional information - the nRec field
 54510  **              of the journal header - being written in between the two
 54511  **              syncs).  If we assume that writing a
 54512  **              single disk sector is atomic, then this mode provides
 54513  **              assurance that the journal will not be corrupted to the
 54514  **              point of causing damage to the database during rollback.
 54515  **
 54516  **    EXTRA     This is like FULL except that is also syncs the directory
 54517  **              that contains the rollback journal after the rollback
 54518  **              journal is unlinked.
 54519  **
 54520  ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
 54521  ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
 54522  ** prior to the start of checkpoint and that the database file is synced
 54523  ** at the conclusion of the checkpoint if the entire content of the WAL
 54524  ** was written back into the database.  But no sync operations occur for
 54525  ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
 54526  ** file is synced following each commit operation, in addition to the
 54527  ** syncs associated with NORMAL.  There is no difference between FULL
 54528  ** and EXTRA for WAL mode.
 54529  **
 54530  ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
 54531  ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
 54532  ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
 54533  ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
 54534  ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
 54535  ** synchronous=FULL versus synchronous=NORMAL setting determines when
 54536  ** the xSync primitive is called and is relevant to all platforms.
 54537  **
 54538  ** Numeric values associated with these states are OFF==1, NORMAL=2,
 54539  ** and FULL=3.
 54540  */
 54541  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 54542  SQLITE_PRIVATE void sqlite3PagerSetFlags(
 54543    Pager *pPager,        /* The pager to set safety level for */
 54544    unsigned pgFlags      /* Various flags */
 54545  ){
 54546    unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
 54547    if( pPager->tempFile ){
 54548      pPager->noSync = 1;
 54549      pPager->fullSync = 0;
 54550      pPager->extraSync = 0;
 54551    }else{
 54552      pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
 54553      pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
 54554      pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
 54555    }
 54556    if( pPager->noSync ){
 54557      pPager->syncFlags = 0;
 54558    }else if( pgFlags & PAGER_FULLFSYNC ){
 54559      pPager->syncFlags = SQLITE_SYNC_FULL;
 54560    }else{
 54561      pPager->syncFlags = SQLITE_SYNC_NORMAL;
 54562    }
 54563    pPager->walSyncFlags = (pPager->syncFlags<<2);
 54564    if( pPager->fullSync ){
 54565      pPager->walSyncFlags |= pPager->syncFlags;
 54566    }
 54567    if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
 54568      pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
 54569    }
 54570    if( pgFlags & PAGER_CACHESPILL ){
 54571      pPager->doNotSpill &= ~SPILLFLAG_OFF;
 54572    }else{
 54573      pPager->doNotSpill |= SPILLFLAG_OFF;
 54574    }
 54575  }
 54576  #endif
 54577  
 54578  /*
 54579  ** The following global variable is incremented whenever the library
 54580  ** attempts to open a temporary file.  This information is used for
 54581  ** testing and analysis only.  
 54582  */
 54583  #ifdef SQLITE_TEST
 54584  SQLITE_API int sqlite3_opentemp_count = 0;
 54585  #endif
 54586  
 54587  /*
 54588  ** Open a temporary file.
 54589  **
 54590  ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
 54591  ** or some other error code if we fail. The OS will automatically 
 54592  ** delete the temporary file when it is closed.
 54593  **
 54594  ** The flags passed to the VFS layer xOpen() call are those specified
 54595  ** by parameter vfsFlags ORed with the following:
 54596  **
 54597  **     SQLITE_OPEN_READWRITE
 54598  **     SQLITE_OPEN_CREATE
 54599  **     SQLITE_OPEN_EXCLUSIVE
 54600  **     SQLITE_OPEN_DELETEONCLOSE
 54601  */
 54602  static int pagerOpentemp(
 54603    Pager *pPager,        /* The pager object */
 54604    sqlite3_file *pFile,  /* Write the file descriptor here */
 54605    int vfsFlags          /* Flags passed through to the VFS */
 54606  ){
 54607    int rc;               /* Return code */
 54608  
 54609  #ifdef SQLITE_TEST
 54610    sqlite3_opentemp_count++;  /* Used for testing and analysis only */
 54611  #endif
 54612  
 54613    vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
 54614              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
 54615    rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
 54616    assert( rc!=SQLITE_OK || isOpen(pFile) );
 54617    return rc;
 54618  }
 54619  
 54620  /*
 54621  ** Set the busy handler function.
 54622  **
 54623  ** The pager invokes the busy-handler if sqlite3OsLock() returns 
 54624  ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
 54625  ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
 54626  ** lock. It does *not* invoke the busy handler when upgrading from
 54627  ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
 54628  ** (which occurs during hot-journal rollback). Summary:
 54629  **
 54630  **   Transition                        | Invokes xBusyHandler
 54631  **   --------------------------------------------------------
 54632  **   NO_LOCK       -> SHARED_LOCK      | Yes
 54633  **   SHARED_LOCK   -> RESERVED_LOCK    | No
 54634  **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
 54635  **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
 54636  **
 54637  ** If the busy-handler callback returns non-zero, the lock is 
 54638  ** retried. If it returns zero, then the SQLITE_BUSY error is
 54639  ** returned to the caller of the pager API function.
 54640  */
 54641  SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
 54642    Pager *pPager,                       /* Pager object */
 54643    int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
 54644    void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
 54645  ){
 54646    void **ap;
 54647    pPager->xBusyHandler = xBusyHandler;
 54648    pPager->pBusyHandlerArg = pBusyHandlerArg;
 54649    ap = (void **)&pPager->xBusyHandler;
 54650    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
 54651    assert( ap[1]==pBusyHandlerArg );
 54652    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
 54653  }
 54654  
 54655  /*
 54656  ** Change the page size used by the Pager object. The new page size 
 54657  ** is passed in *pPageSize.
 54658  **
 54659  ** If the pager is in the error state when this function is called, it
 54660  ** is a no-op. The value returned is the error state error code (i.e. 
 54661  ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
 54662  **
 54663  ** Otherwise, if all of the following are true:
 54664  **
 54665  **   * the new page size (value of *pPageSize) is valid (a power 
 54666  **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
 54667  **
 54668  **   * there are no outstanding page references, and
 54669  **
 54670  **   * the database is either not an in-memory database or it is
 54671  **     an in-memory database that currently consists of zero pages.
 54672  **
 54673  ** then the pager object page size is set to *pPageSize.
 54674  **
 54675  ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
 54676  ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
 54677  ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
 54678  ** In all other cases, SQLITE_OK is returned.
 54679  **
 54680  ** If the page size is not changed, either because one of the enumerated
 54681  ** conditions above is not true, the pager was in error state when this
 54682  ** function was called, or because the memory allocation attempt failed, 
 54683  ** then *pPageSize is set to the old, retained page size before returning.
 54684  */
 54685  SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
 54686    int rc = SQLITE_OK;
 54687  
 54688    /* It is not possible to do a full assert_pager_state() here, as this
 54689    ** function may be called from within PagerOpen(), before the state
 54690    ** of the Pager object is internally consistent.
 54691    **
 54692    ** At one point this function returned an error if the pager was in 
 54693    ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
 54694    ** there is at least one outstanding page reference, this function
 54695    ** is a no-op for that case anyhow.
 54696    */
 54697  
 54698    u32 pageSize = *pPageSize;
 54699    BRANCHTRACE("sqlite3PagerSetPagesize = %d  nReserve=%d", pageSize, nReserve);
 54700    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
 54701    if( (pPager->memDb==0 || pPager->dbSize==0)
 54702     && sqlite3PcacheRefCount(pPager->pPCache)==0 
 54703     && pageSize && pageSize!=(u32)pPager->pageSize 
 54704    ){
 54705      char *pNew = NULL;             /* New temp space */
 54706      i64 nByte = 0;
 54707  
 54708      if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
 54709        rc = sqlite3OsFileSize(pPager->fd, &nByte);
 54710      }
 54711      if( rc==SQLITE_OK ){
 54712        pNew = (char *)sqlite3PageMalloc(pageSize);
 54713        if( !pNew ) rc = SQLITE_NOMEM_BKPT;
 54714      }
 54715  
 54716      if( rc==SQLITE_OK ){
 54717        pager_reset(pPager);
 54718        rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
 54719      }
 54720      if( rc==SQLITE_OK ){
 54721        sqlite3PageFree(pPager->pTmpSpace);
 54722        pPager->pTmpSpace = pNew;
 54723        pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
 54724        pPager->pageSize = pageSize;
 54725      }else{
 54726        sqlite3PageFree(pNew);
 54727      }
 54728    }
 54729  
 54730    *pPageSize = pPager->pageSize;
 54731    if( rc==SQLITE_OK ){
 54732      if( nReserve<0 ) nReserve = pPager->nReserve;
 54733      assert( nReserve>=0 && nReserve<1000 );
 54734      pPager->nReserve = (i16)nReserve;
 54735      pagerReportSize(pPager);
 54736      pagerFixMaplimit(pPager);
 54737    }
 54738    return rc;
 54739  }
 54740  
 54741  /*
 54742  ** Return a pointer to the "temporary page" buffer held internally
 54743  ** by the pager.  This is a buffer that is big enough to hold the
 54744  ** entire content of a database page.  This buffer is used internally
 54745  ** during rollback and will be overwritten whenever a rollback
 54746  ** occurs.  But other modules are free to use it too, as long as
 54747  ** no rollbacks are happening.
 54748  */
 54749  SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
 54750    return pPager->pTmpSpace;
 54751  }
 54752  
 54753  /*
 54754  ** Attempt to set the maximum database page count if mxPage is positive. 
 54755  ** Make no changes if mxPage is zero or negative.  And never reduce the
 54756  ** maximum page count below the current size of the database.
 54757  **
 54758  ** Regardless of mxPage, return the current maximum page count.
 54759  */
 54760  SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
 54761    if( mxPage>0 ){
 54762      pPager->mxPgno = mxPage;
 54763    }
 54764    assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
 54765    /* assert( pPager->mxPgno>=pPager->dbSize ); */
 54766    /* OP_MaxPgcnt ensures that the parameter passed to this function is not
 54767    ** less than the total number of valid pages in the database. But this
 54768    ** may be less than Pager.dbSize, and so the assert() above is not valid */
 54769    return pPager->mxPgno;
 54770  }
 54771  
 54772  /*
 54773  ** The following set of routines are used to disable the simulated
 54774  ** I/O error mechanism.  These routines are used to avoid simulated
 54775  ** errors in places where we do not care about errors.
 54776  **
 54777  ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
 54778  ** and generate no code.
 54779  */
 54780  #ifdef SQLITE_TEST
 54781  SQLITE_API extern int sqlite3_io_error_pending;
 54782  SQLITE_API extern int sqlite3_io_error_hit;
 54783  static int saved_cnt;
 54784  void disable_simulated_io_errors(void){
 54785    saved_cnt = sqlite3_io_error_pending;
 54786    sqlite3_io_error_pending = -1;
 54787  }
 54788  void enable_simulated_io_errors(void){
 54789    sqlite3_io_error_pending = saved_cnt;
 54790  }
 54791  #else
 54792  # define disable_simulated_io_errors()
 54793  # define enable_simulated_io_errors()
 54794  #endif
 54795  
 54796  /*
 54797  ** Read the first N bytes from the beginning of the file into memory
 54798  ** that pDest points to. 
 54799  **
 54800  ** If the pager was opened on a transient file (zFilename==""), or
 54801  ** opened on a file less than N bytes in size, the output buffer is
 54802  ** zeroed and SQLITE_OK returned. The rationale for this is that this 
 54803  ** function is used to read database headers, and a new transient or
 54804  ** zero sized database has a header than consists entirely of zeroes.
 54805  **
 54806  ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
 54807  ** the error code is returned to the caller and the contents of the
 54808  ** output buffer undefined.
 54809  */
 54810  SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
 54811    int rc = SQLITE_OK;
 54812    memset(pDest, 0, N);
 54813    assert( isOpen(pPager->fd) || pPager->tempFile || pPager->useBranches );
 54814  
 54815    /* This routine is only called by btree immediately after creating
 54816    ** the Pager object.  There has not been an opportunity to transition
 54817    ** to WAL mode yet.
 54818    */
 54819    assert( !pagerUseWal(pPager) || pPager->useBranches );
 54820  
 54821    BRANCHTRACE("sqlite3PagerReadFileheader");
 54822  
 54823    if( pPager->useBranches ){
 54824  #if 1
 54825      u8 *pData;
 54826      rc = sqlite3BranchInit(pPager);
 54827      sqlite3BranchBeginReadTransaction(pPager->lmdb, 1, NULL);
 54828      if( rc==SQLITE_OK ){
 54829        rc = sqlite3BranchGetPage(pPager->lmdb, 1, &pData);
 54830      }
 54831      if( rc==SQLITE_OK ){
 54832        memcpy(pDest, pData, N);
 54833      } else if( rc==SQLITE_NOTFOUND ){
 54834        rc = SQLITE_OK;  // SQLITE_IOERR_SHORT_READ;
 54835      }
 54836      sqlite3BranchEndReadTransaction(pPager->lmdb);
 54837  #else
 54838      strcpy((char*)pDest, "SQLite format 3");
 54839      pDest[16] = ((SQLITE_DEFAULT_PAGE_SIZE >> 8) & 255);
 54840      pDest[17] = SQLITE_DEFAULT_PAGE_SIZE & 255;
 54841      pDest[18] = 2;
 54842      pDest[19] = 2;
 54843      pDest[20] = LMDB_PAGE_RESERVED_SPACE;
 54844      pDest[21] = 64;
 54845      pDest[22] = 32;
 54846      pDest[23] = 32;
 54847      pDest[27] = 1;
 54848      *((u32*)&pDest[28]) = htonl(pPager->branch->max_page);
 54849      pDest[95] = 1;
 54850      *((u32*)&pDest[96]) = htonl(SQLITE_VERSION_NUMBER);
 54851  #endif
 54852    } else if( isOpen(pPager->fd) ){
 54853      IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
 54854      rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
 54855      if( rc==SQLITE_IOERR_SHORT_READ ){
 54856        rc = SQLITE_OK;
 54857      }
 54858    }
 54859    return rc;
 54860  }
 54861  
 54862  /*
 54863  ** This function may only be called when a read-transaction is open on
 54864  ** the pager. It returns the total number of pages in the database.
 54865  **
 54866  ** However, if the file is between 1 and <page-size> bytes in size, then 
 54867  ** this is considered a 1 page file.
 54868  */
 54869  SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
 54870    assert( pPager->eState>=PAGER_READER );
 54871    assert( pPager->eState!=PAGER_WRITER_FINISHED );
 54872    *pnPage = (int)pPager->dbSize;
 54873  }
 54874  
 54875  
 54876  /*
 54877  ** Try to obtain a lock of type locktype on the database file. If
 54878  ** a similar or greater lock is already held, this function is a no-op
 54879  ** (returning SQLITE_OK immediately).
 54880  **
 54881  ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
 54882  ** the busy callback if the lock is currently not available. Repeat 
 54883  ** until the busy callback returns false or until the attempt to 
 54884  ** obtain the lock succeeds.
 54885  **
 54886  ** Return SQLITE_OK on success and an error code if we cannot obtain
 54887  ** the lock. If the lock is obtained successfully, set the Pager.state 
 54888  ** variable to locktype before returning.
 54889  */
 54890  static int pager_wait_on_lock(Pager *pPager, int locktype){
 54891    int rc;                              /* Return code */
 54892  
 54893    /* Check that this is either a no-op (because the requested lock is 
 54894    ** already held), or one of the transitions that the busy-handler
 54895    ** may be invoked during, according to the comment above
 54896    ** sqlite3PagerSetBusyhandler().
 54897    */
 54898    assert( (pPager->eLock>=locktype)
 54899         || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
 54900         || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
 54901    );
 54902  
 54903    do {
 54904      rc = pagerLockDb(pPager, locktype);
 54905    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
 54906    return rc;
 54907  }
 54908  
 54909  /*
 54910  ** Function assertTruncateConstraint(pPager) checks that one of the 
 54911  ** following is true for all dirty pages currently in the page-cache:
 54912  **
 54913  **   a) The page number is less than or equal to the size of the 
 54914  **      current database image, in pages, OR
 54915  **
 54916  **   b) if the page content were written at this time, it would not
 54917  **      be necessary to write the current content out to the sub-journal
 54918  **      (as determined by function subjRequiresPage()).
 54919  **
 54920  ** If the condition asserted by this function were not true, and the
 54921  ** dirty page were to be discarded from the cache via the pagerStress()
 54922  ** routine, pagerStress() would not write the current page content to
 54923  ** the database file. If a savepoint transaction were rolled back after
 54924  ** this happened, the correct behavior would be to restore the current
 54925  ** content of the page. However, since this content is not present in either
 54926  ** the database file or the portion of the rollback journal and 
 54927  ** sub-journal rolled back the content could not be restored and the
 54928  ** database image would become corrupt. It is therefore fortunate that 
 54929  ** this circumstance cannot arise.
 54930  */
 54931  #if defined(SQLITE_DEBUG)
 54932  static void assertTruncateConstraintCb(PgHdr *pPg){
 54933    assert( pPg->flags&PGHDR_DIRTY );
 54934    assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
 54935  }
 54936  static void assertTruncateConstraint(Pager *pPager){
 54937    sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
 54938  }
 54939  #else
 54940  # define assertTruncateConstraint(pPager)
 54941  #endif
 54942  
 54943  /*
 54944  ** Truncate the in-memory database file image to nPage pages. This 
 54945  ** function does not actually modify the database file on disk. It 
 54946  ** just sets the internal state of the pager object so that the 
 54947  ** truncation will be done when the current transaction is committed.
 54948  **
 54949  ** This function is only called right before committing a transaction.
 54950  ** Once this function has been called, the transaction must either be
 54951  ** rolled back or committed. It is not safe to call this function and
 54952  ** then continue writing to the database.
 54953  */
 54954  SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
 54955    assert( pPager->dbSize>=nPage );
 54956    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 54957    pPager->dbSize = nPage;
 54958  
 54959    /* At one point the code here called assertTruncateConstraint() to
 54960    ** ensure that all pages being truncated away by this operation are,
 54961    ** if one or more savepoints are open, present in the savepoint 
 54962    ** journal so that they can be restored if the savepoint is rolled
 54963    ** back. This is no longer necessary as this function is now only
 54964    ** called right before committing a transaction. So although the 
 54965    ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
 54966    ** they cannot be rolled back. So the assertTruncateConstraint() call
 54967    ** is no longer correct. */
 54968  }
 54969  
 54970  
 54971  /*
 54972  ** This function is called before attempting a hot-journal rollback. It
 54973  ** syncs the journal file to disk, then sets pPager->journalHdr to the
 54974  ** size of the journal file so that the pager_playback() routine knows
 54975  ** that the entire journal file has been synced.
 54976  **
 54977  ** Syncing a hot-journal to disk before attempting to roll it back ensures 
 54978  ** that if a power-failure occurs during the rollback, the process that
 54979  ** attempts rollback following system recovery sees the same journal
 54980  ** content as this process.
 54981  **
 54982  ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
 54983  ** an SQLite error code.
 54984  */
 54985  static int pagerSyncHotJournal(Pager *pPager){
 54986    int rc = SQLITE_OK;
 54987    if( !pPager->noSync ){
 54988      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
 54989    }
 54990    if( rc==SQLITE_OK ){
 54991      rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
 54992    }
 54993    return rc;
 54994  }
 54995  
 54996  #if SQLITE_MAX_MMAP_SIZE>0
 54997  /*
 54998  ** Obtain a reference to a memory mapped page object for page number pgno. 
 54999  ** The new object will use the pointer pData, obtained from xFetch().
 55000  ** If successful, set *ppPage to point to the new page reference
 55001  ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
 55002  ** *ppPage to zero.
 55003  **
 55004  ** Page references obtained by calling this function should be released
 55005  ** by calling pagerReleaseMapPage().
 55006  */
 55007  static int pagerAcquireMapPage(
 55008    Pager *pPager,                  /* Pager object */
 55009    Pgno pgno,                      /* Page number */
 55010    void *pData,                    /* xFetch()'d data for this page */
 55011    PgHdr **ppPage                  /* OUT: Acquired page object */
 55012  ){
 55013    PgHdr *p;                       /* Memory mapped page to return */
 55014    
 55015    if( pPager->pMmapFreelist ){
 55016      *ppPage = p = pPager->pMmapFreelist;
 55017      pPager->pMmapFreelist = p->pDirty;
 55018      p->pDirty = 0;
 55019      assert( pPager->nExtra>=8 );
 55020      memset(p->pExtra, 0, 8);
 55021    }else{
 55022      *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
 55023      if( p==0 ){
 55024        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
 55025        return SQLITE_NOMEM_BKPT;
 55026      }
 55027      p->pExtra = (void *)&p[1];
 55028      p->flags = PGHDR_MMAP;
 55029      p->nRef = 1;
 55030      p->pPager = pPager;
 55031    }
 55032  
 55033    assert( p->pExtra==(void *)&p[1] );
 55034    assert( p->pPage==0 );
 55035    assert( p->flags==PGHDR_MMAP );
 55036    assert( p->pPager==pPager );
 55037    assert( p->nRef==1 );
 55038  
 55039    p->pgno = pgno;
 55040    p->pData = pData;
 55041    pPager->nMmapOut++;
 55042  
 55043    return SQLITE_OK;
 55044  }
 55045  #endif
 55046  
 55047  /*
 55048  ** Release a reference to page pPg. pPg must have been returned by an 
 55049  ** earlier call to pagerAcquireMapPage().
 55050  */
 55051  static void pagerReleaseMapPage(PgHdr *pPg){
 55052    Pager *pPager = pPg->pPager;
 55053    pPager->nMmapOut--;
 55054    pPg->pDirty = pPager->pMmapFreelist;
 55055    pPager->pMmapFreelist = pPg;
 55056  
 55057    assert( pPager->fd->pMethods->iVersion>=3 );
 55058    sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
 55059  }
 55060  
 55061  /*
 55062  ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
 55063  */
 55064  static void pagerFreeMapHdrs(Pager *pPager){
 55065    PgHdr *p;
 55066    PgHdr *pNext;
 55067    for(p=pPager->pMmapFreelist; p; p=pNext){
 55068      pNext = p->pDirty;
 55069      sqlite3_free(p);
 55070    }
 55071  }
 55072  
 55073  /* Verify that the database file has not be deleted or renamed out from
 55074  ** under the pager.  Return SQLITE_OK if the database is still where it ought
 55075  ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
 55076  ** code from sqlite3OsAccess()) if the database has gone missing.
 55077  */
 55078  static int databaseIsUnmoved(Pager *pPager){
 55079    int bHasMoved = 0;
 55080    int rc;
 55081  
 55082    if( pPager->tempFile ) return SQLITE_OK;
 55083    if( pPager->dbSize==0 ) return SQLITE_OK;
 55084    assert( pPager->zFilename && pPager->zFilename[0] );
 55085    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
 55086    if( rc==SQLITE_NOTFOUND ){
 55087      /* If the HAS_MOVED file-control is unimplemented, assume that the file
 55088      ** has not been moved.  That is the historical behavior of SQLite: prior to
 55089      ** version 3.8.3, it never checked */
 55090      rc = SQLITE_OK;
 55091    }else if( rc==SQLITE_OK && bHasMoved ){
 55092      rc = SQLITE_READONLY_DBMOVED;
 55093    }
 55094    return rc;
 55095  }
 55096  
 55097  
 55098  /*
 55099  ** Shutdown the page cache.  Free all memory and close all files.
 55100  **
 55101  ** If a transaction was in progress when this routine is called, that
 55102  ** transaction is rolled back.  All outstanding pages are invalidated
 55103  ** and their memory is freed.  Any attempt to use a page associated
 55104  ** with this page cache after this function returns will likely
 55105  ** result in a coredump.
 55106  **
 55107  ** This function always succeeds. If a transaction is active an attempt
 55108  ** is made to roll it back. If an error occurs during the rollback 
 55109  ** a hot journal may be left in the filesystem but no error is returned
 55110  ** to the caller.
 55111  */
 55112  SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
 55113    u8 *pTmp = (u8*)pPager->pTmpSpace;
 55114    assert( db || pagerUseWal(pPager)==0 );
 55115    assert( assert_pager_state(pPager) );
 55116    disable_simulated_io_errors();
 55117    sqlite3BeginBenignMalloc();
 55118    pagerFreeMapHdrs(pPager);
 55119    /* pPager->errCode = 0; */
 55120    pPager->exclusiveMode = 0;
 55121  #ifndef SQLITE_OMIT_WAL
 55122    {
 55123      u8 *a = 0;
 55124      assert( db || pPager->pWal==0 );
 55125      if( db && 0==(db->flags & SQLITE_NoCkptOnClose) 
 55126       && SQLITE_OK==databaseIsUnmoved(pPager)
 55127      ){
 55128        a = pTmp;
 55129      }
 55130      sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
 55131      pPager->pWal = 0;
 55132    }
 55133  #endif
 55134    pager_reset(pPager);
 55135    if( MEMDB ){
 55136      pager_unlock(pPager);
 55137    }else{
 55138      /* If it is open, sync the journal file before calling UnlockAndRollback.
 55139      ** If this is not done, then an unsynced portion of the open journal 
 55140      ** file may be played back into the database. If a power failure occurs 
 55141      ** while this is happening, the database could become corrupt.
 55142      **
 55143      ** If an error occurs while trying to sync the journal, shift the pager
 55144      ** into the ERROR state. This causes UnlockAndRollback to unlock the
 55145      ** database and close the journal file without attempting to roll it
 55146      ** back or finalize it. The next database user will have to do hot-journal
 55147      ** rollback before accessing the database file.
 55148      */
 55149      if( isOpen(pPager->jfd) ){
 55150        pager_error(pPager, pagerSyncHotJournal(pPager));
 55151      }
 55152      pagerUnlockAndRollback(pPager);
 55153    }
 55154    if( pPager->useBranches ){
 55155      sqlite3BranchClose(pPager);
 55156    }
 55157    sqlite3EndBenignMalloc();
 55158    enable_simulated_io_errors();
 55159    PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
 55160    IOTRACE(("CLOSE %p\n", pPager))
 55161    sqlite3OsClose(pPager->jfd);
 55162    sqlite3OsClose(pPager->fd);
 55163    sqlite3PageFree(pTmp);
 55164    sqlite3PcacheClose(pPager->pPCache);
 55165  
 55166  #ifdef SQLITE_HAS_CODEC
 55167    if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
 55168  #endif
 55169  
 55170    assert( !pPager->aSavepoint && !pPager->pInJournal );
 55171    assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
 55172  
 55173    sqlite3_free(pPager);
 55174    return SQLITE_OK;
 55175  }
 55176  
 55177  #if !defined(NDEBUG) || defined(SQLITE_TEST)
 55178  /*
 55179  ** Return the page number for page pPg.
 55180  */
 55181  SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
 55182    return pPg->pgno;
 55183  }
 55184  #endif
 55185  
 55186  /*
 55187  ** Increment the reference count for page pPg.
 55188  */
 55189  SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 55190    sqlite3PcacheRef(pPg);
 55191  }
 55192  
 55193  /*
 55194  ** Sync the journal. In other words, make sure all the pages that have
 55195  ** been written to the journal have actually reached the surface of the
 55196  ** disk and can be restored in the event of a hot-journal rollback.
 55197  **
 55198  ** If the Pager.noSync flag is set, then this function is a no-op.
 55199  ** Otherwise, the actions required depend on the journal-mode and the 
 55200  ** device characteristics of the file-system, as follows:
 55201  **
 55202  **   * If the journal file is an in-memory journal file, no action need
 55203  **     be taken.
 55204  **
 55205  **   * Otherwise, if the device does not support the SAFE_APPEND property,
 55206  **     then the nRec field of the most recently written journal header
 55207  **     is updated to contain the number of journal records that have
 55208  **     been written following it. If the pager is operating in full-sync
 55209  **     mode, then the journal file is synced before this field is updated.
 55210  **
 55211  **   * If the device does not support the SEQUENTIAL property, then 
 55212  **     journal file is synced.
 55213  **
 55214  ** Or, in pseudo-code:
 55215  **
 55216  **   if( NOT <in-memory journal> ){
 55217  **     if( NOT SAFE_APPEND ){
 55218  **       if( <full-sync mode> ) xSync(<journal file>);
 55219  **       <update nRec field>
 55220  **     } 
 55221  **     if( NOT SEQUENTIAL ) xSync(<journal file>);
 55222  **   }
 55223  **
 55224  ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
 55225  ** page currently held in memory before returning SQLITE_OK. If an IO
 55226  ** error is encountered, then the IO error code is returned to the caller.
 55227  */
 55228  static int syncJournal(Pager *pPager, int newHdr){
 55229    int rc;                         /* Return code */
 55230  
 55231    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 55232         || pPager->eState==PAGER_WRITER_DBMOD
 55233    );
 55234    assert( assert_pager_state(pPager) );
 55235    assert( !pagerUseWal(pPager) );
 55236  
 55237    rc = sqlite3PagerExclusiveLock(pPager);
 55238    if( rc!=SQLITE_OK ) return rc;
 55239  
 55240    if( !pPager->noSync ){
 55241      assert( !pPager->tempFile );
 55242      if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
 55243        const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 55244        assert( isOpen(pPager->jfd) );
 55245  
 55246        if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 55247          /* This block deals with an obscure problem. If the last connection
 55248          ** that wrote to this database was operating in persistent-journal
 55249          ** mode, then the journal file may at this point actually be larger
 55250          ** than Pager.journalOff bytes. If the next thing in the journal
 55251          ** file happens to be a journal-header (written as part of the
 55252          ** previous connection's transaction), and a crash or power-failure 
 55253          ** occurs after nRec is updated but before this connection writes 
 55254          ** anything else to the journal file (or commits/rolls back its 
 55255          ** transaction), then SQLite may become confused when doing the 
 55256          ** hot-journal rollback following recovery. It may roll back all
 55257          ** of this connections data, then proceed to rolling back the old,
 55258          ** out-of-date data that follows it. Database corruption.
 55259          **
 55260          ** To work around this, if the journal file does appear to contain
 55261          ** a valid header following Pager.journalOff, then write a 0x00
 55262          ** byte to the start of it to prevent it from being recognized.
 55263          **
 55264          ** Variable iNextHdrOffset is set to the offset at which this
 55265          ** problematic header will occur, if it exists. aMagic is used 
 55266          ** as a temporary buffer to inspect the first couple of bytes of
 55267          ** the potential journal header.
 55268          */
 55269          i64 iNextHdrOffset;
 55270          u8 aMagic[8];
 55271          u8 zHeader[sizeof(aJournalMagic)+4];
 55272  
 55273          memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
 55274          put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
 55275  
 55276          iNextHdrOffset = journalHdrOffset(pPager);
 55277          rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
 55278          if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
 55279            static const u8 zerobyte = 0;
 55280            rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
 55281          }
 55282          if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
 55283            return rc;
 55284          }
 55285  
 55286          /* Write the nRec value into the journal file header. If in
 55287          ** full-synchronous mode, sync the journal first. This ensures that
 55288          ** all data has really hit the disk before nRec is updated to mark
 55289          ** it as a candidate for rollback.
 55290          **
 55291          ** This is not required if the persistent media supports the
 55292          ** SAFE_APPEND property. Because in this case it is not possible 
 55293          ** for garbage data to be appended to the file, the nRec field
 55294          ** is populated with 0xFFFFFFFF when the journal header is written
 55295          ** and never needs to be updated.
 55296          */
 55297          if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 55298            PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 55299            IOTRACE(("JSYNC %p\n", pPager))
 55300            rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
 55301            if( rc!=SQLITE_OK ) return rc;
 55302          }
 55303          IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
 55304          rc = sqlite3OsWrite(
 55305              pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
 55306          );
 55307          if( rc!=SQLITE_OK ) return rc;
 55308        }
 55309        if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
 55310          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
 55311          IOTRACE(("JSYNC %p\n", pPager))
 55312          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
 55313            (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
 55314          );
 55315          if( rc!=SQLITE_OK ) return rc;
 55316        }
 55317  
 55318        pPager->journalHdr = pPager->journalOff;
 55319        if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
 55320          pPager->nRec = 0;
 55321          rc = writeJournalHdr(pPager);
 55322          if( rc!=SQLITE_OK ) return rc;
 55323        }
 55324      }else{
 55325        pPager->journalHdr = pPager->journalOff;
 55326      }
 55327    }
 55328  
 55329    /* Unless the pager is in noSync mode, the journal file was just 
 55330    ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
 55331    ** all pages.
 55332    */
 55333    sqlite3PcacheClearSyncFlags(pPager->pPCache);
 55334    pPager->eState = PAGER_WRITER_DBMOD;
 55335    assert( assert_pager_state(pPager) );
 55336    return SQLITE_OK;
 55337  }
 55338  
 55339  /*
 55340  ** The argument is the first in a linked list of dirty pages connected
 55341  ** by the PgHdr.pDirty pointer. This function writes each one of the
 55342  ** in-memory pages in the list to the database file. The argument may
 55343  ** be NULL, representing an empty list. In this case this function is
 55344  ** a no-op.
 55345  **
 55346  ** The pager must hold at least a RESERVED lock when this function
 55347  ** is called. Before writing anything to the database file, this lock
 55348  ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
 55349  ** SQLITE_BUSY is returned and no data is written to the database file.
 55350  ** 
 55351  ** If the pager is a temp-file pager and the actual file-system file
 55352  ** is not yet open, it is created and opened before any data is 
 55353  ** written out.
 55354  **
 55355  ** Once the lock has been upgraded and, if necessary, the file opened,
 55356  ** the pages are written out to the database file in list order. Writing
 55357  ** a page is skipped if it meets either of the following criteria:
 55358  **
 55359  **   * The page number is greater than Pager.dbSize, or
 55360  **   * The PGHDR_DONT_WRITE flag is set on the page.
 55361  **
 55362  ** If writing out a page causes the database file to grow, Pager.dbFileSize
 55363  ** is updated accordingly. If page 1 is written out, then the value cached
 55364  ** in Pager.dbFileVers[] is updated to match the new value stored in
 55365  ** the database file.
 55366  **
 55367  ** If everything is successful, SQLITE_OK is returned. If an IO error 
 55368  ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
 55369  ** be obtained, SQLITE_BUSY is returned.
 55370  */
 55371  static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
 55372    int rc = SQLITE_OK;                  /* Return code */
 55373  
 55374    /* This function is only called for rollback pagers in WRITER_DBMOD state. */
 55375    assert( !pagerUseWal(pPager) );
 55376    assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
 55377    assert( pPager->eLock==EXCLUSIVE_LOCK );
 55378    assert( isOpen(pPager->fd) || pList->pDirty==0 );
 55379  
 55380    /* If the file is a temp-file has not yet been opened, open it now. It
 55381    ** is not possible for rc to be other than SQLITE_OK if this branch
 55382    ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
 55383    */
 55384    if( !isOpen(pPager->fd) ){
 55385      assert( pPager->tempFile && rc==SQLITE_OK );
 55386      rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
 55387    }
 55388  
 55389    /* Before the first write, give the VFS a hint of what the final
 55390    ** file size will be.
 55391    */
 55392    assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
 55393    if( rc==SQLITE_OK 
 55394     && pPager->dbHintSize<pPager->dbSize
 55395     && (pList->pDirty || pList->pgno>pPager->dbHintSize)
 55396    ){
 55397      sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
 55398      sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
 55399      pPager->dbHintSize = pPager->dbSize;
 55400    }
 55401  
 55402    while( rc==SQLITE_OK && pList ){
 55403      Pgno pgno = pList->pgno;
 55404  
 55405      /* If there are dirty pages in the page cache with page numbers greater
 55406      ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
 55407      ** make the file smaller (presumably by auto-vacuum code). Do not write
 55408      ** any such pages to the file.
 55409      **
 55410      ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
 55411      ** set (set by sqlite3PagerDontWrite()).
 55412      */
 55413      if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
 55414        i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
 55415        char *pData;                                   /* Data to write */    
 55416  
 55417        assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
 55418        if( pList->pgno==1 && !pPager->useBranches ){
 55419          pager_write_changecounter(pList);
 55420        }
 55421  
 55422        /* Encode the database */
 55423        CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
 55424  
 55425        /* Write out the page data. */
 55426        rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
 55427  
 55428        /* If page 1 was just written, update Pager.dbFileVers to match
 55429        ** the value now stored in the database file. If writing this 
 55430        ** page caused the database file to grow, update dbFileSize. 
 55431        */
 55432        if( pgno==1 ){
 55433          memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
 55434        }
 55435        if( pgno>pPager->dbFileSize ){
 55436          pPager->dbFileSize = pgno;
 55437        }
 55438        pPager->aStat[PAGER_STAT_WRITE]++;
 55439  
 55440        /* Update any backup objects copying the contents of this pager. */
 55441        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
 55442  
 55443        PAGERTRACE(("STORE %d page %d hash(%08x)\n",
 55444                     PAGERID(pPager), pgno, pager_pagehash(pList)));
 55445        IOTRACE(("PGOUT %p %d\n", pPager, pgno));
 55446        PAGER_INCR(sqlite3_pager_writedb_count);
 55447      }else{
 55448        PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
 55449      }
 55450      pager_set_pagehash(pList);
 55451      pList = pList->pDirty;
 55452    }
 55453  
 55454    return rc;
 55455  }
 55456  
 55457  /*
 55458  ** Ensure that the sub-journal file is open. If it is already open, this 
 55459  ** function is a no-op.
 55460  **
 55461  ** SQLITE_OK is returned if everything goes according to plan. An 
 55462  ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
 55463  ** fails.
 55464  */
 55465  static int openSubJournal(Pager *pPager){
 55466    int rc = SQLITE_OK;
 55467    if( !isOpen(pPager->sjfd) ){
 55468      const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE 
 55469        | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE 
 55470        | SQLITE_OPEN_DELETEONCLOSE;
 55471      int nStmtSpill = sqlite3Config.nStmtSpill;
 55472      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
 55473        nStmtSpill = -1;
 55474      }
 55475      rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
 55476    }
 55477    return rc;
 55478  }
 55479  
 55480  /*
 55481  ** Append a record of the current state of page pPg to the sub-journal. 
 55482  **
 55483  ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
 55484  ** for all open savepoints before returning.
 55485  **
 55486  ** This function returns SQLITE_OK if everything is successful, an IO
 55487  ** error code if the attempt to write to the sub-journal fails, or 
 55488  ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
 55489  ** bitvec.
 55490  */
 55491  static int subjournalPage(PgHdr *pPg){
 55492    int rc = SQLITE_OK;
 55493    Pager *pPager = pPg->pPager;
 55494    if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 55495  
 55496      /* Open the sub-journal, if it has not already been opened */
 55497      assert( pPager->useJournal );
 55498      assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
 55499      assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
 55500      assert( pagerUseWal(pPager) 
 55501           || pageInJournal(pPager, pPg) 
 55502           || pPg->pgno>pPager->dbOrigSize 
 55503      );
 55504      rc = openSubJournal(pPager);
 55505  
 55506      /* If the sub-journal was opened successfully (or was already open),
 55507      ** write the journal record into the file.  */
 55508      if( rc==SQLITE_OK ){
 55509        void *pData = pPg->pData;
 55510        i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
 55511        char *pData2;
 55512  
 55513  #if SQLITE_HAS_CODEC   
 55514        if( !pPager->subjInMemory ){
 55515          CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 55516        }else
 55517  #endif
 55518        pData2 = pData;
 55519        PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
 55520        rc = write32bits(pPager->sjfd, offset, pPg->pgno);
 55521        if( rc==SQLITE_OK ){
 55522          rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
 55523        }
 55524      }
 55525    }
 55526    if( rc==SQLITE_OK ){
 55527      pPager->nSubRec++;
 55528      assert( pPager->nSavepoint>0 );
 55529      rc = addToSavepointBitvecs(pPager, pPg->pgno);
 55530    }
 55531    return rc;
 55532  }
 55533  static int subjournalPageIfRequired(PgHdr *pPg){
 55534    if( subjRequiresPage(pPg) ){
 55535      return subjournalPage(pPg);
 55536    }else{
 55537      return SQLITE_OK;
 55538    }
 55539  }
 55540  
 55541  /*
 55542  ** This function is called by the pcache layer when it has reached some
 55543  ** soft memory limit. The first argument is a pointer to a Pager object
 55544  ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
 55545  ** database). The second argument is a reference to a page that is 
 55546  ** currently dirty but has no outstanding references. The page
 55547  ** is always associated with the Pager object passed as the first 
 55548  ** argument.
 55549  **
 55550  ** The job of this function is to make pPg clean by writing its contents
 55551  ** out to the database file, if possible. This may involve syncing the
 55552  ** journal file. 
 55553  **
 55554  ** If successful, sqlite3PcacheMakeClean() is called on the page and
 55555  ** SQLITE_OK returned. If an IO error occurs while trying to make the
 55556  ** page clean, the IO error code is returned. If the page cannot be
 55557  ** made clean for some other reason, but no error occurs, then SQLITE_OK
 55558  ** is returned by sqlite3PcacheMakeClean() is not called.
 55559  */
 55560  static int pagerStress(void *p, PgHdr *pPg){
 55561    Pager *pPager = (Pager *)p;
 55562    int rc = SQLITE_OK;
 55563  
 55564    assert( pPg->pPager==pPager );
 55565    assert( pPg->flags&PGHDR_DIRTY );
 55566  
 55567    /* The doNotSpill NOSYNC bit is set during times when doing a sync of
 55568    ** journal (and adding a new header) is not allowed.  This occurs
 55569    ** during calls to sqlite3PagerWrite() while trying to journal multiple
 55570    ** pages belonging to the same sector.
 55571    **
 55572    ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
 55573    ** regardless of whether or not a sync is required.  This is set during
 55574    ** a rollback or by user request, respectively.
 55575    **
 55576    ** Spilling is also prohibited when in an error state since that could
 55577    ** lead to database corruption.   In the current implementation it 
 55578    ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
 55579    ** while in the error state, hence it is impossible for this routine to
 55580    ** be called in the error state.  Nevertheless, we include a NEVER()
 55581    ** test for the error state as a safeguard against future changes.
 55582    */
 55583    if( NEVER(pPager->errCode) ) return SQLITE_OK;
 55584    testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
 55585    testcase( pPager->doNotSpill & SPILLFLAG_OFF );
 55586    testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
 55587    if( pPager->doNotSpill
 55588     && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
 55589        || (pPg->flags & PGHDR_NEED_SYNC)!=0)
 55590    ){
 55591      return SQLITE_OK;
 55592    }
 55593  
 55594    pPager->aStat[PAGER_STAT_SPILL]++;
 55595    pPg->pDirty = 0;
 55596    if( pagerUseWal(pPager) ){
 55597      /* Write a single frame for this page to the log. */
 55598      rc = subjournalPageIfRequired(pPg); 
 55599      if( rc==SQLITE_OK ){
 55600        rc = pagerWalFrames(pPager, pPg, 0, 0);
 55601      }
 55602    }else{
 55603      
 55604  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 55605      if( pPager->tempFile==0 ){
 55606        rc = sqlite3JournalCreate(pPager->jfd);
 55607        if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
 55608      }
 55609  #endif
 55610    
 55611      /* Sync the journal file if required. */
 55612      if( pPg->flags&PGHDR_NEED_SYNC 
 55613       || pPager->eState==PAGER_WRITER_CACHEMOD
 55614      ){
 55615        rc = syncJournal(pPager, 1);
 55616      }
 55617    
 55618      /* Write the contents of the page out to the database file. */
 55619      if( rc==SQLITE_OK ){
 55620        assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
 55621        rc = pager_write_pagelist(pPager, pPg);
 55622      }
 55623    }
 55624  
 55625    /* Mark the page as clean. */
 55626    if( rc==SQLITE_OK ){
 55627      PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
 55628      sqlite3PcacheMakeClean(pPg);
 55629    }
 55630  
 55631    return pager_error(pPager, rc); 
 55632  }
 55633  
 55634  /*
 55635  ** Flush all unreferenced dirty pages to disk.
 55636  */
 55637  SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
 55638    int rc = pPager->errCode;
 55639    if( !MEMDB ){
 55640      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
 55641      assert( assert_pager_state(pPager) );
 55642      while( rc==SQLITE_OK && pList ){
 55643        PgHdr *pNext = pList->pDirty;
 55644        if( pList->nRef==0 ){
 55645          rc = pagerStress((void*)pPager, pList);
 55646        }
 55647        pList = pNext;
 55648      }
 55649    }
 55650  
 55651    return rc;
 55652  }
 55653  
 55654  /*
 55655  ** Allocate and initialize a new Pager object and put a pointer to it
 55656  ** in *ppPager. The pager should eventually be freed by passing it
 55657  ** to sqlite3PagerClose().
 55658  **
 55659  ** The zFilename argument is the path to the database file to open.
 55660  ** If zFilename is NULL then a randomly-named temporary file is created
 55661  ** and used as the file to be cached. Temporary files are be deleted
 55662  ** automatically when they are closed. If zFilename is ":memory:" then 
 55663  ** all information is held in cache. It is never written to disk. 
 55664  ** This can be used to implement an in-memory database.
 55665  **
 55666  ** The nExtra parameter specifies the number of bytes of space allocated
 55667  ** along with each page reference. This space is available to the user
 55668  ** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
 55669  ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
 55670  ** (The extra space is used by btree as the MemPage object.)
 55671  **
 55672  ** The flags argument is used to specify properties that affect the
 55673  ** operation of the pager. It should be passed some bitwise combination
 55674  ** of the PAGER_* flags.
 55675  **
 55676  ** The vfsFlags parameter is a bitmask to pass to the flags parameter
 55677  ** of the xOpen() method of the supplied VFS when opening files. 
 55678  **
 55679  ** If the pager object is allocated and the specified file opened 
 55680  ** successfully, SQLITE_OK is returned and *ppPager set to point to
 55681  ** the new pager object. If an error occurs, *ppPager is set to NULL
 55682  ** and error code returned. This function may return SQLITE_NOMEM
 55683  ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
 55684  ** various SQLITE_IO_XXX errors.
 55685  */
 55686  SQLITE_PRIVATE int sqlite3PagerOpen(
 55687    sqlite3_vfs *pVfs,       /* The virtual file system to use */
 55688    Pager **ppPager,         /* OUT: Return the Pager structure here */
 55689    const char *zFilename,   /* Name of the database file to open */
 55690    int nExtra,              /* Extra bytes append to each in-memory page */
 55691    int flags,               /* flags controlling this file */
 55692    int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
 55693    void (*xReinit)(DbPage*) /* Function to reinitialize pages */
 55694  ){
 55695    u8 *pPtr;
 55696    Pager *pPager = 0;       /* Pager object to allocate and return */
 55697    int rc = SQLITE_OK;      /* Return code */
 55698    int tempFile = 0;        /* True for temp files (incl. in-memory files) */
 55699    int memDb = 0;           /* True if this is an in-memory file */
 55700  #ifdef SQLITE_ENABLE_DESERIALIZE
 55701    int memJM = 0;           /* Memory journal mode */
 55702  #else
 55703  # define memJM 0
 55704  #endif
 55705    int readOnly = 0;        /* True if this is a read-only file */
 55706    int journalFileSize;     /* Bytes to allocate for each journal fd */
 55707    char *zPathname = 0;     /* Full path to database file */
 55708    int nPathname = 0;       /* Number of bytes in zPathname */
 55709    int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
 55710    int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
 55711    u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
 55712    const char *zUri = 0;    /* URI args to copy */
 55713    int nUri = 0;            /* Number of bytes of URI args at *zUri */
 55714  
 55715    BRANCHTRACE("sqlite3PagerOpen %s VFS=%s", zFilename && zFilename[0] ? zFilename : "temporary", pVfs->zName);
 55716  
 55717    /* Figure out how much space is required for each journal file-handle
 55718    ** (there are two of them, the main journal and the sub-journal).  */
 55719    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
 55720  
 55721    /* Set the output variable to NULL in case an error occurs. */
 55722    *ppPager = 0;
 55723  
 55724  #ifndef SQLITE_OMIT_MEMORYDB
 55725    if( flags & PAGER_MEMORY ){
 55726      memDb = 1;
 55727      if( zFilename && zFilename[0] ){
 55728        zPathname = sqlite3DbStrDup(0, zFilename);
 55729        if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
 55730        nPathname = sqlite3Strlen30(zPathname);
 55731        zFilename = 0;
 55732      }
 55733    }
 55734  #endif
 55735  
 55736    /* Compute and store the full pathname in an allocated buffer pointed
 55737    ** to by zPathname, length nPathname. Or, if this is a temporary file,
 55738    ** leave both nPathname and zPathname set to 0.
 55739    */
 55740    if( zFilename && zFilename[0] ){
 55741      const char *z;
 55742      nPathname = pVfs->mxPathname+1;
 55743      zPathname = sqlite3DbMallocRaw(0, nPathname*2);
 55744      if( zPathname==0 ){
 55745        return SQLITE_NOMEM_BKPT;
 55746      }
 55747      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
 55748      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
 55749      nPathname = sqlite3Strlen30(zPathname);
 55750      z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
 55751      while( *z ){
 55752        z += sqlite3Strlen30(z)+1;
 55753        z += sqlite3Strlen30(z)+1;
 55754      }
 55755      nUri = (int)(&z[1] - zUri);
 55756      assert( nUri>=0 );
 55757      if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
 55758        /* This branch is taken when the journal path required by
 55759        ** the database being opened will be more than pVfs->mxPathname
 55760        ** bytes in length. This means the database cannot be opened,
 55761        ** as it will not be possible to open the journal file or even
 55762        ** check for a hot-journal before reading.
 55763        */
 55764        rc = SQLITE_CANTOPEN_BKPT;
 55765      }
 55766      if( rc!=SQLITE_OK ){
 55767        sqlite3DbFree(0, zPathname);
 55768        return rc;
 55769      }
 55770    }
 55771  
 55772    /* Allocate memory for the Pager structure, PCache object, the
 55773    ** three file descriptors, the database file name and the journal 
 55774    ** file name. The layout in memory is as follows:
 55775    **
 55776    **     Pager object                    (sizeof(Pager) bytes)
 55777    **     PCache object                   (sqlite3PcacheSize() bytes)
 55778    **     Database file handle            (pVfs->szOsFile bytes)
 55779    **     Sub-journal file handle         (journalFileSize bytes)
 55780    **     Main journal file handle        (journalFileSize bytes)
 55781    **     Database file name              (nPathname+1 bytes)
 55782    **     Journal file name               (nPathname+8+1 bytes)
 55783    */
 55784    pPtr = (u8 *)sqlite3MallocZero(
 55785      ROUND8(sizeof(*pPager)) +      /* Pager structure */
 55786      ROUND8(pcacheSize) +           /* PCache object */
 55787      ROUND8(pVfs->szOsFile) +       /* The main db file */
 55788      journalFileSize * 2 +          /* The two journal files */ 
 55789      nPathname + 1 + nUri +         /* zFilename */
 55790      nPathname + 8 + 2              /* zJournal */
 55791  #ifndef SQLITE_OMIT_WAL
 55792      + nPathname + 4 + 2            /* zWal */
 55793  #endif
 55794    );
 55795    assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
 55796    if( !pPtr ){
 55797      sqlite3DbFree(0, zPathname);
 55798      return SQLITE_NOMEM_BKPT;
 55799    }
 55800    pPager =              (Pager*)(pPtr);
 55801    pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
 55802    pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
 55803    pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
 55804    pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
 55805    pPager->zFilename =    (char*)(pPtr += journalFileSize);
 55806    assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
 55807  
 55808    /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
 55809    if( zPathname ){
 55810      assert( nPathname>0 );
 55811      pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
 55812      memcpy(pPager->zFilename, zPathname, nPathname);
 55813      if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
 55814      memcpy(pPager->zJournal, zPathname, nPathname);
 55815      memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
 55816      sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
 55817  #ifndef SQLITE_OMIT_WAL
 55818      pPager->zWal = &pPager->zJournal[nPathname+8+1];
 55819      memcpy(pPager->zWal, zPathname, nPathname);
 55820      memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
 55821      sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
 55822  #endif
 55823      sqlite3DbFree(0, zPathname);
 55824    }
 55825    pPager->pVfs = pVfs;
 55826    pPager->vfsFlags = vfsFlags;
 55827  
 55828    if( strcmp(pVfs->zName,"null")==0 ){
 55829    //if( sqlite3_uri_boolean(zFilename,"branches",0) ){
 55830      char *zMaxDbSize;
 55831      pPager->useBranches = 1;
 55832      pPager->journalMode = PAGER_JOURNALMODE_BRANCHES;
 55833      zMaxDbSize = (char*) sqlite3_uri_parameter(zFilename, "max_db_size");
 55834      if( zMaxDbSize ){
 55835        sqlite3Atoi64(zMaxDbSize, &pPager->max_db_size, sqlite3Strlen30(zMaxDbSize), SQLITE_UTF8);
 55836      }
 55837      if( pPager->max_db_size==0 ){
 55838        pPager->max_db_size = 512*1024*1024;
 55839      }
 55840    }
 55841  
 55842    /* Open the pager file.
 55843    */
 55844    if( zFilename && zFilename[0] ){
 55845      int fout = 0;                    /* VFS flags returned by xOpen() */
 55846      rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
 55847      assert( !memDb );
 55848  #ifdef SQLITE_ENABLE_DESERIALIZE
 55849      memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
 55850  #endif
 55851      readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
 55852  
 55853      /* If the file was successfully opened for read/write access,
 55854      ** choose a default page size in case we have to create the
 55855      ** database file. The default page size is the maximum of:
 55856      **
 55857      **    + SQLITE_DEFAULT_PAGE_SIZE,
 55858      **    + The value returned by sqlite3OsSectorSize()
 55859      **    + The largest page size that can be written atomically.
 55860      */
 55861      if( rc==SQLITE_OK ){
 55862        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
 55863        if( !readOnly ){
 55864          setSectorSize(pPager);
 55865          assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
 55866          if( szPageDflt<pPager->sectorSize ){
 55867            if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
 55868              szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
 55869            }else{
 55870              szPageDflt = (u32)pPager->sectorSize;
 55871            }
 55872          }
 55873  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 55874          {
 55875            int ii;
 55876            assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
 55877            assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
 55878            assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
 55879            for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
 55880              if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
 55881                szPageDflt = ii;
 55882              }
 55883            }
 55884          }
 55885  #endif
 55886        }
 55887        pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
 55888        if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
 55889         || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
 55890            vfsFlags |= SQLITE_OPEN_READONLY;
 55891            goto act_like_temp_file;
 55892        }
 55893      }
 55894    }else{
 55895      /* If a temporary file is requested, it is not opened immediately.
 55896      ** In this case we accept the default page size and delay actually
 55897      ** opening the file until the first call to OsWrite().
 55898      **
 55899      ** This branch is also run for an in-memory database. An in-memory
 55900      ** database is the same as a temp-file that is never written out to
 55901      ** disk and uses an in-memory rollback journal.
 55902      **
 55903      ** This branch also runs for files marked as immutable.
 55904      */ 
 55905  act_like_temp_file:
 55906      tempFile = 1;
 55907      pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
 55908      pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
 55909      pPager->noLock = 1;                /* Do no locking */
 55910      readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
 55911    }
 55912  
 55913    /* The following call to PagerSetPagesize() serves to set the value of 
 55914    ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
 55915    */
 55916    if( rc==SQLITE_OK ){
 55917      assert( pPager->memDb==0 );
 55918      rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
 55919      testcase( rc!=SQLITE_OK );
 55920    }
 55921  
 55922    /* Initialize the PCache object. */
 55923    if( rc==SQLITE_OK ){
 55924      nExtra = ROUND8(nExtra);
 55925      assert( nExtra>=8 && nExtra<1000 );
 55926      rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
 55927                         !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
 55928    }
 55929  
 55930    /* If an error occurred above, free the  Pager structure and close the file.
 55931    */
 55932    if( rc!=SQLITE_OK ){
 55933      sqlite3OsClose(pPager->fd);
 55934      sqlite3PageFree(pPager->pTmpSpace);
 55935      sqlite3_free(pPager);
 55936      return rc;
 55937    }
 55938  
 55939    PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
 55940    IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
 55941  
 55942    pPager->useJournal = (u8)useJournal;
 55943    /* pPager->stmtOpen = 0; */
 55944    /* pPager->stmtInUse = 0; */
 55945    /* pPager->nRef = 0; */
 55946    /* pPager->stmtSize = 0; */
 55947    /* pPager->stmtJSize = 0; */
 55948    /* pPager->nPage = 0; */
 55949    pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
 55950    /* pPager->state = PAGER_UNLOCK; */
 55951    /* pPager->errMask = 0; */
 55952    pPager->tempFile = (u8)tempFile;
 55953    assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
 55954            || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
 55955    assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
 55956    pPager->exclusiveMode = (u8)tempFile; 
 55957    pPager->changeCountDone = pPager->tempFile;
 55958    pPager->memDb = (u8)memDb;
 55959    pPager->readOnly = (u8)readOnly;
 55960    assert( useJournal || pPager->tempFile );
 55961    pPager->noSync = pPager->tempFile;
 55962    if( pPager->noSync ){
 55963      assert( pPager->fullSync==0 );
 55964      assert( pPager->extraSync==0 );
 55965      assert( pPager->syncFlags==0 );
 55966      assert( pPager->walSyncFlags==0 );
 55967    }else{
 55968      pPager->fullSync = 1;
 55969      pPager->extraSync = 0;
 55970      pPager->syncFlags = SQLITE_SYNC_NORMAL;
 55971      pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
 55972    }
 55973    /* pPager->pFirst = 0; */
 55974    /* pPager->pFirstSynced = 0; */
 55975    /* pPager->pLast = 0; */
 55976    pPager->nExtra = (u16)nExtra;
 55977    pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
 55978    assert( isOpen(pPager->fd) || tempFile );
 55979    setSectorSize(pPager);
 55980    if( !useJournal ){
 55981      pPager->journalMode = PAGER_JOURNALMODE_OFF;
 55982    }else if( memDb || memJM ){
 55983      pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
 55984    }
 55985    /* pPager->xBusyHandler = 0; */
 55986    /* pPager->pBusyHandlerArg = 0; */
 55987    pPager->xReiniter = xReinit;
 55988    setGetterMethod(pPager);
 55989    /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
 55990    /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
 55991  
 55992    *ppPager = pPager;
 55993    return SQLITE_OK;
 55994  }
 55995  
 55996  
 55997  
 55998  /*
 55999  ** This function is called after transitioning from PAGER_UNLOCK to
 56000  ** PAGER_SHARED state. It tests if there is a hot journal present in
 56001  ** the file-system for the given pager. A hot journal is one that 
 56002  ** needs to be played back. According to this function, a hot-journal
 56003  ** file exists if the following criteria are met:
 56004  **
 56005  **   * The journal file exists in the file system, and
 56006  **   * No process holds a RESERVED or greater lock on the database file, and
 56007  **   * The database file itself is greater than 0 bytes in size, and
 56008  **   * The first byte of the journal file exists and is not 0x00.
 56009  **
 56010  ** If the current size of the database file is 0 but a journal file
 56011  ** exists, that is probably an old journal left over from a prior
 56012  ** database with the same name. In this case the journal file is
 56013  ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
 56014  ** is returned.
 56015  **
 56016  ** This routine does not check if there is a master journal filename
 56017  ** at the end of the file. If there is, and that master journal file
 56018  ** does not exist, then the journal file is not really hot. In this
 56019  ** case this routine will return a false-positive. The pager_playback()
 56020  ** routine will discover that the journal file is not really hot and 
 56021  ** will not roll it back. 
 56022  **
 56023  ** If a hot-journal file is found to exist, *pExists is set to 1 and 
 56024  ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
 56025  ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
 56026  ** to determine whether or not a hot-journal file exists, the IO error
 56027  ** code is returned and the value of *pExists is undefined.
 56028  */
 56029  static int hasHotJournal(Pager *pPager, int *pExists){
 56030    sqlite3_vfs * const pVfs = pPager->pVfs;
 56031    int rc = SQLITE_OK;           /* Return code */
 56032    int exists = 1;               /* True if a journal file is present */
 56033    int jrnlOpen = !!isOpen(pPager->jfd);
 56034  
 56035    assert( pPager->useJournal );
 56036    assert( isOpen(pPager->fd) );
 56037    assert( pPager->eState==PAGER_OPEN );
 56038  
 56039    assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
 56040      SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
 56041    ));
 56042  
 56043    *pExists = 0;
 56044    if( !jrnlOpen ){
 56045      rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
 56046    }
 56047    if( rc==SQLITE_OK && exists ){
 56048      int locked = 0;             /* True if some process holds a RESERVED lock */
 56049  
 56050      /* Race condition here:  Another process might have been holding the
 56051      ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
 56052      ** call above, but then delete the journal and drop the lock before
 56053      ** we get to the following sqlite3OsCheckReservedLock() call.  If that
 56054      ** is the case, this routine might think there is a hot journal when
 56055      ** in fact there is none.  This results in a false-positive which will
 56056      ** be dealt with by the playback routine.  Ticket #3883.
 56057      */
 56058      rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
 56059      if( rc==SQLITE_OK && !locked ){
 56060        Pgno nPage;                 /* Number of pages in database file */
 56061  
 56062        assert( pPager->tempFile==0 );
 56063        rc = pagerPagecount(pPager, &nPage);
 56064        if( rc==SQLITE_OK ){
 56065          /* If the database is zero pages in size, that means that either (1) the
 56066          ** journal is a remnant from a prior database with the same name where
 56067          ** the database file but not the journal was deleted, or (2) the initial
 56068          ** transaction that populates a new database is being rolled back.
 56069          ** In either case, the journal file can be deleted.  However, take care
 56070          ** not to delete the journal file if it is already open due to
 56071          ** journal_mode=PERSIST.
 56072          */
 56073          if( nPage==0 && !jrnlOpen ){
 56074            sqlite3BeginBenignMalloc();
 56075            if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
 56076              sqlite3OsDelete(pVfs, pPager->zJournal, 0);
 56077              if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
 56078            }
 56079            sqlite3EndBenignMalloc();
 56080          }else{
 56081            /* The journal file exists and no other connection has a reserved
 56082            ** or greater lock on the database file. Now check that there is
 56083            ** at least one non-zero bytes at the start of the journal file.
 56084            ** If there is, then we consider this journal to be hot. If not, 
 56085            ** it can be ignored.
 56086            */
 56087            if( !jrnlOpen ){
 56088              int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
 56089              rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
 56090            }
 56091            if( rc==SQLITE_OK ){
 56092              u8 first = 0;
 56093              rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
 56094              if( rc==SQLITE_IOERR_SHORT_READ ){
 56095                rc = SQLITE_OK;
 56096              }
 56097              if( !jrnlOpen ){
 56098                sqlite3OsClose(pPager->jfd);
 56099              }
 56100              *pExists = (first!=0);
 56101            }else if( rc==SQLITE_CANTOPEN ){
 56102              /* If we cannot open the rollback journal file in order to see if
 56103              ** it has a zero header, that might be due to an I/O error, or
 56104              ** it might be due to the race condition described above and in
 56105              ** ticket #3883.  Either way, assume that the journal is hot.
 56106              ** This might be a false positive.  But if it is, then the
 56107              ** automatic journal playback and recovery mechanism will deal
 56108              ** with it under an EXCLUSIVE lock where we do not need to
 56109              ** worry so much with race conditions.
 56110              */
 56111              *pExists = 1;
 56112              rc = SQLITE_OK;
 56113            }
 56114          }
 56115        }
 56116      }
 56117    }
 56118  
 56119    return rc;
 56120  }
 56121  
 56122  /*
 56123  ** This function is called to obtain a shared lock on the database file.
 56124  ** It is illegal to call sqlite3PagerGet() until after this function
 56125  ** has been successfully called. If a shared-lock is already held when
 56126  ** this function is called, it is a no-op.
 56127  **
 56128  ** The following operations are also performed by this function.
 56129  **
 56130  **   1) If the pager is currently in PAGER_OPEN state (no lock held
 56131  **      on the database file), then an attempt is made to obtain a
 56132  **      SHARED lock on the database file. Immediately after obtaining
 56133  **      the SHARED lock, the file-system is checked for a hot-journal,
 56134  **      which is played back if present. Following any hot-journal 
 56135  **      rollback, the contents of the cache are validated by checking
 56136  **      the 'change-counter' field of the database file header and
 56137  **      discarded if they are found to be invalid.
 56138  **
 56139  **   2) If the pager is running in exclusive-mode, and there are currently
 56140  **      no outstanding references to any pages, and is in the error state,
 56141  **      then an attempt is made to clear the error state by discarding
 56142  **      the contents of the page cache and rolling back any open journal
 56143  **      file.
 56144  **
 56145  ** If everything is successful, SQLITE_OK is returned. If an IO error 
 56146  ** occurs while locking the database, checking for a hot-journal file or 
 56147  ** rolling back a journal file, the IO error code is returned.
 56148  */
 56149  SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
 56150    int rc = SQLITE_OK;                /* Return code */
 56151  
 56152    BRANCHTRACE("sqlite3PagerSharedLock");
 56153  
 56154    /* This routine is only called from b-tree and only when there are no
 56155    ** outstanding pages. This implies that the pager state should either
 56156    ** be OPEN or READER. READER is only possible if the pager is or was in 
 56157    ** exclusive access mode.  */
 56158    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
 56159    assert( assert_pager_state(pPager) );
 56160    assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
 56161    assert( pPager->errCode==SQLITE_OK );
 56162  
 56163    if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
 56164      int bHotJournal = 1;          /* True if there exists a hot journal-file */
 56165  
 56166      assert( !MEMDB );
 56167      assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
 56168  
 56169      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
 56170      if( rc!=SQLITE_OK ){
 56171        assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
 56172        goto failed;
 56173      }
 56174  
 56175      /* If a journal file exists, and there is no RESERVED lock on the
 56176      ** database file, then it either needs to be played back or deleted.
 56177      */
 56178      if( pPager->eLock<=SHARED_LOCK ){
 56179        rc = hasHotJournal(pPager, &bHotJournal);
 56180      }
 56181      if( rc!=SQLITE_OK ){
 56182        goto failed;
 56183      }
 56184      if( bHotJournal ){
 56185        if( pPager->readOnly ){
 56186          rc = SQLITE_READONLY_ROLLBACK;
 56187          goto failed;
 56188        }
 56189  
 56190        /* Get an EXCLUSIVE lock on the database file. At this point it is
 56191        ** important that a RESERVED lock is not obtained on the way to the
 56192        ** EXCLUSIVE lock. If it were, another process might open the
 56193        ** database file, detect the RESERVED lock, and conclude that the
 56194        ** database is safe to read while this process is still rolling the 
 56195        ** hot-journal back.
 56196        ** 
 56197        ** Because the intermediate RESERVED lock is not requested, any
 56198        ** other process attempting to access the database file will get to 
 56199        ** this point in the code and fail to obtain its own EXCLUSIVE lock 
 56200        ** on the database file.
 56201        **
 56202        ** Unless the pager is in locking_mode=exclusive mode, the lock is
 56203        ** downgraded to SHARED_LOCK before this function returns.
 56204        */
 56205        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 56206        if( rc!=SQLITE_OK ){
 56207          goto failed;
 56208        }
 56209   
 56210        /* If it is not already open and the file exists on disk, open the 
 56211        ** journal for read/write access. Write access is required because 
 56212        ** in exclusive-access mode the file descriptor will be kept open 
 56213        ** and possibly used for a transaction later on. Also, write-access 
 56214        ** is usually required to finalize the journal in journal_mode=persist 
 56215        ** mode (and also for journal_mode=truncate on some systems).
 56216        **
 56217        ** If the journal does not exist, it usually means that some 
 56218        ** other connection managed to get in and roll it back before 
 56219        ** this connection obtained the exclusive lock above. Or, it 
 56220        ** may mean that the pager was in the error-state when this
 56221        ** function was called and the journal file does not exist.
 56222        */
 56223        if( !isOpen(pPager->jfd) ){
 56224          sqlite3_vfs * const pVfs = pPager->pVfs;
 56225          int bExists;              /* True if journal file exists */
 56226          rc = sqlite3OsAccess(
 56227              pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
 56228          if( rc==SQLITE_OK && bExists ){
 56229            int fout = 0;
 56230            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
 56231            assert( !pPager->tempFile );
 56232            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
 56233            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 56234            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
 56235              rc = SQLITE_CANTOPEN_BKPT;
 56236              sqlite3OsClose(pPager->jfd);
 56237            }
 56238          }
 56239        }
 56240   
 56241        /* Playback and delete the journal.  Drop the database write
 56242        ** lock and reacquire the read lock. Purge the cache before
 56243        ** playing back the hot-journal so that we don't end up with
 56244        ** an inconsistent cache.  Sync the hot journal before playing
 56245        ** it back since the process that crashed and left the hot journal
 56246        ** probably did not sync it and we are required to always sync
 56247        ** the journal before playing it back.
 56248        */
 56249        if( isOpen(pPager->jfd) ){
 56250          assert( rc==SQLITE_OK );
 56251          rc = pagerSyncHotJournal(pPager);
 56252          if( rc==SQLITE_OK ){
 56253            rc = pager_playback(pPager, !pPager->tempFile);
 56254            pPager->eState = PAGER_OPEN;
 56255          }
 56256        }else if( !pPager->exclusiveMode ){
 56257          pagerUnlockDb(pPager, SHARED_LOCK);
 56258        }
 56259  
 56260        if( rc!=SQLITE_OK ){
 56261          /* This branch is taken if an error occurs while trying to open
 56262          ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
 56263          ** pager_unlock() routine will be called before returning to unlock
 56264          ** the file. If the unlock attempt fails, then Pager.eLock must be
 56265          ** set to UNKNOWN_LOCK (see the comment above the #define for 
 56266          ** UNKNOWN_LOCK above for an explanation). 
 56267          **
 56268          ** In order to get pager_unlock() to do this, set Pager.eState to
 56269          ** PAGER_ERROR now. This is not actually counted as a transition
 56270          ** to ERROR state in the state diagram at the top of this file,
 56271          ** since we know that the same call to pager_unlock() will very
 56272          ** shortly transition the pager object to the OPEN state. Calling
 56273          ** assert_pager_state() would fail now, as it should not be possible
 56274          ** to be in ERROR state when there are zero outstanding page 
 56275          ** references.
 56276          */
 56277          pager_error(pPager, rc);
 56278          goto failed;
 56279        }
 56280  
 56281        assert( pPager->eState==PAGER_OPEN );
 56282        assert( (pPager->eLock==SHARED_LOCK)
 56283             || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
 56284        );
 56285      }
 56286  
 56287      if( !pPager->tempFile && !pPager->useBranches && pPager->hasHeldSharedLock ){
 56288        /* The shared-lock has just been acquired then check to
 56289        ** see if the database has been modified.  If the database has changed,
 56290        ** flush the cache.  The hasHeldSharedLock flag prevents this from
 56291        ** occurring on the very first access to a file, in order to save a
 56292        ** single unnecessary sqlite3OsRead() call at the start-up.
 56293        **
 56294        ** Database changes are detected by looking at 15 bytes beginning
 56295        ** at offset 24 into the file.  The first 4 of these 16 bytes are
 56296        ** a 32-bit counter that is incremented with each change.  The
 56297        ** other bytes change randomly with each file change when
 56298        ** a codec is in use.
 56299        ** 
 56300        ** There is a vanishingly small chance that a change will not be 
 56301        ** detected.  The chance of an undetected change is so small that
 56302        ** it can be neglected.
 56303        */
 56304        char dbFileVers[sizeof(pPager->dbFileVers)];
 56305  
 56306        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
 56307        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
 56308        if( rc!=SQLITE_OK ){
 56309          if( rc!=SQLITE_IOERR_SHORT_READ ){
 56310            goto failed;
 56311          }
 56312          memset(dbFileVers, 0, sizeof(dbFileVers));
 56313        }
 56314  
 56315        if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
 56316          pager_reset(pPager);
 56317  
 56318          /* Unmap the database file. It is possible that external processes
 56319          ** may have truncated the database file and then extended it back
 56320          ** to its original size while this process was not holding a lock.
 56321          ** In this case there may exist a Pager.pMap mapping that appears
 56322          ** to be the right size but is not actually valid. Avoid this
 56323          ** possibility by unmapping the db here. */
 56324          if( USEFETCH(pPager) ){
 56325            sqlite3OsUnfetch(pPager->fd, 0, 0);
 56326          }
 56327        }
 56328      }
 56329  
 56330      /* If there is a WAL file in the file-system, open this database in WAL
 56331      ** mode. Otherwise, the following function call is a no-op.
 56332      */
 56333      if( pPager->useBranches ){
 56334        rc = sqlite3BranchInit(pPager);
 56335        if( rc==SQLITE_OK && pPager->pWal==0 ){
 56336          rc = sqlite3PagerOpenWal(pPager, 0);
 56337          BRANCHTRACE("now pPager->pWal = %p", pPager->pWal);
 56338        }
 56339      } else {
 56340        rc = pagerOpenWalIfPresent(pPager);
 56341  #ifndef SQLITE_OMIT_WAL
 56342        assert( pPager->pWal==0 || rc==SQLITE_OK );
 56343  #endif
 56344      }
 56345    }
 56346  
 56347    if( pagerUseWal(pPager) ){
 56348      assert( rc==SQLITE_OK );
 56349      rc = pagerBeginReadTransaction(pPager);
 56350    }
 56351  
 56352    if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
 56353      rc = pagerPagecount(pPager, &pPager->dbSize);
 56354    }
 56355  
 56356   failed:
 56357    if( rc!=SQLITE_OK ){
 56358      assert( !MEMDB );
 56359      pager_unlock(pPager);
 56360      assert( pPager->eState==PAGER_OPEN );
 56361    }else{
 56362      pPager->eState = PAGER_READER;
 56363      pPager->hasHeldSharedLock = 1;
 56364    }
 56365    return rc;
 56366  }
 56367  
 56368  /*
 56369  ** If the reference count has reached zero, rollback any active
 56370  ** transaction and unlock the pager.
 56371  **
 56372  ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
 56373  ** the rollback journal, the unlock is not performed and there is
 56374  ** nothing to rollback, so this routine is a no-op.
 56375  */ 
 56376  static void pagerUnlockIfUnused(Pager *pPager){
 56377    if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
 56378      assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
 56379      pagerUnlockAndRollback(pPager);
 56380    }
 56381  }
 56382  
 56383  /*
 56384  ** The page getter methods each try to acquire a reference to a
 56385  ** page with page number pgno. If the requested reference is 
 56386  ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
 56387  **
 56388  ** There are different implementations of the getter method depending
 56389  ** on the current state of the pager.
 56390  **
 56391  **     getPageNormal()         --  The normal getter
 56392  **     getPageError()          --  Used if the pager is in an error state
 56393  **     getPageMmap()           --  Used if memory-mapped I/O is enabled
 56394  **
 56395  ** If the requested page is already in the cache, it is returned. 
 56396  ** Otherwise, a new page object is allocated and populated with data
 56397  ** read from the database file. In some cases, the pcache module may
 56398  ** choose not to allocate a new page object and may reuse an existing
 56399  ** object with no outstanding references.
 56400  **
 56401  ** The extra data appended to a page is always initialized to zeros the 
 56402  ** first time a page is loaded into memory. If the page requested is 
 56403  ** already in the cache when this function is called, then the extra
 56404  ** data is left as it was when the page object was last used.
 56405  **
 56406  ** If the database image is smaller than the requested page or if 
 56407  ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the 
 56408  ** requested page is not already stored in the cache, then no 
 56409  ** actual disk read occurs. In this case the memory image of the 
 56410  ** page is initialized to all zeros. 
 56411  **
 56412  ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
 56413  ** the contents of the page. This occurs in two scenarios:
 56414  **
 56415  **   a) When reading a free-list leaf page from the database, and
 56416  **
 56417  **   b) When a savepoint is being rolled back and we need to load
 56418  **      a new page into the cache to be filled with the data read
 56419  **      from the savepoint journal.
 56420  **
 56421  ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
 56422  ** of being read from the database. Additionally, the bits corresponding
 56423  ** to pgno in Pager.pInJournal (bitvec of pages already written to the
 56424  ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
 56425  ** savepoints are set. This means if the page is made writable at any
 56426  ** point in the future, using a call to sqlite3PagerWrite(), its contents
 56427  ** will not be journaled. This saves IO.
 56428  **
 56429  ** The acquisition might fail for several reasons.  In all cases,
 56430  ** an appropriate error code is returned and *ppPage is set to NULL.
 56431  **
 56432  ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
 56433  ** to find a page in the in-memory cache first.  If the page is not already
 56434  ** in memory, this routine goes to disk to read it in whereas Lookup()
 56435  ** just returns 0.  This routine acquires a read-lock the first time it
 56436  ** has to go to disk, and could also playback an old journal if necessary.
 56437  ** Since Lookup() never goes to disk, it never has to deal with locks
 56438  ** or journal files.
 56439  */
 56440  static int getPageNormal(
 56441    Pager *pPager,      /* The pager open on the database file */
 56442    Pgno pgno,          /* Page number to fetch */
 56443    DbPage **ppPage,    /* Write a pointer to the page here */
 56444    int flags           /* PAGER_GET_XXX flags */
 56445  ){
 56446    int rc = SQLITE_OK;
 56447    PgHdr *pPg;
 56448    u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
 56449    sqlite3_pcache_page *pBase;
 56450  
 56451    assert( pPager->errCode==SQLITE_OK );
 56452    assert( pPager->eState>=PAGER_READER );
 56453    assert( assert_pager_state(pPager) );
 56454    assert( pPager->hasHeldSharedLock==1 );
 56455  
 56456    if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
 56457    pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
 56458    if( pBase==0 ){
 56459      pPg = 0;
 56460      rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
 56461      if( rc!=SQLITE_OK ) goto pager_acquire_err;
 56462      if( pBase==0 ){
 56463        rc = SQLITE_NOMEM_BKPT;
 56464        goto pager_acquire_err;
 56465      }
 56466    }
 56467    pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
 56468    assert( pPg==(*ppPage) );
 56469    assert( pPg->pgno==pgno );
 56470    assert( pPg->pPager==pPager || pPg->pPager==0 );
 56471  
 56472    noContent = (flags & PAGER_GET_NOCONTENT)!=0;
 56473    if( pPg->pPager && !noContent ){
 56474      /* In this case the pcache already contains an initialized copy of
 56475      ** the page. Return without further ado.  */
 56476      assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
 56477      pPager->aStat[PAGER_STAT_HIT]++;
 56478      return SQLITE_OK;
 56479  
 56480    }else{
 56481      /* The pager cache has created a new page. Its content needs to 
 56482      ** be initialized. But first some error checks:
 56483      **
 56484      ** (1) The maximum page number is 2^31
 56485      ** (2) Never try to fetch the locking page
 56486      */
 56487      if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
 56488        rc = SQLITE_CORRUPT_BKPT;
 56489        goto pager_acquire_err;
 56490      }
 56491  
 56492      pPg->pPager = pPager;
 56493  
 56494      assert( !isOpen(pPager->fd) || !MEMDB );
 56495      if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
 56496        if( pgno>pPager->mxPgno ){
 56497          rc = SQLITE_FULL;
 56498          goto pager_acquire_err;
 56499        }
 56500        if( noContent ){
 56501          /* Failure to set the bits in the InJournal bit-vectors is benign.
 56502          ** It merely means that we might do some extra work to journal a 
 56503          ** page that does not need to be journaled.  Nevertheless, be sure 
 56504          ** to test the case where a malloc error occurs while trying to set 
 56505          ** a bit in a bit vector.
 56506          */
 56507          sqlite3BeginBenignMalloc();
 56508          if( pgno<=pPager->dbOrigSize ){
 56509            TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
 56510            testcase( rc==SQLITE_NOMEM );
 56511          }
 56512          TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
 56513          testcase( rc==SQLITE_NOMEM );
 56514          sqlite3EndBenignMalloc();
 56515        }
 56516        memset(pPg->pData, 0, pPager->pageSize);
 56517        IOTRACE(("ZERO %p %d\n", pPager, pgno));
 56518      }else{
 56519        assert( pPg->pPager==pPager );
 56520        pPager->aStat[PAGER_STAT_MISS]++;
 56521        rc = readDbPage(pPg);
 56522        if( rc!=SQLITE_OK ){
 56523          goto pager_acquire_err;
 56524        }
 56525      }
 56526      pager_set_pagehash(pPg);
 56527    }
 56528    return SQLITE_OK;
 56529  
 56530  pager_acquire_err:
 56531    assert( rc!=SQLITE_OK );
 56532    if( pPg ){
 56533      sqlite3PcacheDrop(pPg);
 56534    }
 56535    pagerUnlockIfUnused(pPager);
 56536    *ppPage = 0;
 56537    return rc;
 56538  }
 56539  
 56540  #if SQLITE_MAX_MMAP_SIZE>0
 56541  /* The page getter for when memory-mapped I/O is enabled */
 56542  static int getPageMMap(
 56543    Pager *pPager,      /* The pager open on the database file */
 56544    Pgno pgno,          /* Page number to fetch */
 56545    DbPage **ppPage,    /* Write a pointer to the page here */
 56546    int flags           /* PAGER_GET_XXX flags */
 56547  ){
 56548    int rc = SQLITE_OK;
 56549    PgHdr *pPg = 0;
 56550    u32 iFrame = 0;                 /* Frame to read from WAL file */
 56551  
 56552    /* It is acceptable to use a read-only (mmap) page for any page except
 56553    ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
 56554    ** flag was specified by the caller. And so long as the db is not a 
 56555    ** temporary or in-memory database.  */
 56556    const int bMmapOk = (pgno>1
 56557     && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
 56558    );
 56559  
 56560    assert( USEFETCH(pPager) );
 56561  #ifdef SQLITE_HAS_CODEC
 56562    assert( pPager->xCodec==0 );
 56563  #endif
 56564  
 56565    /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
 56566    ** allows the compiler optimizer to reuse the results of the "pgno>1"
 56567    ** test in the previous statement, and avoid testing pgno==0 in the
 56568    ** common case where pgno is large. */
 56569    if( pgno<=1 && pgno==0 ){
 56570      return SQLITE_CORRUPT_BKPT;
 56571    }
 56572    assert( pPager->eState>=PAGER_READER );
 56573    assert( assert_pager_state(pPager) );
 56574    assert( pPager->hasHeldSharedLock==1 );
 56575    assert( pPager->errCode==SQLITE_OK );
 56576  
 56577    if( bMmapOk && pagerUseWal(pPager) ){
 56578      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
 56579      if( rc!=SQLITE_OK ){
 56580        *ppPage = 0;
 56581        return rc;
 56582      }
 56583    }
 56584    if( bMmapOk && iFrame==0 ){
 56585      void *pData = 0;
 56586      rc = sqlite3OsFetch(pPager->fd, 
 56587          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
 56588      );
 56589      if( rc==SQLITE_OK && pData ){
 56590        if( pPager->eState>PAGER_READER || pPager->tempFile ){
 56591          pPg = sqlite3PagerLookup(pPager, pgno);
 56592        }
 56593        if( pPg==0 ){
 56594          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
 56595        }else{
 56596          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
 56597        }
 56598        if( pPg ){
 56599          assert( rc==SQLITE_OK );
 56600          *ppPage = pPg;
 56601          return SQLITE_OK;
 56602        }
 56603      }
 56604      if( rc!=SQLITE_OK ){
 56605        *ppPage = 0;
 56606        return rc;
 56607      }
 56608    }
 56609    return getPageNormal(pPager, pgno, ppPage, flags);
 56610  }
 56611  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 56612  
 56613  /* The page getter method for when the pager is an error state */
 56614  static int getPageError(
 56615    Pager *pPager,      /* The pager open on the database file */
 56616    Pgno pgno,          /* Page number to fetch */
 56617    DbPage **ppPage,    /* Write a pointer to the page here */
 56618    int flags           /* PAGER_GET_XXX flags */
 56619  ){
 56620    UNUSED_PARAMETER(pgno);
 56621    UNUSED_PARAMETER(flags);
 56622    assert( pPager->errCode!=SQLITE_OK );
 56623    *ppPage = 0;
 56624    return pPager->errCode;
 56625  }
 56626  
 56627  
 56628  /* Dispatch all page fetch requests to the appropriate getter method.
 56629  */
 56630  SQLITE_PRIVATE int sqlite3PagerGet(
 56631    Pager *pPager,      /* The pager open on the database file */
 56632    Pgno pgno,          /* Page number to fetch */
 56633    DbPage **ppPage,    /* Write a pointer to the page here */
 56634    int flags           /* PAGER_GET_XXX flags */
 56635  ){
 56636    BRANCHTRACE("sqlite3PagerGet pgno: %d", pgno);
 56637    return pPager->xGet(pPager, pgno, ppPage, flags);
 56638  }
 56639  
 56640  /*
 56641  ** Acquire a page if it is already in the in-memory cache.  Do
 56642  ** not read the page from disk.  Return a pointer to the page,
 56643  ** or 0 if the page is not in cache. 
 56644  **
 56645  ** See also sqlite3PagerGet().  The difference between this routine
 56646  ** and sqlite3PagerGet() is that _get() will go to the disk and read
 56647  ** in the page if the page is not already in cache.  This routine
 56648  ** returns NULL if the page is not in cache or if a disk I/O error 
 56649  ** has ever happened.
 56650  */
 56651  SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
 56652    sqlite3_pcache_page *pPage;
 56653    assert( pPager!=0 );
 56654    assert( pgno!=0 );
 56655    assert( pPager->pPCache!=0 );
 56656    pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
 56657    assert( pPage==0 || pPager->hasHeldSharedLock );
 56658    if( pPage==0 ) return 0;
 56659    return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
 56660  }
 56661  
 56662  /*
 56663  ** Release a page reference.
 56664  **
 56665  ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
 56666  ** used if we know that the page being released is not the last page.
 56667  ** The btree layer always holds page1 open until the end, so these first
 56668  ** to routines can be used to release any page other than BtShared.pPage1.
 56669  **
 56670  ** Use sqlite3PagerUnrefPageOne() to release page1.  This latter routine
 56671  ** checks the total number of outstanding pages and if the number of
 56672  ** pages reaches zero it drops the database lock.
 56673  */
 56674  SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
 56675    TESTONLY( Pager *pPager = pPg->pPager; )
 56676    assert( pPg!=0 );
 56677    if( pPg->flags & PGHDR_MMAP ){
 56678      assert( pPg->pgno!=1 );  /* Page1 is never memory mapped */
 56679      pagerReleaseMapPage(pPg);
 56680    }else{
 56681      sqlite3PcacheRelease(pPg);
 56682    }
 56683    /* Do not use this routine to release the last reference to page1 */
 56684    assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
 56685  }
 56686  SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
 56687    if( pPg ) sqlite3PagerUnrefNotNull(pPg);
 56688  }
 56689  SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
 56690    Pager *pPager;
 56691    assert( pPg!=0 );
 56692    assert( pPg->pgno==1 );
 56693    assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
 56694    pPager = pPg->pPager;
 56695    sqlite3PagerResetLockTimeout(pPager);
 56696    sqlite3PcacheRelease(pPg);
 56697    pagerUnlockIfUnused(pPager);
 56698  }
 56699  
 56700  /*
 56701  ** This function is called at the start of every write transaction.
 56702  ** There must already be a RESERVED or EXCLUSIVE lock on the database 
 56703  ** file when this routine is called.
 56704  **
 56705  ** Open the journal file for pager pPager and write a journal header
 56706  ** to the start of it. If there are active savepoints, open the sub-journal
 56707  ** as well. This function is only used when the journal file is being 
 56708  ** opened to write a rollback log for a transaction. It is not used 
 56709  ** when opening a hot journal file to roll it back.
 56710  **
 56711  ** If the journal file is already open (as it may be in exclusive mode),
 56712  ** then this function just writes a journal header to the start of the
 56713  ** already open file. 
 56714  **
 56715  ** Whether or not the journal file is opened by this function, the
 56716  ** Pager.pInJournal bitvec structure is allocated.
 56717  **
 56718  ** Return SQLITE_OK if everything is successful. Otherwise, return 
 56719  ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
 56720  ** an IO error code if opening or writing the journal file fails.
 56721  */
 56722  static int pager_open_journal(Pager *pPager){
 56723    int rc = SQLITE_OK;                        /* Return code */
 56724    sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
 56725  
 56726    BRANCHTRACE("pager_open_journal");
 56727  
 56728    assert( pPager->eState==PAGER_WRITER_LOCKED );
 56729    assert( assert_pager_state(pPager) );
 56730    assert( pPager->pInJournal==0 );
 56731    
 56732    /* If already in the error state, this function is a no-op.  But on
 56733    ** the other hand, this routine is never called if we are already in
 56734    ** an error state. */
 56735    if( NEVER(pPager->errCode) ) return pPager->errCode;
 56736  
 56737    if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
 56738      pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
 56739      if( pPager->pInJournal==0 ){
 56740        return SQLITE_NOMEM_BKPT;
 56741      }
 56742    
 56743      /* Open the journal file if it is not already open. */
 56744      if( !isOpen(pPager->jfd) ){
 56745        if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
 56746          sqlite3MemJournalOpen(pPager->jfd);
 56747        }else{
 56748          int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
 56749          int nSpill;
 56750  
 56751          if( pPager->tempFile ){
 56752            flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
 56753            nSpill = sqlite3Config.nStmtSpill;
 56754          }else{
 56755            flags |= SQLITE_OPEN_MAIN_JOURNAL;
 56756            nSpill = jrnlBufferSize(pPager);
 56757          }
 56758            
 56759          /* Verify that the database still has the same name as it did when
 56760          ** it was originally opened. */
 56761          rc = databaseIsUnmoved(pPager);
 56762          if( rc==SQLITE_OK ){
 56763            rc = sqlite3JournalOpen (
 56764                pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
 56765            );
 56766          }
 56767        }
 56768        assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
 56769      }
 56770    
 56771    
 56772      /* Write the first journal header to the journal file and open 
 56773      ** the sub-journal if necessary.
 56774      */
 56775      if( rc==SQLITE_OK ){
 56776        /* TODO: Check if all of these are really required. */
 56777        pPager->nRec = 0;
 56778        pPager->journalOff = 0;
 56779        pPager->setMaster = 0;
 56780        pPager->journalHdr = 0;
 56781        rc = writeJournalHdr(pPager);
 56782      }
 56783    }
 56784  
 56785    if( rc!=SQLITE_OK ){
 56786      sqlite3BitvecDestroy(pPager->pInJournal);
 56787      pPager->pInJournal = 0;
 56788    }else{
 56789      assert( pPager->eState==PAGER_WRITER_LOCKED );
 56790      pPager->eState = PAGER_WRITER_CACHEMOD;
 56791    }
 56792  
 56793    return rc;
 56794  }
 56795  
 56796  /*
 56797  ** Begin a write-transaction on the specified pager object. If a 
 56798  ** write-transaction has already been opened, this function is a no-op.
 56799  **
 56800  ** If the exFlag argument is false, then acquire at least a RESERVED
 56801  ** lock on the database file. If exFlag is true, then acquire at least
 56802  ** an EXCLUSIVE lock. If such a lock is already held, no locking 
 56803  ** functions need be called.
 56804  **
 56805  ** If the subjInMemory argument is non-zero, then any sub-journal opened
 56806  ** within this transaction will be opened as an in-memory file. This
 56807  ** has no effect if the sub-journal is already opened (as it may be when
 56808  ** running in exclusive mode) or if the transaction does not require a
 56809  ** sub-journal. If the subjInMemory argument is zero, then any required
 56810  ** sub-journal is implemented in-memory if pPager is an in-memory database, 
 56811  ** or using a temporary file otherwise.
 56812  */
 56813  SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
 56814    int rc = SQLITE_OK;
 56815  
 56816    BRANCHTRACE("sqlite3PagerBegin");
 56817  
 56818    if( pPager->errCode ) return pPager->errCode;
 56819    assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
 56820    pPager->subjInMemory = (u8)subjInMemory;
 56821  
 56822    if( ALWAYS(pPager->eState==PAGER_READER) ){
 56823      assert( pPager->pInJournal==0 );
 56824  
 56825      if( pagerUseWal(pPager) ){
 56826        BRANCHTRACE("sqlite3PagerBegin - using WAL");
 56827        /* If the pager is configured to use locking_mode=exclusive, and an
 56828        ** exclusive lock on the database is not already held, obtain it now.
 56829        */
 56830        if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
 56831          rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 56832          if( rc!=SQLITE_OK ){
 56833            return rc;
 56834          }
 56835          (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
 56836        }
 56837  
 56838        /* Grab the write lock on the log file. If successful, upgrade to
 56839        ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
 56840        ** The busy-handler is not invoked if another connection already
 56841        ** holds the write-lock. If possible, the upper layer will call it.
 56842        */
 56843        rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
 56844      }else{
 56845        /* Obtain a RESERVED lock on the database file. If the exFlag parameter
 56846        ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
 56847        ** busy-handler callback can be used when upgrading to the EXCLUSIVE
 56848        ** lock, but not when obtaining the RESERVED lock.
 56849        */
 56850        rc = pagerLockDb(pPager, RESERVED_LOCK);
 56851        if( rc==SQLITE_OK && exFlag ){
 56852          rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 56853        }
 56854      }
 56855  
 56856      if( rc==SQLITE_OK ){
 56857        /* Change to WRITER_LOCKED state.
 56858        **
 56859        ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
 56860        ** when it has an open transaction, but never to DBMOD or FINISHED.
 56861        ** This is because in those states the code to roll back savepoint 
 56862        ** transactions may copy data from the sub-journal into the database 
 56863        ** file as well as into the page cache. Which would be incorrect in 
 56864        ** WAL mode.
 56865        */
 56866        pPager->eState = PAGER_WRITER_LOCKED;
 56867        pPager->dbHintSize = pPager->dbSize;
 56868        pPager->dbFileSize = pPager->dbSize;
 56869        pPager->dbOrigSize = pPager->dbSize;
 56870        pPager->journalOff = 0;
 56871      }
 56872  
 56873      assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
 56874      assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
 56875      assert( assert_pager_state(pPager) );
 56876    }
 56877  
 56878    PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
 56879    return rc;
 56880  }
 56881  
 56882  /*
 56883  ** Write page pPg onto the end of the rollback journal.
 56884  */
 56885  static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
 56886    Pager *pPager = pPg->pPager;
 56887    int rc;
 56888    u32 cksum;
 56889    char *pData2;
 56890    i64 iOff = pPager->journalOff;
 56891  
 56892    /* We should never write to the journal file the page that
 56893    ** contains the database locks.  The following assert verifies
 56894    ** that we do not. */
 56895    assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
 56896  
 56897    assert( pPager->journalHdr<=pPager->journalOff );
 56898    CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
 56899    cksum = pager_cksum(pPager, (u8*)pData2);
 56900  
 56901    /* Even if an IO or diskfull error occurs while journalling the
 56902    ** page in the block above, set the need-sync flag for the page.
 56903    ** Otherwise, when the transaction is rolled back, the logic in
 56904    ** playback_one_page() will think that the page needs to be restored
 56905    ** in the database file. And if an IO error occurs while doing so,
 56906    ** then corruption may follow.
 56907    */
 56908    pPg->flags |= PGHDR_NEED_SYNC;
 56909  
 56910    rc = write32bits(pPager->jfd, iOff, pPg->pgno);
 56911    if( rc!=SQLITE_OK ) return rc;
 56912    rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
 56913    if( rc!=SQLITE_OK ) return rc;
 56914    rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
 56915    if( rc!=SQLITE_OK ) return rc;
 56916  
 56917    IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
 56918             pPager->journalOff, pPager->pageSize));
 56919    PAGER_INCR(sqlite3_pager_writej_count);
 56920    PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
 56921         PAGERID(pPager), pPg->pgno, 
 56922         ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
 56923  
 56924    pPager->journalOff += 8 + pPager->pageSize;
 56925    pPager->nRec++;
 56926    assert( pPager->pInJournal!=0 );
 56927    rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
 56928    testcase( rc==SQLITE_NOMEM );
 56929    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 56930    rc |= addToSavepointBitvecs(pPager, pPg->pgno);
 56931    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 56932    return rc;
 56933  }
 56934  
 56935  /*
 56936  ** Mark a single data page as writeable. The page is written into the 
 56937  ** main journal or sub-journal as required. If the page is written into
 56938  ** one of the journals, the corresponding bit is set in the 
 56939  ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
 56940  ** of any open savepoints as appropriate.
 56941  */
 56942  static int pager_write(PgHdr *pPg){
 56943    Pager *pPager = pPg->pPager;
 56944    int rc = SQLITE_OK;
 56945  
 56946    /* This routine is not called unless a write-transaction has already 
 56947    ** been started. The journal file may or may not be open at this point.
 56948    ** It is never called in the ERROR state.
 56949    */
 56950    assert( pPager->eState==PAGER_WRITER_LOCKED
 56951         || pPager->eState==PAGER_WRITER_CACHEMOD
 56952         || pPager->eState==PAGER_WRITER_DBMOD
 56953    );
 56954    assert( assert_pager_state(pPager) );
 56955    assert( pPager->errCode==0 );
 56956    assert( pPager->readOnly==0 );
 56957    CHECK_PAGE(pPg);
 56958  
 56959    /* The journal file needs to be opened. Higher level routines have already
 56960    ** obtained the necessary locks to begin the write-transaction, but the
 56961    ** rollback journal might not yet be open. Open it now if this is the case.
 56962    **
 56963    ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
 56964    ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
 56965    ** an error might occur and the pager would end up in WRITER_LOCKED state
 56966    ** with pages marked as dirty in the cache.
 56967    */
 56968    if( pPager->eState==PAGER_WRITER_LOCKED ){
 56969      rc = pager_open_journal(pPager);
 56970      if( rc!=SQLITE_OK ) return rc;
 56971    }
 56972    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
 56973    assert( assert_pager_state(pPager) );
 56974  
 56975    /* Mark the page that is about to be modified as dirty. */
 56976    sqlite3PcacheMakeDirty(pPg);
 56977  
 56978    /* If a rollback journal is in use, them make sure the page that is about
 56979    ** to change is in the rollback journal, or if the page is a new page off
 56980    ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
 56981    */
 56982    assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
 56983    if( pPager->pInJournal!=0
 56984     && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
 56985    ){
 56986      assert( pagerUseWal(pPager)==0 );
 56987      if( pPg->pgno<=pPager->dbOrigSize ){
 56988        rc = pagerAddPageToRollbackJournal(pPg);
 56989        if( rc!=SQLITE_OK ){
 56990          return rc;
 56991        }
 56992      }else{
 56993        if( pPager->eState!=PAGER_WRITER_DBMOD ){
 56994          pPg->flags |= PGHDR_NEED_SYNC;
 56995        }
 56996        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
 56997                PAGERID(pPager), pPg->pgno,
 56998               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
 56999      }
 57000    }
 57001  
 57002    /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
 57003    ** and before writing the page into the rollback journal.  Wait until now,
 57004    ** after the page has been successfully journalled, before setting the
 57005    ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
 57006    */
 57007    pPg->flags |= PGHDR_WRITEABLE;
 57008    
 57009    /* If the statement journal is open and the page is not in it,
 57010    ** then write the page into the statement journal.
 57011    */
 57012    if( pPager->nSavepoint>0 ){
 57013      rc = subjournalPageIfRequired(pPg);
 57014    }
 57015  
 57016    /* Update the database size and return. */
 57017    if( pPager->dbSize<pPg->pgno ){
 57018      pPager->dbSize = pPg->pgno;
 57019    }
 57020    return rc;
 57021  }
 57022  
 57023  /*
 57024  ** This is a variant of sqlite3PagerWrite() that runs when the sector size
 57025  ** is larger than the page size.  SQLite makes the (reasonable) assumption that
 57026  ** all bytes of a sector are written together by hardware.  Hence, all bytes of
 57027  ** a sector need to be journalled in case of a power loss in the middle of
 57028  ** a write.
 57029  **
 57030  ** Usually, the sector size is less than or equal to the page size, in which
 57031  ** case pages can be individually written.  This routine only runs in the
 57032  ** exceptional case where the page size is smaller than the sector size.
 57033  */
 57034  static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
 57035    int rc = SQLITE_OK;          /* Return code */
 57036    Pgno nPageCount;             /* Total number of pages in database file */
 57037    Pgno pg1;                    /* First page of the sector pPg is located on. */
 57038    int nPage = 0;               /* Number of pages starting at pg1 to journal */
 57039    int ii;                      /* Loop counter */
 57040    int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
 57041    Pager *pPager = pPg->pPager; /* The pager that owns pPg */
 57042    Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
 57043  
 57044    /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
 57045    ** a journal header to be written between the pages journaled by
 57046    ** this function.
 57047    */
 57048    assert( !MEMDB );
 57049    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
 57050    pPager->doNotSpill |= SPILLFLAG_NOSYNC;
 57051  
 57052    /* This trick assumes that both the page-size and sector-size are
 57053    ** an integer power of 2. It sets variable pg1 to the identifier
 57054    ** of the first page of the sector pPg is located on.
 57055    */
 57056    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
 57057  
 57058    nPageCount = pPager->dbSize;
 57059    if( pPg->pgno>nPageCount ){
 57060      nPage = (pPg->pgno - pg1)+1;
 57061    }else if( (pg1+nPagePerSector-1)>nPageCount ){
 57062      nPage = nPageCount+1-pg1;
 57063    }else{
 57064      nPage = nPagePerSector;
 57065    }
 57066    assert(nPage>0);
 57067    assert(pg1<=pPg->pgno);
 57068    assert((pg1+nPage)>pPg->pgno);
 57069  
 57070    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
 57071      Pgno pg = pg1+ii;
 57072      PgHdr *pPage;
 57073      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
 57074        if( pg!=PAGER_MJ_PGNO(pPager) ){
 57075          rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
 57076          if( rc==SQLITE_OK ){
 57077            rc = pager_write(pPage);
 57078            if( pPage->flags&PGHDR_NEED_SYNC ){
 57079              needSync = 1;
 57080            }
 57081            sqlite3PagerUnrefNotNull(pPage);
 57082          }
 57083        }
 57084      }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
 57085        if( pPage->flags&PGHDR_NEED_SYNC ){
 57086          needSync = 1;
 57087        }
 57088        sqlite3PagerUnrefNotNull(pPage);
 57089      }
 57090    }
 57091  
 57092    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
 57093    ** starting at pg1, then it needs to be set for all of them. Because
 57094    ** writing to any of these nPage pages may damage the others, the
 57095    ** journal file must contain sync()ed copies of all of them
 57096    ** before any of them can be written out to the database file.
 57097    */
 57098    if( rc==SQLITE_OK && needSync ){
 57099      assert( !MEMDB );
 57100      for(ii=0; ii<nPage; ii++){
 57101        PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
 57102        if( pPage ){
 57103          pPage->flags |= PGHDR_NEED_SYNC;
 57104          sqlite3PagerUnrefNotNull(pPage);
 57105        }
 57106      }
 57107    }
 57108  
 57109    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
 57110    pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
 57111    return rc;
 57112  }
 57113  
 57114  /*
 57115  ** Mark a data page as writeable. This routine must be called before 
 57116  ** making changes to a page. The caller must check the return value 
 57117  ** of this function and be careful not to change any page data unless 
 57118  ** this routine returns SQLITE_OK.
 57119  **
 57120  ** The difference between this function and pager_write() is that this
 57121  ** function also deals with the special case where 2 or more pages
 57122  ** fit on a single disk sector. In this case all co-resident pages
 57123  ** must have been written to the journal file before returning.
 57124  **
 57125  ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
 57126  ** as appropriate. Otherwise, SQLITE_OK.
 57127  */
 57128  SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
 57129    Pager *pPager = pPg->pPager;
 57130    assert( (pPg->flags & PGHDR_MMAP)==0 );
 57131    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 57132    assert( assert_pager_state(pPager) );
 57133    if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
 57134      if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
 57135      return SQLITE_OK;
 57136    }else if( pPager->errCode ){
 57137      return pPager->errCode;
 57138    }else if( pPager->sectorSize > (u32)pPager->pageSize ){
 57139      assert( pPager->tempFile==0 );
 57140      return pagerWriteLargeSector(pPg);
 57141    }else{
 57142      return pager_write(pPg);
 57143    }
 57144  }
 57145  
 57146  /*
 57147  ** Return TRUE if the page given in the argument was previously passed
 57148  ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
 57149  ** to change the content of the page.
 57150  */
 57151  #ifndef NDEBUG
 57152  SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
 57153    return pPg->flags & PGHDR_WRITEABLE;
 57154  }
 57155  #endif
 57156  
 57157  /*
 57158  ** A call to this routine tells the pager that it is not necessary to
 57159  ** write the information on page pPg back to the disk, even though
 57160  ** that page might be marked as dirty.  This happens, for example, when
 57161  ** the page has been added as a leaf of the freelist and so its
 57162  ** content no longer matters.
 57163  **
 57164  ** The overlying software layer calls this routine when all of the data
 57165  ** on the given page is unused. The pager marks the page as clean so
 57166  ** that it does not get written to disk.
 57167  **
 57168  ** Tests show that this optimization can quadruple the speed of large 
 57169  ** DELETE operations.
 57170  **
 57171  ** This optimization cannot be used with a temp-file, as the page may
 57172  ** have been dirty at the start of the transaction. In that case, if
 57173  ** memory pressure forces page pPg out of the cache, the data does need 
 57174  ** to be written out to disk so that it may be read back in if the 
 57175  ** current transaction is rolled back.
 57176  */
 57177  SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
 57178    Pager *pPager = pPg->pPager;
 57179    if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
 57180      PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
 57181      IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
 57182      pPg->flags |= PGHDR_DONT_WRITE;
 57183      pPg->flags &= ~PGHDR_WRITEABLE;
 57184      testcase( pPg->flags & PGHDR_NEED_SYNC );
 57185      pager_set_pagehash(pPg);
 57186    }
 57187  }
 57188  
 57189  /*
 57190  ** This routine is called to increment the value of the database file 
 57191  ** change-counter, stored as a 4-byte big-endian integer starting at 
 57192  ** byte offset 24 of the pager file.  The secondary change counter at
 57193  ** 92 is also updated, as is the SQLite version number at offset 96.
 57194  **
 57195  ** But this only happens if the pPager->changeCountDone flag is false.
 57196  ** To avoid excess churning of page 1, the update only happens once.
 57197  ** See also the pager_write_changecounter() routine that does an 
 57198  ** unconditional update of the change counters.
 57199  **
 57200  ** If the isDirectMode flag is zero, then this is done by calling 
 57201  ** sqlite3PagerWrite() on page 1, then modifying the contents of the
 57202  ** page data. In this case the file will be updated when the current
 57203  ** transaction is committed.
 57204  **
 57205  ** The isDirectMode flag may only be non-zero if the library was compiled
 57206  ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
 57207  ** if isDirect is non-zero, then the database file is updated directly
 57208  ** by writing an updated version of page 1 using a call to the 
 57209  ** sqlite3OsWrite() function.
 57210  */
 57211  static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
 57212    int rc = SQLITE_OK;
 57213  
 57214    if( pPager->useBranches ) return SQLITE_OK;
 57215    BRANCHTRACE("pager_incr_changecounter");
 57216  
 57217    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 57218         || pPager->eState==PAGER_WRITER_DBMOD
 57219    );
 57220    assert( assert_pager_state(pPager) );
 57221  
 57222    /* Declare and initialize constant integer 'isDirect'. If the
 57223    ** atomic-write optimization is enabled in this build, then isDirect
 57224    ** is initialized to the value passed as the isDirectMode parameter
 57225    ** to this function. Otherwise, it is always set to zero.
 57226    **
 57227    ** The idea is that if the atomic-write optimization is not
 57228    ** enabled at compile time, the compiler can omit the tests of
 57229    ** 'isDirect' below, as well as the block enclosed in the
 57230    ** "if( isDirect )" condition.
 57231    */
 57232  #ifndef SQLITE_ENABLE_ATOMIC_WRITE
 57233  # define DIRECT_MODE 0
 57234    assert( isDirectMode==0 );
 57235    UNUSED_PARAMETER(isDirectMode);
 57236  #else
 57237  # define DIRECT_MODE isDirectMode
 57238  #endif
 57239  
 57240    if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
 57241      PgHdr *pPgHdr;                /* Reference to page 1 */
 57242  
 57243      assert( !pPager->tempFile && isOpen(pPager->fd) );
 57244  
 57245      /* Open page 1 of the file for writing. */
 57246      rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
 57247      assert( pPgHdr==0 || rc==SQLITE_OK );
 57248  
 57249      /* If page one was fetched successfully, and this function is not
 57250      ** operating in direct-mode, make page 1 writable.  When not in 
 57251      ** direct mode, page 1 is always held in cache and hence the PagerGet()
 57252      ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
 57253      */
 57254      if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
 57255        rc = sqlite3PagerWrite(pPgHdr);
 57256      }
 57257  
 57258      if( rc==SQLITE_OK ){
 57259        /* Actually do the update of the change counter */
 57260        pager_write_changecounter(pPgHdr);
 57261  
 57262        /* If running in direct mode, write the contents of page 1 to the file. */
 57263        if( DIRECT_MODE ){
 57264          const void *zBuf;
 57265          assert( pPager->dbFileSize>0 );
 57266          CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
 57267          if( rc==SQLITE_OK ){
 57268            rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
 57269            pPager->aStat[PAGER_STAT_WRITE]++;
 57270          }
 57271          if( rc==SQLITE_OK ){
 57272            /* Update the pager's copy of the change-counter. Otherwise, the
 57273            ** next time a read transaction is opened the cache will be
 57274            ** flushed (as the change-counter values will not match).  */
 57275            const void *pCopy = (const void *)&((const char *)zBuf)[24];
 57276            memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
 57277            pPager->changeCountDone = 1;
 57278          }
 57279        }else{
 57280          pPager->changeCountDone = 1;
 57281        }
 57282      }
 57283  
 57284      /* Release the page reference. */
 57285      sqlite3PagerUnref(pPgHdr);
 57286    }
 57287    return rc;
 57288  }
 57289  
 57290  /*
 57291  ** Sync the database file to disk. This is a no-op for in-memory databases
 57292  ** or pages with the Pager.noSync flag set.
 57293  **
 57294  ** If successful, or if called on a pager for which it is a no-op, this
 57295  ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
 57296  */
 57297  SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
 57298    int rc = SQLITE_OK;
 57299    void *pArg = (void*)zMaster;
 57300    BRANCHTRACE("sqlite3PagerSync");
 57301    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
 57302    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 57303    if( rc==SQLITE_OK && !pPager->noSync ){
 57304      assert( !MEMDB );
 57305      rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
 57306    }
 57307    return rc;
 57308  }
 57309  
 57310  /*
 57311  ** This function may only be called while a write-transaction is active in
 57312  ** rollback. If the connection is in WAL mode, this call is a no-op. 
 57313  ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
 57314  ** the database file, an attempt is made to obtain one.
 57315  **
 57316  ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
 57317  ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
 57318  ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
 57319  ** returned.
 57320  */
 57321  SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
 57322    int rc = pPager->errCode;
 57323    BRANCHTRACE("sqlite3PagerExclusiveLock");
 57324    assert( assert_pager_state(pPager) );
 57325    if( rc==SQLITE_OK ){
 57326      assert( pPager->eState==PAGER_WRITER_CACHEMOD 
 57327           || pPager->eState==PAGER_WRITER_DBMOD 
 57328           || pPager->eState==PAGER_WRITER_LOCKED 
 57329      );
 57330      assert( assert_pager_state(pPager) );
 57331      if( 0==pagerUseWal(pPager) ){
 57332        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
 57333      }
 57334    }
 57335    return rc;
 57336  }
 57337  
 57338  /*
 57339  ** Sync the database file for the pager pPager. zMaster points to the name
 57340  ** of a master journal file that should be written into the individual
 57341  ** journal file. zMaster may be NULL, which is interpreted as no master
 57342  ** journal (a single database transaction).
 57343  **
 57344  ** This routine ensures that:
 57345  **
 57346  **   * The database file change-counter is updated,
 57347  **   * the journal is synced (unless the atomic-write optimization is used),
 57348  **   * all dirty pages are written to the database file, 
 57349  **   * the database file is truncated (if required), and
 57350  **   * the database file synced. 
 57351  **
 57352  ** The only thing that remains to commit the transaction is to finalize 
 57353  ** (delete, truncate or zero the first part of) the journal file (or 
 57354  ** delete the master journal file if specified).
 57355  **
 57356  ** Note that if zMaster==NULL, this does not overwrite a previous value
 57357  ** passed to an sqlite3PagerCommitPhaseOne() call.
 57358  **
 57359  ** If the final parameter - noSync - is true, then the database file itself
 57360  ** is not synced. The caller must call sqlite3PagerSync() directly to
 57361  ** sync the database file before calling CommitPhaseTwo() to delete the
 57362  ** journal file in this case.
 57363  */
 57364  SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
 57365    Pager *pPager,                  /* Pager object */
 57366    const char *zMaster,            /* If not NULL, the master journal name */
 57367    int noSync                      /* True to omit the xSync on the db file */
 57368  ){
 57369    int rc = SQLITE_OK;             /* Return code */
 57370  
 57371    BRANCHTRACE("sqlite3PagerCommitPhaseOne");
 57372  
 57373    assert( pPager->eState==PAGER_WRITER_LOCKED
 57374         || pPager->eState==PAGER_WRITER_CACHEMOD
 57375         || pPager->eState==PAGER_WRITER_DBMOD
 57376         || pPager->eState==PAGER_ERROR
 57377    );
 57378    assert( assert_pager_state(pPager) );
 57379  
 57380    /* If a prior error occurred, report that error again. */
 57381    if( NEVER(pPager->errCode) ) return pPager->errCode;
 57382  
 57383    /* Provide the ability to easily simulate an I/O error during testing */
 57384    if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
 57385  
 57386    PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
 57387        pPager->zFilename, zMaster, pPager->dbSize));
 57388  
 57389    /* If no database changes have been made, return early. */
 57390    if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
 57391  
 57392    assert( MEMDB==0 || pPager->tempFile );
 57393    assert( isOpen(pPager->fd) || pPager->tempFile );
 57394    if( 0==pagerFlushOnCommit(pPager, 1) ){
 57395      /* If this is an in-memory db, or no pages have been written to, or this
 57396      ** function has already been called, it is mostly a no-op.  However, any
 57397      ** backup in progress needs to be restarted.  */
 57398      sqlite3BackupRestart(pPager->pBackup);
 57399    }else{
 57400      PgHdr *pList;
 57401      if( pagerUseWal(pPager) ){
 57402        PgHdr *pPageOne = 0;
 57403        pList = sqlite3PcacheDirtyList(pPager->pPCache);
 57404        if( pList==0 ){
 57405          /* Must have at least one page for the WAL commit flag.
 57406          ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
 57407          rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
 57408          pList = pPageOne;
 57409          pList->pDirty = 0;
 57410        }
 57411        assert( rc==SQLITE_OK );
 57412        if( ALWAYS(pList) ){
 57413          rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
 57414        }
 57415        sqlite3PagerUnref(pPageOne);
 57416        if( rc==SQLITE_OK ){
 57417          sqlite3PcacheCleanAll(pPager->pPCache);
 57418        }
 57419      }else{
 57420        /* The bBatch boolean is true if the batch-atomic-write commit method
 57421        ** should be used.  No rollback journal is created if batch-atomic-write
 57422        ** is enabled.
 57423        */
 57424  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 57425        sqlite3_file *fd = pPager->fd;
 57426        int bBatch = zMaster==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
 57427          && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
 57428          && !pPager->noSync
 57429          && sqlite3JournalIsInMemory(pPager->jfd);
 57430  #else
 57431  #     define bBatch 0
 57432  #endif
 57433  
 57434  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 57435        /* The following block updates the change-counter. Exactly how it
 57436        ** does this depends on whether or not the atomic-update optimization
 57437        ** was enabled at compile time, and if this transaction meets the 
 57438        ** runtime criteria to use the operation: 
 57439        **
 57440        **    * The file-system supports the atomic-write property for
 57441        **      blocks of size page-size, and 
 57442        **    * This commit is not part of a multi-file transaction, and
 57443        **    * Exactly one page has been modified and store in the journal file.
 57444        **
 57445        ** If the optimization was not enabled at compile time, then the
 57446        ** pager_incr_changecounter() function is called to update the change
 57447        ** counter in 'indirect-mode'. If the optimization is compiled in but
 57448        ** is not applicable to this transaction, call sqlite3JournalCreate()
 57449        ** to make sure the journal file has actually been created, then call
 57450        ** pager_incr_changecounter() to update the change-counter in indirect
 57451        ** mode. 
 57452        **
 57453        ** Otherwise, if the optimization is both enabled and applicable,
 57454        ** then call pager_incr_changecounter() to update the change-counter
 57455        ** in 'direct' mode. In this case the journal file will never be
 57456        ** created for this transaction.
 57457        */
 57458        if( bBatch==0 ){
 57459          PgHdr *pPg;
 57460          assert( isOpen(pPager->jfd) 
 57461              || pPager->journalMode==PAGER_JOURNALMODE_OFF 
 57462              || pPager->journalMode==PAGER_JOURNALMODE_WAL 
 57463              );
 57464          if( !zMaster && isOpen(pPager->jfd) 
 57465           && pPager->journalOff==jrnlBufferSize(pPager) 
 57466           && pPager->dbSize>=pPager->dbOrigSize
 57467           && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
 57468          ){
 57469            /* Update the db file change counter via the direct-write method. The 
 57470            ** following call will modify the in-memory representation of page 1 
 57471            ** to include the updated change counter and then write page 1 
 57472            ** directly to the database file. Because of the atomic-write 
 57473            ** property of the host file-system, this is safe.
 57474            */
 57475            rc = pager_incr_changecounter(pPager, 1);
 57476          }else{
 57477            rc = sqlite3JournalCreate(pPager->jfd);
 57478            if( rc==SQLITE_OK ){
 57479              rc = pager_incr_changecounter(pPager, 0);
 57480            }
 57481          }
 57482        }
 57483  #else  /* SQLITE_ENABLE_ATOMIC_WRITE */
 57484  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 57485        if( zMaster ){
 57486          rc = sqlite3JournalCreate(pPager->jfd);
 57487          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 57488          assert( bBatch==0 );
 57489        }
 57490  #endif
 57491        rc = pager_incr_changecounter(pPager, 0);
 57492  #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
 57493        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 57494    
 57495        /* Write the master journal name into the journal file. If a master 
 57496        ** journal file name has already been written to the journal file, 
 57497        ** or if zMaster is NULL (no master journal), then this call is a no-op.
 57498        */
 57499        rc = writeMasterJournal(pPager, zMaster);
 57500        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 57501    
 57502        /* Sync the journal file and write all dirty pages to the database.
 57503        ** If the atomic-update optimization is being used, this sync will not 
 57504        ** create the journal file or perform any real IO.
 57505        **
 57506        ** Because the change-counter page was just modified, unless the
 57507        ** atomic-update optimization is used it is almost certain that the
 57508        ** journal requires a sync here. However, in locking_mode=exclusive
 57509        ** on a system under memory pressure it is just possible that this is 
 57510        ** not the case. In this case it is likely enough that the redundant
 57511        ** xSync() call will be changed to a no-op by the OS anyhow. 
 57512        */
 57513        rc = syncJournal(pPager, 0);
 57514        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 57515  
 57516        pList = sqlite3PcacheDirtyList(pPager->pPCache);
 57517  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 57518        if( bBatch ){
 57519          rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
 57520          if( rc==SQLITE_OK ){
 57521            rc = pager_write_pagelist(pPager, pList);
 57522            if( rc==SQLITE_OK ){
 57523              rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
 57524            }
 57525            if( rc!=SQLITE_OK ){
 57526              sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
 57527            }
 57528          }
 57529  
 57530          if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
 57531            rc = sqlite3JournalCreate(pPager->jfd);
 57532            if( rc!=SQLITE_OK ){
 57533              sqlite3OsClose(pPager->jfd);
 57534              goto commit_phase_one_exit;
 57535            }
 57536            bBatch = 0;
 57537          }else{
 57538            sqlite3OsClose(pPager->jfd);
 57539          }
 57540        }
 57541  #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
 57542  
 57543        if( bBatch==0 ){
 57544          rc = pager_write_pagelist(pPager, pList);
 57545        }
 57546        if( rc!=SQLITE_OK ){
 57547          assert( rc!=SQLITE_IOERR_BLOCKED );
 57548          goto commit_phase_one_exit;
 57549        }
 57550        sqlite3PcacheCleanAll(pPager->pPCache);
 57551  
 57552        /* If the file on disk is smaller than the database image, use 
 57553        ** pager_truncate to grow the file here. This can happen if the database
 57554        ** image was extended as part of the current transaction and then the
 57555        ** last page in the db image moved to the free-list. In this case the
 57556        ** last page is never written out to disk, leaving the database file
 57557        ** undersized. Fix this now if it is the case.  */
 57558        if( pPager->dbSize>pPager->dbFileSize ){
 57559          Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
 57560          assert( pPager->eState==PAGER_WRITER_DBMOD );
 57561          rc = pager_truncate(pPager, nNew);
 57562          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
 57563        }
 57564    
 57565        /* Finally, sync the database file. */
 57566        if( !noSync ){
 57567          rc = sqlite3PagerSync(pPager, zMaster);
 57568        }
 57569        IOTRACE(("DBSYNC %p\n", pPager))
 57570      }
 57571    }
 57572  
 57573  commit_phase_one_exit:
 57574    if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
 57575      pPager->eState = PAGER_WRITER_FINISHED;
 57576    }
 57577    return rc;
 57578  }
 57579  
 57580  
 57581  /*
 57582  ** When this function is called, the database file has been completely
 57583  ** updated to reflect the changes made by the current transaction and
 57584  ** synced to disk. The journal file still exists in the file-system 
 57585  ** though, and if a failure occurs at this point it will eventually
 57586  ** be used as a hot-journal and the current transaction rolled back.
 57587  **
 57588  ** This function finalizes the journal file, either by deleting, 
 57589  ** truncating or partially zeroing it, so that it cannot be used 
 57590  ** for hot-journal rollback. Once this is done the transaction is
 57591  ** irrevocably committed.
 57592  **
 57593  ** If an error occurs, an IO error code is returned and the pager
 57594  ** moves into the error state. Otherwise, SQLITE_OK is returned.
 57595  */
 57596  SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
 57597    int rc = SQLITE_OK;                  /* Return code */
 57598  
 57599    /* This routine should not be called if a prior error has occurred.
 57600    ** But if (due to a coding error elsewhere in the system) it does get
 57601    ** called, just return the same error code without doing anything. */
 57602    if( NEVER(pPager->errCode) ) return pPager->errCode;
 57603  
 57604    assert( pPager->eState==PAGER_WRITER_LOCKED
 57605         || pPager->eState==PAGER_WRITER_FINISHED
 57606         || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
 57607    );
 57608    assert( assert_pager_state(pPager) );
 57609  
 57610    /* An optimization. If the database was not actually modified during
 57611    ** this transaction, the pager is running in exclusive-mode and is
 57612    ** using persistent journals, then this function is a no-op.
 57613    **
 57614    ** The start of the journal file currently contains a single journal 
 57615    ** header with the nRec field set to 0. If such a journal is used as
 57616    ** a hot-journal during hot-journal rollback, 0 changes will be made
 57617    ** to the database file. So there is no need to zero the journal 
 57618    ** header. Since the pager is in exclusive mode, there is no need
 57619    ** to drop any locks either.
 57620    */
 57621    if( pPager->eState==PAGER_WRITER_LOCKED 
 57622     && pPager->exclusiveMode 
 57623     && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
 57624    ){
 57625      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
 57626      pPager->eState = PAGER_READER;
 57627      return SQLITE_OK;
 57628    }
 57629  
 57630    PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
 57631    pPager->iDataVersion++;
 57632    rc = pager_end_transaction(pPager, pPager->setMaster, 1);
 57633    return pager_error(pPager, rc);
 57634  }
 57635  
 57636  /*
 57637  ** If a write transaction is open, then all changes made within the 
 57638  ** transaction are reverted and the current write-transaction is closed.
 57639  ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
 57640  ** state if an error occurs.
 57641  **
 57642  ** If the pager is already in PAGER_ERROR state when this function is called,
 57643  ** it returns Pager.errCode immediately. No work is performed in this case.
 57644  **
 57645  ** Otherwise, in rollback mode, this function performs two functions:
 57646  **
 57647  **   1) It rolls back the journal file, restoring all database file and 
 57648  **      in-memory cache pages to the state they were in when the transaction
 57649  **      was opened, and
 57650  **
 57651  **   2) It finalizes the journal file, so that it is not used for hot
 57652  **      rollback at any point in the future.
 57653  **
 57654  ** Finalization of the journal file (task 2) is only performed if the 
 57655  ** rollback is successful.
 57656  **
 57657  ** In WAL mode, all cache-entries containing data modified within the
 57658  ** current transaction are either expelled from the cache or reverted to
 57659  ** their pre-transaction state by re-reading data from the database or
 57660  ** WAL files. The WAL transaction is then closed.
 57661  */
 57662  SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
 57663    int rc = SQLITE_OK;                  /* Return code */
 57664    BRANCHTRACE("sqlite3PagerRollback");
 57665    PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
 57666  
 57667    /* PagerRollback() is a no-op if called in READER or OPEN state. If
 57668    ** the pager is already in the ERROR state, the rollback is not 
 57669    ** attempted here. Instead, the error code is returned to the caller.
 57670    */
 57671    assert( assert_pager_state(pPager) );
 57672    if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
 57673    if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
 57674  
 57675    if( pagerUseWal(pPager) ){
 57676      int rc2;
 57677      rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
 57678      rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
 57679      if( rc==SQLITE_OK ) rc = rc2;
 57680    }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
 57681      int eState = pPager->eState;
 57682      rc = pager_end_transaction(pPager, 0, 0);
 57683      if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
 57684        /* This can happen using journal_mode=off. Move the pager to the error 
 57685        ** state to indicate that the contents of the cache may not be trusted.
 57686        ** Any active readers will get SQLITE_ABORT.
 57687        */
 57688        pPager->errCode = SQLITE_ABORT;
 57689        pPager->eState = PAGER_ERROR;
 57690        setGetterMethod(pPager);
 57691        return rc;
 57692      }
 57693    }else{
 57694      rc = pager_playback(pPager, 0);
 57695    }
 57696  
 57697    assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
 57698    assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
 57699            || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
 57700            || rc==SQLITE_CANTOPEN
 57701    );
 57702  
 57703    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
 57704    ** cache. So call pager_error() on the way out to make any error persistent.
 57705    */
 57706    return pager_error(pPager, rc);
 57707  }
 57708  
 57709  /*
 57710  ** Return TRUE if the database file is opened read-only.  Return FALSE
 57711  ** if the database is (in theory) writable.
 57712  */
 57713  SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
 57714    return pPager->readOnly;
 57715  }
 57716  
 57717  #ifdef SQLITE_DEBUG
 57718  /*
 57719  ** Return the sum of the reference counts for all pages held by pPager.
 57720  */
 57721  SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
 57722    return sqlite3PcacheRefCount(pPager->pPCache);
 57723  }
 57724  #endif
 57725  
 57726  /*
 57727  ** Return the approximate number of bytes of memory currently
 57728  ** used by the pager and its associated cache.
 57729  */
 57730  SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
 57731    int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
 57732                                       + 5*sizeof(void*);
 57733    return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
 57734             + sqlite3MallocSize(pPager)
 57735             + pPager->pageSize;
 57736  }
 57737  
 57738  /*
 57739  ** Return the number of references to the specified page.
 57740  */
 57741  SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
 57742    return sqlite3PcachePageRefcount(pPage);
 57743  }
 57744  
 57745  #ifdef SQLITE_TEST
 57746  /*
 57747  ** This routine is used for testing and analysis only.
 57748  */
 57749  SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
 57750    static int a[11];
 57751    a[0] = sqlite3PcacheRefCount(pPager->pPCache);
 57752    a[1] = sqlite3PcachePagecount(pPager->pPCache);
 57753    a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
 57754    a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
 57755    a[4] = pPager->eState;
 57756    a[5] = pPager->errCode;
 57757    a[6] = pPager->aStat[PAGER_STAT_HIT];
 57758    a[7] = pPager->aStat[PAGER_STAT_MISS];
 57759    a[8] = 0;  /* Used to be pPager->nOvfl */
 57760    a[9] = pPager->nRead;
 57761    a[10] = pPager->aStat[PAGER_STAT_WRITE];
 57762    return a;
 57763  }
 57764  #endif
 57765  
 57766  /*
 57767  ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
 57768  ** or _WRITE+1.  The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
 57769  ** of SQLITE_DBSTATUS_CACHE_SPILL.  The _SPILL case is not contiguous because
 57770  ** it was added later.
 57771  **
 57772  ** Before returning, *pnVal is incremented by the
 57773  ** current cache hit or miss count, according to the value of eStat. If the 
 57774  ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
 57775  ** returning.
 57776  */
 57777  SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
 57778  
 57779    assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
 57780         || eStat==SQLITE_DBSTATUS_CACHE_MISS
 57781         || eStat==SQLITE_DBSTATUS_CACHE_WRITE
 57782         || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
 57783    );
 57784  
 57785    assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
 57786    assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
 57787    assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
 57788             && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
 57789  
 57790    eStat -= SQLITE_DBSTATUS_CACHE_HIT;
 57791    *pnVal += pPager->aStat[eStat];
 57792    if( reset ){
 57793      pPager->aStat[eStat] = 0;
 57794    }
 57795  }
 57796  
 57797  /*
 57798  ** Return true if this is an in-memory or temp-file backed pager.
 57799  */
 57800  SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
 57801    return pPager->tempFile;
 57802  }
 57803  
 57804  /*
 57805  ** Check that there are at least nSavepoint savepoints open. If there are
 57806  ** currently less than nSavepoints open, then open one or more savepoints
 57807  ** to make up the difference. If the number of savepoints is already
 57808  ** equal to nSavepoint, then this function is a no-op.
 57809  **
 57810  ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
 57811  ** occurs while opening the sub-journal file, then an IO error code is
 57812  ** returned. Otherwise, SQLITE_OK.
 57813  */
 57814  static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
 57815    int rc = SQLITE_OK;                       /* Return code */
 57816    int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
 57817    int ii;                                   /* Iterator variable */
 57818    PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
 57819  
 57820    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 57821    assert( assert_pager_state(pPager) );
 57822    assert( nSavepoint>nCurrent && pPager->useJournal );
 57823  
 57824    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
 57825    ** if the allocation fails. Otherwise, zero the new portion in case a 
 57826    ** malloc failure occurs while populating it in the for(...) loop below.
 57827    */
 57828    aNew = (PagerSavepoint *)sqlite3Realloc(
 57829        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
 57830    );
 57831    if( !aNew ){
 57832      return SQLITE_NOMEM_BKPT;
 57833    }
 57834    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
 57835    pPager->aSavepoint = aNew;
 57836  
 57837    /* Populate the PagerSavepoint structures just allocated. */
 57838    for(ii=nCurrent; ii<nSavepoint; ii++){
 57839      aNew[ii].nOrig = pPager->dbSize;
 57840      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
 57841        aNew[ii].iOffset = pPager->journalOff;
 57842      }else{
 57843        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
 57844      }
 57845      aNew[ii].iSubRec = pPager->nSubRec;
 57846      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
 57847      if( !aNew[ii].pInSavepoint ){
 57848        return SQLITE_NOMEM_BKPT;
 57849      }
 57850      if( pagerUseWal(pPager) ){
 57851        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
 57852      }
 57853      pPager->nSavepoint = ii+1;
 57854    }
 57855    assert( pPager->nSavepoint==nSavepoint );
 57856    assertTruncateConstraint(pPager);
 57857    return rc;
 57858  }
 57859  SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
 57860    BRANCHTRACE("sqlite3PagerOpenSavepoint");
 57861    assert( pPager->eState>=PAGER_WRITER_LOCKED );
 57862    assert( assert_pager_state(pPager) );
 57863  
 57864    if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
 57865      return pagerOpenSavepoint(pPager, nSavepoint);
 57866    }else{
 57867      return SQLITE_OK;
 57868    }
 57869  }
 57870  
 57871  
 57872  /*
 57873  ** This function is called to rollback or release (commit) a savepoint.
 57874  ** The savepoint to release or rollback need not be the most recently 
 57875  ** created savepoint.
 57876  **
 57877  ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
 57878  ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
 57879  ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
 57880  ** that have occurred since the specified savepoint was created.
 57881  **
 57882  ** The savepoint to rollback or release is identified by parameter 
 57883  ** iSavepoint. A value of 0 means to operate on the outermost savepoint
 57884  ** (the first created). A value of (Pager.nSavepoint-1) means operate
 57885  ** on the most recently created savepoint. If iSavepoint is greater than
 57886  ** (Pager.nSavepoint-1), then this function is a no-op.
 57887  **
 57888  ** If a negative value is passed to this function, then the current
 57889  ** transaction is rolled back. This is different to calling 
 57890  ** sqlite3PagerRollback() because this function does not terminate
 57891  ** the transaction or unlock the database, it just restores the 
 57892  ** contents of the database to its original state. 
 57893  **
 57894  ** In any case, all savepoints with an index greater than iSavepoint 
 57895  ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
 57896  ** then savepoint iSavepoint is also destroyed.
 57897  **
 57898  ** This function may return SQLITE_NOMEM if a memory allocation fails,
 57899  ** or an IO error code if an IO error occurs while rolling back a 
 57900  ** savepoint. If no errors occur, SQLITE_OK is returned.
 57901  */ 
 57902  SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
 57903    int rc = pPager->errCode;
 57904    
 57905    BRANCHTRACE("sqlite3PagerSavepoint");
 57906  
 57907  #ifdef SQLITE_ENABLE_ZIPVFS
 57908    if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
 57909  #endif
 57910  
 57911    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 57912    assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
 57913  
 57914    if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
 57915      int ii;            /* Iterator variable */
 57916      int nNew;          /* Number of remaining savepoints after this op. */
 57917  
 57918      /* Figure out how many savepoints will still be active after this
 57919      ** operation. Store this value in nNew. Then free resources associated 
 57920      ** with any savepoints that are destroyed by this operation.
 57921      */
 57922      nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
 57923      for(ii=nNew; ii<pPager->nSavepoint; ii++){
 57924        sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
 57925      }
 57926      pPager->nSavepoint = nNew;
 57927  
 57928      /* If this is a release of the outermost savepoint, truncate 
 57929      ** the sub-journal to zero bytes in size. */
 57930      if( op==SAVEPOINT_RELEASE ){
 57931        if( nNew==0 && isOpen(pPager->sjfd) ){
 57932          /* Only truncate if it is an in-memory sub-journal. */
 57933          if( sqlite3JournalIsInMemory(pPager->sjfd) ){
 57934            rc = sqlite3OsTruncate(pPager->sjfd, 0);
 57935            assert( rc==SQLITE_OK );
 57936          }
 57937          pPager->nSubRec = 0;
 57938        }
 57939      }
 57940      /* Else this is a rollback operation, playback the specified savepoint.
 57941      ** If this is a temp-file, it is possible that the journal file has
 57942      ** not yet been opened. In this case there have been no changes to
 57943      ** the database file, so the playback operation can be skipped.
 57944      */
 57945      else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
 57946        PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
 57947        rc = pagerPlaybackSavepoint(pPager, pSavepoint);
 57948        assert(rc!=SQLITE_DONE);
 57949      }
 57950      
 57951  #ifdef SQLITE_ENABLE_ZIPVFS
 57952      /* If the cache has been modified but the savepoint cannot be rolled 
 57953      ** back journal_mode=off, put the pager in the error state. This way,
 57954      ** if the VFS used by this pager includes ZipVFS, the entire transaction
 57955      ** can be rolled back at the ZipVFS level.  */
 57956      else if( 
 57957          pPager->journalMode==PAGER_JOURNALMODE_OFF 
 57958       && pPager->eState>=PAGER_WRITER_CACHEMOD
 57959      ){
 57960        pPager->errCode = SQLITE_ABORT;
 57961        pPager->eState = PAGER_ERROR;
 57962        setGetterMethod(pPager);
 57963      }
 57964  #endif
 57965    }
 57966  
 57967    return rc;
 57968  }
 57969  
 57970  /*
 57971  ** Return the full pathname of the database file.
 57972  **
 57973  ** Except, if the pager is in-memory only, then return an empty string if
 57974  ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
 57975  ** used to report the filename to the user, for compatibility with legacy
 57976  ** behavior.  But when the Btree needs to know the filename for matching to
 57977  ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
 57978  ** participate in shared-cache.
 57979  */
 57980  SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
 57981    return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
 57982  }
 57983  
 57984  /*
 57985  ** Return the VFS structure for the pager.
 57986  */
 57987  SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
 57988    return pPager->pVfs;
 57989  }
 57990  
 57991  /*
 57992  ** Return the file handle for the database file associated
 57993  ** with the pager.  This might return NULL if the file has
 57994  ** not yet been opened.
 57995  */
 57996  SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
 57997    return pPager->fd;
 57998  }
 57999  
 58000  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
 58001  /*
 58002  ** Reset the lock timeout for pager.
 58003  */
 58004  SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
 58005    int x = 0;
 58006    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
 58007  }
 58008  #endif
 58009  
 58010  /*
 58011  ** Return the file handle for the journal file (if it exists).
 58012  ** This will be either the rollback journal or the WAL file.
 58013  */
 58014  SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
 58015  #if SQLITE_OMIT_WAL
 58016    return pPager->jfd;
 58017  #else
 58018    return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
 58019  #endif
 58020  }
 58021  
 58022  /*
 58023  ** Return the full pathname of the journal file.
 58024  */
 58025  SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
 58026    return pPager->zJournal;
 58027  }
 58028  
 58029  #ifdef SQLITE_HAS_CODEC
 58030  /*
 58031  ** Set or retrieve the codec for this pager
 58032  */
 58033  SQLITE_PRIVATE void sqlite3PagerSetCodec(
 58034    Pager *pPager,
 58035    void *(*xCodec)(void*,void*,Pgno,int),
 58036    void (*xCodecSizeChng)(void*,int,int),
 58037    void (*xCodecFree)(void*),
 58038    void *pCodec
 58039  ){
 58040    if( pPager->xCodecFree ){
 58041      pPager->xCodecFree(pPager->pCodec);
 58042    }else{
 58043      pager_reset(pPager);
 58044    }
 58045    pPager->xCodec = pPager->memDb ? 0 : xCodec;
 58046    pPager->xCodecSizeChng = xCodecSizeChng;
 58047    pPager->xCodecFree = xCodecFree;
 58048    pPager->pCodec = pCodec;
 58049    setGetterMethod(pPager);
 58050    pagerReportSize(pPager);
 58051  }
 58052  SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
 58053    return pPager->pCodec;
 58054  }
 58055  
 58056  /*
 58057  ** This function is called by the wal module when writing page content
 58058  ** into the log file.
 58059  **
 58060  ** This function returns a pointer to a buffer containing the encrypted
 58061  ** page content. If a malloc fails, this function may return NULL.
 58062  */
 58063  SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
 58064    void *aData = 0;
 58065    CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
 58066    return aData;
 58067  }
 58068  
 58069  /*
 58070  ** Return the current pager state
 58071  */
 58072  SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
 58073    return pPager->eState;
 58074  }
 58075  #endif /* SQLITE_HAS_CODEC */
 58076  
 58077  #ifndef SQLITE_OMIT_AUTOVACUUM
 58078  /*
 58079  ** Move the page pPg to location pgno in the file.
 58080  **
 58081  ** There must be no references to the page previously located at
 58082  ** pgno (which we call pPgOld) though that page is allowed to be
 58083  ** in cache.  If the page previously located at pgno is not already
 58084  ** in the rollback journal, it is not put there by by this routine.
 58085  **
 58086  ** References to the page pPg remain valid. Updating any
 58087  ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
 58088  ** allocated along with the page) is the responsibility of the caller.
 58089  **
 58090  ** A transaction must be active when this routine is called. It used to be
 58091  ** required that a statement transaction was not active, but this restriction
 58092  ** has been removed (CREATE INDEX needs to move a page when a statement
 58093  ** transaction is active).
 58094  **
 58095  ** If the fourth argument, isCommit, is non-zero, then this page is being
 58096  ** moved as part of a database reorganization just before the transaction 
 58097  ** is being committed. In this case, it is guaranteed that the database page 
 58098  ** pPg refers to will not be written to again within this transaction.
 58099  **
 58100  ** This function may return SQLITE_NOMEM or an IO error code if an error
 58101  ** occurs. Otherwise, it returns SQLITE_OK.
 58102  */
 58103  SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
 58104    PgHdr *pPgOld;               /* The page being overwritten. */
 58105    Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
 58106    int rc;                      /* Return code */
 58107    Pgno origPgno;               /* The original page number */
 58108  
 58109    assert( pPg->nRef>0 );
 58110    assert( pPager->eState==PAGER_WRITER_CACHEMOD
 58111         || pPager->eState==PAGER_WRITER_DBMOD
 58112    );
 58113    assert( assert_pager_state(pPager) );
 58114  
 58115    /* In order to be able to rollback, an in-memory database must journal
 58116    ** the page we are moving from.
 58117    */
 58118    assert( pPager->tempFile || !MEMDB );
 58119    if( pPager->tempFile ){
 58120      rc = sqlite3PagerWrite(pPg);
 58121      if( rc ) return rc;
 58122    }
 58123  
 58124    /* If the page being moved is dirty and has not been saved by the latest
 58125    ** savepoint, then save the current contents of the page into the 
 58126    ** sub-journal now. This is required to handle the following scenario:
 58127    **
 58128    **   BEGIN;
 58129    **     <journal page X, then modify it in memory>
 58130    **     SAVEPOINT one;
 58131    **       <Move page X to location Y>
 58132    **     ROLLBACK TO one;
 58133    **
 58134    ** If page X were not written to the sub-journal here, it would not
 58135    ** be possible to restore its contents when the "ROLLBACK TO one"
 58136    ** statement were is processed.
 58137    **
 58138    ** subjournalPage() may need to allocate space to store pPg->pgno into
 58139    ** one or more savepoint bitvecs. This is the reason this function
 58140    ** may return SQLITE_NOMEM.
 58141    */
 58142    if( (pPg->flags & PGHDR_DIRTY)!=0
 58143     && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
 58144    ){
 58145      return rc;
 58146    }
 58147  
 58148    PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
 58149        PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
 58150    IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
 58151  
 58152    /* If the journal needs to be sync()ed before page pPg->pgno can
 58153    ** be written to, store pPg->pgno in local variable needSyncPgno.
 58154    **
 58155    ** If the isCommit flag is set, there is no need to remember that
 58156    ** the journal needs to be sync()ed before database page pPg->pgno 
 58157    ** can be written to. The caller has already promised not to write to it.
 58158    */
 58159    if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
 58160      needSyncPgno = pPg->pgno;
 58161      assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
 58162              pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
 58163      assert( pPg->flags&PGHDR_DIRTY );
 58164    }
 58165  
 58166    /* If the cache contains a page with page-number pgno, remove it
 58167    ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
 58168    ** page pgno before the 'move' operation, it needs to be retained 
 58169    ** for the page moved there.
 58170    */
 58171    pPg->flags &= ~PGHDR_NEED_SYNC;
 58172    pPgOld = sqlite3PagerLookup(pPager, pgno);
 58173    assert( !pPgOld || pPgOld->nRef==1 );
 58174    if( pPgOld ){
 58175      pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
 58176      if( pPager->tempFile ){
 58177        /* Do not discard pages from an in-memory database since we might
 58178        ** need to rollback later.  Just move the page out of the way. */
 58179        sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
 58180      }else{
 58181        sqlite3PcacheDrop(pPgOld);
 58182      }
 58183    }
 58184  
 58185    origPgno = pPg->pgno;
 58186    sqlite3PcacheMove(pPg, pgno);
 58187    sqlite3PcacheMakeDirty(pPg);
 58188  
 58189    /* For an in-memory database, make sure the original page continues
 58190    ** to exist, in case the transaction needs to roll back.  Use pPgOld
 58191    ** as the original page since it has already been allocated.
 58192    */
 58193    if( pPager->tempFile && pPgOld ){
 58194      sqlite3PcacheMove(pPgOld, origPgno);
 58195      sqlite3PagerUnrefNotNull(pPgOld);
 58196    }
 58197  
 58198    if( needSyncPgno ){
 58199      /* If needSyncPgno is non-zero, then the journal file needs to be 
 58200      ** sync()ed before any data is written to database file page needSyncPgno.
 58201      ** Currently, no such page exists in the page-cache and the 
 58202      ** "is journaled" bitvec flag has been set. This needs to be remedied by
 58203      ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
 58204      ** flag.
 58205      **
 58206      ** If the attempt to load the page into the page-cache fails, (due
 58207      ** to a malloc() or IO failure), clear the bit in the pInJournal[]
 58208      ** array. Otherwise, if the page is loaded and written again in
 58209      ** this transaction, it may be written to the database file before
 58210      ** it is synced into the journal file. This way, it may end up in
 58211      ** the journal file twice, but that is not a problem.
 58212      */
 58213      PgHdr *pPgHdr;
 58214      rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
 58215      if( rc!=SQLITE_OK ){
 58216        if( needSyncPgno<=pPager->dbOrigSize ){
 58217          assert( pPager->pTmpSpace!=0 );
 58218          sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
 58219        }
 58220        return rc;
 58221      }
 58222      pPgHdr->flags |= PGHDR_NEED_SYNC;
 58223      sqlite3PcacheMakeDirty(pPgHdr);
 58224      sqlite3PagerUnrefNotNull(pPgHdr);
 58225    }
 58226  
 58227    return SQLITE_OK;
 58228  }
 58229  #endif
 58230  
 58231  /*
 58232  ** The page handle passed as the first argument refers to a dirty page 
 58233  ** with a page number other than iNew. This function changes the page's 
 58234  ** page number to iNew and sets the value of the PgHdr.flags field to 
 58235  ** the value passed as the third parameter.
 58236  */
 58237  SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
 58238    assert( pPg->pgno!=iNew );
 58239    pPg->flags = flags;
 58240    sqlite3PcacheMove(pPg, iNew);
 58241  }
 58242  
 58243  /*
 58244  ** Return a pointer to the data for the specified page.
 58245  */
 58246  SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
 58247    assert( pPg->nRef>0 || pPg->pPager->memDb );
 58248    return pPg->pData;
 58249  }
 58250  
 58251  /*
 58252  ** Return a pointer to the Pager.nExtra bytes of "extra" space 
 58253  ** allocated along with the specified page.
 58254  */
 58255  SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
 58256    return pPg->pExtra;
 58257  }
 58258  
 58259  /*
 58260  ** Get/set the locking-mode for this pager. Parameter eMode must be one
 58261  ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
 58262  ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
 58263  ** the locking-mode is set to the value specified.
 58264  **
 58265  ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
 58266  ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
 58267  ** locking-mode.
 58268  */
 58269  SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
 58270    assert( eMode==PAGER_LOCKINGMODE_QUERY
 58271              || eMode==PAGER_LOCKINGMODE_NORMAL
 58272              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
 58273    assert( PAGER_LOCKINGMODE_QUERY<0 );
 58274    assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
 58275    assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
 58276    if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
 58277      pPager->exclusiveMode = (u8)eMode;
 58278    }
 58279    return (int)pPager->exclusiveMode;
 58280  }
 58281  
 58282  /*
 58283  ** Set the journal-mode for this pager. Parameter eMode must be one of:
 58284  **
 58285  **    PAGER_JOURNALMODE_DELETE
 58286  **    PAGER_JOURNALMODE_TRUNCATE
 58287  **    PAGER_JOURNALMODE_PERSIST
 58288  **    PAGER_JOURNALMODE_OFF
 58289  **    PAGER_JOURNALMODE_MEMORY
 58290  **    PAGER_JOURNALMODE_WAL
 58291  **
 58292  ** The journalmode is set to the value specified if the change is allowed.
 58293  ** The change may be disallowed for the following reasons:
 58294  **
 58295  **   *  An in-memory database can only have its journal_mode set to _OFF
 58296  **      or _MEMORY.
 58297  **
 58298  **   *  Temporary databases cannot have _WAL journalmode.
 58299  **
 58300  ** The returned indicate the current (possibly updated) journal-mode.
 58301  */
 58302  SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
 58303    u8 eOld = pPager->journalMode;    /* Prior journalmode */
 58304  
 58305    BRANCHTRACE("sqlite3PagerSetJournalMode");
 58306  
 58307    /* The eMode parameter is always valid */
 58308    assert(      eMode==PAGER_JOURNALMODE_DELETE
 58309              || eMode==PAGER_JOURNALMODE_TRUNCATE
 58310              || eMode==PAGER_JOURNALMODE_PERSIST
 58311              || eMode==PAGER_JOURNALMODE_OFF 
 58312              || eMode==PAGER_JOURNALMODE_WAL 
 58313              || eMode==PAGER_JOURNALMODE_BRANCHES
 58314              || eMode==PAGER_JOURNALMODE_MEMORY );
 58315  
 58316    /* This routine is only called from the OP_JournalMode opcode, and
 58317    ** the logic there will never allow a temporary file to be changed
 58318    ** to WAL mode.
 58319    */
 58320    assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
 58321  
 58322    /* Do allow the journalmode of an in-memory database to be set to
 58323    ** anything other than MEMORY or OFF
 58324    */
 58325    if( MEMDB ){
 58326      assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
 58327      if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
 58328        eMode = eOld;
 58329      }
 58330    }
 58331  
 58332    /* Do not allow to change from and to branch mode. It must be specified
 58333    ** in the URI
 58334    */
 58335    if( eOld==PAGER_JOURNALMODE_BRANCHES || eMode==PAGER_JOURNALMODE_BRANCHES ){
 58336      eMode = eOld;
 58337    }
 58338  
 58339    if( eMode!=eOld ){
 58340  
 58341      /* Change the journal mode. */
 58342      assert( pPager->eState!=PAGER_ERROR );
 58343      pPager->journalMode = (u8)eMode;
 58344  
 58345      /* When transistioning from TRUNCATE or PERSIST to any other journal
 58346      ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
 58347      ** delete the journal file.
 58348      */
 58349      assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
 58350      assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
 58351      assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
 58352      assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
 58353      assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
 58354      assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
 58355      assert( (PAGER_JOURNALMODE_BRANCHES & 5)==4 );
 58356  
 58357      assert( isOpen(pPager->fd) || pPager->exclusiveMode );
 58358      if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
 58359  
 58360        /* In this case we would like to delete the journal file. If it is
 58361        ** not possible, then that is not a problem. Deleting the journal file
 58362        ** here is an optimization only.
 58363        **
 58364        ** Before deleting the journal file, obtain a RESERVED lock on the
 58365        ** database file. This ensures that the journal file is not deleted
 58366        ** while it is in use by some other client.
 58367        */
 58368        sqlite3OsClose(pPager->jfd);
 58369        if( pPager->eLock>=RESERVED_LOCK ){
 58370          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 58371        }else{
 58372          int rc = SQLITE_OK;
 58373          int state = pPager->eState;
 58374          assert( state==PAGER_OPEN || state==PAGER_READER );
 58375          if( state==PAGER_OPEN ){
 58376            rc = sqlite3PagerSharedLock(pPager);
 58377          }
 58378          if( pPager->eState==PAGER_READER ){
 58379            assert( rc==SQLITE_OK );
 58380            rc = pagerLockDb(pPager, RESERVED_LOCK);
 58381          }
 58382          if( rc==SQLITE_OK ){
 58383            sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
 58384          }
 58385          if( rc==SQLITE_OK && state==PAGER_READER ){
 58386            pagerUnlockDb(pPager, SHARED_LOCK);
 58387          }else if( state==PAGER_OPEN ){
 58388            pager_unlock(pPager);
 58389          }
 58390          assert( state==pPager->eState );
 58391        }
 58392      }else if( eMode==PAGER_JOURNALMODE_OFF ){
 58393        sqlite3OsClose(pPager->jfd);
 58394      }
 58395    }
 58396  
 58397    /* Return the new journal mode */
 58398    return (int)pPager->journalMode;
 58399  }
 58400  
 58401  /*
 58402  ** Return the current journal mode.
 58403  */
 58404  SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
 58405    return (int)pPager->journalMode;
 58406  }
 58407  
 58408  /*
 58409  ** Return TRUE if the pager is in a state where it is OK to change the
 58410  ** journalmode.  Journalmode changes can only happen when the database
 58411  ** is unmodified.
 58412  */
 58413  SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
 58414    assert( assert_pager_state(pPager) );
 58415    if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
 58416    if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
 58417    return 1;
 58418  }
 58419  
 58420  /*
 58421  ** Get/set the size-limit used for persistent journal files.
 58422  **
 58423  ** Setting the size limit to -1 means no limit is enforced.
 58424  ** An attempt to set a limit smaller than -1 is a no-op.
 58425  */
 58426  SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
 58427    if( iLimit>=-1 ){
 58428      pPager->journalSizeLimit = iLimit;
 58429      sqlite3WalLimit(pPager->pWal, iLimit);
 58430    }
 58431    return pPager->journalSizeLimit;
 58432  }
 58433  
 58434  /*
 58435  ** Return a pointer to the pPager->pBackup variable. The backup module
 58436  ** in backup.c maintains the content of this variable. This module
 58437  ** uses it opaquely as an argument to sqlite3BackupRestart() and
 58438  ** sqlite3BackupUpdate() only.
 58439  */
 58440  SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
 58441    return &pPager->pBackup;
 58442  }
 58443  
 58444  #ifndef SQLITE_OMIT_VACUUM
 58445  /*
 58446  ** Unless this is an in-memory or temporary database, clear the pager cache.
 58447  */
 58448  SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
 58449    assert( MEMDB==0 || pPager->tempFile );
 58450    if( pPager->tempFile==0 ) pager_reset(pPager);
 58451  }
 58452  #endif
 58453  
 58454  
 58455  #ifndef SQLITE_OMIT_WAL
 58456  /*
 58457  ** This function is called when the user invokes "PRAGMA wal_checkpoint",
 58458  ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
 58459  ** or wal_blocking_checkpoint() API functions.
 58460  **
 58461  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 58462  */
 58463  SQLITE_PRIVATE int sqlite3PagerCheckpoint(
 58464    Pager *pPager,                  /* Checkpoint on this pager */
 58465    sqlite3 *db,                    /* Db handle used to check for interrupts */
 58466    int eMode,                      /* Type of checkpoint */
 58467    int *pnLog,                     /* OUT: Final number of frames in log */
 58468    int *pnCkpt                     /* OUT: Final number of checkpointed frames */
 58469  ){
 58470    int rc = SQLITE_OK;
 58471    if( pPager->pWal ){
 58472      rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
 58473          (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
 58474          pPager->pBusyHandlerArg,
 58475          pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
 58476          pnLog, pnCkpt
 58477      );
 58478      sqlite3PagerResetLockTimeout(pPager);
 58479    }
 58480    return rc;
 58481  }
 58482  
 58483  SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
 58484    return sqlite3WalCallback(pPager->pWal);
 58485  }
 58486  
 58487  /*
 58488  ** Return true if the underlying VFS for the given pager supports the
 58489  ** primitives necessary for write-ahead logging.
 58490  */
 58491  SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
 58492    const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
 58493  //  if( pPager->useBranches ) return 1;  // use the method bellow if the io_methods has lock support
 58494    if( pPager->noLock ) return 0;
 58495    return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap) || pPager->useBranches;
 58496  }
 58497  
 58498  /*
 58499  ** Attempt to take an exclusive lock on the database file. If a PENDING lock
 58500  ** is obtained instead, immediately release it.
 58501  */
 58502  static int pagerExclusiveLock(Pager *pPager){
 58503    int rc;                         /* Return code */
 58504  
 58505    assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 58506    rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
 58507    if( rc!=SQLITE_OK ){
 58508      /* If the attempt to grab the exclusive lock failed, release the 
 58509      ** pending lock that may have been obtained instead.  */
 58510      pagerUnlockDb(pPager, SHARED_LOCK);
 58511    }
 58512  
 58513    return rc;
 58514  }
 58515  
 58516  /*
 58517  ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
 58518  ** exclusive-locking mode when this function is called, take an EXCLUSIVE
 58519  ** lock on the database file and use heap-memory to store the wal-index
 58520  ** in. Otherwise, use the normal shared-memory.
 58521  */
 58522  static int pagerOpenWal(Pager *pPager){
 58523    int rc = SQLITE_OK;
 58524  
 58525    BRANCHTRACE("pagerOpenWal");
 58526  
 58527    assert( pPager->pWal==0 && pPager->tempFile==0 );
 58528    assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 58529  
 58530    /* If the pager is already in exclusive-mode, the WAL module will use 
 58531    ** heap-memory for the wal-index instead of the VFS shared-memory 
 58532    ** implementation. Take the exclusive lock now, before opening the WAL
 58533    ** file, to make sure this is safe.
 58534    */
 58535    if( pPager->exclusiveMode ){
 58536      rc = pagerExclusiveLock(pPager);
 58537    }
 58538  
 58539    /* Open the connection to the log file. If this operation fails, 
 58540    ** (e.g. due to malloc() failure), return an error code.
 58541    */
 58542    if( rc==SQLITE_OK ){
 58543      rc = sqlite3WalOpen(pPager->pVfs,
 58544          pPager->fd, pPager->zWal, pPager->exclusiveMode,
 58545          pPager->journalSizeLimit, pPager->lmdb, &pPager->pWal
 58546      );
 58547    }
 58548    pagerFixMaplimit(pPager);
 58549  
 58550    return rc;
 58551  }
 58552  
 58553  
 58554  /*
 58555  ** The caller must be holding a SHARED lock on the database file to call
 58556  ** this function.
 58557  **
 58558  ** If the pager passed as the first argument is open on a real database
 58559  ** file (not a temp file or an in-memory database), and the WAL file
 58560  ** is not already open, make an attempt to open it now. If successful,
 58561  ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
 58562  ** not support the xShmXXX() methods, return an error code. *pbOpen is
 58563  ** not modified in either case.
 58564  **
 58565  ** If the pager is open on a temp-file (or in-memory database), or if
 58566  ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
 58567  ** without doing anything.
 58568  */
 58569  SQLITE_PRIVATE int sqlite3PagerOpenWal(
 58570    Pager *pPager,                  /* Pager object */
 58571    int *pbOpen                     /* OUT: Set to true if call is a no-op */
 58572  ){
 58573    int rc = SQLITE_OK;             /* Return code */
 58574  
 58575    assert( assert_pager_state(pPager) );
 58576    assert( pPager->eState==PAGER_OPEN   || pbOpen );
 58577    assert( pPager->eState==PAGER_READER || !pbOpen );
 58578    assert( pbOpen==0 || *pbOpen==0 );
 58579    assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
 58580  
 58581    if( !pPager->tempFile && !pPager->pWal ){
 58582      if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
 58583  
 58584      /* Close any rollback journal previously open */
 58585      sqlite3OsClose(pPager->jfd);
 58586  
 58587      rc = pagerOpenWal(pPager);
 58588      if( rc==SQLITE_OK ){
 58589        if( !pPager->useBranches )
 58590          pPager->journalMode = PAGER_JOURNALMODE_WAL;
 58591        pPager->eState = PAGER_OPEN;
 58592      }
 58593    }else{
 58594      *pbOpen = 1;
 58595    }
 58596  
 58597    return rc;
 58598  }
 58599  
 58600  /*
 58601  ** This function is called to close the connection to the log file prior
 58602  ** to switching from WAL to rollback mode.
 58603  **
 58604  ** Before closing the log file, this function attempts to take an 
 58605  ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
 58606  ** error (SQLITE_BUSY) is returned and the log connection is not closed.
 58607  ** If successful, the EXCLUSIVE lock is not released before returning.
 58608  */
 58609  SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
 58610    int rc = SQLITE_OK;
 58611  
 58612    assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
 58613  
 58614    /* If the log file is not already open, but does exist in the file-system,
 58615    ** it may need to be checkpointed before the connection can switch to
 58616    ** rollback mode. Open it now so this can happen.
 58617    */
 58618    if( !pPager->pWal ){
 58619      int logexists = 0;
 58620      rc = pagerLockDb(pPager, SHARED_LOCK);
 58621      if( rc==SQLITE_OK ){
 58622        rc = sqlite3OsAccess(
 58623            pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
 58624        );
 58625      }
 58626      if( rc==SQLITE_OK && logexists ){
 58627        rc = pagerOpenWal(pPager);
 58628      }
 58629    }
 58630      
 58631    /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
 58632    ** the database file, the log and log-summary files will be deleted.
 58633    */
 58634    if( rc==SQLITE_OK && pPager->pWal ){
 58635      rc = pagerExclusiveLock(pPager);
 58636      if( rc==SQLITE_OK ){
 58637        rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
 58638                             pPager->pageSize, (u8*)pPager->pTmpSpace);
 58639        pPager->pWal = 0;
 58640        pagerFixMaplimit(pPager);
 58641        if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
 58642      }
 58643    }
 58644    return rc;
 58645  }
 58646  
 58647  #ifdef SQLITE_ENABLE_SNAPSHOT
 58648  /*
 58649  ** If this is a WAL database, obtain a snapshot handle for the snapshot
 58650  ** currently open. Otherwise, return an error.
 58651  */
 58652  SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
 58653    int rc = SQLITE_ERROR;
 58654    if( pPager->pWal ){
 58655      rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
 58656    }
 58657    return rc;
 58658  }
 58659  
 58660  /*
 58661  ** If this is a WAL database, store a pointer to pSnapshot. Next time a
 58662  ** read transaction is opened, attempt to read from the snapshot it 
 58663  ** identifies. If this is not a WAL database, return an error.
 58664  */
 58665  SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
 58666    int rc = SQLITE_OK;
 58667    if( pPager->pWal ){
 58668      sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
 58669    }else{
 58670      rc = SQLITE_ERROR;
 58671    }
 58672    return rc;
 58673  }
 58674  
 58675  /*
 58676  ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this 
 58677  ** is not a WAL database, return an error.
 58678  */
 58679  SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
 58680    int rc;
 58681    if( pPager->pWal ){
 58682      rc = sqlite3WalSnapshotRecover(pPager->pWal);
 58683    }else{
 58684      rc = SQLITE_ERROR;
 58685    }
 58686    return rc;
 58687  }
 58688  
 58689  /*
 58690  ** The caller currently has a read transaction open on the database.
 58691  ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
 58692  ** this function takes a SHARED lock on the CHECKPOINTER slot and then
 58693  ** checks if the snapshot passed as the second argument is still 
 58694  ** available. If so, SQLITE_OK is returned.
 58695  **
 58696  ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
 58697  ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
 58698  ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
 58699  ** lock is released before returning.
 58700  */
 58701  SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
 58702    int rc;
 58703    if( pPager->pWal ){
 58704      rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
 58705    }else{
 58706      rc = SQLITE_ERROR;
 58707    }
 58708    return rc;
 58709  }
 58710  
 58711  /*
 58712  ** Release a lock obtained by an earlier successful call to
 58713  ** sqlite3PagerSnapshotCheck().
 58714  */
 58715  SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
 58716    assert( pPager->pWal );
 58717    return sqlite3WalSnapshotUnlock(pPager->pWal);
 58718  }
 58719  
 58720  #endif /* SQLITE_ENABLE_SNAPSHOT */
 58721  #endif /* !SQLITE_OMIT_WAL */
 58722  
 58723  #ifdef SQLITE_ENABLE_ZIPVFS
 58724  /*
 58725  ** A read-lock must be held on the pager when this function is called. If
 58726  ** the pager is in WAL mode and the WAL file currently contains one or more
 58727  ** frames, return the size in bytes of the page images stored within the
 58728  ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
 58729  ** is empty, return 0.
 58730  */
 58731  SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 58732    assert( pPager->eState>=PAGER_READER );
 58733    return sqlite3WalFramesize(pPager->pWal);
 58734  }
 58735  #endif
 58736  
 58737  #endif /* SQLITE_OMIT_DISKIO */
 58738  
 58739  /************** End of pager.c ***********************************************/
 58740  /************** Begin file wal.c *********************************************/
 58741  /*
 58742  ** 2010 February 1
 58743  **
 58744  ** The author disclaims copyright to this source code.  In place of
 58745  ** a legal notice, here is a blessing:
 58746  **
 58747  **    May you do good and not evil.
 58748  **    May you find forgiveness for yourself and forgive others.
 58749  **    May you share freely, never taking more than you give.
 58750  **
 58751  *************************************************************************
 58752  **
 58753  ** This file contains the implementation of a write-ahead log (WAL) used in 
 58754  ** "journal_mode=WAL" mode.
 58755  **
 58756  ** WRITE-AHEAD LOG (WAL) FILE FORMAT
 58757  **
 58758  ** A WAL file consists of a header followed by zero or more "frames".
 58759  ** Each frame records the revised content of a single page from the
 58760  ** database file.  All changes to the database are recorded by writing
 58761  ** frames into the WAL.  Transactions commit when a frame is written that
 58762  ** contains a commit marker.  A single WAL can and usually does record 
 58763  ** multiple transactions.  Periodically, the content of the WAL is
 58764  ** transferred back into the database file in an operation called a
 58765  ** "checkpoint".
 58766  **
 58767  ** A single WAL file can be used multiple times.  In other words, the
 58768  ** WAL can fill up with frames and then be checkpointed and then new
 58769  ** frames can overwrite the old ones.  A WAL always grows from beginning
 58770  ** toward the end.  Checksums and counters attached to each frame are
 58771  ** used to determine which frames within the WAL are valid and which
 58772  ** are leftovers from prior checkpoints.
 58773  **
 58774  ** The WAL header is 32 bytes in size and consists of the following eight
 58775  ** big-endian 32-bit unsigned integer values:
 58776  **
 58777  **     0: Magic number.  0x377f0682 or 0x377f0683
 58778  **     4: File format version.  Currently 3007000
 58779  **     8: Database page size.  Example: 1024
 58780  **    12: Checkpoint sequence number
 58781  **    16: Salt-1, random integer incremented with each checkpoint
 58782  **    20: Salt-2, a different random integer changing with each ckpt
 58783  **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
 58784  **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
 58785  **
 58786  ** Immediately following the wal-header are zero or more frames. Each
 58787  ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
 58788  ** of page data. The frame-header is six big-endian 32-bit unsigned 
 58789  ** integer values, as follows:
 58790  **
 58791  **     0: Page number.
 58792  **     4: For commit records, the size of the database image in pages 
 58793  **        after the commit. For all other records, zero.
 58794  **     8: Salt-1 (copied from the header)
 58795  **    12: Salt-2 (copied from the header)
 58796  **    16: Checksum-1.
 58797  **    20: Checksum-2.
 58798  **
 58799  ** A frame is considered valid if and only if the following conditions are
 58800  ** true:
 58801  **
 58802  **    (1) The salt-1 and salt-2 values in the frame-header match
 58803  **        salt values in the wal-header
 58804  **
 58805  **    (2) The checksum values in the final 8 bytes of the frame-header
 58806  **        exactly match the checksum computed consecutively on the
 58807  **        WAL header and the first 8 bytes and the content of all frames
 58808  **        up to and including the current frame.
 58809  **
 58810  ** The checksum is computed using 32-bit big-endian integers if the
 58811  ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
 58812  ** is computed using little-endian if the magic number is 0x377f0682.
 58813  ** The checksum values are always stored in the frame header in a
 58814  ** big-endian format regardless of which byte order is used to compute
 58815  ** the checksum.  The checksum is computed by interpreting the input as
 58816  ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
 58817  ** algorithm used for the checksum is as follows:
 58818  ** 
 58819  **   for i from 0 to n-1 step 2:
 58820  **     s0 += x[i] + s1;
 58821  **     s1 += x[i+1] + s0;
 58822  **   endfor
 58823  **
 58824  ** Note that s0 and s1 are both weighted checksums using fibonacci weights
 58825  ** in reverse order (the largest fibonacci weight occurs on the first element
 58826  ** of the sequence being summed.)  The s1 value spans all 32-bit 
 58827  ** terms of the sequence whereas s0 omits the final term.
 58828  **
 58829  ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
 58830  ** WAL is transferred into the database, then the database is VFS.xSync-ed.
 58831  ** The VFS.xSync operations serve as write barriers - all writes launched
 58832  ** before the xSync must complete before any write that launches after the
 58833  ** xSync begins.
 58834  **
 58835  ** After each checkpoint, the salt-1 value is incremented and the salt-2
 58836  ** value is randomized.  This prevents old and new frames in the WAL from
 58837  ** being considered valid at the same time and being checkpointing together
 58838  ** following a crash.
 58839  **
 58840  ** READER ALGORITHM
 58841  **
 58842  ** To read a page from the database (call it page number P), a reader
 58843  ** first checks the WAL to see if it contains page P.  If so, then the
 58844  ** last valid instance of page P that is a followed by a commit frame
 58845  ** or is a commit frame itself becomes the value read.  If the WAL
 58846  ** contains no copies of page P that are valid and which are a commit
 58847  ** frame or are followed by a commit frame, then page P is read from
 58848  ** the database file.
 58849  **
 58850  ** To start a read transaction, the reader records the index of the last
 58851  ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
 58852  ** for all subsequent read operations.  New transactions can be appended
 58853  ** to the WAL, but as long as the reader uses its original mxFrame value
 58854  ** and ignores the newly appended content, it will see a consistent snapshot
 58855  ** of the database from a single point in time.  This technique allows
 58856  ** multiple concurrent readers to view different versions of the database
 58857  ** content simultaneously.
 58858  **
 58859  ** The reader algorithm in the previous paragraphs works correctly, but 
 58860  ** because frames for page P can appear anywhere within the WAL, the
 58861  ** reader has to scan the entire WAL looking for page P frames.  If the
 58862  ** WAL is large (multiple megabytes is typical) that scan can be slow,
 58863  ** and read performance suffers.  To overcome this problem, a separate
 58864  ** data structure called the wal-index is maintained to expedite the
 58865  ** search for frames of a particular page.
 58866  ** 
 58867  ** WAL-INDEX FORMAT
 58868  **
 58869  ** Conceptually, the wal-index is shared memory, though VFS implementations
 58870  ** might choose to implement the wal-index using a mmapped file.  Because
 58871  ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
 58872  ** on a network filesystem.  All users of the database must be able to
 58873  ** share memory.
 58874  **
 58875  ** In the default unix and windows implementation, the wal-index is a mmapped
 58876  ** file whose name is the database name with a "-shm" suffix added.  For that
 58877  ** reason, the wal-index is sometimes called the "shm" file.
 58878  **
 58879  ** The wal-index is transient.  After a crash, the wal-index can (and should
 58880  ** be) reconstructed from the original WAL file.  In fact, the VFS is required
 58881  ** to either truncate or zero the header of the wal-index when the last
 58882  ** connection to it closes.  Because the wal-index is transient, it can
 58883  ** use an architecture-specific format; it does not have to be cross-platform.
 58884  ** Hence, unlike the database and WAL file formats which store all values
 58885  ** as big endian, the wal-index can store multi-byte values in the native
 58886  ** byte order of the host computer.
 58887  **
 58888  ** The purpose of the wal-index is to answer this question quickly:  Given
 58889  ** a page number P and a maximum frame index M, return the index of the 
 58890  ** last frame in the wal before frame M for page P in the WAL, or return
 58891  ** NULL if there are no frames for page P in the WAL prior to M.
 58892  **
 58893  ** The wal-index consists of a header region, followed by an one or
 58894  ** more index blocks.  
 58895  **
 58896  ** The wal-index header contains the total number of frames within the WAL
 58897  ** in the mxFrame field.
 58898  **
 58899  ** Each index block except for the first contains information on 
 58900  ** HASHTABLE_NPAGE frames. The first index block contains information on
 58901  ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
 58902  ** HASHTABLE_NPAGE are selected so that together the wal-index header and
 58903  ** first index block are the same size as all other index blocks in the
 58904  ** wal-index.
 58905  **
 58906  ** Each index block contains two sections, a page-mapping that contains the
 58907  ** database page number associated with each wal frame, and a hash-table 
 58908  ** that allows readers to query an index block for a specific page number.
 58909  ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
 58910  ** for the first index block) 32-bit page numbers. The first entry in the 
 58911  ** first index-block contains the database page number corresponding to the
 58912  ** first frame in the WAL file. The first entry in the second index block
 58913  ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
 58914  ** the log, and so on.
 58915  **
 58916  ** The last index block in a wal-index usually contains less than the full
 58917  ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
 58918  ** depending on the contents of the WAL file. This does not change the
 58919  ** allocated size of the page-mapping array - the page-mapping array merely
 58920  ** contains unused entries.
 58921  **
 58922  ** Even without using the hash table, the last frame for page P
 58923  ** can be found by scanning the page-mapping sections of each index block
 58924  ** starting with the last index block and moving toward the first, and
 58925  ** within each index block, starting at the end and moving toward the
 58926  ** beginning.  The first entry that equals P corresponds to the frame
 58927  ** holding the content for that page.
 58928  **
 58929  ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
 58930  ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
 58931  ** hash table for each page number in the mapping section, so the hash 
 58932  ** table is never more than half full.  The expected number of collisions 
 58933  ** prior to finding a match is 1.  Each entry of the hash table is an
 58934  ** 1-based index of an entry in the mapping section of the same
 58935  ** index block.   Let K be the 1-based index of the largest entry in
 58936  ** the mapping section.  (For index blocks other than the last, K will
 58937  ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
 58938  ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
 58939  ** contain a value of 0.
 58940  **
 58941  ** To look for page P in the hash table, first compute a hash iKey on
 58942  ** P as follows:
 58943  **
 58944  **      iKey = (P * 383) % HASHTABLE_NSLOT
 58945  **
 58946  ** Then start scanning entries of the hash table, starting with iKey
 58947  ** (wrapping around to the beginning when the end of the hash table is
 58948  ** reached) until an unused hash slot is found. Let the first unused slot
 58949  ** be at index iUnused.  (iUnused might be less than iKey if there was
 58950  ** wrap-around.) Because the hash table is never more than half full,
 58951  ** the search is guaranteed to eventually hit an unused entry.  Let 
 58952  ** iMax be the value between iKey and iUnused, closest to iUnused,
 58953  ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
 58954  ** no hash slot such that aHash[i]==p) then page P is not in the
 58955  ** current index block.  Otherwise the iMax-th mapping entry of the
 58956  ** current index block corresponds to the last entry that references 
 58957  ** page P.
 58958  **
 58959  ** A hash search begins with the last index block and moves toward the
 58960  ** first index block, looking for entries corresponding to page P.  On
 58961  ** average, only two or three slots in each index block need to be
 58962  ** examined in order to either find the last entry for page P, or to
 58963  ** establish that no such entry exists in the block.  Each index block
 58964  ** holds over 4000 entries.  So two or three index blocks are sufficient
 58965  ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
 58966  ** comparisons (on average) suffice to either locate a frame in the
 58967  ** WAL or to establish that the frame does not exist in the WAL.  This
 58968  ** is much faster than scanning the entire 10MB WAL.
 58969  **
 58970  ** Note that entries are added in order of increasing K.  Hence, one
 58971  ** reader might be using some value K0 and a second reader that started
 58972  ** at a later time (after additional transactions were added to the WAL
 58973  ** and to the wal-index) might be using a different value K1, where K1>K0.
 58974  ** Both readers can use the same hash table and mapping section to get
 58975  ** the correct result.  There may be entries in the hash table with
 58976  ** K>K0 but to the first reader, those entries will appear to be unused
 58977  ** slots in the hash table and so the first reader will get an answer as
 58978  ** if no values greater than K0 had ever been inserted into the hash table
 58979  ** in the first place - which is what reader one wants.  Meanwhile, the
 58980  ** second reader using K1 will see additional values that were inserted
 58981  ** later, which is exactly what reader two wants.  
 58982  **
 58983  ** When a rollback occurs, the value of K is decreased. Hash table entries
 58984  ** that correspond to frames greater than the new K value are removed
 58985  ** from the hash table at this point.
 58986  */
 58987  #ifndef SQLITE_OMIT_WAL
 58988  
 58989  /* #include "wal.h" */
 58990  
 58991  /*
 58992  ** Trace output macros
 58993  */
 58994  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 58995  SQLITE_PRIVATE int sqlite3WalTrace = 0;
 58996  # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
 58997  #else
 58998  # define WALTRACE(X)
 58999  #endif
 59000  
 59001  /*
 59002  ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
 59003  ** places.  The following macros try to make this explicit.
 59004  */
 59005  #if GCC_VESRION>=5004000
 59006  # define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
 59007  # define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
 59008  #else
 59009  # define AtomicLoad(PTR)       (*(PTR))
 59010  # define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
 59011  #endif
 59012  
 59013  /*
 59014  ** The maximum (and only) versions of the wal and wal-index formats
 59015  ** that may be interpreted by this version of SQLite.
 59016  **
 59017  ** If a client begins recovering a WAL file and finds that (a) the checksum
 59018  ** values in the wal-header are correct and (b) the version field is not
 59019  ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
 59020  **
 59021  ** Similarly, if a client successfully reads a wal-index header (i.e. the 
 59022  ** checksum test is successful) and finds that the version field is not
 59023  ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
 59024  ** returns SQLITE_CANTOPEN.
 59025  */
 59026  #define WAL_MAX_VERSION      3007000
 59027  #define WALINDEX_MAX_VERSION 3007000
 59028  
 59029  /*
 59030  ** Index numbers for various locking bytes.   WAL_NREADER is the number
 59031  ** of available reader locks and should be at least 3.  The default
 59032  ** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
 59033  **
 59034  ** Technically, the various VFSes are free to implement these locks however
 59035  ** they see fit.  However, compatibility is encouraged so that VFSes can
 59036  ** interoperate.  The standard implemention used on both unix and windows
 59037  ** is for the index number to indicate a byte offset into the
 59038  ** WalCkptInfo.aLock[] array in the wal-index header.  In other words, all
 59039  ** locks are on the shm file.  The WALINDEX_LOCK_OFFSET constant (which
 59040  ** should be 120) is the location in the shm file for the first locking
 59041  ** byte.
 59042  */
 59043  #define WAL_WRITE_LOCK         0
 59044  #define WAL_ALL_BUT_WRITE      1
 59045  #define WAL_CKPT_LOCK          1
 59046  #define WAL_RECOVER_LOCK       2
 59047  #define WAL_READ_LOCK(I)       (3+(I))
 59048  #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
 59049  
 59050  
 59051  /* Object declarations */
 59052  typedef struct WalIndexHdr WalIndexHdr;
 59053  typedef struct WalIterator WalIterator;
 59054  typedef struct WalCkptInfo WalCkptInfo;
 59055  
 59056  
 59057  /*
 59058  ** The following object holds a copy of the wal-index header content.
 59059  **
 59060  ** The actual header in the wal-index consists of two copies of this
 59061  ** object followed by one instance of the WalCkptInfo object.
 59062  ** For all versions of SQLite through 3.10.0 and probably beyond,
 59063  ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
 59064  ** the total header size is 136 bytes.
 59065  **
 59066  ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
 59067  ** Or it can be 1 to represent a 65536-byte page.  The latter case was
 59068  ** added in 3.7.1 when support for 64K pages was added.  
 59069  */
 59070  struct WalIndexHdr {
 59071    u32 iVersion;                   /* Wal-index version */
 59072    u32 unused;                     /* Unused (padding) field */
 59073    u32 iChange;                    /* Counter incremented each transaction */
 59074    u8 isInit;                      /* 1 when initialized */
 59075    u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
 59076    u16 szPage;                     /* Database page size in bytes. 1==64K */
 59077    u32 mxFrame;                    /* Index of last valid frame in the WAL */
 59078    u32 nPage;                      /* Size of database in pages */
 59079    u32 aFrameCksum[2];             /* Checksum of last frame in log */
 59080    u32 aSalt[2];                   /* Two salt values copied from WAL header */
 59081    u32 aCksum[2];                  /* Checksum over all prior fields */
 59082  };
 59083  
 59084  /*
 59085  ** A copy of the following object occurs in the wal-index immediately
 59086  ** following the second copy of the WalIndexHdr.  This object stores
 59087  ** information used by checkpoint.
 59088  **
 59089  ** nBackfill is the number of frames in the WAL that have been written
 59090  ** back into the database. (We call the act of moving content from WAL to
 59091  ** database "backfilling".)  The nBackfill number is never greater than
 59092  ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
 59093  ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
 59094  ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
 59095  ** mxFrame back to zero when the WAL is reset.
 59096  **
 59097  ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
 59098  ** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
 59099  ** the nBackfillAttempted is set before any backfilling is done and the
 59100  ** nBackfill is only set after all backfilling completes.  So if a checkpoint
 59101  ** crashes, nBackfillAttempted might be larger than nBackfill.  The
 59102  ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
 59103  **
 59104  ** The aLock[] field is a set of bytes used for locking.  These bytes should
 59105  ** never be read or written.
 59106  **
 59107  ** There is one entry in aReadMark[] for each reader lock.  If a reader
 59108  ** holds read-lock K, then the value in aReadMark[K] is no greater than
 59109  ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
 59110  ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
 59111  ** a special case; its value is never used and it exists as a place-holder
 59112  ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
 59113  ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
 59114  ** directly from the database.
 59115  **
 59116  ** The value of aReadMark[K] may only be changed by a thread that
 59117  ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
 59118  ** aReadMark[K] cannot changed while there is a reader is using that mark
 59119  ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
 59120  **
 59121  ** The checkpointer may only transfer frames from WAL to database where
 59122  ** the frame numbers are less than or equal to every aReadMark[] that is
 59123  ** in use (that is, every aReadMark[j] for which there is a corresponding
 59124  ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
 59125  ** largest value and will increase an unused aReadMark[] to mxFrame if there
 59126  ** is not already an aReadMark[] equal to mxFrame.  The exception to the
 59127  ** previous sentence is when nBackfill equals mxFrame (meaning that everything
 59128  ** in the WAL has been backfilled into the database) then new readers
 59129  ** will choose aReadMark[0] which has value 0 and hence such reader will
 59130  ** get all their all content directly from the database file and ignore 
 59131  ** the WAL.
 59132  **
 59133  ** Writers normally append new frames to the end of the WAL.  However,
 59134  ** if nBackfill equals mxFrame (meaning that all WAL content has been
 59135  ** written back into the database) and if no readers are using the WAL
 59136  ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
 59137  ** the writer will first "reset" the WAL back to the beginning and start
 59138  ** writing new content beginning at frame 1.
 59139  **
 59140  ** We assume that 32-bit loads are atomic and so no locks are needed in
 59141  ** order to read from any aReadMark[] entries.
 59142  */
 59143  struct WalCkptInfo {
 59144    u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
 59145    u32 aReadMark[WAL_NREADER];     /* Reader marks */
 59146    u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
 59147    u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
 59148    u32 notUsed0;                   /* Available for future enhancements */
 59149  };
 59150  #define READMARK_NOT_USED  0xffffffff
 59151  
 59152  
 59153  /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
 59154  ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
 59155  ** only support mandatory file-locks, we do not read or write data
 59156  ** from the region of the file on which locks are applied.
 59157  */
 59158  #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
 59159  #define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
 59160  
 59161  /* Size of header before each frame in wal */
 59162  #define WAL_FRAME_HDRSIZE 24
 59163  
 59164  /* Size of write ahead log header, including checksum. */
 59165  #define WAL_HDRSIZE 32
 59166  
 59167  /* WAL magic value. Either this value, or the same value with the least
 59168  ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
 59169  ** big-endian format in the first 4 bytes of a WAL file.
 59170  **
 59171  ** If the LSB is set, then the checksums for each frame within the WAL
 59172  ** file are calculated by treating all data as an array of 32-bit 
 59173  ** big-endian words. Otherwise, they are calculated by interpreting 
 59174  ** all data as 32-bit little-endian words.
 59175  */
 59176  #define WAL_MAGIC 0x377f0682
 59177  
 59178  /*
 59179  ** Return the offset of frame iFrame in the write-ahead log file, 
 59180  ** assuming a database page size of szPage bytes. The offset returned
 59181  ** is to the start of the write-ahead log frame-header.
 59182  */
 59183  #define walFrameOffset(iFrame, szPage) (                               \
 59184    WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
 59185  )
 59186  
 59187  /*
 59188  ** An open write-ahead log file is represented by an instance of the
 59189  ** following object.
 59190  */
 59191  struct Wal {
 59192    sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
 59193    sqlite3_file *pDbFd;       /* File handle for the database file */
 59194    sqlite3_file *pWalFd;      /* File handle for WAL file */
 59195    u32 iCallback;             /* Value to pass to log callback (or 0) */
 59196    i64 mxWalSize;             /* Truncate WAL to this size upon reset */
 59197    int nWiData;               /* Size of array apWiData */
 59198    int szFirstBlock;          /* Size of first block written to WAL file */
 59199    volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
 59200    u32 szPage;                /* Database page size */
 59201    i16 readLock;              /* Which read lock is being held.  -1 for none */
 59202    u8 syncFlags;              /* Flags to use to sync header writes */
 59203    u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
 59204    u8 writeLock;              /* True if in a write transaction */
 59205    u8 ckptLock;               /* True if holding a checkpoint lock */
 59206    u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
 59207    u8 truncateOnCommit;       /* True to truncate WAL file on commit */
 59208    u8 syncHeader;             /* Fsync the WAL header if true */
 59209    u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
 59210    u8 bShmUnreliable;         /* SHM content is read-only and unreliable */
 59211    WalIndexHdr hdr;           /* Wal-index header for current transaction */
 59212    u32 minFrame;              /* Ignore wal frames before this one */
 59213    u32 iReCksum;              /* On commit, recalculate checksums from here */
 59214    const char *zWalName;      /* Name of WAL file */
 59215    u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
 59216  #ifdef SQLITE_DEBUG
 59217    u8 lockError;              /* True if a locking error has occurred */
 59218  #endif
 59219  #ifdef SQLITE_ENABLE_SNAPSHOT
 59220    WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
 59221  #endif
 59222    /* Branch support variables */
 59223    u8 useBranches;
 59224    lmdb *lmdb;
 59225  };
 59226  
 59227  /*
 59228  ** Candidate values for Wal.exclusiveMode.
 59229  */
 59230  #define WAL_NORMAL_MODE     0
 59231  #define WAL_EXCLUSIVE_MODE  1     
 59232  #define WAL_HEAPMEMORY_MODE 2
 59233  
 59234  /*
 59235  ** Possible values for WAL.readOnly
 59236  */
 59237  #define WAL_RDWR        0    /* Normal read/write connection */
 59238  #define WAL_RDONLY      1    /* The WAL file is readonly */
 59239  #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
 59240  
 59241  /*
 59242  ** Each page of the wal-index mapping contains a hash-table made up of
 59243  ** an array of HASHTABLE_NSLOT elements of the following type.
 59244  */
 59245  typedef u16 ht_slot;
 59246  
 59247  /*
 59248  ** This structure is used to implement an iterator that loops through
 59249  ** all frames in the WAL in database page order. Where two or more frames
 59250  ** correspond to the same database page, the iterator visits only the 
 59251  ** frame most recently written to the WAL (in other words, the frame with
 59252  ** the largest index).
 59253  **
 59254  ** The internals of this structure are only accessed by:
 59255  **
 59256  **   walIteratorInit() - Create a new iterator,
 59257  **   walIteratorNext() - Step an iterator,
 59258  **   walIteratorFree() - Free an iterator.
 59259  **
 59260  ** This functionality is used by the checkpoint code (see walCheckpoint()).
 59261  */
 59262  struct WalIterator {
 59263    int iPrior;                     /* Last result returned from the iterator */
 59264    int nSegment;                   /* Number of entries in aSegment[] */
 59265    struct WalSegment {
 59266      int iNext;                    /* Next slot in aIndex[] not yet returned */
 59267      ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
 59268      u32 *aPgno;                   /* Array of page numbers. */
 59269      int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
 59270      int iZero;                    /* Frame number associated with aPgno[0] */
 59271    } aSegment[1];                  /* One for every 32KB page in the wal-index */
 59272  };
 59273  
 59274  /*
 59275  ** Define the parameters of the hash tables in the wal-index file. There
 59276  ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
 59277  ** wal-index.
 59278  **
 59279  ** Changing any of these constants will alter the wal-index format and
 59280  ** create incompatibilities.
 59281  */
 59282  #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
 59283  #define HASHTABLE_HASH_1     383                  /* Should be prime */
 59284  #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
 59285  
 59286  /* 
 59287  ** The block of page numbers associated with the first hash-table in a
 59288  ** wal-index is smaller than usual. This is so that there is a complete
 59289  ** hash-table on each aligned 32KB page of the wal-index.
 59290  */
 59291  #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
 59292  
 59293  /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
 59294  #define WALINDEX_PGSZ   (                                         \
 59295      sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
 59296  )
 59297  
 59298  /*
 59299  ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
 59300  ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
 59301  ** numbered from zero.
 59302  **
 59303  ** If the wal-index is currently smaller the iPage pages then the size
 59304  ** of the wal-index might be increased, but only if it is safe to do
 59305  ** so.  It is safe to enlarge the wal-index if pWal->writeLock is true
 59306  ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
 59307  **
 59308  ** If this call is successful, *ppPage is set to point to the wal-index
 59309  ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
 59310  ** then an SQLite error code is returned and *ppPage is set to 0.
 59311  */
 59312  static SQLITE_NOINLINE int walIndexPageRealloc(
 59313    Wal *pWal,               /* The WAL context */
 59314    int iPage,               /* The page we seek */
 59315    volatile u32 **ppPage    /* Write the page pointer here */
 59316  ){
 59317    int rc = SQLITE_OK;
 59318  
 59319    /* Enlarge the pWal->apWiData[] array if required */
 59320    if( pWal->nWiData<=iPage ){
 59321      int nByte = sizeof(u32*)*(iPage+1);
 59322      volatile u32 **apNew;
 59323      apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
 59324      if( !apNew ){
 59325        *ppPage = 0;
 59326        return SQLITE_NOMEM_BKPT;
 59327      }
 59328      memset((void*)&apNew[pWal->nWiData], 0,
 59329             sizeof(u32*)*(iPage+1-pWal->nWiData));
 59330      pWal->apWiData = apNew;
 59331      pWal->nWiData = iPage+1;
 59332    }
 59333  
 59334    /* Request a pointer to the required page from the VFS */
 59335    assert( pWal->apWiData[iPage]==0 );
 59336    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
 59337      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
 59338      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
 59339    }else{
 59340      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
 59341          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
 59342      );
 59343      assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
 59344      testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
 59345      if( (rc&0xff)==SQLITE_READONLY ){
 59346        pWal->readOnly |= WAL_SHM_RDONLY;
 59347        if( rc==SQLITE_READONLY ){
 59348          rc = SQLITE_OK;
 59349        }
 59350      }
 59351    }
 59352  
 59353    *ppPage = pWal->apWiData[iPage];
 59354    assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
 59355    return rc;
 59356  }
 59357  static int walIndexPage(
 59358    Wal *pWal,               /* The WAL context */
 59359    int iPage,               /* The page we seek */
 59360    volatile u32 **ppPage    /* Write the page pointer here */
 59361  ){
 59362    if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
 59363      return walIndexPageRealloc(pWal, iPage, ppPage);
 59364    }
 59365    return SQLITE_OK;
 59366  }
 59367  
 59368  /*
 59369  ** Return a pointer to the WalCkptInfo structure in the wal-index.
 59370  */
 59371  static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
 59372    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 59373    return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
 59374  }
 59375  
 59376  /*
 59377  ** Return a pointer to the WalIndexHdr structure in the wal-index.
 59378  */
 59379  static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
 59380    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 59381    return (volatile WalIndexHdr*)pWal->apWiData[0];
 59382  }
 59383  
 59384  /*
 59385  ** The argument to this macro must be of type u32. On a little-endian
 59386  ** architecture, it returns the u32 value that results from interpreting
 59387  ** the 4 bytes as a big-endian value. On a big-endian architecture, it
 59388  ** returns the value that would be produced by interpreting the 4 bytes
 59389  ** of the input value as a little-endian integer.
 59390  */
 59391  #define BYTESWAP32(x) ( \
 59392      (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
 59393    + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
 59394  )
 59395  
 59396  /*
 59397  ** Generate or extend an 8 byte checksum based on the data in 
 59398  ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
 59399  ** initial values of 0 and 0 if aIn==NULL).
 59400  **
 59401  ** The checksum is written back into aOut[] before returning.
 59402  **
 59403  ** nByte must be a positive multiple of 8.
 59404  */
 59405  static void walChecksumBytes(
 59406    int nativeCksum, /* True for native byte-order, false for non-native */
 59407    u8 *a,           /* Content to be checksummed */
 59408    int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
 59409    const u32 *aIn,  /* Initial checksum value input */
 59410    u32 *aOut        /* OUT: Final checksum value output */
 59411  ){
 59412    u32 s1, s2;
 59413    u32 *aData = (u32 *)a;
 59414    u32 *aEnd = (u32 *)&a[nByte];
 59415  
 59416    if( aIn ){
 59417      s1 = aIn[0];
 59418      s2 = aIn[1];
 59419    }else{
 59420      s1 = s2 = 0;
 59421    }
 59422  
 59423    assert( nByte>=8 );
 59424    assert( (nByte&0x00000007)==0 );
 59425  
 59426    if( nativeCksum ){
 59427      do {
 59428        s1 += *aData++ + s2;
 59429        s2 += *aData++ + s1;
 59430      }while( aData<aEnd );
 59431    }else{
 59432      do {
 59433        s1 += BYTESWAP32(aData[0]) + s2;
 59434        s2 += BYTESWAP32(aData[1]) + s1;
 59435        aData += 2;
 59436      }while( aData<aEnd );
 59437    }
 59438  
 59439    aOut[0] = s1;
 59440    aOut[1] = s2;
 59441  }
 59442  
 59443  static void walShmBarrier(Wal *pWal){
 59444    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
 59445      sqlite3OsShmBarrier(pWal->pDbFd);
 59446    }
 59447  }
 59448  
 59449  /*
 59450  ** Write the header information in pWal->hdr into the wal-index.
 59451  **
 59452  ** The checksum on pWal->hdr is updated before it is written.
 59453  */
 59454  static void walIndexWriteHdr(Wal *pWal){
 59455    volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
 59456    const int nCksum = offsetof(WalIndexHdr, aCksum);
 59457  
 59458    assert( pWal->writeLock );
 59459    pWal->hdr.isInit = 1;
 59460    pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
 59461    walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
 59462    memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
 59463    walShmBarrier(pWal);
 59464    memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
 59465  }
 59466  
 59467  /*
 59468  ** This function encodes a single frame header and writes it to a buffer
 59469  ** supplied by the caller. A frame-header is made up of a series of 
 59470  ** 4-byte big-endian integers, as follows:
 59471  **
 59472  **     0: Page number.
 59473  **     4: For commit records, the size of the database image in pages 
 59474  **        after the commit. For all other records, zero.
 59475  **     8: Salt-1 (copied from the wal-header)
 59476  **    12: Salt-2 (copied from the wal-header)
 59477  **    16: Checksum-1.
 59478  **    20: Checksum-2.
 59479  */
 59480  static void walEncodeFrame(
 59481    Wal *pWal,                      /* The write-ahead log */
 59482    u32 iPage,                      /* Database page number for frame */
 59483    u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
 59484    u8 *aData,                      /* Pointer to page data */
 59485    u8 *aFrame                      /* OUT: Write encoded frame here */
 59486  ){
 59487    int nativeCksum;                /* True for native byte-order checksums */
 59488    u32 *aCksum = pWal->hdr.aFrameCksum;
 59489    assert( WAL_FRAME_HDRSIZE==24 );
 59490    sqlite3Put4byte(&aFrame[0], iPage);
 59491    sqlite3Put4byte(&aFrame[4], nTruncate);
 59492    if( pWal->iReCksum==0 ){
 59493      memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
 59494  
 59495      nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 59496      walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 59497      walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 59498  
 59499      sqlite3Put4byte(&aFrame[16], aCksum[0]);
 59500      sqlite3Put4byte(&aFrame[20], aCksum[1]);
 59501    }else{
 59502      memset(&aFrame[8], 0, 16);
 59503    }
 59504  }
 59505  
 59506  /*
 59507  ** Check to see if the frame with header in aFrame[] and content
 59508  ** in aData[] is valid.  If it is a valid frame, fill *piPage and
 59509  ** *pnTruncate and return true.  Return if the frame is not valid.
 59510  */
 59511  static int walDecodeFrame(
 59512    Wal *pWal,                      /* The write-ahead log */
 59513    u32 *piPage,                    /* OUT: Database page number for frame */
 59514    u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
 59515    u8 *aData,                      /* Pointer to page data (for checksum) */
 59516    u8 *aFrame                      /* Frame data */
 59517  ){
 59518    int nativeCksum;                /* True for native byte-order checksums */
 59519    u32 *aCksum = pWal->hdr.aFrameCksum;
 59520    u32 pgno;                       /* Page number of the frame */
 59521    assert( WAL_FRAME_HDRSIZE==24 );
 59522  
 59523    /* A frame is only valid if the salt values in the frame-header
 59524    ** match the salt values in the wal-header. 
 59525    */
 59526    if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
 59527      return 0;
 59528    }
 59529  
 59530    /* A frame is only valid if the page number is creater than zero.
 59531    */
 59532    pgno = sqlite3Get4byte(&aFrame[0]);
 59533    if( pgno==0 ){
 59534      return 0;
 59535    }
 59536  
 59537    /* A frame is only valid if a checksum of the WAL header,
 59538    ** all prior frams, the first 16 bytes of this frame-header, 
 59539    ** and the frame-data matches the checksum in the last 8 
 59540    ** bytes of this frame-header.
 59541    */
 59542    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
 59543    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
 59544    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
 59545    if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
 59546     || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
 59547    ){
 59548      /* Checksum failed. */
 59549      return 0;
 59550    }
 59551  
 59552    /* If we reach this point, the frame is valid.  Return the page number
 59553    ** and the new database size.
 59554    */
 59555    *piPage = pgno;
 59556    *pnTruncate = sqlite3Get4byte(&aFrame[4]);
 59557    return 1;
 59558  }
 59559  
 59560  
 59561  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 59562  /*
 59563  ** Names of locks.  This routine is used to provide debugging output and is not
 59564  ** a part of an ordinary build.
 59565  */
 59566  static const char *walLockName(int lockIdx){
 59567    if( lockIdx==WAL_WRITE_LOCK ){
 59568      return "WRITE-LOCK";
 59569    }else if( lockIdx==WAL_CKPT_LOCK ){
 59570      return "CKPT-LOCK";
 59571    }else if( lockIdx==WAL_RECOVER_LOCK ){
 59572      return "RECOVER-LOCK";
 59573    }else{
 59574      static char zName[15];
 59575      sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
 59576                       lockIdx-WAL_READ_LOCK(0));
 59577      return zName;
 59578    }
 59579  }
 59580  #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
 59581      
 59582  
 59583  /*
 59584  ** Set or release locks on the WAL.  Locks are either shared or exclusive.
 59585  ** A lock cannot be moved directly between shared and exclusive - it must go
 59586  ** through the unlocked state first.
 59587  **
 59588  ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
 59589  */
 59590  static int walLockShared(Wal *pWal, int lockIdx){
 59591    int rc;
 59592    if( pWal->exclusiveMode ) return SQLITE_OK;
 59593    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 59594                          SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
 59595    WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
 59596              walLockName(lockIdx), rc ? "failed" : "ok"));
 59597    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 59598    return rc;
 59599  }
 59600  static void walUnlockShared(Wal *pWal, int lockIdx){
 59601    if( pWal->exclusiveMode ) return;
 59602    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
 59603                           SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
 59604    WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
 59605  }
 59606  static int walLockExclusive(Wal *pWal, int lockIdx, int n){
 59607    int rc;
 59608    if( pWal->exclusiveMode ) return SQLITE_OK;
 59609    rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 59610                          SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
 59611    WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
 59612              walLockName(lockIdx), n, rc ? "failed" : "ok"));
 59613    VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
 59614    return rc;
 59615  }
 59616  static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
 59617    if( pWal->exclusiveMode ) return;
 59618    (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
 59619                           SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
 59620    WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
 59621               walLockName(lockIdx), n));
 59622  }
 59623  
 59624  /*
 59625  ** Compute a hash on a page number.  The resulting hash value must land
 59626  ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
 59627  ** the hash to the next value in the event of a collision.
 59628  */
 59629  static int walHash(u32 iPage){
 59630    assert( iPage>0 );
 59631    assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
 59632    return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
 59633  }
 59634  static int walNextHash(int iPriorHash){
 59635    return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
 59636  }
 59637  
 59638  /*
 59639  ** An instance of the WalHashLoc object is used to describe the location
 59640  ** of a page hash table in the wal-index.  This becomes the return value
 59641  ** from walHashGet().
 59642  */
 59643  typedef struct WalHashLoc WalHashLoc;
 59644  struct WalHashLoc {
 59645    volatile ht_slot *aHash;  /* Start of the wal-index hash table */
 59646    volatile u32 *aPgno;      /* aPgno[1] is the page of first frame indexed */
 59647    u32 iZero;                /* One less than the frame number of first indexed*/
 59648  };
 59649  
 59650  /* 
 59651  ** Return pointers to the hash table and page number array stored on
 59652  ** page iHash of the wal-index. The wal-index is broken into 32KB pages
 59653  ** numbered starting from 0.
 59654  **
 59655  ** Set output variable pLoc->aHash to point to the start of the hash table
 59656  ** in the wal-index file. Set pLoc->iZero to one less than the frame 
 59657  ** number of the first frame indexed by this hash table. If a
 59658  ** slot in the hash table is set to N, it refers to frame number 
 59659  ** (pLoc->iZero+N) in the log.
 59660  **
 59661  ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
 59662  ** first frame indexed by the hash table, frame (pLoc->iZero+1).
 59663  */
 59664  static int walHashGet(
 59665    Wal *pWal,                      /* WAL handle */
 59666    int iHash,                      /* Find the iHash'th table */
 59667    WalHashLoc *pLoc                /* OUT: Hash table location */
 59668  ){
 59669    int rc;                         /* Return code */
 59670  
 59671    rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
 59672    assert( rc==SQLITE_OK || iHash>0 );
 59673  
 59674    if( rc==SQLITE_OK ){
 59675      pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
 59676      if( iHash==0 ){
 59677        pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
 59678        pLoc->iZero = 0;
 59679      }else{
 59680        pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
 59681      }
 59682      pLoc->aPgno = &pLoc->aPgno[-1];
 59683    }
 59684    return rc;
 59685  }
 59686  
 59687  /*
 59688  ** Return the number of the wal-index page that contains the hash-table
 59689  ** and page-number array that contain entries corresponding to WAL frame
 59690  ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
 59691  ** are numbered starting from 0.
 59692  */
 59693  static int walFramePage(u32 iFrame){
 59694    int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
 59695    assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
 59696         && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
 59697         && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
 59698         && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
 59699         && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
 59700    );
 59701    return iHash;
 59702  }
 59703  
 59704  /*
 59705  ** Return the page number associated with frame iFrame in this WAL.
 59706  */
 59707  static u32 walFramePgno(Wal *pWal, u32 iFrame){
 59708    int iHash = walFramePage(iFrame);
 59709    if( iHash==0 ){
 59710      return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
 59711    }
 59712    return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
 59713  }
 59714  
 59715  /*
 59716  ** Remove entries from the hash table that point to WAL slots greater
 59717  ** than pWal->hdr.mxFrame.
 59718  **
 59719  ** This function is called whenever pWal->hdr.mxFrame is decreased due
 59720  ** to a rollback or savepoint.
 59721  **
 59722  ** At most only the hash table containing pWal->hdr.mxFrame needs to be
 59723  ** updated.  Any later hash tables will be automatically cleared when
 59724  ** pWal->hdr.mxFrame advances to the point where those hash tables are
 59725  ** actually needed.
 59726  */
 59727  static void walCleanupHash(Wal *pWal){
 59728    WalHashLoc sLoc;                /* Hash table location */
 59729    int iLimit = 0;                 /* Zero values greater than this */
 59730    int nByte;                      /* Number of bytes to zero in aPgno[] */
 59731    int i;                          /* Used to iterate through aHash[] */
 59732  
 59733    assert( pWal->writeLock );
 59734    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
 59735    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
 59736    testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
 59737  
 59738    if( pWal->hdr.mxFrame==0 ) return;
 59739  
 59740    /* Obtain pointers to the hash-table and page-number array containing 
 59741    ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
 59742    ** that the page said hash-table and array reside on is already mapped.
 59743    */
 59744    assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
 59745    assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
 59746    walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
 59747  
 59748    /* Zero all hash-table entries that correspond to frame numbers greater
 59749    ** than pWal->hdr.mxFrame.
 59750    */
 59751    iLimit = pWal->hdr.mxFrame - sLoc.iZero;
 59752    assert( iLimit>0 );
 59753    for(i=0; i<HASHTABLE_NSLOT; i++){
 59754      if( sLoc.aHash[i]>iLimit ){
 59755        sLoc.aHash[i] = 0;
 59756      }
 59757    }
 59758    
 59759    /* Zero the entries in the aPgno array that correspond to frames with
 59760    ** frame numbers greater than pWal->hdr.mxFrame. 
 59761    */
 59762    nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
 59763    memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
 59764  
 59765  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 59766    /* Verify that the every entry in the mapping region is still reachable
 59767    ** via the hash table even after the cleanup.
 59768    */
 59769    if( iLimit ){
 59770      int j;           /* Loop counter */
 59771      int iKey;        /* Hash key */
 59772      for(j=1; j<=iLimit; j++){
 59773        for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
 59774          if( sLoc.aHash[iKey]==j ) break;
 59775        }
 59776        assert( sLoc.aHash[iKey]==j );
 59777      }
 59778    }
 59779  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 59780  }
 59781  
 59782  
 59783  /*
 59784  ** Set an entry in the wal-index that will map database page number
 59785  ** pPage into WAL frame iFrame.
 59786  */
 59787  static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 59788    int rc;                         /* Return code */
 59789    WalHashLoc sLoc;                /* Wal-index hash table location */
 59790  
 59791    rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
 59792  
 59793    /* Assuming the wal-index file was successfully mapped, populate the
 59794    ** page number array and hash table entry.
 59795    */
 59796    if( rc==SQLITE_OK ){
 59797      int iKey;                     /* Hash table key */
 59798      int idx;                      /* Value to write to hash-table slot */
 59799      int nCollide;                 /* Number of hash collisions */
 59800  
 59801      idx = iFrame - sLoc.iZero;
 59802      assert( idx <= HASHTABLE_NSLOT/2 + 1 );
 59803      
 59804      /* If this is the first entry to be added to this hash-table, zero the
 59805      ** entire hash table and aPgno[] array before proceeding. 
 59806      */
 59807      if( idx==1 ){
 59808        int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
 59809                                 - (u8 *)&sLoc.aPgno[1]);
 59810        memset((void*)&sLoc.aPgno[1], 0, nByte);
 59811      }
 59812  
 59813      /* If the entry in aPgno[] is already set, then the previous writer
 59814      ** must have exited unexpectedly in the middle of a transaction (after
 59815      ** writing one or more dirty pages to the WAL to free up memory). 
 59816      ** Remove the remnants of that writers uncommitted transaction from 
 59817      ** the hash-table before writing any new entries.
 59818      */
 59819      if( sLoc.aPgno[idx] ){
 59820        walCleanupHash(pWal);
 59821        assert( !sLoc.aPgno[idx] );
 59822      }
 59823  
 59824      /* Write the aPgno[] array entry and the hash-table slot. */
 59825      nCollide = idx;
 59826      for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
 59827        if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
 59828      }
 59829      sLoc.aPgno[idx] = iPage;
 59830      sLoc.aHash[iKey] = (ht_slot)idx;
 59831  
 59832  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 59833      /* Verify that the number of entries in the hash table exactly equals
 59834      ** the number of entries in the mapping region.
 59835      */
 59836      {
 59837        int i;           /* Loop counter */
 59838        int nEntry = 0;  /* Number of entries in the hash table */
 59839        for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
 59840        assert( nEntry==idx );
 59841      }
 59842  
 59843      /* Verify that the every entry in the mapping region is reachable
 59844      ** via the hash table.  This turns out to be a really, really expensive
 59845      ** thing to check, so only do this occasionally - not on every
 59846      ** iteration.
 59847      */
 59848      if( (idx&0x3ff)==0 ){
 59849        int i;           /* Loop counter */
 59850        for(i=1; i<=idx; i++){
 59851          for(iKey=walHash(sLoc.aPgno[i]);
 59852              sLoc.aHash[iKey];
 59853              iKey=walNextHash(iKey)){
 59854            if( sLoc.aHash[iKey]==i ) break;
 59855          }
 59856          assert( sLoc.aHash[iKey]==i );
 59857        }
 59858      }
 59859  #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
 59860    }
 59861  
 59862  
 59863    return rc;
 59864  }
 59865  
 59866  
 59867  /*
 59868  ** Recover the wal-index by reading the write-ahead log file. 
 59869  **
 59870  ** This routine first tries to establish an exclusive lock on the
 59871  ** wal-index to prevent other threads/processes from doing anything
 59872  ** with the WAL or wal-index while recovery is running.  The
 59873  ** WAL_RECOVER_LOCK is also held so that other threads will know
 59874  ** that this thread is running recovery.  If unable to establish
 59875  ** the necessary locks, this routine returns SQLITE_BUSY.
 59876  */
 59877  static int walIndexRecover(Wal *pWal){
 59878    int rc;                         /* Return Code */
 59879    i64 nSize;                      /* Size of log file */
 59880    u32 aFrameCksum[2] = {0, 0};
 59881    int iLock;                      /* Lock offset to lock for checkpoint */
 59882  
 59883    /* Obtain an exclusive lock on all byte in the locking range not already
 59884    ** locked by the caller. The caller is guaranteed to have locked the
 59885    ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
 59886    ** If successful, the same bytes that are locked here are unlocked before
 59887    ** this function returns.
 59888    */
 59889    assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
 59890    assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
 59891    assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
 59892    assert( pWal->writeLock );
 59893    iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
 59894    rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
 59895    if( rc==SQLITE_OK ){
 59896      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 59897      if( rc!=SQLITE_OK ){
 59898        walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
 59899      }
 59900    }
 59901    if( rc ){
 59902      return rc;
 59903    }
 59904  
 59905    WALTRACE(("WAL%p: recovery begin...\n", pWal));
 59906  
 59907    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 59908  
 59909    rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
 59910    if( rc!=SQLITE_OK ){
 59911      goto recovery_error;
 59912    }
 59913  
 59914    if( nSize>WAL_HDRSIZE ){
 59915      u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
 59916      u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
 59917      int szFrame;                  /* Number of bytes in buffer aFrame[] */
 59918      u8 *aData;                    /* Pointer to data part of aFrame buffer */
 59919      int iFrame;                   /* Index of last frame read */
 59920      i64 iOffset;                  /* Next offset to read from log file */
 59921      int szPage;                   /* Page size according to the log */
 59922      u32 magic;                    /* Magic value read from WAL header */
 59923      u32 version;                  /* Magic value read from WAL header */
 59924      int isValid;                  /* True if this frame is valid */
 59925  
 59926      /* Read in the WAL header. */
 59927      rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
 59928      if( rc!=SQLITE_OK ){
 59929        goto recovery_error;
 59930      }
 59931  
 59932      /* If the database page size is not a power of two, or is greater than
 59933      ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
 59934      ** data. Similarly, if the 'magic' value is invalid, ignore the whole
 59935      ** WAL file.
 59936      */
 59937      magic = sqlite3Get4byte(&aBuf[0]);
 59938      szPage = sqlite3Get4byte(&aBuf[8]);
 59939      if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
 59940       || szPage&(szPage-1) 
 59941       || szPage>SQLITE_MAX_PAGE_SIZE 
 59942       || szPage<512 
 59943      ){
 59944        goto finished;
 59945      }
 59946      pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
 59947      pWal->szPage = szPage;
 59948      pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
 59949      memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
 59950  
 59951      /* Verify that the WAL header checksum is correct */
 59952      walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
 59953          aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
 59954      );
 59955      if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
 59956       || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
 59957      ){
 59958        goto finished;
 59959      }
 59960  
 59961      /* Verify that the version number on the WAL format is one that
 59962      ** are able to understand */
 59963      version = sqlite3Get4byte(&aBuf[4]);
 59964      if( version!=WAL_MAX_VERSION ){
 59965        rc = SQLITE_CANTOPEN_BKPT;
 59966        goto finished;
 59967      }
 59968  
 59969      /* Malloc a buffer to read frames into. */
 59970      szFrame = szPage + WAL_FRAME_HDRSIZE;
 59971      aFrame = (u8 *)sqlite3_malloc64(szFrame);
 59972      if( !aFrame ){
 59973        rc = SQLITE_NOMEM_BKPT;
 59974        goto recovery_error;
 59975      }
 59976      aData = &aFrame[WAL_FRAME_HDRSIZE];
 59977  
 59978      /* Read all frames from the log file. */
 59979      iFrame = 0;
 59980      for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
 59981        u32 pgno;                   /* Database page number for frame */
 59982        u32 nTruncate;              /* dbsize field from frame header */
 59983  
 59984        /* Read and decode the next log frame. */
 59985        iFrame++;
 59986        rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
 59987        if( rc!=SQLITE_OK ) break;
 59988        isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
 59989        if( !isValid ) break;
 59990        rc = walIndexAppend(pWal, iFrame, pgno);
 59991        if( rc!=SQLITE_OK ) break;
 59992  
 59993        /* If nTruncate is non-zero, this is a commit record. */
 59994        if( nTruncate ){
 59995          pWal->hdr.mxFrame = iFrame;
 59996          pWal->hdr.nPage = nTruncate;
 59997          pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 59998          testcase( szPage<=32768 );
 59999          testcase( szPage>=65536 );
 60000          aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
 60001          aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
 60002        }
 60003      }
 60004  
 60005      sqlite3_free(aFrame);
 60006    }
 60007  
 60008  finished:
 60009    if( rc==SQLITE_OK ){
 60010      volatile WalCkptInfo *pInfo;
 60011      int i;
 60012      pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
 60013      pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
 60014      walIndexWriteHdr(pWal);
 60015  
 60016      /* Reset the checkpoint-header. This is safe because this thread is 
 60017      ** currently holding locks that exclude all other readers, writers and
 60018      ** checkpointers.
 60019      */
 60020      pInfo = walCkptInfo(pWal);
 60021      pInfo->nBackfill = 0;
 60022      pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
 60023      pInfo->aReadMark[0] = 0;
 60024      for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 60025      if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
 60026  
 60027      /* If more than one frame was recovered from the log file, report an
 60028      ** event via sqlite3_log(). This is to help with identifying performance
 60029      ** problems caused by applications routinely shutting down without
 60030      ** checkpointing the log file.
 60031      */
 60032      if( pWal->hdr.nPage ){
 60033        sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
 60034            "recovered %d frames from WAL file %s",
 60035            pWal->hdr.mxFrame, pWal->zWalName
 60036        );
 60037      }
 60038    }
 60039  
 60040  recovery_error:
 60041    WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
 60042    walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
 60043    walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 60044    return rc;
 60045  }
 60046  
 60047  /*
 60048  ** Close an open wal-index.
 60049  */
 60050  static void walIndexClose(Wal *pWal, int isDelete){
 60051    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
 60052      int i;
 60053      for(i=0; i<pWal->nWiData; i++){
 60054        sqlite3_free((void *)pWal->apWiData[i]);
 60055        pWal->apWiData[i] = 0;
 60056      }
 60057    }
 60058    if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
 60059      sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
 60060    }
 60061  }
 60062  
 60063  /* 
 60064  ** Open a connection to the WAL file zWalName. The database file must 
 60065  ** already be opened on connection pDbFd. The buffer that zWalName points
 60066  ** to must remain valid for the lifetime of the returned Wal* handle.
 60067  **
 60068  ** A SHARED lock should be held on the database file when this function
 60069  ** is called. The purpose of this SHARED lock is to prevent any other
 60070  ** client from unlinking the WAL or wal-index file. If another process
 60071  ** were to do this just after this client opened one of these files, the
 60072  ** system would be badly broken.
 60073  **
 60074  ** If the log file is successfully opened, SQLITE_OK is returned and 
 60075  ** *ppWal is set to point to a new WAL handle. If an error occurs,
 60076  ** an SQLite error code is returned and *ppWal is left unmodified.
 60077  */
 60078  SQLITE_PRIVATE int sqlite3WalOpen(
 60079    sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
 60080    sqlite3_file *pDbFd,            /* The open database file */
 60081    const char *zWalName,           /* Name of the WAL file */
 60082    int bNoShm,                     /* True to run in heap-memory mode */
 60083    i64 mxWalSize,                  /* Truncate WAL to this size on reset */
 60084    lmdb *lmdb,                     /* Pointer to LMDB struct */
 60085    Wal **ppWal                     /* OUT: Allocated Wal handle */
 60086  ){
 60087    int rc;                         /* Return Code */
 60088    Wal *pRet;                      /* Object to allocate and return */
 60089    int flags;                      /* Flags passed to OsOpen() */
 60090  
 60091    BRANCHTRACE("sqlite3WalOpen %s", zWalName);
 60092  
 60093    assert( zWalName && zWalName[0] );
 60094    assert( pDbFd );
 60095  
 60096    /* In the amalgamation, the os_unix.c and os_win.c source files come before
 60097    ** this source file.  Verify that the #defines of the locking byte offsets
 60098    ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
 60099    ** For that matter, if the lock offset ever changes from its initial design
 60100    ** value of 120, we need to know that so there is an assert() to check it.
 60101    */
 60102    assert( 120==WALINDEX_LOCK_OFFSET );
 60103    assert( 136==WALINDEX_HDR_SIZE );
 60104  #ifdef WIN_SHM_BASE
 60105    assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
 60106  #endif
 60107  #ifdef UNIX_SHM_BASE
 60108    assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
 60109  #endif
 60110  
 60111  
 60112    /* Allocate an instance of struct Wal to return. */
 60113    *ppWal = 0;
 60114    pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
 60115    if( !pRet ){
 60116      return SQLITE_NOMEM_BKPT;
 60117    }
 60118  
 60119    if( lmdb ){
 60120      BRANCHTRACE("sqlite3WalOpen - using LMDB");
 60121      pRet->useBranches = 1;
 60122      pRet->lmdb = lmdb;
 60123      rc = SQLITE_OK;
 60124      goto wal_open_ok;
 60125    }
 60126  
 60127    pRet->pVfs = pVfs;
 60128    pRet->pWalFd = (sqlite3_file *)&pRet[1];
 60129    pRet->pDbFd = pDbFd;
 60130    pRet->readLock = -1;
 60131    pRet->mxWalSize = mxWalSize;
 60132    pRet->zWalName = zWalName;
 60133    pRet->syncHeader = 1;
 60134    pRet->padToSectorBoundary = 1;
 60135    pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
 60136  
 60137    /* Open file handle on the write-ahead log file. */
 60138    flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
 60139    rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
 60140    if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
 60141      pRet->readOnly = WAL_RDONLY;
 60142    }
 60143  
 60144    if( rc!=SQLITE_OK ){
 60145      walIndexClose(pRet, 0);
 60146      sqlite3OsClose(pRet->pWalFd);
 60147      sqlite3_free(pRet);
 60148    }else{
 60149      int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
 60150      if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
 60151      if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
 60152        pRet->padToSectorBoundary = 0;
 60153      }
 60154  wal_open_ok:
 60155      *ppWal = pRet;
 60156      WALTRACE(("WAL%d: opened\n", pRet));
 60157    }
 60158    return rc;
 60159  }
 60160  
 60161  /*
 60162  ** Change the size to which the WAL file is trucated on each reset.
 60163  */
 60164  SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
 60165    if( pWal ) pWal->mxWalSize = iLimit;
 60166  }
 60167  
 60168  /*
 60169  ** Find the smallest page number out of all pages held in the WAL that
 60170  ** has not been returned by any prior invocation of this method on the
 60171  ** same WalIterator object.   Write into *piFrame the frame index where
 60172  ** that page was last written into the WAL.  Write into *piPage the page
 60173  ** number.
 60174  **
 60175  ** Return 0 on success.  If there are no pages in the WAL with a page
 60176  ** number larger than *piPage, then return 1.
 60177  */
 60178  static int walIteratorNext(
 60179    WalIterator *p,               /* Iterator */
 60180    u32 *piPage,                  /* OUT: The page number of the next page */
 60181    u32 *piFrame                  /* OUT: Wal frame index of next page */
 60182  ){
 60183    u32 iMin;                     /* Result pgno must be greater than iMin */
 60184    u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
 60185    int i;                        /* For looping through segments */
 60186  
 60187    iMin = p->iPrior;
 60188    assert( iMin<0xffffffff );
 60189    for(i=p->nSegment-1; i>=0; i--){
 60190      struct WalSegment *pSegment = &p->aSegment[i];
 60191      while( pSegment->iNext<pSegment->nEntry ){
 60192        u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
 60193        if( iPg>iMin ){
 60194          if( iPg<iRet ){
 60195            iRet = iPg;
 60196            *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
 60197          }
 60198          break;
 60199        }
 60200        pSegment->iNext++;
 60201      }
 60202    }
 60203  
 60204    *piPage = p->iPrior = iRet;
 60205    return (iRet==0xFFFFFFFF);
 60206  }
 60207  
 60208  /*
 60209  ** This function merges two sorted lists into a single sorted list.
 60210  **
 60211  ** aLeft[] and aRight[] are arrays of indices.  The sort key is
 60212  ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
 60213  ** is guaranteed for all J<K:
 60214  **
 60215  **        aContent[aLeft[J]] < aContent[aLeft[K]]
 60216  **        aContent[aRight[J]] < aContent[aRight[K]]
 60217  **
 60218  ** This routine overwrites aRight[] with a new (probably longer) sequence
 60219  ** of indices such that the aRight[] contains every index that appears in
 60220  ** either aLeft[] or the old aRight[] and such that the second condition
 60221  ** above is still met.
 60222  **
 60223  ** The aContent[aLeft[X]] values will be unique for all X.  And the
 60224  ** aContent[aRight[X]] values will be unique too.  But there might be
 60225  ** one or more combinations of X and Y such that
 60226  **
 60227  **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
 60228  **
 60229  ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
 60230  */
 60231  static void walMerge(
 60232    const u32 *aContent,            /* Pages in wal - keys for the sort */
 60233    ht_slot *aLeft,                 /* IN: Left hand input list */
 60234    int nLeft,                      /* IN: Elements in array *paLeft */
 60235    ht_slot **paRight,              /* IN/OUT: Right hand input list */
 60236    int *pnRight,                   /* IN/OUT: Elements in *paRight */
 60237    ht_slot *aTmp                   /* Temporary buffer */
 60238  ){
 60239    int iLeft = 0;                  /* Current index in aLeft */
 60240    int iRight = 0;                 /* Current index in aRight */
 60241    int iOut = 0;                   /* Current index in output buffer */
 60242    int nRight = *pnRight;
 60243    ht_slot *aRight = *paRight;
 60244  
 60245    assert( nLeft>0 && nRight>0 );
 60246    while( iRight<nRight || iLeft<nLeft ){
 60247      ht_slot logpage;
 60248      Pgno dbpage;
 60249  
 60250      if( (iLeft<nLeft) 
 60251       && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
 60252      ){
 60253        logpage = aLeft[iLeft++];
 60254      }else{
 60255        logpage = aRight[iRight++];
 60256      }
 60257      dbpage = aContent[logpage];
 60258  
 60259      aTmp[iOut++] = logpage;
 60260      if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
 60261  
 60262      assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
 60263      assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
 60264    }
 60265  
 60266    *paRight = aLeft;
 60267    *pnRight = iOut;
 60268    memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
 60269  }
 60270  
 60271  /*
 60272  ** Sort the elements in list aList using aContent[] as the sort key.
 60273  ** Remove elements with duplicate keys, preferring to keep the
 60274  ** larger aList[] values.
 60275  **
 60276  ** The aList[] entries are indices into aContent[].  The values in
 60277  ** aList[] are to be sorted so that for all J<K:
 60278  **
 60279  **      aContent[aList[J]] < aContent[aList[K]]
 60280  **
 60281  ** For any X and Y such that
 60282  **
 60283  **      aContent[aList[X]] == aContent[aList[Y]]
 60284  **
 60285  ** Keep the larger of the two values aList[X] and aList[Y] and discard
 60286  ** the smaller.
 60287  */
 60288  static void walMergesort(
 60289    const u32 *aContent,            /* Pages in wal */
 60290    ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
 60291    ht_slot *aList,                 /* IN/OUT: List to sort */
 60292    int *pnList                     /* IN/OUT: Number of elements in aList[] */
 60293  ){
 60294    struct Sublist {
 60295      int nList;                    /* Number of elements in aList */
 60296      ht_slot *aList;               /* Pointer to sub-list content */
 60297    };
 60298  
 60299    const int nList = *pnList;      /* Size of input list */
 60300    int nMerge = 0;                 /* Number of elements in list aMerge */
 60301    ht_slot *aMerge = 0;            /* List to be merged */
 60302    int iList;                      /* Index into input list */
 60303    u32 iSub = 0;                   /* Index into aSub array */
 60304    struct Sublist aSub[13];        /* Array of sub-lists */
 60305  
 60306    memset(aSub, 0, sizeof(aSub));
 60307    assert( nList<=HASHTABLE_NPAGE && nList>0 );
 60308    assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
 60309  
 60310    for(iList=0; iList<nList; iList++){
 60311      nMerge = 1;
 60312      aMerge = &aList[iList];
 60313      for(iSub=0; iList & (1<<iSub); iSub++){
 60314        struct Sublist *p;
 60315        assert( iSub<ArraySize(aSub) );
 60316        p = &aSub[iSub];
 60317        assert( p->aList && p->nList<=(1<<iSub) );
 60318        assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
 60319        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 60320      }
 60321      aSub[iSub].aList = aMerge;
 60322      aSub[iSub].nList = nMerge;
 60323    }
 60324  
 60325    for(iSub++; iSub<ArraySize(aSub); iSub++){
 60326      if( nList & (1<<iSub) ){
 60327        struct Sublist *p;
 60328        assert( iSub<ArraySize(aSub) );
 60329        p = &aSub[iSub];
 60330        assert( p->nList<=(1<<iSub) );
 60331        assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
 60332        walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
 60333      }
 60334    }
 60335    assert( aMerge==aList );
 60336    *pnList = nMerge;
 60337  
 60338  #ifdef SQLITE_DEBUG
 60339    {
 60340      int i;
 60341      for(i=1; i<*pnList; i++){
 60342        assert( aContent[aList[i]] > aContent[aList[i-1]] );
 60343      }
 60344    }
 60345  #endif
 60346  }
 60347  
 60348  /* 
 60349  ** Free an iterator allocated by walIteratorInit().
 60350  */
 60351  static void walIteratorFree(WalIterator *p){
 60352    sqlite3_free(p);
 60353  }
 60354  
 60355  /*
 60356  ** Construct a WalInterator object that can be used to loop over all 
 60357  ** pages in the WAL following frame nBackfill in ascending order. Frames
 60358  ** nBackfill or earlier may be included - excluding them is an optimization
 60359  ** only. The caller must hold the checkpoint lock.
 60360  **
 60361  ** On success, make *pp point to the newly allocated WalInterator object
 60362  ** return SQLITE_OK. Otherwise, return an error code. If this routine
 60363  ** returns an error, the value of *pp is undefined.
 60364  **
 60365  ** The calling routine should invoke walIteratorFree() to destroy the
 60366  ** WalIterator object when it has finished with it.
 60367  */
 60368  static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
 60369    WalIterator *p;                 /* Return value */
 60370    int nSegment;                   /* Number of segments to merge */
 60371    u32 iLast;                      /* Last frame in log */
 60372    int nByte;                      /* Number of bytes to allocate */
 60373    int i;                          /* Iterator variable */
 60374    ht_slot *aTmp;                  /* Temp space used by merge-sort */
 60375    int rc = SQLITE_OK;             /* Return Code */
 60376  
 60377    /* This routine only runs while holding the checkpoint lock. And
 60378    ** it only runs if there is actually content in the log (mxFrame>0).
 60379    */
 60380    assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
 60381    iLast = pWal->hdr.mxFrame;
 60382  
 60383    /* Allocate space for the WalIterator object. */
 60384    nSegment = walFramePage(iLast) + 1;
 60385    nByte = sizeof(WalIterator) 
 60386          + (nSegment-1)*sizeof(struct WalSegment)
 60387          + iLast*sizeof(ht_slot);
 60388    p = (WalIterator *)sqlite3_malloc64(nByte);
 60389    if( !p ){
 60390      return SQLITE_NOMEM_BKPT;
 60391    }
 60392    memset(p, 0, nByte);
 60393    p->nSegment = nSegment;
 60394  
 60395    /* Allocate temporary space used by the merge-sort routine. This block
 60396    ** of memory will be freed before this function returns.
 60397    */
 60398    aTmp = (ht_slot *)sqlite3_malloc64(
 60399        sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
 60400    );
 60401    if( !aTmp ){
 60402      rc = SQLITE_NOMEM_BKPT;
 60403    }
 60404  
 60405    for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
 60406      WalHashLoc sLoc;
 60407  
 60408      rc = walHashGet(pWal, i, &sLoc);
 60409      if( rc==SQLITE_OK ){
 60410        int j;                      /* Counter variable */
 60411        int nEntry;                 /* Number of entries in this segment */
 60412        ht_slot *aIndex;            /* Sorted index for this segment */
 60413  
 60414        sLoc.aPgno++;
 60415        if( (i+1)==nSegment ){
 60416          nEntry = (int)(iLast - sLoc.iZero);
 60417        }else{
 60418          nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
 60419        }
 60420        aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
 60421        sLoc.iZero++;
 60422    
 60423        for(j=0; j<nEntry; j++){
 60424          aIndex[j] = (ht_slot)j;
 60425        }
 60426        walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
 60427        p->aSegment[i].iZero = sLoc.iZero;
 60428        p->aSegment[i].nEntry = nEntry;
 60429        p->aSegment[i].aIndex = aIndex;
 60430        p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
 60431      }
 60432    }
 60433    sqlite3_free(aTmp);
 60434  
 60435    if( rc!=SQLITE_OK ){
 60436      walIteratorFree(p);
 60437      p = 0;
 60438    }
 60439    *pp = p;
 60440    return rc;
 60441  }
 60442  
 60443  /*
 60444  ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
 60445  ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
 60446  ** busy-handler function. Invoke it and retry the lock until either the
 60447  ** lock is successfully obtained or the busy-handler returns 0.
 60448  */
 60449  static int walBusyLock(
 60450    Wal *pWal,                      /* WAL connection */
 60451    int (*xBusy)(void*),            /* Function to call when busy */
 60452    void *pBusyArg,                 /* Context argument for xBusyHandler */
 60453    int lockIdx,                    /* Offset of first byte to lock */
 60454    int n                           /* Number of bytes to lock */
 60455  ){
 60456    int rc;
 60457    do {
 60458      rc = walLockExclusive(pWal, lockIdx, n);
 60459    }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
 60460    return rc;
 60461  }
 60462  
 60463  /*
 60464  ** The cache of the wal-index header must be valid to call this function.
 60465  ** Return the page-size in bytes used by the database.
 60466  */
 60467  static int walPagesize(Wal *pWal){
 60468    return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 60469  }
 60470  
 60471  /*
 60472  ** The following is guaranteed when this function is called:
 60473  **
 60474  **   a) the WRITER lock is held,
 60475  **   b) the entire log file has been checkpointed, and
 60476  **   c) any existing readers are reading exclusively from the database
 60477  **      file - there are no readers that may attempt to read a frame from
 60478  **      the log file.
 60479  **
 60480  ** This function updates the shared-memory structures so that the next
 60481  ** client to write to the database (which may be this one) does so by
 60482  ** writing frames into the start of the log file.
 60483  **
 60484  ** The value of parameter salt1 is used as the aSalt[1] value in the 
 60485  ** new wal-index header. It should be passed a pseudo-random value (i.e. 
 60486  ** one obtained from sqlite3_randomness()).
 60487  */
 60488  static void walRestartHdr(Wal *pWal, u32 salt1){
 60489    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 60490    int i;                          /* Loop counter */
 60491    u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
 60492    pWal->nCkpt++;
 60493    pWal->hdr.mxFrame = 0;
 60494    sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
 60495    memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
 60496    walIndexWriteHdr(pWal);
 60497    pInfo->nBackfill = 0;
 60498    pInfo->nBackfillAttempted = 0;
 60499    pInfo->aReadMark[1] = 0;
 60500    for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
 60501    assert( pInfo->aReadMark[0]==0 );
 60502  }
 60503  
 60504  /*
 60505  ** Copy as much content as we can from the WAL back into the database file
 60506  ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
 60507  **
 60508  ** The amount of information copies from WAL to database might be limited
 60509  ** by active readers.  This routine will never overwrite a database page
 60510  ** that a concurrent reader might be using.
 60511  **
 60512  ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
 60513  ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
 60514  ** checkpoints are always run by a background thread or background 
 60515  ** process, foreground threads will never block on a lengthy fsync call.
 60516  **
 60517  ** Fsync is called on the WAL before writing content out of the WAL and
 60518  ** into the database.  This ensures that if the new content is persistent
 60519  ** in the WAL and can be recovered following a power-loss or hard reset.
 60520  **
 60521  ** Fsync is also called on the database file if (and only if) the entire
 60522  ** WAL content is copied into the database file.  This second fsync makes
 60523  ** it safe to delete the WAL since the new content will persist in the
 60524  ** database file.
 60525  **
 60526  ** This routine uses and updates the nBackfill field of the wal-index header.
 60527  ** This is the only routine that will increase the value of nBackfill.  
 60528  ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
 60529  ** its value.)
 60530  **
 60531  ** The caller must be holding sufficient locks to ensure that no other
 60532  ** checkpoint is running (in any other thread or process) at the same
 60533  ** time.
 60534  */
 60535  static int walCheckpoint(
 60536    Wal *pWal,                      /* Wal connection */
 60537    sqlite3 *db,                    /* Check for interrupts on this handle */
 60538    int eMode,                      /* One of PASSIVE, FULL or RESTART */
 60539    int (*xBusy)(void*),            /* Function to call when busy */
 60540    void *pBusyArg,                 /* Context argument for xBusyHandler */
 60541    int sync_flags,                 /* Flags for OsSync() (or 0) */
 60542    u8 *zBuf                        /* Temporary buffer to use */
 60543  ){
 60544    int rc = SQLITE_OK;             /* Return code */
 60545    int szPage;                     /* Database page-size */
 60546    WalIterator *pIter = 0;         /* Wal iterator context */
 60547    u32 iDbpage = 0;                /* Next database page to write */
 60548    u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
 60549    u32 mxSafeFrame;                /* Max frame that can be backfilled */
 60550    u32 mxPage;                     /* Max database page to write */
 60551    int i;                          /* Loop counter */
 60552    volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
 60553  
 60554    szPage = walPagesize(pWal);
 60555    testcase( szPage<=32768 );
 60556    testcase( szPage>=65536 );
 60557    pInfo = walCkptInfo(pWal);
 60558    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
 60559  
 60560      /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
 60561      ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
 60562      assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
 60563  
 60564      /* Compute in mxSafeFrame the index of the last frame of the WAL that is
 60565      ** safe to write into the database.  Frames beyond mxSafeFrame might
 60566      ** overwrite database pages that are in use by active readers and thus
 60567      ** cannot be backfilled from the WAL.
 60568      */
 60569      mxSafeFrame = pWal->hdr.mxFrame;
 60570      mxPage = pWal->hdr.nPage;
 60571      for(i=1; i<WAL_NREADER; i++){
 60572        /* Thread-sanitizer reports that the following is an unsafe read,
 60573        ** as some other thread may be in the process of updating the value
 60574        ** of the aReadMark[] slot. The assumption here is that if that is
 60575        ** happening, the other client may only be increasing the value,
 60576        ** not decreasing it. So assuming either that either the "old" or
 60577        ** "new" version of the value is read, and not some arbitrary value
 60578        ** that would never be written by a real client, things are still 
 60579        ** safe.  */
 60580        u32 y = pInfo->aReadMark[i];
 60581        if( mxSafeFrame>y ){
 60582          assert( y<=pWal->hdr.mxFrame );
 60583          rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
 60584          if( rc==SQLITE_OK ){
 60585            pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
 60586            walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 60587          }else if( rc==SQLITE_BUSY ){
 60588            mxSafeFrame = y;
 60589            xBusy = 0;
 60590          }else{
 60591            goto walcheckpoint_out;
 60592          }
 60593        }
 60594      }
 60595  
 60596      /* Allocate the iterator */
 60597      if( pInfo->nBackfill<mxSafeFrame ){
 60598        rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
 60599        assert( rc==SQLITE_OK || pIter==0 );
 60600      }
 60601  
 60602      if( pIter
 60603       && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
 60604      ){
 60605        u32 nBackfill = pInfo->nBackfill;
 60606  
 60607        pInfo->nBackfillAttempted = mxSafeFrame;
 60608  
 60609        /* Sync the WAL to disk */
 60610        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
 60611  
 60612        /* If the database may grow as a result of this checkpoint, hint
 60613        ** about the eventual size of the db file to the VFS layer.
 60614        */
 60615        if( rc==SQLITE_OK ){
 60616          i64 nReq = ((i64)mxPage * szPage);
 60617          i64 nSize;                    /* Current size of database file */
 60618          rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
 60619          if( rc==SQLITE_OK && nSize<nReq ){
 60620            sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
 60621          }
 60622        }
 60623  
 60624  
 60625        /* Iterate through the contents of the WAL, copying data to the db file */
 60626        while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
 60627          i64 iOffset;
 60628          assert( walFramePgno(pWal, iFrame)==iDbpage );
 60629          if( db->u1.isInterrupted ){
 60630            rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
 60631            break;
 60632          }
 60633          if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
 60634            continue;
 60635          }
 60636          iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
 60637          /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
 60638          rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
 60639          if( rc!=SQLITE_OK ) break;
 60640          iOffset = (iDbpage-1)*(i64)szPage;
 60641          testcase( IS_BIG_INT(iOffset) );
 60642          rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
 60643          if( rc!=SQLITE_OK ) break;
 60644        }
 60645  
 60646        /* If work was actually accomplished... */
 60647        if( rc==SQLITE_OK ){
 60648          if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
 60649            i64 szDb = pWal->hdr.nPage*(i64)szPage;
 60650            testcase( IS_BIG_INT(szDb) );
 60651            rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
 60652            if( rc==SQLITE_OK ){
 60653              rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
 60654            }
 60655          }
 60656          if( rc==SQLITE_OK ){
 60657            pInfo->nBackfill = mxSafeFrame;
 60658          }
 60659        }
 60660  
 60661        /* Release the reader lock held while backfilling */
 60662        walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
 60663      }
 60664  
 60665      if( rc==SQLITE_BUSY ){
 60666        /* Reset the return code so as not to report a checkpoint failure
 60667        ** just because there are active readers.  */
 60668        rc = SQLITE_OK;
 60669      }
 60670    }
 60671  
 60672    /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
 60673    ** entire wal file has been copied into the database file, then block 
 60674    ** until all readers have finished using the wal file. This ensures that 
 60675    ** the next process to write to the database restarts the wal file.
 60676    */
 60677    if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 60678      assert( pWal->writeLock );
 60679      if( pInfo->nBackfill<pWal->hdr.mxFrame ){
 60680        rc = SQLITE_BUSY;
 60681      }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
 60682        u32 salt1;
 60683        sqlite3_randomness(4, &salt1);
 60684        assert( pInfo->nBackfill==pWal->hdr.mxFrame );
 60685        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
 60686        if( rc==SQLITE_OK ){
 60687          if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
 60688            /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
 60689            ** SQLITE_CHECKPOINT_RESTART with the addition that it also
 60690            ** truncates the log file to zero bytes just prior to a
 60691            ** successful return.
 60692            **
 60693            ** In theory, it might be safe to do this without updating the
 60694            ** wal-index header in shared memory, as all subsequent reader or
 60695            ** writer clients should see that the entire log file has been
 60696            ** checkpointed and behave accordingly. This seems unsafe though,
 60697            ** as it would leave the system in a state where the contents of
 60698            ** the wal-index header do not match the contents of the 
 60699            ** file-system. To avoid this, update the wal-index header to
 60700            ** indicate that the log file contains zero valid frames.  */
 60701            walRestartHdr(pWal, salt1);
 60702            rc = sqlite3OsTruncate(pWal->pWalFd, 0);
 60703          }
 60704          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 60705        }
 60706      }
 60707    }
 60708  
 60709   walcheckpoint_out:
 60710    walIteratorFree(pIter);
 60711    return rc;
 60712  }
 60713  
 60714  /*
 60715  ** If the WAL file is currently larger than nMax bytes in size, truncate
 60716  ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
 60717  */
 60718  static void walLimitSize(Wal *pWal, i64 nMax){
 60719    i64 sz;
 60720    int rx;
 60721    sqlite3BeginBenignMalloc();
 60722    rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
 60723    if( rx==SQLITE_OK && (sz > nMax ) ){
 60724      rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
 60725    }
 60726    sqlite3EndBenignMalloc();
 60727    if( rx ){
 60728      sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
 60729    }
 60730  }
 60731  
 60732  /*
 60733  ** Close a connection to a log file.
 60734  */
 60735  SQLITE_PRIVATE int sqlite3WalClose(
 60736    Wal *pWal,                      /* Wal to close */
 60737    sqlite3 *db,                    /* For interrupt flag */
 60738    int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
 60739    int nBuf,
 60740    u8 *zBuf                        /* Buffer of at least nBuf bytes */
 60741  ){
 60742    int rc = SQLITE_OK;
 60743    BRANCHTRACE("sqlite3WalClose");
 60744    if( pWal ){
 60745      int isDelete = 0;             /* True to unlink wal and wal-index files */
 60746  
 60747      if( pWal->useBranches ){
 60748        sqlite3_free(pWal);
 60749        return SQLITE_OK;
 60750      }
 60751  
 60752      /* If an EXCLUSIVE lock can be obtained on the database file (using the
 60753      ** ordinary, rollback-mode locking methods, this guarantees that the
 60754      ** connection associated with this log file is the only connection to
 60755      ** the database. In this case checkpoint the database and unlink both
 60756      ** the wal and wal-index files.
 60757      **
 60758      ** The EXCLUSIVE lock is not released before returning.
 60759      */
 60760      if( zBuf!=0
 60761       && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
 60762      ){
 60763        if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
 60764          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
 60765        }
 60766        rc = sqlite3WalCheckpoint(pWal, db, 
 60767            SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
 60768        );
 60769        if( rc==SQLITE_OK ){
 60770          int bPersist = -1;
 60771          sqlite3OsFileControlHint(
 60772              pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
 60773          );
 60774          if( bPersist!=1 ){
 60775            /* Try to delete the WAL file if the checkpoint completed and
 60776            ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
 60777            ** mode (!bPersist) */
 60778            isDelete = 1;
 60779          }else if( pWal->mxWalSize>=0 ){
 60780            /* Try to truncate the WAL file to zero bytes if the checkpoint
 60781            ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
 60782            ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
 60783            ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
 60784            ** to zero bytes as truncating to the journal_size_limit might
 60785            ** leave a corrupt WAL file on disk. */
 60786            walLimitSize(pWal, 0);
 60787          }
 60788        }
 60789      }
 60790  
 60791      walIndexClose(pWal, isDelete);
 60792      sqlite3OsClose(pWal->pWalFd);
 60793      if( isDelete ){
 60794        sqlite3BeginBenignMalloc();
 60795        sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
 60796        sqlite3EndBenignMalloc();
 60797      }
 60798      WALTRACE(("WAL%p: closed\n", pWal));
 60799      sqlite3_free((void *)pWal->apWiData);
 60800      sqlite3_free(pWal);
 60801    }
 60802    return rc;
 60803  }
 60804  
 60805  /*
 60806  ** Try to read the wal-index header.  Return 0 on success and 1 if
 60807  ** there is a problem.
 60808  **
 60809  ** The wal-index is in shared memory.  Another thread or process might
 60810  ** be writing the header at the same time this procedure is trying to
 60811  ** read it, which might result in inconsistency.  A dirty read is detected
 60812  ** by verifying that both copies of the header are the same and also by
 60813  ** a checksum on the header.
 60814  **
 60815  ** If and only if the read is consistent and the header is different from
 60816  ** pWal->hdr, then pWal->hdr is updated to the content of the new header
 60817  ** and *pChanged is set to 1.
 60818  **
 60819  ** If the checksum cannot be verified return non-zero. If the header
 60820  ** is read successfully and the checksum verified, return zero.
 60821  */
 60822  static int walIndexTryHdr(Wal *pWal, int *pChanged){
 60823    u32 aCksum[2];                  /* Checksum on the header content */
 60824    WalIndexHdr h1, h2;             /* Two copies of the header content */
 60825    WalIndexHdr volatile *aHdr;     /* Header in shared memory */
 60826  
 60827    /* The first page of the wal-index must be mapped at this point. */
 60828    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 60829  
 60830    /* Read the header. This might happen concurrently with a write to the
 60831    ** same area of shared memory on a different CPU in a SMP,
 60832    ** meaning it is possible that an inconsistent snapshot is read
 60833    ** from the file. If this happens, return non-zero.
 60834    **
 60835    ** There are two copies of the header at the beginning of the wal-index.
 60836    ** When reading, read [0] first then [1].  Writes are in the reverse order.
 60837    ** Memory barriers are used to prevent the compiler or the hardware from
 60838    ** reordering the reads and writes.
 60839    */
 60840    aHdr = walIndexHdr(pWal);
 60841    memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
 60842    walShmBarrier(pWal);
 60843    memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
 60844  
 60845    if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
 60846      return 1;   /* Dirty read */
 60847    }  
 60848    if( h1.isInit==0 ){
 60849      return 1;   /* Malformed header - probably all zeros */
 60850    }
 60851    walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
 60852    if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
 60853      return 1;   /* Checksum does not match */
 60854    }
 60855  
 60856    if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
 60857      *pChanged = 1;
 60858      memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
 60859      pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
 60860      testcase( pWal->szPage<=32768 );
 60861      testcase( pWal->szPage>=65536 );
 60862    }
 60863  
 60864    /* The header was successfully read. Return zero. */
 60865    return 0;
 60866  }
 60867  
 60868  /*
 60869  ** This is the value that walTryBeginRead returns when it needs to
 60870  ** be retried.
 60871  */
 60872  #define WAL_RETRY  (-1)
 60873  
 60874  /*
 60875  ** Read the wal-index header from the wal-index and into pWal->hdr.
 60876  ** If the wal-header appears to be corrupt, try to reconstruct the
 60877  ** wal-index from the WAL before returning.
 60878  **
 60879  ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
 60880  ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
 60881  ** to 0.
 60882  **
 60883  ** If the wal-index header is successfully read, return SQLITE_OK. 
 60884  ** Otherwise an SQLite error code.
 60885  */
 60886  static int walIndexReadHdr(Wal *pWal, int *pChanged){
 60887    int rc;                         /* Return code */
 60888    int badHdr;                     /* True if a header read failed */
 60889    volatile u32 *page0;            /* Chunk of wal-index containing header */
 60890  
 60891    /* Ensure that page 0 of the wal-index (the page that contains the 
 60892    ** wal-index header) is mapped. Return early if an error occurs here.
 60893    */
 60894    assert( pChanged );
 60895    rc = walIndexPage(pWal, 0, &page0);
 60896    if( rc!=SQLITE_OK ){
 60897      assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
 60898      if( rc==SQLITE_READONLY_CANTINIT ){
 60899        /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
 60900        ** was openable but is not writable, and this thread is unable to
 60901        ** confirm that another write-capable connection has the shared-memory
 60902        ** open, and hence the content of the shared-memory is unreliable,
 60903        ** since the shared-memory might be inconsistent with the WAL file
 60904        ** and there is no writer on hand to fix it. */
 60905        assert( page0==0 );
 60906        assert( pWal->writeLock==0 );
 60907        assert( pWal->readOnly & WAL_SHM_RDONLY );
 60908        pWal->bShmUnreliable = 1;
 60909        pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
 60910        *pChanged = 1;
 60911      }else{
 60912        return rc; /* Any other non-OK return is just an error */
 60913      }
 60914    }else{
 60915      /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
 60916      ** is zero, which prevents the SHM from growing */
 60917      testcase( page0!=0 );
 60918    }
 60919    assert( page0!=0 || pWal->writeLock==0 );
 60920  
 60921    /* If the first page of the wal-index has been mapped, try to read the
 60922    ** wal-index header immediately, without holding any lock. This usually
 60923    ** works, but may fail if the wal-index header is corrupt or currently 
 60924    ** being modified by another thread or process.
 60925    */
 60926    badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
 60927  
 60928    /* If the first attempt failed, it might have been due to a race
 60929    ** with a writer.  So get a WRITE lock and try again.
 60930    */
 60931    assert( badHdr==0 || pWal->writeLock==0 );
 60932    if( badHdr ){
 60933      if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
 60934        if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
 60935          walUnlockShared(pWal, WAL_WRITE_LOCK);
 60936          rc = SQLITE_READONLY_RECOVERY;
 60937        }
 60938      }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
 60939        pWal->writeLock = 1;
 60940        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
 60941          badHdr = walIndexTryHdr(pWal, pChanged);
 60942          if( badHdr ){
 60943            /* If the wal-index header is still malformed even while holding
 60944            ** a WRITE lock, it can only mean that the header is corrupted and
 60945            ** needs to be reconstructed.  So run recovery to do exactly that.
 60946            */
 60947            rc = walIndexRecover(pWal);
 60948            *pChanged = 1;
 60949          }
 60950        }
 60951        pWal->writeLock = 0;
 60952        walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 60953      }
 60954    }
 60955  
 60956    /* If the header is read successfully, check the version number to make
 60957    ** sure the wal-index was not constructed with some future format that
 60958    ** this version of SQLite cannot understand.
 60959    */
 60960    if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
 60961      rc = SQLITE_CANTOPEN_BKPT;
 60962    }
 60963    if( pWal->bShmUnreliable ){
 60964      if( rc!=SQLITE_OK ){
 60965        walIndexClose(pWal, 0);
 60966        pWal->bShmUnreliable = 0;
 60967        assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
 60968        /* walIndexRecover() might have returned SHORT_READ if a concurrent
 60969        ** writer truncated the WAL out from under it.  If that happens, it
 60970        ** indicates that a writer has fixed the SHM file for us, so retry */
 60971        if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
 60972      }
 60973      pWal->exclusiveMode = WAL_NORMAL_MODE;
 60974    }
 60975  
 60976    return rc;
 60977  }
 60978  
 60979  /*
 60980  ** Open a transaction in a connection where the shared-memory is read-only
 60981  ** and where we cannot verify that there is a separate write-capable connection
 60982  ** on hand to keep the shared-memory up-to-date with the WAL file.
 60983  **
 60984  ** This can happen, for example, when the shared-memory is implemented by
 60985  ** memory-mapping a *-shm file, where a prior writer has shut down and
 60986  ** left the *-shm file on disk, and now the present connection is trying
 60987  ** to use that database but lacks write permission on the *-shm file.
 60988  ** Other scenarios are also possible, depending on the VFS implementation.
 60989  **
 60990  ** Precondition:
 60991  **
 60992  **    The *-wal file has been read and an appropriate wal-index has been
 60993  **    constructed in pWal->apWiData[] using heap memory instead of shared
 60994  **    memory. 
 60995  **
 60996  ** If this function returns SQLITE_OK, then the read transaction has
 60997  ** been successfully opened. In this case output variable (*pChanged) 
 60998  ** is set to true before returning if the caller should discard the
 60999  ** contents of the page cache before proceeding. Or, if it returns 
 61000  ** WAL_RETRY, then the heap memory wal-index has been discarded and 
 61001  ** the caller should retry opening the read transaction from the 
 61002  ** beginning (including attempting to map the *-shm file). 
 61003  **
 61004  ** If an error occurs, an SQLite error code is returned.
 61005  */
 61006  static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
 61007    i64 szWal;                      /* Size of wal file on disk in bytes */
 61008    i64 iOffset;                    /* Current offset when reading wal file */
 61009    u8 aBuf[WAL_HDRSIZE];           /* Buffer to load WAL header into */
 61010    u8 *aFrame = 0;                 /* Malloc'd buffer to load entire frame */
 61011    int szFrame;                    /* Number of bytes in buffer aFrame[] */
 61012    u8 *aData;                      /* Pointer to data part of aFrame buffer */
 61013    volatile void *pDummy;          /* Dummy argument for xShmMap */
 61014    int rc;                         /* Return code */
 61015    u32 aSaveCksum[2];              /* Saved copy of pWal->hdr.aFrameCksum */
 61016  
 61017    assert( pWal->bShmUnreliable );
 61018    assert( pWal->readOnly & WAL_SHM_RDONLY );
 61019    assert( pWal->nWiData>0 && pWal->apWiData[0] );
 61020  
 61021    /* Take WAL_READ_LOCK(0). This has the effect of preventing any
 61022    ** writers from running a checkpoint, but does not stop them
 61023    ** from running recovery.  */
 61024    rc = walLockShared(pWal, WAL_READ_LOCK(0));
 61025    if( rc!=SQLITE_OK ){
 61026      if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
 61027      goto begin_unreliable_shm_out;
 61028    }
 61029    pWal->readLock = 0;
 61030  
 61031    /* Check to see if a separate writer has attached to the shared-memory area,
 61032    ** thus making the shared-memory "reliable" again.  Do this by invoking
 61033    ** the xShmMap() routine of the VFS and looking to see if the return
 61034    ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
 61035    **
 61036    ** If the shared-memory is now "reliable" return WAL_RETRY, which will
 61037    ** cause the heap-memory WAL-index to be discarded and the actual
 61038    ** shared memory to be used in its place.
 61039    **
 61040    ** This step is important because, even though this connection is holding
 61041    ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
 61042    ** have already checkpointed the WAL file and, while the current
 61043    ** is active, wrap the WAL and start overwriting frames that this
 61044    ** process wants to use.
 61045    **
 61046    ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
 61047    ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
 61048    ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
 61049    ** even if some external agent does a "chmod" to make the shared-memory
 61050    ** writable by us, until sqlite3OsShmUnmap() has been called.
 61051    ** This is a requirement on the VFS implementation.
 61052     */
 61053    rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
 61054    assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
 61055    if( rc!=SQLITE_READONLY_CANTINIT ){
 61056      rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
 61057      goto begin_unreliable_shm_out;
 61058    }
 61059  
 61060    /* We reach this point only if the real shared-memory is still unreliable.
 61061    ** Assume the in-memory WAL-index substitute is correct and load it
 61062    ** into pWal->hdr.
 61063    */
 61064    memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
 61065  
 61066    /* Make sure some writer hasn't come in and changed the WAL file out
 61067    ** from under us, then disconnected, while we were not looking.
 61068    */
 61069    rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
 61070    if( rc!=SQLITE_OK ){
 61071      goto begin_unreliable_shm_out;
 61072    }
 61073    if( szWal<WAL_HDRSIZE ){
 61074      /* If the wal file is too small to contain a wal-header and the
 61075      ** wal-index header has mxFrame==0, then it must be safe to proceed
 61076      ** reading the database file only. However, the page cache cannot
 61077      ** be trusted, as a read/write connection may have connected, written
 61078      ** the db, run a checkpoint, truncated the wal file and disconnected
 61079      ** since this client's last read transaction.  */
 61080      *pChanged = 1;
 61081      rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
 61082      goto begin_unreliable_shm_out;
 61083    }
 61084  
 61085    /* Check the salt keys at the start of the wal file still match. */
 61086    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
 61087    if( rc!=SQLITE_OK ){
 61088      goto begin_unreliable_shm_out;
 61089    }
 61090    if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
 61091      /* Some writer has wrapped the WAL file while we were not looking.
 61092      ** Return WAL_RETRY which will cause the in-memory WAL-index to be
 61093      ** rebuilt. */
 61094      rc = WAL_RETRY;
 61095      goto begin_unreliable_shm_out;
 61096    }
 61097  
 61098    /* Allocate a buffer to read frames into */
 61099    szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
 61100    aFrame = (u8 *)sqlite3_malloc64(szFrame);
 61101    if( aFrame==0 ){
 61102      rc = SQLITE_NOMEM_BKPT;
 61103      goto begin_unreliable_shm_out;
 61104    }
 61105    aData = &aFrame[WAL_FRAME_HDRSIZE];
 61106  
 61107    /* Check to see if a complete transaction has been appended to the
 61108    ** wal file since the heap-memory wal-index was created. If so, the
 61109    ** heap-memory wal-index is discarded and WAL_RETRY returned to
 61110    ** the caller.  */
 61111    aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
 61112    aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
 61113    for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage); 
 61114        iOffset+szFrame<=szWal; 
 61115        iOffset+=szFrame
 61116    ){
 61117      u32 pgno;                   /* Database page number for frame */
 61118      u32 nTruncate;              /* dbsize field from frame header */
 61119  
 61120      /* Read and decode the next log frame. */
 61121      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
 61122      if( rc!=SQLITE_OK ) break;
 61123      if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
 61124  
 61125      /* If nTruncate is non-zero, then a complete transaction has been
 61126      ** appended to this wal file. Set rc to WAL_RETRY and break out of
 61127      ** the loop.  */
 61128      if( nTruncate ){
 61129        rc = WAL_RETRY;
 61130        break;
 61131      }
 61132    }
 61133    pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
 61134    pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
 61135  
 61136   begin_unreliable_shm_out:
 61137    sqlite3_free(aFrame);
 61138    if( rc!=SQLITE_OK ){
 61139      int i;
 61140      for(i=0; i<pWal->nWiData; i++){
 61141        sqlite3_free((void*)pWal->apWiData[i]);
 61142        pWal->apWiData[i] = 0;
 61143      }
 61144      pWal->bShmUnreliable = 0;
 61145      sqlite3WalEndReadTransaction(pWal);
 61146      *pChanged = 1;
 61147    }
 61148    return rc;
 61149  }
 61150  
 61151  /*
 61152  ** Attempt to start a read transaction.  This might fail due to a race or
 61153  ** other transient condition.  When that happens, it returns WAL_RETRY to
 61154  ** indicate to the caller that it is safe to retry immediately.
 61155  **
 61156  ** On success return SQLITE_OK.  On a permanent failure (such an
 61157  ** I/O error or an SQLITE_BUSY because another process is running
 61158  ** recovery) return a positive error code.
 61159  **
 61160  ** The useWal parameter is true to force the use of the WAL and disable
 61161  ** the case where the WAL is bypassed because it has been completely
 61162  ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
 61163  ** to make a copy of the wal-index header into pWal->hdr.  If the 
 61164  ** wal-index header has changed, *pChanged is set to 1 (as an indication 
 61165  ** to the caller that the local page cache is obsolete and needs to be 
 61166  ** flushed.)  When useWal==1, the wal-index header is assumed to already
 61167  ** be loaded and the pChanged parameter is unused.
 61168  **
 61169  ** The caller must set the cnt parameter to the number of prior calls to
 61170  ** this routine during the current read attempt that returned WAL_RETRY.
 61171  ** This routine will start taking more aggressive measures to clear the
 61172  ** race conditions after multiple WAL_RETRY returns, and after an excessive
 61173  ** number of errors will ultimately return SQLITE_PROTOCOL.  The
 61174  ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
 61175  ** and is not honoring the locking protocol.  There is a vanishingly small
 61176  ** chance that SQLITE_PROTOCOL could be returned because of a run of really
 61177  ** bad luck when there is lots of contention for the wal-index, but that
 61178  ** possibility is so small that it can be safely neglected, we believe.
 61179  **
 61180  ** On success, this routine obtains a read lock on 
 61181  ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
 61182  ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
 61183  ** that means the Wal does not hold any read lock.  The reader must not
 61184  ** access any database page that is modified by a WAL frame up to and
 61185  ** including frame number aReadMark[pWal->readLock].  The reader will
 61186  ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
 61187  ** Or if pWal->readLock==0, then the reader will ignore the WAL
 61188  ** completely and get all content directly from the database file.
 61189  ** If the useWal parameter is 1 then the WAL will never be ignored and
 61190  ** this routine will always set pWal->readLock>0 on success.
 61191  ** When the read transaction is completed, the caller must release the
 61192  ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
 61193  **
 61194  ** This routine uses the nBackfill and aReadMark[] fields of the header
 61195  ** to select a particular WAL_READ_LOCK() that strives to let the
 61196  ** checkpoint process do as much work as possible.  This routine might
 61197  ** update values of the aReadMark[] array in the header, but if it does
 61198  ** so it takes care to hold an exclusive lock on the corresponding
 61199  ** WAL_READ_LOCK() while changing values.
 61200  */
 61201  static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
 61202    volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
 61203    u32 mxReadMark;                 /* Largest aReadMark[] value */
 61204    int mxI;                        /* Index of largest aReadMark[] value */
 61205    int i;                          /* Loop counter */
 61206    int rc = SQLITE_OK;             /* Return code  */
 61207    u32 mxFrame;                    /* Wal frame to lock to */
 61208  
 61209    assert( pWal->readLock<0 );     /* Not currently locked */
 61210  
 61211    /* useWal may only be set for read/write connections */
 61212    assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
 61213  
 61214    /* Take steps to avoid spinning forever if there is a protocol error.
 61215    **
 61216    ** Circumstances that cause a RETRY should only last for the briefest
 61217    ** instances of time.  No I/O or other system calls are done while the
 61218    ** locks are held, so the locks should not be held for very long. But 
 61219    ** if we are unlucky, another process that is holding a lock might get
 61220    ** paged out or take a page-fault that is time-consuming to resolve, 
 61221    ** during the few nanoseconds that it is holding the lock.  In that case,
 61222    ** it might take longer than normal for the lock to free.
 61223    **
 61224    ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
 61225    ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
 61226    ** is more of a scheduler yield than an actual delay.  But on the 10th
 61227    ** an subsequent retries, the delays start becoming longer and longer, 
 61228    ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
 61229    ** The total delay time before giving up is less than 10 seconds.
 61230    */
 61231    if( cnt>5 ){
 61232      int nDelay = 1;                      /* Pause time in microseconds */
 61233      if( cnt>100 ){
 61234        VVA_ONLY( pWal->lockError = 1; )
 61235        return SQLITE_PROTOCOL;
 61236      }
 61237      if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
 61238      sqlite3OsSleep(pWal->pVfs, nDelay);
 61239    }
 61240  
 61241    if( !useWal ){
 61242      assert( rc==SQLITE_OK );
 61243      if( pWal->bShmUnreliable==0 ){
 61244        rc = walIndexReadHdr(pWal, pChanged);
 61245      }
 61246      if( rc==SQLITE_BUSY ){
 61247        /* If there is not a recovery running in another thread or process
 61248        ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
 61249        ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
 61250        ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
 61251        ** would be technically correct.  But the race is benign since with
 61252        ** WAL_RETRY this routine will be called again and will probably be
 61253        ** right on the second iteration.
 61254        */
 61255        if( pWal->apWiData[0]==0 ){
 61256          /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
 61257          ** We assume this is a transient condition, so return WAL_RETRY. The
 61258          ** xShmMap() implementation used by the default unix and win32 VFS 
 61259          ** modules may return SQLITE_BUSY due to a race condition in the 
 61260          ** code that determines whether or not the shared-memory region 
 61261          ** must be zeroed before the requested page is returned.
 61262          */
 61263          rc = WAL_RETRY;
 61264        }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
 61265          walUnlockShared(pWal, WAL_RECOVER_LOCK);
 61266          rc = WAL_RETRY;
 61267        }else if( rc==SQLITE_BUSY ){
 61268          rc = SQLITE_BUSY_RECOVERY;
 61269        }
 61270      }
 61271      if( rc!=SQLITE_OK ){
 61272        return rc;
 61273      }
 61274      else if( pWal->bShmUnreliable ){
 61275        return walBeginShmUnreliable(pWal, pChanged);
 61276      }
 61277    }
 61278  
 61279    assert( pWal->nWiData>0 );
 61280    assert( pWal->apWiData[0]!=0 );
 61281    pInfo = walCkptInfo(pWal);
 61282    if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
 61283  #ifdef SQLITE_ENABLE_SNAPSHOT
 61284     && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
 61285  #endif
 61286    ){
 61287      /* The WAL has been completely backfilled (or it is empty).
 61288      ** and can be safely ignored.
 61289      */
 61290      rc = walLockShared(pWal, WAL_READ_LOCK(0));
 61291      walShmBarrier(pWal);
 61292      if( rc==SQLITE_OK ){
 61293        if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
 61294          /* It is not safe to allow the reader to continue here if frames
 61295          ** may have been appended to the log before READ_LOCK(0) was obtained.
 61296          ** When holding READ_LOCK(0), the reader ignores the entire log file,
 61297          ** which implies that the database file contains a trustworthy
 61298          ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
 61299          ** happening, this is usually correct.
 61300          **
 61301          ** However, if frames have been appended to the log (or if the log 
 61302          ** is wrapped and written for that matter) before the READ_LOCK(0)
 61303          ** is obtained, that is not necessarily true. A checkpointer may
 61304          ** have started to backfill the appended frames but crashed before
 61305          ** it finished. Leaving a corrupt image in the database file.
 61306          */
 61307          walUnlockShared(pWal, WAL_READ_LOCK(0));
 61308          return WAL_RETRY;
 61309        }
 61310        pWal->readLock = 0;
 61311        return SQLITE_OK;
 61312      }else if( rc!=SQLITE_BUSY ){
 61313        return rc;
 61314      }
 61315    }
 61316  
 61317    /* If we get this far, it means that the reader will want to use
 61318    ** the WAL to get at content from recent commits.  The job now is
 61319    ** to select one of the aReadMark[] entries that is closest to
 61320    ** but not exceeding pWal->hdr.mxFrame and lock that entry.
 61321    */
 61322    mxReadMark = 0;
 61323    mxI = 0;
 61324    mxFrame = pWal->hdr.mxFrame;
 61325  #ifdef SQLITE_ENABLE_SNAPSHOT
 61326    if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
 61327      mxFrame = pWal->pSnapshot->mxFrame;
 61328    }
 61329  #endif
 61330    for(i=1; i<WAL_NREADER; i++){
 61331      u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
 61332      if( mxReadMark<=thisMark && thisMark<=mxFrame ){
 61333        assert( thisMark!=READMARK_NOT_USED );
 61334        mxReadMark = thisMark;
 61335        mxI = i;
 61336      }
 61337    }
 61338    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
 61339     && (mxReadMark<mxFrame || mxI==0)
 61340    ){
 61341      for(i=1; i<WAL_NREADER; i++){
 61342        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
 61343        if( rc==SQLITE_OK ){
 61344          mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
 61345          mxI = i;
 61346          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
 61347          break;
 61348        }else if( rc!=SQLITE_BUSY ){
 61349          return rc;
 61350        }
 61351      }
 61352    }
 61353    if( mxI==0 ){
 61354      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
 61355      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
 61356    }
 61357  
 61358    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
 61359    if( rc ){
 61360      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
 61361    }
 61362    /* Now that the read-lock has been obtained, check that neither the
 61363    ** value in the aReadMark[] array or the contents of the wal-index
 61364    ** header have changed.
 61365    **
 61366    ** It is necessary to check that the wal-index header did not change
 61367    ** between the time it was read and when the shared-lock was obtained
 61368    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
 61369    ** that the log file may have been wrapped by a writer, or that frames
 61370    ** that occur later in the log than pWal->hdr.mxFrame may have been
 61371    ** copied into the database by a checkpointer. If either of these things
 61372    ** happened, then reading the database with the current value of
 61373    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
 61374    ** instead.
 61375    **
 61376    ** Before checking that the live wal-index header has not changed
 61377    ** since it was read, set Wal.minFrame to the first frame in the wal
 61378    ** file that has not yet been checkpointed. This client will not need
 61379    ** to read any frames earlier than minFrame from the wal file - they
 61380    ** can be safely read directly from the database file.
 61381    **
 61382    ** Because a ShmBarrier() call is made between taking the copy of 
 61383    ** nBackfill and checking that the wal-header in shared-memory still
 61384    ** matches the one cached in pWal->hdr, it is guaranteed that the 
 61385    ** checkpointer that set nBackfill was not working with a wal-index
 61386    ** header newer than that cached in pWal->hdr. If it were, that could
 61387    ** cause a problem. The checkpointer could omit to checkpoint
 61388    ** a version of page X that lies before pWal->minFrame (call that version
 61389    ** A) on the basis that there is a newer version (version B) of the same
 61390    ** page later in the wal file. But if version B happens to like past
 61391    ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
 61392    ** that it can read version A from the database file. However, since
 61393    ** we can guarantee that the checkpointer that set nBackfill could not
 61394    ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
 61395    */
 61396    pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
 61397    walShmBarrier(pWal);
 61398    if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
 61399     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
 61400    ){
 61401      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
 61402      return WAL_RETRY;
 61403    }else{
 61404      assert( mxReadMark<=pWal->hdr.mxFrame );
 61405      pWal->readLock = (i16)mxI;
 61406    }
 61407    return rc;
 61408  }
 61409  
 61410  #ifdef SQLITE_ENABLE_SNAPSHOT
 61411  /*
 61412  ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted 
 61413  ** variable so that older snapshots can be accessed. To do this, loop
 61414  ** through all wal frames from nBackfillAttempted to (nBackfill+1), 
 61415  ** comparing their content to the corresponding page with the database
 61416  ** file, if any. Set nBackfillAttempted to the frame number of the
 61417  ** first frame for which the wal file content matches the db file.
 61418  **
 61419  ** This is only really safe if the file-system is such that any page 
 61420  ** writes made by earlier checkpointers were atomic operations, which 
 61421  ** is not always true. It is also possible that nBackfillAttempted
 61422  ** may be left set to a value larger than expected, if a wal frame
 61423  ** contains content that duplicate of an earlier version of the same
 61424  ** page.
 61425  **
 61426  ** SQLITE_OK is returned if successful, or an SQLite error code if an
 61427  ** error occurs. It is not an error if nBackfillAttempted cannot be
 61428  ** decreased at all.
 61429  */
 61430  SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
 61431    int rc;
 61432  
 61433    assert( pWal->readLock>=0 );
 61434    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
 61435    if( rc==SQLITE_OK ){
 61436      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 61437      int szPage = (int)pWal->szPage;
 61438      i64 szDb;                   /* Size of db file in bytes */
 61439  
 61440      rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
 61441      if( rc==SQLITE_OK ){
 61442        void *pBuf1 = sqlite3_malloc(szPage);
 61443        void *pBuf2 = sqlite3_malloc(szPage);
 61444        if( pBuf1==0 || pBuf2==0 ){
 61445          rc = SQLITE_NOMEM;
 61446        }else{
 61447          u32 i = pInfo->nBackfillAttempted;
 61448          for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
 61449            WalHashLoc sLoc;          /* Hash table location */
 61450            u32 pgno;                 /* Page number in db file */
 61451            i64 iDbOff;               /* Offset of db file entry */
 61452            i64 iWalOff;              /* Offset of wal file entry */
 61453  
 61454            rc = walHashGet(pWal, walFramePage(i), &sLoc);
 61455            if( rc!=SQLITE_OK ) break;
 61456            pgno = sLoc.aPgno[i-sLoc.iZero];
 61457            iDbOff = (i64)(pgno-1) * szPage;
 61458  
 61459            if( iDbOff+szPage<=szDb ){
 61460              iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
 61461              rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
 61462  
 61463              if( rc==SQLITE_OK ){
 61464                rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
 61465              }
 61466  
 61467              if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
 61468                break;
 61469              }
 61470            }
 61471  
 61472            pInfo->nBackfillAttempted = i-1;
 61473          }
 61474        }
 61475  
 61476        sqlite3_free(pBuf1);
 61477        sqlite3_free(pBuf2);
 61478      }
 61479      walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
 61480    }
 61481  
 61482    return rc;
 61483  }
 61484  #endif /* SQLITE_ENABLE_SNAPSHOT */
 61485  
 61486  /*
 61487  ** Begin a read transaction on the database.
 61488  **
 61489  ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
 61490  ** it takes a snapshot of the state of the WAL and wal-index for the current
 61491  ** instant in time.  The current thread will continue to use this snapshot.
 61492  ** Other threads might append new content to the WAL and wal-index but
 61493  ** that extra content is ignored by the current thread.
 61494  **
 61495  ** If the database contents have changes since the previous read
 61496  ** transaction, then *pChanged is set to 1 before returning.  The
 61497  ** Pager layer will use this to know that its cache is stale and
 61498  ** needs to be flushed.
 61499  */
 61500  SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
 61501    int rc;                         /* Return code */
 61502    int cnt = 0;                    /* Number of TryBeginRead attempts */
 61503  
 61504    if( pWal->useBranches ){
 61505      return sqlite3BranchBeginReadTransaction(pWal->lmdb, 1, pChanged);
 61506    }
 61507  
 61508  #ifdef SQLITE_ENABLE_SNAPSHOT
 61509  {
 61510    int bChanged = 0;
 61511    WalIndexHdr *pSnapshot = pWal->pSnapshot;
 61512    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
 61513      bChanged = 1;
 61514    }
 61515  }
 61516  #endif
 61517  
 61518    do{
 61519      rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
 61520    }while( rc==WAL_RETRY );
 61521    testcase( (rc&0xff)==SQLITE_BUSY );
 61522    testcase( (rc&0xff)==SQLITE_IOERR );
 61523    testcase( rc==SQLITE_PROTOCOL );
 61524    testcase( rc==SQLITE_OK );
 61525  
 61526  #ifdef SQLITE_ENABLE_SNAPSHOT
 61527    if( rc==SQLITE_OK ){
 61528      if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
 61529        /* At this point the client has a lock on an aReadMark[] slot holding
 61530        ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
 61531        ** is populated with the wal-index header corresponding to the head
 61532        ** of the wal file. Verify that pSnapshot is still valid before
 61533        ** continuing.  Reasons why pSnapshot might no longer be valid:
 61534        **
 61535        **    (1)  The WAL file has been reset since the snapshot was taken.
 61536        **         In this case, the salt will have changed.
 61537        **
 61538        **    (2)  A checkpoint as been attempted that wrote frames past
 61539        **         pSnapshot->mxFrame into the database file.  Note that the
 61540        **         checkpoint need not have completed for this to cause problems.
 61541        */
 61542        volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 61543  
 61544        assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
 61545        assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
 61546  
 61547        /* It is possible that there is a checkpointer thread running 
 61548        ** concurrent with this code. If this is the case, it may be that the
 61549        ** checkpointer has already determined that it will checkpoint 
 61550        ** snapshot X, where X is later in the wal file than pSnapshot, but 
 61551        ** has not yet set the pInfo->nBackfillAttempted variable to indicate 
 61552        ** its intent. To avoid the race condition this leads to, ensure that
 61553        ** there is no checkpointer process by taking a shared CKPT lock 
 61554        ** before checking pInfo->nBackfillAttempted.  
 61555        **
 61556        ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
 61557        **       this already?
 61558        */
 61559        rc = walLockShared(pWal, WAL_CKPT_LOCK);
 61560  
 61561        if( rc==SQLITE_OK ){
 61562          /* Check that the wal file has not been wrapped. Assuming that it has
 61563          ** not, also check that no checkpointer has attempted to checkpoint any
 61564          ** frames beyond pSnapshot->mxFrame. If either of these conditions are
 61565          ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
 61566          ** with *pSnapshot and set *pChanged as appropriate for opening the
 61567          ** snapshot.  */
 61568          if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
 61569           && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
 61570          ){
 61571            assert( pWal->readLock>0 );
 61572            memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
 61573            *pChanged = bChanged;
 61574          }else{
 61575            rc = SQLITE_ERROR_SNAPSHOT;
 61576          }
 61577  
 61578          /* Release the shared CKPT lock obtained above. */
 61579          walUnlockShared(pWal, WAL_CKPT_LOCK);
 61580          pWal->minFrame = 1;
 61581        }
 61582  
 61583  
 61584        if( rc!=SQLITE_OK ){
 61585          sqlite3WalEndReadTransaction(pWal);
 61586        }
 61587      }
 61588    }
 61589  #endif
 61590    return rc;
 61591  }
 61592  
 61593  /*
 61594  ** Finish with a read transaction.  All this does is release the
 61595  ** read-lock.
 61596  */
 61597  SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
 61598    if( pWal->useBranches ){
 61599      sqlite3BranchEndReadTransaction(pWal->lmdb);
 61600      return;
 61601    }
 61602    sqlite3WalEndWriteTransaction(pWal);
 61603    if( pWal->readLock>=0 ){
 61604      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 61605      pWal->readLock = -1;
 61606    }
 61607  }
 61608  
 61609  /*
 61610  ** Search the wal file for page pgno. If found, set *piRead to the frame that
 61611  ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
 61612  ** to zero.
 61613  **
 61614  ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
 61615  ** error does occur, the final value of *piRead is undefined.
 61616  */
 61617  SQLITE_PRIVATE int sqlite3WalFindFrame(
 61618    Wal *pWal,                      /* WAL handle */
 61619    Pgno pgno,                      /* Database page number to read data for */
 61620    u32 *piRead                     /* OUT: Frame number (or zero) */
 61621  ){
 61622    u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
 61623    u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
 61624    int iHash;                      /* Used to loop through N hash tables */
 61625    int iMinHash;
 61626  
 61627    /* This routine is only be called from within a read transaction. */
 61628    assert( pWal->readLock>=0 || pWal->lockError );
 61629  
 61630    /* If the "last page" field of the wal-index header snapshot is 0, then
 61631    ** no data will be read from the wal under any circumstances. Return early
 61632    ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
 61633    ** then the WAL is ignored by the reader so return early, as if the 
 61634    ** WAL were empty.
 61635    */
 61636    if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
 61637      *piRead = 0;
 61638      return SQLITE_OK;
 61639    }
 61640  
 61641    /* Search the hash table or tables for an entry matching page number
 61642    ** pgno. Each iteration of the following for() loop searches one
 61643    ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
 61644    **
 61645    ** This code might run concurrently to the code in walIndexAppend()
 61646    ** that adds entries to the wal-index (and possibly to this hash 
 61647    ** table). This means the value just read from the hash 
 61648    ** slot (aHash[iKey]) may have been added before or after the 
 61649    ** current read transaction was opened. Values added after the
 61650    ** read transaction was opened may have been written incorrectly -
 61651    ** i.e. these slots may contain garbage data. However, we assume
 61652    ** that any slots written before the current read transaction was
 61653    ** opened remain unmodified.
 61654    **
 61655    ** For the reasons above, the if(...) condition featured in the inner
 61656    ** loop of the following block is more stringent that would be required 
 61657    ** if we had exclusive access to the hash-table:
 61658    **
 61659    **   (aPgno[iFrame]==pgno): 
 61660    **     This condition filters out normal hash-table collisions.
 61661    **
 61662    **   (iFrame<=iLast): 
 61663    **     This condition filters out entries that were added to the hash
 61664    **     table after the current read-transaction had started.
 61665    */
 61666    iMinHash = walFramePage(pWal->minFrame);
 61667    for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
 61668      WalHashLoc sLoc;              /* Hash table location */
 61669      int iKey;                     /* Hash slot index */
 61670      int nCollide;                 /* Number of hash collisions remaining */
 61671      int rc;                       /* Error code */
 61672  
 61673      rc = walHashGet(pWal, iHash, &sLoc);
 61674      if( rc!=SQLITE_OK ){
 61675        return rc;
 61676      }
 61677      nCollide = HASHTABLE_NSLOT;
 61678      for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
 61679        u32 iFrame = sLoc.aHash[iKey] + sLoc.iZero;
 61680        if( iFrame<=iLast && iFrame>=pWal->minFrame
 61681         && sLoc.aPgno[sLoc.aHash[iKey]]==pgno ){
 61682          assert( iFrame>iRead || CORRUPT_DB );
 61683          iRead = iFrame;
 61684        }
 61685        if( (nCollide--)==0 ){
 61686          return SQLITE_CORRUPT_BKPT;
 61687        }
 61688      }
 61689      if( iRead ) break;
 61690    }
 61691  
 61692  #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
 61693    /* If expensive assert() statements are available, do a linear search
 61694    ** of the wal-index file content. Make sure the results agree with the
 61695    ** result obtained using the hash indexes above.  */
 61696    {
 61697      u32 iRead2 = 0;
 61698      u32 iTest;
 61699      assert( pWal->bShmUnreliable || pWal->minFrame>0 );
 61700      for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
 61701        if( walFramePgno(pWal, iTest)==pgno ){
 61702          iRead2 = iTest;
 61703          break;
 61704        }
 61705      }
 61706      assert( iRead==iRead2 );
 61707    }
 61708  #endif
 61709  
 61710    *piRead = iRead;
 61711    return SQLITE_OK;
 61712  }
 61713  
 61714  /*
 61715  ** Read the contents of frame iRead from the wal file into buffer pOut
 61716  ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
 61717  ** error code otherwise.
 61718  */
 61719  SQLITE_PRIVATE int sqlite3WalReadFrame(
 61720    Wal *pWal,                      /* WAL handle */
 61721    u32 iRead,                      /* Frame to read */
 61722    int nOut,                       /* Size of buffer pOut in bytes */
 61723    u8 *pOut                        /* Buffer to write page data to */
 61724  ){
 61725    int sz;
 61726    i64 iOffset;
 61727    sz = pWal->hdr.szPage;
 61728    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
 61729    testcase( sz<=32768 );
 61730    testcase( sz>=65536 );
 61731    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
 61732    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
 61733    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
 61734  }
 61735  
 61736  /* 
 61737  ** Return the size of the database in pages (or zero, if unknown).
 61738  */
 61739  SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
 61740    if( pWal && pWal->useBranches ){
 61741      if( pWal->lmdb && pWal->lmdb->current_branch ){
 61742        branch_info *current_branch = pWal->lmdb->current_branch;
 61743        if( current_branch->pages_db == 0 ){
 61744          sqlite3BranchOpen(pWal->lmdb, current_branch->id, 0);
 61745        }
 61746        if( current_branch->max_commit > 0 ){
 61747          //if( current_branch->commit_max_page==0 && current_branch->maxpg_db==0 ){
 61748          //  sqlite3BranchOpen(pWal->lmdb, current_branch->id, 0);
 61749          //}
 61750          BRANCHTRACE("sqlite3WalDbsize returning %d", current_branch->commit_max_page);
 61751          return current_branch->commit_max_page;
 61752        } else {
 61753          if( current_branch->max_page==0 ){
 61754            /* retrieve the number of pages on this branch */
 61755            sqlite3BranchGetMaxPage(pWal->lmdb, current_branch);
 61756          }
 61757          BRANCHTRACE("sqlite3WalDbsize returning %d", current_branch->max_page);
 61758          return current_branch->max_page;
 61759        }
 61760      } else {
 61761        BRANCHTRACE("sqlite3WalDbsize returning %d", 0);
 61762        return 0;
 61763      }
 61764    }
 61765    if( pWal && ALWAYS(pWal->readLock>=0) ){
 61766      return pWal->hdr.nPage;
 61767    }
 61768    return 0;
 61769  }
 61770  
 61771  
 61772  /* 
 61773  ** This function starts a write transaction on the WAL.
 61774  **
 61775  ** A read transaction must have already been started by a prior call
 61776  ** to sqlite3WalBeginReadTransaction().
 61777  **
 61778  ** If another thread or process has written into the database since
 61779  ** the read transaction was started, then it is not possible for this
 61780  ** thread to write as doing so would cause a fork.  So this routine
 61781  ** returns SQLITE_BUSY in that case and no write transaction is started.
 61782  **
 61783  ** There can only be a single writer active at a time.
 61784  */
 61785  SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
 61786    int rc;
 61787  
 61788    if( pWal->useBranches ){
 61789      return sqlite3BranchBeginWriteTransaction(pWal->lmdb);
 61790    }
 61791  
 61792    /* Cannot start a write transaction without first holding a read
 61793    ** transaction. */
 61794    assert( pWal->readLock>=0 );
 61795    assert( pWal->writeLock==0 && pWal->iReCksum==0 );
 61796  
 61797    if( pWal->readOnly ){
 61798      return SQLITE_READONLY;
 61799    }
 61800  
 61801    /* Only one writer allowed at a time.  Get the write lock.  Return
 61802    ** SQLITE_BUSY if unable.
 61803    */
 61804    rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
 61805    if( rc ){
 61806      return rc;
 61807    }
 61808    pWal->writeLock = 1;
 61809  
 61810    /* If another connection has written to the database file since the
 61811    ** time the read transaction on this connection was started, then
 61812    ** the write is disallowed.
 61813    */
 61814    if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
 61815      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 61816      pWal->writeLock = 0;
 61817      rc = SQLITE_BUSY_SNAPSHOT;
 61818    }
 61819  
 61820    return rc;
 61821  }
 61822  
 61823  /*
 61824  ** End a write transaction.  The commit has already been done.  This
 61825  ** routine merely releases the lock.
 61826  */
 61827  SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
 61828    if( pWal->useBranches ){
 61829      return sqlite3BranchEndWriteTransaction(pWal->lmdb, 1);
 61830    }
 61831    if( pWal->writeLock ){
 61832      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
 61833      pWal->writeLock = 0;
 61834      pWal->iReCksum = 0;
 61835      pWal->truncateOnCommit = 0;
 61836    }
 61837    return SQLITE_OK;
 61838  }
 61839  
 61840  /*
 61841  ** If any data has been written (but not committed) to the log file, this
 61842  ** function moves the write-pointer back to the start of the transaction.
 61843  **
 61844  ** Additionally, the callback function is invoked for each frame written
 61845  ** to the WAL since the start of the transaction. If the callback returns
 61846  ** other than SQLITE_OK, it is not invoked again and the error code is
 61847  ** returned to the caller.
 61848  **
 61849  ** Otherwise, if the callback function does not return an error, this
 61850  ** function returns SQLITE_OK.
 61851  */
 61852  SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
 61853    int rc = SQLITE_OK;
 61854    if( pWal->useBranches ){
 61855      return sqlite3BranchUndoChanges(pWal->lmdb);
 61856    }
 61857    if( ALWAYS(pWal->writeLock) ){
 61858      Pgno iMax = pWal->hdr.mxFrame;
 61859      Pgno iFrame;
 61860    
 61861      /* Restore the clients cache of the wal-index header to the state it
 61862      ** was in before the client began writing to the database. 
 61863      */
 61864      memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
 61865  
 61866      for(iFrame=pWal->hdr.mxFrame+1; 
 61867          ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
 61868          iFrame++
 61869      ){
 61870        /* This call cannot fail. Unless the page for which the page number
 61871        ** is passed as the second argument is (a) in the cache and 
 61872        ** (b) has an outstanding reference, then xUndo is either a no-op
 61873        ** (if (a) is false) or simply expels the page from the cache (if (b)
 61874        ** is false).
 61875        **
 61876        ** If the upper layer is doing a rollback, it is guaranteed that there
 61877        ** are no outstanding references to any page other than page 1. And
 61878        ** page 1 is never written to the log until the transaction is
 61879        ** committed. As a result, the call to xUndo may not fail.
 61880        */
 61881        assert( walFramePgno(pWal, iFrame)!=1 );
 61882        rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
 61883      }
 61884      if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
 61885    }
 61886    return rc;
 61887  }
 61888  
 61889  /* 
 61890  ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
 61891  ** values. This function populates the array with values required to 
 61892  ** "rollback" the write position of the WAL handle back to the current 
 61893  ** point in the event of a savepoint rollback (via WalSavepointUndo()).
 61894  */
 61895  SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
 61896    if( pWal->useBranches ){
 61897      sqlite3BranchSavepoint(pWal->lmdb, aWalData);
 61898      return;
 61899    }
 61900    assert( pWal->writeLock );
 61901    aWalData[0] = pWal->hdr.mxFrame;
 61902    aWalData[1] = pWal->hdr.aFrameCksum[0];
 61903    aWalData[2] = pWal->hdr.aFrameCksum[1];
 61904    aWalData[3] = pWal->nCkpt;
 61905  }
 61906  
 61907  /* 
 61908  ** Move the write position of the WAL back to the point identified by
 61909  ** the values in the aWalData[] array. aWalData must point to an array
 61910  ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
 61911  ** by a call to WalSavepoint().
 61912  */
 61913  SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
 61914    int rc = SQLITE_OK;
 61915  
 61916    if( pWal->useBranches ){
 61917      return sqlite3BranchSavepointUndo(pWal->lmdb, aWalData);
 61918    }
 61919  
 61920    assert( pWal->writeLock );
 61921    assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
 61922  
 61923    if( aWalData[3]!=pWal->nCkpt ){
 61924      /* This savepoint was opened immediately after the write-transaction
 61925      ** was started. Right after that, the writer decided to wrap around
 61926      ** to the start of the log. Update the savepoint values to match.
 61927      */
 61928      aWalData[0] = 0;
 61929      aWalData[3] = pWal->nCkpt;
 61930    }
 61931  
 61932    if( aWalData[0]<pWal->hdr.mxFrame ){
 61933      pWal->hdr.mxFrame = aWalData[0];
 61934      pWal->hdr.aFrameCksum[0] = aWalData[1];
 61935      pWal->hdr.aFrameCksum[1] = aWalData[2];
 61936      walCleanupHash(pWal);
 61937    }
 61938  
 61939    return rc;
 61940  }
 61941  
 61942  /*
 61943  ** This function is called just before writing a set of frames to the log
 61944  ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
 61945  ** to the current log file, it is possible to overwrite the start of the
 61946  ** existing log file with the new frames (i.e. "reset" the log). If so,
 61947  ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
 61948  ** unchanged.
 61949  **
 61950  ** SQLITE_OK is returned if no error is encountered (regardless of whether
 61951  ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
 61952  ** if an error occurs.
 61953  */
 61954  static int walRestartLog(Wal *pWal){
 61955    int rc = SQLITE_OK;
 61956    int cnt;
 61957  
 61958    if( pWal->readLock==0 ){
 61959      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
 61960      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
 61961      if( pInfo->nBackfill>0 ){
 61962        u32 salt1;
 61963        sqlite3_randomness(4, &salt1);
 61964        rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 61965        if( rc==SQLITE_OK ){
 61966          /* If all readers are using WAL_READ_LOCK(0) (in other words if no
 61967          ** readers are currently using the WAL), then the transactions
 61968          ** frames will overwrite the start of the existing log. Update the
 61969          ** wal-index header to reflect this.
 61970          **
 61971          ** In theory it would be Ok to update the cache of the header only
 61972          ** at this point. But updating the actual wal-index header is also
 61973          ** safe and means there is no special case for sqlite3WalUndo()
 61974          ** to handle if this transaction is rolled back.  */
 61975          walRestartHdr(pWal, salt1);
 61976          walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
 61977        }else if( rc!=SQLITE_BUSY ){
 61978          return rc;
 61979        }
 61980      }
 61981      walUnlockShared(pWal, WAL_READ_LOCK(0));
 61982      pWal->readLock = -1;
 61983      cnt = 0;
 61984      do{
 61985        int notUsed;
 61986        rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
 61987      }while( rc==WAL_RETRY );
 61988      assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
 61989      testcase( (rc&0xff)==SQLITE_IOERR );
 61990      testcase( rc==SQLITE_PROTOCOL );
 61991      testcase( rc==SQLITE_OK );
 61992    }
 61993    return rc;
 61994  }
 61995  
 61996  /*
 61997  ** Information about the current state of the WAL file and where
 61998  ** the next fsync should occur - passed from sqlite3WalFrames() into
 61999  ** walWriteToLog().
 62000  */
 62001  typedef struct WalWriter {
 62002    Wal *pWal;                   /* The complete WAL information */
 62003    sqlite3_file *pFd;           /* The WAL file to which we write */
 62004    sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
 62005    int syncFlags;               /* Flags for the fsync */
 62006    int szPage;                  /* Size of one page */
 62007  } WalWriter;
 62008  
 62009  /*
 62010  ** Write iAmt bytes of content into the WAL file beginning at iOffset.
 62011  ** Do a sync when crossing the p->iSyncPoint boundary.
 62012  **
 62013  ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
 62014  ** first write the part before iSyncPoint, then sync, then write the
 62015  ** rest.
 62016  */
 62017  static int walWriteToLog(
 62018    WalWriter *p,              /* WAL to write to */
 62019    void *pContent,            /* Content to be written */
 62020    int iAmt,                  /* Number of bytes to write */
 62021    sqlite3_int64 iOffset      /* Start writing at this offset */
 62022  ){
 62023    int rc;
 62024    if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
 62025      int iFirstAmt = (int)(p->iSyncPoint - iOffset);
 62026      rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
 62027      if( rc ) return rc;
 62028      iOffset += iFirstAmt;
 62029      iAmt -= iFirstAmt;
 62030      pContent = (void*)(iFirstAmt + (char*)pContent);
 62031      assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
 62032      rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
 62033      if( iAmt==0 || rc ) return rc;
 62034    }
 62035    rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
 62036    return rc;
 62037  }
 62038  
 62039  /*
 62040  ** Write out a single frame of the WAL
 62041  */
 62042  static int walWriteOneFrame(
 62043    WalWriter *p,               /* Where to write the frame */
 62044    PgHdr *pPage,               /* The page of the frame to be written */
 62045    int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
 62046    sqlite3_int64 iOffset       /* Byte offset at which to write */
 62047  ){
 62048    int rc;                         /* Result code from subfunctions */
 62049    void *pData;                    /* Data actually written */
 62050    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
 62051  #if defined(SQLITE_HAS_CODEC)
 62052    if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
 62053  #else
 62054    pData = pPage->pData;
 62055  #endif
 62056    walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
 62057    rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
 62058    if( rc ) return rc;
 62059    /* Write the page data */
 62060    rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
 62061    return rc;
 62062  }
 62063  
 62064  /*
 62065  ** This function is called as part of committing a transaction within which
 62066  ** one or more frames have been overwritten. It updates the checksums for
 62067  ** all frames written to the wal file by the current transaction starting
 62068  ** with the earliest to have been overwritten.
 62069  **
 62070  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 62071  */
 62072  static int walRewriteChecksums(Wal *pWal, u32 iLast){
 62073    const int szPage = pWal->szPage;/* Database page size */
 62074    int rc = SQLITE_OK;             /* Return code */
 62075    u8 *aBuf;                       /* Buffer to load data from wal file into */
 62076    u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
 62077    u32 iRead;                      /* Next frame to read from wal file */
 62078    i64 iCksumOff;
 62079  
 62080    aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
 62081    if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
 62082  
 62083    /* Find the checksum values to use as input for the recalculating the
 62084    ** first checksum. If the first frame is frame 1 (implying that the current
 62085    ** transaction restarted the wal file), these values must be read from the
 62086    ** wal-file header. Otherwise, read them from the frame header of the
 62087    ** previous frame.  */
 62088    assert( pWal->iReCksum>0 );
 62089    if( pWal->iReCksum==1 ){
 62090      iCksumOff = 24;
 62091    }else{
 62092      iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
 62093    }
 62094    rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
 62095    pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
 62096    pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
 62097  
 62098    iRead = pWal->iReCksum;
 62099    pWal->iReCksum = 0;
 62100    for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
 62101      i64 iOff = walFrameOffset(iRead, szPage);
 62102      rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
 62103      if( rc==SQLITE_OK ){
 62104        u32 iPgno, nDbSize;
 62105        iPgno = sqlite3Get4byte(aBuf);
 62106        nDbSize = sqlite3Get4byte(&aBuf[4]);
 62107  
 62108        walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
 62109        rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
 62110      }
 62111    }
 62112  
 62113    sqlite3_free(aBuf);
 62114    return rc;
 62115  }
 62116  
 62117  /* 
 62118  ** Write a set of frames to the log. The caller must hold the write-lock
 62119  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
 62120  */
 62121  SQLITE_PRIVATE int sqlite3WalFrames(
 62122    Wal *pWal,                      /* Wal handle to write to */
 62123    int szPage,                     /* Database page-size in bytes */
 62124    PgHdr *pList,                   /* List of dirty pages to write */
 62125    Pgno nTruncate,                 /* Database size after this commit */
 62126    int isCommit,                   /* True if this is a commit */
 62127    int sync_flags                  /* Flags to pass to OsSync() (or 0) */
 62128  ){
 62129    int rc;                         /* Used to catch return codes */
 62130    u32 iFrame;                     /* Next frame address */
 62131    PgHdr *p;                       /* Iterator to run through pList with. */
 62132    PgHdr *pLast = 0;               /* Last frame in list */
 62133    int nExtra = 0;                 /* Number of extra copies of last page */
 62134    int szFrame;                    /* The size of a single frame */
 62135    i64 iOffset;                    /* Next byte to write in WAL file */
 62136    WalWriter w;                    /* The writer */
 62137    u32 iFirst = 0;                 /* First frame that may be overwritten */
 62138    WalIndexHdr *pLive;             /* Pointer to shared header */
 62139  
 62140    assert( pList );
 62141    assert( pWal->writeLock );
 62142  
 62143    /* If this frame set completes a transaction, then nTruncate>0.  If
 62144    ** nTruncate==0 then this frame set does not complete the transaction. */
 62145    assert( (isCommit!=0)==(nTruncate!=0) );
 62146  
 62147  #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
 62148    { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
 62149      WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
 62150                pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
 62151    }
 62152  #endif
 62153  
 62154    pLive = (WalIndexHdr*)walIndexHdr(pWal);
 62155    if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
 62156      iFirst = pLive->mxFrame+1;
 62157    }
 62158  
 62159    /* See if it is possible to write these frames into the start of the
 62160    ** log file, instead of appending to it at pWal->hdr.mxFrame.
 62161    */
 62162    if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
 62163      return rc;
 62164    }
 62165  
 62166    /* If this is the first frame written into the log, write the WAL
 62167    ** header to the start of the WAL file. See comments at the top of
 62168    ** this source file for a description of the WAL header format.
 62169    */
 62170    iFrame = pWal->hdr.mxFrame;
 62171    if( iFrame==0 ){
 62172      u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
 62173      u32 aCksum[2];                /* Checksum for wal-header */
 62174  
 62175      sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
 62176      sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
 62177      sqlite3Put4byte(&aWalHdr[8], szPage);
 62178      sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
 62179      if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
 62180      memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
 62181      walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
 62182      sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
 62183      sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
 62184      
 62185      pWal->szPage = szPage;
 62186      pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
 62187      pWal->hdr.aFrameCksum[0] = aCksum[0];
 62188      pWal->hdr.aFrameCksum[1] = aCksum[1];
 62189      pWal->truncateOnCommit = 1;
 62190  
 62191      rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
 62192      WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
 62193      if( rc!=SQLITE_OK ){
 62194        return rc;
 62195      }
 62196  
 62197      /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
 62198      ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
 62199      ** an out-of-order write following a WAL restart could result in
 62200      ** database corruption.  See the ticket:
 62201      **
 62202      **     https://sqlite.org/src/info/ff5be73dee
 62203      */
 62204      if( pWal->syncHeader ){
 62205        rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
 62206        if( rc ) return rc;
 62207      }
 62208    }
 62209    assert( (int)pWal->szPage==szPage );
 62210  
 62211    /* Setup information needed to write frames into the WAL */
 62212    w.pWal = pWal;
 62213    w.pFd = pWal->pWalFd;
 62214    w.iSyncPoint = 0;
 62215    w.syncFlags = sync_flags;
 62216    w.szPage = szPage;
 62217    iOffset = walFrameOffset(iFrame+1, szPage);
 62218    szFrame = szPage + WAL_FRAME_HDRSIZE;
 62219  
 62220    /* Write all frames into the log file exactly once */
 62221    for(p=pList; p; p=p->pDirty){
 62222      int nDbSize;   /* 0 normally.  Positive == commit flag */
 62223  
 62224      /* Check if this page has already been written into the wal file by
 62225      ** the current transaction. If so, overwrite the existing frame and
 62226      ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that 
 62227      ** checksums must be recomputed when the transaction is committed.  */
 62228      if( iFirst && (p->pDirty || isCommit==0) ){
 62229        u32 iWrite = 0;
 62230        VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
 62231        assert( rc==SQLITE_OK || iWrite==0 );
 62232        if( iWrite>=iFirst ){
 62233          i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
 62234          void *pData;
 62235          if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
 62236            pWal->iReCksum = iWrite;
 62237          }
 62238  #if defined(SQLITE_HAS_CODEC)
 62239          if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
 62240  #else
 62241          pData = p->pData;
 62242  #endif
 62243          rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
 62244          if( rc ) return rc;
 62245          p->flags &= ~PGHDR_WAL_APPEND;
 62246          continue;
 62247        }
 62248      }
 62249  
 62250      iFrame++;
 62251      assert( iOffset==walFrameOffset(iFrame, szPage) );
 62252      nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
 62253      rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
 62254      if( rc ) return rc;
 62255      pLast = p;
 62256      iOffset += szFrame;
 62257      p->flags |= PGHDR_WAL_APPEND;
 62258    }
 62259  
 62260    /* Recalculate checksums within the wal file if required. */
 62261    if( isCommit && pWal->iReCksum ){
 62262      rc = walRewriteChecksums(pWal, iFrame);
 62263      if( rc ) return rc;
 62264    }
 62265  
 62266    /* If this is the end of a transaction, then we might need to pad
 62267    ** the transaction and/or sync the WAL file.
 62268    **
 62269    ** Padding and syncing only occur if this set of frames complete a
 62270    ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
 62271    ** or synchronous==OFF, then no padding or syncing are needed.
 62272    **
 62273    ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
 62274    ** needed and only the sync is done.  If padding is needed, then the
 62275    ** final frame is repeated (with its commit mark) until the next sector
 62276    ** boundary is crossed.  Only the part of the WAL prior to the last
 62277    ** sector boundary is synced; the part of the last frame that extends
 62278    ** past the sector boundary is written after the sync.
 62279    */
 62280    if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
 62281      int bSync = 1;
 62282      if( pWal->padToSectorBoundary ){
 62283        int sectorSize = sqlite3SectorSize(pWal->pWalFd);
 62284        w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
 62285        bSync = (w.iSyncPoint==iOffset);
 62286        testcase( bSync );
 62287        while( iOffset<w.iSyncPoint ){
 62288          rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
 62289          if( rc ) return rc;
 62290          iOffset += szFrame;
 62291          nExtra++;
 62292        }
 62293      }
 62294      if( bSync ){
 62295        assert( rc==SQLITE_OK );
 62296        rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
 62297      }
 62298    }
 62299  
 62300    /* If this frame set completes the first transaction in the WAL and
 62301    ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
 62302    ** journal size limit, if possible.
 62303    */
 62304    if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
 62305      i64 sz = pWal->mxWalSize;
 62306      if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
 62307        sz = walFrameOffset(iFrame+nExtra+1, szPage);
 62308      }
 62309      walLimitSize(pWal, sz);
 62310      pWal->truncateOnCommit = 0;
 62311    }
 62312  
 62313    /* Append data to the wal-index. It is not necessary to lock the 
 62314    ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
 62315    ** guarantees that there are no other writers, and no data that may
 62316    ** be in use by existing readers is being overwritten.
 62317    */
 62318    iFrame = pWal->hdr.mxFrame;
 62319    for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
 62320      if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
 62321      iFrame++;
 62322      rc = walIndexAppend(pWal, iFrame, p->pgno);
 62323    }
 62324    while( rc==SQLITE_OK && nExtra>0 ){
 62325      iFrame++;
 62326      nExtra--;
 62327      rc = walIndexAppend(pWal, iFrame, pLast->pgno);
 62328    }
 62329  
 62330    if( rc==SQLITE_OK ){
 62331      /* Update the private copy of the header. */
 62332      pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
 62333      testcase( szPage<=32768 );
 62334      testcase( szPage>=65536 );
 62335      pWal->hdr.mxFrame = iFrame;
 62336      if( isCommit ){
 62337        pWal->hdr.iChange++;
 62338        pWal->hdr.nPage = nTruncate;
 62339      }
 62340      /* If this is a commit, update the wal-index header too. */
 62341      if( isCommit ){
 62342        walIndexWriteHdr(pWal);
 62343        pWal->iCallback = iFrame;
 62344      }
 62345    }
 62346  
 62347    WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
 62348    return rc;
 62349  }
 62350  
 62351  /* 
 62352  ** This routine is called to implement sqlite3_wal_checkpoint() and
 62353  ** related interfaces.
 62354  **
 62355  ** Obtain a CHECKPOINT lock and then backfill as much information as
 62356  ** we can from WAL into the database.
 62357  **
 62358  ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
 62359  ** callback. In this case this function runs a blocking checkpoint.
 62360  */
 62361  SQLITE_PRIVATE int sqlite3WalCheckpoint(
 62362    Wal *pWal,                      /* Wal connection */
 62363    sqlite3 *db,                    /* Check this handle's interrupt flag */
 62364    int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
 62365    int (*xBusy)(void*),            /* Function to call when busy */
 62366    void *pBusyArg,                 /* Context argument for xBusyHandler */
 62367    int sync_flags,                 /* Flags to sync db file with (or 0) */
 62368    int nBuf,                       /* Size of temporary buffer */
 62369    u8 *zBuf,                       /* Temporary buffer to use */
 62370    int *pnLog,                     /* OUT: Number of frames in WAL */
 62371    int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
 62372  ){
 62373    int rc;                         /* Return code */
 62374    int isChanged = 0;              /* True if a new wal-index header is loaded */
 62375    int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
 62376    int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
 62377  
 62378    BRANCHTRACE("sqlite3WalCheckpoint");
 62379    if( pWal->useBranches ) return SQLITE_OK;
 62380  
 62381    assert( pWal->ckptLock==0 );
 62382    assert( pWal->writeLock==0 );
 62383  
 62384    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
 62385    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
 62386    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
 62387  
 62388    if( pWal->readOnly ) return SQLITE_READONLY;
 62389    WALTRACE(("WAL%p: checkpoint begins\n", pWal));
 62390  
 62391    /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive 
 62392    ** "checkpoint" lock on the database file. */
 62393    rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
 62394    if( rc ){
 62395      /* EVIDENCE-OF: R-10421-19736 If any other process is running a
 62396      ** checkpoint operation at the same time, the lock cannot be obtained and
 62397      ** SQLITE_BUSY is returned.
 62398      ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
 62399      ** it will not be invoked in this case.
 62400      */
 62401      testcase( rc==SQLITE_BUSY );
 62402      testcase( xBusy!=0 );
 62403      return rc;
 62404    }
 62405    pWal->ckptLock = 1;
 62406  
 62407    /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
 62408    ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
 62409    ** file.
 62410    **
 62411    ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
 62412    ** immediately, and a busy-handler is configured, it is invoked and the
 62413    ** writer lock retried until either the busy-handler returns 0 or the
 62414    ** lock is successfully obtained.
 62415    */
 62416    if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
 62417      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
 62418      if( rc==SQLITE_OK ){
 62419        pWal->writeLock = 1;
 62420      }else if( rc==SQLITE_BUSY ){
 62421        eMode2 = SQLITE_CHECKPOINT_PASSIVE;
 62422        xBusy2 = 0;
 62423        rc = SQLITE_OK;
 62424      }
 62425    }
 62426  
 62427    /* Read the wal-index header. */
 62428    if( rc==SQLITE_OK ){
 62429      rc = walIndexReadHdr(pWal, &isChanged);
 62430      if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
 62431        sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
 62432      }
 62433    }
 62434  
 62435    /* Copy data from the log to the database file. */
 62436    if( rc==SQLITE_OK ){
 62437  
 62438      if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
 62439        rc = SQLITE_CORRUPT_BKPT;
 62440      }else{
 62441        rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
 62442      }
 62443  
 62444      /* If no error occurred, set the output variables. */
 62445      if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
 62446        if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
 62447        if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
 62448      }
 62449    }
 62450  
 62451    if( isChanged ){
 62452      /* If a new wal-index header was loaded before the checkpoint was 
 62453      ** performed, then the pager-cache associated with pWal is now
 62454      ** out of date. So zero the cached wal-index header to ensure that
 62455      ** next time the pager opens a snapshot on this database it knows that
 62456      ** the cache needs to be reset.
 62457      */
 62458      memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
 62459    }
 62460  
 62461    /* Release the locks. */
 62462    sqlite3WalEndWriteTransaction(pWal);
 62463    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
 62464    pWal->ckptLock = 0;
 62465    WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
 62466    return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
 62467  }
 62468  
 62469  /* Return the value to pass to a sqlite3_wal_hook callback, the
 62470  ** number of frames in the WAL at the point of the last commit since
 62471  ** sqlite3WalCallback() was called.  If no commits have occurred since
 62472  ** the last call, then return 0.
 62473  */
 62474  SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
 62475    u32 ret = 0;
 62476    if( pWal ){
 62477      ret = pWal->iCallback;
 62478      pWal->iCallback = 0;
 62479    }
 62480    return (int)ret;
 62481  }
 62482  
 62483  /*
 62484  ** This function is called to change the WAL subsystem into or out
 62485  ** of locking_mode=EXCLUSIVE.
 62486  **
 62487  ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
 62488  ** into locking_mode=NORMAL.  This means that we must acquire a lock
 62489  ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
 62490  ** or if the acquisition of the lock fails, then return 0.  If the
 62491  ** transition out of exclusive-mode is successful, return 1.  This
 62492  ** operation must occur while the pager is still holding the exclusive
 62493  ** lock on the main database file.
 62494  **
 62495  ** If op is one, then change from locking_mode=NORMAL into 
 62496  ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
 62497  ** be released.  Return 1 if the transition is made and 0 if the
 62498  ** WAL is already in exclusive-locking mode - meaning that this
 62499  ** routine is a no-op.  The pager must already hold the exclusive lock
 62500  ** on the main database file before invoking this operation.
 62501  **
 62502  ** If op is negative, then do a dry-run of the op==1 case but do
 62503  ** not actually change anything. The pager uses this to see if it
 62504  ** should acquire the database exclusive lock prior to invoking
 62505  ** the op==1 case.
 62506  */
 62507  SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
 62508    int rc;
 62509  
 62510    if( pWal->useBranches ) return SQLITE_OK;
 62511  
 62512    assert( pWal->writeLock==0 );
 62513    assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
 62514  
 62515    /* pWal->readLock is usually set, but might be -1 if there was a 
 62516    ** prior error while attempting to acquire are read-lock. This cannot 
 62517    ** happen if the connection is actually in exclusive mode (as no xShmLock
 62518    ** locks are taken in this case). Nor should the pager attempt to
 62519    ** upgrade to exclusive-mode following such an error.
 62520    */
 62521    assert( pWal->readLock>=0 || pWal->lockError );
 62522    assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
 62523  
 62524    if( op==0 ){
 62525      if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
 62526        pWal->exclusiveMode = WAL_NORMAL_MODE;
 62527        if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
 62528          pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
 62529        }
 62530        rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
 62531      }else{
 62532        /* Already in locking_mode=NORMAL */
 62533        rc = 0;
 62534      }
 62535    }else if( op>0 ){
 62536      assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
 62537      assert( pWal->readLock>=0 );
 62538      walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
 62539      pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
 62540      rc = 1;
 62541    }else{
 62542      rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
 62543    }
 62544    return rc;
 62545  }
 62546  
 62547  /* 
 62548  ** Return true if the argument is non-NULL and the WAL module is using
 62549  ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
 62550  ** WAL module is using shared-memory, return false. 
 62551  */
 62552  SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
 62553    if( pWal && pWal->useBranches ) return 1;
 62554    return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
 62555  }
 62556  
 62557  #ifdef SQLITE_ENABLE_SNAPSHOT
 62558  /* Create a snapshot object.  The content of a snapshot is opaque to
 62559  ** every other subsystem, so the WAL module can put whatever it needs
 62560  ** in the object.
 62561  */
 62562  SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
 62563    int rc = SQLITE_OK;
 62564    WalIndexHdr *pRet;
 62565    static const u32 aZero[4] = { 0, 0, 0, 0 };
 62566  
 62567    assert( pWal->readLock>=0 && pWal->writeLock==0 );
 62568  
 62569    if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
 62570      *ppSnapshot = 0;
 62571      return SQLITE_ERROR;
 62572    }
 62573    pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
 62574    if( pRet==0 ){
 62575      rc = SQLITE_NOMEM_BKPT;
 62576    }else{
 62577      memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
 62578      *ppSnapshot = (sqlite3_snapshot*)pRet;
 62579    }
 62580  
 62581    return rc;
 62582  }
 62583  
 62584  /* Try to open on pSnapshot when the next read-transaction starts
 62585  */
 62586  SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
 62587    pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
 62588  }
 62589  
 62590  /* 
 62591  ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
 62592  ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
 62593  */
 62594  SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
 62595    WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
 62596    WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
 62597  
 62598    /* aSalt[0] is a copy of the value stored in the wal file header. It
 62599    ** is incremented each time the wal file is restarted.  */
 62600    if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
 62601    if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
 62602    if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
 62603    if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
 62604    return 0;
 62605  }
 62606  
 62607  /*
 62608  ** The caller currently has a read transaction open on the database.
 62609  ** This function takes a SHARED lock on the CHECKPOINTER slot and then
 62610  ** checks if the snapshot passed as the second argument is still 
 62611  ** available. If so, SQLITE_OK is returned.
 62612  **
 62613  ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
 62614  ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
 62615  ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
 62616  ** lock is released before returning.
 62617  */
 62618  SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
 62619    int rc;
 62620    rc = walLockShared(pWal, WAL_CKPT_LOCK);
 62621    if( rc==SQLITE_OK ){
 62622      WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
 62623      if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
 62624       || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
 62625      ){
 62626        rc = SQLITE_ERROR_SNAPSHOT;
 62627        walUnlockShared(pWal, WAL_CKPT_LOCK);
 62628      }
 62629    }
 62630    return rc;
 62631  }
 62632  
 62633  /*
 62634  ** Release a lock obtained by an earlier successful call to
 62635  ** sqlite3WalSnapshotCheck().
 62636  */
 62637  SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
 62638    assert( pWal );
 62639    walUnlockShared(pWal, WAL_CKPT_LOCK);
 62640  }
 62641  
 62642  
 62643  #endif /* SQLITE_ENABLE_SNAPSHOT */
 62644  
 62645  #ifdef SQLITE_ENABLE_ZIPVFS
 62646  /*
 62647  ** If the argument is not NULL, it points to a Wal object that holds a
 62648  ** read-lock. This function returns the database page-size if it is known,
 62649  ** or zero if it is not (or if pWal is NULL).
 62650  */
 62651  SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
 62652    assert( pWal==0 || pWal->readLock>=0 );
 62653    return (pWal ? pWal->szPage : 0);
 62654  }
 62655  #endif
 62656  
 62657  /* Return the sqlite3_file object for the WAL file
 62658  */
 62659  SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
 62660    return pWal->pWalFd;
 62661  }
 62662  
 62663  #endif /* #ifndef SQLITE_OMIT_WAL */
 62664  
 62665  /************** End of wal.c *************************************************/
 62666  /************** Begin file branches.c ****************************************/
 62667  
 62668  #if defined(_WIN32)
 62669  #define BIG_ENDIAN      0x1000
 62670  #define LITTLE_ENDIAN   0x0001
 62671  #define BYTE_ORDER      LITTLE_ENDIAN
 62672  #elif defined(__APPLE__)
 62673  #ifndef BYTE_ORDER
 62674  #define BIG_ENDIAN      0x1000
 62675  #define LITTLE_ENDIAN   0x0001
 62676  #define BYTE_ORDER      LITTLE_ENDIAN
 62677  #endif
 62678  #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
 62679  #include <sys/endian.h>
 62680  #elif defined(_AIX)
 62681  #include <sys/machine.h>
 62682  #else
 62683  #include <endian.h>
 62684  #endif
 62685  
 62686  #ifndef BYTE_ORDER
 62687  #error "BYTE_ORDER not defined"
 62688  #endif
 62689  #ifndef BIG_ENDIAN
 62690  #error "BIG_ENDIAN not defined"
 62691  #endif
 62692  #ifndef LITTLE_ENDIAN
 62693  #error "LITTLE_ENDIAN not defined"
 62694  #endif
 62695  #if BIG_ENDIAN == LITTLE_ENDIAN
 62696  #error "BIG_ENDIAN == LITTLE_ENDIAN"
 62697  #endif
 62698  #if BYTE_ORDER!=BIG_ENDIAN && BYTE_ORDER!=LITTLE_ENDIAN                                                                                               
 62699  #error "BYTE_ORDER not supported"                                                                                                                     
 62700  #endif
 62701  
 62702  #ifdef UNUSED_FUNCTION
 62703  /*
 62704  ** Converts the 32bit integer to big endian
 62705  */
 62706  SQLITE_PRIVATE unsigned int tobe32(unsigned int input) {
 62707  #if BYTE_ORDER == BIG_ENDIAN
 62708    return input;
 62709  #else
 62710    unsigned int result;
 62711    unsigned char *source = (unsigned char *) &input;
 62712    unsigned char *dest = (unsigned char *) &result;
 62713  
 62714    dest[0] = source[3];
 62715    dest[1] = source[2];
 62716    dest[2] = source[1];
 62717    dest[3] = source[0];
 62718  
 62719    return result;
 62720  #endif
 62721  }
 62722  
 62723  /*
 62724  ** Converts the 32bit integer from big endian
 62725  */
 62726  #define frombe32 tobe32
 62727  
 62728  #endif
 62729  
 62730  #ifdef UNUSED_FUNCTION
 62731  /*
 62732  ** Add a new item to the data_chunk list
 62733  */
 62734  SQLITE_PRIVATE int chunk_list_add(struct data_chunk *list, void *data, int size){
 62735    struct data_chunk *chunk = list;
 62736    unsigned char *p;
 62737  
 62738    if( !list || !data || size <= 0 || size > 255 ) return SQLITE_INTERNAL;
 62739  
 62740    while( chunk->next ) chunk = chunk->next;
 62741  
 62742    if( chunk->used + size > chunk->total ){
 62743      chunk->next = (struct data_chunk *) sqlite3_malloc(4096);
 62744      if( !chunk->next ) return SQLITE_NOMEM;
 62745      chunk = chunk->next;
 62746      chunk->next = NULL;
 62747      chunk->total = 4096 - offsetof(struct data_chunk, buf);
 62748      chunk->used = 0;
 62749    }
 62750  
 62751    p = &chunk->buf[chunk->used];
 62752    *p = size; p++;
 62753    memcpy(p, data, size);
 62754    chunk->used += (1 + size);
 62755  
 62756    return SQLITE_OK;
 62757  }
 62758  
 62759  /*
 62760  ** Release the data_chunk list
 62761  */
 62762  SQLITE_PRIVATE void chunk_list_free(struct data_chunk *list){
 62763    while( list ){
 62764      struct data_chunk *next = list->next;
 62765      sqlite3_free(list);
 62766      list = next;
 62767    }
 62768  }
 62769  #endif
 62770  
 62771  /*
 62772  ** Trims the string, modifying it and returning
 62773  ** a pointer to its content.
 62774  */
 62775  SQLITE_PRIVATE char * trimstr(char *str){
 62776    /* trim leading spaces */
 62777    while( sqlite3Isspace(*str) ) str++;
 62778    if( *str ){
 62779      /* trim trailing spaces */
 62780      char *end = str + strlen(str) - 1;
 62781      while( str < end && sqlite3Isspace(*end) ) end--;
 62782      /* add the null terminator */
 62783      end[1] = '\0';
 62784    }
 62785    return str;
 62786  }
 62787  
 62788  /*
 62789  ** Returns the position of a string inside another, using
 62790  ** case insensitive comparison.
 62791  */
 62792  #ifdef _WIN32
 62793  SQLITE_PRIVATE char * stristr(const char *haystack, const char *needle) {
 62794    if( !haystack || !needle ) return NULL;
 62795    do {
 62796      unsigned char *h = (unsigned char *) haystack;
 62797      unsigned char *n = (unsigned char *) needle;
 62798      while (sqlite3Tolower(*h)==sqlite3Tolower(*n) && *n) {
 62799        h++;
 62800        n++;
 62801      }
 62802      if (*n == 0) return haystack;
 62803    } while (*haystack++);
 62804    return NULL;
 62805  }
 62806  #else
 62807  #define stristr strcasestr
 62808  #endif
 62809  
 62810  #ifndef OMIT_BRANCH_LOG  /* this is to avoid warning of unused function */
 62811  
 62812  /*
 62813  ** Replace only the first ocurrence of oldstr by newstr
 62814  */
 62815  SQLITE_PRIVATE char * replace_first(char *mainstr, char *oldstr, char *newstr) {
 62816    int  oldlen, newlen, mainlen;
 62817    char *pfound;
 62818    if ((mainstr == NULL) || (oldstr == NULL) || (newstr == NULL)) return NULL;
 62819    mainlen = strlen(mainstr);
 62820    oldlen = strlen(oldstr);
 62821    newlen = strlen(newstr);
 62822    if ((mainlen == 0) || (oldlen == 0)) return mainstr;
 62823    if (newlen > oldlen) return NULL;
 62824    pfound = stristr(mainstr, oldstr);
 62825    if (pfound == NULL) return mainstr;
 62826    if (newlen>0) memcpy(pfound, newstr, newlen);
 62827    if (newlen < oldlen) {
 62828      memmove(pfound + newlen, pfound + oldlen, mainlen - (pfound - mainstr) - oldlen + 1);
 62829    }
 62830    return mainstr;
 62831  }
 62832  
 62833  #endif
 62834  
 62835  /*
 62836  ** Strip a string at the position of the given character.
 62837  */
 62838  SQLITE_PRIVATE char * stripchr(char *mainstr, int separator) {
 62839    char *ptr;
 62840  
 62841    if (mainstr == NULL) return NULL;
 62842  
 62843    ptr = strchr(mainstr, separator);
 62844    if (ptr == 0) return NULL;
 62845    ptr[0] = '\0';
 62846    ptr++;
 62847    return ptr;
 62848  
 62849  }
 62850  
 62851  #ifdef UNUSED_FUNCTION
 62852  
 62853  /*
 62854  ** Strip a string at the position of the given character, searching
 62855  ** in reverse order.
 62856  */
 62857  SQLITE_PRIVATE char * stripchrinv(char *mainstr, int separator) {
 62858    char *ptr;
 62859  
 62860    if (mainstr == NULL) return NULL;
 62861  
 62862    ptr = strrchr(mainstr, separator);
 62863    if (ptr == 0) return NULL;
 62864    ptr[0] = '\0';
 62865    ptr++;
 62866    return ptr;
 62867  
 62868  }
 62869  
 62870  /*
 62871  ** Strip a string at the position of a sub-string.
 62872  */
 62873  SQLITE_PRIVATE char * stripstr(char *mainstr, char *separator) {
 62874    char *ptr;
 62875  
 62876    if ((mainstr == NULL) || (separator == NULL)) return NULL;
 62877  
 62878    ptr = strstr(mainstr, separator);
 62879    if (ptr == 0) return NULL;
 62880    ptr[0] = '\0';
 62881    ptr += strlen(separator);
 62882    return ptr;
 62883  
 62884  }
 62885  
 62886  #endif
 62887  
 62888  /*
 62889  ** Strip a string at the position of a sub-string using
 62890  ** case insensitive comparison.
 62891  */
 62892  SQLITE_PRIVATE char * stripstri(char *mainstr, char *separator) {
 62893    char *ptr;
 62894  
 62895    if ((mainstr == NULL) || (separator == NULL)) return NULL;
 62896  
 62897    ptr = stristr(mainstr, separator);
 62898    if (ptr == 0) return NULL;
 62899    ptr[0] = '\0';
 62900    ptr += strlen(separator);
 62901    return ptr;
 62902  
 62903  }
 62904  
 62905  /*
 62906  ** Parse special characters in locus (modifies the passed string)
 62907  ** \n \t \xFF
 62908  */
 62909  SQLITE_PRIVATE void parse_delimiter(char *delim){
 62910    char *src, *dst, c;
 62911  
 62912    for( src=delim, dst=delim; *src; src++, dst++ ){
 62913      if( *src=='\\' ){
 62914        switch( src[1] ){
 62915        case 'n':
 62916          c = '\n';
 62917          src++;
 62918          goto loc_copy;
 62919        case 't':
 62920          c = '\t';
 62921          src++;
 62922          goto loc_copy;
 62923        case 'x':
 62924          c = (sqlite3HexToInt(src[2])<<4) | sqlite3HexToInt(src[3]);
 62925          src += 3;
 62926          goto loc_copy;
 62927        }
 62928      }
 62929      if( dst!=src ){
 62930         c = *src;
 62931  loc_copy:
 62932        *dst = c;
 62933      }
 62934    }
 62935  
 62936    if( dst!=src ){
 62937      *dst = 0;  /* null terminator */
 62938    }
 62939  
 62940  }
 62941  
 62942  /*
 62943  ** Reallocate the memory and "zero" the allocated space that is bigger than previously allocated.
 62944  */
 62945  SQLITE_PRIVATE void * sqlite3_realloc_zero(void *old_ptr, int old_nitems, int new_nitems, int item_size){
 62946    char *new_ptr = sqlite3_realloc(old_ptr, new_nitems * item_size);
 62947    if( !new_ptr ) return NULL;
 62948    else {
 62949      char *start = new_ptr + (old_nitems * item_size);
 62950      int size = (new_nitems - old_nitems) * item_size;
 62951      if( size > 0 ){
 62952        memset(start, 0, size);
 62953      }
 62954    }
 62955    return new_ptr;
 62956  }
 62957  
 62958  /*
 62959  ** Returns a copy of the data in allocated memory.
 62960  */
 62961  SQLITE_PRIVATE char * sqlite3_memdup(char *source, int size) {
 62962    char *dest;
 62963    if( !source || size<=0 ) return NULL;
 62964    dest = sqlite3_malloc(size);
 62965    if( dest ) memcpy(dest, source, size);
 62966    return dest;
 62967  }
 62968  
 62969  /*
 62970  ** Returns a copy of the string in allocated memory.
 62971  */
 62972  SQLITE_PRIVATE char * sqlite3_strdup(char *text) {
 62973    return sqlite3_memdup(text, strlen(text)+1);
 62974  }
 62975  
 62976  /*
 62977  ** Parsing of parameters
 62978  */
 62979  struct params {
 62980    const char *name;
 62981    int *result;
 62982    int value;
 62983    char **argument;
 62984  };
 62985  
 62986  SQLITE_PRIVATE void init_params(struct params *options){
 62987    int i;
 62988    for( i=0; options[i].name; i++ ){
 62989      *options[i].result = 0;
 62990      if( options[i].argument ) *options[i].argument = NULL;
 62991    }
 62992  }
 62993  
 62994  SQLITE_PRIVATE int check_param(char *param, struct params *options, char **remaining) {
 62995    int i;
 62996  
 62997    for( i=0; options[i].name; i++ ){
 62998      int len = strlen(options[i].name);
 62999      if( strncmp(param,options[i].name,len)==0 ){
 63000        char *p = param + len;
 63001        if( *p=='[' ){
 63002          if( !options[i].argument ) break;
 63003          p++;
 63004          *options[i].argument = p;
 63005          while( *p && *p!=']' ) p++;
 63006          if( *p==']' ){ 
 63007            *p = '\0'; p++;
 63008          }
 63009        } else if( *p && !sqlite3Isspace(*p) ){
 63010          continue;
 63011        }
 63012        *remaining = trimstr(p);
 63013        *options[i].result |= options[i].value;
 63014        return SQLITE_OK;
 63015      }
 63016    }
 63017  
 63018    /* no parameter found with this name */
 63019    *remaining = param;
 63020    return 1;
 63021  }
 63022  
 63023  SQLITE_PRIVATE int parse_params(char *params, struct params *options, char **remaining) {
 63024    int rc, i, size;
 63025    char *p, *tmp;
 63026  
 63027    init_params(options);
 63028  
 63029    params = trimstr(params);
 63030    *remaining = params;
 63031    p = params;
 63032  
 63033    /* search for options in the beginning */
 63034    while( *p=='-' ){
 63035      p++;
 63036      if( *p=='-' ){
 63037        p++;
 63038        if( (rc=check_param(p,options,remaining))!=SQLITE_OK ) return rc;
 63039        p = *remaining;
 63040      }
 63041    }
 63042  
 63043    tmp = *remaining;
 63044  
 63045    /* search for options at the end */
 63046    size = strlen(p);
 63047    for( i=size-1; i>=2; i-- ){
 63048      if( p[i]=='-' && p[i-1]=='-' && sqlite3Isspace(p[i-2]) ){
 63049        if( (rc=check_param(&p[i+1],options,remaining))!=SQLITE_OK ) return rc;
 63050        /* add a null terminator at the space position */
 63051        i-=2; p[i] = '\0';
 63052      }
 63053    }
 63054  
 63055    *remaining = tmp;
 63056    return SQLITE_OK;
 63057  }
 63058  
 63059  /*
 63060  ** Count the number of digits (base 10) in a positive integer
 63061  */
 63062  SQLITE_PRIVATE int numdigits(size_t len) {
 63063    int n = 1;
 63064    if ( len >= 100000000 ) { n += 8; len /= 100000000; }
 63065    if ( len >= 10000     ) { n += 4; len /= 10000; }
 63066    if ( len >= 100       ) { n += 2; len /= 100; }
 63067    if ( len >= 10        ) { n += 1; }
 63068    return n;
 63069  }
 63070  
 63071  #ifndef OMIT_BRANCH_LOG  /* this is to avoid warning of unused function */
 63072  
 63073  /*
 63074  ** Nestring parsing
 63075  */
 63076  
 63077  #define NETSTRING_ERROR_TOO_LONG      -1
 63078  #define NETSTRING_ERROR_NO_COLON      -2
 63079  #define NETSTRING_ERROR_TOO_SHORT     -3
 63080  #define NETSTRING_ERROR_NO_COMMA      -4
 63081  #define NETSTRING_ERROR_LEADING_ZERO  -5
 63082  #define NETSTRING_ERROR_NO_LENGTH     -6
 63083  
 63084  SQLITE_PRIVATE int netstring_read(char **pbuffer,         size_t *pbuffer_length,
 63085                                    char **netstring_start, size_t *netstring_length)
 63086  {
 63087    int i;
 63088    size_t len = 0;
 63089    char *buffer = *pbuffer;
 63090    size_t buffer_length = *pbuffer_length;
 63091  
 63092    /* Write default values for outputs */
 63093    *netstring_start = NULL;
 63094    *netstring_length = 0;
 63095  
 63096    /* Make sure buffer is big enough. Minimum size is 3. */
 63097    if (buffer_length < 3) return NETSTRING_ERROR_TOO_SHORT;
 63098  
 63099    /* No leading zeros allowed! */
 63100    if (buffer[0] == '0' && sqlite3Isdigit(buffer[1]))
 63101      return NETSTRING_ERROR_LEADING_ZERO;
 63102  
 63103    /* The netstring must start with a number */
 63104    if (!sqlite3Isdigit(buffer[0])) return NETSTRING_ERROR_NO_LENGTH;
 63105  
 63106    /* Read the number of bytes */
 63107    for (i = 0; i < buffer_length && sqlite3Isdigit(buffer[i]); i++) {
 63108      /* Error if more than 9 digits */
 63109      if (i >= 9) return NETSTRING_ERROR_TOO_LONG;
 63110      /* Accumulate each digit, assuming ASCII. */
 63111      len = len*10 + (buffer[i] - '0');
 63112    }
 63113  
 63114    /* Check buffer length once and for all. Specifically, we make sure
 63115       that the buffer is longer than the number we've read, the length
 63116       of the string itself, and the colon and comma. */
 63117    if (i + len + 1 >= buffer_length) return NETSTRING_ERROR_TOO_SHORT;
 63118  
 63119    /* Read the colon */
 63120    if (buffer[i++] != ':') return NETSTRING_ERROR_NO_COLON;
 63121  
 63122    /* Test for the trailing comma */
 63123    if (buffer[i + len] != ',') return NETSTRING_ERROR_NO_COMMA;
 63124  
 63125    /* Set the return values */
 63126    *netstring_start = &buffer[i];
 63127    *netstring_length = len;
 63128    *pbuffer = *netstring_start + len + 1;
 63129    *pbuffer_length = buffer_length - (i + len + 1);
 63130  
 63131    return 0;
 63132  }
 63133  
 63134  /*
 63135  ** Adds a buffer to the netstring
 63136  */
 63137  SQLITE_PRIVATE size_t netstring_add_ex(char **netstring, char *data, size_t len) {
 63138    size_t num_len, size_prev=0, size_next;
 63139    char *ptr;
 63140  
 63141    if (netstring == 0 || (len > 0 && data == 0)) return 0;
 63142  
 63143    num_len = numdigits(len);
 63144    size_next = num_len + len + 2;
 63145  
 63146    if (*netstring == 0) {
 63147      ptr = sqlite3_malloc(size_next + 1);
 63148      if (ptr == 0) return 0;
 63149      *netstring = ptr;
 63150    } else {
 63151      size_prev = strlen(*netstring);
 63152      ptr = sqlite3_realloc(*netstring, size_prev + size_next + 1);
 63153      if (ptr == 0) return 0;
 63154      *netstring = ptr;
 63155      ptr += size_prev;
 63156    }
 63157  
 63158    if (len == 0) {
 63159      strcpy(ptr, "0:,");
 63160    } else {
 63161      sqlite3_snprintf(num_len+2, ptr, "%lu:", (unsigned long)len);
 63162      ptr += num_len + 1;
 63163      memcpy(ptr, data, len);
 63164      ptr += len; *ptr = ',';
 63165      ptr++; *ptr = 0;
 63166    }
 63167    return size_prev + size_next;
 63168  }
 63169  
 63170  /*
 63171  ** Adds a null terminated string to the netstring
 63172  */
 63173  SQLITE_PRIVATE size_t netstring_add(char **netstring, char *str) {
 63174    return netstring_add_ex(netstring, str, strlen(str));
 63175  }
 63176  
 63177  #endif
 63178  
 63179  /*
 63180  ** Returns the Btree from the given db connection and db index
 63181  */
 63182  SQLITE_PRIVATE Btree * getBtreeFromiDb(sqlite3 *db, int iDb);
 63183  
 63184  /*
 63185  ** Returns the pager associated with a Btree
 63186  */
 63187  SQLITE_PRIVATE Pager * getPagerFromBtree(Btree *pBtree);
 63188  
 63189  /*
 63190  ** Returns the Pager from the given db connection and db index
 63191  */
 63192  SQLITE_PRIVATE Pager * getPagerFromiDb(sqlite3 *db, int iDb);
 63193  
 63194  /*
 63195  ** Returns the LMDB error code converted to SQLite
 63196  */
 63197  SQLITE_PRIVATE int lmdb_error(int rc){
 63198  
 63199    BRANCHTRACE("lmdb error: %d", rc);
 63200  
 63201    switch( rc ){
 63202  
 63203      /** key/data pair already exists */
 63204      //case MDB_KEYEXIST:
 63205      //  return SQLITE_ ;
 63206  
 63207      /** key/data pair not found (EOF) */
 63208      case MDB_NOTFOUND:
 63209        return SQLITE_NOTFOUND;
 63210  
 63211      /** Requested page not found - this usually indicates corruption */
 63212      case MDB_PAGE_NOTFOUND:
 63213      /** Located page was wrong type */
 63214      case MDB_CORRUPTED:
 63215        return SQLITE_CORRUPT;
 63216  
 63217      /** Update of meta page failed or environment had fatal error */
 63218      case MDB_PANIC:
 63219        return SQLITE_IOERR;
 63220  
 63221      /** Environment version mismatch */
 63222      case MDB_VERSION_MISMATCH:
 63223      /** File is not a valid LMDB file */
 63224      case MDB_INVALID:
 63225        return SQLITE_NOTADB;
 63226  
 63227      /** Environment mapsize reached */
 63228      case MDB_MAP_FULL:
 63229      /** Database contents grew beyond environment mapsize */
 63230      case MDB_MAP_RESIZED:
 63231        return SQLITE_FULL;
 63232  
 63233      /** Environment maxdbs reached */
 63234      case MDB_DBS_FULL:
 63235      /** Environment maxreaders reached */
 63236      case MDB_READERS_FULL:
 63237      /** Too many TLS keys in use - Windows only */
 63238      case MDB_TLS_FULL:
 63239      /** Txn has too many dirty pages */
 63240      case MDB_TXN_FULL:
 63241        return SQLITE_INTERRUPT;
 63242  
 63243      /** Cursor stack too deep - internal error */
 63244      case MDB_CURSOR_FULL:
 63245      /** Page has not enough space - internal error */
 63246      case MDB_PAGE_FULL:
 63247      /** Operation and DB incompatible, or DB type changed. This can mean:
 63248       *	<ul>
 63249       *	<li>The operation expects an #MDB_DUPSORT / #MDB_DUPFIXED database.
 63250       *	<li>Opening a named DB when the unnamed DB has #MDB_DUPSORT / #MDB_INTEGERKEY.
 63251       *	<li>Accessing a data record as a database, or vice versa.
 63252       *	<li>The database was dropped and recreated with different flags.
 63253       *	</ul>
 63254       */
 63255      case MDB_INCOMPATIBLE:
 63256      /** Invalid reuse of reader locktable slot */
 63257      case MDB_BAD_RSLOT:
 63258      /** The specified DBI was changed unexpectedly */
 63259      case MDB_BAD_DBI:
 63260        return SQLITE_INTERNAL;
 63261  
 63262      /** Unsupported size of key/DB name/data, or wrong DUPFIXED size */
 63263      case MDB_BAD_VALSIZE:
 63264        return SQLITE_TOOBIG;
 63265  
 63266      /** Transaction must abort, has a child, or is invalid */
 63267      case MDB_BAD_TXN:
 63268        return SQLITE_ABORT;
 63269  
 63270      case ENOMEM:
 63271      case ENOEXEC:
 63272        return SQLITE_NOMEM;
 63273      case EPERM:
 63274        return SQLITE_PERM;
 63275      case EACCES:
 63276        return SQLITE_READONLY;
 63277      case ENOENT:
 63278        return SQLITE_CANTOPEN;
 63279      case EIO:
 63280        return SQLITE_IOERR;
 63281      case ENOSPC:
 63282        return SQLITE_FULL;
 63283      case EINVAL:
 63284        return SQLITE_INTERNAL;
 63285  
 63286      case MDB_SUCCESS:
 63287        return SQLITE_OK;
 63288  
 63289      default:
 63290        return SQLITE_ERROR;
 63291  
 63292    }
 63293  
 63294  }
 63295  
 63296  /*
 63297  ** Helper function to read values from LMDB
 63298  */
 63299  SQLITE_PRIVATE int mdb_str_get(MDB_txn *txn, MDB_dbi dbi, char *keyname, char **pvalue, u32 *psize){
 63300    MDB_val key, value;
 63301    int rc;
 63302  
 63303    BRANCHTRACE("mdb_str_get key: %s", keyname);
 63304  
 63305    if( !txn || !keyname || !pvalue ) return MDB_INVALID;
 63306    *pvalue = 0;
 63307  
 63308    /* set the key */
 63309    key.mv_data = keyname;
 63310    key.mv_size = strlen(keyname);
 63311  
 63312    /* get the value */
 63313    rc = mdb_get(txn, dbi, &key, &value);
 63314    if( rc==MDB_SUCCESS ){
 63315      *pvalue = (char*)value.mv_data;
 63316      if( psize ) *psize = value.mv_size;
 63317    } else if( rc==MDB_NOTFOUND ){
 63318      BRANCHTRACE("mdb_str_get - NOT FOUND");
 63319    }
 63320  
 63321    /* return the result */
 63322    return rc;
 63323  
 63324  }
 63325  
 63326  /*
 63327  ** Helper function to read string values from LMDB
 63328  */
 63329  SQLITE_PRIVATE int mdb_str_get_str(MDB_txn *txn, MDB_dbi dbi, char *keyname, char **pvalue){
 63330    u32 size;
 63331    int rc = mdb_str_get(txn, dbi, keyname, pvalue, &size);
 63332    if( rc==MDB_SUCCESS && size==0 ){
 63333      rc = MDB_NOTFOUND;
 63334    }
 63335    return rc;
 63336  }
 63337  
 63338  /*
 63339  ** Helper function to read u64 values from LMDB
 63340  */
 63341  SQLITE_PRIVATE int mdb_get_u64(MDB_txn *txn, MDB_dbi dbi, MDB_val *pkey, u64 *pvalue){
 63342    MDB_val value;
 63343    int rc;
 63344  
 63345    if( !txn || !pkey || !pvalue ) return MDB_INVALID;
 63346    *pvalue = 0;
 63347  
 63348    /* get the value */
 63349    rc = mdb_get(txn, dbi, pkey, &value);
 63350    if( rc==MDB_SUCCESS ){
 63351      int ret = sqlite4GetVarint64( (const unsigned char*)value.mv_data, value.mv_size, pvalue);
 63352      if( ret>0 ){
 63353        BRANCHTRACE("mdb_get_varint value: %llu", *pvalue);
 63354      } else {
 63355        rc = MDB_BAD_VALSIZE;
 63356      }
 63357    } else if( rc==MDB_NOTFOUND ){
 63358      BRANCHTRACE("mdb_get_varint - NOT FOUND");
 63359    }
 63360  
 63361    /* return the result */
 63362    return rc;
 63363  
 63364  }
 63365  
 63366  /*
 63367  ** Helper function to read unsigned int values from LMDB
 63368  */
 63369  SQLITE_PRIVATE int mdb_get_u32(MDB_txn *txn, MDB_dbi dbi, MDB_val *pkey, u32 *pvalue){
 63370    u64 value;
 63371    int rc = mdb_get_u64(txn, dbi, pkey, &value);
 63372    if( rc==MDB_SUCCESS ){
 63373      if( value<=0xFFFFFFFFLL ){
 63374        *pvalue = value;
 63375      } else {
 63376        rc = MDB_BAD_VALSIZE;
 63377      }
 63378    }
 63379    return rc;
 63380  }
 63381  
 63382  /*
 63383  ** Helper function to read unsigned int values from LMDB
 63384  */
 63385  SQLITE_PRIVATE int mdb_str_get_u64(MDB_txn *txn, MDB_dbi dbi, char *keyname, u64 *pvalue){
 63386    MDB_val key;
 63387  
 63388    BRANCHTRACE("mdb_str_get_u64 key: %s", keyname);
 63389  
 63390    if( !txn || !keyname || !pvalue ) return MDB_INVALID;
 63391    *pvalue = 0;
 63392  
 63393    /* set the key */
 63394    key.mv_data = keyname;
 63395    key.mv_size = strlen(keyname);
 63396  
 63397    /* get the value */
 63398    return mdb_get_u64(txn, dbi, &key, pvalue);
 63399  
 63400  }
 63401  
 63402  /*
 63403  ** Helper function to read unsigned int values from LMDB
 63404  */
 63405  SQLITE_PRIVATE int mdb_str_get_u32(MDB_txn *txn, MDB_dbi dbi, char *keyname, u32 *pvalue){
 63406    MDB_val key;
 63407  
 63408    BRANCHTRACE("mdb_str_get_u32 key: %s", keyname);
 63409  
 63410    if( !txn || !keyname || !pvalue ) return MDB_INVALID;
 63411    *pvalue = 0;
 63412  
 63413    /* set the key */
 63414    key.mv_data = keyname;
 63415    key.mv_size = strlen(keyname);
 63416  
 63417    /* get the value */
 63418    return mdb_get_u32(txn, dbi, &key, pvalue);
 63419  
 63420  }
 63421  
 63422  /*
 63423  ** Helper function to read int values from LMDB
 63424  ** For now it is just calling the unsigned int get function
 63425  */
 63426  SQLITE_PRIVATE int mdb_str_get_int(MDB_txn *txn, MDB_dbi dbi, char *keyname, int *pvalue){
 63427    return mdb_str_get_u32(txn, dbi, keyname, (u32*)pvalue);
 63428  }
 63429  
 63430  /*
 63431  ** Helper function to read unsigned int values from LMDB
 63432  */
 63433  SQLITE_PRIVATE int mdb_u64_get_u32(MDB_txn *txn, MDB_dbi dbi, u64 ikey, u32 *pvalue){
 63434    MDB_val key;
 63435    unsigned char buf[12];
 63436  
 63437    BRANCHTRACE("mdb_u64_get_u32 %llu", ikey);
 63438  
 63439    if( !txn ) return MDB_INVALID;
 63440  
 63441    /* set the key */
 63442    //mdb_value_set_u64(&key, buf, ikey);
 63443    key.mv_data = buf;
 63444    key.mv_size = sqlite4PutVarint64(buf, ikey);
 63445  
 63446    /* get the value */
 63447    return mdb_get_u32(txn, dbi, &key, pvalue);
 63448  
 63449  }
 63450  
 63451  /*
 63452  ** Helper function to write values to LMDB
 63453  */
 63454  SQLITE_PRIVATE int mdb_str_put(MDB_txn *txn, MDB_dbi dbi, char *keyname, char *data, int size){
 63455    MDB_val key, value;
 63456  
 63457    //BRANCHTRACE("mdb_str_put %s = %s", keyname, to_hex(data,size));
 63458  
 63459    if( !txn || !keyname ) return MDB_INVALID;
 63460  
 63461    /* set the key */
 63462    key.mv_data = keyname;
 63463    key.mv_size = strlen(keyname);
 63464  
 63465    /* set the value with the null terminator */
 63466    value.mv_data = data;
 63467    value.mv_size = size;
 63468  
 63469    /* store the data */
 63470    return mdb_put(txn, dbi, &key, &value, 0);
 63471  
 63472  }
 63473  
 63474  /*
 63475  ** Helper function to write unsigned int values to LMDB
 63476  */
 63477  SQLITE_PRIVATE int mdb_str_put_u64(MDB_txn *txn, MDB_dbi dbi, char *keyname, u64 ivalue){
 63478    MDB_val key, value;
 63479    unsigned char buf[12];
 63480  
 63481    BRANCHTRACE("mdb_str_put_u64 %s = %llu", keyname, ivalue);
 63482  
 63483    if( !txn || !keyname ) return MDB_INVALID;
 63484  
 63485    /* set the key */
 63486    key.mv_data = keyname;
 63487    key.mv_size = strlen(keyname);
 63488  
 63489    /* set the value */
 63490    value.mv_data = buf;
 63491    value.mv_size = sqlite4PutVarint64(buf, ivalue);
 63492  
 63493    /* store the data */
 63494    return mdb_put(txn, dbi, &key, &value, 0);
 63495  
 63496  }
 63497  
 63498  #define mdb_str_put_u32 mdb_str_put_u64
 63499  
 63500  /*
 63501  ** Helper function to write int values to LMDB
 63502  */
 63503  SQLITE_PRIVATE int mdb_str_put_int(MDB_txn *txn, MDB_dbi dbi, char *keyname, int ivalue){
 63504    return mdb_str_put_u64(txn, dbi, keyname, ivalue);
 63505  }
 63506  
 63507  /*
 63508  ** Helper function to write null terminated string values to LMDB
 63509  */
 63510  SQLITE_PRIVATE int mdb_str_put_str(MDB_txn *txn, MDB_dbi dbi, char *keyname, char *svalue){
 63511    BRANCHTRACE("mdb_str_put_str %s = %s", keyname, svalue);
 63512    /* store the value with the null terminator  */
 63513    return mdb_str_put(txn, dbi, keyname, svalue, strlen(svalue) + 1);
 63514  }
 63515  
 63516  /*
 63517  ** Helper function to write int values to LMDB
 63518  */
 63519  SQLITE_PRIVATE int mdb_u64_put_u32(MDB_txn *txn, MDB_dbi dbi, u64 ikey, u32 ivalue){
 63520    MDB_val key, value;
 63521    unsigned char buf1[12], buf2[12];
 63522  
 63523    BRANCHTRACE("mdb_u64_put_u32 %llu = %u", ikey, ivalue);
 63524  
 63525    if( !txn ) return MDB_INVALID;
 63526  
 63527    /* set the key */
 63528    key.mv_data = buf1;
 63529    key.mv_size = sqlite4PutVarint64(buf1, ikey);
 63530  
 63531    /* set the value */
 63532    value.mv_data = buf2;
 63533    value.mv_size = sqlite4PutVarint64(buf2, ivalue);
 63534  
 63535    /* store the data */
 63536    return mdb_put(txn, dbi, &key, &value, 0);
 63537  
 63538  }
 63539  
 63540  /*
 63541  ** Initialize the use of branches on the pager (open the LMDB environment)
 63542  */
 63543  SQLITE_PRIVATE int sqlite3BranchInit(Pager *pPager){
 63544    sqlite3_mutex *mutex;
 63545    struct global_lmdb *g_lmdb;
 63546    lmdb *lmdb;
 63547    int rc;
 63548  
 63549    BRANCHTRACE("sqlite3BranchInit");
 63550  
 63551    /* if it was already initialized, exit */
 63552    if( pPager->lmdb ) return SQLITE_OK;
 63553  
 63554    /* allocate memory for the struct */
 63555    lmdb = sqlite3_malloc(sizeof(struct lmdb));
 63556    if( lmdb==0 ) return SQLITE_NOMEM;
 63557    memset(lmdb, 0, sizeof(struct lmdb));
 63558  
 63559    BRANCHTRACE("sqlite3BranchInit - lmdb struct allocated");
 63560  
 63561    /* use a mutex to access the global list of open LMDB environments */
 63562    mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_APP3);
 63563    sqlite3_mutex_enter(mutex);
 63564  
 63565    /* search for an already open environment for this db */
 63566    for( g_lmdb = global_lmdb; g_lmdb; g_lmdb = g_lmdb->next ){
 63567      const char *dbpath;
 63568      if( mdb_env_get_path(g_lmdb->env,&dbpath)==MDB_SUCCESS ){
 63569        if( strcmp(pPager->zFilename,dbpath)==0 ) break;  //! filenames on Windows are case insensitive!!
 63570      }
 63571    }
 63572    /* if no environment was found for the given db path */
 63573    if( !g_lmdb ){
 63574      /* allocate a new list member */
 63575      g_lmdb = sqlite3_malloc(sizeof(struct global_lmdb));
 63576      if( !g_lmdb ){
 63577        sqlite3_free(lmdb);
 63578        rc = SQLITE_NOMEM;
 63579        goto loc_exit;
 63580      }
 63581      /* zero the fields */
 63582      g_lmdb->env = NULL;
 63583      g_lmdb->refcount = 0;
 63584    }
 63585  
 63586    /* found? */
 63587    if( g_lmdb->env ){
 63588      /* use the already open environment */
 63589      lmdb->env = g_lmdb->env;
 63590    } else {
 63591      /* create and open a new LMDB environment */
 63592      if( (rc=mdb_env_create(&lmdb->env)) != MDB_SUCCESS ) goto loc_failed;
 63593      if( (rc=mdb_env_set_maxdbs(lmdb->env,1024)) != MDB_SUCCESS ) goto loc_failed;
 63594      if( (rc=mdb_env_set_mapsize(lmdb->env,pPager->max_db_size)) != MDB_SUCCESS ) goto loc_failed;
 63595      if( (rc=mdb_env_open(lmdb->env,pPager->zFilename,MDB_NOSUBDIR|MDB_NOTLS,0664)) != MDB_SUCCESS ) goto loc_failed;
 63596    }
 63597  
 63598    /* open the main database */
 63599    if( (rc=mdb_txn_begin(lmdb->env, NULL, MDB_RDONLY, &lmdb->txn)) != MDB_SUCCESS ) goto loc_failed;
 63600    if( (rc=mdb_dbi_open(lmdb->txn, NULL,   0, &lmdb->main_db))!=MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63601  #ifndef OMIT_BRANCH_LOG
 63602    if( (rc=mdb_dbi_open(lmdb->txn, "logs", 0, &lmdb->logs_db))!=MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63603  #endif
 63604    if( (rc=mdb_dbi_open(lmdb->txn, "meta", 0, &lmdb->meta_db))!=MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63605    if( (rc=mdb_txn_commit(lmdb->txn)) != MDB_SUCCESS ) goto loc_failed;
 63606    lmdb->txn = 0;
 63607  
 63608    /* store the page size */
 63609    lmdb->pageSize = pPager->pageSize;
 63610  
 63611    /* save the new struct */
 63612    pPager->lmdb = lmdb;
 63613  
 63614    /* if a new LMDB environment was created */
 63615    if( !g_lmdb->env ){
 63616      /* save the new environment */
 63617      g_lmdb->env = lmdb->env;
 63618      g_lmdb->refcount = 1;
 63619      /* add it to the linked list */
 63620      g_lmdb->next = global_lmdb;
 63621      global_lmdb = g_lmdb;
 63622    } else {
 63623      /* increment the reference counter */
 63624      g_lmdb->refcount++;
 63625    }
 63626  
 63627    /* save the pointer to the global struct */
 63628    lmdb->global = g_lmdb;
 63629  
 63630    rc = SQLITE_OK;
 63631  
 63632  loc_exit:
 63633  
 63634    sqlite3_mutex_leave(mutex);
 63635    return rc;
 63636  
 63637  loc_failed:
 63638  
 63639    BRANCHTRACE("sqlite3BranchInit - failed");
 63640    if( lmdb ){
 63641      if( lmdb->env && !g_lmdb->env ){
 63642        mdb_env_close(lmdb->env);
 63643      }
 63644      sqlite3_free(lmdb);
 63645    }
 63646    if( g_lmdb && !g_lmdb->env ) sqlite3_free(g_lmdb);
 63647    rc = lmdb_error(rc);
 63648    goto loc_exit;
 63649  
 63650  }
 63651  
 63652  /*
 63653  ** Find the branch by name and returns its id.
 63654  ** The comparison is case sensitive.
 63655  ** If it is not found, returns -1.
 63656  */
 63657  SQLITE_PRIVATE int sqlite3BranchFind(lmdb *lmdb, char *name){
 63658    int i;
 63659  
 63660    BRANCHTRACE("sqlite3BranchFind [%s]", name);
 63661  
 63662    if( !lmdb || !name ) return -1;
 63663  
 63664    for( i=1; i <= lmdb->num_branches; i++ )  /* use base 1 access to the array */
 63665      if( lmdb->branches[i].visible && strcmp(lmdb->branches[i].name,name)==0 )
 63666        return i;
 63667  
 63668    /* not found */
 63669    return -1;
 63670  
 63671  }
 63672  
 63673  /*
 63674  
 63675  TRANSITION from read to write transactions MUST invalidade the read values/pages BECAUSE another thread may had
 63676  written to the db and this one should reload the values...
 63677  
 63678  maybe this is not a problem
 63679  
 63680  BEGIN
 63681  SELECT ...  <- start read txn and load pages
 63682  UPDATE ...  <- move to write txn!!! no problem on single access to the db, but a problem if used by many connections and another changed the db
 63683  
 63684    normal SQLite with WAL will return SQLITE_BUSY_SNAPSHOT (https://www.sqlite.org/rescode.html#busy_snapshot)
 63685  
 63686    solution 1: return the same error message!
 63687                that can be detected using the change_counter
 63688  
 63689    solution 2: use a BEGIN WRITE command to inform a write operation should occur in the current txn
 63690                and return an error if a write is tried on a read txn
 63691  
 63692  */
 63693  
 63694  /*
 63695  ** Update the current branch in use
 63696  ** If the branch with the given name is not found, don't change the current branch
 63697  */
 63698  SQLITE_PRIVATE int set_current_branch(lmdb *lmdb, char *name, u64 max_commit){
 63699    branch_info *branch;
 63700    int branch_id;
 63701  
 63702    /* search for the branch with the given name */
 63703    branch_id = sqlite3BranchFind(lmdb, name);
 63704  
 63705    /* not found? */
 63706    if( branch_id <= 0 ) return SQLITE_NOTFOUND;
 63707  
 63708    /* check if the max commit is valid */
 63709    branch = &lmdb->branches[branch_id];
 63710    if( max_commit > branch->last_commit ) return SQLITE_NOTFOUND;  //! should it zero/reset the current_branch bellow? maybe not, keeping at the current branch position.
 63711  
 63712    /* check if the max commit is accessible */
 63713    if( max_commit > 0 ){
 63714      int is_accessible;
 63715      int rc = is_commit_accessible(lmdb, branch_id, max_commit, &is_accessible);
 63716      BRANCHTRACE("is_commit_accessible rc=%d is_accessible=%d", rc, is_accessible);
 63717      if( rc ) return rc;
 63718      if( !is_accessible ) return SQLITE_NOTFOUND;
 63719    }
 63720  
 63721    /* update the selection */
 63722    strcpy(lmdb->current_branch_name, name);
 63723    lmdb->current_branch_commit = max_commit;
 63724  
 63725    /* update the array */
 63726    lmdb->current_branch = branch;
 63727    lmdb->current_branch->max_commit = max_commit;
 63728  
 63729    return SQLITE_OK;
 63730  }
 63731  
 63732  /*
 63733  ** Update the current branch in use.
 63734  ** If the branch is not found (was deleted or renamed), the current branch is invalid.
 63735  ** This is because as the library is reusing branch slots on the array (branch ids) a 
 63736  ** delete followed by a new branch may be identified as a rename. We can avoid this by
 63737  ** using a unique id for each in a key (uid=value).
 63738  */
 63739  SQLITE_PRIVATE int update_current_branch(lmdb *lmdb){
 63740    int branch_id;
 63741  
 63742    /* if no name is set, use the default */
 63743    if( lmdb->current_branch_name[0]=='\0' ){
 63744      /* try to use the name "master" */
 63745      int rc = set_current_branch(lmdb, "master", 0);
 63746      /* if not found, use the first available branch */
 63747      if( rc==SQLITE_NOTFOUND ){
 63748        int i;
 63749        for(i=1; i<=lmdb->num_branches; i++){
 63750          if( lmdb->branches[i].visible )
 63751            return set_current_branch(lmdb, lmdb->branches[i].name, 0);
 63752        }
 63753        /* if none is visible it will return SQLITE_NOTFOUND bellow */
 63754      }
 63755      return rc;
 63756    }
 63757  
 63758    /* search for the branch with the given name */
 63759    branch_id = sqlite3BranchFind(lmdb, lmdb->current_branch_name);
 63760  
 63761    /* not found? */
 63762    if( branch_id <= 0 ){
 63763      lmdb->current_branch = NULL;
 63764      return SQLITE_NOTFOUND;
 63765    }
 63766  
 63767    lmdb->current_branch = &lmdb->branches[branch_id];
 63768  
 63769    /* check if the max commit is valid */
 63770    if( lmdb->current_branch_commit > lmdb->current_branch->last_commit ){
 63771      lmdb->current_branch = NULL;
 63772      return SQLITE_NOTFOUND;
 63773    }
 63774    lmdb->current_branch->max_commit = lmdb->current_branch_commit;
 63775  
 63776    //set_current_branch(lmdb, branch_id);
 63777    return SQLITE_OK;
 63778  
 63779  }
 63780  
 63781  /*
 63782  ** Reset the page cache and invalidate the loaded schemas
 63783  */
 63784  SQLITE_PRIVATE int invalidate_loaded_sqlite_data(sqlite3 *db, Btree *pBtree){
 63785    Pager *pPager = getPagerFromBtree(pBtree);
 63786  
 63787    BRANCHTRACE("reseting the page cache and invalidating the db schema");
 63788  
 63789    if( !db || !pBtree || !pPager ) return SQLITE_ERROR;
 63790  
 63791    /* reset the btrees, invalidate the loaded schemas and the prepared statements */
 63792    db->mDbFlags |= DBFLAG_SchemaChange;
 63793    sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 63794    sqlite3CloseSavepoints(db);
 63795  
 63796    /* reset the page cache */
 63797    pager_reset(pPager);
 63798  
 63799    return SQLITE_OK;
 63800  
 63801  }
 63802  
 63803  /*
 63804  ** Helper function to put value to LMDB main db
 63805  */
 63806  SQLITE_PRIVATE int put_branch_int(lmdb *lmdb, int branch_id, char *key, int value){
 63807    char buf[128];
 63808    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63809    return mdb_str_put_int(lmdb->txn, lmdb->main_db, buf, value);
 63810  }
 63811  
 63812  #ifdef UNUSED_FUNCTION
 63813  /*
 63814  ** Helper function to put value to LMDB main db
 63815  */
 63816  SQLITE_PRIVATE int put_branch_u32(lmdb *lmdb, int branch_id, char *key, u32 value){
 63817    char buf[128];
 63818    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63819    return mdb_str_put_u32(lmdb->txn, lmdb->main_db, buf, value);
 63820  }
 63821  #endif
 63822  
 63823  /*
 63824  ** Helper function to put value to LMDB main db
 63825  */
 63826  SQLITE_PRIVATE int put_branch_u64(lmdb *lmdb, int branch_id, char *key, u64 value){
 63827    char buf[128];
 63828    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63829    return mdb_str_put_u64(lmdb->txn, lmdb->main_db, buf, value);
 63830  }
 63831  
 63832  /*
 63833  ** Helper function to put value to LMDB main db
 63834  */
 63835  SQLITE_PRIVATE int put_branch_str(lmdb *lmdb, int branch_id, char *key, char *value){
 63836    char buf[128];
 63837    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63838    return mdb_str_put_str(lmdb->txn, lmdb->main_db, buf, value);
 63839  }
 63840  
 63841  /*
 63842  ** Helper function to get value from LMDB main db
 63843  */
 63844  SQLITE_PRIVATE int get_branch_int(lmdb *lmdb, int branch_id, char *key, int *pvalue){
 63845    char buf[128];
 63846    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63847    return mdb_str_get_int(lmdb->txn, lmdb->main_db, buf, pvalue);
 63848  }
 63849  
 63850  #ifdef UNUSED_FUNCTION
 63851  /*
 63852  ** Helper function to get value from LMDB main db
 63853  */
 63854  SQLITE_PRIVATE int get_branch_u32(lmdb *lmdb, int branch_id, char *key, u32 *pvalue){
 63855    char buf[128];
 63856    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63857    return mdb_str_get_u32(lmdb->txn, lmdb->main_db, buf, pvalue);
 63858  }
 63859  #endif
 63860  
 63861  /*
 63862  ** Helper function to get value from LMDB main db
 63863  */
 63864  SQLITE_PRIVATE int get_branch_u64(lmdb *lmdb, int branch_id, char *key, u64 *pvalue){
 63865    char buf[128];
 63866    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63867    return mdb_str_get_u64(lmdb->txn, lmdb->main_db, buf, pvalue);
 63868  }
 63869  
 63870  /*
 63871  ** Helper function to get value from LMDB main db
 63872  */
 63873  SQLITE_PRIVATE int get_branch_str(lmdb *lmdb, int branch_id, char *key, char *pvalue){
 63874    int rc;
 63875    char buf[128], *value;
 63876    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, key);
 63877    rc = mdb_str_get_str(lmdb->txn, lmdb->main_db, buf, &value);
 63878    if( rc==MDB_SUCCESS ) strcpy(pvalue, value);
 63879    return rc;
 63880  }
 63881  
 63882  /*
 63883  ** Helper function to delete a key from LMDB main db
 63884  */
 63885  SQLITE_PRIVATE int del_branch_key(lmdb *lmdb, int branch_id, char *keyname){
 63886    char buf[128];
 63887    MDB_val key;
 63888    sqlite3_snprintf(sizeof(buf), buf, "b%d.%s", branch_id, keyname);
 63889    BRANCHTRACE("del_branch_key %s", buf);
 63890    key.mv_data = buf;
 63891    key.mv_size = strlen(buf);
 63892    return mdb_del(lmdb->txn, lmdb->main_db, &key, NULL);
 63893  }
 63894  
 63895  /*
 63896  ** Loads the branch info from the database to the array
 63897  */
 63898  SQLITE_PRIVATE int load_branch(lmdb *lmdb, int branch_id){
 63899    struct branch_info *branch;
 63900    int rc;
 63901  
 63902    BRANCHTRACE("load_branch - branch id: %d", branch_id);
 63903  
 63904    if( !lmdb || branch_id<=0 || branch_id>lmdb->num_branches ) return SQLITE_ERROR;
 63905  
 63906    /* pointer to the array item */
 63907    branch = &lmdb->branches[branch_id];
 63908  
 63909    /* read value from the main db */
 63910    rc = get_branch_int(lmdb, branch_id, "visible", &branch->visible);
 63911    /* if the key is not found then the branch is no more in use */
 63912    if( rc==MDB_NOTFOUND ){
 63913      branch->id = 0;
 63914      return SQLITE_OK;
 63915    } else if( rc!=MDB_SUCCESS ) goto loc_failed;
 63916  
 63917    /* the branch is in use so we must set its id... */
 63918    branch->id = branch_id;
 63919  
 63920    /* ...and load the values */
 63921    if( (rc = get_branch_str(lmdb, branch_id, "name",          branch->name          )) != MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63922    if( (rc = get_branch_int(lmdb, branch_id, "source_branch", &branch->source_branch)) != MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63923    if( (rc = get_branch_u64(lmdb, branch_id, "source_commit", &branch->source_commit)) != MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63924    if( (rc = get_branch_u64(lmdb, branch_id, "last_commit",   &branch->last_commit  )) != MDB_SUCCESS && rc!=MDB_NOTFOUND ) goto loc_failed;
 63925  
 63926    BRANCHTRACE("load_branch OK");
 63927  
 63928    return SQLITE_OK;
 63929  
 63930  loc_failed:
 63931    return lmdb_error(rc);
 63932  
 63933  }
 63934  
 63935  /*
 63936  ** Saves the branch info from the array to the database
 63937  */
 63938  SQLITE_PRIVATE int save_branch(lmdb *lmdb, int branch_id){
 63939    struct branch_info *branch;
 63940    int rc;
 63941  
 63942    BRANCHTRACE("save_branch - branch id: %d", branch_id);
 63943  
 63944    if( !lmdb || branch_id<=0 || branch_id>lmdb->num_branches ) return SQLITE_ERROR;
 63945  
 63946    /* pointer to the array item */
 63947    branch = &lmdb->branches[branch_id];
 63948  
 63949    /* if the branch is no more in use */
 63950    if( branch->id==0 ){
 63951      /* delete the values from the main db */
 63952      del_branch_key(lmdb, branch_id, "name");
 63953      del_branch_key(lmdb, branch_id, "visible");
 63954      del_branch_key(lmdb, branch_id, "source_branch");
 63955      del_branch_key(lmdb, branch_id, "source_commit");
 63956      del_branch_key(lmdb, branch_id, "last_commit");
 63957      return SQLITE_OK;
 63958    }
 63959  
 63960    /* store the new values in the main db */
 63961    if( (rc = put_branch_str(lmdb, branch_id, "name",          branch->name         )) != MDB_SUCCESS ) goto loc_failed;
 63962    if( (rc = put_branch_int(lmdb, branch_id, "visible",       branch->visible      )) != MDB_SUCCESS ) goto loc_failed;
 63963    if( (rc = put_branch_int(lmdb, branch_id, "source_branch", branch->source_branch)) != MDB_SUCCESS ) goto loc_failed;
 63964    if( (rc = put_branch_u64(lmdb, branch_id, "source_commit", branch->source_commit)) != MDB_SUCCESS ) goto loc_failed;
 63965    if( (rc = put_branch_u64(lmdb, branch_id, "last_commit",   branch->last_commit  )) != MDB_SUCCESS ) goto loc_failed;
 63966  
 63967    /* store the max branch id */
 63968    if( (rc = mdb_str_put_int(lmdb->txn, lmdb->main_db, "last_branch_id", lmdb->num_branches)) != MDB_SUCCESS ) goto loc_failed;
 63969  
 63970    BRANCHTRACE("save_branch OK");
 63971  
 63972    return SQLITE_OK;
 63973  
 63974  loc_failed:
 63975    return lmdb_error(rc);
 63976  
 63977  }
 63978  
 63979  /*
 63980  ** Load the list of branches to the array
 63981  ** A transaction must be open prior to calling this function
 63982  ** If no branch name was specified, use the first one (master) as the current
 63983  */
 63984  SQLITE_PRIVATE int sqlite3BranchLoadArray(lmdb *lmdb){
 63985    int num_branches;
 63986    int rc, i;
 63987  
 63988    BRANCHTRACE("sqlite3BranchLoadArray");
 63989  
 63990    if( !lmdb ) return SQLITE_ERROR;
 63991  
 63992    /* get the total number of branches */
 63993    rc =  mdb_str_get_int(lmdb->txn, lmdb->main_db, "last_branch_id", &num_branches);
 63994    if( rc!=MDB_SUCCESS && rc!=MDB_NOTFOUND ) return lmdb_error(rc);
 63995  
 63996    /* is the array already loaded? */
 63997    if( !lmdb->branches ){
 63998      /* allocate memory for the array */
 63999      int max_branches = num_branches>0 ? num_branches : 1; // at least one item
 64000      lmdb->branches = sqlite3MallocZero((max_branches + 1) * sizeof(struct branch_info)); // allocate one more to use base 1 array access
 64001      if( !lmdb->branches ) return SQLITE_NOMEM;
 64002      lmdb->num_branches = max_branches;
 64003    /* has the number of branches changed? */
 64004    } else if( num_branches != lmdb->num_branches ){
 64005      /* allocate memory for the array */
 64006      branch_info *branches;
 64007      int max_branches = num_branches>0 ? num_branches : 1;
 64008      branches = sqlite3_realloc_zero(lmdb->branches, lmdb->num_branches + 1, max_branches + 1, sizeof(struct branch_info));
 64009      if( !branches ) return SQLITE_NOMEM;
 64010      lmdb->branches = branches;
 64011      lmdb->num_branches = max_branches;
 64012    }
 64013  
 64014    /* is the db empty? */
 64015    if( num_branches==0 ){
 64016      /* initialize the branch array */
 64017      lmdb->branches[1].id = 1;
 64018      lmdb->branches[1].visible = 1;
 64019      lmdb->branches[1].is_new = 1;
 64020      strcpy(lmdb->branches[1].name, "master");
 64021      /* set the current branch */
 64022      return set_current_branch(lmdb, "master", 0);
 64023    }
 64024  
 64025    /* clear the max_page of all branches to reload them later because the number of
 64026    ** pages can have been modified on another db connection */
 64027    for( i=1; i<=num_branches; i++ ){
 64028      lmdb->branches[i].max_page = 0;
 64029    }
 64030  
 64031    /* load each branch info into the array */
 64032    for( i=1; i<=num_branches; i++ ){
 64033      rc = load_branch(lmdb, i);
 64034      if( rc ) return rc;
 64035    }
 64036  
 64037    /* set the current branch */
 64038    rc = update_current_branch(lmdb);
 64039  
 64040    return rc;
 64041  
 64042  }
 64043  
 64044  /*
 64045  ** Opens the branch's pages db and gets the max pgno
 64046  */
 64047  SQLITE_PRIVATE int sqlite3BranchOpen(lmdb *lmdb, int branch_id, int open_txn){
 64048    struct branch_info *branch;
 64049    char zPagesDb[64];
 64050    char zMaxPgDb[64];
 64051    int rc=SQLITE_ERROR;
 64052  
 64053    BRANCHTRACE("sqlite3BranchOpen [%s] id=%d", lmdb->branches[branch_id].name, branch_id);
 64054  
 64055    if( !lmdb || branch_id<=0 || branch_id>lmdb->num_branches ) return SQLITE_ERROR;
 64056  
 64057    /* pointer to the array item */
 64058    branch = &lmdb->branches[branch_id];
 64059  
 64060    /* is it already open? */
 64061    if( branch->pages_db > 0 ) return SQLITE_OK;
 64062  
 64063    /* get the sub-db names */
 64064    sqlite3_snprintf(sizeof(zPagesDb), zPagesDb, "b%d-pages", branch_id);
 64065    sqlite3_snprintf(sizeof(zMaxPgDb), zMaxPgDb, "b%d-maxpage", branch_id);
 64066  
 64067    if( open_txn ){
 64068      /* we need a transaction to open the databases */
 64069      rc = mdb_txn_begin(lmdb->env, NULL, 0, &lmdb->txn);
 64070      if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 64071    }
 64072  
 64073    /* open the pages subdb and the maxpage subdb */
 64074    if( (rc=mdb_dbi_open(lmdb->txn, zPagesDb, MDB_CREATE, &branch->pages_db)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 64075    if( (rc=mdb_dbi_open(lmdb->txn, zMaxPgDb, MDB_CREATE, &branch->maxpg_db)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 64076  
 64077    /* open the subdbs from the source branches recursively */
 64078    if( branch->source_branch ){
 64079      rc = sqlite3BranchOpen(lmdb, branch->source_branch, 0);  /* it should not reopen the transaction */
 64080      if( rc ) goto loc_failed;
 64081    }
 64082  
 64083    /* retrieve the number of pages on this branch */
 64084    rc = sqlite3BranchGetMaxPage(lmdb, branch);
 64085    if( rc ) goto loc_failed;
 64086  
 64087    if( branch->max_commit > 0 ){
 64088      /* retrieve the max pgno up to this commit */
 64089      rc = sqlite3BranchGetCommitMaxPage(lmdb, branch, branch->max_commit, &branch->commit_max_page);
 64090      if( rc ) goto loc_failed;
 64091    }
 64092  
 64093    if( open_txn ){
 64094      /* this will make the opened dbs available for later use */
 64095      rc = mdb_txn_commit(lmdb->txn);
 64096      lmdb->txn = 0;  /* the handle is closed even on failure */
 64097      if( rc!=MDB_SUCCESS ) goto loc_lmdb_failed;
 64098    }
 64099  
 64100    if( !open_txn ){
 64101      branch->temp_db_handle = 1;
 64102    }
 64103  
 64104    BRANCHTRACE("sqlite3BranchOpen - OK");
 64105    return SQLITE_OK;
 64106  
 64107  loc_lmdb_failed:
 64108    rc = lmdb_error(rc);
 64109  loc_failed:
 64110    BRANCHTRACE("sqlite3BranchOpen - failed");
 64111    if( open_txn && lmdb->txn ){
 64112      mdb_txn_abort(lmdb->txn);
 64113      lmdb->txn = 0;
 64114    }
 64115    if( branch->pages_db ){
 64116      mdb_dbi_close(lmdb->env, branch->pages_db);
 64117      branch->pages_db = 0;
 64118    }
 64119    return rc;
 64120  
 64121  }
 64122  
 64123  #ifdef UNUSED_FUNCTION
 64124  /*
 64125  ** Close the open dbs
 64126  */
 64127  SQLITE_PRIVATE void sqlite3BranchCloseDbs(lmdb *lmdb){
 64128    int i;
 64129    if( !lmdb->branches ) return;
 64130    for( i=1; i <= lmdb->num_branches; i++ ){
 64131      branch_info *branch = &lmdb->branches[i];
 64132      if( branch->pages_db ){
 64133        mdb_dbi_close(lmdb->env, branch->pages_db);
 64134        branch->pages_db = 0;
 64135      }
 64136      if( branch->maxpg_db ){
 64137        mdb_dbi_close(lmdb->env, branch->maxpg_db);
 64138        branch->maxpg_db = 0;
 64139      }
 64140      branch->temp_db_handle = 0;
 64141    }
 64142  }
 64143  #endif
 64144  
 64145  /*
 64146  ** Unload the branch array
 64147  */
 64148  SQLITE_PRIVATE void unload_branch_array(lmdb * lmdb){
 64149    if( lmdb ){
 64150      //sqlite3BranchCloseDbs(lmdb);
 64151      sqlite3_free(lmdb->branches);
 64152      lmdb->branches = NULL;
 64153      lmdb->num_branches = 0;
 64154      lmdb->current_branch = NULL;
 64155    }
 64156  }
 64157  
 64158  /*
 64159  ** Release the unused items at the global LMDB environment list
 64160  */
 64161  SQLITE_PRIVATE void release_unused_global_lmdb(){
 64162    struct global_lmdb *g_lmdb, *next, *prev=NULL;
 64163  
 64164    for( g_lmdb = global_lmdb; g_lmdb; g_lmdb = next ){
 64165      next = g_lmdb->next;
 64166      if( g_lmdb->env==NULL ){
 64167        BRANCHTRACE("releasing global lmdb list item");
 64168        sqlite3_free(g_lmdb);
 64169        if( prev ) prev->next = next;
 64170        else global_lmdb = next;
 64171      } else {
 64172        prev = g_lmdb;
 64173      }
 64174    }
 64175  
 64176  }
 64177  
 64178  /*
 64179  ** Close the branch environment
 64180  */
 64181  SQLITE_PRIVATE void sqlite3BranchClose(Pager *pPager){
 64182    lmdb *lmdb;
 64183  
 64184    BRANCHTRACE("sqlite3BranchClose");
 64185  
 64186    lmdb = pPager->lmdb;
 64187    if( !lmdb ) return;
 64188  
 64189    if( lmdb->txn ){
 64190      mdb_txn_abort(lmdb->txn);
 64191    }
 64192    //sqlite3BranchCloseDbs(lmdb);  -- do not close the dbs because they can be shared between connections
 64193  
 64194    if( lmdb->global ){
 64195      /* use a mutex to access the global list of open LMDB environments */
 64196      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_APP3);
 64197      sqlite3_mutex_enter(mutex);
 64198      /* decrement the reference counter */
 64199      lmdb->global->refcount--;
 64200      BRANCHTRACE("decremented lmdb->global->refcount to %d", lmdb->global->refcount);
 64201      if( lmdb->global->refcount==0 ){
 64202        /* close the LMDB environment */
 64203        if( lmdb->global->env ) mdb_env_close(lmdb->global->env);
 64204        lmdb->global->env = NULL;
 64205        /* release the list item */
 64206        release_unused_global_lmdb();
 64207      }
 64208      sqlite3_mutex_leave(mutex);
 64209    }
 64210  
 64211    if( lmdb->branches ) sqlite3_free(lmdb->branches);
 64212    sqlite3_free(lmdb);
 64213  
 64214    pPager->lmdb = 0;
 64215  
 64216  }
 64217  
 64218  /*
 64219  ** Close the open dbs that were not 'commited'.
 64220  */
 64221  SQLITE_PRIVATE void sqlite3BranchCloseTempHandles(lmdb *lmdb){
 64222    int i;
 64223    for( i=1; i <= lmdb->num_branches; i++ ){
 64224      branch_info *branch = &lmdb->branches[i];
 64225      if( branch->temp_db_handle ){
 64226  //!      mdb_dbi_close(branch->pages_db);   -- does it always return the same dbi for the same db??? if yes, closing is not needed
 64227  //!      mdb_dbi_close(branch->maxpg_db);
 64228        branch->pages_db = 0;
 64229        branch->maxpg_db = 0;
 64230        branch->temp_db_handle = 0;
 64231      }
 64232    }
 64233  }
 64234  
 64235  /*
 64236  ** Mark the db handles as 'commited' so they don't need to be reopened.
 64237  */
 64238  SQLITE_PRIVATE void sqlite3BranchCommitTempHandles(lmdb *lmdb){
 64239    int i;
 64240    if( !lmdb->branches ) return;
 64241    for( i=1; i <= lmdb->num_branches; i++ ){
 64242      branch_info *branch = &lmdb->branches[i];
 64243      if( branch->temp_db_handle ){
 64244        branch->temp_db_handle = 0;
 64245      }
 64246    }
 64247  }
 64248  
 64249  /*
 64250  ** Check if the db was modified since the last time it was loaded.
 64251  ** Returns 0 if no modification and 1 if modified.
 64252  */
 64253  SQLITE_PRIVATE int db_has_changed(lmdb *lmdb, int *pchanged, int *pchange_counter){
 64254    int change_counter;
 64255    int rc;
 64256  
 64257    /* check the change_counter */
 64258    rc = mdb_str_get_int(lmdb->txn, lmdb->main_db, "change_counter", &change_counter);
 64259    if( rc!=MDB_SUCCESS && rc!=MDB_NOTFOUND ) return lmdb_error(rc);
 64260  
 64261    /* was the db modified by other connection? */
 64262    if( rc==MDB_NOTFOUND || change_counter==lmdb->db_change_counter ){
 64263      /* either not found or not modified */
 64264      *pchanged = 0;
 64265      if( pchange_counter ) *pchange_counter = lmdb->db_change_counter;
 64266    } else {
 64267      /* the db was modified */
 64268      *pchanged = 1;
 64269      if( pchange_counter ) *pchange_counter = change_counter;
 64270    }
 64271  
 64272    return SQLITE_OK;
 64273  }
 64274  
 64275  /*
 64276  ** Begin a read transaction on the database.
 64277  **
 64278  ** It takes a snapshot of the db state for the current
 64279  ** instant in time. This connection will continue to use this snapshot.
 64280  ** Other connections might append new content to the db but
 64281  ** that extra content is ignored by the current connection.
 64282  **
 64283  ** If the database contents have changes since the previous read
 64284  ** transaction, then *pChanged is set to 1 before returning.  The
 64285  ** Pager layer will use this to know that is cache is stale and
 64286  ** needs to be flushed.
 64287  */
 64288  SQLITE_PRIVATE int sqlite3BranchBeginReadTransaction(lmdb *lmdb, int check_for_updates, int *pChanged){
 64289    int changed, change_counter, rc;
 64290  
 64291    BRANCHTRACE("sqlite3BranchBeginReadTransaction");
 64292  
 64293    if( !lmdb ) return SQLITE_ERROR;
 64294  
 64295    /* if the transaction is already open */
 64296    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_OK;
 64297  
 64298    /* open a new read transaction */
 64299    rc = mdb_txn_begin(lmdb->env, NULL, MDB_RDONLY, &lmdb->txn);
 64300    if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 64301  
 64302    if( !lmdb->branches || (check_for_updates && lmdb->singleConnection==0) ){
 64303      /* check if the database was modified since the last loading */
 64304      rc = db_has_changed(lmdb, &changed, &change_counter);
 64305      if( rc ) goto loc_failed;
 64306      if( pChanged ) *pChanged = changed;
 64307      /* if the array is not loaded or the db was modified */
 64308      if( !lmdb->branches || changed ){
 64309        /* update the array */
 64310        rc = sqlite3BranchLoadArray(lmdb);
 64311        if( rc ) goto loc_failed;
 64312        /* update the change_counter */
 64313        lmdb->db_change_counter = change_counter;
 64314      }
 64315    }
 64316  
 64317    /* flag the open read transaction */
 64318    lmdb->inReadTxn = 1;
 64319  
 64320    return SQLITE_OK;
 64321  
 64322  loc_failed:
 64323    mdb_txn_abort(lmdb->txn);
 64324    lmdb->txn = 0;
 64325    return rc;
 64326  
 64327  }
 64328  
 64329  /*
 64330  ** Finish with a read transaction.  All this does is release the
 64331  ** read-lock.
 64332  */
 64333  SQLITE_PRIVATE void sqlite3BranchEndReadTransaction(lmdb *lmdb){
 64334  
 64335    BRANCHTRACE("sqlite3BranchEndReadTransaction");
 64336  
 64337    if( !lmdb ) return;
 64338  
 64339    /* if the transaction is already closed */
 64340    if( !lmdb->inReadTxn ) return;
 64341  
 64342    /* close the dbs that must be closed */
 64343    sqlite3BranchCloseTempHandles(lmdb);
 64344  
 64345    /* close the transaction */
 64346    mdb_txn_abort(lmdb->txn);
 64347    lmdb->txn = 0;
 64348    lmdb->inReadTxn = 0;
 64349  
 64350  }
 64351  
 64352  /* 
 64353  ** This function starts a write transaction on the WAL.
 64354  **
 64355  ** A read transaction must have already been started by a prior call
 64356  ** to sqlite3WalBeginReadTransaction().
 64357  **
 64358  ** If another thread or process has written into the database since
 64359  ** the read transaction was started, then it is not possible for this
 64360  ** thread to write as doing so would cause a fork.  So this routine
 64361  ** returns SQLITE_BUSY in that case and no write transaction is started.
 64362  **
 64363  ** There can only be a single writer active at a time.
 64364  */
 64365  SQLITE_PRIVATE int sqlite3BranchBeginWriteTransaction(lmdb *lmdb){
 64366    int rc, changed, reopen_read_txn=0;
 64367  
 64368    BRANCHTRACE("sqlite3BranchBeginWriteTransaction");
 64369  
 64370    if( !lmdb ) return SQLITE_ERROR;
 64371  
 64372    /* if the transaction is already open */
 64373    if( lmdb->inWriteTxn ) return SQLITE_OK;
 64374  
 64375    /* if the there is an open read transaction */
 64376    if( lmdb->inReadTxn ){
 64377      sqlite3BranchEndReadTransaction(lmdb);
 64378      reopen_read_txn = 1;
 64379    }
 64380  
 64381    /* open a new write transaction */
 64382    rc = mdb_txn_begin(lmdb->env, NULL, 0, &lmdb->txn);
 64383    if( rc!=MDB_SUCCESS ){
 64384      if( reopen_read_txn ) sqlite3BranchBeginReadTransaction(lmdb, 0, NULL);
 64385      return lmdb_error(rc);
 64386    }
 64387  
 64388    /* flag the open write transaction */
 64389    lmdb->inWriteTxn = 1;
 64390  
 64391    /* create sub-databases if not yet created */
 64392  #ifndef OMIT_BRANCH_LOG
 64393    if( lmdb->logs_db==0 ){
 64394      if( (rc=mdb_dbi_open(lmdb->txn, "logs", MDB_CREATE, &lmdb->logs_db))!=MDB_SUCCESS ) goto loc_lmdb_failed;
 64395    }
 64396  #endif
 64397    if( lmdb->meta_db==0 ){
 64398      if( (rc=mdb_dbi_open(lmdb->txn, "meta", MDB_CREATE, &lmdb->meta_db))!=MDB_SUCCESS ) goto loc_lmdb_failed;
 64399    }
 64400  
 64401    /* reset the number of pages on the current branch */
 64402    if( lmdb->current_branch ){
 64403      lmdb->current_branch->txn_max_page = 0;
 64404    }
 64405  
 64406    /* If another connection has written to the database file since the
 64407    ** time the read transaction on this connection was started, then
 64408    ** the write is disallowed.
 64409    */
 64410    if( db_has_changed(lmdb, &changed, NULL) != SQLITE_OK ) return SQLITE_ERROR;
 64411    if( changed ){
 64412      rc = SQLITE_BUSY_SNAPSHOT;
 64413      goto loc_failed;
 64414    }
 64415  
 64416    return SQLITE_OK;
 64417  
 64418  loc_lmdb_failed:
 64419  
 64420    rc = lmdb_error(rc);
 64421  
 64422  loc_failed:
 64423  
 64424    sqlite3BranchEndWriteTransaction(lmdb, reopen_read_txn);
 64425    return rc;
 64426  
 64427  }
 64428  
 64429  /*
 64430  ** End a write transaction.  The commit has already been done.  This
 64431  ** routine merely releases the lock.
 64432  */
 64433  SQLITE_PRIVATE int sqlite3BranchEndWriteTransaction(lmdb *lmdb, int reopen_read_txn){
 64434  
 64435    BRANCHTRACE("sqlite3BranchEndWriteTransaction");
 64436  
 64437    if( !lmdb ) return SQLITE_ERROR;
 64438  
 64439    /* if the transaction is already closed */
 64440    if( !lmdb->inWriteTxn ) return SQLITE_OK;
 64441  
 64442  #ifndef OMIT_BRANCH_LOG
 64443    /* discard the current txn commands */
 64444    sqlite3BranchDiscardSqlLog(lmdb);
 64445  #endif
 64446  
 64447    /* close the dbs that must be closed */
 64448    sqlite3BranchCloseTempHandles(lmdb);
 64449  
 64450    if( lmdb->txn ){
 64451      /* abort the transaction */
 64452      mdb_txn_abort(lmdb->txn);
 64453      lmdb->txn = 0;
 64454    }
 64455  
 64456    lmdb->inWriteTxn = 0;
 64457  
 64458    /* if this is not a SQLite transaction, exit here */
 64459    if( !reopen_read_txn ) return SQLITE_OK;
 64460  
 64461    /* open a read transaction because the SQLite engine expects this behaviour */
 64462    return sqlite3BranchBeginReadTransaction(lmdb, 0, NULL);
 64463  
 64464  }
 64465  
 64466  /*
 64467  ** Commit a write transaction.
 64468  */
 64469  SQLITE_PRIVATE int sqlite3BranchCommitTransaction(lmdb *lmdb, int reopen_read_txn){
 64470    int change_counter;
 64471    int rc;
 64472  
 64473    BRANCHTRACE("sqlite3BranchCommitTransaction");
 64474  
 64475    if( !lmdb ) return SQLITE_ERROR;
 64476  
 64477    /* if the transaction is not open */
 64478    if( !lmdb->inWriteTxn ) return SQLITE_OK;
 64479  
 64480    /* update the global change counter */
 64481    if( lmdb->db_change_counter < 0x7FFFFFFE ){
 64482      change_counter = lmdb->db_change_counter + 1;
 64483    } else {
 64484      change_counter = 1;  /* restart the change counter */
 64485    }
 64486    rc = mdb_str_put_int(lmdb->txn, lmdb->main_db, "change_counter", change_counter);
 64487    if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 64488  
 64489    /* commit the transaction */
 64490    rc = mdb_txn_commit(lmdb->txn);
 64491    lmdb->txn = 0;  /* the handle is closed even on failure */
 64492  
 64493    if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 64494  
 64495    /* update the change counter in memory */
 64496    lmdb->db_change_counter = change_counter;
 64497  
 64498    /* close the dbs that must be closed */
 64499    sqlite3BranchCommitTempHandles(lmdb);
 64500  
 64501    /* flag that it is no more in a write transaction */
 64502    lmdb->inWriteTxn = 0;
 64503  
 64504    /* if this is not a SQLite transaction, exit here */
 64505    if( !reopen_read_txn ) return SQLITE_OK;
 64506  
 64507    /* open a read transaction because the SQLite engine expects this behaviour */
 64508    sqlite3BranchBeginReadTransaction(lmdb, 0, NULL);  // the return value is not used
 64509  
 64510    return SQLITE_OK;
 64511  
 64512  }
 64513  
 64514  /*
 64515  ** Undo the changes made on the current transaction.
 64516  */
 64517  SQLITE_PRIVATE int sqlite3BranchUndoChanges(lmdb *lmdb){
 64518    int rc;
 64519  
 64520    BRANCHTRACE("sqlite3BranchUndoChanges");
 64521  
 64522    if( !lmdb ) return SQLITE_ERROR;
 64523  
 64524    /* if the transaction is not open */
 64525    if( !lmdb->inWriteTxn ) return SQLITE_OK;
 64526  
 64527    /* abort the current transaction */
 64528    if( lmdb->txn ){
 64529      mdb_txn_abort(lmdb->txn);
 64530      lmdb->txn = 0;
 64531    }
 64532  
 64533  #ifndef OMIT_BRANCH_LOG
 64534    /* discard the current txn commands */
 64535    sqlite3BranchDiscardSqlLog(lmdb);
 64536  #endif
 64537  
 64538    /* close the dbs that must be closed */
 64539    sqlite3BranchCloseTempHandles(lmdb);
 64540  
 64541    /* reset the value */
 64542    if( lmdb->current_branch ){
 64543      lmdb->current_branch->txn_max_page = 0;
 64544    }
 64545  
 64546    /* open a new write transaction */
 64547    rc = mdb_txn_begin(lmdb->env, NULL, 0, &lmdb->txn);
 64548    if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 64549  
 64550    return SQLITE_OK;
 64551  
 64552  }
 64553  
 64554  /*
 64555  ** Builds the key used in the pages db for each branch
 64556  */
 64557  SQLITE_PRIVATE void mdb_value_set_u64(MDB_val *key, char *buf, u64 value){
 64558    key->mv_data = buf;
 64559    key->mv_size = sqlite4PutVarint64((unsigned char *)buf, value);
 64560    BRANCHTRACE("set_varint  value: %llu  len: %d bytes", value, key->mv_size);
 64561  }
 64562  
 64563  /*
 64564  ** Read an unsigned int from the key
 64565  */
 64566  SQLITE_PRIVATE int mdb_value_get_u64(MDB_val *key, u64 *pvalue){
 64567    int n;
 64568    if( !key || !key->mv_data ) return SQLITE_INTERNAL;
 64569    n = sqlite4GetVarint64((unsigned char*)key->mv_data, key->mv_size, pvalue);
 64570    return n > 0 ? SQLITE_OK : SQLITE_CORRUPT;
 64571  }
 64572  
 64573  /*
 64574  ** Read an unsigned int from the key
 64575  */
 64576  SQLITE_PRIVATE int mdb_value_get_u32(MDB_val *key, u32 *pvalue){
 64577    int n;
 64578    if( !key || !key->mv_data ) return SQLITE_INTERNAL;
 64579    n = sqlite4GetVarint32((unsigned char*)key->mv_data, key->mv_size, pvalue);
 64580    return n > 0 ? SQLITE_OK : SQLITE_CORRUPT;
 64581  }
 64582  
 64583  #define PAGE_DB_KEY_MAX_SIZE 32   /* 2 varints = 2 * 9 bytes = 18 bytes */
 64584  
 64585  /*
 64586  ** Retrieves the pgno from the key
 64587  */
 64588  SQLITE_PRIVATE int pgno_from_key(MDB_val *key, Pgno *pvalue){
 64589    return mdb_value_get_u32(key, pvalue);
 64590  }
 64591  
 64592  /*
 64593  ** Retrieves the commit id from the key
 64594  */
 64595  SQLITE_PRIVATE int commit_from_key(MDB_val *key, u64 *pvalue){
 64596    Pgno pgno;
 64597    int n;
 64598    if( !key || !key->mv_data ) return SQLITE_INTERNAL;
 64599    n = sqlite4GetVarint32( (unsigned char*)key->mv_data, key->mv_size, &pgno);
 64600    if( n<=0 ) return SQLITE_CORRUPT;
 64601    n = sqlite4GetVarint64( &((unsigned char*)key->mv_data)[n], key->mv_size-n, pvalue);
 64602    return n > 0 ? SQLITE_OK : SQLITE_CORRUPT;
 64603  }
 64604  
 64605  /*
 64606  ** Builds the key used in the pages db for each branch
 64607  */
 64608  SQLITE_PRIVATE void branch_set_page_key(MDB_val *key, char *buf, Pgno pgno, u64 commit_id){
 64609    int len=0;
 64610  
 64611    len += sqlite4PutVarint64( (unsigned char *) &buf[len], pgno);
 64612    len += sqlite4PutVarint64( (unsigned char *) &buf[len], commit_id);
 64613  
 64614    key->mv_data = buf;
 64615    key->mv_size = len;
 64616  
 64617    BRANCHTRACE("built page_db key  pgno=%u commit_id=%llu len: %d bytes", pgno, commit_id, len);
 64618  
 64619  }
 64620  
 64621  /*
 64622  ** Builds the key used in logs and meta dbs
 64623  */
 64624  SQLITE_PRIVATE void branch_set_commit_key(MDB_val *key, char *buf, int branch_id, u64 commit_id){
 64625    int len=0;
 64626  
 64627    len += sqlite4PutVarint64( (unsigned char *) &buf[len], branch_id);
 64628    len += sqlite4PutVarint64( (unsigned char *) &buf[len], commit_id);
 64629  
 64630    key->mv_data = buf;
 64631    key->mv_size = len;
 64632  
 64633    BRANCHTRACE("built commit key  branch_id=%d commit_id=%llu len: %d bytes", branch_id, commit_id, len);
 64634  
 64635  }
 64636  
 64637  /*
 64638  ** Returns the number of pages in the database.
 64639  ** A transaction must be open.
 64640  ** Return SQLITE_OK if successful, or an error code otherwise.
 64641  */
 64642  SQLITE_PRIVATE int sqlite3BranchGetMaxPage(
 64643    lmdb *lmdb,                     /* LMDB handle */
 64644    branch_info *branch             /* The branch info */
 64645  ){
 64646    int rc=SQLITE_ERROR;
 64647    MDB_val key, value;
 64648    MDB_cursor *cursor=0;
 64649  
 64650    BRANCHTRACE("sqlite3BranchGetMaxPage [%s] id=%d", branch->name, branch->id);
 64651  
 64652    if( !lmdb || !branch ) goto loc_exit;
 64653  
 64654    branch->max_page = 0;
 64655  
 64656    rc = mdb_cursor_open(lmdb->txn, branch->pages_db, &cursor);
 64657    if( rc!=MDB_SUCCESS ) goto loc_failed;
 64658  
 64659    /* move to the last record */
 64660    switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_LAST)) ){
 64661      case MDB_SUCCESS:
 64662        /* get the page number */
 64663        rc = pgno_from_key(&key, &branch->max_page);
 64664        if( rc!=SQLITE_OK ) goto loc_exit;
 64665        break;
 64666      case MDB_NOTFOUND:
 64667        /* the db is empty */
 64668        BRANCHTRACE("sqlite3BranchGetMaxPage - EMPTY DB");
 64669        break;
 64670      default:
 64671        goto loc_failed;
 64672    }
 64673  
 64674    rc = SQLITE_OK;
 64675  
 64676  loc_exit:
 64677    if( cursor ) mdb_cursor_close(cursor);
 64678  
 64679    /* no pages on this branch yet? */
 64680    if( rc==SQLITE_OK && branch->max_page==0 && branch->source_branch > 0 ){
 64681      /* retrieve the max page from the source branch */
 64682      rc = sqlite3BranchGetCommitMaxPage(lmdb, &lmdb->branches[branch->source_branch], branch->source_commit, &branch->max_page);
 64683    }
 64684  
 64685    BRANCHTRACE("sqlite3BranchGetMaxPage returning max_page=%d", branch->max_page);
 64686    return rc;
 64687  
 64688  loc_failed:
 64689    rc = lmdb_error(rc);
 64690    goto loc_exit;
 64691  
 64692  }
 64693  
 64694  /*
 64695  ** Returns the number of pages in the database.
 64696  ** A transaction must be open.
 64697  ** Return SQLITE_OK if successful, or an error code otherwise.
 64698  */
 64699  SQLITE_PRIVATE int sqlite3BranchGetCommitMaxPage(
 64700    lmdb *lmdb,                     /* LMDB handle */
 64701    branch_info *branch,            /* The branch info */
 64702    u64 commit_id,                  /* The commit id */
 64703    Pgno *pMaxPgno                  /* The max pgno will be written here */
 64704  ){
 64705    int rc=SQLITE_ERROR;
 64706    MDB_val key, value;
 64707    MDB_cursor *cursor=0;
 64708    char buf[12];
 64709  
 64710    BRANCHTRACE("sqlite3BranchGetCommitMaxPage on branch [%s] up to commit %llu", branch->name, commit_id);
 64711  
 64712    if( !lmdb || !branch || !pMaxPgno ) goto loc_exit;
 64713  
 64714    rc = mdb_cursor_open(lmdb->txn, branch->maxpg_db, &cursor);
 64715    if( rc!=MDB_SUCCESS ) goto loc_failed;
 64716  
 64717    /* set the key */
 64718    mdb_value_set_u64(&key, buf, commit_id);
 64719  
 64720    /* search for the specific key */
 64721    switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_SET_KEY)) ){
 64722      case MDB_SUCCESS:
 64723        goto loc_found;
 64724      case MDB_NOTFOUND:
 64725        /* check the previous key */
 64726        switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_PREV)) ){
 64727          case MDB_SUCCESS:  goto loc_found;
 64728          case MDB_NOTFOUND: goto loc_notfound;
 64729        }
 64730    }
 64731  
 64732  loc_failed:
 64733  
 64734    rc = lmdb_error(rc);
 64735  
 64736  loc_exit:
 64737  
 64738    if( rc==SQLITE_OK ){
 64739      BRANCHTRACE("sqlite3BranchGetCommitMaxPage returning max_page=%u", *pMaxPgno);
 64740    } else {
 64741      BRANCHTRACE("sqlite3BranchGetCommitMaxPage failed");
 64742    }
 64743  
 64744    if( cursor ) mdb_cursor_close(cursor);
 64745    return rc;
 64746  
 64747  loc_found:
 64748  
 64749    /* read the value */
 64750    rc = mdb_value_get_u32(&value, pMaxPgno);
 64751  
 64752    goto loc_exit;
 64753  
 64754  loc_notfound:
 64755  
 64756    BRANCHTRACE("sqlite3BranchGetCommitMaxPage NOT FOUND");
 64757  
 64758    /* does this branch start from another? */
 64759    if( branch->source_branch > 0 ){
 64760      /* retrieve the max page from the source branch recursively */
 64761      rc = sqlite3BranchGetCommitMaxPage(lmdb, &lmdb->branches[branch->source_branch], branch->source_commit, pMaxPgno);
 64762    } else {
 64763      *pMaxPgno = 0;
 64764      rc = SQLITE_OK;
 64765    }
 64766  
 64767    goto loc_exit;
 64768  
 64769  }
 64770  
 64771  /*
 64772  ** Search for the page in the supplied branch up to max commit.
 64773  ** Returns the pointer to the page from the LMDB.
 64774  ** Returns SQLITE_OK if successful, or an error code otherwise.
 64775  */
 64776  SQLITE_PRIVATE int sqlite3BranchFindPage(
 64777    lmdb *lmdb,                     /* LMDB handle */
 64778    Pgno pgno,                      /* Database page number to read data for */
 64779    branch_info *branch,
 64780    u64  max_commit,                /* Database page number to read data for */
 64781    u8 **ppData                     /* OUT: store the pointer to the data here */
 64782  ){
 64783    int rc=SQLITE_ERROR;
 64784    char buf[PAGE_DB_KEY_MAX_SIZE];
 64785    MDB_val key, value;
 64786    MDB_cursor *cursor=0;
 64787    Pgno this_pgno;
 64788  
 64789    BRANCHTRACE("sqlite3BranchFindPage [%s] id=%d pgno=%u max_commit=%llu", branch->name, branch->id, pgno, max_commit);
 64790  
 64791    if( !lmdb || pgno<=0 || !branch || !ppData ) return rc;
 64792  
 64793    /* if the pages db is not open, open it now */
 64794    if( branch->pages_db == 0 ){
 64795      rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 64796      if( rc==SQLITE_READONLY ) rc = SQLITE_NOTFOUND;
 64797      if( rc ) return rc;
 64798    }
 64799  
 64800    rc = mdb_cursor_open(lmdb->txn, branch->pages_db, &cursor);
 64801    if( rc!=MDB_SUCCESS ) goto loc_failed;
 64802  
 64803    /* set the key */
 64804    branch_set_page_key(&key, buf, pgno, max_commit);
 64805  
 64806    switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_SET_KEY)) ){  // MDB_SET_RANGE would point to the next if the current was not found, and would return True
 64807      case MDB_SUCCESS:
 64808        goto loc_found;
 64809      case MDB_NOTFOUND:
 64810        /* check the previous key */
 64811        switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_PREV)) ){
 64812        case MDB_SUCCESS:
 64813          /* read the pgno */
 64814          rc = pgno_from_key(&key, &this_pgno);
 64815          if( rc!=SQLITE_OK ) goto loc_exit;
 64816          /* has this previous key the same pgno? */
 64817          if( this_pgno == pgno ) goto loc_found;
 64818          /* continue to notfound bellow */
 64819        case MDB_NOTFOUND:
 64820          goto loc_notfound;
 64821        }
 64822    }
 64823  
 64824  loc_failed:
 64825  
 64826    rc = lmdb_error(rc);
 64827  
 64828  loc_exit:
 64829  
 64830    if( cursor ) mdb_cursor_close(cursor);
 64831    return rc;
 64832  
 64833  loc_found:
 64834  
 64835  #ifdef DEBUGBRANCHES
 64836    {
 64837    u64 commit_id=0;
 64838    commit_from_key(&key, &commit_id);
 64839    BRANCHTRACE("sqlite3BranchFindPage FOUND - from commit %llu", commit_id);
 64840    }
 64841  #endif
 64842  
 64843    /* check the value size */
 64844    if( value.mv_size != lmdb->pageSize-LMDB_PAGE_RESERVED_SPACE ){
 64845      rc = SQLITE_CORRUPT;
 64846      goto loc_exit;
 64847    }
 64848  
 64849    /* return the pointer to the data */
 64850    *ppData = value.mv_data;
 64851  
 64852    rc = SQLITE_OK;
 64853    goto loc_exit;
 64854  
 64855  loc_notfound:
 64856  
 64857    BRANCHTRACE("sqlite3BranchFindPage NOT FOUND");
 64858  
 64859    /* does this branch starts from another? */
 64860    if( branch->source_branch > 0 && branch->source_branch <= lmdb->num_branches ){
 64861      /* search on the source branch, at the commit this branch starts at */
 64862      rc = sqlite3BranchFindPage(lmdb, pgno, &lmdb->branches[branch->source_branch], branch->source_commit, ppData);
 64863    } else {
 64864      rc = SQLITE_NOTFOUND;
 64865    }
 64866  
 64867    goto loc_exit;
 64868  
 64869  }
 64870  
 64871  /*
 64872  ** Returns the pointer to the page pgno from the LMDB.
 64873  ** Return SQLITE_OK if successful, or an error code otherwise.
 64874  */
 64875  SQLITE_PRIVATE int sqlite3BranchGetPage(
 64876    lmdb *lmdb,                     /* LMDB handle */
 64877    Pgno pgno,                      /* Database page number to read data for */
 64878    u8 **ppData                     /* OUT: store the pointer to the data here */
 64879  ){
 64880    branch_info *current_branch;
 64881    u64 max_commit;
 64882    int rc=SQLITE_ERROR;
 64883  
 64884    BRANCHTRACE("sqlite3BranchGetPage pgno=%d", pgno);
 64885  
 64886    if( !lmdb || pgno<=0 || ppData==0 ) return rc;
 64887  
 64888    current_branch = lmdb->current_branch;
 64889    if( !current_branch ) return SQLITE_ERROR;
 64890  
 64891    // it could use the current_branch->last_commit if current_branch->max_commit is not defined, and set
 64892    // the key to exactly pgno+commit
 64893    // PROBLEM: in a write txn with a small cache, cache spill can happen, and when reloading a page the max_commit in memory may not be
 64894    // the same used to save the page
 64895    // SOLUTION: use last_commit + 1 if in a write txn
 64896  
 64897    if( current_branch->max_commit > 0 ){
 64898      max_commit = current_branch->max_commit;
 64899    } else if( lmdb->inWriteTxn ){
 64900      max_commit = current_branch->last_commit + 1;
 64901    } else {
 64902      max_commit = current_branch->last_commit;
 64903    }
 64904  
 64905    /* start the search for this page on the current branch, at the supplied max commit */
 64906    return sqlite3BranchFindPage(lmdb, pgno, current_branch, max_commit, ppData);
 64907  
 64908  }
 64909  
 64910  /*
 64911  ** Read the contents of page pgno from the LMDB db into buffer pOut
 64912  ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
 64913  ** error code otherwise.
 64914  */
 64915  SQLITE_PRIVATE int sqlite3BranchReadPage(
 64916    lmdb *lmdb,                     /* LMDB handle */
 64917    Pgno pgno,                      /* Database page number to read data for */
 64918    int nOut,                       /* Size of buffer pOut in bytes */
 64919    u8 *pOut                        /* Buffer to write page data to */
 64920  ){
 64921    u8 *pData;
 64922    int rc;
 64923    int size;
 64924  
 64925    BRANCHTRACE("sqlite3BranchReadPage pgno=%d size=%d", pgno, nOut);
 64926  
 64927    if( nOut>(int)lmdb->pageSize || nOut<0 || pOut==0 ) return SQLITE_ERROR;
 64928  
 64929    rc = sqlite3BranchGetPage(lmdb, pgno, &pData);
 64930    BRANCHTRACE("sqlite3BranchGetPage returned %d", rc);
 64931    if( rc ) return rc;
 64932  
 64933    size = lmdb->pageSize - LMDB_PAGE_RESERVED_SPACE;
 64934    if( nOut < size ) size = nOut;
 64935  
 64936    memcpy(pOut, pData, size);
 64937  
 64938    return SQLITE_OK;
 64939  
 64940  }
 64941  
 64942  /* 
 64943  ** Write a set of pages to the log. The caller must hold the write-lock
 64944  ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
 64945  */
 64946  SQLITE_PRIVATE int sqlite3BranchWritePages(
 64947    lmdb *lmdb,                     /* LMDB handle */
 64948    PgHdr *pList,                   /* List of dirty pages to write */
 64949    Pgno nTruncate,                 /* Database size after this commit */
 64950    int isCommit                    /* True if this is a commit */
 64951  ){
 64952    int rc;                         /* Used to catch return codes */
 64953    PgHdr *p;                       /* Iterator to run through pList with. */
 64954    branch_info *branch;
 64955    MDB_val key, value;
 64956    char buf[PAGE_DB_KEY_MAX_SIZE];
 64957    u64 current_commit;
 64958  
 64959    BRANCHTRACE("sqlite3BranchWritePages nTruncate=%d isCommit=%d", nTruncate, isCommit);
 64960  
 64961    if( !lmdb || pList==0 || !lmdb->current_branch ) return SQLITE_ERROR;
 64962  
 64963    branch = lmdb->current_branch;
 64964  
 64965    /* it is only possible to edit the database at the end of each visible branch */
 64966    if( branch->max_commit > 0 || branch->visible==0 ){
 64967      return SQLITE_PERM;
 64968    }
 64969  
 64970    /* if the pages db is not open, open it now */
 64971    if( branch->pages_db == 0 ){
 64972      rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 64973      if( rc ) return rc;
 64974    }
 64975  
 64976    /* if this is the first branch, save its info now. others are saved when created */
 64977    if( branch->is_new ){
 64978      rc = save_branch(lmdb, branch->id);
 64979      if( rc ) return rc;
 64980      branch->is_new = 0;
 64981    }
 64982  
 64983    /* get the current commit id */
 64984    current_commit = branch->last_commit + 1;
 64985  
 64986    /* iterate through all the pages to be stored */
 64987    for(p=pList; p; p=p->pDirty){
 64988  
 64989      BRANCHTRACE("commit %llu - writting page %u", current_commit, p->pgno);
 64990  
 64991      /* set the key */
 64992      branch_set_page_key(&key, buf, p->pgno, current_commit);
 64993  
 64994      /* set the value */
 64995      value.mv_size = lmdb->pageSize - LMDB_PAGE_RESERVED_SPACE;
 64996      value.mv_data = p->pData;
 64997  
 64998      /* store the page */
 64999      rc = mdb_put(lmdb->txn, branch->pages_db, &key, &value, 0);
 65000      if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 65001  
 65002      /* update the mxPage */
 65003      if( p->pgno > branch->txn_max_page ) branch->txn_max_page = p->pgno;
 65004    }
 65005  
 65006  
 65007    if( isCommit ){
 65008      /* here it will always use branch->max_page because writing is only allowed at the branch's end */
 65009      u32 max_page = max_page = MAX(branch->txn_max_page, branch->max_page);
 65010  
 65011      if( nTruncate < max_page ){
 65012        BRANCHTRACE("truncating to %d pages", nTruncate);
 65013        /* update the number of pages */
 65014        max_page = nTruncate;   //! would this happen in other case than VACUUM?  - can it write bigger pages (spill) and then undo?
 65015      }
 65016  
 65017      if( branch->txn_max_page > branch->max_page || nTruncate < branch->max_page ){
 65018        /* save the number of pages on this commit */
 65019        rc = mdb_u64_put_u32(lmdb->txn, branch->maxpg_db, current_commit, max_page);
 65020        if( rc ) return lmdb_error(rc);
 65021      }
 65022  
 65023      /* update the last_commit for this branch */
 65024      rc = put_branch_u64(lmdb, branch->id, "last_commit", current_commit);
 65025      if( rc ) return lmdb_error(rc);
 65026  
 65027  #ifndef OMIT_BRANCH_LOG
 65028      /* save the SQL commands */
 65029      if( lmdb->sql ){
 65030        rc = sqlite3BranchStoreLastCommand(lmdb);
 65031        if( rc ) return rc;
 65032      }
 65033      if( lmdb->log ){
 65034        rc = sqlite3BranchSaveSqlLog(lmdb, branch->id, current_commit);
 65035        if( rc ) return rc;
 65036      }
 65037  #endif
 65038  
 65039      /* commit the transaction */
 65040      if( (rc=sqlite3BranchCommitTransaction(lmdb,1))!=SQLITE_OK ) return rc;
 65041  
 65042      /* update the last commit id */
 65043      branch->last_commit++;
 65044  
 65045      /* update the number of pages */
 65046      branch->max_page = max_page;
 65047  
 65048      /* reset the value for the next transaction */
 65049      branch->txn_max_page = 0;
 65050    }
 65051  
 65052    return SQLITE_OK;
 65053  
 65054  }
 65055  
 65056  /*
 65057  ** Check if the database was modified and so needs to be reloaded
 65058  */
 65059  SQLITE_PRIVATE int sqlite3BranchCheckReloadDb(Pager *pPager, int keep_txn_open){
 65060    int changed;
 65061    int rc = sqlite3BranchBeginReadTransaction(pPager->lmdb, 1, &changed);
 65062    if( rc ) return rc;
 65063    if( changed ){
 65064      pager_reset(pPager);
 65065    }
 65066    if( !keep_txn_open ){
 65067      sqlite3BranchEndReadTransaction(pPager->lmdb);
 65068    }
 65069    return rc;
 65070  }
 65071  
 65072  /*
 65073  ** This function populates the array with values required to
 65074  ** "rollback" the SQL commands list to the current point in
 65075  ** the event of a savepoint rollback.
 65076  */
 65077  SQLITE_PRIVATE void sqlite3BranchSavepoint(lmdb *lmdb, u32 *aWalData){
 65078    BRANCHTRACE("sqlite3BranchSavepoint");
 65079  #ifndef OMIT_BRANCH_LOG
 65080    if( lmdb && lmdb->log ){
 65081      aWalData[0] = strlen(lmdb->log);
 65082    } else {
 65083      aWalData[0] = 0;
 65084    }
 65085  #endif
 65086  }
 65087  
 65088  /*
 65089  ** Truncate the SQL commands list to the state at the given savepoint.
 65090  */
 65091  SQLITE_PRIVATE int sqlite3BranchSavepointUndo(lmdb *lmdb, u32 *aWalData){
 65092    BRANCHTRACE("sqlite3BranchSavepointUndo");
 65093  #ifndef OMIT_BRANCH_LOG
 65094    if( lmdb && lmdb->log ){
 65095      int len = aWalData[0];
 65096      if( len < strlen(lmdb->log) ){
 65097        lmdb->log[len] = 0;
 65098      }
 65099    }
 65100  #endif
 65101    return SQLITE_OK;
 65102  }
 65103  
 65104  #ifndef OMIT_BRANCH_LOG
 65105  
 65106  /*
 65107  ** Set the commit log
 65108  */
 65109  SQLITE_PRIVATE int branch_set_log(lmdb *lmdb, int branch_id, u64 commit_id, char *log, int size){
 65110    char buf[64];
 65111    MDB_val key, value;
 65112    int rc;
 65113  
 65114    BRANCHTRACE("set commit log %d.%llu = %s", branch_id, commit_id, log);
 65115  
 65116    /* set the key */
 65117    branch_set_commit_key(&key, buf, branch_id, commit_id);
 65118  
 65119    /* set the value with the null terminator */
 65120    value.mv_data = log;
 65121    value.mv_size = size;
 65122  
 65123    /* store the data */
 65124    rc = mdb_put(lmdb->txn, lmdb->logs_db, &key, &value, 0);
 65125    if( rc ) return lmdb_error(rc);
 65126  
 65127    return SQLITE_OK;
 65128  
 65129  }
 65130  
 65131  /*
 65132  ** Get the commit log
 65133  */
 65134  SQLITE_PRIVATE int branch_get_log(lmdb *lmdb, int branch_id, u64 commit_id, char **plog, int *psize){
 65135    char buf[64];
 65136    MDB_val key, value;
 65137    int rc;
 65138  
 65139    BRANCHTRACE("get commit log: %d.%llu", branch_id, commit_id);
 65140  
 65141    /* set the key */
 65142    branch_set_commit_key(&key, buf, branch_id, commit_id);
 65143  
 65144    /* store the data */
 65145    rc = mdb_get(lmdb->txn, lmdb->logs_db, &key, &value);
 65146    if( rc ) return lmdb_error(rc);
 65147  
 65148    /* retrieve the value, containing a null terminator */
 65149    if( plog  ) *plog  = value.mv_data;
 65150    if( psize ) *psize = value.mv_size;
 65151  
 65152    return SQLITE_OK;
 65153  
 65154  }
 65155  
 65156  /*
 65157  ** Save the current transaction SQL commands to the commit's log
 65158  */
 65159  SQLITE_PRIVATE int sqlite3BranchSaveSqlLog(lmdb *lmdb, int branch_id, u64 commit_id){
 65160    int rc;
 65161  
 65162  //  BRANCHTRACE("saving commit log: %s", lmdb->log);
 65163  
 65164    /* set the value with the null terminator */
 65165    rc = branch_set_log(lmdb, branch_id, commit_id, lmdb->log, strlen(lmdb->log)+1);
 65166    if( rc ) return rc;
 65167  
 65168    /* release the memory */
 65169    sqlite3_free(lmdb->log);
 65170    lmdb->log = 0;
 65171  
 65172    return SQLITE_OK;
 65173  
 65174  }
 65175  
 65176  /*
 65177  ** Save the current SQL command for later use
 65178  */
 65179  SQLITE_PRIVATE void litetreeSetSqlCommand(lmdb *lmdb, char *sql) {
 65180  
 65181    if( lmdb->sql ){
 65182      sqlite3_free(lmdb->sql);
 65183    }
 65184  
 65185    lmdb->sql = sql;
 65186  
 65187  }
 65188  
 65189  /*
 65190  ** Add the current SQL command to the list
 65191  */
 65192  SQLITE_PRIVATE int sqlite3BranchStoreLastCommand(lmdb *lmdb) {
 65193  
 65194    if( lmdb->sql==0 ) return SQLITE_OK;
 65195  
 65196    netstring_add(&lmdb->log, lmdb->sql);
 65197  
 65198    if( lmdb->log==0 ){
 65199      sqlite3_log(SQLITE_NOMEM, "litetreeStoreLastCommand: out of memory");
 65200      return SQLITE_NOMEM;
 65201    }
 65202  
 65203    sqlite3_free(lmdb->sql);
 65204    lmdb->sql = 0;
 65205  
 65206    return SQLITE_OK;
 65207  
 65208  }
 65209  
 65210  /*
 65211  ** Discard the current transaction SQL commands
 65212  */
 65213  SQLITE_PRIVATE void sqlite3BranchDiscardSqlLog(lmdb *lmdb) {
 65214  
 65215    BRANCHTRACE("discarding the transaction sql commands");
 65216  
 65217    if( lmdb->log ){
 65218      sqlite3_free(lmdb->log);
 65219      lmdb->log = 0;
 65220    }
 65221  
 65222    litetreeSetSqlCommand(lmdb, (char*)0);
 65223  
 65224  }
 65225  
 65226  /*
 65227  ** Process the current SQL command
 65228  */
 65229  SQLITE_PRIVATE void litetreeProcessExecCommand(sqlite3 *db, int iDb, Pager *pPager, char *zSql) {
 65230    const char *zDbName = db->aDb[iDb].zDbSName;
 65231    char find[256], *p;
 65232  
 65233    BRANCHTRACE(" expanded SQL: %s", zSql);
 65234  
 65235    if( iDb>0 ){
 65236      /* remove the attached database name */
 65237      strcpy(find, zDbName);
 65238      strcat(find, ".");
 65239      replace_first(zSql, find, "");
 65240      BRANCHTRACE("updated expanded SQL: %s", zSql);
 65241    }
 65242  
 65243    /* remove trailing ';' */
 65244    p = zSql + strlen(zSql) - 1;
 65245    if( *p==';' ) *p=0;
 65246  
 65247    /* store the command for later use */
 65248    litetreeSetSqlCommand(pPager->lmdb, zSql);
 65249  
 65250  }
 65251  
 65252  /*
 65253  ** Check if the SQL command currently being executed must be saved in the log
 65254  */
 65255  SQLITE_PRIVATE void litetreeCheckExecCommand(sqlite3 *db, Vdbe *p, char *zSql) {
 65256    Pager *pPager;
 65257    int j;
 65258  
 65259    /* remove leading spaces */
 65260    while( sqlite3Isspace(*zSql) ) zSql++;
 65261  
 65262    /* read and pragma commands are not included */
 65263    if( sqlite3StrNICmp(zSql, "select", 6)==0 ||
 65264        sqlite3StrNICmp(zSql, "pragma", 6)==0 ){
 65265      return;
 65266    }
 65267  
 65268    /* transaction commands are not included */
 65269    if( sqlite3StrNICmp(zSql, "begin", 5)==0 ||
 65270        sqlite3StrNICmp(zSql, "commit", 6)==0 ||
 65271        sqlite3StrNICmp(zSql, "end", 3)==0 ||
 65272        sqlite3StrNICmp(zSql, "savepoint", 9)==0 ||
 65273        sqlite3StrNICmp(zSql, "release", 7)==0 ||
 65274        sqlite3StrNICmp(zSql, "rollback", 8)==0 ){
 65275      return;
 65276    }
 65277  
 65278    for(j=0; j<db->nDb; j++){
 65279      if( DbMaskTest(p->btreeMask, j) ){
 65280        BRANCHTRACE("db: %s  SQL: %s", db->aDb[j].zDbSName, zSql);
 65281        pPager = getPagerFromiDb(db, j);
 65282        if( pPager && pPager->lmdb ){
 65283          char *sql = sqlite3VdbeExpandSql(p, zSql);
 65284          litetreeProcessExecCommand(db, j, pPager, sql);
 65285          //sqlite3_free(sql);  it is released later
 65286        }
 65287      }
 65288    }
 65289  
 65290  }
 65291  
 65292  /*
 65293  ** Check whether the just executed SQL command must be stored or discarded
 65294  */
 65295  SQLITE_PRIVATE void litetreeCheckExecResult(sqlite3 *db, int rc) {
 65296    Pager *pPager;
 65297    int j;
 65298  
 65299    /* this function does not use the p->btreeMask because the command should always be released on failure */
 65300  
 65301    for(j=0; j<db->nDb; j++){
 65302      pPager = getPagerFromiDb(db, j);
 65303      if( pPager && pPager->lmdb ){
 65304        lmdb *lmdb = pPager->lmdb;
 65305        if( lmdb->sql ){
 65306          if( rc==SQLITE_DONE ){
 65307            BRANCHTRACE("exec result - storing last command: %s", lmdb->sql);
 65308            sqlite3BranchStoreLastCommand(lmdb);
 65309          } else {
 65310            /* Discard the SQL command on failure */
 65311            BRANCHTRACE("exec result - discarding last command: %s", lmdb->sql);
 65312            litetreeSetSqlCommand(lmdb, (char *) 0);
 65313          }
 65314        }
 65315      }
 65316    }
 65317  
 65318  }
 65319  
 65320  #endif /* OMIT_BRANCH_LOG */
 65321  
 65322  /*
 65323  ** PRAGMA commands -----------------------------------------------------------
 65324  */
 65325  
 65326  // PRAGMA branch_result=json
 65327  // PRAGMA branch_result=rows
 65328  
 65329  SQLITE_PRIVATE int pragma_set_current_branch(sqlite3 *db, int iDb, char *zBranch, u64 iCommit){
 65330    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65331    Pager *pPager = getPagerFromBtree(pBtree);
 65332    lmdb *lmdb;
 65333    branch_info *branch;
 65334    int rc;
 65335  
 65336    BRANCHTRACE("pragma_set_current_branch to %s at commit %llu", zBranch, iCommit);
 65337  
 65338    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 65339    lmdb = pPager->lmdb;
 65340  
 65341    /* if the db is being accessed by many db connections */
 65342    if( !lmdb->singleConnection ){
 65343      /* check if the db was modified in another db connection */
 65344      rc = sqlite3BranchCheckReloadDb(pPager, 1);
 65345    } else {
 65346      rc = sqlite3BranchBeginReadTransaction(pPager->lmdb, 0, NULL);
 65347    }
 65348    if( rc ) return rc;
 65349  
 65350    /* try to set the current branch */
 65351    rc = set_current_branch(lmdb, zBranch, iCommit);
 65352    if( rc ) goto loc_exit;
 65353    branch = lmdb->current_branch;
 65354  
 65355    /* if this is a child branch or reading at specific commit */
 65356    if( branch->source_branch || iCommit>0 ){
 65357      if( branch->pages_db==0 || branch->maxpg_db==0 ){
 65358        /* open the branch dbs and retrieve the max pgno up to this commit */
 65359        rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 65360      } else if( iCommit>0 ){
 65361        //branch->commit_max_page = 0;  // this will make it reload the value later
 65362        /* retrieve the max pgno up to this commit */
 65363        rc = sqlite3BranchGetCommitMaxPage(lmdb, branch, branch->max_commit, &branch->commit_max_page);
 65364      }
 65365      if( rc ) goto loc_exit;
 65366    }
 65367  
 65368    /* reset the page cache and invalidate the loaded schemas */
 65369    rc = invalidate_loaded_sqlite_data(db, pBtree);
 65370  
 65371  loc_exit:
 65372    sqlite3BranchEndReadTransaction(lmdb);
 65373    return rc;
 65374  }
 65375  
 65376  SQLITE_PRIVATE char * pragma_get_current_branch(sqlite3 *db, int iDb, Parse *pParse){
 65377    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65378    Pager *pPager = getPagerFromBtree(pBtree);
 65379    char *pname="<none>";
 65380    char name[256];
 65381    lmdb *lmdb;
 65382  
 65383    if( !pPager || !pPager->lmdb ) return NULL;
 65384    lmdb = pPager->lmdb;
 65385  
 65386    /* if the db is being accessed by many db connections */
 65387    if( !lmdb->singleConnection ){
 65388      if( sqlite3BranchCheckReloadDb(pPager,0)!=SQLITE_OK ){
 65389        sqlite3ErrorMsg(pParse, "failed to reload branch info");
 65390        return NULL;
 65391      }
 65392    }
 65393  
 65394    if( lmdb->current_branch ){
 65395      struct branch_info *current_branch = lmdb->current_branch;
 65396      if( current_branch->visible ){
 65397        if( current_branch->max_commit > 0 ){
 65398          /* returns the branch name and the max commit */
 65399          sqlite3_snprintf(sizeof(name), name, "%s.%llu", current_branch->name, current_branch->max_commit);
 65400          pname = name;
 65401        } else {
 65402          /* returns just the branch name */
 65403          pname = lmdb->current_branch->name;
 65404        }
 65405      }
 65406    }
 65407  
 65408    return sqlite3_strdup(pname);
 65409  }
 65410  
 65411  SQLITE_PRIVATE int pragma_new_branch(sqlite3 *db, int iDb, char *zBranchName, char *zSourceBranch, char *zSourceCommit){
 65412    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65413    Pager *pPager = getPagerFromBtree(pBtree);
 65414    lmdb *lmdb;
 65415    u64 iSourceCommit;
 65416    int source_branch_id, i, rc;
 65417    branch_info *source_branch;
 65418    branch_info *new_branch=0;
 65419  
 65420    BRANCHTRACE("new branch [%s] starting at [%s] commit [%s]", zBranchName, zSourceBranch, zSourceCommit);
 65421  
 65422    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 65423    lmdb = pPager->lmdb;
 65424    /* this command cannot be run inside of a transaction */
 65425    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_MISUSE;
 65426  
 65427    /* check if the name is valid */
 65428    if( !zBranchName ) return SQLITE_MISUSE;
 65429    zBranchName = trimstr(zBranchName);
 65430    switch( zBranchName[0] ){
 65431    case 0: case '-':
 65432      return SQLITE_MISUSE;
 65433    }
 65434    if( strchr(zBranchName,'.') ) return SQLITE_MISUSE;
 65435    if( strchr(zBranchName,'(') ) return SQLITE_MISUSE;
 65436    if( strchr(zBranchName,')') ) return SQLITE_MISUSE;
 65437    if( strchr(zBranchName,'=') ) return SQLITE_MISUSE;
 65438    if( isnumeric(zBranchName) ) return SQLITE_MISUSE;
 65439  
 65440    /* if the db is being accessed by many db connections */
 65441    if( !lmdb->singleConnection ){
 65442      /* check if the db was modified in another db connection */
 65443      if( (rc=sqlite3BranchCheckReloadDb(pPager,0))!=SQLITE_OK ) return rc;
 65444    }
 65445  
 65446    /* check if the new branch name already exists */
 65447    if( sqlite3BranchFind(lmdb,zBranchName) > 0 ) return SQLITE_MISUSE;
 65448  
 65449    if( zSourceBranch ){
 65450      /* check if the source branch is valid */
 65451      source_branch_id = sqlite3BranchFind(lmdb, zSourceBranch);
 65452      if( source_branch_id <= 0 ) return SQLITE_NOTFOUND;
 65453      source_branch = &lmdb->branches[source_branch_id];
 65454    } else if( lmdb->current_branch ){
 65455      /* start at the current branch */
 65456      source_branch = lmdb->current_branch;
 65457      source_branch_id = source_branch->id;
 65458    } else {
 65459      return SQLITE_MISUSE;
 65460    }
 65461  
 65462    /* parse the source commit */
 65463    if( zSourceCommit ){
 65464      rc = sqlite3AtoU64(zSourceCommit, &iSourceCommit, strlen(zSourceCommit), SQLITE_UTF8);
 65465      if( rc ) return SQLITE_MISUSE;
 65466    } else {
 65467      iSourceCommit = source_branch->last_commit;
 65468    }
 65469  
 65470    /* check if the source commit is valid */
 65471    if( iSourceCommit == 0 || iSourceCommit > source_branch->last_commit ){
 65472      return SQLITE_NOTFOUND;
 65473    }
 65474  
 65475    /* make a recursive search for a valid source branch and commit */
 65476    if( iSourceCommit > 0 ){
 65477      while( iSourceCommit <= source_branch->source_commit ){
 65478        source_branch = &lmdb->branches[source_branch->source_branch];
 65479      }
 65480      /* at this point source_branch_id may no longer point to the final source branch id */
 65481      source_branch_id = source_branch->id;
 65482    }
 65483  
 65484    /* check if the source commit is accessible */
 65485    if( iSourceCommit > 0 ){
 65486      int is_accessible;
 65487      rc = is_commit_accessible(lmdb, source_branch_id, iSourceCommit, &is_accessible);
 65488      BRANCHTRACE("is_commit_accessible rc=%d is_accessible=%d", rc, is_accessible);
 65489      if( rc ) return rc;
 65490      if( !is_accessible ) return SQLITE_NOTFOUND;
 65491    }
 65492  
 65493    /* search for an unused space on the array */
 65494    for( i=1; i <= lmdb->num_branches; i++ ){
 65495      if( lmdb->branches[i].id == 0 ){
 65496        new_branch = &lmdb->branches[i];
 65497        memset(new_branch, 0, sizeof(struct branch_info));
 65498        new_branch->id = i;  /* mark as being used */
 65499        break;
 65500      }
 65501    }
 65502  
 65503    /* no free space found. allocate new space for the new branch */
 65504    if( !new_branch ){
 65505      int num_branches = lmdb->num_branches + 1;
 65506      branch_info *branches = sqlite3_realloc_zero(lmdb->branches, lmdb->num_branches + 1, num_branches + 1, sizeof(struct branch_info));
 65507      if( !branches ) return SQLITE_NOMEM;
 65508      lmdb->branches = branches;
 65509      lmdb->num_branches++;
 65510      new_branch = &lmdb->branches[num_branches];
 65511      new_branch->id = num_branches;
 65512      /* update the pointers */
 65513      source_branch = &lmdb->branches[source_branch_id];
 65514      lmdb->current_branch = 0;
 65515    }
 65516  
 65517    /* store the new branch info in the array */
 65518    new_branch->visible = 1;
 65519    strcpy(new_branch->name, zBranchName);
 65520    new_branch->source_branch = source_branch_id;
 65521    if( iSourceCommit > 0 ){
 65522      new_branch->source_commit = iSourceCommit;
 65523    } else {
 65524      new_branch->source_commit = source_branch->last_commit;
 65525    }
 65526    new_branch->last_commit = new_branch->source_commit;
 65527    // new_branch->max_page is retrieved on sqlite3BranchOpen
 65528  
 65529    // what if this command is inside of a transaction block?
 65530    // 1. just after the BEGIN command, so it is in a read txn    - update to write txn?
 65531    // 2. after writing something to the db, so it is in a write txn
 65532    //      we can detect these using the autocommit variable
 65533    //  or:
 65534    // 3. not in a txn - start and close it
 65535  
 65536    // it could use SQLite code to do this...
 65537    rc = sqlite3BranchBeginWriteTransaction(lmdb);
 65538    if( rc ) return rc;
 65539  
 65540    /* save the new branch into the database */
 65541    rc = save_branch(lmdb, new_branch->id);
 65542    if( rc ) goto loc_cancel;
 65543  
 65544    /* create the pages subdb and the maxpage subdb */
 65545    rc = sqlite3BranchOpen(lmdb, new_branch->id, 0);
 65546    if( rc ) goto loc_cancel;
 65547  
 65548    // it could use SQLite code to do this...
 65549    rc = sqlite3BranchCommitTransaction(lmdb, 0);
 65550    if( rc ) goto loc_cancel;
 65551  
 65552    /* set the new branch as the current one */
 65553    rc = set_current_branch(lmdb, zBranchName, 0);
 65554    if( rc ) return rc;
 65555  
 65556    /* reset the page cache and invalidate the loaded schemas */
 65557    rc = invalidate_loaded_sqlite_data(db, pBtree);
 65558  
 65559  loc_exit:
 65560  
 65561    if( rc ){
 65562      /* unallocate the array here in the case of error. it should be reallocated later */
 65563      unload_branch_array(lmdb);
 65564    }
 65565  
 65566    return rc;
 65567  
 65568  loc_cancel:
 65569  
 65570    /* abort the open write transaction */
 65571    sqlite3BranchEndWriteTransaction(lmdb, 0);
 65572    goto loc_exit;
 65573  
 65574  }
 65575  
 65576  /*
 65577  ** Retrieves the max commit number that is used by another branch.
 65578  ** We cannot delete commits equal or previous to this one.
 65579  */
 65580  SQLITE_PRIVATE u64 get_max_fixed_commit(lmdb *lmdb, int id){
 65581    u64 max_fixed_commit = 0;
 65582    int i;
 65583    for( i=1; i <= lmdb->num_branches; i++ ){  /* use base 1 access to the array */
 65584      if( lmdb->branches[i].source_branch == id ){
 65585        if( lmdb->branches[i].source_commit > max_fixed_commit )
 65586          max_fixed_commit = lmdb->branches[i].source_commit;
 65587      }
 65588    }
 65589    return max_fixed_commit;
 65590  }
 65591  
 65592  /*
 65593  ** Truncate the pages_db and maxpg_db to the given commit number.
 65594  */
 65595  SQLITE_PRIVATE int branch_truncate_dbs(lmdb *lmdb, branch_info *branch, u64 max_commit){
 65596    int rc=SQLITE_ERROR, rc2;
 65597    MDB_val key, value;
 65598    MDB_cursor *cursor=0;
 65599  
 65600    BRANCHTRACE("branch_truncate_dbs to [%s.%llu]", branch->name, max_commit);
 65601  
 65602    if( !lmdb || !branch || max_commit==0 ) goto loc_exit;
 65603  
 65604  
 65605    /* delete all the pages from posterior commits */
 65606  
 65607    rc = mdb_cursor_open(lmdb->txn, branch->pages_db, &cursor);
 65608    if( rc!=MDB_SUCCESS ) goto loc_failed;
 65609  
 65610    switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_FIRST)) ){
 65611      case MDB_SUCCESS:   break;
 65612      case MDB_NOTFOUND:  goto loc_next;
 65613      default:            goto loc_failed;
 65614    }
 65615  
 65616    do {
 65617      u64 this_commit;
 65618      /* get the commit id */
 65619      if( (rc=commit_from_key(&key,&this_commit))!=SQLITE_OK ) goto loc_exit;
 65620      /* check the key */
 65621      if( this_commit > max_commit ){
 65622        if( (rc=mdb_cursor_del(cursor,0)) != MDB_SUCCESS ) goto loc_failed;
 65623      }
 65624    } while ( (rc2=mdb_cursor_get(cursor, &key, &value, MDB_NEXT)) == MDB_SUCCESS );
 65625  
 65626    if( rc2!=MDB_NOTFOUND ){ rc = rc2; goto loc_failed; }
 65627  
 65628  loc_next:
 65629  
 65630    if( cursor ){ mdb_cursor_close(cursor); cursor = 0; }
 65631  
 65632  
 65633    /* delete the max-page info from posterior commits */
 65634  
 65635    rc = mdb_cursor_open(lmdb->txn, branch->maxpg_db, &cursor);
 65636    if( rc!=MDB_SUCCESS ) goto loc_failed;
 65637  
 65638    /* move to the last key */
 65639    while( (rc2=mdb_cursor_get(cursor, &key, &value, MDB_LAST)) == MDB_SUCCESS ){
 65640      u64 this_commit;
 65641      /* get the commit id */
 65642      if( (rc=mdb_value_get_u64(&key,&this_commit))!=SQLITE_OK ) goto loc_exit;
 65643      /* check the key */
 65644      if( this_commit > max_commit ){
 65645        if( (rc=mdb_cursor_del(cursor,0)) != MDB_SUCCESS ) goto loc_failed;
 65646      } else {
 65647        break;
 65648      }
 65649    }
 65650  
 65651    if( rc2==MDB_SUCCESS || rc2==MDB_NOTFOUND ){
 65652      rc = SQLITE_OK;
 65653    } else {
 65654      rc = rc2;
 65655      goto loc_failed;
 65656    }
 65657  
 65658  loc_exit:
 65659  
 65660    if( cursor ) mdb_cursor_close(cursor);
 65661    return rc;
 65662  
 65663  loc_failed:
 65664  
 65665    rc = lmdb_error(rc);
 65666    goto loc_exit;
 65667  
 65668    // test: check if this fn deleted the correct items (and left the others)
 65669    // test: commit ids > uint32_max. it must accept up to u64
 65670  
 65671  }
 65672  
 65673  SQLITE_PRIVATE int update_branch_source(lmdb *lmdb, int from_id, int to_id){
 65674    int rc, i;
 65675  
 65676    /* update the source branch of child branches */
 65677    for( i=1; i <= lmdb->num_branches; i++ ){
 65678      if( lmdb->branches[i].id > 0 &&
 65679          lmdb->branches[i].source_branch == from_id ){
 65680        /* update the database */
 65681        rc = put_branch_int(lmdb, i, "source_branch", to_id);
 65682        if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 65683        /* update the array */
 65684        lmdb->branches[i].source_branch = to_id;
 65685      }
 65686    }
 65687  
 65688    return SQLITE_OK;
 65689  
 65690  }
 65691  
 65692  SQLITE_PRIVATE int delete_branch(lmdb *lmdb, branch_info *branch){
 65693    u64 max_fixed_commit;
 65694    int rc, id;
 65695  
 65696    if( !lmdb || !branch ) return SQLITE_INTERNAL;
 65697  
 65698    BRANCHTRACE("delete branch [%s]", branch->name);
 65699  
 65700    id = branch->id;
 65701    if( id==0 ) return SQLITE_OK;
 65702  
 65703    /* it is not possible to delete the current branch */
 65704    if( branch == lmdb->current_branch ) return SQLITE_PERM;
 65705  
 65706    if( branch->pages_db==0 ){
 65707      /* open the branch dbs and retrieve the max pgno up to this commit */
 65708      rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 65709      if( rc ) return rc;
 65710    }
 65711  
 65712    /* get the last fixed commit that cannot be deleted */
 65713    max_fixed_commit = get_max_fixed_commit(lmdb, branch->id);
 65714  
 65715    /* can we delete all the commits? */
 65716    if( max_fixed_commit > 0 ){
 65717      /* delete the last commits down to the last one in use */
 65718      rc = branch_truncate_dbs(lmdb, branch, max_fixed_commit);
 65719      if( rc ) return rc;
 65720      /* update the last commit on this branch */
 65721      branch->last_commit = max_fixed_commit;
 65722      /* force to reload the max number of pages */
 65723      branch->max_page = 0;
 65724    } else {
 65725      /* delete all the commits */
 65726      if( (rc=mdb_drop(lmdb->txn,branch->pages_db,1))!=MDB_SUCCESS ) goto loc_failed;
 65727      if( (rc=mdb_drop(lmdb->txn,branch->maxpg_db,1))!=MDB_SUCCESS ) goto loc_failed;
 65728      /* delete this entire branch */
 65729      branch->id = 0;
 65730    }
 65731  
 65732    /* mark this branch as not visible */
 65733    branch->visible = 0;
 65734  
 65735    rc = save_branch(lmdb, id);
 65736  
 65737  loc_exit:
 65738    return rc;
 65739  
 65740  loc_failed:
 65741    rc = lmdb_error(rc);
 65742    goto loc_exit;
 65743  
 65744  }
 65745  
 65746  SQLITE_PRIVATE int pragma_delete_branch(sqlite3 *db, int iDb, char *name){
 65747  #ifndef SQLITE_OMIT_DELETE_BRANCH
 65748    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65749    Pager *pPager = getPagerFromBtree(pBtree);
 65750    lmdb *lmdb;
 65751    branch_info *branch;
 65752    int id, rc;
 65753  
 65754    BRANCHTRACE("pragma delete branch [%s]", name);
 65755  
 65756    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 65757    lmdb = pPager->lmdb;
 65758    /* this command cannot be run inside of a transaction */
 65759    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_MISUSE;
 65760  
 65761    /* if the db is being accessed by many db connections */
 65762    if( !lmdb->singleConnection ){
 65763      /* check if the db was modified in another db connection */
 65764      if( (rc=sqlite3BranchCheckReloadDb(pPager,0))!=SQLITE_OK ) return rc;
 65765    }
 65766  
 65767    /* check if the branch name is valid */
 65768    id = sqlite3BranchFind(lmdb, name);
 65769    if( id <= 0 ) return SQLITE_NOTFOUND;
 65770    /* it is not possible to delete the current branch */
 65771    if( id == lmdb->current_branch->id ) return SQLITE_PERM;
 65772    branch = &lmdb->branches[id];
 65773  
 65774    if( !branch->visible ) return SQLITE_PERM;
 65775  
 65776    rc = sqlite3BranchBeginWriteTransaction(lmdb);
 65777    if( rc ) return rc;
 65778  
 65779    rc = delete_branch(lmdb, branch);
 65780    if( rc ) goto loc_failed;
 65781  
 65782    rc = sqlite3BranchCommitTransaction(lmdb, 0);
 65783    return rc;
 65784  
 65785  loc_failed:
 65786  
 65787    sqlite3BranchEndWriteTransaction(lmdb, 0);
 65788    return rc;
 65789  
 65790  // test: delete in one conn then try to access itself and its children in another conn
 65791  // test: delete in one conn a branch that is in use in another conn
 65792  // test: try to delete the branch that is the current one (should fail)
 65793  
 65794  #endif
 65795  }
 65796  
 65797  SQLITE_PRIVATE int pragma_truncate_branch(sqlite3 *db, int iDb, char *name, u64 to_commit){
 65798  #ifndef SQLITE_OMIT_DELETE_BRANCH
 65799    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65800    Pager *pPager = getPagerFromBtree(pBtree);
 65801    lmdb *lmdb;
 65802    branch_info *branch;
 65803    u64 max_fixed_commit;
 65804    int id, rc;
 65805  
 65806    BRANCHTRACE("truncate branch [%s] down to commit [%llu]", name, to_commit);
 65807  
 65808    if( !pPager || !pPager->lmdb || !name || to_commit==0 ) return SQLITE_ERROR;
 65809    lmdb = pPager->lmdb;
 65810    /* this command cannot be run inside of a transaction */
 65811    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_MISUSE;
 65812  
 65813    /* if the db is being accessed by many db connections */
 65814    if( !lmdb->singleConnection ){
 65815      /* check if the db was modified in another db connection */
 65816      if( (rc=sqlite3BranchCheckReloadDb(pPager,0))!=SQLITE_OK ) return rc;
 65817    }
 65818  
 65819    /* check if the branch name is valid */
 65820    id = sqlite3BranchFind(lmdb, name);
 65821    if( id <= 0 ) return SQLITE_NOTFOUND;
 65822    branch = &lmdb->branches[id];
 65823  
 65824    /* get the last fixed commit that cannot be deleted */
 65825    max_fixed_commit = get_max_fixed_commit(lmdb, id);
 65826  
 65827    /* can we truncate to this commit? */
 65828    if( max_fixed_commit > 0 && to_commit < max_fixed_commit ){
 65829      return SQLITE_PERM;
 65830    }
 65831    if( to_commit >= branch->last_commit ){
 65832      return SQLITE_OK;
 65833    }
 65834    if( branch->max_commit > 0 && to_commit < branch->max_commit ){
 65835      return SQLITE_PERM;
 65836    }
 65837  
 65838    /* check if the source commit is accessible */
 65839    if( to_commit > 0 ){
 65840      int is_accessible;
 65841      rc = is_commit_accessible(lmdb, id, to_commit, &is_accessible);
 65842      BRANCHTRACE("is_commit_accessible rc=%d is_accessible=%d", rc, is_accessible);
 65843      if( rc ) return rc;
 65844      if( !is_accessible ) return SQLITE_PERM;
 65845    }
 65846  
 65847    rc = sqlite3BranchBeginWriteTransaction(lmdb);
 65848    if( rc ) return rc;
 65849  
 65850    /* if the pages db is not open, open it now */
 65851    if( branch->pages_db == 0 ){
 65852      rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 65853      if( rc ) goto loc_failed;
 65854    }
 65855  
 65856    /* delete the last commits down to the last one in use */
 65857    rc = branch_truncate_dbs(lmdb, branch, to_commit);
 65858    if( rc ) goto loc_failed;
 65859  
 65860    /* update the last commit on this branch */
 65861    branch->last_commit = to_commit;
 65862  
 65863    /* force to reload the max number of pages */
 65864    branch->max_page = 0;
 65865  
 65866    rc = save_branch(lmdb, id);
 65867    if( rc ) goto loc_failed;
 65868  
 65869    rc = sqlite3BranchCommitTransaction(lmdb, 0);
 65870    if( rc ) goto loc_failed;
 65871  
 65872    /* reset the page cache and invalidate the loaded schemas */
 65873    rc = invalidate_loaded_sqlite_data(db, pBtree);
 65874  
 65875    return rc;
 65876  
 65877  loc_failed:
 65878  
 65879    sqlite3BranchEndWriteTransaction(lmdb, 0);
 65880    return rc;
 65881  
 65882  // test: truncate in one conn then try to access it in another conn (branch that is in use in another conn)
 65883  
 65884  #endif
 65885  }
 65886  
 65887  SQLITE_PRIVATE int pragma_rename_branch(sqlite3 *db, int iDb, char *zOldName, char *zNewName){
 65888    Btree *pBtree = getBtreeFromiDb(db, iDb);
 65889    Pager *pPager = getPagerFromBtree(pBtree);
 65890    lmdb *lmdb;
 65891    branch_info *branch;
 65892    int id, rc;
 65893  
 65894    BRANCHTRACE("rename branch [%s] to [%s]", zOldName, zNewName);
 65895  
 65896    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 65897    lmdb = pPager->lmdb;
 65898    /* this command cannot be run inside of a transaction */
 65899    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_MISUSE;
 65900  
 65901    /* if the db is being accessed by many db connections */
 65902    if( !lmdb->singleConnection ){
 65903      /* check if the db was modified in another db connection */
 65904      if( (rc=sqlite3BranchCheckReloadDb(pPager,0))!=SQLITE_OK ) return rc;
 65905    }
 65906  
 65907    /* check if the source branch is valid */
 65908    id = sqlite3BranchFind(lmdb, zOldName);
 65909    if( id <= 0 ) return SQLITE_NOTFOUND;
 65910    branch = &lmdb->branches[id];
 65911  
 65912    rc = sqlite3BranchBeginWriteTransaction(lmdb);
 65913    if( rc ) return rc;
 65914  
 65915    /* save the new name to the database */
 65916    if( (rc=put_branch_str(lmdb, id, "name", zNewName)) != MDB_SUCCESS ){
 65917      sqlite3BranchEndWriteTransaction(lmdb, 0);
 65918      return SQLITE_ERROR;
 65919    }
 65920  
 65921    rc = sqlite3BranchCommitTransaction(lmdb, 0);
 65922    if( rc ) return rc;
 65923  
 65924    /* update the name on the array */
 65925    strncpy(branch->name, zNewName, sizeof(branch->name));
 65926  
 65927    return SQLITE_OK;
 65928  
 65929    // test: create branch in one conn and try to rename it on another conn
 65930    // test: rename branch in one conn and try to move to the previous/old name on another conn (should work if single_conn=true)
 65931    // test: rename branch in one conn and check the current branch name on another conn (and list the names)
 65932  
 65933  }
 65934  
 65935  /*
 65936  ** Compare the branch structs based on the source commit in descending order
 65937  */
 65938  SQLITE_PRIVATE int compare_source_commit(const void *elem1, const void *elem2){
 65939    struct branch_info *branch1 = *(struct branch_info **) elem1;
 65940    struct branch_info *branch2 = *(struct branch_info **) elem2;
 65941    if( branch1->source_commit > branch2->source_commit ) return -1;
 65942    if( branch1->source_commit < branch2->source_commit ) return 1;
 65943    return 0;
 65944  }
 65945  
 65946  /*
 65947  ** Add the branch to the branch tree
 65948  */
 65949  SQLITE_PRIVATE int add_branch_to_tree(lmdb *lmdb, int id, char **lines, int *ppos, int digits_per_commit){
 65950    int i, j, pos = *ppos;
 65951    int count = 0, next;
 65952    u64 u;
 65953    char *p;
 65954  
 65955    /* it does not support huge branches */
 65956    if( lmdb->branches[id].last_commit > 1024 ) return SQLITE_MISUSE;
 65957  
 65958    /* it will write to this line */
 65959    p = lines[pos];
 65960  
 65961    /* add padding */
 65962    for( u=0; u < lmdb->branches[id].source_commit; u++ ){
 65963      for( j=0; j < digits_per_commit + 1; j++ ){
 65964        *p = ' '; p++;
 65965      }
 65966    }
 65967  
 65968    /* if it is a child branch, add traces to the source branch */
 65969    if( lmdb->branches[id].source_commit > 0 ){
 65970      int n;
 65971      p -= 2;
 65972      n = p - lines[pos];
 65973      *p = '`'; p++;
 65974      *p = '-'; p++;
 65975      /* fill the previous lines */
 65976      for( i=pos-1; i>0; i-- ){
 65977        char *q = lines[i];
 65978        if( q[n] == '`' ){
 65979          q[n] = '+';
 65980        } else if( q[n] == ' ' ){
 65981          q[n] = '|';
 65982        } else {
 65983          break;
 65984        }
 65985      }
 65986    }
 65987  
 65988    /* insert the commits */
 65989    for( u=lmdb->branches[id].source_commit+1; u<=lmdb->branches[id].last_commit; u++ ){
 65990      int commit = u;  /* convert to 32-bit integer, as bigger numbers will not be supported */
 65991      if( count > 0 ){
 65992        *p = '-'; p++;
 65993      }
 65994      count++;
 65995      sprintf(p, "%0*d", digits_per_commit, commit);
 65996      p += digits_per_commit;
 65997    }
 65998  
 65999    /* add 2 spaces and the branch name */
 66000    *p = ' '; p++;
 66001    *p = ' '; p++;
 66002    strcpy(p, lmdb->branches[id].name);
 66003  
 66004    /* create a list of child branches */
 66005    struct branch_info **child = sqlite3_malloc((lmdb->num_branches+1) * sizeof(void*));
 66006    if( !child ) return SQLITE_NOMEM;
 66007    count = 0;
 66008    /* copy the child branches to the list */
 66009    for( i=1; i<=lmdb->num_branches; i++ ){
 66010      if( lmdb->branches[i].source_branch==id ){
 66011        child[count] = &lmdb->branches[i];
 66012        count++;
 66013      }
 66014    }
 66015    /* sort the list by the source_commit in descending order */
 66016    qsort(child, count, sizeof(void*), compare_source_commit);
 66017    /* iterate through the child branches, calling this function recursively */
 66018    for( i=0; i<count; i++ ){
 66019      /* get the position of this branch in the array */
 66020      for( j=1; j<=lmdb->num_branches; j++ ){
 66021        if( &lmdb->branches[j] == child[i] ){
 66022          next = j;
 66023          break;
 66024        }
 66025      }
 66026      *ppos += 2;
 66027      add_branch_to_tree(lmdb, next, lines, ppos, digits_per_commit);
 66028    }
 66029    /* release the array */
 66030    sqlite3_free(child);
 66031  
 66032    return SQLITE_OK;
 66033  }
 66034  
 66035  /*
 66036  ** Builds a tree of the existing branches
 66037  */
 66038  SQLITE_PRIVATE int pragma_branch_tree(sqlite3 *db, int iDb, char **presult){
 66039    Btree *pBtree = getBtreeFromiDb(db, iDb);
 66040    Pager *pPager = getPagerFromBtree(pBtree);
 66041    lmdb *lmdb;
 66042    sqlite3_str *result;
 66043    char **lines;
 66044    int max_commit=0, max_name=0, digits_per_commit, num_lines, size;
 66045    int rc, i, j, pos;
 66046  
 66047    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 66048    lmdb = pPager->lmdb;
 66049  
 66050    /* get the highest commit number and the longer name */
 66051    for( i=1; i<=lmdb->num_branches; i++ ){
 66052      int len = strlen(lmdb->branches[i].name);
 66053      if( len > max_name ) max_name = len;
 66054      if( lmdb->branches[i].last_commit > max_commit ){
 66055        max_commit = lmdb->branches[i].last_commit;
 66056      }
 66057    }
 66058  
 66059    /* how many digits to print each commit */
 66060    digits_per_commit = numdigits(max_commit);
 66061  
 66062    /* allocate an array of lines */
 66063    num_lines = lmdb->num_branches * 2 - 1;
 66064    lines = sqlite3_malloc(num_lines * sizeof(void*));
 66065    if( !lines ) return SQLITE_NOMEM;
 66066    memset(lines, 0, num_lines * sizeof(void*));
 66067  
 66068    /* calculate the size of each line */
 66069    size = max_commit * digits_per_commit * 2 + max_name + 3;
 66070  
 66071    /* allocate the lines */
 66072    for( i=0; i<num_lines; i++ ){
 66073      lines[i] = sqlite3_malloc(size);
 66074      if( !lines[i] ){ rc = SQLITE_NOMEM; goto loc_exit; }
 66075      for( j=0; j<size; j++ ){
 66076        lines[i][j] = ' ';
 66077      }
 66078      lines[i][size-1] = '\0';
 66079    }
 66080  
 66081    /* add the first branch to the tree */
 66082    pos = 0;
 66083    rc = add_branch_to_tree(lmdb, 1, lines, &pos, digits_per_commit);
 66084    if( rc ) goto loc_exit;
 66085  
 66086    /* concatenate the lines into a single string */
 66087    result = sqlite3_str_new(NULL);
 66088    for(i=0; i<=pos; i++){
 66089      for(j=size-2; j>0; j--){
 66090        if( lines[i][j] != ' ' ) break;
 66091        lines[i][j] = '\0';
 66092      }
 66093      if( i>0 ) sqlite3_str_appendall(result, "\n");
 66094      sqlite3_str_appendall(result, lines[i]);
 66095    }
 66096    /* check for error */
 66097    rc = sqlite3_str_errcode(result);
 66098    if( rc ){ sqlite3_str_destroy(result); goto loc_exit; }
 66099    /* retrieve the result string */
 66100    *presult = sqlite3_str_finish(result);
 66101  
 66102    rc = SQLITE_OK;
 66103  
 66104  loc_exit:
 66105  
 66106    for( i=0; i<num_lines; i++ ){
 66107      sqlite3_free(lines[i]);
 66108    }
 66109    sqlite3_free(lines);
 66110    return rc;
 66111  
 66112  }
 66113  
 66114  #ifndef OMIT_BRANCH_LOG
 66115  
 66116  /*
 66117  ** The branch log can be iterated using the following formats:
 66118  ** -split: one SQL command per result row
 66119  ** -netstring: one commit per result row, SQL commands joined in netstring format
 66120  ** -delimited: one commit per result row, SQL commands joined using a delimiter
 66121  */
 66122  
 66123  #define BRANCH_LOG_SPLIT      0
 66124  #define BRANCH_LOG_DELIMITED  1
 66125  #define BRANCH_LOG_NETSTRING  2
 66126  
 66127  #define get_log_format(id)    (id==BRANCH_LOG_NETSTRING?"netstring": \
 66128                                 id==BRANCH_LOG_DELIMITED?"delimited":"split")
 66129  
 66130  /*
 66131  ** Iterate through the branch logs and calls the supplied callback
 66132  ** for each log item, according to the requested format.
 66133  **
 66134  ** The callback must be of this format:
 66135  **
 66136  ** int function_name(void *arg, char *branch_name, u64 commit, char *log)
 66137  */
 66138  SQLITE_PRIVATE int iterate_branch_logs(
 66139    lmdb *lmdb,
 66140    branch_info *branch,
 66141    u64 commit,
 66142    u64 to_commit,
 66143    int format,
 66144    char *delimiter,
 66145    int (*callback)(void*,char*,u64,char*),  /* Callback function */
 66146    void *arg                                /* First argument to callback() */
 66147  ){
 66148    int rc;
 66149  
 66150    BRANCHTRACE("iterate_branch_logs branch=%s commit=%llu to_commit=%llu format=%s",
 66151                branch->name, commit, to_commit, get_log_format(format));
 66152  
 66153    if( !delimiter ) delimiter = ";";
 66154  
 66155    /* iterate through the commits */
 66156    for(; commit<=to_commit; commit++){
 66157      char *log;
 66158      int size;
 66159      /* get this commit's branch */
 66160      branch_info *xbranch = branch;
 66161      int branch_id = xbranch->id;
 66162      while( commit <= xbranch->source_commit ){
 66163        branch_id = xbranch->source_branch;
 66164        xbranch = &lmdb->branches[branch_id];
 66165      }
 66166      /* load the commit log */
 66167      rc = branch_get_log(lmdb, branch_id, commit, &log, &size);
 66168      if( rc==SQLITE_NOTFOUND ) continue;
 66169      if( rc ) goto loc_exit;
 66170      /* process the logs according to the requested format */
 66171      if( format==BRANCH_LOG_NETSTRING ){
 66172        /* call the callback function */
 66173        callback(arg, xbranch->name, commit, log);
 66174      } else {
 66175        sqlite3_str *cmds = NULL;
 66176        char  *sql, *base = log;
 66177        size_t len, bsize = size;
 66178        /* parse the netstring */
 66179        while( netstring_read(&base, &bsize, &sql, &len)==0 ){
 66180          if( format==BRANCH_LOG_DELIMITED ){
 66181            if( !cmds ){
 66182              cmds = sqlite3_str_new(NULL);
 66183            } else {
 66184              sqlite3_str_appendall(cmds, delimiter);
 66185            }
 66186            /* append the SQL command */
 66187            sqlite3_str_append(cmds, sql, len);
 66188            /* check for error */
 66189            rc = sqlite3_str_errcode(cmds);
 66190            if( rc ){ sqlite3_str_destroy(cmds); goto loc_exit; }
 66191          } else {
 66192            /* create a copy to add a null terminator, as we cannot modify memory from LMDB */
 66193            char *sql2 = sqlite3_memdup(sql, len+1);
 66194            if( !sql2 ) return SQLITE_NOMEM;
 66195            sql2[len] = 0;
 66196            /* call the callback function */
 66197            callback(arg, xbranch->name, commit, sql2);
 66198            sqlite3_free(sql2);
 66199          }
 66200        }
 66201        if( format==BRANCH_LOG_DELIMITED ){
 66202          /* call the callback function */
 66203          callback(arg, xbranch->name, commit, sqlite3_str_value(cmds));
 66204          /* release the netstring */
 66205          sqlite3_str_destroy(cmds);
 66206          cmds = NULL;
 66207        }
 66208      }
 66209    }
 66210  
 66211    rc = SQLITE_OK;
 66212  
 66213  loc_exit:
 66214    return rc;
 66215  
 66216  }
 66217  
 66218  /*
 66219  ** Callback used to add the branch log to the pragma result table
 66220  */
 66221  SQLITE_PRIVATE int add_branch_log_result(void *arg, char *branch_name, u64 commit, char *log){
 66222    Vdbe *v = (Vdbe *)arg;
 66223    BRANCHTRACE("add_branch_log_result branch=%s commit=%llu", branch_name, commit);
 66224    /* add the new record */
 66225    sqlite3VdbeMultiLoad(v, 1, "sus",   //! the vdbe is currently using i64 instead of u64. it does not have a P4_UINT64
 66226        branch_name,
 66227        commit,
 66228        log);
 66229    return SQLITE_OK;
 66230  }
 66231  
 66232  /*
 66233  ** Parse and validate the supplied range.
 66234  ** Calls the iterator for the SQL logs using the above function as callback.
 66235  */
 66236  SQLITE_PRIVATE int pragma_get_branch_log_b(lmdb *lmdb, char *range, int is_strict, int format, char *delimiter, Parse *pParse){
 66237    Vdbe *v = sqlite3GetVdbe(pParse);
 66238    branch_info *branch;
 66239    char *branch_name=NULL;
 66240    int branch_id=0;
 66241    u64 commit=0, to_commit=0;
 66242  
 66243    BRANCHTRACE("pragma_get_branch_log range=%s is_strict=%d", range, is_strict);
 66244  
 66245    /* process the argument */
 66246    if( range && strlen(range)>0 ){
 66247      char *zcommit = stripchr(range, '.');
 66248      branch_name = range;
 66249      if( zcommit ){
 66250        char *zto_commit = stripchr(zcommit, '-');
 66251        if( *zcommit!='*' ){
 66252          commit = atou64(zcommit);
 66253          if( commit==0 ) return SQLITE_MISUSE;
 66254        }
 66255        if( zto_commit ){
 66256          if( *zto_commit!='*' ){
 66257            to_commit = atou64(zto_commit);
 66258            if( to_commit==0 ) return SQLITE_MISUSE;
 66259          }
 66260        } else {
 66261          to_commit = commit;
 66262        }
 66263      } else {
 66264        /* all commits from the requested branch */
 66265      }
 66266    } else {
 66267      /* all commits from the current branch */
 66268    }
 66269  
 66270    if( branch_name ){
 66271      /* search for the branch with the given name */
 66272      branch_id = sqlite3BranchFind(lmdb, branch_name);
 66273      /* not found? */
 66274      if( branch_id <= 0 ) return SQLITE_NOTFOUND;
 66275      branch = &lmdb->branches[branch_id];
 66276    } else if( lmdb->current_branch ){
 66277      /* use the current branch */
 66278      branch = lmdb->current_branch;
 66279      branch_id = branch->id;
 66280      to_commit = branch->max_commit;
 66281    } else {
 66282      /* no current branch */
 66283      return SQLITE_MISUSE;
 66284    }
 66285  
 66286    if( branch->last_commit==0 ){
 66287      /* set the number of columns */
 66288      pParse->nMem = 3;
 66289      /* the database is empty */
 66290      return add_branch_log_result(v, "", 0, "");
 66291    }
 66292  
 66293    if( commit==0 ){
 66294      /* set the starting commit */
 66295      if( is_strict ){
 66296        commit = branch->source_commit + 1;
 66297      } else {
 66298        commit = 1;
 66299      }
 66300    }
 66301  
 66302    if( to_commit==0 ){
 66303      /* return all commits from the requested branch */
 66304      to_commit = branch->last_commit;
 66305    }
 66306  
 66307    /* check for valid arguments */
 66308    if( to_commit < commit ) return SQLITE_MISUSE;
 66309    if( to_commit > branch->last_commit ) return SQLITE_NOTFOUND;
 66310  
 66311    /* set the number of columns */
 66312    pParse->nMem = 3;
 66313  
 66314    /* iterate through the logs using the supplied callback */
 66315    return iterate_branch_logs(lmdb, branch, commit, to_commit, format, delimiter, add_branch_log_result, v);
 66316  
 66317  }
 66318  
 66319  /*
 66320  ** PRAGMA branch_log [--strict] [{range}] [{format}]
 66321  **
 66322  ** where {range} can be:
 66323  ** -empty
 66324  ** -a branch name
 66325  ** -a single commit
 66326  ** -a commit range
 66327  */
 66328  SQLITE_PRIVATE int pragma_get_branch_log(sqlite3 *db, int iDb, char *params, Parse *pParse){
 66329    Btree *pBtree = getBtreeFromiDb(db, iDb);
 66330    Pager *pPager = getPagerFromBtree(pBtree);
 66331    lmdb *lmdb;
 66332    int already_in_txn=0, rc;
 66333    int is_strict = 0;
 66334    int format = BRANCH_LOG_SPLIT;
 66335    char *delimiter;
 66336  
 66337    struct params options[] = {
 66338      {"strict", &is_strict, 1, NULL},
 66339      {"netstring", &format, BRANCH_LOG_NETSTRING, NULL},
 66340      {"delimited", &format, BRANCH_LOG_DELIMITED, &delimiter},
 66341      {NULL,NULL,0,NULL,}
 66342    };
 66343  
 66344    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 66345    lmdb = pPager->lmdb;
 66346  
 66347    if( params ){
 66348      rc = parse_params(params, options, &params);
 66349      if( rc ){
 66350        sqlite3ErrorMsg(pParse, "invalid option: %s", params);
 66351        return SQLITE_OK;
 66352      }
 66353      if( delimiter ) parse_delimiter(delimiter);
 66354    }
 66355  
 66356    /* is it already inside of a transaction? */
 66357    if( lmdb->inReadTxn || lmdb->inWriteTxn ){
 66358      already_in_txn = 1;
 66359    } else {
 66360      /* if the db is being accessed by many db connections */
 66361      if( !lmdb->singleConnection ){
 66362        /* check if the db was modified in another db connection */
 66363        rc = sqlite3BranchCheckReloadDb(pPager, 1);
 66364      } else {
 66365        rc = sqlite3BranchBeginReadTransaction(pPager->lmdb, 0, NULL);
 66366      }
 66367      if( rc ) return rc;
 66368    }
 66369  
 66370    rc = pragma_get_branch_log_b(lmdb, params, is_strict, format, delimiter, pParse);
 66371  
 66372    if( !already_in_txn ) sqlite3BranchEndReadTransaction(lmdb);
 66373    return rc;
 66374  
 66375  }
 66376  
 66377  #define BRANCH_LOG_SET  1
 66378  #define BRANCH_LOG_ADD  2
 66379  #define BRANCH_LOG_DEL  3
 66380  
 66381  /*
 66382  ** PRAGMA branch_log --set {commit} {commands} {commit} {commands} ...
 66383  ** PRAGMA branch_log --add {commit} {commands}
 66384  ** PRAGMA branch_log --del {commit} {command_list}
 66385  */
 66386  SQLITE_PRIVATE int pragma_branch_edit_log(sqlite3 *db, int iDb, int command, char *args, char **msg){
 66387    int rc=SQLITE_OK;
 66388  
 66389  
 66390    return rc;
 66391  
 66392  }
 66393  
 66394  #endif /* OMIT_BRANCH_LOG */
 66395  
 66396  /*
 66397  ** PRAGMA branch_diff {from_branch}[.{commit}] {to_branch}[.{commit}]
 66398  */
 66399  SQLITE_PRIVATE char * pragma_branch_diff(sqlite3 *db, int iDb, char *point1, char *point2){
 66400  
 66401  
 66402    //! to implement
 66403  
 66404  
 66405    return sqlite3_strdup("OK");
 66406  
 66407  
 66408  }
 66409  
 66410  /*
 66411  ** Merges forward commits from a single direct child branch into the parent branch
 66412  */
 66413  SQLITE_PRIVATE int forward_merge_one_branch(lmdb *lmdb, branch_info *parent, branch_info *child, u64 num_commits){
 66414    MDB_cursor *cursor=0;
 66415    MDB_val key, value;
 66416    u64 start_commit, end_commit, commit;
 66417    int rc, cmd, i;
 66418  
 66419    BRANCHTRACE("forward_merge_one_branch parent=%s child=%s num_commits=%llu", parent->name, child->name, num_commits);
 66420  
 66421    /* if the pages db is not open, open it now */
 66422    if( parent->pages_db == 0 ){
 66423      rc = sqlite3BranchOpen(lmdb, parent->id, 0);
 66424      if( rc ) goto loc_failed;
 66425    }
 66426    if( child->pages_db == 0 ){
 66427      rc = sqlite3BranchOpen(lmdb, child->id, 0);
 66428      if( rc ) goto loc_failed;
 66429    }
 66430  
 66431    /* move the db pages from the child branch to the parent branch */
 66432  
 66433    start_commit = child->source_commit + 1;
 66434    end_commit = start_commit + num_commits - 1;
 66435  
 66436    parent->txn_max_page = parent->max_page;
 66437  
 66438    /* scan the db searching for pages belonging to these commits */
 66439  
 66440    if( (rc = mdb_cursor_open(lmdb->txn, child->pages_db, &cursor)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 66441  
 66442    cmd = MDB_FIRST;
 66443    while( (rc=mdb_cursor_get(cursor,&key,&value,cmd))==MDB_SUCCESS ){
 66444      cmd = MDB_NEXT;
 66445      /* get the commit id */
 66446      if( (rc=commit_from_key(&key,&commit))!=SQLITE_OK ) goto loc_failed;
 66447      /* should this commit be moved? */
 66448      if( commit >= start_commit && commit <= end_commit ){
 66449        Pgno pgno;
 66450        /* get the page number */
 66451        if( (rc=pgno_from_key(&key,&pgno))!=SQLITE_OK ) goto loc_failed;
 66452        BRANCHTRACE("moving page %u from commit %llu", pgno, commit);
 66453        /* check the value size */
 66454        if( value.mv_size != lmdb->pageSize-LMDB_PAGE_RESERVED_SPACE ) { rc = SQLITE_CORRUPT; goto loc_failed; }
 66455        /* copy the page to the parent branch */
 66456        if( (rc=mdb_put(lmdb->txn, parent->pages_db, &key, &value, 0)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 66457        /* delete the page from the child branch */
 66458        if( (rc=mdb_del(lmdb->txn, child->pages_db, &key, NULL)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 66459        /* update the parent max_page */
 66460        if( pgno > parent->txn_max_page ) parent->txn_max_page = pgno;
 66461      }
 66462    }
 66463  
 66464    if( rc!=MDB_NOTFOUND ) goto loc_lmdb_failed;
 66465  
 66466    mdb_cursor_close(cursor);
 66467  
 66468    /* copy data from the child->maxpg_db to the parent one */
 66469    for( commit = start_commit; commit <= end_commit; commit++ ){
 66470      u32 max_page;
 66471      /* get the number of pages on this commit, if set */
 66472      rc = mdb_u64_get_u32(lmdb->txn, child->maxpg_db, commit, &max_page);
 66473      if( rc==MDB_SUCCESS ){
 66474        /* save it on the parent maxpg db */
 66475        rc = mdb_u64_put_u32(lmdb->txn, parent->maxpg_db, commit, max_page);
 66476        if( rc ) goto loc_lmdb_failed;
 66477      } else if( rc!=MDB_NOTFOUND ) goto loc_lmdb_failed;
 66478    }
 66479  
 66480    /* save the new values to the database */
 66481    rc = put_branch_u64(lmdb, parent->id, "last_commit", parent->last_commit + num_commits);
 66482    if( rc!=MDB_SUCCESS ) goto loc_lmdb_failed;
 66483    rc = put_branch_u64(lmdb, child->id, "source_commit", child->source_commit + num_commits);
 66484    if( rc!=MDB_SUCCESS ) goto loc_lmdb_failed;
 66485  
 66486    /* update the values on the branch array */
 66487    parent->last_commit += num_commits;
 66488    child->source_commit += num_commits;
 66489    parent->max_page = parent->txn_max_page;
 66490  
 66491    /* update the source branch of branches that start at the moved commits */
 66492    for( i=1; i <= lmdb->num_branches; i++ ){
 66493      if( lmdb->branches[i].id > 0 &&
 66494          lmdb->branches[i].source_branch == child->id &&
 66495          lmdb->branches[i].source_commit >= start_commit &&
 66496          lmdb->branches[i].source_commit <= end_commit )
 66497      {
 66498        /* update the database */
 66499        rc = put_branch_int(lmdb, i, "source_branch", parent->id);
 66500        if( rc!=MDB_SUCCESS ) goto loc_lmdb_failed;
 66501        /* update the array */
 66502        lmdb->branches[i].source_branch = parent->id;
 66503      }
 66504    }
 66505  
 66506    return SQLITE_OK;
 66507  
 66508  loc_lmdb_failed:
 66509  
 66510    rc = lmdb_error(rc);
 66511  
 66512  loc_failed:
 66513  
 66514    if( cursor ) mdb_cursor_close(cursor);
 66515    return rc;
 66516  
 66517  }
 66518  
 66519  /*
 66520  ** This function can be called recursively until it finds the direct child of the parent branch
 66521  ** Updates the number of remaining commits to merge
 66522  */
 66523  SQLITE_PRIVATE int forward_merge_sub_branch(lmdb *lmdb, branch_info *parent, branch_info *child, u64 last_commit, u64 *p_remaining_commits){
 66524    int rc;
 66525  
 66526    /* if this is not a direct child of the parent branch */
 66527    if( child->source_branch != parent->id ){
 66528      /* makes a recursive call */
 66529      rc = forward_merge_sub_branch(lmdb, parent, &lmdb->branches[child->source_branch], child->source_commit, p_remaining_commits);
 66530      if( rc ) return rc;
 66531    }
 66532  
 66533    /* if now it is a direct child of the parent branch */
 66534    if( child->source_branch == parent->id && *p_remaining_commits > 0 ){
 66535      u64 num_commits;
 66536      /* the child branch must start at the end of the parent branch */
 66537      if( child->source_commit != parent->last_commit ) return SQLITE_MISUSE;
 66538      /* check how many commits to merge now */
 66539      /* we cannot use child->last_commit here because the branch can extend to another side */
 66540      num_commits = last_commit - parent->last_commit;
 66541      if( num_commits > 0 ){
 66542        if( num_commits > *p_remaining_commits ) num_commits = *p_remaining_commits;
 66543        rc = forward_merge_one_branch(lmdb, parent, child, num_commits);
 66544        if( rc ) return rc;
 66545        *p_remaining_commits -= num_commits;
 66546      }
 66547      /* on forward merge we can delete internal branches when:
 66548      ** - the branch is empty
 66549      ** - there are remaining commits to merge
 66550      **   in another words: when we are crossing over the branch
 66551      */
 66552      if( child->last_commit == child->source_commit && *p_remaining_commits > 0 ){
 66553        /* make the child branches point to the parent */
 66554        rc = update_branch_source(lmdb, child->id, parent->id);
 66555        if( rc ) return rc;
 66556        /* delete this branch */
 66557        rc = delete_branch(lmdb, child);
 66558        if( rc ) return rc;
 66559      }
 66560    }
 66561  
 66562    return SQLITE_OK;
 66563  
 66564  }
 66565  
 66566  /*
 66567  ** Deals with the transactions on the forward merge
 66568  */
 66569  SQLITE_PRIVATE int branch_forward_merge(lmdb *lmdb, branch_info *parent, branch_info *child, u64 num_commits){
 66570    int rc;
 66571  
 66572    /* start a write transaction */
 66573    rc = sqlite3BranchBeginWriteTransaction(lmdb);
 66574    if( rc ) return rc;  /* it can fail if the database was modified */
 66575  
 66576    rc = forward_merge_sub_branch(lmdb, parent, child, child->last_commit, &num_commits);
 66577    if( rc ) goto loc_failed;
 66578  
 66579    /* commit the transaction */
 66580    rc = sqlite3BranchCommitTransaction(lmdb, 0);
 66581    if( rc ) goto loc_failed;
 66582  
 66583    return SQLITE_OK;
 66584  
 66585  loc_failed:
 66586    unload_branch_array(lmdb);
 66587    sqlite3BranchEndWriteTransaction(lmdb, 0);
 66588    return rc;
 66589  
 66590  }
 66591  
 66592  /*
 66593  ** Called by the pragma branch_merge --forward command
 66594  */
 66595  SQLITE_PRIVATE int pragma_branch_forward_merge(sqlite3 *db, int iDb, char *zparent, char *zchild, char *znum_commits){
 66596    Btree *pBtree = getBtreeFromiDb(db, iDb);
 66597    Pager *pPager = getPagerFromBtree(pBtree);
 66598    lmdb *lmdb;
 66599    branch_info *parent, *child;
 66600    int id_parent, id_child, rc;
 66601    u64 to_commit=0, num_commits=0;
 66602    char *zto_commit;
 66603  
 66604    BRANCHTRACE("forward merge parent=%s child=%s num_commits=%s", zparent, zchild, znum_commits);
 66605  
 66606    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 66607    lmdb = pPager->lmdb;
 66608    /* this command cannot be run inside of a transaction */
 66609    if( lmdb->inReadTxn || lmdb->inWriteTxn ) return SQLITE_MISUSE;
 66610  
 66611    /* if the db is being accessed by many db connections */
 66612    if( !lmdb->singleConnection ){
 66613      /* check if the db was modified in another db connection */
 66614      if( (rc=sqlite3BranchCheckReloadDb(pPager,0))!=SQLITE_OK ) return rc;
 66615    }
 66616  
 66617    /* get the max commit, if present */
 66618    zto_commit = stripchr(zchild, '.');
 66619  
 66620    /* check if the parent branch is valid */
 66621    id_parent = sqlite3BranchFind(lmdb, zparent);
 66622    if( id_parent <= 0 ) return SQLITE_NOTFOUND;
 66623    parent = &lmdb->branches[id_parent];
 66624  
 66625    /* check if the child branch is valid */
 66626    id_child = sqlite3BranchFind(lmdb, zchild);
 66627    if( id_child <= 0 ) return SQLITE_NOTFOUND;
 66628    child = &lmdb->branches[id_child];
 66629  
 66630    //! if( current->id == id_parent && current->max_commit != 0 ) return SQLITE_MISUSE;
 66631  
 66632    /* check if both branches are valid */
 66633    if( znum_commits ){
 66634      num_commits = atou64(znum_commits);
 66635      if( num_commits==0 ) return SQLITE_MISUSE;
 66636    }
 66637    if( zto_commit ){
 66638      to_commit = atou64(zto_commit);
 66639      if( to_commit==0 ) return SQLITE_MISUSE;
 66640    }
 66641  
 66642    /* these 2 values should not be supplied at the same time */
 66643    if( num_commits!=0 && to_commit!=0 ){
 66644      return SQLITE_MISUSE;
 66645    }
 66646  
 66647    if( num_commits==0 && to_commit==0 ){
 66648      to_commit = child->last_commit;
 66649    }
 66650    if( to_commit > 0 ){
 66651      if( to_commit <= parent->last_commit ) return SQLITE_MISUSE;
 66652      if( to_commit > child->last_commit ) return SQLITE_MISUSE;
 66653      /* get the number of commits to copy */
 66654      num_commits = to_commit - parent->last_commit;
 66655    }
 66656  
 66657    rc = branch_forward_merge(lmdb, parent, child, num_commits);
 66658    if( rc ) return rc;
 66659  
 66660    /* if the current branch is the parent we need to reset the schema and pager */
 66661    if( lmdb->current_branch && lmdb->current_branch->id == id_parent ){
 66662      rc = invalidate_loaded_sqlite_data(db, pBtree);
 66663      if( rc ) return rc;
 66664    }
 66665  
 66666    return SQLITE_OK;
 66667  
 66668    // test: valid and invalid parameters
 66669    // test: reopen the db and test - max_page
 66670  
 66671  }
 66672  
 66673  /*
 66674  ** Read a commit id from the commit range list
 66675  */
 66676  SQLITE_PRIVATE u64 read_range_commit(MDB_val *value){
 66677    u64 commit;
 66678    int len = sqlite4GetVarint64(value->mv_data, value->mv_size, &commit);
 66679    if( len <= 0 ) return 0;
 66680    value->mv_data = (char*)value->mv_data + len;
 66681    value->mv_size -= len;
 66682    return commit;
 66683  }
 66684  
 66685  /*
 66686  ** Write a commit id to the commit range list
 66687  */
 66688  SQLITE_PRIVATE void write_range_commit(sqlite3_str *ranges, u64 commit){
 66689    char buf[16];
 66690    int len = sqlite4PutVarint64((unsigned char *)buf, commit);
 66691    sqlite3_str_append(ranges, buf, len);
 66692  }
 66693  
 66694  /*
 66695  ** Check if the given commit is accessible for the following operations:
 66696  ** -define as current commit
 66697  ** -start a new branch at it
 66698  ** -truncate a branch at it
 66699  */
 66700  SQLITE_PRIVATE int is_commit_accessible(lmdb *lmdb, int branch_id, u64 commit, int *paccessible){
 66701    char keyname[64];
 66702    MDB_val key, value;
 66703    int rc;
 66704  
 66705    /* an open transaction is required */
 66706    if( !lmdb->inReadTxn && !lmdb->inWriteTxn ){
 66707      /* open a new read transaction */
 66708      rc = mdb_txn_begin(lmdb->env, NULL, MDB_RDONLY, &lmdb->txn);
 66709      if( rc!=MDB_SUCCESS ) return lmdb_error(rc);
 66710    }
 66711  
 66712    /* set the key */
 66713    sqlite3_snprintf(sizeof(keyname), keyname, "b%d.discarded_commits", branch_id);
 66714    key.mv_data = keyname;
 66715    key.mv_size = strlen(keyname);
 66716    /* get the value */
 66717    rc = mdb_get(lmdb->txn, lmdb->main_db, &key, &value);
 66718    if( rc==MDB_NOTFOUND ) goto loc_ok;
 66719    if( rc ) goto loc_failed;
 66720  
 66721    /* there is a key with this name */
 66722    while( value.mv_size>0 ){
 66723      u64 start, end;
 66724      if( (start=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66725      if( (end=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66726      /* check the range */
 66727      if( commit >= start && commit <= end ){
 66728        *paccessible = 0;
 66729        rc = SQLITE_OK;
 66730        goto loc_exit;
 66731      }
 66732    }
 66733  
 66734  loc_ok:
 66735  
 66736    *paccessible = 1;
 66737    rc = SQLITE_OK;
 66738  
 66739  loc_exit:
 66740  
 66741    if( !lmdb->inReadTxn && !lmdb->inWriteTxn ){
 66742      mdb_txn_abort(lmdb->txn);
 66743      lmdb->txn = 0;
 66744    }
 66745    return rc;
 66746  
 66747  loc_invalid_value:
 66748  
 66749    BRANCHTRACE("is_commit_accessible invalid value!");
 66750    rc = MDB_BAD_VALSIZE;
 66751  
 66752  loc_failed:
 66753  
 66754    rc = lmdb_error(rc);
 66755    goto loc_exit;
 66756  
 66757  }
 66758  
 66759  /*
 66760  ** Join the commit range with existing ranges, extending the start and end points
 66761  ** if there are ranges that intersect with the supplied one.
 66762  */
 66763  SQLITE_PRIVATE int join_commit_range(lmdb *lmdb, int branch_id, u64 *pstart, u64 *pend){
 66764    char keyname[64];
 66765    MDB_val key, value;
 66766    u64 start = *pstart;
 66767    u64 end = *pend;
 66768    int rc;
 66769  
 66770    /* set the key */
 66771    sqlite3_snprintf(sizeof(keyname), keyname, "b%d.discarded_commits", branch_id);
 66772    key.mv_data = keyname;
 66773    key.mv_size = strlen(keyname);
 66774    /* get the value */
 66775    rc = mdb_get(lmdb->txn, lmdb->main_db, &key, &value);
 66776    if( rc==MDB_NOTFOUND ) return SQLITE_OK;
 66777    if( rc ) return lmdb_error(rc);
 66778  
 66779    /* there is a key with this name */
 66780    while( value.mv_size>0 ){
 66781      u64 rstart, rend;
 66782      if( (rstart=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66783      if( (rend=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66784      BRANCHTRACE("join_commit_range existing discarded range: %llu to %llu", rstart, rend);
 66785      /* check the range */
 66786      if( rstart < start && rend >= start ) start = rstart;
 66787      if( rend > end && rstart <= end ) end = rend;
 66788    }
 66789  
 66790    *pstart = start;
 66791    *pend = end;
 66792    return SQLITE_OK;
 66793  
 66794  loc_invalid_value:
 66795  
 66796    BRANCHTRACE("join_commit_range invalid value!");
 66797    return lmdb_error(MDB_BAD_VALSIZE);
 66798  
 66799  }
 66800  
 66801  /*
 66802  ** Add the range to the list of unaccessible ranges.
 66803  ** They are stored as a list of varints under a key named 'discarded_commits':
 66804  **
 66805  ** b1.discarded_commits = <start><end><start><end><start><end>...
 66806  **
 66807  ** Optionally it could use a DUPSORT sub-database, with the downside of having an
 66808  ** additional sub-db for each branch.
 66809  */
 66810  SQLITE_PRIVATE int add_commit_range(lmdb *lmdb, int branch_id, u64 start, u64 end){
 66811    char keyname[64];
 66812    MDB_val key, value;
 66813    sqlite3_str *ranges=NULL;
 66814    int rc;
 66815  
 66816    BRANCHTRACE("add_commit_range branch_id=%d start=%llu end=%llu", branch_id, start, end);
 66817  
 66818    /* set the key */
 66819    sqlite3_snprintf(sizeof(keyname), keyname, "b%d.discarded_commits", branch_id);
 66820    key.mv_data = keyname;
 66821    key.mv_size = strlen(keyname);
 66822  
 66823    /* get the value */
 66824    switch( (rc=mdb_get(lmdb->txn, lmdb->main_db, &key, &value)) ){
 66825      case MDB_SUCCESS: { /* there is a key with this name */
 66826        int added=0;
 66827        /* allocate a new list */
 66828        ranges = sqlite3_str_new(NULL);
 66829        /* iterate through all the existing ranges */
 66830        while( value.mv_size>0 ){
 66831          u64 rstart, rend;
 66832          if( (rstart=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66833          if( (rend=read_range_commit(&value))==0 ) goto loc_invalid_value;
 66834          /* add the ranges to the new list */
 66835          if( rstart >= start && !added ){
 66836            /* append the new range */
 66837            BRANCHTRACE("add_commit_range new %llu-%llu", start, end);
 66838            write_range_commit(ranges, start);
 66839            write_range_commit(ranges, end);
 66840            added = 1;
 66841          }
 66842          if( rstart < start || rstart > end ){
 66843            /* append the old range */
 66844            BRANCHTRACE("add_commit_range old %llu-%llu", rstart, rend);
 66845            write_range_commit(ranges, rstart);
 66846            write_range_commit(ranges, rend);
 66847          } else {
 66848            /* do not add this range */
 66849            BRANCHTRACE("add_commit_range discarded %llu-%llu", rstart, rend);
 66850          }
 66851        }
 66852        if( !added ){
 66853          /* append the new range */
 66854          BRANCHTRACE("add_commit_range new %llu-%llu", start, end);
 66855          write_range_commit(ranges, start);
 66856          write_range_commit(ranges, end);
 66857        }
 66858        /* check for error */
 66859        rc = sqlite3_str_errcode(ranges);
 66860        if( rc ) goto loc_exit;
 66861        /* save the new range list */
 66862        rc = mdb_str_put(lmdb->txn, lmdb->main_db, keyname, sqlite3_str_value(ranges), sqlite3_str_length(ranges));
 66863        sqlite3_str_destroy(ranges); ranges = NULL;
 66864        break;
 66865      }
 66866      case MDB_NOTFOUND: {  /* no excluded regions yet */
 66867        char buf[32];
 66868        int len=0;
 66869        /* store the range in a new list */
 66870        len += sqlite4PutVarint64( (unsigned char *) &buf[len], start);
 66871        len += sqlite4PutVarint64( (unsigned char *) &buf[len], end);
 66872        /* save the list */
 66873        rc = mdb_str_put(lmdb->txn, lmdb->main_db, keyname, buf, len);
 66874        break;
 66875      }
 66876    }
 66877  
 66878    if( rc ) rc = lmdb_error(rc);
 66879  
 66880  loc_exit:
 66881  
 66882    if( ranges ) sqlite3_str_destroy(ranges);
 66883    return rc;
 66884  
 66885  loc_invalid_value:
 66886  
 66887    BRANCHTRACE("join_commit_range invalid value!");
 66888    rc = lmdb_error(MDB_BAD_VALSIZE);
 66889    goto loc_exit;
 66890  
 66891  }
 66892  
 66893  /*
 66894  ** Discard commits:
 66895  ** This function deletes previous ocurrences of pages within a commit range. Only the last
 66896  ** ocurrence is kept.
 66897  */
 66898  SQLITE_PRIVATE int branch_discard_commits(lmdb *lmdb, char *branch_name, u64 from_commit, u64 to_commit){
 66899    branch_info *branch;
 66900    int branch_id=0, i, rc;
 66901    u64 commit;
 66902    Pgno pgno, max_pgno;
 66903    MDB_cursor *cursor=0;
 66904    Bitvec *pages=0;
 66905  
 66906    BRANCHTRACE("branch_discard_commits branch=%s from_commit=%llu to_commit=%llu", branch_name, from_commit, to_commit);
 66907  
 66908    if( branch_name ){
 66909      /* search for the branch with the given name */
 66910      branch_id = sqlite3BranchFind(lmdb, branch_name);
 66911      /* not found? */
 66912      if( branch_id <= 0 ) return SQLITE_NOTFOUND;
 66913      branch = &lmdb->branches[branch_id];
 66914    } else {
 66915      /* branch not informed */
 66916      return SQLITE_MISUSE;
 66917    }
 66918  
 66919    /* check for valid arguments */
 66920    if( from_commit==0 || to_commit==0 ) return SQLITE_MISUSE;
 66921    if( to_commit < from_commit ) return SQLITE_MISUSE;
 66922    if( to_commit > branch->last_commit ) return SQLITE_NOTFOUND;
 66923    if( from_commit <= branch->source_commit ) return SQLITE_NOTFOUND;
 66924  
 66925    /* it is not possible to discard the current commit */
 66926    if( branch==lmdb->current_branch && branch->max_commit > 0 ){
 66927      commit = branch->max_commit;
 66928      if( commit>=from_commit && commit<=to_commit ) return SQLITE_MISUSE;
 66929    }
 66930  
 66931    /* are there child branches starting withing the commit range? */
 66932    for( i=1; i <= lmdb->num_branches; i++ ){
 66933      if( lmdb->branches[i].source_branch == branch_id ){
 66934        commit = lmdb->branches[i].source_commit;
 66935        if( commit>=from_commit && commit<=to_commit ) return SQLITE_MISUSE;
 66936      }
 66937    }
 66938  
 66939    /* merge this range with existing ones */
 66940    rc = join_commit_range(lmdb, branch_id, &from_commit, &to_commit);
 66941    if( rc ) return rc;
 66942  
 66943    BRANCHTRACE("branch_discard_commits final range: from_commit=%llu to_commit=%llu", from_commit, to_commit);
 66944  
 66945    /* if the pages db is not open, open it now */
 66946    if( branch->pages_db == 0 ){
 66947      rc = sqlite3BranchOpen(lmdb, branch->id, 0);
 66948      if( rc==SQLITE_READONLY ) rc = SQLITE_NOTFOUND;
 66949      if( rc ) return rc;
 66950    }
 66951  
 66952    /* make the last commit point to an accessible (not discarded) commit */
 66953    if( to_commit < branch->last_commit ) to_commit++;
 66954  
 66955    /* check how many pages in this commit */
 66956    rc = sqlite3BranchGetCommitMaxPage(lmdb, branch, to_commit, &max_pgno);
 66957    if( rc ) return rc;
 66958  
 66959    /* allocate a bitvector to store the pages that are present in the commit range */
 66960    pages = sqlite3BitvecCreate(max_pgno);
 66961    if( !pages ) return SQLITE_NOMEM;
 66962  
 66963    rc = mdb_cursor_open(lmdb->txn, branch->pages_db, &cursor);
 66964    if( rc!=MDB_SUCCESS ) goto loc_lmdb_failed;
 66965  
 66966    /* iterate through all the pages, starting from the last one */
 66967    for( pgno=max_pgno; pgno>0; pgno-- ){
 66968      char buf[PAGE_DB_KEY_MAX_SIZE];
 66969      MDB_val key, value;
 66970  
 66971      /* are there instances of this page in this commit range? */
 66972  
 66973      commit = to_commit;  /* also used in the log message bellow */
 66974      branch_set_page_key(&key, buf, pgno, commit);
 66975  
 66976      /* search for the page from the last commit */
 66977      switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_SET_KEY)) ){
 66978        case MDB_SUCCESS:  goto loc_found;
 66979        case MDB_NOTFOUND: goto loc_previous;
 66980        default:           goto loc_lmdb_failed;
 66981      }
 66982  
 66983  loc_found:
 66984  
 66985      /* is this page already in this range? */
 66986      if( sqlite3BitvecTest(pages,pgno) ){
 66987        /* delete the page */
 66988        BRANCHTRACE("branch_discard_commits - deleting page %u from commit %llu", pgno, commit);
 66989        if( (rc=mdb_cursor_del(cursor,0)) != MDB_SUCCESS ) goto loc_lmdb_failed;
 66990      } else {
 66991        /* add this page number to the list */
 66992        BRANCHTRACE("branch_discard_commits - keeping page %u from commit %llu", pgno, commit);
 66993        rc = sqlite3BitvecSet(pages, pgno);
 66994        if( rc ) goto loc_exit;
 66995      }
 66996  
 66997  loc_previous:
 66998  
 66999      /* check the previous key */
 67000      switch( (rc=mdb_cursor_get(cursor, &key, &value, MDB_PREV)) ){
 67001      case MDB_SUCCESS:
 67002        /* read the pgno */
 67003        rc = pgno_from_key(&key, &pgno);
 67004        if( rc!=SQLITE_OK ) goto loc_exit;
 67005        /* read the commit */
 67006        rc = commit_from_key(&key, &commit);
 67007        if( rc!=SQLITE_OK ) goto loc_exit;
 67008        /* is it within the commit range? */
 67009        if( commit>=from_commit && commit<=to_commit ) goto loc_found;
 67010        /* no. go to the previous page */
 67011        break;
 67012      case MDB_NOTFOUND:
 67013        /* no more rows in table */
 67014        goto loc_done;
 67015      default:
 67016        goto loc_lmdb_failed;
 67017      }
 67018  
 67019    }
 67020  
 67021  loc_done:
 67022  
 67023    /* save this commit range (excluding the last commit) as not accessible */
 67024    rc = add_commit_range(lmdb, branch_id, from_commit, to_commit-1);
 67025  
 67026  loc_exit:
 67027  
 67028    if( pages ) sqlite3BitvecDestroy(pages);
 67029    if( cursor ) mdb_cursor_close(cursor);
 67030    return rc;
 67031  
 67032  loc_lmdb_failed:
 67033  
 67034    rc = lmdb_error(rc);
 67035    goto loc_exit;
 67036  
 67037  }
 67038  
 67039  /*
 67040  ** PRAGMA discard_commits {range}
 67041  */
 67042  SQLITE_PRIVATE int pragma_discard_commits(sqlite3 *db, int iDb, char *range){
 67043    Btree *pBtree = getBtreeFromiDb(db, iDb);
 67044    Pager *pPager = getPagerFromBtree(pBtree);
 67045    lmdb *lmdb;
 67046    char *branch_name=0;
 67047    int already_in_txn=0, rc;
 67048    u64 commit=0, to_commit=0;
 67049  
 67050    //BRANCHTRACE("pragma_discard_commits range=%s", range);
 67051  
 67052    /* process the argument */
 67053    if( range ){
 67054      char *zcommit = stripchr(range, '.');
 67055      branch_name = range;
 67056      if( zcommit ){
 67057        char *zto_commit = stripchr(zcommit, '-');
 67058        commit = atou64(zcommit);
 67059        if( zto_commit ){
 67060          to_commit = atou64(zto_commit);
 67061        }
 67062      }
 67063    } else return SQLITE_MISUSE;
 67064  
 67065    if( to_commit==0 ) to_commit = commit;
 67066  
 67067    if( !pPager || !pPager->lmdb ) return SQLITE_ERROR;
 67068    lmdb = pPager->lmdb;
 67069  
 67070    /* this command cannot be run inside of a transaction */
 67071    if( lmdb->inReadTxn ) return SQLITE_MISUSE;
 67072  
 67073    /* is it already inside of a write transaction? */
 67074    if( lmdb->inWriteTxn ){
 67075      already_in_txn = 1;
 67076    } else {
 67077      rc = sqlite3BranchBeginWriteTransaction(pPager->lmdb);
 67078      if( rc ) return rc;
 67079    }
 67080  
 67081    rc = branch_discard_commits(lmdb, branch_name, commit, to_commit);
 67082  
 67083    if( !already_in_txn ){
 67084      if( rc==SQLITE_OK ){
 67085        rc = sqlite3BranchCommitTransaction(lmdb, 0);
 67086      } else {
 67087        sqlite3BranchEndWriteTransaction(lmdb, 0);
 67088      }
 67089    }
 67090    return rc;
 67091  
 67092  }
 67093  
 67094  /************** End of branches.c ********************************************/
 67095  /************** Begin file btmutex.c *****************************************/
 67096  /*
 67097  ** 2007 August 27
 67098  **
 67099  ** The author disclaims copyright to this source code.  In place of
 67100  ** a legal notice, here is a blessing:
 67101  **
 67102  **    May you do good and not evil.
 67103  **    May you find forgiveness for yourself and forgive others.
 67104  **    May you share freely, never taking more than you give.
 67105  **
 67106  *************************************************************************
 67107  **
 67108  ** This file contains code used to implement mutexes on Btree objects.
 67109  ** This code really belongs in btree.c.  But btree.c is getting too
 67110  ** big and we want to break it down some.  This packaged seemed like
 67111  ** a good breakout.
 67112  */
 67113  /************** Include btreeInt.h in the middle of btmutex.c ****************/
 67114  /************** Begin file btreeInt.h ****************************************/
 67115  /*
 67116  ** 2004 April 6
 67117  **
 67118  ** The author disclaims copyright to this source code.  In place of
 67119  ** a legal notice, here is a blessing:
 67120  **
 67121  **    May you do good and not evil.
 67122  **    May you find forgiveness for yourself and forgive others.
 67123  **    May you share freely, never taking more than you give.
 67124  **
 67125  *************************************************************************
 67126  ** This file implements an external (disk-based) database using BTrees.
 67127  ** For a detailed discussion of BTrees, refer to
 67128  **
 67129  **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
 67130  **     "Sorting And Searching", pages 473-480. Addison-Wesley
 67131  **     Publishing Company, Reading, Massachusetts.
 67132  **
 67133  ** The basic idea is that each page of the file contains N database
 67134  ** entries and N+1 pointers to subpages.
 67135  **
 67136  **   ----------------------------------------------------------------
 67137  **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
 67138  **   ----------------------------------------------------------------
 67139  **
 67140  ** All of the keys on the page that Ptr(0) points to have values less
 67141  ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
 67142  ** values greater than Key(0) and less than Key(1).  All of the keys
 67143  ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
 67144  ** so forth.
 67145  **
 67146  ** Finding a particular key requires reading O(log(M)) pages from the 
 67147  ** disk where M is the number of entries in the tree.
 67148  **
 67149  ** In this implementation, a single file can hold one or more separate 
 67150  ** BTrees.  Each BTree is identified by the index of its root page.  The
 67151  ** key and data for any entry are combined to form the "payload".  A
 67152  ** fixed amount of payload can be carried directly on the database
 67153  ** page.  If the payload is larger than the preset amount then surplus
 67154  ** bytes are stored on overflow pages.  The payload for an entry
 67155  ** and the preceding pointer are combined to form a "Cell".  Each 
 67156  ** page has a small header which contains the Ptr(N) pointer and other
 67157  ** information such as the size of key and data.
 67158  **
 67159  ** FORMAT DETAILS
 67160  **
 67161  ** The file is divided into pages.  The first page is called page 1,
 67162  ** the second is page 2, and so forth.  A page number of zero indicates
 67163  ** "no such page".  The page size can be any power of 2 between 512 and 65536.
 67164  ** Each page can be either a btree page, a freelist page, an overflow
 67165  ** page, or a pointer-map page.
 67166  **
 67167  ** The first page is always a btree page.  The first 100 bytes of the first
 67168  ** page contain a special header (the "file header") that describes the file.
 67169  ** The format of the file header is as follows:
 67170  **
 67171  **   OFFSET   SIZE    DESCRIPTION
 67172  **      0      16     Header string: "SQLite format 3\000"
 67173  **     16       2     Page size in bytes.  (1 means 65536)
 67174  **     18       1     File format write version
 67175  **     19       1     File format read version
 67176  **     20       1     Bytes of unused space at the end of each page
 67177  **     21       1     Max embedded payload fraction (must be 64)
 67178  **     22       1     Min embedded payload fraction (must be 32)
 67179  **     23       1     Min leaf payload fraction (must be 32)
 67180  **     24       4     File change counter
 67181  **     28       4     Reserved for future use
 67182  **     32       4     First freelist page
 67183  **     36       4     Number of freelist pages in the file
 67184  **     40      60     15 4-byte meta values passed to higher layers
 67185  **
 67186  **     40       4     Schema cookie
 67187  **     44       4     File format of schema layer
 67188  **     48       4     Size of page cache
 67189  **     52       4     Largest root-page (auto/incr_vacuum)
 67190  **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
 67191  **     60       4     User version
 67192  **     64       4     Incremental vacuum mode
 67193  **     68       4     Application-ID
 67194  **     72      20     unused
 67195  **     92       4     The version-valid-for number
 67196  **     96       4     SQLITE_VERSION_NUMBER
 67197  **
 67198  ** All of the integer values are big-endian (most significant byte first).
 67199  **
 67200  ** The file change counter is incremented when the database is changed
 67201  ** This counter allows other processes to know when the file has changed
 67202  ** and thus when they need to flush their cache.
 67203  **
 67204  ** The max embedded payload fraction is the amount of the total usable
 67205  ** space in a page that can be consumed by a single cell for standard
 67206  ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
 67207  ** is to limit the maximum cell size so that at least 4 cells will fit
 67208  ** on one page.  Thus the default max embedded payload fraction is 64.
 67209  **
 67210  ** If the payload for a cell is larger than the max payload, then extra
 67211  ** payload is spilled to overflow pages.  Once an overflow page is allocated,
 67212  ** as many bytes as possible are moved into the overflow pages without letting
 67213  ** the cell size drop below the min embedded payload fraction.
 67214  **
 67215  ** The min leaf payload fraction is like the min embedded payload fraction
 67216  ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
 67217  ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
 67218  ** not specified in the header.
 67219  **
 67220  ** Each btree pages is divided into three sections:  The header, the
 67221  ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
 67222  ** file header that occurs before the page header.
 67223  **
 67224  **      |----------------|
 67225  **      | file header    |   100 bytes.  Page 1 only.
 67226  **      |----------------|
 67227  **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
 67228  **      |----------------|
 67229  **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
 67230  **      | array          |   |  Grows downward
 67231  **      |                |   v
 67232  **      |----------------|
 67233  **      | unallocated    |
 67234  **      | space          |
 67235  **      |----------------|   ^  Grows upwards
 67236  **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
 67237  **      | area           |   |  and free space fragments.
 67238  **      |----------------|
 67239  **
 67240  ** The page headers looks like this:
 67241  **
 67242  **   OFFSET   SIZE     DESCRIPTION
 67243  **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
 67244  **      1       2      byte offset to the first freeblock
 67245  **      3       2      number of cells on this page
 67246  **      5       2      first byte of the cell content area
 67247  **      7       1      number of fragmented free bytes
 67248  **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
 67249  **
 67250  ** The flags define the format of this btree page.  The leaf flag means that
 67251  ** this page has no children.  The zerodata flag means that this page carries
 67252  ** only keys and no data.  The intkey flag means that the key is an integer
 67253  ** which is stored in the key size entry of the cell header rather than in
 67254  ** the payload area.
 67255  **
 67256  ** The cell pointer array begins on the first byte after the page header.
 67257  ** The cell pointer array contains zero or more 2-byte numbers which are
 67258  ** offsets from the beginning of the page to the cell content in the cell
 67259  ** content area.  The cell pointers occur in sorted order.  The system strives
 67260  ** to keep free space after the last cell pointer so that new cells can
 67261  ** be easily added without having to defragment the page.
 67262  **
 67263  ** Cell content is stored at the very end of the page and grows toward the
 67264  ** beginning of the page.
 67265  **
 67266  ** Unused space within the cell content area is collected into a linked list of
 67267  ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
 67268  ** to the first freeblock is given in the header.  Freeblocks occur in
 67269  ** increasing order.  Because a freeblock must be at least 4 bytes in size,
 67270  ** any group of 3 or fewer unused bytes in the cell content area cannot
 67271  ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
 67272  ** a fragment.  The total number of bytes in all fragments is recorded.
 67273  ** in the page header at offset 7.
 67274  **
 67275  **    SIZE    DESCRIPTION
 67276  **      2     Byte offset of the next freeblock
 67277  **      2     Bytes in this freeblock
 67278  **
 67279  ** Cells are of variable length.  Cells are stored in the cell content area at
 67280  ** the end of the page.  Pointers to the cells are in the cell pointer array
 67281  ** that immediately follows the page header.  Cells is not necessarily
 67282  ** contiguous or in order, but cell pointers are contiguous and in order.
 67283  **
 67284  ** Cell content makes use of variable length integers.  A variable
 67285  ** length integer is 1 to 9 bytes where the lower 7 bits of each 
 67286  ** byte are used.  The integer consists of all bytes that have bit 8 set and
 67287  ** the first byte with bit 8 clear.  The most significant byte of the integer
 67288  ** appears first.  A variable-length integer may not be more than 9 bytes long.
 67289  ** As a special case, all 8 bytes of the 9th byte are used as data.  This
 67290  ** allows a 64-bit integer to be encoded in 9 bytes.
 67291  **
 67292  **    0x00                      becomes  0x00000000
 67293  **    0x7f                      becomes  0x0000007f
 67294  **    0x81 0x00                 becomes  0x00000080
 67295  **    0x82 0x00                 becomes  0x00000100
 67296  **    0x80 0x7f                 becomes  0x0000007f
 67297  **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
 67298  **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
 67299  **
 67300  ** Variable length integers are used for rowids and to hold the number of
 67301  ** bytes of key and data in a btree cell.
 67302  **
 67303  ** The content of a cell looks like this:
 67304  **
 67305  **    SIZE    DESCRIPTION
 67306  **      4     Page number of the left child. Omitted if leaf flag is set.
 67307  **     var    Number of bytes of data. Omitted if the zerodata flag is set.
 67308  **     var    Number of bytes of key. Or the key itself if intkey flag is set.
 67309  **      *     Payload
 67310  **      4     First page of the overflow chain.  Omitted if no overflow
 67311  **
 67312  ** Overflow pages form a linked list.  Each page except the last is completely
 67313  ** filled with data (pagesize - 4 bytes).  The last page can have as little
 67314  ** as 1 byte of data.
 67315  **
 67316  **    SIZE    DESCRIPTION
 67317  **      4     Page number of next overflow page
 67318  **      *     Data
 67319  **
 67320  ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
 67321  ** file header points to the first in a linked list of trunk page.  Each trunk
 67322  ** page points to multiple leaf pages.  The content of a leaf page is
 67323  ** unspecified.  A trunk page looks like this:
 67324  **
 67325  **    SIZE    DESCRIPTION
 67326  **      4     Page number of next trunk page
 67327  **      4     Number of leaf pointers on this page
 67328  **      *     zero or more pages numbers of leaves
 67329  */
 67330  /* #include "sqliteInt.h" */
 67331  
 67332  
 67333  /* The following value is the maximum cell size assuming a maximum page
 67334  ** size give above.
 67335  */
 67336  #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
 67337  
 67338  /* The maximum number of cells on a single page of the database.  This
 67339  ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
 67340  ** plus 2 bytes for the index to the cell in the page header).  Such
 67341  ** small cells will be rare, but they are possible.
 67342  */
 67343  #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
 67344  
 67345  /* Forward declarations */
 67346  typedef struct MemPage MemPage;
 67347  typedef struct BtLock BtLock;
 67348  typedef struct CellInfo CellInfo;
 67349  
 67350  /*
 67351  ** This is a magic string that appears at the beginning of every
 67352  ** SQLite database in order to identify the file as a real database.
 67353  **
 67354  ** You can change this value at compile-time by specifying a
 67355  ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
 67356  ** header must be exactly 16 bytes including the zero-terminator so
 67357  ** the string itself should be 15 characters long.  If you change
 67358  ** the header, then your custom library will not be able to read 
 67359  ** databases generated by the standard tools and the standard tools
 67360  ** will not be able to read databases created by your custom library.
 67361  */
 67362  #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
 67363  #  define SQLITE_FILE_HEADER "SQLite format 3"
 67364  #endif
 67365  
 67366  /*
 67367  ** Page type flags.  An ORed combination of these flags appear as the
 67368  ** first byte of on-disk image of every BTree page.
 67369  */
 67370  #define PTF_INTKEY    0x01
 67371  #define PTF_ZERODATA  0x02
 67372  #define PTF_LEAFDATA  0x04
 67373  #define PTF_LEAF      0x08
 67374  
 67375  /*
 67376  ** An instance of this object stores information about each a single database
 67377  ** page that has been loaded into memory.  The information in this object
 67378  ** is derived from the raw on-disk page content.
 67379  **
 67380  ** As each database page is loaded into memory, the pager allocats an
 67381  ** instance of this object and zeros the first 8 bytes.  (This is the
 67382  ** "extra" information associated with each page of the pager.)
 67383  **
 67384  ** Access to all fields of this structure is controlled by the mutex
 67385  ** stored in MemPage.pBt->mutex.
 67386  */
 67387  struct MemPage {
 67388    u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
 67389    u8 bBusy;            /* Prevent endless loops on corrupt database files */
 67390    u8 intKey;           /* True if table b-trees.  False for index b-trees */
 67391    u8 intKeyLeaf;       /* True if the leaf of an intKey table */
 67392    Pgno pgno;           /* Page number for this page */
 67393    /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
 67394    ** is allocated. All fields that follow must be initialized before use */
 67395    u8 leaf;             /* True if a leaf page */
 67396    u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
 67397    u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
 67398    u8 max1bytePayload;  /* min(maxLocal,127) */
 67399    u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
 67400    u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
 67401    u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
 67402    u16 cellOffset;      /* Index in aData of first cell pointer */
 67403    u16 nFree;           /* Number of free bytes on the page */
 67404    u16 nCell;           /* Number of cells on this page, local and ovfl */
 67405    u16 maskPage;        /* Mask for page offset */
 67406    u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
 67407                         ** non-overflow cell */
 67408    u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
 67409    BtShared *pBt;       /* Pointer to BtShared that this page is part of */
 67410    u8 *aData;           /* Pointer to disk image of the page data */
 67411    u8 *aDataEnd;        /* One byte past the end of usable data */
 67412    u8 *aCellIdx;        /* The cell index area */
 67413    u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
 67414    DbPage *pDbPage;     /* Pager page handle */
 67415    u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
 67416    void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
 67417  };
 67418  
 67419  /*
 67420  ** A linked list of the following structures is stored at BtShared.pLock.
 67421  ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
 67422  ** is opened on the table with root page BtShared.iTable. Locks are removed
 67423  ** from this list when a transaction is committed or rolled back, or when
 67424  ** a btree handle is closed.
 67425  */
 67426  struct BtLock {
 67427    Btree *pBtree;        /* Btree handle holding this lock */
 67428    Pgno iTable;          /* Root page of table */
 67429    u8 eLock;             /* READ_LOCK or WRITE_LOCK */
 67430    BtLock *pNext;        /* Next in BtShared.pLock list */
 67431  };
 67432  
 67433  /* Candidate values for BtLock.eLock */
 67434  #define READ_LOCK     1
 67435  #define WRITE_LOCK    2
 67436  
 67437  /* A Btree handle
 67438  **
 67439  ** A database connection contains a pointer to an instance of
 67440  ** this object for every database file that it has open.  This structure
 67441  ** is opaque to the database connection.  The database connection cannot
 67442  ** see the internals of this structure and only deals with pointers to
 67443  ** this structure.
 67444  **
 67445  ** For some database files, the same underlying database cache might be 
 67446  ** shared between multiple connections.  In that case, each connection
 67447  ** has it own instance of this object.  But each instance of this object
 67448  ** points to the same BtShared object.  The database cache and the
 67449  ** schema associated with the database file are all contained within
 67450  ** the BtShared object.
 67451  **
 67452  ** All fields in this structure are accessed under sqlite3.mutex.
 67453  ** The pBt pointer itself may not be changed while there exists cursors 
 67454  ** in the referenced BtShared that point back to this Btree since those
 67455  ** cursors have to go through this Btree to find their BtShared and
 67456  ** they often do so without holding sqlite3.mutex.
 67457  */
 67458  struct Btree {
 67459    sqlite3 *db;       /* The database connection holding this btree */
 67460    BtShared *pBt;     /* Sharable content of this btree */
 67461    u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
 67462    u8 sharable;       /* True if we can share pBt with another db */
 67463    u8 locked;         /* True if db currently has pBt locked */
 67464    u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
 67465    int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
 67466    int nBackup;       /* Number of backup operations reading this btree */
 67467    u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
 67468    Btree *pNext;      /* List of other sharable Btrees from the same db */
 67469    Btree *pPrev;      /* Back pointer of the same list */
 67470  #ifndef SQLITE_OMIT_SHARED_CACHE
 67471    BtLock lock;       /* Object used to lock page 1 */
 67472  #endif
 67473  };
 67474  
 67475  /*
 67476  ** Btree.inTrans may take one of the following values.
 67477  **
 67478  ** If the shared-data extension is enabled, there may be multiple users
 67479  ** of the Btree structure. At most one of these may open a write transaction,
 67480  ** but any number may have active read transactions.
 67481  */
 67482  #define TRANS_NONE  0
 67483  #define TRANS_READ  1
 67484  #define TRANS_WRITE 2
 67485  
 67486  /*
 67487  ** An instance of this object represents a single database file.
 67488  ** 
 67489  ** A single database file can be in use at the same time by two
 67490  ** or more database connections.  When two or more connections are
 67491  ** sharing the same database file, each connection has it own
 67492  ** private Btree object for the file and each of those Btrees points
 67493  ** to this one BtShared object.  BtShared.nRef is the number of
 67494  ** connections currently sharing this database file.
 67495  **
 67496  ** Fields in this structure are accessed under the BtShared.mutex
 67497  ** mutex, except for nRef and pNext which are accessed under the
 67498  ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
 67499  ** may not be modified once it is initially set as long as nRef>0.
 67500  ** The pSchema field may be set once under BtShared.mutex and
 67501  ** thereafter is unchanged as long as nRef>0.
 67502  **
 67503  ** isPending:
 67504  **
 67505  **   If a BtShared client fails to obtain a write-lock on a database
 67506  **   table (because there exists one or more read-locks on the table),
 67507  **   the shared-cache enters 'pending-lock' state and isPending is
 67508  **   set to true.
 67509  **
 67510  **   The shared-cache leaves the 'pending lock' state when either of
 67511  **   the following occur:
 67512  **
 67513  **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
 67514  **     2) The number of locks held by other connections drops to zero.
 67515  **
 67516  **   while in the 'pending-lock' state, no connection may start a new
 67517  **   transaction.
 67518  **
 67519  **   This feature is included to help prevent writer-starvation.
 67520  */
 67521  struct BtShared {
 67522    Pager *pPager;        /* The page cache */
 67523    sqlite3 *db;          /* Database connection currently using this Btree */
 67524    BtCursor *pCursor;    /* A list of all open cursors */
 67525    MemPage *pPage1;      /* First page of the database */
 67526    u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
 67527  #ifndef SQLITE_OMIT_AUTOVACUUM
 67528    u8 autoVacuum;        /* True if auto-vacuum is enabled */
 67529    u8 incrVacuum;        /* True if incr-vacuum is enabled */
 67530    u8 bDoTruncate;       /* True to truncate db on commit */
 67531  #endif
 67532    u8 inTransaction;     /* Transaction state */
 67533    u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
 67534  #ifdef SQLITE_HAS_CODEC
 67535    u8 optimalReserve;    /* Desired amount of reserved space per page */
 67536  #endif
 67537    u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
 67538    u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
 67539    u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
 67540    u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
 67541    u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
 67542    u32 pageSize;         /* Total number of bytes on a page */
 67543    u32 usableSize;       /* Number of usable bytes on each page */
 67544    int nTransaction;     /* Number of open transactions (read + write) */
 67545    u32 nPage;            /* Number of pages in the database */
 67546    void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
 67547    void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
 67548    sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
 67549    Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
 67550  #ifndef SQLITE_OMIT_SHARED_CACHE
 67551    int nRef;             /* Number of references to this structure */
 67552    BtShared *pNext;      /* Next on a list of sharable BtShared structs */
 67553    BtLock *pLock;        /* List of locks held on this shared-btree struct */
 67554    Btree *pWriter;       /* Btree with currently open write transaction */
 67555  #endif
 67556    u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
 67557  };
 67558  
 67559  /*
 67560  ** Allowed values for BtShared.btsFlags
 67561  */
 67562  #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
 67563  #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
 67564  #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
 67565  #define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */
 67566  #define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */
 67567  #define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */
 67568  #define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */
 67569  #define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */
 67570  #define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */
 67571  
 67572  /*
 67573  ** An instance of the following structure is used to hold information
 67574  ** about a cell.  The parseCellPtr() function fills in this structure
 67575  ** based on information extract from the raw disk page.
 67576  */
 67577  struct CellInfo {
 67578    i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
 67579    u8 *pPayload;  /* Pointer to the start of payload */
 67580    u32 nPayload;  /* Bytes of payload */
 67581    u16 nLocal;    /* Amount of payload held locally, not on overflow */
 67582    u16 nSize;     /* Size of the cell content on the main b-tree page */
 67583  };
 67584  
 67585  /*
 67586  ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
 67587  ** this will be declared corrupt. This value is calculated based on a
 67588  ** maximum database size of 2^31 pages a minimum fanout of 2 for a
 67589  ** root-node and 3 for all other internal nodes.
 67590  **
 67591  ** If a tree that appears to be taller than this is encountered, it is
 67592  ** assumed that the database is corrupt.
 67593  */
 67594  #define BTCURSOR_MAX_DEPTH 20
 67595  
 67596  /*
 67597  ** A cursor is a pointer to a particular entry within a particular
 67598  ** b-tree within a database file.
 67599  **
 67600  ** The entry is identified by its MemPage and the index in
 67601  ** MemPage.aCell[] of the entry.
 67602  **
 67603  ** A single database file can be shared by two more database connections,
 67604  ** but cursors cannot be shared.  Each cursor is associated with a
 67605  ** particular database connection identified BtCursor.pBtree.db.
 67606  **
 67607  ** Fields in this structure are accessed under the BtShared.mutex
 67608  ** found at self->pBt->mutex. 
 67609  **
 67610  ** skipNext meaning:
 67611  ** The meaning of skipNext depends on the value of eState:
 67612  **
 67613  **   eState            Meaning of skipNext
 67614  **   VALID             skipNext is meaningless and is ignored
 67615  **   INVALID           skipNext is meaningless and is ignored
 67616  **   SKIPNEXT          sqlite3BtreeNext() is a no-op if skipNext>0 and
 67617  **                     sqlite3BtreePrevious() is no-op if skipNext<0.
 67618  **   REQUIRESEEK       restoreCursorPosition() restores the cursor to
 67619  **                     eState=SKIPNEXT if skipNext!=0
 67620  **   FAULT             skipNext holds the cursor fault error code.
 67621  */
 67622  struct BtCursor {
 67623    u8 eState;                /* One of the CURSOR_XXX constants (see below) */
 67624    u8 curFlags;              /* zero or more BTCF_* flags defined below */
 67625    u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
 67626    u8 hints;                 /* As configured by CursorSetHints() */
 67627    int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
 67628                     ** Error code if eState==CURSOR_FAULT */
 67629    Btree *pBtree;            /* The Btree to which this cursor belongs */
 67630    Pgno *aOverflow;          /* Cache of overflow page locations */
 67631    void *pKey;               /* Saved key that was cursor last known position */
 67632    /* All fields above are zeroed when the cursor is allocated.  See
 67633    ** sqlite3BtreeCursorZero().  Fields that follow must be manually
 67634    ** initialized. */
 67635  #define BTCURSOR_FIRST_UNINIT pBt   /* Name of first uninitialized field */
 67636    BtShared *pBt;            /* The BtShared this cursor points to */
 67637    BtCursor *pNext;          /* Forms a linked list of all cursors */
 67638    CellInfo info;            /* A parse of the cell we are pointing at */
 67639    i64 nKey;                 /* Size of pKey, or last integer key */
 67640    Pgno pgnoRoot;            /* The root page of this tree */
 67641    i8 iPage;                 /* Index of current page in apPage */
 67642    u8 curIntKey;             /* Value of apPage[0]->intKey */
 67643    u16 ix;                   /* Current index for apPage[iPage] */
 67644    u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */
 67645    struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */
 67646    MemPage *pPage;                        /* Current page */
 67647    MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
 67648  };
 67649  
 67650  /*
 67651  ** Legal values for BtCursor.curFlags
 67652  */
 67653  #define BTCF_WriteFlag    0x01   /* True if a write cursor */
 67654  #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
 67655  #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
 67656  #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
 67657  #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
 67658  #define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
 67659  
 67660  /*
 67661  ** Potential values for BtCursor.eState.
 67662  **
 67663  ** CURSOR_INVALID:
 67664  **   Cursor does not point to a valid entry. This can happen (for example) 
 67665  **   because the table is empty or because BtreeCursorFirst() has not been
 67666  **   called.
 67667  **
 67668  ** CURSOR_VALID:
 67669  **   Cursor points to a valid entry. getPayload() etc. may be called.
 67670  **
 67671  ** CURSOR_SKIPNEXT:
 67672  **   Cursor is valid except that the Cursor.skipNext field is non-zero
 67673  **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
 67674  **   operation should be a no-op.
 67675  **
 67676  ** CURSOR_REQUIRESEEK:
 67677  **   The table that this cursor was opened on still exists, but has been 
 67678  **   modified since the cursor was last used. The cursor position is saved
 67679  **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
 67680  **   this state, restoreCursorPosition() can be called to attempt to
 67681  **   seek the cursor to the saved position.
 67682  **
 67683  ** CURSOR_FAULT:
 67684  **   An unrecoverable error (an I/O error or a malloc failure) has occurred
 67685  **   on a different connection that shares the BtShared cache with this
 67686  **   cursor.  The error has left the cache in an inconsistent state.
 67687  **   Do nothing else with this cursor.  Any attempt to use the cursor
 67688  **   should return the error code stored in BtCursor.skipNext
 67689  */
 67690  #define CURSOR_VALID             0
 67691  #define CURSOR_INVALID           1
 67692  #define CURSOR_SKIPNEXT          2
 67693  #define CURSOR_REQUIRESEEK       3
 67694  #define CURSOR_FAULT             4
 67695  
 67696  /* 
 67697  ** The database page the PENDING_BYTE occupies. This page is never used.
 67698  */
 67699  # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
 67700  
 67701  /*
 67702  ** These macros define the location of the pointer-map entry for a 
 67703  ** database page. The first argument to each is the number of usable
 67704  ** bytes on each page of the database (often 1024). The second is the
 67705  ** page number to look up in the pointer map.
 67706  **
 67707  ** PTRMAP_PAGENO returns the database page number of the pointer-map
 67708  ** page that stores the required pointer. PTRMAP_PTROFFSET returns
 67709  ** the offset of the requested map entry.
 67710  **
 67711  ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
 67712  ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
 67713  ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
 67714  ** this test.
 67715  */
 67716  #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
 67717  #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
 67718  #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
 67719  
 67720  /*
 67721  ** The pointer map is a lookup table that identifies the parent page for
 67722  ** each child page in the database file.  The parent page is the page that
 67723  ** contains a pointer to the child.  Every page in the database contains
 67724  ** 0 or 1 parent pages.  (In this context 'database page' refers
 67725  ** to any page that is not part of the pointer map itself.)  Each pointer map
 67726  ** entry consists of a single byte 'type' and a 4 byte parent page number.
 67727  ** The PTRMAP_XXX identifiers below are the valid types.
 67728  **
 67729  ** The purpose of the pointer map is to facility moving pages from one
 67730  ** position in the file to another as part of autovacuum.  When a page
 67731  ** is moved, the pointer in its parent must be updated to point to the
 67732  ** new location.  The pointer map is used to locate the parent page quickly.
 67733  **
 67734  ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
 67735  **                  used in this case.
 67736  **
 67737  ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
 67738  **                  is not used in this case.
 67739  **
 67740  ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
 67741  **                   overflow pages. The page number identifies the page that
 67742  **                   contains the cell with a pointer to this overflow page.
 67743  **
 67744  ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
 67745  **                   overflow pages. The page-number identifies the previous
 67746  **                   page in the overflow page list.
 67747  **
 67748  ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
 67749  **               identifies the parent page in the btree.
 67750  */
 67751  #define PTRMAP_ROOTPAGE 1
 67752  #define PTRMAP_FREEPAGE 2
 67753  #define PTRMAP_OVERFLOW1 3
 67754  #define PTRMAP_OVERFLOW2 4
 67755  #define PTRMAP_BTREE 5
 67756  
 67757  /* A bunch of assert() statements to check the transaction state variables
 67758  ** of handle p (type Btree*) are internally consistent.
 67759  */
 67760  #define btreeIntegrity(p) \
 67761    assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
 67762    assert( p->pBt->inTransaction>=p->inTrans ); 
 67763  
 67764  
 67765  /*
 67766  ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
 67767  ** if the database supports auto-vacuum or not. Because it is used
 67768  ** within an expression that is an argument to another macro 
 67769  ** (sqliteMallocRaw), it is not possible to use conditional compilation.
 67770  ** So, this macro is defined instead.
 67771  */
 67772  #ifndef SQLITE_OMIT_AUTOVACUUM
 67773  #define ISAUTOVACUUM (pBt->autoVacuum)
 67774  #else
 67775  #define ISAUTOVACUUM 0
 67776  #endif
 67777  
 67778  
 67779  /*
 67780  ** This structure is passed around through all the sanity checking routines
 67781  ** in order to keep track of some global state information.
 67782  **
 67783  ** The aRef[] array is allocated so that there is 1 bit for each page in
 67784  ** the database. As the integrity-check proceeds, for each page used in
 67785  ** the database the corresponding bit is set. This allows integrity-check to 
 67786  ** detect pages that are used twice and orphaned pages (both of which 
 67787  ** indicate corruption).
 67788  */
 67789  typedef struct IntegrityCk IntegrityCk;
 67790  struct IntegrityCk {
 67791    BtShared *pBt;    /* The tree being checked out */
 67792    Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
 67793    u8 *aPgRef;       /* 1 bit per page in the db (see above) */
 67794    Pgno nPage;       /* Number of pages in the database */
 67795    int mxErr;        /* Stop accumulating errors when this reaches zero */
 67796    int nErr;         /* Number of messages written to zErrMsg so far */
 67797    int mallocFailed; /* A memory allocation error has occurred */
 67798    const char *zPfx; /* Error message prefix */
 67799    int v1, v2;       /* Values for up to two %d fields in zPfx */
 67800    StrAccum errMsg;  /* Accumulate the error message text here */
 67801    u32 *heap;        /* Min-heap used for analyzing cell coverage */
 67802  };
 67803  
 67804  /*
 67805  ** Routines to read or write a two- and four-byte big-endian integer values.
 67806  */
 67807  #define get2byte(x)   ((x)[0]<<8 | (x)[1])
 67808  #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
 67809  #define get4byte sqlite3Get4byte
 67810  #define put4byte sqlite3Put4byte
 67811  
 67812  /*
 67813  ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
 67814  ** two-byte aligned address.  get2bytea() is only used for accessing the
 67815  ** cell addresses in a btree header.
 67816  */
 67817  #if SQLITE_BYTEORDER==4321
 67818  # define get2byteAligned(x)  (*(u16*)(x))
 67819  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
 67820  # define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
 67821  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
 67822  # define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
 67823  #else
 67824  # define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
 67825  #endif
 67826  
 67827  /************** End of btreeInt.h ********************************************/
 67828  /************** Continuing where we left off in btmutex.c ********************/
 67829  #ifndef SQLITE_OMIT_SHARED_CACHE
 67830  #if SQLITE_THREADSAFE
 67831  
 67832  /*
 67833  ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
 67834  ** set BtShared.db to the database handle associated with p and the
 67835  ** p->locked boolean to true.
 67836  */
 67837  static void lockBtreeMutex(Btree *p){
 67838    assert( p->locked==0 );
 67839    assert( sqlite3_mutex_notheld(p->pBt->mutex) );
 67840    assert( sqlite3_mutex_held(p->db->mutex) );
 67841  
 67842    sqlite3_mutex_enter(p->pBt->mutex);
 67843    p->pBt->db = p->db;
 67844    p->locked = 1;
 67845  }
 67846  
 67847  /*
 67848  ** Release the BtShared mutex associated with B-Tree handle p and
 67849  ** clear the p->locked boolean.
 67850  */
 67851  static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
 67852    BtShared *pBt = p->pBt;
 67853    assert( p->locked==1 );
 67854    assert( sqlite3_mutex_held(pBt->mutex) );
 67855    assert( sqlite3_mutex_held(p->db->mutex) );
 67856    assert( p->db==pBt->db );
 67857  
 67858    sqlite3_mutex_leave(pBt->mutex);
 67859    p->locked = 0;
 67860  }
 67861  
 67862  /* Forward reference */
 67863  static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
 67864  
 67865  /*
 67866  ** Enter a mutex on the given BTree object.
 67867  **
 67868  ** If the object is not sharable, then no mutex is ever required
 67869  ** and this routine is a no-op.  The underlying mutex is non-recursive.
 67870  ** But we keep a reference count in Btree.wantToLock so the behavior
 67871  ** of this interface is recursive.
 67872  **
 67873  ** To avoid deadlocks, multiple Btrees are locked in the same order
 67874  ** by all database connections.  The p->pNext is a list of other
 67875  ** Btrees belonging to the same database connection as the p Btree
 67876  ** which need to be locked after p.  If we cannot get a lock on
 67877  ** p, then first unlock all of the others on p->pNext, then wait
 67878  ** for the lock to become available on p, then relock all of the
 67879  ** subsequent Btrees that desire a lock.
 67880  */
 67881  SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 67882    /* Some basic sanity checking on the Btree.  The list of Btrees
 67883    ** connected by pNext and pPrev should be in sorted order by
 67884    ** Btree.pBt value. All elements of the list should belong to
 67885    ** the same connection. Only shared Btrees are on the list. */
 67886    assert( p->pNext==0 || p->pNext->pBt>p->pBt );
 67887    assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
 67888    assert( p->pNext==0 || p->pNext->db==p->db );
 67889    assert( p->pPrev==0 || p->pPrev->db==p->db );
 67890    assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
 67891  
 67892    /* Check for locking consistency */
 67893    assert( !p->locked || p->wantToLock>0 );
 67894    assert( p->sharable || p->wantToLock==0 );
 67895  
 67896    /* We should already hold a lock on the database connection */
 67897    assert( sqlite3_mutex_held(p->db->mutex) );
 67898  
 67899    /* Unless the database is sharable and unlocked, then BtShared.db
 67900    ** should already be set correctly. */
 67901    assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
 67902  
 67903    if( !p->sharable ) return;
 67904    p->wantToLock++;
 67905    if( p->locked ) return;
 67906    btreeLockCarefully(p);
 67907  }
 67908  
 67909  /* This is a helper function for sqlite3BtreeLock(). By moving
 67910  ** complex, but seldom used logic, out of sqlite3BtreeLock() and
 67911  ** into this routine, we avoid unnecessary stack pointer changes
 67912  ** and thus help the sqlite3BtreeLock() routine to run much faster
 67913  ** in the common case.
 67914  */
 67915  static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
 67916    Btree *pLater;
 67917  
 67918    /* In most cases, we should be able to acquire the lock we
 67919    ** want without having to go through the ascending lock
 67920    ** procedure that follows.  Just be sure not to block.
 67921    */
 67922    if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
 67923      p->pBt->db = p->db;
 67924      p->locked = 1;
 67925      return;
 67926    }
 67927  
 67928    /* To avoid deadlock, first release all locks with a larger
 67929    ** BtShared address.  Then acquire our lock.  Then reacquire
 67930    ** the other BtShared locks that we used to hold in ascending
 67931    ** order.
 67932    */
 67933    for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 67934      assert( pLater->sharable );
 67935      assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
 67936      assert( !pLater->locked || pLater->wantToLock>0 );
 67937      if( pLater->locked ){
 67938        unlockBtreeMutex(pLater);
 67939      }
 67940    }
 67941    lockBtreeMutex(p);
 67942    for(pLater=p->pNext; pLater; pLater=pLater->pNext){
 67943      if( pLater->wantToLock ){
 67944        lockBtreeMutex(pLater);
 67945      }
 67946    }
 67947  }
 67948  
 67949  
 67950  /*
 67951  ** Exit the recursive mutex on a Btree.
 67952  */
 67953  SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
 67954    assert( sqlite3_mutex_held(p->db->mutex) );
 67955    if( p->sharable ){
 67956      assert( p->wantToLock>0 );
 67957      p->wantToLock--;
 67958      if( p->wantToLock==0 ){
 67959        unlockBtreeMutex(p);
 67960      }
 67961    }
 67962  }
 67963  
 67964  #ifndef NDEBUG
 67965  /*
 67966  ** Return true if the BtShared mutex is held on the btree, or if the
 67967  ** B-Tree is not marked as sharable.
 67968  **
 67969  ** This routine is used only from within assert() statements.
 67970  */
 67971  SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
 67972    assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
 67973    assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
 67974    assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
 67975    assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
 67976  
 67977    return (p->sharable==0 || p->locked);
 67978  }
 67979  #endif
 67980  
 67981  
 67982  /*
 67983  ** Enter the mutex on every Btree associated with a database
 67984  ** connection.  This is needed (for example) prior to parsing
 67985  ** a statement since we will be comparing table and column names
 67986  ** against all schemas and we do not want those schemas being
 67987  ** reset out from under us.
 67988  **
 67989  ** There is a corresponding leave-all procedures.
 67990  **
 67991  ** Enter the mutexes in accending order by BtShared pointer address
 67992  ** to avoid the possibility of deadlock when two threads with
 67993  ** two or more btrees in common both try to lock all their btrees
 67994  ** at the same instant.
 67995  */
 67996  static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
 67997    int i;
 67998    int skipOk = 1;
 67999    Btree *p;
 68000    assert( sqlite3_mutex_held(db->mutex) );
 68001    for(i=0; i<db->nDb; i++){
 68002      p = db->aDb[i].pBt;
 68003      if( p && p->sharable ){
 68004        sqlite3BtreeEnter(p);
 68005        skipOk = 0;
 68006      }
 68007    }
 68008    db->noSharedCache = skipOk;
 68009  }
 68010  SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 68011    if( db->noSharedCache==0 ) btreeEnterAll(db);
 68012  }
 68013  static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
 68014    int i;
 68015    Btree *p;
 68016    assert( sqlite3_mutex_held(db->mutex) );
 68017    for(i=0; i<db->nDb; i++){
 68018      p = db->aDb[i].pBt;
 68019      if( p ) sqlite3BtreeLeave(p);
 68020    }
 68021  }
 68022  SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
 68023    if( db->noSharedCache==0 ) btreeLeaveAll(db);
 68024  }
 68025  
 68026  #ifndef NDEBUG
 68027  /*
 68028  ** Return true if the current thread holds the database connection
 68029  ** mutex and all required BtShared mutexes.
 68030  **
 68031  ** This routine is used inside assert() statements only.
 68032  */
 68033  SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
 68034    int i;
 68035    if( !sqlite3_mutex_held(db->mutex) ){
 68036      return 0;
 68037    }
 68038    for(i=0; i<db->nDb; i++){
 68039      Btree *p;
 68040      p = db->aDb[i].pBt;
 68041      if( p && p->sharable &&
 68042           (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
 68043        return 0;
 68044      }
 68045    }
 68046    return 1;
 68047  }
 68048  #endif /* NDEBUG */
 68049  
 68050  #ifndef NDEBUG
 68051  /*
 68052  ** Return true if the correct mutexes are held for accessing the
 68053  ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
 68054  ** access are:
 68055  **
 68056  **   (1) The mutex on db
 68057  **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
 68058  **
 68059  ** If pSchema is not NULL, then iDb is computed from pSchema and
 68060  ** db using sqlite3SchemaToIndex().
 68061  */
 68062  SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
 68063    Btree *p;
 68064    assert( db!=0 );
 68065    if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
 68066    assert( iDb>=0 && iDb<db->nDb );
 68067    if( !sqlite3_mutex_held(db->mutex) ) return 0;
 68068    if( iDb==1 ) return 1;
 68069    p = db->aDb[iDb].pBt;
 68070    assert( p!=0 );
 68071    return p->sharable==0 || p->locked==1;
 68072  }
 68073  #endif /* NDEBUG */
 68074  
 68075  #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
 68076  /*
 68077  ** The following are special cases for mutex enter routines for use
 68078  ** in single threaded applications that use shared cache.  Except for
 68079  ** these two routines, all mutex operations are no-ops in that case and
 68080  ** are null #defines in btree.h.
 68081  **
 68082  ** If shared cache is disabled, then all btree mutex routines, including
 68083  ** the ones below, are no-ops and are null #defines in btree.h.
 68084  */
 68085  
 68086  SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
 68087    p->pBt->db = p->db;
 68088  }
 68089  SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 68090    int i;
 68091    for(i=0; i<db->nDb; i++){
 68092      Btree *p = db->aDb[i].pBt;
 68093      if( p ){
 68094        p->pBt->db = p->db;
 68095      }
 68096    }
 68097  }
 68098  #endif /* if SQLITE_THREADSAFE */
 68099  
 68100  #ifndef SQLITE_OMIT_INCRBLOB
 68101  /*
 68102  ** Enter a mutex on a Btree given a cursor owned by that Btree. 
 68103  **
 68104  ** These entry points are used by incremental I/O only. Enter() is required 
 68105  ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not 
 68106  ** the build is threadsafe. Leave() is only required by threadsafe builds.
 68107  */
 68108  SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
 68109    sqlite3BtreeEnter(pCur->pBtree);
 68110  }
 68111  # if SQLITE_THREADSAFE
 68112  SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
 68113    sqlite3BtreeLeave(pCur->pBtree);
 68114  }
 68115  # endif
 68116  #endif /* ifndef SQLITE_OMIT_INCRBLOB */
 68117  
 68118  #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
 68119  
 68120  /************** End of btmutex.c *********************************************/
 68121  /************** Begin file btree.c *******************************************/
 68122  /*
 68123  ** 2004 April 6
 68124  **
 68125  ** The author disclaims copyright to this source code.  In place of
 68126  ** a legal notice, here is a blessing:
 68127  **
 68128  **    May you do good and not evil.
 68129  **    May you find forgiveness for yourself and forgive others.
 68130  **    May you share freely, never taking more than you give.
 68131  **
 68132  *************************************************************************
 68133  ** This file implements an external (disk-based) database using BTrees.
 68134  ** See the header comment on "btreeInt.h" for additional information.
 68135  ** Including a description of file format and an overview of operation.
 68136  */
 68137  /* #include "btreeInt.h" */
 68138  
 68139  /*
 68140  ** The header string that appears at the beginning of every
 68141  ** SQLite database.
 68142  */
 68143  static const char zMagicHeader[] = SQLITE_FILE_HEADER;
 68144  
 68145  /*
 68146  ** Set this global variable to 1 to enable tracing using the TRACE
 68147  ** macro.
 68148  */
 68149  #if 0
 68150  int sqlite3BtreeTrace=1;  /* True to enable tracing */
 68151  # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
 68152  #else
 68153  # define TRACE(X)
 68154  #endif
 68155  
 68156  /*
 68157  ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
 68158  ** But if the value is zero, make it 65536.
 68159  **
 68160  ** This routine is used to extract the "offset to cell content area" value
 68161  ** from the header of a btree page.  If the page size is 65536 and the page
 68162  ** is empty, the offset should be 65536, but the 2-byte value stores zero.
 68163  ** This routine makes the necessary adjustment to 65536.
 68164  */
 68165  #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
 68166  
 68167  /*
 68168  ** Values passed as the 5th argument to allocateBtreePage()
 68169  */
 68170  #define BTALLOC_ANY   0           /* Allocate any page */
 68171  #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
 68172  #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
 68173  
 68174  /*
 68175  ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
 68176  ** defined, or 0 if it is. For example:
 68177  **
 68178  **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
 68179  */
 68180  #ifndef SQLITE_OMIT_AUTOVACUUM
 68181  #define IfNotOmitAV(expr) (expr)
 68182  #else
 68183  #define IfNotOmitAV(expr) 0
 68184  #endif
 68185  
 68186  #ifndef SQLITE_OMIT_SHARED_CACHE
 68187  /*
 68188  ** A list of BtShared objects that are eligible for participation
 68189  ** in shared cache.  This variable has file scope during normal builds,
 68190  ** but the test harness needs to access it so we make it global for 
 68191  ** test builds.
 68192  **
 68193  ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
 68194  */
 68195  #ifdef SQLITE_TEST
 68196  SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 68197  #else
 68198  static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
 68199  #endif
 68200  #endif /* SQLITE_OMIT_SHARED_CACHE */
 68201  
 68202  #ifndef SQLITE_OMIT_SHARED_CACHE
 68203  /*
 68204  ** Enable or disable the shared pager and schema features.
 68205  **
 68206  ** This routine has no effect on existing database connections.
 68207  ** The shared cache setting effects only future calls to
 68208  ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
 68209  */
 68210  SQLITE_API int sqlite3_enable_shared_cache(int enable){
 68211    sqlite3GlobalConfig.sharedCacheEnabled = enable;
 68212    return SQLITE_OK;
 68213  }
 68214  #endif
 68215  
 68216  
 68217  
 68218  #ifdef SQLITE_OMIT_SHARED_CACHE
 68219    /*
 68220    ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
 68221    ** and clearAllSharedCacheTableLocks()
 68222    ** manipulate entries in the BtShared.pLock linked list used to store
 68223    ** shared-cache table level locks. If the library is compiled with the
 68224    ** shared-cache feature disabled, then there is only ever one user
 68225    ** of each BtShared structure and so this locking is not necessary. 
 68226    ** So define the lock related functions as no-ops.
 68227    */
 68228    #define querySharedCacheTableLock(a,b,c) SQLITE_OK
 68229    #define setSharedCacheTableLock(a,b,c) SQLITE_OK
 68230    #define clearAllSharedCacheTableLocks(a)
 68231    #define downgradeAllSharedCacheTableLocks(a)
 68232    #define hasSharedCacheTableLock(a,b,c,d) 1
 68233    #define hasReadConflicts(a, b) 0
 68234  #endif
 68235  
 68236  /*
 68237  ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
 68238  ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
 68239  **
 68240  ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
 68241  ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
 68242  ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
 68243  ** with the page number and filename associated with the (MemPage*).
 68244  */
 68245  #ifdef SQLITE_DEBUG
 68246  int corruptPageError(int lineno, MemPage *p){
 68247    char *zMsg;
 68248    sqlite3BeginBenignMalloc();
 68249    zMsg = sqlite3_mprintf("database corruption page %d of %s",
 68250        (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
 68251    );
 68252    sqlite3EndBenignMalloc();
 68253    if( zMsg ){
 68254      sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
 68255    }
 68256    sqlite3_free(zMsg);
 68257    return SQLITE_CORRUPT_BKPT;
 68258  }
 68259  # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
 68260  #else
 68261  # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
 68262  #endif
 68263  
 68264  #ifndef SQLITE_OMIT_SHARED_CACHE
 68265  
 68266  #ifdef SQLITE_DEBUG
 68267  /*
 68268  **** This function is only used as part of an assert() statement. ***
 68269  **
 68270  ** Check to see if pBtree holds the required locks to read or write to the 
 68271  ** table with root page iRoot.   Return 1 if it does and 0 if not.
 68272  **
 68273  ** For example, when writing to a table with root-page iRoot via 
 68274  ** Btree connection pBtree:
 68275  **
 68276  **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
 68277  **
 68278  ** When writing to an index that resides in a sharable database, the 
 68279  ** caller should have first obtained a lock specifying the root page of
 68280  ** the corresponding table. This makes things a bit more complicated,
 68281  ** as this module treats each table as a separate structure. To determine
 68282  ** the table corresponding to the index being written, this
 68283  ** function has to search through the database schema.
 68284  **
 68285  ** Instead of a lock on the table/index rooted at page iRoot, the caller may
 68286  ** hold a write-lock on the schema table (root page 1). This is also
 68287  ** acceptable.
 68288  */
 68289  static int hasSharedCacheTableLock(
 68290    Btree *pBtree,         /* Handle that must hold lock */
 68291    Pgno iRoot,            /* Root page of b-tree */
 68292    int isIndex,           /* True if iRoot is the root of an index b-tree */
 68293    int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
 68294  ){
 68295    Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
 68296    Pgno iTab = 0;
 68297    BtLock *pLock;
 68298  
 68299    /* If this database is not shareable, or if the client is reading
 68300    ** and has the read-uncommitted flag set, then no lock is required. 
 68301    ** Return true immediately.
 68302    */
 68303    if( (pBtree->sharable==0)
 68304     || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
 68305    ){
 68306      return 1;
 68307    }
 68308  
 68309    /* If the client is reading  or writing an index and the schema is
 68310    ** not loaded, then it is too difficult to actually check to see if
 68311    ** the correct locks are held.  So do not bother - just return true.
 68312    ** This case does not come up very often anyhow.
 68313    */
 68314    if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
 68315      return 1;
 68316    }
 68317  
 68318    /* Figure out the root-page that the lock should be held on. For table
 68319    ** b-trees, this is just the root page of the b-tree being read or
 68320    ** written. For index b-trees, it is the root page of the associated
 68321    ** table.  */
 68322    if( isIndex ){
 68323      HashElem *p;
 68324      for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
 68325        Index *pIdx = (Index *)sqliteHashData(p);
 68326        if( pIdx->tnum==(int)iRoot ){
 68327          if( iTab ){
 68328            /* Two or more indexes share the same root page.  There must
 68329            ** be imposter tables.  So just return true.  The assert is not
 68330            ** useful in that case. */
 68331            return 1;
 68332          }
 68333          iTab = pIdx->pTable->tnum;
 68334        }
 68335      }
 68336    }else{
 68337      iTab = iRoot;
 68338    }
 68339  
 68340    /* Search for the required lock. Either a write-lock on root-page iTab, a 
 68341    ** write-lock on the schema table, or (if the client is reading) a
 68342    ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
 68343    for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
 68344      if( pLock->pBtree==pBtree 
 68345       && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
 68346       && pLock->eLock>=eLockType 
 68347      ){
 68348        return 1;
 68349      }
 68350    }
 68351  
 68352    /* Failed to find the required lock. */
 68353    return 0;
 68354  }
 68355  #endif /* SQLITE_DEBUG */
 68356  
 68357  #ifdef SQLITE_DEBUG
 68358  /*
 68359  **** This function may be used as part of assert() statements only. ****
 68360  **
 68361  ** Return true if it would be illegal for pBtree to write into the
 68362  ** table or index rooted at iRoot because other shared connections are
 68363  ** simultaneously reading that same table or index.
 68364  **
 68365  ** It is illegal for pBtree to write if some other Btree object that
 68366  ** shares the same BtShared object is currently reading or writing
 68367  ** the iRoot table.  Except, if the other Btree object has the
 68368  ** read-uncommitted flag set, then it is OK for the other object to
 68369  ** have a read cursor.
 68370  **
 68371  ** For example, before writing to any part of the table or index
 68372  ** rooted at page iRoot, one should call:
 68373  **
 68374  **    assert( !hasReadConflicts(pBtree, iRoot) );
 68375  */
 68376  static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
 68377    BtCursor *p;
 68378    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 68379      if( p->pgnoRoot==iRoot 
 68380       && p->pBtree!=pBtree
 68381       && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
 68382      ){
 68383        return 1;
 68384      }
 68385    }
 68386    return 0;
 68387  }
 68388  #endif    /* #ifdef SQLITE_DEBUG */
 68389  
 68390  /*
 68391  ** Query to see if Btree handle p may obtain a lock of type eLock 
 68392  ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
 68393  ** SQLITE_OK if the lock may be obtained (by calling
 68394  ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
 68395  */
 68396  static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
 68397    BtShared *pBt = p->pBt;
 68398    BtLock *pIter;
 68399  
 68400    assert( sqlite3BtreeHoldsMutex(p) );
 68401    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 68402    assert( p->db!=0 );
 68403    assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
 68404    
 68405    /* If requesting a write-lock, then the Btree must have an open write
 68406    ** transaction on this file. And, obviously, for this to be so there 
 68407    ** must be an open write transaction on the file itself.
 68408    */
 68409    assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
 68410    assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
 68411    
 68412    /* This routine is a no-op if the shared-cache is not enabled */
 68413    if( !p->sharable ){
 68414      return SQLITE_OK;
 68415    }
 68416  
 68417    /* If some other connection is holding an exclusive lock, the
 68418    ** requested lock may not be obtained.
 68419    */
 68420    if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
 68421      sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
 68422      return SQLITE_LOCKED_SHAREDCACHE;
 68423    }
 68424  
 68425    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 68426      /* The condition (pIter->eLock!=eLock) in the following if(...) 
 68427      ** statement is a simplification of:
 68428      **
 68429      **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
 68430      **
 68431      ** since we know that if eLock==WRITE_LOCK, then no other connection
 68432      ** may hold a WRITE_LOCK on any table in this file (since there can
 68433      ** only be a single writer).
 68434      */
 68435      assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
 68436      assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
 68437      if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
 68438        sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
 68439        if( eLock==WRITE_LOCK ){
 68440          assert( p==pBt->pWriter );
 68441          pBt->btsFlags |= BTS_PENDING;
 68442        }
 68443        return SQLITE_LOCKED_SHAREDCACHE;
 68444      }
 68445    }
 68446    return SQLITE_OK;
 68447  }
 68448  #endif /* !SQLITE_OMIT_SHARED_CACHE */
 68449  
 68450  #ifndef SQLITE_OMIT_SHARED_CACHE
 68451  /*
 68452  ** Add a lock on the table with root-page iTable to the shared-btree used
 68453  ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
 68454  ** WRITE_LOCK.
 68455  **
 68456  ** This function assumes the following:
 68457  **
 68458  **   (a) The specified Btree object p is connected to a sharable
 68459  **       database (one with the BtShared.sharable flag set), and
 68460  **
 68461  **   (b) No other Btree objects hold a lock that conflicts
 68462  **       with the requested lock (i.e. querySharedCacheTableLock() has
 68463  **       already been called and returned SQLITE_OK).
 68464  **
 68465  ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
 68466  ** is returned if a malloc attempt fails.
 68467  */
 68468  static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
 68469    BtShared *pBt = p->pBt;
 68470    BtLock *pLock = 0;
 68471    BtLock *pIter;
 68472  
 68473    assert( sqlite3BtreeHoldsMutex(p) );
 68474    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
 68475    assert( p->db!=0 );
 68476  
 68477    /* A connection with the read-uncommitted flag set will never try to
 68478    ** obtain a read-lock using this function. The only read-lock obtained
 68479    ** by a connection in read-uncommitted mode is on the sqlite_master 
 68480    ** table, and that lock is obtained in BtreeBeginTrans().  */
 68481    assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
 68482  
 68483    /* This function should only be called on a sharable b-tree after it 
 68484    ** has been determined that no other b-tree holds a conflicting lock.  */
 68485    assert( p->sharable );
 68486    assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
 68487  
 68488    /* First search the list for an existing lock on this table. */
 68489    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 68490      if( pIter->iTable==iTable && pIter->pBtree==p ){
 68491        pLock = pIter;
 68492        break;
 68493      }
 68494    }
 68495  
 68496    /* If the above search did not find a BtLock struct associating Btree p
 68497    ** with table iTable, allocate one and link it into the list.
 68498    */
 68499    if( !pLock ){
 68500      pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
 68501      if( !pLock ){
 68502        return SQLITE_NOMEM_BKPT;
 68503      }
 68504      pLock->iTable = iTable;
 68505      pLock->pBtree = p;
 68506      pLock->pNext = pBt->pLock;
 68507      pBt->pLock = pLock;
 68508    }
 68509  
 68510    /* Set the BtLock.eLock variable to the maximum of the current lock
 68511    ** and the requested lock. This means if a write-lock was already held
 68512    ** and a read-lock requested, we don't incorrectly downgrade the lock.
 68513    */
 68514    assert( WRITE_LOCK>READ_LOCK );
 68515    if( eLock>pLock->eLock ){
 68516      pLock->eLock = eLock;
 68517    }
 68518  
 68519    return SQLITE_OK;
 68520  }
 68521  #endif /* !SQLITE_OMIT_SHARED_CACHE */
 68522  
 68523  #ifndef SQLITE_OMIT_SHARED_CACHE
 68524  /*
 68525  ** Release all the table locks (locks obtained via calls to
 68526  ** the setSharedCacheTableLock() procedure) held by Btree object p.
 68527  **
 68528  ** This function assumes that Btree p has an open read or write 
 68529  ** transaction. If it does not, then the BTS_PENDING flag
 68530  ** may be incorrectly cleared.
 68531  */
 68532  static void clearAllSharedCacheTableLocks(Btree *p){
 68533    BtShared *pBt = p->pBt;
 68534    BtLock **ppIter = &pBt->pLock;
 68535  
 68536    assert( sqlite3BtreeHoldsMutex(p) );
 68537    assert( p->sharable || 0==*ppIter );
 68538    assert( p->inTrans>0 );
 68539  
 68540    while( *ppIter ){
 68541      BtLock *pLock = *ppIter;
 68542      assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
 68543      assert( pLock->pBtree->inTrans>=pLock->eLock );
 68544      if( pLock->pBtree==p ){
 68545        *ppIter = pLock->pNext;
 68546        assert( pLock->iTable!=1 || pLock==&p->lock );
 68547        if( pLock->iTable!=1 ){
 68548          sqlite3_free(pLock);
 68549        }
 68550      }else{
 68551        ppIter = &pLock->pNext;
 68552      }
 68553    }
 68554  
 68555    assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
 68556    if( pBt->pWriter==p ){
 68557      pBt->pWriter = 0;
 68558      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 68559    }else if( pBt->nTransaction==2 ){
 68560      /* This function is called when Btree p is concluding its 
 68561      ** transaction. If there currently exists a writer, and p is not
 68562      ** that writer, then the number of locks held by connections other
 68563      ** than the writer must be about to drop to zero. In this case
 68564      ** set the BTS_PENDING flag to 0.
 68565      **
 68566      ** If there is not currently a writer, then BTS_PENDING must
 68567      ** be zero already. So this next line is harmless in that case.
 68568      */
 68569      pBt->btsFlags &= ~BTS_PENDING;
 68570    }
 68571  }
 68572  
 68573  /*
 68574  ** This function changes all write-locks held by Btree p into read-locks.
 68575  */
 68576  static void downgradeAllSharedCacheTableLocks(Btree *p){
 68577    BtShared *pBt = p->pBt;
 68578    if( pBt->pWriter==p ){
 68579      BtLock *pLock;
 68580      pBt->pWriter = 0;
 68581      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
 68582      for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
 68583        assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
 68584        pLock->eLock = READ_LOCK;
 68585      }
 68586    }
 68587  }
 68588  
 68589  #endif /* SQLITE_OMIT_SHARED_CACHE */
 68590  
 68591  static void releasePage(MemPage *pPage);         /* Forward reference */
 68592  static void releasePageOne(MemPage *pPage);      /* Forward reference */
 68593  static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
 68594  
 68595  /*
 68596  ***** This routine is used inside of assert() only ****
 68597  **
 68598  ** Verify that the cursor holds the mutex on its BtShared
 68599  */
 68600  #ifdef SQLITE_DEBUG
 68601  static int cursorHoldsMutex(BtCursor *p){
 68602    return sqlite3_mutex_held(p->pBt->mutex);
 68603  }
 68604  
 68605  /* Verify that the cursor and the BtShared agree about what is the current
 68606  ** database connetion. This is important in shared-cache mode. If the database 
 68607  ** connection pointers get out-of-sync, it is possible for routines like
 68608  ** btreeInitPage() to reference an stale connection pointer that references a
 68609  ** a connection that has already closed.  This routine is used inside assert()
 68610  ** statements only and for the purpose of double-checking that the btree code
 68611  ** does keep the database connection pointers up-to-date.
 68612  */
 68613  static int cursorOwnsBtShared(BtCursor *p){
 68614    assert( cursorHoldsMutex(p) );
 68615    return (p->pBtree->db==p->pBt->db);
 68616  }
 68617  #endif
 68618  
 68619  /*
 68620  ** Invalidate the overflow cache of the cursor passed as the first argument.
 68621  ** on the shared btree structure pBt.
 68622  */
 68623  #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
 68624  
 68625  /*
 68626  ** Invalidate the overflow page-list cache for all cursors opened
 68627  ** on the shared btree structure pBt.
 68628  */
 68629  static void invalidateAllOverflowCache(BtShared *pBt){
 68630    BtCursor *p;
 68631    assert( sqlite3_mutex_held(pBt->mutex) );
 68632    for(p=pBt->pCursor; p; p=p->pNext){
 68633      invalidateOverflowCache(p);
 68634    }
 68635  }
 68636  
 68637  #ifndef SQLITE_OMIT_INCRBLOB
 68638  /*
 68639  ** This function is called before modifying the contents of a table
 68640  ** to invalidate any incrblob cursors that are open on the
 68641  ** row or one of the rows being modified.
 68642  **
 68643  ** If argument isClearTable is true, then the entire contents of the
 68644  ** table is about to be deleted. In this case invalidate all incrblob
 68645  ** cursors open on any row within the table with root-page pgnoRoot.
 68646  **
 68647  ** Otherwise, if argument isClearTable is false, then the row with
 68648  ** rowid iRow is being replaced or deleted. In this case invalidate
 68649  ** only those incrblob cursors open on that specific row.
 68650  */
 68651  static void invalidateIncrblobCursors(
 68652    Btree *pBtree,          /* The database file to check */
 68653    Pgno pgnoRoot,          /* The table that might be changing */
 68654    i64 iRow,               /* The rowid that might be changing */
 68655    int isClearTable        /* True if all rows are being deleted */
 68656  ){
 68657    BtCursor *p;
 68658    if( pBtree->hasIncrblobCur==0 ) return;
 68659    assert( sqlite3BtreeHoldsMutex(pBtree) );
 68660    pBtree->hasIncrblobCur = 0;
 68661    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 68662      if( (p->curFlags & BTCF_Incrblob)!=0 ){
 68663        pBtree->hasIncrblobCur = 1;
 68664        if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
 68665          p->eState = CURSOR_INVALID;
 68666        }
 68667      }
 68668    }
 68669  }
 68670  
 68671  #else
 68672    /* Stub function when INCRBLOB is omitted */
 68673    #define invalidateIncrblobCursors(w,x,y,z)
 68674  #endif /* SQLITE_OMIT_INCRBLOB */
 68675  
 68676  /*
 68677  ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
 68678  ** when a page that previously contained data becomes a free-list leaf 
 68679  ** page.
 68680  **
 68681  ** The BtShared.pHasContent bitvec exists to work around an obscure
 68682  ** bug caused by the interaction of two useful IO optimizations surrounding
 68683  ** free-list leaf pages:
 68684  **
 68685  **   1) When all data is deleted from a page and the page becomes
 68686  **      a free-list leaf page, the page is not written to the database
 68687  **      (as free-list leaf pages contain no meaningful data). Sometimes
 68688  **      such a page is not even journalled (as it will not be modified,
 68689  **      why bother journalling it?).
 68690  **
 68691  **   2) When a free-list leaf page is reused, its content is not read
 68692  **      from the database or written to the journal file (why should it
 68693  **      be, if it is not at all meaningful?).
 68694  **
 68695  ** By themselves, these optimizations work fine and provide a handy
 68696  ** performance boost to bulk delete or insert operations. However, if
 68697  ** a page is moved to the free-list and then reused within the same
 68698  ** transaction, a problem comes up. If the page is not journalled when
 68699  ** it is moved to the free-list and it is also not journalled when it
 68700  ** is extracted from the free-list and reused, then the original data
 68701  ** may be lost. In the event of a rollback, it may not be possible
 68702  ** to restore the database to its original configuration.
 68703  **
 68704  ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
 68705  ** moved to become a free-list leaf page, the corresponding bit is
 68706  ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
 68707  ** optimization 2 above is omitted if the corresponding bit is already
 68708  ** set in BtShared.pHasContent. The contents of the bitvec are cleared
 68709  ** at the end of every transaction.
 68710  */
 68711  static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
 68712    int rc = SQLITE_OK;
 68713    if( !pBt->pHasContent ){
 68714      assert( pgno<=pBt->nPage );
 68715      pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
 68716      if( !pBt->pHasContent ){
 68717        rc = SQLITE_NOMEM_BKPT;
 68718      }
 68719    }
 68720    if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
 68721      rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
 68722    }
 68723    return rc;
 68724  }
 68725  
 68726  /*
 68727  ** Query the BtShared.pHasContent vector.
 68728  **
 68729  ** This function is called when a free-list leaf page is removed from the
 68730  ** free-list for reuse. It returns false if it is safe to retrieve the
 68731  ** page from the pager layer with the 'no-content' flag set. True otherwise.
 68732  */
 68733  static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
 68734    Bitvec *p = pBt->pHasContent;
 68735    return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
 68736  }
 68737  
 68738  /*
 68739  ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
 68740  ** invoked at the conclusion of each write-transaction.
 68741  */
 68742  static void btreeClearHasContent(BtShared *pBt){
 68743    sqlite3BitvecDestroy(pBt->pHasContent);
 68744    pBt->pHasContent = 0;
 68745  }
 68746  
 68747  /*
 68748  ** Release all of the apPage[] pages for a cursor.
 68749  */
 68750  static void btreeReleaseAllCursorPages(BtCursor *pCur){
 68751    int i;
 68752    if( pCur->iPage>=0 ){
 68753      for(i=0; i<pCur->iPage; i++){
 68754        releasePageNotNull(pCur->apPage[i]);
 68755      }
 68756      releasePageNotNull(pCur->pPage);
 68757      pCur->iPage = -1;
 68758    }
 68759  }
 68760  
 68761  /*
 68762  ** The cursor passed as the only argument must point to a valid entry
 68763  ** when this function is called (i.e. have eState==CURSOR_VALID). This
 68764  ** function saves the current cursor key in variables pCur->nKey and
 68765  ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 
 68766  ** code otherwise.
 68767  **
 68768  ** If the cursor is open on an intkey table, then the integer key
 68769  ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
 68770  ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 
 68771  ** set to point to a malloced buffer pCur->nKey bytes in size containing 
 68772  ** the key.
 68773  */
 68774  static int saveCursorKey(BtCursor *pCur){
 68775    int rc = SQLITE_OK;
 68776    assert( CURSOR_VALID==pCur->eState );
 68777    assert( 0==pCur->pKey );
 68778    assert( cursorHoldsMutex(pCur) );
 68779  
 68780    if( pCur->curIntKey ){
 68781      /* Only the rowid is required for a table btree */
 68782      pCur->nKey = sqlite3BtreeIntegerKey(pCur);
 68783    }else{
 68784      /* For an index btree, save the complete key content. It is possible
 68785      ** that the current key is corrupt. In that case, it is possible that
 68786      ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
 68787      ** up to the size of 1 varint plus 1 8-byte value when the cursor 
 68788      ** position is restored. Hence the 17 bytes of padding allocated 
 68789      ** below. */
 68790      void *pKey;
 68791      pCur->nKey = sqlite3BtreePayloadSize(pCur);
 68792      pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
 68793      if( pKey ){
 68794        rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
 68795        if( rc==SQLITE_OK ){
 68796          memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
 68797          pCur->pKey = pKey;
 68798        }else{
 68799          sqlite3_free(pKey);
 68800        }
 68801      }else{
 68802        rc = SQLITE_NOMEM_BKPT;
 68803      }
 68804    }
 68805    assert( !pCur->curIntKey || !pCur->pKey );
 68806    return rc;
 68807  }
 68808  
 68809  /*
 68810  ** Save the current cursor position in the variables BtCursor.nKey 
 68811  ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
 68812  **
 68813  ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
 68814  ** prior to calling this routine.  
 68815  */
 68816  static int saveCursorPosition(BtCursor *pCur){
 68817    int rc;
 68818  
 68819    assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
 68820    assert( 0==pCur->pKey );
 68821    assert( cursorHoldsMutex(pCur) );
 68822  
 68823    if( pCur->eState==CURSOR_SKIPNEXT ){
 68824      pCur->eState = CURSOR_VALID;
 68825    }else{
 68826      pCur->skipNext = 0;
 68827    }
 68828  
 68829    rc = saveCursorKey(pCur);
 68830    if( rc==SQLITE_OK ){
 68831      btreeReleaseAllCursorPages(pCur);
 68832      pCur->eState = CURSOR_REQUIRESEEK;
 68833    }
 68834  
 68835    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
 68836    return rc;
 68837  }
 68838  
 68839  /* Forward reference */
 68840  static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
 68841  
 68842  /*
 68843  ** Save the positions of all cursors (except pExcept) that are open on
 68844  ** the table with root-page iRoot.  "Saving the cursor position" means that
 68845  ** the location in the btree is remembered in such a way that it can be
 68846  ** moved back to the same spot after the btree has been modified.  This
 68847  ** routine is called just before cursor pExcept is used to modify the
 68848  ** table, for example in BtreeDelete() or BtreeInsert().
 68849  **
 68850  ** If there are two or more cursors on the same btree, then all such 
 68851  ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
 68852  ** routine enforces that rule.  This routine only needs to be called in
 68853  ** the uncommon case when pExpect has the BTCF_Multiple flag set.
 68854  **
 68855  ** If pExpect!=NULL and if no other cursors are found on the same root-page,
 68856  ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
 68857  ** pointless call to this routine.
 68858  **
 68859  ** Implementation note:  This routine merely checks to see if any cursors
 68860  ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
 68861  ** event that cursors are in need to being saved.
 68862  */
 68863  static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
 68864    BtCursor *p;
 68865    assert( sqlite3_mutex_held(pBt->mutex) );
 68866    assert( pExcept==0 || pExcept->pBt==pBt );
 68867    for(p=pBt->pCursor; p; p=p->pNext){
 68868      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
 68869    }
 68870    if( p ) return saveCursorsOnList(p, iRoot, pExcept);
 68871    if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
 68872    return SQLITE_OK;
 68873  }
 68874  
 68875  /* This helper routine to saveAllCursors does the actual work of saving
 68876  ** the cursors if and when a cursor is found that actually requires saving.
 68877  ** The common case is that no cursors need to be saved, so this routine is
 68878  ** broken out from its caller to avoid unnecessary stack pointer movement.
 68879  */
 68880  static int SQLITE_NOINLINE saveCursorsOnList(
 68881    BtCursor *p,         /* The first cursor that needs saving */
 68882    Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
 68883    BtCursor *pExcept    /* Do not save this cursor */
 68884  ){
 68885    do{
 68886      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
 68887        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
 68888          int rc = saveCursorPosition(p);
 68889          if( SQLITE_OK!=rc ){
 68890            return rc;
 68891          }
 68892        }else{
 68893          testcase( p->iPage>=0 );
 68894          btreeReleaseAllCursorPages(p);
 68895        }
 68896      }
 68897      p = p->pNext;
 68898    }while( p );
 68899    return SQLITE_OK;
 68900  }
 68901  
 68902  /*
 68903  ** Clear the current cursor position.
 68904  */
 68905  SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
 68906    assert( cursorHoldsMutex(pCur) );
 68907    sqlite3_free(pCur->pKey);
 68908    pCur->pKey = 0;
 68909    pCur->eState = CURSOR_INVALID;
 68910  }
 68911  
 68912  /*
 68913  ** In this version of BtreeMoveto, pKey is a packed index record
 68914  ** such as is generated by the OP_MakeRecord opcode.  Unpack the
 68915  ** record and then call BtreeMovetoUnpacked() to do the work.
 68916  */
 68917  static int btreeMoveto(
 68918    BtCursor *pCur,     /* Cursor open on the btree to be searched */
 68919    const void *pKey,   /* Packed key if the btree is an index */
 68920    i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
 68921    int bias,           /* Bias search to the high end */
 68922    int *pRes           /* Write search results here */
 68923  ){
 68924    int rc;                    /* Status code */
 68925    UnpackedRecord *pIdxKey;   /* Unpacked index key */
 68926  
 68927    if( pKey ){
 68928      KeyInfo *pKeyInfo = pCur->pKeyInfo;
 68929      assert( nKey==(i64)(int)nKey );
 68930      pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
 68931      if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
 68932      sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
 68933      if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
 68934        rc = SQLITE_CORRUPT_BKPT;
 68935        goto moveto_done;
 68936      }
 68937    }else{
 68938      pIdxKey = 0;
 68939    }
 68940    rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
 68941  moveto_done:
 68942    if( pIdxKey ){
 68943      sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
 68944    }
 68945    return rc;
 68946  }
 68947  
 68948  /*
 68949  ** Restore the cursor to the position it was in (or as close to as possible)
 68950  ** when saveCursorPosition() was called. Note that this call deletes the 
 68951  ** saved position info stored by saveCursorPosition(), so there can be
 68952  ** at most one effective restoreCursorPosition() call after each 
 68953  ** saveCursorPosition().
 68954  */
 68955  static int btreeRestoreCursorPosition(BtCursor *pCur){
 68956    int rc;
 68957    int skipNext;
 68958    assert( cursorOwnsBtShared(pCur) );
 68959    assert( pCur->eState>=CURSOR_REQUIRESEEK );
 68960    if( pCur->eState==CURSOR_FAULT ){
 68961      return pCur->skipNext;
 68962    }
 68963    pCur->eState = CURSOR_INVALID;
 68964    rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
 68965    if( rc==SQLITE_OK ){
 68966      sqlite3_free(pCur->pKey);
 68967      pCur->pKey = 0;
 68968      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
 68969      if( skipNext ) pCur->skipNext = skipNext;
 68970      if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
 68971        pCur->eState = CURSOR_SKIPNEXT;
 68972      }
 68973    }
 68974    return rc;
 68975  }
 68976  
 68977  #define restoreCursorPosition(p) \
 68978    (p->eState>=CURSOR_REQUIRESEEK ? \
 68979           btreeRestoreCursorPosition(p) : \
 68980           SQLITE_OK)
 68981  
 68982  /*
 68983  ** Determine whether or not a cursor has moved from the position where
 68984  ** it was last placed, or has been invalidated for any other reason.
 68985  ** Cursors can move when the row they are pointing at is deleted out
 68986  ** from under them, for example.  Cursor might also move if a btree
 68987  ** is rebalanced.
 68988  **
 68989  ** Calling this routine with a NULL cursor pointer returns false.
 68990  **
 68991  ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
 68992  ** back to where it ought to be if this routine returns true.
 68993  */
 68994  SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
 68995    assert( EIGHT_BYTE_ALIGNMENT(pCur)
 68996         || pCur==sqlite3BtreeFakeValidCursor() );
 68997    assert( offsetof(BtCursor, eState)==0 );
 68998    assert( sizeof(pCur->eState)==1 );
 68999    return CURSOR_VALID != *(u8*)pCur;
 69000  }
 69001  
 69002  /*
 69003  ** Return a pointer to a fake BtCursor object that will always answer
 69004  ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
 69005  ** cursor returned must not be used with any other Btree interface.
 69006  */
 69007  SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
 69008    static u8 fakeCursor = CURSOR_VALID;
 69009    assert( offsetof(BtCursor, eState)==0 );
 69010    return (BtCursor*)&fakeCursor;
 69011  }
 69012  
 69013  /*
 69014  ** This routine restores a cursor back to its original position after it
 69015  ** has been moved by some outside activity (such as a btree rebalance or
 69016  ** a row having been deleted out from under the cursor).  
 69017  **
 69018  ** On success, the *pDifferentRow parameter is false if the cursor is left
 69019  ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
 69020  ** was pointing to has been deleted, forcing the cursor to point to some
 69021  ** nearby row.
 69022  **
 69023  ** This routine should only be called for a cursor that just returned
 69024  ** TRUE from sqlite3BtreeCursorHasMoved().
 69025  */
 69026  SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
 69027    int rc;
 69028  
 69029    assert( pCur!=0 );
 69030    assert( pCur->eState!=CURSOR_VALID );
 69031    rc = restoreCursorPosition(pCur);
 69032    if( rc ){
 69033      *pDifferentRow = 1;
 69034      return rc;
 69035    }
 69036    if( pCur->eState!=CURSOR_VALID ){
 69037      *pDifferentRow = 1;
 69038    }else{
 69039      *pDifferentRow = 0;
 69040    }
 69041    return SQLITE_OK;
 69042  }
 69043  
 69044  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 69045  /*
 69046  ** Provide hints to the cursor.  The particular hint given (and the type
 69047  ** and number of the varargs parameters) is determined by the eHintType
 69048  ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
 69049  */
 69050  SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
 69051    /* Used only by system that substitute their own storage engine */
 69052  }
 69053  #endif
 69054  
 69055  /*
 69056  ** Provide flag hints to the cursor.
 69057  */
 69058  SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
 69059    assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
 69060    pCur->hints = x;
 69061  }
 69062  
 69063  
 69064  #ifndef SQLITE_OMIT_AUTOVACUUM
 69065  /*
 69066  ** Given a page number of a regular database page, return the page
 69067  ** number for the pointer-map page that contains the entry for the
 69068  ** input page number.
 69069  **
 69070  ** Return 0 (not a valid page) for pgno==1 since there is
 69071  ** no pointer map associated with page 1.  The integrity_check logic
 69072  ** requires that ptrmapPageno(*,1)!=1.
 69073  */
 69074  static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
 69075    int nPagesPerMapPage;
 69076    Pgno iPtrMap, ret;
 69077    assert( sqlite3_mutex_held(pBt->mutex) );
 69078    if( pgno<2 ) return 0;
 69079    nPagesPerMapPage = (pBt->usableSize/5)+1;
 69080    iPtrMap = (pgno-2)/nPagesPerMapPage;
 69081    ret = (iPtrMap*nPagesPerMapPage) + 2; 
 69082    if( ret==PENDING_BYTE_PAGE(pBt) ){
 69083      ret++;
 69084    }
 69085    return ret;
 69086  }
 69087  
 69088  /*
 69089  ** Write an entry into the pointer map.
 69090  **
 69091  ** This routine updates the pointer map entry for page number 'key'
 69092  ** so that it maps to type 'eType' and parent page number 'pgno'.
 69093  **
 69094  ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
 69095  ** a no-op.  If an error occurs, the appropriate error code is written
 69096  ** into *pRC.
 69097  */
 69098  static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
 69099    DbPage *pDbPage;  /* The pointer map page */
 69100    u8 *pPtrmap;      /* The pointer map data */
 69101    Pgno iPtrmap;     /* The pointer map page number */
 69102    int offset;       /* Offset in pointer map page */
 69103    int rc;           /* Return code from subfunctions */
 69104  
 69105    if( *pRC ) return;
 69106  
 69107    assert( sqlite3_mutex_held(pBt->mutex) );
 69108    /* The master-journal page number must never be used as a pointer map page */
 69109    assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
 69110  
 69111    assert( pBt->autoVacuum );
 69112    if( key==0 ){
 69113      *pRC = SQLITE_CORRUPT_BKPT;
 69114      return;
 69115    }
 69116    iPtrmap = PTRMAP_PAGENO(pBt, key);
 69117    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
 69118    if( rc!=SQLITE_OK ){
 69119      *pRC = rc;
 69120      return;
 69121    }
 69122    if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
 69123      /* The first byte of the extra data is the MemPage.isInit byte.
 69124      ** If that byte is set, it means this page is also being used
 69125      ** as a btree page. */
 69126      *pRC = SQLITE_CORRUPT_BKPT;
 69127      goto ptrmap_exit;
 69128    }
 69129    offset = PTRMAP_PTROFFSET(iPtrmap, key);
 69130    if( offset<0 ){
 69131      *pRC = SQLITE_CORRUPT_BKPT;
 69132      goto ptrmap_exit;
 69133    }
 69134    assert( offset <= (int)pBt->usableSize-5 );
 69135    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 69136  
 69137    if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
 69138      TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
 69139      *pRC= rc = sqlite3PagerWrite(pDbPage);
 69140      if( rc==SQLITE_OK ){
 69141        pPtrmap[offset] = eType;
 69142        put4byte(&pPtrmap[offset+1], parent);
 69143      }
 69144    }
 69145  
 69146  ptrmap_exit:
 69147    sqlite3PagerUnref(pDbPage);
 69148  }
 69149  
 69150  /*
 69151  ** Read an entry from the pointer map.
 69152  **
 69153  ** This routine retrieves the pointer map entry for page 'key', writing
 69154  ** the type and parent page number to *pEType and *pPgno respectively.
 69155  ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
 69156  */
 69157  static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
 69158    DbPage *pDbPage;   /* The pointer map page */
 69159    int iPtrmap;       /* Pointer map page index */
 69160    u8 *pPtrmap;       /* Pointer map page data */
 69161    int offset;        /* Offset of entry in pointer map */
 69162    int rc;
 69163  
 69164    assert( sqlite3_mutex_held(pBt->mutex) );
 69165  
 69166    iPtrmap = PTRMAP_PAGENO(pBt, key);
 69167    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
 69168    if( rc!=0 ){
 69169      return rc;
 69170    }
 69171    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
 69172  
 69173    offset = PTRMAP_PTROFFSET(iPtrmap, key);
 69174    if( offset<0 ){
 69175      sqlite3PagerUnref(pDbPage);
 69176      return SQLITE_CORRUPT_BKPT;
 69177    }
 69178    assert( offset <= (int)pBt->usableSize-5 );
 69179    assert( pEType!=0 );
 69180    *pEType = pPtrmap[offset];
 69181    if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
 69182  
 69183    sqlite3PagerUnref(pDbPage);
 69184    if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
 69185    return SQLITE_OK;
 69186  }
 69187  
 69188  #else /* if defined SQLITE_OMIT_AUTOVACUUM */
 69189    #define ptrmapPut(w,x,y,z,rc)
 69190    #define ptrmapGet(w,x,y,z) SQLITE_OK
 69191    #define ptrmapPutOvflPtr(x, y, z, rc)
 69192  #endif
 69193  
 69194  /*
 69195  ** Given a btree page and a cell index (0 means the first cell on
 69196  ** the page, 1 means the second cell, and so forth) return a pointer
 69197  ** to the cell content.
 69198  **
 69199  ** findCellPastPtr() does the same except it skips past the initial
 69200  ** 4-byte child pointer found on interior pages, if there is one.
 69201  **
 69202  ** This routine works only for pages that do not contain overflow cells.
 69203  */
 69204  #define findCell(P,I) \
 69205    ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
 69206  #define findCellPastPtr(P,I) \
 69207    ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
 69208  
 69209  
 69210  /*
 69211  ** This is common tail processing for btreeParseCellPtr() and
 69212  ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
 69213  ** on a single B-tree page.  Make necessary adjustments to the CellInfo
 69214  ** structure.
 69215  */
 69216  static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
 69217    MemPage *pPage,         /* Page containing the cell */
 69218    u8 *pCell,              /* Pointer to the cell text. */
 69219    CellInfo *pInfo         /* Fill in this structure */
 69220  ){
 69221    /* If the payload will not fit completely on the local page, we have
 69222    ** to decide how much to store locally and how much to spill onto
 69223    ** overflow pages.  The strategy is to minimize the amount of unused
 69224    ** space on overflow pages while keeping the amount of local storage
 69225    ** in between minLocal and maxLocal.
 69226    **
 69227    ** Warning:  changing the way overflow payload is distributed in any
 69228    ** way will result in an incompatible file format.
 69229    */
 69230    int minLocal;  /* Minimum amount of payload held locally */
 69231    int maxLocal;  /* Maximum amount of payload held locally */
 69232    int surplus;   /* Overflow payload available for local storage */
 69233  
 69234    minLocal = pPage->minLocal;
 69235    maxLocal = pPage->maxLocal;
 69236    surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
 69237    testcase( surplus==maxLocal );
 69238    testcase( surplus==maxLocal+1 );
 69239    if( surplus <= maxLocal ){
 69240      pInfo->nLocal = (u16)surplus;
 69241    }else{
 69242      pInfo->nLocal = (u16)minLocal;
 69243    }
 69244    pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
 69245  }
 69246  
 69247  /*
 69248  ** The following routines are implementations of the MemPage.xParseCell()
 69249  ** method.
 69250  **
 69251  ** Parse a cell content block and fill in the CellInfo structure.
 69252  **
 69253  ** btreeParseCellPtr()        =>   table btree leaf nodes
 69254  ** btreeParseCellNoPayload()  =>   table btree internal nodes
 69255  ** btreeParseCellPtrIndex()   =>   index btree nodes
 69256  **
 69257  ** There is also a wrapper function btreeParseCell() that works for
 69258  ** all MemPage types and that references the cell by index rather than
 69259  ** by pointer.
 69260  */
 69261  static void btreeParseCellPtrNoPayload(
 69262    MemPage *pPage,         /* Page containing the cell */
 69263    u8 *pCell,              /* Pointer to the cell text. */
 69264    CellInfo *pInfo         /* Fill in this structure */
 69265  ){
 69266    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69267    assert( pPage->leaf==0 );
 69268    assert( pPage->childPtrSize==4 );
 69269  #ifndef SQLITE_DEBUG
 69270    UNUSED_PARAMETER(pPage);
 69271  #endif
 69272    pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
 69273    pInfo->nPayload = 0;
 69274    pInfo->nLocal = 0;
 69275    pInfo->pPayload = 0;
 69276    return;
 69277  }
 69278  static void btreeParseCellPtr(
 69279    MemPage *pPage,         /* Page containing the cell */
 69280    u8 *pCell,              /* Pointer to the cell text. */
 69281    CellInfo *pInfo         /* Fill in this structure */
 69282  ){
 69283    u8 *pIter;              /* For scanning through pCell */
 69284    u32 nPayload;           /* Number of bytes of cell payload */
 69285    u64 iKey;               /* Extracted Key value */
 69286  
 69287    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69288    assert( pPage->leaf==0 || pPage->leaf==1 );
 69289    assert( pPage->intKeyLeaf );
 69290    assert( pPage->childPtrSize==0 );
 69291    pIter = pCell;
 69292  
 69293    /* The next block of code is equivalent to:
 69294    **
 69295    **     pIter += getVarint32(pIter, nPayload);
 69296    **
 69297    ** The code is inlined to avoid a function call.
 69298    */
 69299    nPayload = *pIter;
 69300    if( nPayload>=0x80 ){
 69301      u8 *pEnd = &pIter[8];
 69302      nPayload &= 0x7f;
 69303      do{
 69304        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
 69305      }while( (*pIter)>=0x80 && pIter<pEnd );
 69306    }
 69307    pIter++;
 69308  
 69309    /* The next block of code is equivalent to:
 69310    **
 69311    **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
 69312    **
 69313    ** The code is inlined to avoid a function call.
 69314    */
 69315    iKey = *pIter;
 69316    if( iKey>=0x80 ){
 69317      u8 *pEnd = &pIter[7];
 69318      iKey &= 0x7f;
 69319      while(1){
 69320        iKey = (iKey<<7) | (*++pIter & 0x7f);
 69321        if( (*pIter)<0x80 ) break;
 69322        if( pIter>=pEnd ){
 69323          iKey = (iKey<<8) | *++pIter;
 69324          break;
 69325        }
 69326      }
 69327    }
 69328    pIter++;
 69329  
 69330    pInfo->nKey = *(i64*)&iKey;
 69331    pInfo->nPayload = nPayload;
 69332    pInfo->pPayload = pIter;
 69333    testcase( nPayload==pPage->maxLocal );
 69334    testcase( nPayload==pPage->maxLocal+1 );
 69335    if( nPayload<=pPage->maxLocal ){
 69336      /* This is the (easy) common case where the entire payload fits
 69337      ** on the local page.  No overflow is required.
 69338      */
 69339      pInfo->nSize = nPayload + (u16)(pIter - pCell);
 69340      if( pInfo->nSize<4 ) pInfo->nSize = 4;
 69341      pInfo->nLocal = (u16)nPayload;
 69342    }else{
 69343      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
 69344    }
 69345  }
 69346  static void btreeParseCellPtrIndex(
 69347    MemPage *pPage,         /* Page containing the cell */
 69348    u8 *pCell,              /* Pointer to the cell text. */
 69349    CellInfo *pInfo         /* Fill in this structure */
 69350  ){
 69351    u8 *pIter;              /* For scanning through pCell */
 69352    u32 nPayload;           /* Number of bytes of cell payload */
 69353  
 69354    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69355    assert( pPage->leaf==0 || pPage->leaf==1 );
 69356    assert( pPage->intKeyLeaf==0 );
 69357    pIter = pCell + pPage->childPtrSize;
 69358    nPayload = *pIter;
 69359    if( nPayload>=0x80 ){
 69360      u8 *pEnd = &pIter[8];
 69361      nPayload &= 0x7f;
 69362      do{
 69363        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
 69364      }while( *(pIter)>=0x80 && pIter<pEnd );
 69365    }
 69366    pIter++;
 69367    pInfo->nKey = nPayload;
 69368    pInfo->nPayload = nPayload;
 69369    pInfo->pPayload = pIter;
 69370    testcase( nPayload==pPage->maxLocal );
 69371    testcase( nPayload==pPage->maxLocal+1 );
 69372    if( nPayload<=pPage->maxLocal ){
 69373      /* This is the (easy) common case where the entire payload fits
 69374      ** on the local page.  No overflow is required.
 69375      */
 69376      pInfo->nSize = nPayload + (u16)(pIter - pCell);
 69377      if( pInfo->nSize<4 ) pInfo->nSize = 4;
 69378      pInfo->nLocal = (u16)nPayload;
 69379    }else{
 69380      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
 69381    }
 69382  }
 69383  static void btreeParseCell(
 69384    MemPage *pPage,         /* Page containing the cell */
 69385    int iCell,              /* The cell index.  First cell is 0 */
 69386    CellInfo *pInfo         /* Fill in this structure */
 69387  ){
 69388    pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
 69389  }
 69390  
 69391  /*
 69392  ** The following routines are implementations of the MemPage.xCellSize
 69393  ** method.
 69394  **
 69395  ** Compute the total number of bytes that a Cell needs in the cell
 69396  ** data area of the btree-page.  The return number includes the cell
 69397  ** data header and the local payload, but not any overflow page or
 69398  ** the space used by the cell pointer.
 69399  **
 69400  ** cellSizePtrNoPayload()    =>   table internal nodes
 69401  ** cellSizePtr()             =>   all index nodes & table leaf nodes
 69402  */
 69403  static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
 69404    u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
 69405    u8 *pEnd;                                /* End mark for a varint */
 69406    u32 nSize;                               /* Size value to return */
 69407  
 69408  #ifdef SQLITE_DEBUG
 69409    /* The value returned by this function should always be the same as
 69410    ** the (CellInfo.nSize) value found by doing a full parse of the
 69411    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
 69412    ** this function verifies that this invariant is not violated. */
 69413    CellInfo debuginfo;
 69414    pPage->xParseCell(pPage, pCell, &debuginfo);
 69415  #endif
 69416  
 69417    nSize = *pIter;
 69418    if( nSize>=0x80 ){
 69419      pEnd = &pIter[8];
 69420      nSize &= 0x7f;
 69421      do{
 69422        nSize = (nSize<<7) | (*++pIter & 0x7f);
 69423      }while( *(pIter)>=0x80 && pIter<pEnd );
 69424    }
 69425    pIter++;
 69426    if( pPage->intKey ){
 69427      /* pIter now points at the 64-bit integer key value, a variable length 
 69428      ** integer. The following block moves pIter to point at the first byte
 69429      ** past the end of the key value. */
 69430      pEnd = &pIter[9];
 69431      while( (*pIter++)&0x80 && pIter<pEnd );
 69432    }
 69433    testcase( nSize==pPage->maxLocal );
 69434    testcase( nSize==pPage->maxLocal+1 );
 69435    if( nSize<=pPage->maxLocal ){
 69436      nSize += (u32)(pIter - pCell);
 69437      if( nSize<4 ) nSize = 4;
 69438    }else{
 69439      int minLocal = pPage->minLocal;
 69440      nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
 69441      testcase( nSize==pPage->maxLocal );
 69442      testcase( nSize==pPage->maxLocal+1 );
 69443      if( nSize>pPage->maxLocal ){
 69444        nSize = minLocal;
 69445      }
 69446      nSize += 4 + (u16)(pIter - pCell);
 69447    }
 69448    assert( nSize==debuginfo.nSize || CORRUPT_DB );
 69449    return (u16)nSize;
 69450  }
 69451  static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
 69452    u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
 69453    u8 *pEnd;              /* End mark for a varint */
 69454  
 69455  #ifdef SQLITE_DEBUG
 69456    /* The value returned by this function should always be the same as
 69457    ** the (CellInfo.nSize) value found by doing a full parse of the
 69458    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
 69459    ** this function verifies that this invariant is not violated. */
 69460    CellInfo debuginfo;
 69461    pPage->xParseCell(pPage, pCell, &debuginfo);
 69462  #else
 69463    UNUSED_PARAMETER(pPage);
 69464  #endif
 69465  
 69466    assert( pPage->childPtrSize==4 );
 69467    pEnd = pIter + 9;
 69468    while( (*pIter++)&0x80 && pIter<pEnd );
 69469    assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
 69470    return (u16)(pIter - pCell);
 69471  }
 69472  
 69473  
 69474  #ifdef SQLITE_DEBUG
 69475  /* This variation on cellSizePtr() is used inside of assert() statements
 69476  ** only. */
 69477  static u16 cellSize(MemPage *pPage, int iCell){
 69478    return pPage->xCellSize(pPage, findCell(pPage, iCell));
 69479  }
 69480  #endif
 69481  
 69482  #ifndef SQLITE_OMIT_AUTOVACUUM
 69483  /*
 69484  ** The cell pCell is currently part of page pSrc but will ultimately be part
 69485  ** of pPage.  (pSrc and pPager are often the same.)  If pCell contains a
 69486  ** pointer to an overflow page, insert an entry into the pointer-map for
 69487  ** the overflow page that will be valid after pCell has been moved to pPage.
 69488  */
 69489  static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
 69490    CellInfo info;
 69491    if( *pRC ) return;
 69492    assert( pCell!=0 );
 69493    pPage->xParseCell(pPage, pCell, &info);
 69494    if( info.nLocal<info.nPayload ){
 69495      Pgno ovfl;
 69496      if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
 69497        testcase( pSrc!=pPage );
 69498        *pRC = SQLITE_CORRUPT_BKPT;
 69499        return;
 69500      }
 69501      ovfl = get4byte(&pCell[info.nSize-4]);
 69502      ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
 69503    }
 69504  }
 69505  #endif
 69506  
 69507  
 69508  /*
 69509  ** Defragment the page given. This routine reorganizes cells within the
 69510  ** page so that there are no free-blocks on the free-block list.
 69511  **
 69512  ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
 69513  ** present in the page after this routine returns.
 69514  **
 69515  ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
 69516  ** b-tree page so that there are no freeblocks or fragment bytes, all
 69517  ** unused bytes are contained in the unallocated space region, and all
 69518  ** cells are packed tightly at the end of the page.
 69519  */
 69520  static int defragmentPage(MemPage *pPage, int nMaxFrag){
 69521    int i;                     /* Loop counter */
 69522    int pc;                    /* Address of the i-th cell */
 69523    int hdr;                   /* Offset to the page header */
 69524    int size;                  /* Size of a cell */
 69525    int usableSize;            /* Number of usable bytes on a page */
 69526    int cellOffset;            /* Offset to the cell pointer array */
 69527    int cbrk;                  /* Offset to the cell content area */
 69528    int nCell;                 /* Number of cells on the page */
 69529    unsigned char *data;       /* The page data */
 69530    unsigned char *temp;       /* Temp area for cell content */
 69531    unsigned char *src;        /* Source of content */
 69532    int iCellFirst;            /* First allowable cell index */
 69533    int iCellLast;             /* Last possible cell index */
 69534  
 69535    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 69536    assert( pPage->pBt!=0 );
 69537    assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
 69538    assert( pPage->nOverflow==0 );
 69539    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69540    temp = 0;
 69541    src = data = pPage->aData;
 69542    hdr = pPage->hdrOffset;
 69543    cellOffset = pPage->cellOffset;
 69544    nCell = pPage->nCell;
 69545    assert( nCell==get2byte(&data[hdr+3]) );
 69546    iCellFirst = cellOffset + 2*nCell;
 69547    usableSize = pPage->pBt->usableSize;
 69548  
 69549    /* This block handles pages with two or fewer free blocks and nMaxFrag
 69550    ** or fewer fragmented bytes. In this case it is faster to move the
 69551    ** two (or one) blocks of cells using memmove() and add the required
 69552    ** offsets to each pointer in the cell-pointer array than it is to 
 69553    ** reconstruct the entire page.  */
 69554    if( (int)data[hdr+7]<=nMaxFrag ){
 69555      int iFree = get2byte(&data[hdr+1]);
 69556  
 69557      /* If the initial freeblock offset were out of bounds, that would
 69558      ** have been detected by btreeInitPage() when it was computing the
 69559      ** number of free bytes on the page. */
 69560      assert( iFree<=usableSize-4 );
 69561      if( iFree ){
 69562        int iFree2 = get2byte(&data[iFree]);
 69563        if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
 69564        if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
 69565          u8 *pEnd = &data[cellOffset + nCell*2];
 69566          u8 *pAddr;
 69567          int sz2 = 0;
 69568          int sz = get2byte(&data[iFree+2]);
 69569          int top = get2byte(&data[hdr+5]);
 69570          if( top>=iFree ){
 69571            return SQLITE_CORRUPT_PAGE(pPage);
 69572          }
 69573          if( iFree2 ){
 69574            if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
 69575            sz2 = get2byte(&data[iFree2+2]);
 69576            if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
 69577            memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
 69578            sz += sz2;
 69579          }
 69580          cbrk = top+sz;
 69581          assert( cbrk+(iFree-top) <= usableSize );
 69582          memmove(&data[cbrk], &data[top], iFree-top);
 69583          for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
 69584            pc = get2byte(pAddr);
 69585            if( pc<iFree ){ put2byte(pAddr, pc+sz); }
 69586            else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
 69587          }
 69588          goto defragment_out;
 69589        }
 69590      }
 69591    }
 69592  
 69593    cbrk = usableSize;
 69594    iCellLast = usableSize - 4;
 69595    for(i=0; i<nCell; i++){
 69596      u8 *pAddr;     /* The i-th cell pointer */
 69597      pAddr = &data[cellOffset + i*2];
 69598      pc = get2byte(pAddr);
 69599      testcase( pc==iCellFirst );
 69600      testcase( pc==iCellLast );
 69601      /* These conditions have already been verified in btreeInitPage()
 69602      ** if PRAGMA cell_size_check=ON.
 69603      */
 69604      if( pc<iCellFirst || pc>iCellLast ){
 69605        return SQLITE_CORRUPT_PAGE(pPage);
 69606      }
 69607      assert( pc>=iCellFirst && pc<=iCellLast );
 69608      size = pPage->xCellSize(pPage, &src[pc]);
 69609      cbrk -= size;
 69610      if( cbrk<iCellFirst || pc+size>usableSize ){
 69611        return SQLITE_CORRUPT_PAGE(pPage);
 69612      }
 69613      assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
 69614      testcase( cbrk+size==usableSize );
 69615      testcase( pc+size==usableSize );
 69616      put2byte(pAddr, cbrk);
 69617      if( temp==0 ){
 69618        int x;
 69619        if( cbrk==pc ) continue;
 69620        temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
 69621        x = get2byte(&data[hdr+5]);
 69622        memcpy(&temp[x], &data[x], (cbrk+size) - x);
 69623        src = temp;
 69624      }
 69625      memcpy(&data[cbrk], &src[pc], size);
 69626    }
 69627    data[hdr+7] = 0;
 69628  
 69629   defragment_out:
 69630    if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
 69631      return SQLITE_CORRUPT_PAGE(pPage);
 69632    }
 69633    assert( cbrk>=iCellFirst );
 69634    put2byte(&data[hdr+5], cbrk);
 69635    data[hdr+1] = 0;
 69636    data[hdr+2] = 0;
 69637    memset(&data[iCellFirst], 0, cbrk-iCellFirst);
 69638    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 69639    return SQLITE_OK;
 69640  }
 69641  
 69642  /*
 69643  ** Search the free-list on page pPg for space to store a cell nByte bytes in
 69644  ** size. If one can be found, return a pointer to the space and remove it
 69645  ** from the free-list.
 69646  **
 69647  ** If no suitable space can be found on the free-list, return NULL.
 69648  **
 69649  ** This function may detect corruption within pPg.  If corruption is
 69650  ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
 69651  **
 69652  ** Slots on the free list that are between 1 and 3 bytes larger than nByte
 69653  ** will be ignored if adding the extra space to the fragmentation count
 69654  ** causes the fragmentation count to exceed 60.
 69655  */
 69656  static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
 69657    const int hdr = pPg->hdrOffset;
 69658    u8 * const aData = pPg->aData;
 69659    int iAddr = hdr + 1;
 69660    int pc = get2byte(&aData[iAddr]);
 69661    int x;
 69662    int usableSize = pPg->pBt->usableSize;
 69663    int size;            /* Size of the free slot */
 69664  
 69665    assert( pc>0 );
 69666    while( pc<=usableSize-4 ){
 69667      /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
 69668      ** freeblock form a big-endian integer which is the size of the freeblock
 69669      ** in bytes, including the 4-byte header. */
 69670      size = get2byte(&aData[pc+2]);
 69671      if( (x = size - nByte)>=0 ){
 69672        testcase( x==4 );
 69673        testcase( x==3 );
 69674        if( size+pc > usableSize ){
 69675          *pRc = SQLITE_CORRUPT_PAGE(pPg);
 69676          return 0;
 69677        }else if( x<4 ){
 69678          /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
 69679          ** number of bytes in fragments may not exceed 60. */
 69680          if( aData[hdr+7]>57 ) return 0;
 69681  
 69682          /* Remove the slot from the free-list. Update the number of
 69683          ** fragmented bytes within the page. */
 69684          memcpy(&aData[iAddr], &aData[pc], 2);
 69685          aData[hdr+7] += (u8)x;
 69686        }else{
 69687          /* The slot remains on the free-list. Reduce its size to account
 69688           ** for the portion used by the new allocation. */
 69689          put2byte(&aData[pc+2], x);
 69690        }
 69691        return &aData[pc + x];
 69692      }
 69693      iAddr = pc;
 69694      pc = get2byte(&aData[pc]);
 69695      if( pc<iAddr+size ) break;
 69696    }
 69697    if( pc ){
 69698      *pRc = SQLITE_CORRUPT_PAGE(pPg);
 69699    }
 69700  
 69701    return 0;
 69702  }
 69703  
 69704  /*
 69705  ** Allocate nByte bytes of space from within the B-Tree page passed
 69706  ** as the first argument. Write into *pIdx the index into pPage->aData[]
 69707  ** of the first byte of allocated space. Return either SQLITE_OK or
 69708  ** an error code (usually SQLITE_CORRUPT).
 69709  **
 69710  ** The caller guarantees that there is sufficient space to make the
 69711  ** allocation.  This routine might need to defragment in order to bring
 69712  ** all the space together, however.  This routine will avoid using
 69713  ** the first two bytes past the cell pointer area since presumably this
 69714  ** allocation is being made in order to insert a new cell, so we will
 69715  ** also end up needing a new cell pointer.
 69716  */
 69717  static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
 69718    const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
 69719    u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
 69720    int top;                             /* First byte of cell content area */
 69721    int rc = SQLITE_OK;                  /* Integer return code */
 69722    int gap;        /* First byte of gap between cell pointers and cell content */
 69723    
 69724    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 69725    assert( pPage->pBt );
 69726    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69727    assert( nByte>=0 );  /* Minimum cell size is 4 */
 69728    assert( pPage->nFree>=nByte );
 69729    assert( pPage->nOverflow==0 );
 69730    assert( nByte < (int)(pPage->pBt->usableSize-8) );
 69731  
 69732    assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
 69733    gap = pPage->cellOffset + 2*pPage->nCell;
 69734    assert( gap<=65536 );
 69735    /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
 69736    ** and the reserved space is zero (the usual value for reserved space)
 69737    ** then the cell content offset of an empty page wants to be 65536.
 69738    ** However, that integer is too large to be stored in a 2-byte unsigned
 69739    ** integer, so a value of 0 is used in its place. */
 69740    top = get2byte(&data[hdr+5]);
 69741    assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
 69742    if( gap>top ){
 69743      if( top==0 && pPage->pBt->usableSize==65536 ){
 69744        top = 65536;
 69745      }else{
 69746        return SQLITE_CORRUPT_PAGE(pPage);
 69747      }
 69748    }
 69749  
 69750    /* If there is enough space between gap and top for one more cell pointer
 69751    ** array entry offset, and if the freelist is not empty, then search the
 69752    ** freelist looking for a free slot big enough to satisfy the request.
 69753    */
 69754    testcase( gap+2==top );
 69755    testcase( gap+1==top );
 69756    testcase( gap==top );
 69757    if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
 69758      u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
 69759      if( pSpace ){
 69760        assert( pSpace>=data && (pSpace - data)<65536 );
 69761        *pIdx = (int)(pSpace - data);
 69762        return SQLITE_OK;
 69763      }else if( rc ){
 69764        return rc;
 69765      }
 69766    }
 69767  
 69768    /* The request could not be fulfilled using a freelist slot.  Check
 69769    ** to see if defragmentation is necessary.
 69770    */
 69771    testcase( gap+2+nByte==top );
 69772    if( gap+2+nByte>top ){
 69773      assert( pPage->nCell>0 || CORRUPT_DB );
 69774      rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
 69775      if( rc ) return rc;
 69776      top = get2byteNotZero(&data[hdr+5]);
 69777      assert( gap+2+nByte<=top );
 69778    }
 69779  
 69780  
 69781    /* Allocate memory from the gap in between the cell pointer array
 69782    ** and the cell content area.  The btreeInitPage() call has already
 69783    ** validated the freelist.  Given that the freelist is valid, there
 69784    ** is no way that the allocation can extend off the end of the page.
 69785    ** The assert() below verifies the previous sentence.
 69786    */
 69787    top -= nByte;
 69788    put2byte(&data[hdr+5], top);
 69789    assert( top+nByte <= (int)pPage->pBt->usableSize );
 69790    *pIdx = top;
 69791    return SQLITE_OK;
 69792  }
 69793  
 69794  /*
 69795  ** Return a section of the pPage->aData to the freelist.
 69796  ** The first byte of the new free block is pPage->aData[iStart]
 69797  ** and the size of the block is iSize bytes.
 69798  **
 69799  ** Adjacent freeblocks are coalesced.
 69800  **
 69801  ** Note that even though the freeblock list was checked by btreeInitPage(),
 69802  ** that routine will not detect overlap between cells or freeblocks.  Nor
 69803  ** does it detect cells or freeblocks that encrouch into the reserved bytes
 69804  ** at the end of the page.  So do additional corruption checks inside this
 69805  ** routine and return SQLITE_CORRUPT if any problems are found.
 69806  */
 69807  static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
 69808    u16 iPtr;                             /* Address of ptr to next freeblock */
 69809    u16 iFreeBlk;                         /* Address of the next freeblock */
 69810    u8 hdr;                               /* Page header size.  0 or 100 */
 69811    u8 nFrag = 0;                         /* Reduction in fragmentation */
 69812    u16 iOrigSize = iSize;                /* Original value of iSize */
 69813    u16 x;                                /* Offset to cell content area */
 69814    u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
 69815    unsigned char *data = pPage->aData;   /* Page content */
 69816  
 69817    assert( pPage->pBt!=0 );
 69818    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 69819    assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
 69820    assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
 69821    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69822    assert( iSize>=4 );   /* Minimum cell size is 4 */
 69823    assert( iStart<=pPage->pBt->usableSize-4 );
 69824  
 69825    /* The list of freeblocks must be in ascending order.  Find the 
 69826    ** spot on the list where iStart should be inserted.
 69827    */
 69828    hdr = pPage->hdrOffset;
 69829    iPtr = hdr + 1;
 69830    if( data[iPtr+1]==0 && data[iPtr]==0 ){
 69831      iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
 69832    }else{
 69833      while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
 69834        if( iFreeBlk<iPtr+4 ){
 69835          if( iFreeBlk==0 ) break;
 69836          return SQLITE_CORRUPT_PAGE(pPage);
 69837        }
 69838        iPtr = iFreeBlk;
 69839      }
 69840      if( iFreeBlk>pPage->pBt->usableSize-4 ){
 69841        return SQLITE_CORRUPT_PAGE(pPage);
 69842      }
 69843      assert( iFreeBlk>iPtr || iFreeBlk==0 );
 69844    
 69845      /* At this point:
 69846      **    iFreeBlk:   First freeblock after iStart, or zero if none
 69847      **    iPtr:       The address of a pointer to iFreeBlk
 69848      **
 69849      ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
 69850      */
 69851      if( iFreeBlk && iEnd+3>=iFreeBlk ){
 69852        nFrag = iFreeBlk - iEnd;
 69853        if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
 69854        iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
 69855        if( iEnd > pPage->pBt->usableSize ){
 69856          return SQLITE_CORRUPT_PAGE(pPage);
 69857        }
 69858        iSize = iEnd - iStart;
 69859        iFreeBlk = get2byte(&data[iFreeBlk]);
 69860      }
 69861    
 69862      /* If iPtr is another freeblock (that is, if iPtr is not the freelist
 69863      ** pointer in the page header) then check to see if iStart should be
 69864      ** coalesced onto the end of iPtr.
 69865      */
 69866      if( iPtr>hdr+1 ){
 69867        int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
 69868        if( iPtrEnd+3>=iStart ){
 69869          if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
 69870          nFrag += iStart - iPtrEnd;
 69871          iSize = iEnd - iPtr;
 69872          iStart = iPtr;
 69873        }
 69874      }
 69875      if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
 69876      data[hdr+7] -= nFrag;
 69877    }
 69878    x = get2byte(&data[hdr+5]);
 69879    if( iStart<=x ){
 69880      /* The new freeblock is at the beginning of the cell content area,
 69881      ** so just extend the cell content area rather than create another
 69882      ** freelist entry */
 69883      if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
 69884      put2byte(&data[hdr+1], iFreeBlk);
 69885      put2byte(&data[hdr+5], iEnd);
 69886    }else{
 69887      /* Insert the new freeblock into the freelist */
 69888      put2byte(&data[iPtr], iStart);
 69889    }
 69890    if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
 69891      /* Overwrite deleted information with zeros when the secure_delete
 69892      ** option is enabled */
 69893      memset(&data[iStart], 0, iSize);
 69894    }
 69895    put2byte(&data[iStart], iFreeBlk);
 69896    put2byte(&data[iStart+2], iSize);
 69897    pPage->nFree += iOrigSize;
 69898    return SQLITE_OK;
 69899  }
 69900  
 69901  /*
 69902  ** Decode the flags byte (the first byte of the header) for a page
 69903  ** and initialize fields of the MemPage structure accordingly.
 69904  **
 69905  ** Only the following combinations are supported.  Anything different
 69906  ** indicates a corrupt database files:
 69907  **
 69908  **         PTF_ZERODATA
 69909  **         PTF_ZERODATA | PTF_LEAF
 69910  **         PTF_LEAFDATA | PTF_INTKEY
 69911  **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
 69912  */
 69913  static int decodeFlags(MemPage *pPage, int flagByte){
 69914    BtShared *pBt;     /* A copy of pPage->pBt */
 69915  
 69916    assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
 69917    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69918    pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
 69919    flagByte &= ~PTF_LEAF;
 69920    pPage->childPtrSize = 4-4*pPage->leaf;
 69921    pPage->xCellSize = cellSizePtr;
 69922    pBt = pPage->pBt;
 69923    if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
 69924      /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
 69925      ** interior table b-tree page. */
 69926      assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
 69927      /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
 69928      ** leaf table b-tree page. */
 69929      assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
 69930      pPage->intKey = 1;
 69931      if( pPage->leaf ){
 69932        pPage->intKeyLeaf = 1;
 69933        pPage->xParseCell = btreeParseCellPtr;
 69934      }else{
 69935        pPage->intKeyLeaf = 0;
 69936        pPage->xCellSize = cellSizePtrNoPayload;
 69937        pPage->xParseCell = btreeParseCellPtrNoPayload;
 69938      }
 69939      pPage->maxLocal = pBt->maxLeaf;
 69940      pPage->minLocal = pBt->minLeaf;
 69941    }else if( flagByte==PTF_ZERODATA ){
 69942      /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
 69943      ** interior index b-tree page. */
 69944      assert( (PTF_ZERODATA)==2 );
 69945      /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
 69946      ** leaf index b-tree page. */
 69947      assert( (PTF_ZERODATA|PTF_LEAF)==10 );
 69948      pPage->intKey = 0;
 69949      pPage->intKeyLeaf = 0;
 69950      pPage->xParseCell = btreeParseCellPtrIndex;
 69951      pPage->maxLocal = pBt->maxLocal;
 69952      pPage->minLocal = pBt->minLocal;
 69953    }else{
 69954      /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
 69955      ** an error. */
 69956      return SQLITE_CORRUPT_PAGE(pPage);
 69957    }
 69958    pPage->max1bytePayload = pBt->max1bytePayload;
 69959    return SQLITE_OK;
 69960  }
 69961  
 69962  /*
 69963  ** Initialize the auxiliary information for a disk block.
 69964  **
 69965  ** Return SQLITE_OK on success.  If we see that the page does
 69966  ** not contain a well-formed database page, then return 
 69967  ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
 69968  ** guarantee that the page is well-formed.  It only shows that
 69969  ** we failed to detect any corruption.
 69970  */
 69971  static int btreeInitPage(MemPage *pPage){
 69972    int pc;            /* Address of a freeblock within pPage->aData[] */
 69973    u8 hdr;            /* Offset to beginning of page header */
 69974    u8 *data;          /* Equal to pPage->aData */
 69975    BtShared *pBt;        /* The main btree structure */
 69976    int usableSize;    /* Amount of usable space on each page */
 69977    u16 cellOffset;    /* Offset from start of page to first cell pointer */
 69978    int nFree;         /* Number of unused bytes on the page */
 69979    int top;           /* First byte of the cell content area */
 69980    int iCellFirst;    /* First allowable cell or freeblock offset */
 69981    int iCellLast;     /* Last possible cell or freeblock offset */
 69982  
 69983    assert( pPage->pBt!=0 );
 69984    assert( pPage->pBt->db!=0 );
 69985    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 69986    assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
 69987    assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
 69988    assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
 69989    assert( pPage->isInit==0 );
 69990  
 69991    pBt = pPage->pBt;
 69992    hdr = pPage->hdrOffset;
 69993    data = pPage->aData;
 69994    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
 69995    ** the b-tree page type. */
 69996    if( decodeFlags(pPage, data[hdr]) ){
 69997      return SQLITE_CORRUPT_PAGE(pPage);
 69998    }
 69999    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 70000    pPage->maskPage = (u16)(pBt->pageSize - 1);
 70001    pPage->nOverflow = 0;
 70002    usableSize = pBt->usableSize;
 70003    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
 70004    pPage->aDataEnd = &data[usableSize];
 70005    pPage->aCellIdx = &data[cellOffset];
 70006    pPage->aDataOfst = &data[pPage->childPtrSize];
 70007    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
 70008    ** the start of the cell content area. A zero value for this integer is
 70009    ** interpreted as 65536. */
 70010    top = get2byteNotZero(&data[hdr+5]);
 70011    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
 70012    ** number of cells on the page. */
 70013    pPage->nCell = get2byte(&data[hdr+3]);
 70014    if( pPage->nCell>MX_CELL(pBt) ){
 70015      /* To many cells for a single page.  The page must be corrupt */
 70016      return SQLITE_CORRUPT_PAGE(pPage);
 70017    }
 70018    testcase( pPage->nCell==MX_CELL(pBt) );
 70019    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
 70020    ** possible for a root page of a table that contains no rows) then the
 70021    ** offset to the cell content area will equal the page size minus the
 70022    ** bytes of reserved space. */
 70023    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
 70024  
 70025    /* A malformed database page might cause us to read past the end
 70026    ** of page when parsing a cell.  
 70027    **
 70028    ** The following block of code checks early to see if a cell extends
 70029    ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
 70030    ** returned if it does.
 70031    */
 70032    iCellFirst = cellOffset + 2*pPage->nCell;
 70033    iCellLast = usableSize - 4;
 70034    if( pBt->db->flags & SQLITE_CellSizeCk ){
 70035      int i;            /* Index into the cell pointer array */
 70036      int sz;           /* Size of a cell */
 70037  
 70038      if( !pPage->leaf ) iCellLast--;
 70039      for(i=0; i<pPage->nCell; i++){
 70040        pc = get2byteAligned(&data[cellOffset+i*2]);
 70041        testcase( pc==iCellFirst );
 70042        testcase( pc==iCellLast );
 70043        if( pc<iCellFirst || pc>iCellLast ){
 70044          return SQLITE_CORRUPT_PAGE(pPage);
 70045        }
 70046        sz = pPage->xCellSize(pPage, &data[pc]);
 70047        testcase( pc+sz==usableSize );
 70048        if( pc+sz>usableSize ){
 70049          return SQLITE_CORRUPT_PAGE(pPage);
 70050        }
 70051      }
 70052      if( !pPage->leaf ) iCellLast++;
 70053    }  
 70054  
 70055    /* Compute the total free space on the page
 70056    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
 70057    ** start of the first freeblock on the page, or is zero if there are no
 70058    ** freeblocks. */
 70059    pc = get2byte(&data[hdr+1]);
 70060    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
 70061    if( pc>0 ){
 70062      u32 next, size;
 70063      if( pc<iCellFirst ){
 70064        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
 70065        ** always be at least one cell before the first freeblock.
 70066        */
 70067        return SQLITE_CORRUPT_PAGE(pPage); 
 70068      }
 70069      while( 1 ){
 70070        if( pc>iCellLast ){
 70071          /* Freeblock off the end of the page */
 70072          return SQLITE_CORRUPT_PAGE(pPage);
 70073        }
 70074        next = get2byte(&data[pc]);
 70075        size = get2byte(&data[pc+2]);
 70076        nFree = nFree + size;
 70077        if( next<=pc+size+3 ) break;
 70078        pc = next;
 70079      }
 70080      if( next>0 ){
 70081        /* Freeblock not in ascending order */
 70082        return SQLITE_CORRUPT_PAGE(pPage);
 70083      }
 70084      if( pc+size>(unsigned int)usableSize ){
 70085        /* Last freeblock extends past page end */
 70086        return SQLITE_CORRUPT_PAGE(pPage);
 70087      }
 70088    }
 70089  
 70090    /* At this point, nFree contains the sum of the offset to the start
 70091    ** of the cell-content area plus the number of free bytes within
 70092    ** the cell-content area. If this is greater than the usable-size
 70093    ** of the page, then the page must be corrupted. This check also
 70094    ** serves to verify that the offset to the start of the cell-content
 70095    ** area, according to the page header, lies within the page.
 70096    */
 70097    if( nFree>usableSize ){
 70098      return SQLITE_CORRUPT_PAGE(pPage);
 70099    }
 70100    pPage->nFree = (u16)(nFree - iCellFirst);
 70101    pPage->isInit = 1;
 70102    return SQLITE_OK;
 70103  }
 70104  
 70105  /*
 70106  ** Set up a raw page so that it looks like a database page holding
 70107  ** no entries.
 70108  */
 70109  static void zeroPage(MemPage *pPage, int flags){
 70110    unsigned char *data = pPage->aData;
 70111    BtShared *pBt = pPage->pBt;
 70112    u8 hdr = pPage->hdrOffset;
 70113    u16 first;
 70114  
 70115    assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
 70116    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 70117    assert( sqlite3PagerGetData(pPage->pDbPage) == data );
 70118    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 70119    assert( sqlite3_mutex_held(pBt->mutex) );
 70120    if( pBt->btsFlags & BTS_FAST_SECURE ){
 70121      memset(&data[hdr], 0, pBt->usableSize - hdr);
 70122    }
 70123    data[hdr] = (char)flags;
 70124    first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
 70125    memset(&data[hdr+1], 0, 4);
 70126    data[hdr+7] = 0;
 70127    put2byte(&data[hdr+5], pBt->usableSize);
 70128    pPage->nFree = (u16)(pBt->usableSize - first);
 70129    decodeFlags(pPage, flags);
 70130    pPage->cellOffset = first;
 70131    pPage->aDataEnd = &data[pBt->usableSize];
 70132    pPage->aCellIdx = &data[first];
 70133    pPage->aDataOfst = &data[pPage->childPtrSize];
 70134    pPage->nOverflow = 0;
 70135    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 70136    pPage->maskPage = (u16)(pBt->pageSize - 1);
 70137    pPage->nCell = 0;
 70138    pPage->isInit = 1;
 70139  }
 70140  
 70141  
 70142  /*
 70143  ** Convert a DbPage obtained from the pager into a MemPage used by
 70144  ** the btree layer.
 70145  */
 70146  static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
 70147    MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
 70148    if( pgno!=pPage->pgno ){
 70149      pPage->aData = sqlite3PagerGetData(pDbPage);
 70150      pPage->pDbPage = pDbPage;
 70151      pPage->pBt = pBt;
 70152      pPage->pgno = pgno;
 70153      pPage->hdrOffset = pgno==1 ? 100 : 0;
 70154    }
 70155    assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
 70156    return pPage; 
 70157  }
 70158  
 70159  /*
 70160  ** Get a page from the pager.  Initialize the MemPage.pBt and
 70161  ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
 70162  **
 70163  ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
 70164  ** about the content of the page at this time.  So do not go to the disk
 70165  ** to fetch the content.  Just fill in the content with zeros for now.
 70166  ** If in the future we call sqlite3PagerWrite() on this page, that
 70167  ** means we have started to be concerned about content and the disk
 70168  ** read should occur at that point.
 70169  */
 70170  static int btreeGetPage(
 70171    BtShared *pBt,       /* The btree */
 70172    Pgno pgno,           /* Number of the page to fetch */
 70173    MemPage **ppPage,    /* Return the page in this parameter */
 70174    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
 70175  ){
 70176    int rc;
 70177    DbPage *pDbPage;
 70178  
 70179    assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
 70180    assert( sqlite3_mutex_held(pBt->mutex) );
 70181    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
 70182    if( rc ) return rc;
 70183    *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
 70184    return SQLITE_OK;
 70185  }
 70186  
 70187  /*
 70188  ** Retrieve a page from the pager cache. If the requested page is not
 70189  ** already in the pager cache return NULL. Initialize the MemPage.pBt and
 70190  ** MemPage.aData elements if needed.
 70191  */
 70192  static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
 70193    DbPage *pDbPage;
 70194    assert( sqlite3_mutex_held(pBt->mutex) );
 70195    pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
 70196    if( pDbPage ){
 70197      return btreePageFromDbPage(pDbPage, pgno, pBt);
 70198    }
 70199    return 0;
 70200  }
 70201  
 70202  /*
 70203  ** Return the size of the database file in pages. If there is any kind of
 70204  ** error, return ((unsigned int)-1).
 70205  */
 70206  static Pgno btreePagecount(BtShared *pBt){
 70207    return pBt->nPage;
 70208  }
 70209  SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
 70210    assert( sqlite3BtreeHoldsMutex(p) );
 70211    assert( ((p->pBt->nPage)&0x80000000)==0 );
 70212    return btreePagecount(p->pBt);
 70213  }
 70214  
 70215  /*
 70216  ** Get a page from the pager and initialize it.
 70217  **
 70218  ** If pCur!=0 then the page is being fetched as part of a moveToChild()
 70219  ** call.  Do additional sanity checking on the page in this case.
 70220  ** And if the fetch fails, this routine must decrement pCur->iPage.
 70221  **
 70222  ** The page is fetched as read-write unless pCur is not NULL and is
 70223  ** a read-only cursor.
 70224  **
 70225  ** If an error occurs, then *ppPage is undefined. It
 70226  ** may remain unchanged, or it may be set to an invalid value.
 70227  */
 70228  static int getAndInitPage(
 70229    BtShared *pBt,                  /* The database file */
 70230    Pgno pgno,                      /* Number of the page to get */
 70231    MemPage **ppPage,               /* Write the page pointer here */
 70232    BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
 70233    int bReadOnly                   /* True for a read-only page */
 70234  ){
 70235    int rc;
 70236    DbPage *pDbPage;
 70237    assert( sqlite3_mutex_held(pBt->mutex) );
 70238    assert( pCur==0 || ppPage==&pCur->pPage );
 70239    assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
 70240    assert( pCur==0 || pCur->iPage>0 );
 70241  
 70242    if( pgno>btreePagecount(pBt) ){
 70243      rc = SQLITE_CORRUPT_BKPT;
 70244      goto getAndInitPage_error;
 70245    }
 70246    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
 70247    if( rc ){
 70248      goto getAndInitPage_error;
 70249    }
 70250    *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
 70251    if( (*ppPage)->isInit==0 ){
 70252      btreePageFromDbPage(pDbPage, pgno, pBt);
 70253      rc = btreeInitPage(*ppPage);
 70254      if( rc!=SQLITE_OK ){
 70255        releasePage(*ppPage);
 70256        goto getAndInitPage_error;
 70257      }
 70258    }
 70259    assert( (*ppPage)->pgno==pgno );
 70260    assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
 70261  
 70262    /* If obtaining a child page for a cursor, we must verify that the page is
 70263    ** compatible with the root page. */
 70264    if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
 70265      rc = SQLITE_CORRUPT_PGNO(pgno);
 70266      releasePage(*ppPage);
 70267      goto getAndInitPage_error;
 70268    }
 70269    return SQLITE_OK;
 70270  
 70271  getAndInitPage_error:
 70272    if( pCur ){
 70273      pCur->iPage--;
 70274      pCur->pPage = pCur->apPage[pCur->iPage];
 70275    }
 70276    testcase( pgno==0 );
 70277    assert( pgno!=0 || rc==SQLITE_CORRUPT );
 70278    return rc;
 70279  }
 70280  
 70281  /*
 70282  ** Release a MemPage.  This should be called once for each prior
 70283  ** call to btreeGetPage.
 70284  **
 70285  ** Page1 is a special case and must be released using releasePageOne().
 70286  */
 70287  static void releasePageNotNull(MemPage *pPage){
 70288    assert( pPage->aData );
 70289    assert( pPage->pBt );
 70290    assert( pPage->pDbPage!=0 );
 70291    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 70292    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
 70293    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 70294    sqlite3PagerUnrefNotNull(pPage->pDbPage);
 70295  }
 70296  static void releasePage(MemPage *pPage){
 70297    if( pPage ) releasePageNotNull(pPage);
 70298  }
 70299  static void releasePageOne(MemPage *pPage){
 70300    assert( pPage!=0 );
 70301    assert( pPage->aData );
 70302    assert( pPage->pBt );
 70303    assert( pPage->pDbPage!=0 );
 70304    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
 70305    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
 70306    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 70307    sqlite3PagerUnrefPageOne(pPage->pDbPage);
 70308  }
 70309  
 70310  /*
 70311  ** Get an unused page.
 70312  **
 70313  ** This works just like btreeGetPage() with the addition:
 70314  **
 70315  **   *  If the page is already in use for some other purpose, immediately
 70316  **      release it and return an SQLITE_CURRUPT error.
 70317  **   *  Make sure the isInit flag is clear
 70318  */
 70319  static int btreeGetUnusedPage(
 70320    BtShared *pBt,       /* The btree */
 70321    Pgno pgno,           /* Number of the page to fetch */
 70322    MemPage **ppPage,    /* Return the page in this parameter */
 70323    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
 70324  ){
 70325    int rc = btreeGetPage(pBt, pgno, ppPage, flags);
 70326    if( rc==SQLITE_OK ){
 70327      if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
 70328        releasePage(*ppPage);
 70329        *ppPage = 0;
 70330        return SQLITE_CORRUPT_BKPT;
 70331      }
 70332      (*ppPage)->isInit = 0;
 70333    }else{
 70334      *ppPage = 0;
 70335    }
 70336    return rc;
 70337  }
 70338  
 70339  
 70340  /*
 70341  ** During a rollback, when the pager reloads information into the cache
 70342  ** so that the cache is restored to its original state at the start of
 70343  ** the transaction, for each page restored this routine is called.
 70344  **
 70345  ** This routine needs to reset the extra data section at the end of the
 70346  ** page to agree with the restored data.
 70347  */
 70348  static void pageReinit(DbPage *pData){
 70349    MemPage *pPage;
 70350    pPage = (MemPage *)sqlite3PagerGetExtra(pData);
 70351    assert( sqlite3PagerPageRefcount(pData)>0 );
 70352    if( pPage->isInit ){
 70353      assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 70354      pPage->isInit = 0;
 70355      if( sqlite3PagerPageRefcount(pData)>1 ){
 70356        /* pPage might not be a btree page;  it might be an overflow page
 70357        ** or ptrmap page or a free page.  In those cases, the following
 70358        ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
 70359        ** But no harm is done by this.  And it is very important that
 70360        ** btreeInitPage() be called on every btree page so we make
 70361        ** the call for every page that comes in for re-initing. */
 70362        btreeInitPage(pPage);
 70363      }
 70364    }
 70365  }
 70366  
 70367  /*
 70368  ** Invoke the busy handler for a btree.
 70369  */
 70370  static int btreeInvokeBusyHandler(void *pArg){
 70371    BtShared *pBt = (BtShared*)pArg;
 70372    assert( pBt->db );
 70373    assert( sqlite3_mutex_held(pBt->db->mutex) );
 70374    return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
 70375                                    sqlite3PagerFile(pBt->pPager));
 70376  }
 70377  
 70378  sqlite3_vfs *sqlite3_nullvfs(void);
 70379  
 70380  /*
 70381  ** Open a database file.
 70382  ** 
 70383  ** zFilename is the name of the database file.  If zFilename is NULL
 70384  ** then an ephemeral database is created.  The ephemeral database might
 70385  ** be exclusively in memory, or it might use a disk-based memory cache.
 70386  ** Either way, the ephemeral database will be automatically deleted 
 70387  ** when sqlite3BtreeClose() is called.
 70388  **
 70389  ** If zFilename is ":memory:" then an in-memory database is created
 70390  ** that is automatically destroyed when it is closed.
 70391  **
 70392  ** The "flags" parameter is a bitmask that might contain bits like
 70393  ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
 70394  **
 70395  ** If the database is already opened in the same database connection
 70396  ** and we are in shared cache mode, then the open will fail with an
 70397  ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
 70398  ** objects in the same database connection since doing so will lead
 70399  ** to problems with locking.
 70400  */
 70401  SQLITE_PRIVATE int sqlite3BtreeOpen(
 70402    sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
 70403    const char *zFilename,  /* Name of the file containing the BTree database */
 70404    sqlite3 *db,            /* Associated database handle */
 70405    Btree **ppBtree,        /* Pointer to new Btree object written here */
 70406    int flags,              /* Options */
 70407    int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
 70408  ){
 70409    BtShared *pBt = 0;             /* Shared part of btree structure */
 70410    Btree *p;                      /* Handle to return */
 70411    sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
 70412    int rc = SQLITE_OK;            /* Result code from this function */
 70413    u8 nReserve;                   /* Byte of unused space on each page */
 70414    unsigned char zDbHeader[100];  /* Database header content */
 70415  
 70416    /* True if opening an ephemeral, temporary database */
 70417    const int isTempDb = zFilename==0 || zFilename[0]==0;
 70418  
 70419    /* Set the variable isMemdb to true for an in-memory database, or 
 70420    ** false for a file-based database.
 70421    */
 70422  #ifdef SQLITE_OMIT_MEMORYDB
 70423    const int isMemdb = 0;
 70424  #else
 70425    const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
 70426                         || (isTempDb && sqlite3TempInMemory(db))
 70427                         || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
 70428  #endif
 70429  
 70430    BRANCHTRACE("sqlite3BtreeOpen %s VFS=%s", isTempDb ? "temporary" : zFilename, pVfs->zName);
 70431  
 70432    if( isTempDb && pVfs==sqlite3_nullvfs() ){
 70433      /* temporary dbs use the default VFS */
 70434      pVfs = sqlite3_vfs_find(NULL);
 70435    }
 70436  
 70437    assert( db!=0 );
 70438    assert( pVfs!=0 );
 70439    assert( sqlite3_mutex_held(db->mutex) );
 70440    assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
 70441  
 70442    /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
 70443    assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
 70444  
 70445    /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
 70446    assert( (flags & BTREE_SINGLE)==0 || isTempDb );
 70447  
 70448    if( isMemdb ){
 70449      flags |= BTREE_MEMORY;
 70450    }
 70451    if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
 70452      vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
 70453    }
 70454    p = sqlite3MallocZero(sizeof(Btree));
 70455    if( !p ){
 70456      return SQLITE_NOMEM_BKPT;
 70457    }
 70458    p->inTrans = TRANS_NONE;
 70459    p->db = db;
 70460  #ifndef SQLITE_OMIT_SHARED_CACHE
 70461    p->lock.pBtree = p;
 70462    p->lock.iTable = 1;
 70463  #endif
 70464  
 70465  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 70466    /*
 70467    ** If this Btree is a candidate for shared cache, try to find an
 70468    ** existing BtShared object that we can share with
 70469    */
 70470    if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
 70471      if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
 70472        int nFilename = sqlite3Strlen30(zFilename)+1;
 70473        int nFullPathname = pVfs->mxPathname+1;
 70474        char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
 70475        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 70476  
 70477        p->sharable = 1;
 70478        if( !zFullPathname ){
 70479          sqlite3_free(p);
 70480          return SQLITE_NOMEM_BKPT;
 70481        }
 70482        if( isMemdb ){
 70483          memcpy(zFullPathname, zFilename, nFilename);
 70484        }else{
 70485          rc = sqlite3OsFullPathname(pVfs, zFilename,
 70486                                     nFullPathname, zFullPathname);
 70487          if( rc ){
 70488            sqlite3_free(zFullPathname);
 70489            sqlite3_free(p);
 70490            return rc;
 70491          }
 70492        }
 70493  #if SQLITE_THREADSAFE
 70494        mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
 70495        sqlite3_mutex_enter(mutexOpen);
 70496        mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
 70497        sqlite3_mutex_enter(mutexShared);
 70498  #endif
 70499        for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
 70500          assert( pBt->nRef>0 );
 70501          if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
 70502                   && sqlite3PagerVfs(pBt->pPager)==pVfs ){
 70503            int iDb;
 70504            for(iDb=db->nDb-1; iDb>=0; iDb--){
 70505              Btree *pExisting = db->aDb[iDb].pBt;
 70506              if( pExisting && pExisting->pBt==pBt ){
 70507                sqlite3_mutex_leave(mutexShared);
 70508                sqlite3_mutex_leave(mutexOpen);
 70509                sqlite3_free(zFullPathname);
 70510                sqlite3_free(p);
 70511                return SQLITE_CONSTRAINT;
 70512              }
 70513            }
 70514            p->pBt = pBt;
 70515            pBt->nRef++;
 70516            break;
 70517          }
 70518        }
 70519        sqlite3_mutex_leave(mutexShared);
 70520        sqlite3_free(zFullPathname);
 70521      }
 70522  #ifdef SQLITE_DEBUG
 70523      else{
 70524        /* In debug mode, we mark all persistent databases as sharable
 70525        ** even when they are not.  This exercises the locking code and
 70526        ** gives more opportunity for asserts(sqlite3_mutex_held())
 70527        ** statements to find locking problems.
 70528        */
 70529        p->sharable = 1;
 70530      }
 70531  #endif
 70532    }
 70533  #endif
 70534    if( pBt==0 ){
 70535      /*
 70536      ** The following asserts make sure that structures used by the btree are
 70537      ** the right size.  This is to guard against size changes that result
 70538      ** when compiling on a different architecture.
 70539      */
 70540      assert( sizeof(i64)==8 );
 70541      assert( sizeof(u64)==8 );
 70542      assert( sizeof(u32)==4 );
 70543      assert( sizeof(u16)==2 );
 70544      assert( sizeof(Pgno)==4 );
 70545    
 70546      pBt = sqlite3MallocZero( sizeof(*pBt) );
 70547      if( pBt==0 ){
 70548        rc = SQLITE_NOMEM_BKPT;
 70549        goto btree_open_out;
 70550      }
 70551      rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
 70552                            sizeof(MemPage), flags, vfsFlags, pageReinit);
 70553      if( rc==SQLITE_OK ){
 70554        sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
 70555        rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
 70556      }
 70557      if( rc!=SQLITE_OK ){
 70558        goto btree_open_out;
 70559      }
 70560      pBt->openFlags = (u8)flags;
 70561      pBt->db = db;
 70562      sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
 70563      p->pBt = pBt;
 70564    
 70565      pBt->pCursor = 0;
 70566      pBt->pPage1 = 0;
 70567      if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
 70568  #if defined(SQLITE_SECURE_DELETE)
 70569      pBt->btsFlags |= BTS_SECURE_DELETE;
 70570  #elif defined(SQLITE_FAST_SECURE_DELETE)
 70571      pBt->btsFlags |= BTS_OVERWRITE;
 70572  #endif
 70573      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
 70574      ** determined by the 2-byte integer located at an offset of 16 bytes from
 70575      ** the beginning of the database file. */
 70576      pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
 70577      if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
 70578           || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
 70579        pBt->pageSize = 0;
 70580  #ifndef SQLITE_OMIT_AUTOVACUUM
 70581        /* If the magic name ":memory:" will create an in-memory database, then
 70582        ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
 70583        ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
 70584        ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
 70585        ** regular file-name. In this case the auto-vacuum applies as per normal.
 70586        */
 70587        if( zFilename && !isMemdb ){
 70588          pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
 70589          pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
 70590        }
 70591  #endif
 70592        nReserve = 0;
 70593      }else{
 70594        /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
 70595        ** determined by the one-byte unsigned integer found at an offset of 20
 70596        ** into the database file header. */
 70597        nReserve = zDbHeader[20];
 70598        pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 70599  #ifndef SQLITE_OMIT_AUTOVACUUM
 70600        pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
 70601        pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
 70602  #endif
 70603      }
 70604      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 70605      if( rc ) goto btree_open_out;
 70606      pBt->usableSize = pBt->pageSize - nReserve;
 70607      assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
 70608     
 70609  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 70610      /* Add the new BtShared object to the linked list sharable BtShareds.
 70611      */
 70612      pBt->nRef = 1;
 70613      if( p->sharable ){
 70614        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
 70615        MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
 70616        if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
 70617          pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
 70618          if( pBt->mutex==0 ){
 70619            rc = SQLITE_NOMEM_BKPT;
 70620            goto btree_open_out;
 70621          }
 70622        }
 70623        sqlite3_mutex_enter(mutexShared);
 70624        pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
 70625        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
 70626        sqlite3_mutex_leave(mutexShared);
 70627      }
 70628  #endif
 70629    }
 70630  
 70631  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
 70632    /* If the new Btree uses a sharable pBtShared, then link the new
 70633    ** Btree into the list of all sharable Btrees for the same connection.
 70634    ** The list is kept in ascending order by pBt address.
 70635    */
 70636    if( p->sharable ){
 70637      int i;
 70638      Btree *pSib;
 70639      for(i=0; i<db->nDb; i++){
 70640        if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
 70641          while( pSib->pPrev ){ pSib = pSib->pPrev; }
 70642          if( (uptr)p->pBt<(uptr)pSib->pBt ){
 70643            p->pNext = pSib;
 70644            p->pPrev = 0;
 70645            pSib->pPrev = p;
 70646          }else{
 70647            while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
 70648              pSib = pSib->pNext;
 70649            }
 70650            p->pNext = pSib->pNext;
 70651            p->pPrev = pSib;
 70652            if( p->pNext ){
 70653              p->pNext->pPrev = p;
 70654            }
 70655            pSib->pNext = p;
 70656          }
 70657          break;
 70658        }
 70659      }
 70660    }
 70661  #endif
 70662    *ppBtree = p;
 70663  
 70664  btree_open_out:
 70665    if( rc!=SQLITE_OK ){
 70666      if( pBt && pBt->pPager ){
 70667        sqlite3PagerClose(pBt->pPager, 0);
 70668      }
 70669      sqlite3_free(pBt);
 70670      sqlite3_free(p);
 70671      *ppBtree = 0;
 70672    }else{
 70673      sqlite3_file *pFile;
 70674  
 70675      /* If the B-Tree was successfully opened, set the pager-cache size to the
 70676      ** default value. Except, when opening on an existing shared pager-cache,
 70677      ** do not change the pager-cache size.
 70678      */
 70679      if( sqlite3BtreeSchema(p, 0, 0)==0 ){
 70680        sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
 70681      }
 70682  
 70683      pFile = sqlite3PagerFile(pBt->pPager);
 70684      if( pFile->pMethods ){
 70685        sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
 70686      }
 70687    }
 70688    if( mutexOpen ){
 70689      assert( sqlite3_mutex_held(mutexOpen) );
 70690      sqlite3_mutex_leave(mutexOpen);
 70691    }
 70692    assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
 70693    return rc;
 70694  }
 70695  
 70696  /*
 70697  ** Decrement the BtShared.nRef counter.  When it reaches zero,
 70698  ** remove the BtShared structure from the sharing list.  Return
 70699  ** true if the BtShared.nRef counter reaches zero and return
 70700  ** false if it is still positive.
 70701  */
 70702  static int removeFromSharingList(BtShared *pBt){
 70703  #ifndef SQLITE_OMIT_SHARED_CACHE
 70704    MUTEX_LOGIC( sqlite3_mutex *pMaster; )
 70705    BtShared *pList;
 70706    int removed = 0;
 70707  
 70708    assert( sqlite3_mutex_notheld(pBt->mutex) );
 70709    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
 70710    sqlite3_mutex_enter(pMaster);
 70711    pBt->nRef--;
 70712    if( pBt->nRef<=0 ){
 70713      if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
 70714        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
 70715      }else{
 70716        pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
 70717        while( ALWAYS(pList) && pList->pNext!=pBt ){
 70718          pList=pList->pNext;
 70719        }
 70720        if( ALWAYS(pList) ){
 70721          pList->pNext = pBt->pNext;
 70722        }
 70723      }
 70724      if( SQLITE_THREADSAFE ){
 70725        sqlite3_mutex_free(pBt->mutex);
 70726      }
 70727      removed = 1;
 70728    }
 70729    sqlite3_mutex_leave(pMaster);
 70730    return removed;
 70731  #else
 70732    return 1;
 70733  #endif
 70734  }
 70735  
 70736  /*
 70737  ** Make sure pBt->pTmpSpace points to an allocation of 
 70738  ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
 70739  ** pointer.
 70740  */
 70741  static void allocateTempSpace(BtShared *pBt){
 70742    if( !pBt->pTmpSpace ){
 70743      pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
 70744  
 70745      /* One of the uses of pBt->pTmpSpace is to format cells before
 70746      ** inserting them into a leaf page (function fillInCell()). If
 70747      ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
 70748      ** by the various routines that manipulate binary cells. Which
 70749      ** can mean that fillInCell() only initializes the first 2 or 3
 70750      ** bytes of pTmpSpace, but that the first 4 bytes are copied from
 70751      ** it into a database page. This is not actually a problem, but it
 70752      ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
 70753      ** data is passed to system call write(). So to avoid this error,
 70754      ** zero the first 4 bytes of temp space here.
 70755      **
 70756      ** Also:  Provide four bytes of initialized space before the
 70757      ** beginning of pTmpSpace as an area available to prepend the
 70758      ** left-child pointer to the beginning of a cell.
 70759      */
 70760      if( pBt->pTmpSpace ){
 70761        memset(pBt->pTmpSpace, 0, 8);
 70762        pBt->pTmpSpace += 4;
 70763      }
 70764    }
 70765  }
 70766  
 70767  /*
 70768  ** Free the pBt->pTmpSpace allocation
 70769  */
 70770  static void freeTempSpace(BtShared *pBt){
 70771    if( pBt->pTmpSpace ){
 70772      pBt->pTmpSpace -= 4;
 70773      sqlite3PageFree(pBt->pTmpSpace);
 70774      pBt->pTmpSpace = 0;
 70775    }
 70776  }
 70777  
 70778  /*
 70779  ** Close an open database and invalidate all cursors.
 70780  */
 70781  SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
 70782    BtShared *pBt = p->pBt;
 70783    BtCursor *pCur;
 70784  
 70785    /* Close all cursors opened via this handle.  */
 70786    assert( sqlite3_mutex_held(p->db->mutex) );
 70787    sqlite3BtreeEnter(p);
 70788    pCur = pBt->pCursor;
 70789    while( pCur ){
 70790      BtCursor *pTmp = pCur;
 70791      pCur = pCur->pNext;
 70792      if( pTmp->pBtree==p ){
 70793        sqlite3BtreeCloseCursor(pTmp);
 70794      }
 70795    }
 70796  
 70797    /* Rollback any active transaction and free the handle structure.
 70798    ** The call to sqlite3BtreeRollback() drops any table-locks held by
 70799    ** this handle.
 70800    */
 70801    sqlite3BtreeRollback(p, SQLITE_OK, 0);
 70802    sqlite3BtreeLeave(p);
 70803  
 70804    /* If there are still other outstanding references to the shared-btree
 70805    ** structure, return now. The remainder of this procedure cleans 
 70806    ** up the shared-btree.
 70807    */
 70808    assert( p->wantToLock==0 && p->locked==0 );
 70809    if( !p->sharable || removeFromSharingList(pBt) ){
 70810      /* The pBt is no longer on the sharing list, so we can access
 70811      ** it without having to hold the mutex.
 70812      **
 70813      ** Clean out and delete the BtShared object.
 70814      */
 70815      assert( !pBt->pCursor );
 70816      sqlite3PagerClose(pBt->pPager, p->db);
 70817      if( pBt->xFreeSchema && pBt->pSchema ){
 70818        pBt->xFreeSchema(pBt->pSchema);
 70819      }
 70820      sqlite3DbFree(0, pBt->pSchema);
 70821      freeTempSpace(pBt);
 70822      sqlite3_free(pBt);
 70823    }
 70824  
 70825  #ifndef SQLITE_OMIT_SHARED_CACHE
 70826    assert( p->wantToLock==0 );
 70827    assert( p->locked==0 );
 70828    if( p->pPrev ) p->pPrev->pNext = p->pNext;
 70829    if( p->pNext ) p->pNext->pPrev = p->pPrev;
 70830  #endif
 70831  
 70832    sqlite3_free(p);
 70833    return SQLITE_OK;
 70834  }
 70835  
 70836  /*
 70837  ** Change the "soft" limit on the number of pages in the cache.
 70838  ** Unused and unmodified pages will be recycled when the number of
 70839  ** pages in the cache exceeds this soft limit.  But the size of the
 70840  ** cache is allowed to grow larger than this limit if it contains
 70841  ** dirty pages or pages still in active use.
 70842  */
 70843  SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
 70844    BtShared *pBt = p->pBt;
 70845    assert( sqlite3_mutex_held(p->db->mutex) );
 70846    sqlite3BtreeEnter(p);
 70847    sqlite3PagerSetCachesize(pBt->pPager, mxPage);
 70848    sqlite3BtreeLeave(p);
 70849    return SQLITE_OK;
 70850  }
 70851  
 70852  /*
 70853  ** Change the "spill" limit on the number of pages in the cache.
 70854  ** If the number of pages exceeds this limit during a write transaction,
 70855  ** the pager might attempt to "spill" pages to the journal early in
 70856  ** order to free up memory.
 70857  **
 70858  ** The value returned is the current spill size.  If zero is passed
 70859  ** as an argument, no changes are made to the spill size setting, so
 70860  ** using mxPage of 0 is a way to query the current spill size.
 70861  */
 70862  SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
 70863    BtShared *pBt = p->pBt;
 70864    int res;
 70865    assert( sqlite3_mutex_held(p->db->mutex) );
 70866    sqlite3BtreeEnter(p);
 70867    res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
 70868    sqlite3BtreeLeave(p);
 70869    return res;
 70870  }
 70871  
 70872  #if SQLITE_MAX_MMAP_SIZE>0
 70873  /*
 70874  ** Change the limit on the amount of the database file that may be
 70875  ** memory mapped.
 70876  */
 70877  SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
 70878    BtShared *pBt = p->pBt;
 70879    assert( sqlite3_mutex_held(p->db->mutex) );
 70880    sqlite3BtreeEnter(p);
 70881    sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
 70882    sqlite3BtreeLeave(p);
 70883    return SQLITE_OK;
 70884  }
 70885  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
 70886  
 70887  /*
 70888  ** Change the way data is synced to disk in order to increase or decrease
 70889  ** how well the database resists damage due to OS crashes and power
 70890  ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
 70891  ** there is a high probability of damage)  Level 2 is the default.  There
 70892  ** is a very low but non-zero probability of damage.  Level 3 reduces the
 70893  ** probability of damage to near zero but with a write performance reduction.
 70894  */
 70895  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 70896  SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
 70897    Btree *p,              /* The btree to set the safety level on */
 70898    unsigned pgFlags       /* Various PAGER_* flags */
 70899  ){
 70900    BtShared *pBt = p->pBt;
 70901    assert( sqlite3_mutex_held(p->db->mutex) );
 70902    sqlite3BtreeEnter(p);
 70903    sqlite3PagerSetFlags(pBt->pPager, pgFlags);
 70904    sqlite3BtreeLeave(p);
 70905    return SQLITE_OK;
 70906  }
 70907  #endif
 70908  
 70909  /*
 70910  ** Change the default pages size and the number of reserved bytes per page.
 70911  ** Or, if the page size has already been fixed, return SQLITE_READONLY 
 70912  ** without changing anything.
 70913  **
 70914  ** The page size must be a power of 2 between 512 and 65536.  If the page
 70915  ** size supplied does not meet this constraint then the page size is not
 70916  ** changed.
 70917  **
 70918  ** Page sizes are constrained to be a power of two so that the region
 70919  ** of the database file used for locking (beginning at PENDING_BYTE,
 70920  ** the first byte past the 1GB boundary, 0x40000000) needs to occur
 70921  ** at the beginning of a page.
 70922  **
 70923  ** If parameter nReserve is less than zero, then the number of reserved
 70924  ** bytes per page is left unchanged.
 70925  **
 70926  ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
 70927  ** and autovacuum mode can no longer be changed.
 70928  */
 70929  SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
 70930    int rc = SQLITE_OK;
 70931    BtShared *pBt = p->pBt;
 70932    assert( nReserve>=-1 && nReserve<=255 );
 70933    sqlite3BtreeEnter(p);
 70934  #if SQLITE_HAS_CODEC
 70935    if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
 70936  #endif
 70937    if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
 70938      sqlite3BtreeLeave(p);
 70939      return SQLITE_READONLY;
 70940    }
 70941    if( nReserve<0 ){
 70942      nReserve = pBt->pageSize - pBt->usableSize;
 70943    }
 70944    assert( nReserve>=0 && nReserve<=255 );
 70945    if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
 70946          ((pageSize-1)&pageSize)==0 ){
 70947      assert( (pageSize & 7)==0 );
 70948      assert( !pBt->pCursor );
 70949      pBt->pageSize = (u32)pageSize;
 70950      freeTempSpace(pBt);
 70951    }
 70952    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
 70953    pBt->usableSize = pBt->pageSize - (u16)nReserve;
 70954    if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 70955    sqlite3BtreeLeave(p);
 70956    return rc;
 70957  }
 70958  
 70959  /*
 70960  ** Return the currently defined page size
 70961  */
 70962  SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
 70963    return p->pBt->pageSize;
 70964  }
 70965  
 70966  /*
 70967  ** This function is similar to sqlite3BtreeGetReserve(), except that it
 70968  ** may only be called if it is guaranteed that the b-tree mutex is already
 70969  ** held.
 70970  **
 70971  ** This is useful in one special case in the backup API code where it is
 70972  ** known that the shared b-tree mutex is held, but the mutex on the 
 70973  ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
 70974  ** were to be called, it might collide with some other operation on the
 70975  ** database handle that owns *p, causing undefined behavior.
 70976  */
 70977  SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
 70978    int n;
 70979    assert( sqlite3_mutex_held(p->pBt->mutex) );
 70980    n = p->pBt->pageSize - p->pBt->usableSize;
 70981    return n;
 70982  }
 70983  
 70984  /*
 70985  ** Return the number of bytes of space at the end of every page that
 70986  ** are intentually left unused.  This is the "reserved" space that is
 70987  ** sometimes used by extensions.
 70988  **
 70989  ** If SQLITE_HAS_MUTEX is defined then the number returned is the
 70990  ** greater of the current reserved space and the maximum requested
 70991  ** reserve space.
 70992  */
 70993  SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
 70994    int n;
 70995    sqlite3BtreeEnter(p);
 70996    n = sqlite3BtreeGetReserveNoMutex(p);
 70997  #ifdef SQLITE_HAS_CODEC
 70998    if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
 70999  #endif
 71000    sqlite3BtreeLeave(p);
 71001    return n;
 71002  }
 71003  
 71004  
 71005  /*
 71006  ** Set the maximum page count for a database if mxPage is positive.
 71007  ** No changes are made if mxPage is 0 or negative.
 71008  ** Regardless of the value of mxPage, return the maximum page count.
 71009  */
 71010  SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
 71011    int n;
 71012    sqlite3BtreeEnter(p);
 71013    n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
 71014    sqlite3BtreeLeave(p);
 71015    return n;
 71016  }
 71017  
 71018  /*
 71019  ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
 71020  **
 71021  **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
 71022  **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
 71023  **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
 71024  **    newFlag==(-1)    No changes
 71025  **
 71026  ** This routine acts as a query if newFlag is less than zero
 71027  **
 71028  ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
 71029  ** freelist leaf pages are not written back to the database.  Thus in-page
 71030  ** deleted content is cleared, but freelist deleted content is not.
 71031  **
 71032  ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
 71033  ** that freelist leaf pages are written back into the database, increasing
 71034  ** the amount of disk I/O.
 71035  */
 71036  SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
 71037    int b;
 71038    if( p==0 ) return 0;
 71039    sqlite3BtreeEnter(p);
 71040    assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
 71041    assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
 71042    if( newFlag>=0 ){
 71043      p->pBt->btsFlags &= ~BTS_FAST_SECURE;
 71044      p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
 71045    }
 71046    b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
 71047    sqlite3BtreeLeave(p);
 71048    return b;
 71049  }
 71050  
 71051  /*
 71052  ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
 71053  ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
 71054  ** is disabled. The default value for the auto-vacuum property is 
 71055  ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
 71056  */
 71057  SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
 71058  #ifdef SQLITE_OMIT_AUTOVACUUM
 71059    return SQLITE_READONLY;
 71060  #else
 71061    BtShared *pBt = p->pBt;
 71062    int rc = SQLITE_OK;
 71063    u8 av = (u8)autoVacuum;
 71064  
 71065    sqlite3BtreeEnter(p);
 71066    if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
 71067      rc = SQLITE_READONLY;
 71068    }else{
 71069      pBt->autoVacuum = av ?1:0;
 71070      pBt->incrVacuum = av==2 ?1:0;
 71071    }
 71072    sqlite3BtreeLeave(p);
 71073    return rc;
 71074  #endif
 71075  }
 71076  
 71077  /*
 71078  ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
 71079  ** enabled 1 is returned. Otherwise 0.
 71080  */
 71081  SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
 71082  #ifdef SQLITE_OMIT_AUTOVACUUM
 71083    return BTREE_AUTOVACUUM_NONE;
 71084  #else
 71085    int rc;
 71086    sqlite3BtreeEnter(p);
 71087    rc = (
 71088      (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
 71089      (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
 71090      BTREE_AUTOVACUUM_INCR
 71091    );
 71092    sqlite3BtreeLeave(p);
 71093    return rc;
 71094  #endif
 71095  }
 71096  
 71097  /*
 71098  ** If the user has not set the safety-level for this database connection
 71099  ** using "PRAGMA synchronous", and if the safety-level is not already
 71100  ** set to the value passed to this function as the second parameter,
 71101  ** set it so.
 71102  */
 71103  #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
 71104      && !defined(SQLITE_OMIT_WAL)
 71105  static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
 71106    sqlite3 *db;
 71107    Db *pDb;
 71108    if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
 71109      while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
 71110      if( pDb->bSyncSet==0 
 71111       && pDb->safety_level!=safety_level 
 71112       && pDb!=&db->aDb[1] 
 71113      ){
 71114        pDb->safety_level = safety_level;
 71115        sqlite3PagerSetFlags(pBt->pPager,
 71116            pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
 71117      }
 71118    }
 71119  }
 71120  #else
 71121  # define setDefaultSyncFlag(pBt,safety_level)
 71122  #endif
 71123  
 71124  /* Forward declaration */
 71125  static int newDatabase(BtShared*);
 71126  
 71127  
 71128  /*
 71129  ** Get a reference to pPage1 of the database file.  This will
 71130  ** also acquire a readlock on that file.
 71131  **
 71132  ** SQLITE_OK is returned on success.  If the file is not a
 71133  ** well-formed database file, then SQLITE_CORRUPT is returned.
 71134  ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
 71135  ** is returned if we run out of memory. 
 71136  */
 71137  static int lockBtree(BtShared *pBt){
 71138    int rc;              /* Result code from subfunctions */
 71139    MemPage *pPage1;     /* Page 1 of the database file */
 71140    u32 nPage;           /* Number of pages in the database */
 71141    u32 nPageFile = 0;   /* Number of pages in the database file */
 71142    u32 nPageHeader;     /* Number of pages in the database according to hdr */
 71143  
 71144    BRANCHTRACE("lockBtree");
 71145  
 71146    assert( sqlite3_mutex_held(pBt->mutex) );
 71147    assert( pBt->pPage1==0 );
 71148    rc = sqlite3PagerSharedLock(pBt->pPager);
 71149    if( rc!=SQLITE_OK ) return rc;
 71150    rc = btreeGetPage(pBt, 1, &pPage1, 0);
 71151    if( rc!=SQLITE_OK ) return rc;
 71152  
 71153    /* Do some checking to help insure the file we opened really is
 71154    ** a valid database file. 
 71155    */
 71156    nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
 71157    sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
 71158    if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
 71159      nPage = nPageFile;
 71160    }
 71161    if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
 71162      nPage = 0;
 71163    }
 71164    if( nPage>0 ){
 71165      u32 pageSize;
 71166      u32 usableSize;
 71167      u8 *page1 = pPage1->aData;
 71168      rc = SQLITE_NOTADB;
 71169      /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
 71170      ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
 71171      ** 61 74 20 33 00. */
 71172      if( memcmp(page1, zMagicHeader, 16)!=0 ){
 71173        goto page1_init_failed;
 71174      }
 71175  
 71176  #ifdef SQLITE_OMIT_WAL
 71177      if( page1[18]>1 ){
 71178        pBt->btsFlags |= BTS_READ_ONLY;
 71179      }
 71180      if( page1[19]>1 ){
 71181        goto page1_init_failed;
 71182      }
 71183  #else
 71184      if( page1[18]>2 ){
 71185        pBt->btsFlags |= BTS_READ_ONLY;
 71186      }
 71187      if( page1[19]>2 ){
 71188        goto page1_init_failed;
 71189      }
 71190  
 71191      /* If the write version is set to 2, this database should be accessed
 71192      ** in WAL mode. If the log is not already open, open it now. Then 
 71193      ** return SQLITE_OK and return without populating BtShared.pPage1.
 71194      ** The caller detects this and calls this function again. This is
 71195      ** required as the version of page 1 currently in the page1 buffer
 71196      ** may not be the latest version - there may be a newer one in the log
 71197      ** file.
 71198      */
 71199      if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
 71200        int isOpen = 0;
 71201        rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
 71202        if( rc!=SQLITE_OK ){
 71203          goto page1_init_failed;
 71204        }else{
 71205          setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
 71206          if( isOpen==0 ){
 71207            releasePageOne(pPage1);
 71208            return SQLITE_OK;
 71209          }
 71210        }
 71211        rc = SQLITE_NOTADB;
 71212      }else{
 71213        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
 71214      }
 71215  #endif
 71216  
 71217      /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
 71218      ** fractions and the leaf payload fraction values must be 64, 32, and 32.
 71219      **
 71220      ** The original design allowed these amounts to vary, but as of
 71221      ** version 3.6.0, we require them to be fixed.
 71222      */
 71223      if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
 71224        goto page1_init_failed;
 71225      }
 71226      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
 71227      ** determined by the 2-byte integer located at an offset of 16 bytes from
 71228      ** the beginning of the database file. */
 71229      pageSize = (page1[16]<<8) | (page1[17]<<16);
 71230      /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
 71231      ** between 512 and 65536 inclusive. */
 71232      if( ((pageSize-1)&pageSize)!=0
 71233       || pageSize>SQLITE_MAX_PAGE_SIZE 
 71234       || pageSize<=256 
 71235      ){
 71236        goto page1_init_failed;
 71237      }
 71238      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 71239      assert( (pageSize & 7)==0 );
 71240      /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
 71241      ** integer at offset 20 is the number of bytes of space at the end of
 71242      ** each page to reserve for extensions. 
 71243      **
 71244      ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
 71245      ** determined by the one-byte unsigned integer found at an offset of 20
 71246      ** into the database file header. */
 71247      usableSize = pageSize - page1[20];
 71248      if( (u32)pageSize!=pBt->pageSize ){
 71249        /* After reading the first page of the database assuming a page size
 71250        ** of BtShared.pageSize, we have discovered that the page-size is
 71251        ** actually pageSize. Unlock the database, leave pBt->pPage1 at
 71252        ** zero and return SQLITE_OK. The caller will call this function
 71253        ** again with the correct page-size.
 71254        */
 71255        releasePageOne(pPage1);
 71256        pBt->usableSize = usableSize;
 71257        pBt->pageSize = pageSize;
 71258        freeTempSpace(pBt);
 71259        rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
 71260                                     pageSize-usableSize);
 71261        return rc;
 71262      }
 71263      if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
 71264        rc = SQLITE_CORRUPT_BKPT;
 71265        goto page1_init_failed;
 71266      }
 71267      /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
 71268      ** be less than 480. In other words, if the page size is 512, then the
 71269      ** reserved space size cannot exceed 32. */
 71270      if( usableSize<480 ){
 71271        goto page1_init_failed;
 71272      }
 71273      pBt->pageSize = pageSize;
 71274      pBt->usableSize = usableSize;
 71275  #ifndef SQLITE_OMIT_AUTOVACUUM
 71276      pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
 71277      pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
 71278  #endif
 71279    }
 71280  
 71281    /* maxLocal is the maximum amount of payload to store locally for
 71282    ** a cell.  Make sure it is small enough so that at least minFanout
 71283    ** cells can will fit on one page.  We assume a 10-byte page header.
 71284    ** Besides the payload, the cell must store:
 71285    **     2-byte pointer to the cell
 71286    **     4-byte child pointer
 71287    **     9-byte nKey value
 71288    **     4-byte nData value
 71289    **     4-byte overflow page pointer
 71290    ** So a cell consists of a 2-byte pointer, a header which is as much as
 71291    ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
 71292    ** page pointer.
 71293    */
 71294    pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
 71295    pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
 71296    pBt->maxLeaf = (u16)(pBt->usableSize - 35);
 71297    pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
 71298    if( pBt->maxLocal>127 ){
 71299      pBt->max1bytePayload = 127;
 71300    }else{
 71301      pBt->max1bytePayload = (u8)pBt->maxLocal;
 71302    }
 71303    assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
 71304    pBt->pPage1 = pPage1;
 71305    pBt->nPage = nPage;
 71306    return SQLITE_OK;
 71307  
 71308  page1_init_failed:
 71309    releasePageOne(pPage1);
 71310    pBt->pPage1 = 0;
 71311    return rc;
 71312  }
 71313  
 71314  #ifndef NDEBUG
 71315  /*
 71316  ** Return the number of cursors open on pBt. This is for use
 71317  ** in assert() expressions, so it is only compiled if NDEBUG is not
 71318  ** defined.
 71319  **
 71320  ** Only write cursors are counted if wrOnly is true.  If wrOnly is
 71321  ** false then all cursors are counted.
 71322  **
 71323  ** For the purposes of this routine, a cursor is any cursor that
 71324  ** is capable of reading or writing to the database.  Cursors that
 71325  ** have been tripped into the CURSOR_FAULT state are not counted.
 71326  */
 71327  static int countValidCursors(BtShared *pBt, int wrOnly){
 71328    BtCursor *pCur;
 71329    int r = 0;
 71330    for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
 71331      if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
 71332       && pCur->eState!=CURSOR_FAULT ) r++; 
 71333    }
 71334    return r;
 71335  }
 71336  #endif
 71337  
 71338  /*
 71339  ** If there are no outstanding cursors and we are not in the middle
 71340  ** of a transaction but there is a read lock on the database, then
 71341  ** this routine unrefs the first page of the database file which 
 71342  ** has the effect of releasing the read lock.
 71343  **
 71344  ** If there is a transaction in progress, this routine is a no-op.
 71345  */
 71346  static void unlockBtreeIfUnused(BtShared *pBt){
 71347    assert( sqlite3_mutex_held(pBt->mutex) );
 71348    assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
 71349    if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
 71350      MemPage *pPage1 = pBt->pPage1;
 71351      assert( pPage1->aData );
 71352      assert( sqlite3PagerRefcount(pBt->pPager)==1 );
 71353      pBt->pPage1 = 0;
 71354      releasePageOne(pPage1);
 71355    }
 71356  }
 71357  
 71358  /*
 71359  ** If pBt points to an empty file then convert that empty file
 71360  ** into a new empty database by initializing the first page of
 71361  ** the database.
 71362  */
 71363  static int newDatabase(BtShared *pBt){
 71364    MemPage *pP1;
 71365    unsigned char *data;
 71366    int rc;
 71367  
 71368    assert( sqlite3_mutex_held(pBt->mutex) );
 71369    if( pBt->nPage>0 ){
 71370      return SQLITE_OK;
 71371    }
 71372    pP1 = pBt->pPage1;
 71373    assert( pP1!=0 );
 71374    data = pP1->aData;
 71375    rc = sqlite3PagerWrite(pP1->pDbPage);
 71376    if( rc ) return rc;
 71377    memcpy(data, zMagicHeader, sizeof(zMagicHeader));
 71378    assert( sizeof(zMagicHeader)==16 );
 71379    data[16] = (u8)((pBt->pageSize>>8)&0xff);
 71380    data[17] = (u8)((pBt->pageSize>>16)&0xff);
 71381    data[18] = 1;
 71382    data[19] = 1;
 71383    assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
 71384    data[20] = (u8)(pBt->pageSize - pBt->usableSize);
 71385    data[21] = 64;
 71386    data[22] = 32;
 71387    data[23] = 32;
 71388    memset(&data[24], 0, 100-24);
 71389    zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
 71390    pBt->btsFlags |= BTS_PAGESIZE_FIXED;
 71391  #ifndef SQLITE_OMIT_AUTOVACUUM
 71392    assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
 71393    assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
 71394    put4byte(&data[36 + 4*4], pBt->autoVacuum);
 71395    put4byte(&data[36 + 7*4], pBt->incrVacuum);
 71396  #endif
 71397    pBt->nPage = 1;
 71398    data[31] = 1;
 71399    return SQLITE_OK;
 71400  }
 71401  
 71402  /*
 71403  ** Initialize the first page of the database file (creating a database
 71404  ** consisting of a single page and no schema objects). Return SQLITE_OK
 71405  ** if successful, or an SQLite error code otherwise.
 71406  */
 71407  SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 71408    int rc;
 71409    sqlite3BtreeEnter(p);
 71410    p->pBt->nPage = 0;
 71411    rc = newDatabase(p->pBt);
 71412    sqlite3BtreeLeave(p);
 71413    return rc;
 71414  }
 71415  
 71416  /*
 71417  ** Attempt to start a new transaction. A write-transaction
 71418  ** is started if the second argument is nonzero, otherwise a read-
 71419  ** transaction.  If the second argument is 2 or more and exclusive
 71420  ** transaction is started, meaning that no other process is allowed
 71421  ** to access the database.  A preexisting transaction may not be
 71422  ** upgraded to exclusive by calling this routine a second time - the
 71423  ** exclusivity flag only works for a new transaction.
 71424  **
 71425  ** A write-transaction must be started before attempting any 
 71426  ** changes to the database.  None of the following routines 
 71427  ** will work unless a transaction is started first:
 71428  **
 71429  **      sqlite3BtreeCreateTable()
 71430  **      sqlite3BtreeCreateIndex()
 71431  **      sqlite3BtreeClearTable()
 71432  **      sqlite3BtreeDropTable()
 71433  **      sqlite3BtreeInsert()
 71434  **      sqlite3BtreeDelete()
 71435  **      sqlite3BtreeUpdateMeta()
 71436  **
 71437  ** If an initial attempt to acquire the lock fails because of lock contention
 71438  ** and the database was previously unlocked, then invoke the busy handler
 71439  ** if there is one.  But if there was previously a read-lock, do not
 71440  ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
 71441  ** returned when there is already a read-lock in order to avoid a deadlock.
 71442  **
 71443  ** Suppose there are two processes A and B.  A has a read lock and B has
 71444  ** a reserved lock.  B tries to promote to exclusive but is blocked because
 71445  ** of A's read lock.  A tries to promote to reserved but is blocked by B.
 71446  ** One or the other of the two processes must give way or there can be
 71447  ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
 71448  ** when A already has a read lock, we encourage A to give up and let B
 71449  ** proceed.
 71450  */
 71451  SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
 71452    BtShared *pBt = p->pBt;
 71453    int rc = SQLITE_OK;
 71454  
 71455    sqlite3BtreeEnter(p);
 71456    btreeIntegrity(p);
 71457  
 71458    /* If the btree is already in a write-transaction, or it
 71459    ** is already in a read-transaction and a read-transaction
 71460    ** is requested, this is a no-op.
 71461    */
 71462    if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
 71463      goto trans_begun;
 71464    }
 71465    assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
 71466  
 71467    if( (p->db->flags & SQLITE_ResetDatabase) 
 71468     && sqlite3PagerIsreadonly(pBt->pPager)==0 
 71469    ){
 71470      pBt->btsFlags &= ~BTS_READ_ONLY;
 71471    }
 71472  
 71473    /* Write transactions are not possible on a read-only database */
 71474    if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
 71475      rc = SQLITE_READONLY;
 71476      goto trans_begun;
 71477    }
 71478  
 71479  #ifndef SQLITE_OMIT_SHARED_CACHE
 71480    {
 71481      sqlite3 *pBlock = 0;
 71482      /* If another database handle has already opened a write transaction 
 71483      ** on this shared-btree structure and a second write transaction is
 71484      ** requested, return SQLITE_LOCKED.
 71485      */
 71486      if( (wrflag && pBt->inTransaction==TRANS_WRITE)
 71487       || (pBt->btsFlags & BTS_PENDING)!=0
 71488      ){
 71489        pBlock = pBt->pWriter->db;
 71490      }else if( wrflag>1 ){
 71491        BtLock *pIter;
 71492        for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
 71493          if( pIter->pBtree!=p ){
 71494            pBlock = pIter->pBtree->db;
 71495            break;
 71496          }
 71497        }
 71498      }
 71499      if( pBlock ){
 71500        sqlite3ConnectionBlocked(p->db, pBlock);
 71501        rc = SQLITE_LOCKED_SHAREDCACHE;
 71502        goto trans_begun;
 71503      }
 71504    }
 71505  #endif
 71506  
 71507    /* Any read-only or read-write transaction implies a read-lock on 
 71508    ** page 1. So if some other shared-cache client already has a write-lock 
 71509    ** on page 1, the transaction cannot be opened. */
 71510    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 71511    if( SQLITE_OK!=rc ) goto trans_begun;
 71512  
 71513    pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
 71514    if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
 71515    do {
 71516      /* Call lockBtree() until either pBt->pPage1 is populated or
 71517      ** lockBtree() returns something other than SQLITE_OK. lockBtree()
 71518      ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
 71519      ** reading page 1 it discovers that the page-size of the database 
 71520      ** file is not pBt->pageSize. In this case lockBtree() will update
 71521      ** pBt->pageSize to the page-size of the file on disk.
 71522      */
 71523      while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
 71524  
 71525      if( rc==SQLITE_OK && wrflag ){
 71526        if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
 71527          rc = SQLITE_READONLY;
 71528        }else{
 71529          rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
 71530          if( rc==SQLITE_OK ){
 71531            rc = newDatabase(pBt);
 71532          }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
 71533            /* if there was no transaction opened when this function was
 71534            ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
 71535            ** code to SQLITE_BUSY. */
 71536            rc = SQLITE_BUSY;
 71537          }
 71538        }
 71539      }
 71540    
 71541      if( rc!=SQLITE_OK ){
 71542        unlockBtreeIfUnused(pBt);
 71543      }
 71544    }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
 71545            btreeInvokeBusyHandler(pBt) );
 71546    sqlite3PagerResetLockTimeout(pBt->pPager);
 71547  
 71548    if( rc==SQLITE_OK ){
 71549      if( p->inTrans==TRANS_NONE ){
 71550        pBt->nTransaction++;
 71551  #ifndef SQLITE_OMIT_SHARED_CACHE
 71552        if( p->sharable ){
 71553          assert( p->lock.pBtree==p && p->lock.iTable==1 );
 71554          p->lock.eLock = READ_LOCK;
 71555          p->lock.pNext = pBt->pLock;
 71556          pBt->pLock = &p->lock;
 71557        }
 71558  #endif
 71559      }
 71560      p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
 71561      if( p->inTrans>pBt->inTransaction ){
 71562        pBt->inTransaction = p->inTrans;
 71563      }
 71564      if( wrflag ){
 71565        MemPage *pPage1 = pBt->pPage1;
 71566  #ifndef SQLITE_OMIT_SHARED_CACHE
 71567        assert( !pBt->pWriter );
 71568        pBt->pWriter = p;
 71569        pBt->btsFlags &= ~BTS_EXCLUSIVE;
 71570        if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
 71571  #endif
 71572  
 71573        /* If the db-size header field is incorrect (as it may be if an old
 71574        ** client has been writing the database file), update it now. Doing
 71575        ** this sooner rather than later means the database size can safely 
 71576        ** re-read the database size from page 1 if a savepoint or transaction
 71577        ** rollback occurs within the transaction.
 71578        */
 71579        if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
 71580          rc = sqlite3PagerWrite(pPage1->pDbPage);
 71581          if( rc==SQLITE_OK ){
 71582            put4byte(&pPage1->aData[28], pBt->nPage);
 71583          }
 71584        }
 71585      }
 71586    }
 71587  
 71588  trans_begun:
 71589    if( rc==SQLITE_OK ){
 71590      if( pSchemaVersion ){
 71591        *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
 71592      }
 71593      if( wrflag ){
 71594        /* This call makes sure that the pager has the correct number of
 71595        ** open savepoints. If the second parameter is greater than 0 and
 71596        ** the sub-journal is not already open, then it will be opened here.
 71597        */
 71598        rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
 71599      }
 71600    }
 71601  
 71602    btreeIntegrity(p);
 71603    sqlite3BtreeLeave(p);
 71604    return rc;
 71605  }
 71606  
 71607  #ifndef SQLITE_OMIT_AUTOVACUUM
 71608  
 71609  /*
 71610  ** Set the pointer-map entries for all children of page pPage. Also, if
 71611  ** pPage contains cells that point to overflow pages, set the pointer
 71612  ** map entries for the overflow pages as well.
 71613  */
 71614  static int setChildPtrmaps(MemPage *pPage){
 71615    int i;                             /* Counter variable */
 71616    int nCell;                         /* Number of cells in page pPage */
 71617    int rc;                            /* Return code */
 71618    BtShared *pBt = pPage->pBt;
 71619    Pgno pgno = pPage->pgno;
 71620  
 71621    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 71622    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
 71623    if( rc!=SQLITE_OK ) return rc;
 71624    nCell = pPage->nCell;
 71625  
 71626    for(i=0; i<nCell; i++){
 71627      u8 *pCell = findCell(pPage, i);
 71628  
 71629      ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
 71630  
 71631      if( !pPage->leaf ){
 71632        Pgno childPgno = get4byte(pCell);
 71633        ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 71634      }
 71635    }
 71636  
 71637    if( !pPage->leaf ){
 71638      Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 71639      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
 71640    }
 71641  
 71642    return rc;
 71643  }
 71644  
 71645  /*
 71646  ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
 71647  ** that it points to iTo. Parameter eType describes the type of pointer to
 71648  ** be modified, as  follows:
 71649  **
 71650  ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
 71651  **                   page of pPage.
 71652  **
 71653  ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
 71654  **                   page pointed to by one of the cells on pPage.
 71655  **
 71656  ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
 71657  **                   overflow page in the list.
 71658  */
 71659  static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
 71660    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 71661    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 71662    if( eType==PTRMAP_OVERFLOW2 ){
 71663      /* The pointer is always the first 4 bytes of the page in this case.  */
 71664      if( get4byte(pPage->aData)!=iFrom ){
 71665        return SQLITE_CORRUPT_PAGE(pPage);
 71666      }
 71667      put4byte(pPage->aData, iTo);
 71668    }else{
 71669      int i;
 71670      int nCell;
 71671      int rc;
 71672  
 71673      rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
 71674      if( rc ) return rc;
 71675      nCell = pPage->nCell;
 71676  
 71677      for(i=0; i<nCell; i++){
 71678        u8 *pCell = findCell(pPage, i);
 71679        if( eType==PTRMAP_OVERFLOW1 ){
 71680          CellInfo info;
 71681          pPage->xParseCell(pPage, pCell, &info);
 71682          if( info.nLocal<info.nPayload ){
 71683            if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
 71684              return SQLITE_CORRUPT_PAGE(pPage);
 71685            }
 71686            if( iFrom==get4byte(pCell+info.nSize-4) ){
 71687              put4byte(pCell+info.nSize-4, iTo);
 71688              break;
 71689            }
 71690          }
 71691        }else{
 71692          if( get4byte(pCell)==iFrom ){
 71693            put4byte(pCell, iTo);
 71694            break;
 71695          }
 71696        }
 71697      }
 71698    
 71699      if( i==nCell ){
 71700        if( eType!=PTRMAP_BTREE || 
 71701            get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
 71702          return SQLITE_CORRUPT_PAGE(pPage);
 71703        }
 71704        put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
 71705      }
 71706    }
 71707    return SQLITE_OK;
 71708  }
 71709  
 71710  
 71711  /*
 71712  ** Move the open database page pDbPage to location iFreePage in the 
 71713  ** database. The pDbPage reference remains valid.
 71714  **
 71715  ** The isCommit flag indicates that there is no need to remember that
 71716  ** the journal needs to be sync()ed before database page pDbPage->pgno 
 71717  ** can be written to. The caller has already promised not to write to that
 71718  ** page.
 71719  */
 71720  static int relocatePage(
 71721    BtShared *pBt,           /* Btree */
 71722    MemPage *pDbPage,        /* Open page to move */
 71723    u8 eType,                /* Pointer map 'type' entry for pDbPage */
 71724    Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
 71725    Pgno iFreePage,          /* The location to move pDbPage to */
 71726    int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
 71727  ){
 71728    MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
 71729    Pgno iDbPage = pDbPage->pgno;
 71730    Pager *pPager = pBt->pPager;
 71731    int rc;
 71732  
 71733    assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
 71734        eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
 71735    assert( sqlite3_mutex_held(pBt->mutex) );
 71736    assert( pDbPage->pBt==pBt );
 71737    if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
 71738  
 71739    /* Move page iDbPage from its current location to page number iFreePage */
 71740    TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
 71741        iDbPage, iFreePage, iPtrPage, eType));
 71742    rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
 71743    if( rc!=SQLITE_OK ){
 71744      return rc;
 71745    }
 71746    pDbPage->pgno = iFreePage;
 71747  
 71748    /* If pDbPage was a btree-page, then it may have child pages and/or cells
 71749    ** that point to overflow pages. The pointer map entries for all these
 71750    ** pages need to be changed.
 71751    **
 71752    ** If pDbPage is an overflow page, then the first 4 bytes may store a
 71753    ** pointer to a subsequent overflow page. If this is the case, then
 71754    ** the pointer map needs to be updated for the subsequent overflow page.
 71755    */
 71756    if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
 71757      rc = setChildPtrmaps(pDbPage);
 71758      if( rc!=SQLITE_OK ){
 71759        return rc;
 71760      }
 71761    }else{
 71762      Pgno nextOvfl = get4byte(pDbPage->aData);
 71763      if( nextOvfl!=0 ){
 71764        ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
 71765        if( rc!=SQLITE_OK ){
 71766          return rc;
 71767        }
 71768      }
 71769    }
 71770  
 71771    /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
 71772    ** that it points at iFreePage. Also fix the pointer map entry for
 71773    ** iPtrPage.
 71774    */
 71775    if( eType!=PTRMAP_ROOTPAGE ){
 71776      rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
 71777      if( rc!=SQLITE_OK ){
 71778        return rc;
 71779      }
 71780      rc = sqlite3PagerWrite(pPtrPage->pDbPage);
 71781      if( rc!=SQLITE_OK ){
 71782        releasePage(pPtrPage);
 71783        return rc;
 71784      }
 71785      rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
 71786      releasePage(pPtrPage);
 71787      if( rc==SQLITE_OK ){
 71788        ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
 71789      }
 71790    }
 71791    return rc;
 71792  }
 71793  
 71794  /* Forward declaration required by incrVacuumStep(). */
 71795  static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
 71796  
 71797  /*
 71798  ** Perform a single step of an incremental-vacuum. If successful, return
 71799  ** SQLITE_OK. If there is no work to do (and therefore no point in 
 71800  ** calling this function again), return SQLITE_DONE. Or, if an error 
 71801  ** occurs, return some other error code.
 71802  **
 71803  ** More specifically, this function attempts to re-organize the database so 
 71804  ** that the last page of the file currently in use is no longer in use.
 71805  **
 71806  ** Parameter nFin is the number of pages that this database would contain
 71807  ** were this function called until it returns SQLITE_DONE.
 71808  **
 71809  ** If the bCommit parameter is non-zero, this function assumes that the 
 71810  ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
 71811  ** or an error. bCommit is passed true for an auto-vacuum-on-commit 
 71812  ** operation, or false for an incremental vacuum.
 71813  */
 71814  static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
 71815    Pgno nFreeList;           /* Number of pages still on the free-list */
 71816    int rc;
 71817  
 71818    assert( sqlite3_mutex_held(pBt->mutex) );
 71819    assert( iLastPg>nFin );
 71820  
 71821    if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
 71822      u8 eType;
 71823      Pgno iPtrPage;
 71824  
 71825      nFreeList = get4byte(&pBt->pPage1->aData[36]);
 71826      if( nFreeList==0 ){
 71827        return SQLITE_DONE;
 71828      }
 71829  
 71830      rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
 71831      if( rc!=SQLITE_OK ){
 71832        return rc;
 71833      }
 71834      if( eType==PTRMAP_ROOTPAGE ){
 71835        return SQLITE_CORRUPT_BKPT;
 71836      }
 71837  
 71838      if( eType==PTRMAP_FREEPAGE ){
 71839        if( bCommit==0 ){
 71840          /* Remove the page from the files free-list. This is not required
 71841          ** if bCommit is non-zero. In that case, the free-list will be
 71842          ** truncated to zero after this function returns, so it doesn't 
 71843          ** matter if it still contains some garbage entries.
 71844          */
 71845          Pgno iFreePg;
 71846          MemPage *pFreePg;
 71847          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
 71848          if( rc!=SQLITE_OK ){
 71849            return rc;
 71850          }
 71851          assert( iFreePg==iLastPg );
 71852          releasePage(pFreePg);
 71853        }
 71854      } else {
 71855        Pgno iFreePg;             /* Index of free page to move pLastPg to */
 71856        MemPage *pLastPg;
 71857        u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
 71858        Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
 71859  
 71860        rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
 71861        if( rc!=SQLITE_OK ){
 71862          return rc;
 71863        }
 71864  
 71865        /* If bCommit is zero, this loop runs exactly once and page pLastPg
 71866        ** is swapped with the first free page pulled off the free list.
 71867        **
 71868        ** On the other hand, if bCommit is greater than zero, then keep
 71869        ** looping until a free-page located within the first nFin pages
 71870        ** of the file is found.
 71871        */
 71872        if( bCommit==0 ){
 71873          eMode = BTALLOC_LE;
 71874          iNear = nFin;
 71875        }
 71876        do {
 71877          MemPage *pFreePg;
 71878          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
 71879          if( rc!=SQLITE_OK ){
 71880            releasePage(pLastPg);
 71881            return rc;
 71882          }
 71883          releasePage(pFreePg);
 71884        }while( bCommit && iFreePg>nFin );
 71885        assert( iFreePg<iLastPg );
 71886        
 71887        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
 71888        releasePage(pLastPg);
 71889        if( rc!=SQLITE_OK ){
 71890          return rc;
 71891        }
 71892      }
 71893    }
 71894  
 71895    if( bCommit==0 ){
 71896      do {
 71897        iLastPg--;
 71898      }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
 71899      pBt->bDoTruncate = 1;
 71900      pBt->nPage = iLastPg;
 71901    }
 71902    return SQLITE_OK;
 71903  }
 71904  
 71905  /*
 71906  ** The database opened by the first argument is an auto-vacuum database
 71907  ** nOrig pages in size containing nFree free pages. Return the expected 
 71908  ** size of the database in pages following an auto-vacuum operation.
 71909  */
 71910  static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
 71911    int nEntry;                     /* Number of entries on one ptrmap page */
 71912    Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
 71913    Pgno nFin;                      /* Return value */
 71914  
 71915    nEntry = pBt->usableSize/5;
 71916    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
 71917    nFin = nOrig - nFree - nPtrmap;
 71918    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
 71919      nFin--;
 71920    }
 71921    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
 71922      nFin--;
 71923    }
 71924  
 71925    return nFin;
 71926  }
 71927  
 71928  /*
 71929  ** A write-transaction must be opened before calling this function.
 71930  ** It performs a single unit of work towards an incremental vacuum.
 71931  **
 71932  ** If the incremental vacuum is finished after this function has run,
 71933  ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
 71934  ** SQLITE_OK is returned. Otherwise an SQLite error code. 
 71935  */
 71936  SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
 71937    int rc;
 71938    BtShared *pBt = p->pBt;
 71939  
 71940    sqlite3BtreeEnter(p);
 71941    assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
 71942    if( !pBt->autoVacuum ){
 71943      rc = SQLITE_DONE;
 71944    }else{
 71945      Pgno nOrig = btreePagecount(pBt);
 71946      Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
 71947      Pgno nFin = finalDbSize(pBt, nOrig, nFree);
 71948  
 71949      if( nOrig<nFin ){
 71950        rc = SQLITE_CORRUPT_BKPT;
 71951      }else if( nFree>0 ){
 71952        rc = saveAllCursors(pBt, 0, 0);
 71953        if( rc==SQLITE_OK ){
 71954          invalidateAllOverflowCache(pBt);
 71955          rc = incrVacuumStep(pBt, nFin, nOrig, 0);
 71956        }
 71957        if( rc==SQLITE_OK ){
 71958          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 71959          put4byte(&pBt->pPage1->aData[28], pBt->nPage);
 71960        }
 71961      }else{
 71962        rc = SQLITE_DONE;
 71963      }
 71964    }
 71965    sqlite3BtreeLeave(p);
 71966    return rc;
 71967  }
 71968  
 71969  /*
 71970  ** This routine is called prior to sqlite3PagerCommit when a transaction
 71971  ** is committed for an auto-vacuum database.
 71972  **
 71973  ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
 71974  ** the database file should be truncated to during the commit process. 
 71975  ** i.e. the database has been reorganized so that only the first *pnTrunc
 71976  ** pages are in use.
 71977  */
 71978  static int autoVacuumCommit(BtShared *pBt){
 71979    int rc = SQLITE_OK;
 71980    Pager *pPager = pBt->pPager;
 71981    VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
 71982  
 71983    assert( sqlite3_mutex_held(pBt->mutex) );
 71984    invalidateAllOverflowCache(pBt);
 71985    assert(pBt->autoVacuum);
 71986    if( !pBt->incrVacuum ){
 71987      Pgno nFin;         /* Number of pages in database after autovacuuming */
 71988      Pgno nFree;        /* Number of pages on the freelist initially */
 71989      Pgno iFree;        /* The next page to be freed */
 71990      Pgno nOrig;        /* Database size before freeing */
 71991  
 71992      nOrig = btreePagecount(pBt);
 71993      if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
 71994        /* It is not possible to create a database for which the final page
 71995        ** is either a pointer-map page or the pending-byte page. If one
 71996        ** is encountered, this indicates corruption.
 71997        */
 71998        return SQLITE_CORRUPT_BKPT;
 71999      }
 72000  
 72001      nFree = get4byte(&pBt->pPage1->aData[36]);
 72002      nFin = finalDbSize(pBt, nOrig, nFree);
 72003      if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
 72004      if( nFin<nOrig ){
 72005        rc = saveAllCursors(pBt, 0, 0);
 72006      }
 72007      for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
 72008        rc = incrVacuumStep(pBt, nFin, iFree, 1);
 72009      }
 72010      if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
 72011        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 72012        put4byte(&pBt->pPage1->aData[32], 0);
 72013        put4byte(&pBt->pPage1->aData[36], 0);
 72014        put4byte(&pBt->pPage1->aData[28], nFin);
 72015        pBt->bDoTruncate = 1;
 72016        pBt->nPage = nFin;
 72017      }
 72018      if( rc!=SQLITE_OK ){
 72019        sqlite3PagerRollback(pPager);
 72020      }
 72021    }
 72022  
 72023    assert( nRef>=sqlite3PagerRefcount(pPager) );
 72024    return rc;
 72025  }
 72026  
 72027  #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
 72028  # define setChildPtrmaps(x) SQLITE_OK
 72029  #endif
 72030  
 72031  /*
 72032  ** This routine does the first phase of a two-phase commit.  This routine
 72033  ** causes a rollback journal to be created (if it does not already exist)
 72034  ** and populated with enough information so that if a power loss occurs
 72035  ** the database can be restored to its original state by playing back
 72036  ** the journal.  Then the contents of the journal are flushed out to
 72037  ** the disk.  After the journal is safely on oxide, the changes to the
 72038  ** database are written into the database file and flushed to oxide.
 72039  ** At the end of this call, the rollback journal still exists on the
 72040  ** disk and we are still holding all locks, so the transaction has not
 72041  ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
 72042  ** commit process.
 72043  **
 72044  ** This call is a no-op if no write-transaction is currently active on pBt.
 72045  **
 72046  ** Otherwise, sync the database file for the btree pBt. zMaster points to
 72047  ** the name of a master journal file that should be written into the
 72048  ** individual journal file, or is NULL, indicating no master journal file 
 72049  ** (single database transaction).
 72050  **
 72051  ** When this is called, the master journal should already have been
 72052  ** created, populated with this journal pointer and synced to disk.
 72053  **
 72054  ** Once this is routine has returned, the only thing required to commit
 72055  ** the write-transaction for this database file is to delete the journal.
 72056  */
 72057  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
 72058    int rc = SQLITE_OK;
 72059    if( p->inTrans==TRANS_WRITE ){
 72060      BtShared *pBt = p->pBt;
 72061      sqlite3BtreeEnter(p);
 72062  #ifndef SQLITE_OMIT_AUTOVACUUM
 72063      if( pBt->autoVacuum ){
 72064        rc = autoVacuumCommit(pBt);
 72065        if( rc!=SQLITE_OK ){
 72066          sqlite3BtreeLeave(p);
 72067          return rc;
 72068        }
 72069      }
 72070      if( pBt->bDoTruncate ){
 72071        sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
 72072      }
 72073  #endif
 72074      rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
 72075      sqlite3BtreeLeave(p);
 72076    }
 72077    return rc;
 72078  }
 72079  
 72080  /*
 72081  ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
 72082  ** at the conclusion of a transaction.
 72083  */
 72084  static void btreeEndTransaction(Btree *p){
 72085    BtShared *pBt = p->pBt;
 72086    sqlite3 *db = p->db;
 72087    assert( sqlite3BtreeHoldsMutex(p) );
 72088  
 72089  #ifndef SQLITE_OMIT_AUTOVACUUM
 72090    pBt->bDoTruncate = 0;
 72091  #endif
 72092    if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
 72093      /* If there are other active statements that belong to this database
 72094      ** handle, downgrade to a read-only transaction. The other statements
 72095      ** may still be reading from the database.  */
 72096      downgradeAllSharedCacheTableLocks(p);
 72097      p->inTrans = TRANS_READ;
 72098    }else{
 72099      /* If the handle had any kind of transaction open, decrement the 
 72100      ** transaction count of the shared btree. If the transaction count 
 72101      ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
 72102      ** call below will unlock the pager.  */
 72103      if( p->inTrans!=TRANS_NONE ){
 72104        clearAllSharedCacheTableLocks(p);
 72105        pBt->nTransaction--;
 72106        if( 0==pBt->nTransaction ){
 72107          pBt->inTransaction = TRANS_NONE;
 72108        }
 72109      }
 72110  
 72111      /* Set the current transaction state to TRANS_NONE and unlock the 
 72112      ** pager if this call closed the only read or write transaction.  */
 72113      p->inTrans = TRANS_NONE;
 72114      unlockBtreeIfUnused(pBt);
 72115    }
 72116  
 72117    btreeIntegrity(p);
 72118  }
 72119  
 72120  /*
 72121  ** Commit the transaction currently in progress.
 72122  **
 72123  ** This routine implements the second phase of a 2-phase commit.  The
 72124  ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
 72125  ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
 72126  ** routine did all the work of writing information out to disk and flushing the
 72127  ** contents so that they are written onto the disk platter.  All this
 72128  ** routine has to do is delete or truncate or zero the header in the
 72129  ** the rollback journal (which causes the transaction to commit) and
 72130  ** drop locks.
 72131  **
 72132  ** Normally, if an error occurs while the pager layer is attempting to 
 72133  ** finalize the underlying journal file, this function returns an error and
 72134  ** the upper layer will attempt a rollback. However, if the second argument
 72135  ** is non-zero then this b-tree transaction is part of a multi-file 
 72136  ** transaction. In this case, the transaction has already been committed 
 72137  ** (by deleting a master journal file) and the caller will ignore this 
 72138  ** functions return code. So, even if an error occurs in the pager layer,
 72139  ** reset the b-tree objects internal state to indicate that the write
 72140  ** transaction has been closed. This is quite safe, as the pager will have
 72141  ** transitioned to the error state.
 72142  **
 72143  ** This will release the write lock on the database file.  If there
 72144  ** are no active cursors, it also releases the read lock.
 72145  */
 72146  SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
 72147  
 72148    if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
 72149    sqlite3BtreeEnter(p);
 72150    btreeIntegrity(p);
 72151  
 72152    /* If the handle has a write-transaction open, commit the shared-btrees 
 72153    ** transaction and set the shared state to TRANS_READ.
 72154    */
 72155    if( p->inTrans==TRANS_WRITE ){
 72156      int rc;
 72157      BtShared *pBt = p->pBt;
 72158      assert( pBt->inTransaction==TRANS_WRITE );
 72159      assert( pBt->nTransaction>0 );
 72160      rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
 72161      if( rc!=SQLITE_OK && bCleanup==0 ){
 72162        sqlite3BtreeLeave(p);
 72163        return rc;
 72164      }
 72165      p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
 72166      pBt->inTransaction = TRANS_READ;
 72167      btreeClearHasContent(pBt);
 72168    }
 72169  
 72170    btreeEndTransaction(p);
 72171    sqlite3BtreeLeave(p);
 72172    return SQLITE_OK;
 72173  }
 72174  
 72175  /*
 72176  ** Do both phases of a commit.
 72177  */
 72178  SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
 72179    int rc;
 72180    sqlite3BtreeEnter(p);
 72181    rc = sqlite3BtreeCommitPhaseOne(p, 0);
 72182    if( rc==SQLITE_OK ){
 72183      rc = sqlite3BtreeCommitPhaseTwo(p, 0);
 72184    }
 72185    sqlite3BtreeLeave(p);
 72186    return rc;
 72187  }
 72188  
 72189  /*
 72190  ** This routine sets the state to CURSOR_FAULT and the error
 72191  ** code to errCode for every cursor on any BtShared that pBtree
 72192  ** references.  Or if the writeOnly flag is set to 1, then only
 72193  ** trip write cursors and leave read cursors unchanged.
 72194  **
 72195  ** Every cursor is a candidate to be tripped, including cursors
 72196  ** that belong to other database connections that happen to be
 72197  ** sharing the cache with pBtree.
 72198  **
 72199  ** This routine gets called when a rollback occurs. If the writeOnly
 72200  ** flag is true, then only write-cursors need be tripped - read-only
 72201  ** cursors save their current positions so that they may continue 
 72202  ** following the rollback. Or, if writeOnly is false, all cursors are 
 72203  ** tripped. In general, writeOnly is false if the transaction being
 72204  ** rolled back modified the database schema. In this case b-tree root
 72205  ** pages may be moved or deleted from the database altogether, making
 72206  ** it unsafe for read cursors to continue.
 72207  **
 72208  ** If the writeOnly flag is true and an error is encountered while 
 72209  ** saving the current position of a read-only cursor, all cursors, 
 72210  ** including all read-cursors are tripped.
 72211  **
 72212  ** SQLITE_OK is returned if successful, or if an error occurs while
 72213  ** saving a cursor position, an SQLite error code.
 72214  */
 72215  SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
 72216    BtCursor *p;
 72217    int rc = SQLITE_OK;
 72218  
 72219    assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
 72220    if( pBtree ){
 72221      sqlite3BtreeEnter(pBtree);
 72222      for(p=pBtree->pBt->pCursor; p; p=p->pNext){
 72223        if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
 72224          if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
 72225            rc = saveCursorPosition(p);
 72226            if( rc!=SQLITE_OK ){
 72227              (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
 72228              break;
 72229            }
 72230          }
 72231        }else{
 72232          sqlite3BtreeClearCursor(p);
 72233          p->eState = CURSOR_FAULT;
 72234          p->skipNext = errCode;
 72235        }
 72236        btreeReleaseAllCursorPages(p);
 72237      }
 72238      sqlite3BtreeLeave(pBtree);
 72239    }
 72240    return rc;
 72241  }
 72242  
 72243  /*
 72244  ** Rollback the transaction in progress.
 72245  **
 72246  ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
 72247  ** Only write cursors are tripped if writeOnly is true but all cursors are
 72248  ** tripped if writeOnly is false.  Any attempt to use
 72249  ** a tripped cursor will result in an error.
 72250  **
 72251  ** This will release the write lock on the database file.  If there
 72252  ** are no active cursors, it also releases the read lock.
 72253  */
 72254  SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
 72255    int rc;
 72256    BtShared *pBt = p->pBt;
 72257    MemPage *pPage1;
 72258  
 72259    assert( writeOnly==1 || writeOnly==0 );
 72260    assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
 72261    sqlite3BtreeEnter(p);
 72262    if( tripCode==SQLITE_OK ){
 72263      rc = tripCode = saveAllCursors(pBt, 0, 0);
 72264      if( rc ) writeOnly = 0;
 72265    }else{
 72266      rc = SQLITE_OK;
 72267    }
 72268    if( tripCode ){
 72269      int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
 72270      assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
 72271      if( rc2!=SQLITE_OK ) rc = rc2;
 72272    }
 72273    btreeIntegrity(p);
 72274  
 72275    if( p->inTrans==TRANS_WRITE ){
 72276      int rc2;
 72277  
 72278      assert( TRANS_WRITE==pBt->inTransaction );
 72279      rc2 = sqlite3PagerRollback(pBt->pPager);
 72280      if( rc2!=SQLITE_OK ){
 72281        rc = rc2;
 72282      }
 72283  
 72284      /* The rollback may have destroyed the pPage1->aData value.  So
 72285      ** call btreeGetPage() on page 1 again to make
 72286      ** sure pPage1->aData is set correctly. */
 72287      if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
 72288        int nPage = get4byte(28+(u8*)pPage1->aData);
 72289        testcase( nPage==0 );
 72290        if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
 72291        testcase( pBt->nPage!=nPage );
 72292        pBt->nPage = nPage;
 72293        releasePageOne(pPage1);
 72294      }
 72295      assert( countValidCursors(pBt, 1)==0 );
 72296      pBt->inTransaction = TRANS_READ;
 72297      btreeClearHasContent(pBt);
 72298    }
 72299  
 72300    btreeEndTransaction(p);
 72301    sqlite3BtreeLeave(p);
 72302    return rc;
 72303  }
 72304  
 72305  /*
 72306  ** Start a statement subtransaction. The subtransaction can be rolled
 72307  ** back independently of the main transaction. You must start a transaction 
 72308  ** before starting a subtransaction. The subtransaction is ended automatically 
 72309  ** if the main transaction commits or rolls back.
 72310  **
 72311  ** Statement subtransactions are used around individual SQL statements
 72312  ** that are contained within a BEGIN...COMMIT block.  If a constraint
 72313  ** error occurs within the statement, the effect of that one statement
 72314  ** can be rolled back without having to rollback the entire transaction.
 72315  **
 72316  ** A statement sub-transaction is implemented as an anonymous savepoint. The
 72317  ** value passed as the second parameter is the total number of savepoints,
 72318  ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
 72319  ** are no active savepoints and no other statement-transactions open,
 72320  ** iStatement is 1. This anonymous savepoint can be released or rolled back
 72321  ** using the sqlite3BtreeSavepoint() function.
 72322  */
 72323  SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
 72324    int rc;
 72325    BtShared *pBt = p->pBt;
 72326    sqlite3BtreeEnter(p);
 72327    assert( p->inTrans==TRANS_WRITE );
 72328    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 72329    assert( iStatement>0 );
 72330    assert( iStatement>p->db->nSavepoint );
 72331    assert( pBt->inTransaction==TRANS_WRITE );
 72332    /* At the pager level, a statement transaction is a savepoint with
 72333    ** an index greater than all savepoints created explicitly using
 72334    ** SQL statements. It is illegal to open, release or rollback any
 72335    ** such savepoints while the statement transaction savepoint is active.
 72336    */
 72337    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
 72338    sqlite3BtreeLeave(p);
 72339    return rc;
 72340  }
 72341  
 72342  /*
 72343  ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
 72344  ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
 72345  ** savepoint identified by parameter iSavepoint, depending on the value 
 72346  ** of op.
 72347  **
 72348  ** Normally, iSavepoint is greater than or equal to zero. However, if op is
 72349  ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
 72350  ** contents of the entire transaction are rolled back. This is different
 72351  ** from a normal transaction rollback, as no locks are released and the
 72352  ** transaction remains open.
 72353  */
 72354  SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
 72355    int rc = SQLITE_OK;
 72356    if( p && p->inTrans==TRANS_WRITE ){
 72357      BtShared *pBt = p->pBt;
 72358      assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
 72359      assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
 72360      sqlite3BtreeEnter(p);
 72361      if( op==SAVEPOINT_ROLLBACK ){
 72362        rc = saveAllCursors(pBt, 0, 0);
 72363      }
 72364      if( rc==SQLITE_OK ){
 72365        rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
 72366      }
 72367      if( rc==SQLITE_OK ){
 72368        if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
 72369          pBt->nPage = 0;
 72370        }
 72371        rc = newDatabase(pBt);
 72372        pBt->nPage = get4byte(28 + pBt->pPage1->aData);
 72373  
 72374        /* The database size was written into the offset 28 of the header
 72375        ** when the transaction started, so we know that the value at offset
 72376        ** 28 is nonzero. */
 72377        assert( pBt->nPage>0 );
 72378      }
 72379      sqlite3BtreeLeave(p);
 72380    }
 72381    return rc;
 72382  }
 72383  
 72384  /*
 72385  ** Create a new cursor for the BTree whose root is on the page
 72386  ** iTable. If a read-only cursor is requested, it is assumed that
 72387  ** the caller already has at least a read-only transaction open
 72388  ** on the database already. If a write-cursor is requested, then
 72389  ** the caller is assumed to have an open write transaction.
 72390  **
 72391  ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
 72392  ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
 72393  ** can be used for reading or for writing if other conditions for writing
 72394  ** are also met.  These are the conditions that must be met in order
 72395  ** for writing to be allowed:
 72396  **
 72397  ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
 72398  **
 72399  ** 2:  Other database connections that share the same pager cache
 72400  **     but which are not in the READ_UNCOMMITTED state may not have
 72401  **     cursors open with wrFlag==0 on the same table.  Otherwise
 72402  **     the changes made by this write cursor would be visible to
 72403  **     the read cursors in the other database connection.
 72404  **
 72405  ** 3:  The database must be writable (not on read-only media)
 72406  **
 72407  ** 4:  There must be an active transaction.
 72408  **
 72409  ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
 72410  ** is set.  If FORDELETE is set, that is a hint to the implementation that
 72411  ** this cursor will only be used to seek to and delete entries of an index
 72412  ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
 72413  ** this implementation.  But in a hypothetical alternative storage engine 
 72414  ** in which index entries are automatically deleted when corresponding table
 72415  ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
 72416  ** operations on this cursor can be no-ops and all READ operations can 
 72417  ** return a null row (2-bytes: 0x01 0x00).
 72418  **
 72419  ** No checking is done to make sure that page iTable really is the
 72420  ** root page of a b-tree.  If it is not, then the cursor acquired
 72421  ** will not work correctly.
 72422  **
 72423  ** It is assumed that the sqlite3BtreeCursorZero() has been called
 72424  ** on pCur to initialize the memory space prior to invoking this routine.
 72425  */
 72426  static int btreeCursor(
 72427    Btree *p,                              /* The btree */
 72428    int iTable,                            /* Root page of table to open */
 72429    int wrFlag,                            /* 1 to write. 0 read-only */
 72430    struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
 72431    BtCursor *pCur                         /* Space for new cursor */
 72432  ){
 72433    BtShared *pBt = p->pBt;                /* Shared b-tree handle */
 72434    BtCursor *pX;                          /* Looping over other all cursors */
 72435  
 72436    assert( sqlite3BtreeHoldsMutex(p) );
 72437    assert( wrFlag==0 
 72438         || wrFlag==BTREE_WRCSR 
 72439         || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 
 72440    );
 72441  
 72442    /* The following assert statements verify that if this is a sharable 
 72443    ** b-tree database, the connection is holding the required table locks, 
 72444    ** and that no other connection has any open cursor that conflicts with 
 72445    ** this lock.  */
 72446    assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
 72447    assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
 72448  
 72449    /* Assert that the caller has opened the required transaction. */
 72450    assert( p->inTrans>TRANS_NONE );
 72451    assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
 72452    assert( pBt->pPage1 && pBt->pPage1->aData );
 72453    assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
 72454  
 72455    if( wrFlag ){
 72456      allocateTempSpace(pBt);
 72457      if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
 72458    }
 72459    if( iTable==1 && btreePagecount(pBt)==0 ){
 72460      assert( wrFlag==0 );
 72461      iTable = 0;
 72462    }
 72463  
 72464    /* Now that no other errors can occur, finish filling in the BtCursor
 72465    ** variables and link the cursor into the BtShared list.  */
 72466    pCur->pgnoRoot = (Pgno)iTable;
 72467    pCur->iPage = -1;
 72468    pCur->pKeyInfo = pKeyInfo;
 72469    pCur->pBtree = p;
 72470    pCur->pBt = pBt;
 72471    pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
 72472    pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
 72473    /* If there are two or more cursors on the same btree, then all such
 72474    ** cursors *must* have the BTCF_Multiple flag set. */
 72475    for(pX=pBt->pCursor; pX; pX=pX->pNext){
 72476      if( pX->pgnoRoot==(Pgno)iTable ){
 72477        pX->curFlags |= BTCF_Multiple;
 72478        pCur->curFlags |= BTCF_Multiple;
 72479      }
 72480    }
 72481    pCur->pNext = pBt->pCursor;
 72482    pBt->pCursor = pCur;
 72483    pCur->eState = CURSOR_INVALID;
 72484    return SQLITE_OK;
 72485  }
 72486  SQLITE_PRIVATE int sqlite3BtreeCursor(
 72487    Btree *p,                                   /* The btree */
 72488    int iTable,                                 /* Root page of table to open */
 72489    int wrFlag,                                 /* 1 to write. 0 read-only */
 72490    struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
 72491    BtCursor *pCur                              /* Write new cursor here */
 72492  ){
 72493    int rc;
 72494    if( iTable<1 ){
 72495      rc = SQLITE_CORRUPT_BKPT;
 72496    }else{
 72497      sqlite3BtreeEnter(p);
 72498      rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
 72499      sqlite3BtreeLeave(p);
 72500    }
 72501    return rc;
 72502  }
 72503  
 72504  /*
 72505  ** Return the size of a BtCursor object in bytes.
 72506  **
 72507  ** This interfaces is needed so that users of cursors can preallocate
 72508  ** sufficient storage to hold a cursor.  The BtCursor object is opaque
 72509  ** to users so they cannot do the sizeof() themselves - they must call
 72510  ** this routine.
 72511  */
 72512  SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
 72513    return ROUND8(sizeof(BtCursor));
 72514  }
 72515  
 72516  /*
 72517  ** Initialize memory that will be converted into a BtCursor object.
 72518  **
 72519  ** The simple approach here would be to memset() the entire object
 72520  ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
 72521  ** do not need to be zeroed and they are large, so we can save a lot
 72522  ** of run-time by skipping the initialization of those elements.
 72523  */
 72524  SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
 72525    memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
 72526  }
 72527  
 72528  /*
 72529  ** Close a cursor.  The read lock on the database file is released
 72530  ** when the last cursor is closed.
 72531  */
 72532  SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
 72533    Btree *pBtree = pCur->pBtree;
 72534    if( pBtree ){
 72535      BtShared *pBt = pCur->pBt;
 72536      sqlite3BtreeEnter(pBtree);
 72537      assert( pBt->pCursor!=0 );
 72538      if( pBt->pCursor==pCur ){
 72539        pBt->pCursor = pCur->pNext;
 72540      }else{
 72541        BtCursor *pPrev = pBt->pCursor;
 72542        do{
 72543          if( pPrev->pNext==pCur ){
 72544            pPrev->pNext = pCur->pNext;
 72545            break;
 72546          }
 72547          pPrev = pPrev->pNext;
 72548        }while( ALWAYS(pPrev) );
 72549      }
 72550      btreeReleaseAllCursorPages(pCur);
 72551      unlockBtreeIfUnused(pBt);
 72552      sqlite3_free(pCur->aOverflow);
 72553      sqlite3_free(pCur->pKey);
 72554      sqlite3BtreeLeave(pBtree);
 72555      pCur->pBtree = 0;
 72556    }
 72557    return SQLITE_OK;
 72558  }
 72559  
 72560  /*
 72561  ** Make sure the BtCursor* given in the argument has a valid
 72562  ** BtCursor.info structure.  If it is not already valid, call
 72563  ** btreeParseCell() to fill it in.
 72564  **
 72565  ** BtCursor.info is a cache of the information in the current cell.
 72566  ** Using this cache reduces the number of calls to btreeParseCell().
 72567  */
 72568  #ifndef NDEBUG
 72569    static int cellInfoEqual(CellInfo *a, CellInfo *b){
 72570      if( a->nKey!=b->nKey ) return 0;
 72571      if( a->pPayload!=b->pPayload ) return 0;
 72572      if( a->nPayload!=b->nPayload ) return 0;
 72573      if( a->nLocal!=b->nLocal ) return 0;
 72574      if( a->nSize!=b->nSize ) return 0;
 72575      return 1;
 72576    }
 72577    static void assertCellInfo(BtCursor *pCur){
 72578      CellInfo info;
 72579      memset(&info, 0, sizeof(info));
 72580      btreeParseCell(pCur->pPage, pCur->ix, &info);
 72581      assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
 72582    }
 72583  #else
 72584    #define assertCellInfo(x)
 72585  #endif
 72586  static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
 72587    if( pCur->info.nSize==0 ){
 72588      pCur->curFlags |= BTCF_ValidNKey;
 72589      btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
 72590    }else{
 72591      assertCellInfo(pCur);
 72592    }
 72593  }
 72594  
 72595  #ifndef NDEBUG  /* The next routine used only within assert() statements */
 72596  /*
 72597  ** Return true if the given BtCursor is valid.  A valid cursor is one
 72598  ** that is currently pointing to a row in a (non-empty) table.
 72599  ** This is a verification routine is used only within assert() statements.
 72600  */
 72601  SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
 72602    return pCur && pCur->eState==CURSOR_VALID;
 72603  }
 72604  #endif /* NDEBUG */
 72605  SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
 72606    assert( pCur!=0 );
 72607    return pCur->eState==CURSOR_VALID;
 72608  }
 72609  
 72610  /*
 72611  ** Return the value of the integer key or "rowid" for a table btree.
 72612  ** This routine is only valid for a cursor that is pointing into a
 72613  ** ordinary table btree.  If the cursor points to an index btree or
 72614  ** is invalid, the result of this routine is undefined.
 72615  */
 72616  SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
 72617    assert( cursorHoldsMutex(pCur) );
 72618    assert( pCur->eState==CURSOR_VALID );
 72619    assert( pCur->curIntKey );
 72620    getCellInfo(pCur);
 72621    return pCur->info.nKey;
 72622  }
 72623  
 72624  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
 72625  /*
 72626  ** Return the offset into the database file for the start of the
 72627  ** payload to which the cursor is pointing.
 72628  */
 72629  SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
 72630    assert( cursorHoldsMutex(pCur) );
 72631    assert( pCur->eState==CURSOR_VALID );
 72632    getCellInfo(pCur);
 72633    return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
 72634           (i64)(pCur->info.pPayload - pCur->pPage->aData);
 72635  }
 72636  #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
 72637  
 72638  /*
 72639  ** Return the number of bytes of payload for the entry that pCur is
 72640  ** currently pointing to.  For table btrees, this will be the amount
 72641  ** of data.  For index btrees, this will be the size of the key.
 72642  **
 72643  ** The caller must guarantee that the cursor is pointing to a non-NULL
 72644  ** valid entry.  In other words, the calling procedure must guarantee
 72645  ** that the cursor has Cursor.eState==CURSOR_VALID.
 72646  */
 72647  SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
 72648    assert( cursorHoldsMutex(pCur) );
 72649    assert( pCur->eState==CURSOR_VALID );
 72650    getCellInfo(pCur);
 72651    return pCur->info.nPayload;
 72652  }
 72653  
 72654  /*
 72655  ** Return an upper bound on the size of any record for the table
 72656  ** that the cursor is pointing into.
 72657  **
 72658  ** This is an optimization.  Everything will still work if this
 72659  ** routine always returns 2147483647 (which is the largest record
 72660  ** that SQLite can handle) or more.  But returning a smaller value might
 72661  ** prevent large memory allocations when trying to interpret a
 72662  ** corrupt datrabase.
 72663  **
 72664  ** The current implementation merely returns the size of the underlying
 72665  ** database file.
 72666  */
 72667  SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
 72668    assert( cursorHoldsMutex(pCur) );
 72669    assert( pCur->eState==CURSOR_VALID );
 72670    return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
 72671  }
 72672  
 72673  /*
 72674  ** Given the page number of an overflow page in the database (parameter
 72675  ** ovfl), this function finds the page number of the next page in the 
 72676  ** linked list of overflow pages. If possible, it uses the auto-vacuum
 72677  ** pointer-map data instead of reading the content of page ovfl to do so. 
 72678  **
 72679  ** If an error occurs an SQLite error code is returned. Otherwise:
 72680  **
 72681  ** The page number of the next overflow page in the linked list is 
 72682  ** written to *pPgnoNext. If page ovfl is the last page in its linked 
 72683  ** list, *pPgnoNext is set to zero. 
 72684  **
 72685  ** If ppPage is not NULL, and a reference to the MemPage object corresponding
 72686  ** to page number pOvfl was obtained, then *ppPage is set to point to that
 72687  ** reference. It is the responsibility of the caller to call releasePage()
 72688  ** on *ppPage to free the reference. In no reference was obtained (because
 72689  ** the pointer-map was used to obtain the value for *pPgnoNext), then
 72690  ** *ppPage is set to zero.
 72691  */
 72692  static int getOverflowPage(
 72693    BtShared *pBt,               /* The database file */
 72694    Pgno ovfl,                   /* Current overflow page number */
 72695    MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
 72696    Pgno *pPgnoNext              /* OUT: Next overflow page number */
 72697  ){
 72698    Pgno next = 0;
 72699    MemPage *pPage = 0;
 72700    int rc = SQLITE_OK;
 72701  
 72702    assert( sqlite3_mutex_held(pBt->mutex) );
 72703    assert(pPgnoNext);
 72704  
 72705  #ifndef SQLITE_OMIT_AUTOVACUUM
 72706    /* Try to find the next page in the overflow list using the
 72707    ** autovacuum pointer-map pages. Guess that the next page in 
 72708    ** the overflow list is page number (ovfl+1). If that guess turns 
 72709    ** out to be wrong, fall back to loading the data of page 
 72710    ** number ovfl to determine the next page number.
 72711    */
 72712    if( pBt->autoVacuum ){
 72713      Pgno pgno;
 72714      Pgno iGuess = ovfl+1;
 72715      u8 eType;
 72716  
 72717      while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
 72718        iGuess++;
 72719      }
 72720  
 72721      if( iGuess<=btreePagecount(pBt) ){
 72722        rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
 72723        if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
 72724          next = iGuess;
 72725          rc = SQLITE_DONE;
 72726        }
 72727      }
 72728    }
 72729  #endif
 72730  
 72731    assert( next==0 || rc==SQLITE_DONE );
 72732    if( rc==SQLITE_OK ){
 72733      rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
 72734      assert( rc==SQLITE_OK || pPage==0 );
 72735      if( rc==SQLITE_OK ){
 72736        next = get4byte(pPage->aData);
 72737      }
 72738    }
 72739  
 72740    *pPgnoNext = next;
 72741    if( ppPage ){
 72742      *ppPage = pPage;
 72743    }else{
 72744      releasePage(pPage);
 72745    }
 72746    return (rc==SQLITE_DONE ? SQLITE_OK : rc);
 72747  }
 72748  
 72749  /*
 72750  ** Copy data from a buffer to a page, or from a page to a buffer.
 72751  **
 72752  ** pPayload is a pointer to data stored on database page pDbPage.
 72753  ** If argument eOp is false, then nByte bytes of data are copied
 72754  ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
 72755  ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
 72756  ** of data are copied from the buffer pBuf to pPayload.
 72757  **
 72758  ** SQLITE_OK is returned on success, otherwise an error code.
 72759  */
 72760  static int copyPayload(
 72761    void *pPayload,           /* Pointer to page data */
 72762    void *pBuf,               /* Pointer to buffer */
 72763    int nByte,                /* Number of bytes to copy */
 72764    int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
 72765    DbPage *pDbPage           /* Page containing pPayload */
 72766  ){
 72767    if( eOp ){
 72768      /* Copy data from buffer to page (a write operation) */
 72769      int rc = sqlite3PagerWrite(pDbPage);
 72770      if( rc!=SQLITE_OK ){
 72771        return rc;
 72772      }
 72773      memcpy(pPayload, pBuf, nByte);
 72774    }else{
 72775      /* Copy data from page to buffer (a read operation) */
 72776      memcpy(pBuf, pPayload, nByte);
 72777    }
 72778    return SQLITE_OK;
 72779  }
 72780  
 72781  /*
 72782  ** This function is used to read or overwrite payload information
 72783  ** for the entry that the pCur cursor is pointing to. The eOp
 72784  ** argument is interpreted as follows:
 72785  **
 72786  **   0: The operation is a read. Populate the overflow cache.
 72787  **   1: The operation is a write. Populate the overflow cache.
 72788  **
 72789  ** A total of "amt" bytes are read or written beginning at "offset".
 72790  ** Data is read to or from the buffer pBuf.
 72791  **
 72792  ** The content being read or written might appear on the main page
 72793  ** or be scattered out on multiple overflow pages.
 72794  **
 72795  ** If the current cursor entry uses one or more overflow pages
 72796  ** this function may allocate space for and lazily populate
 72797  ** the overflow page-list cache array (BtCursor.aOverflow). 
 72798  ** Subsequent calls use this cache to make seeking to the supplied offset 
 72799  ** more efficient.
 72800  **
 72801  ** Once an overflow page-list cache has been allocated, it must be
 72802  ** invalidated if some other cursor writes to the same table, or if
 72803  ** the cursor is moved to a different row. Additionally, in auto-vacuum
 72804  ** mode, the following events may invalidate an overflow page-list cache.
 72805  **
 72806  **   * An incremental vacuum,
 72807  **   * A commit in auto_vacuum="full" mode,
 72808  **   * Creating a table (may require moving an overflow page).
 72809  */
 72810  static int accessPayload(
 72811    BtCursor *pCur,      /* Cursor pointing to entry to read from */
 72812    u32 offset,          /* Begin reading this far into payload */
 72813    u32 amt,             /* Read this many bytes */
 72814    unsigned char *pBuf, /* Write the bytes into this buffer */ 
 72815    int eOp              /* zero to read. non-zero to write. */
 72816  ){
 72817    unsigned char *aPayload;
 72818    int rc = SQLITE_OK;
 72819    int iIdx = 0;
 72820    MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
 72821    BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
 72822  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 72823    unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
 72824  #endif
 72825  
 72826    assert( pPage );
 72827    assert( eOp==0 || eOp==1 );
 72828    assert( pCur->eState==CURSOR_VALID );
 72829    assert( pCur->ix<pPage->nCell );
 72830    assert( cursorHoldsMutex(pCur) );
 72831  
 72832    getCellInfo(pCur);
 72833    aPayload = pCur->info.pPayload;
 72834    assert( offset+amt <= pCur->info.nPayload );
 72835  
 72836    assert( aPayload > pPage->aData );
 72837    if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
 72838      /* Trying to read or write past the end of the data is an error.  The
 72839      ** conditional above is really:
 72840      **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
 72841      ** but is recast into its current form to avoid integer overflow problems
 72842      */
 72843      return SQLITE_CORRUPT_PAGE(pPage);
 72844    }
 72845  
 72846    /* Check if data must be read/written to/from the btree page itself. */
 72847    if( offset<pCur->info.nLocal ){
 72848      int a = amt;
 72849      if( a+offset>pCur->info.nLocal ){
 72850        a = pCur->info.nLocal - offset;
 72851      }
 72852      rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
 72853      offset = 0;
 72854      pBuf += a;
 72855      amt -= a;
 72856    }else{
 72857      offset -= pCur->info.nLocal;
 72858    }
 72859  
 72860  
 72861    if( rc==SQLITE_OK && amt>0 ){
 72862      const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
 72863      Pgno nextPage;
 72864  
 72865      nextPage = get4byte(&aPayload[pCur->info.nLocal]);
 72866  
 72867      /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
 72868      **
 72869      ** The aOverflow[] array is sized at one entry for each overflow page
 72870      ** in the overflow chain. The page number of the first overflow page is
 72871      ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
 72872      ** means "not yet known" (the cache is lazily populated).
 72873      */
 72874      if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
 72875        int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
 72876        if( pCur->aOverflow==0
 72877         || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
 72878        ){
 72879          Pgno *aNew = (Pgno*)sqlite3Realloc(
 72880              pCur->aOverflow, nOvfl*2*sizeof(Pgno)
 72881          );
 72882          if( aNew==0 ){
 72883            return SQLITE_NOMEM_BKPT;
 72884          }else{
 72885            pCur->aOverflow = aNew;
 72886          }
 72887        }
 72888        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
 72889        pCur->curFlags |= BTCF_ValidOvfl;
 72890      }else{
 72891        /* If the overflow page-list cache has been allocated and the
 72892        ** entry for the first required overflow page is valid, skip
 72893        ** directly to it.
 72894        */
 72895        if( pCur->aOverflow[offset/ovflSize] ){
 72896          iIdx = (offset/ovflSize);
 72897          nextPage = pCur->aOverflow[iIdx];
 72898          offset = (offset%ovflSize);
 72899        }
 72900      }
 72901  
 72902      assert( rc==SQLITE_OK && amt>0 );
 72903      while( nextPage ){
 72904        /* If required, populate the overflow page-list cache. */
 72905        assert( pCur->aOverflow[iIdx]==0
 72906                || pCur->aOverflow[iIdx]==nextPage
 72907                || CORRUPT_DB );
 72908        pCur->aOverflow[iIdx] = nextPage;
 72909  
 72910        if( offset>=ovflSize ){
 72911          /* The only reason to read this page is to obtain the page
 72912          ** number for the next page in the overflow chain. The page
 72913          ** data is not required. So first try to lookup the overflow
 72914          ** page-list cache, if any, then fall back to the getOverflowPage()
 72915          ** function.
 72916          */
 72917          assert( pCur->curFlags & BTCF_ValidOvfl );
 72918          assert( pCur->pBtree->db==pBt->db );
 72919          if( pCur->aOverflow[iIdx+1] ){
 72920            nextPage = pCur->aOverflow[iIdx+1];
 72921          }else{
 72922            rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
 72923          }
 72924          offset -= ovflSize;
 72925        }else{
 72926          /* Need to read this page properly. It contains some of the
 72927          ** range of data that is being read (eOp==0) or written (eOp!=0).
 72928          */
 72929          int a = amt;
 72930          if( a + offset > ovflSize ){
 72931            a = ovflSize - offset;
 72932          }
 72933  
 72934  #ifdef SQLITE_DIRECT_OVERFLOW_READ
 72935          /* If all the following are true:
 72936          **
 72937          **   1) this is a read operation, and 
 72938          **   2) data is required from the start of this overflow page, and
 72939          **   3) there are no dirty pages in the page-cache
 72940          **   4) the database is file-backed, and
 72941          **   5) the page is not in the WAL file
 72942          **   6) at least 4 bytes have already been read into the output buffer 
 72943          **
 72944          ** then data can be read directly from the database file into the
 72945          ** output buffer, bypassing the page-cache altogether. This speeds
 72946          ** up loading large records that span many overflow pages.
 72947          */
 72948          if( eOp==0                                             /* (1) */
 72949           && offset==0                                          /* (2) */
 72950           && sqlite3PagerDirectReadOk(pBt->pPager, nextPage)    /* (3,4,5) */
 72951           && &pBuf[-4]>=pBufStart                               /* (6) */
 72952          ){
 72953            sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
 72954            u8 aSave[4];
 72955            u8 *aWrite = &pBuf[-4];
 72956            assert( aWrite>=pBufStart );                         /* due to (6) */
 72957            memcpy(aSave, aWrite, 4);
 72958            rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
 72959            nextPage = get4byte(aWrite);
 72960            memcpy(aWrite, aSave, 4);
 72961          }else
 72962  #endif
 72963  
 72964          {
 72965            DbPage *pDbPage;
 72966            rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
 72967                (eOp==0 ? PAGER_GET_READONLY : 0)
 72968            );
 72969            if( rc==SQLITE_OK ){
 72970              aPayload = sqlite3PagerGetData(pDbPage);
 72971              nextPage = get4byte(aPayload);
 72972              rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
 72973              sqlite3PagerUnref(pDbPage);
 72974              offset = 0;
 72975            }
 72976          }
 72977          amt -= a;
 72978          if( amt==0 ) return rc;
 72979          pBuf += a;
 72980        }
 72981        if( rc ) break;
 72982        iIdx++;
 72983      }
 72984    }
 72985  
 72986    if( rc==SQLITE_OK && amt>0 ){
 72987      /* Overflow chain ends prematurely */
 72988      return SQLITE_CORRUPT_PAGE(pPage);
 72989    }
 72990    return rc;
 72991  }
 72992  
 72993  /*
 72994  ** Read part of the payload for the row at which that cursor pCur is currently
 72995  ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
 72996  ** begins at "offset".
 72997  **
 72998  ** pCur can be pointing to either a table or an index b-tree.
 72999  ** If pointing to a table btree, then the content section is read.  If
 73000  ** pCur is pointing to an index b-tree then the key section is read.
 73001  **
 73002  ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
 73003  ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
 73004  ** cursor might be invalid or might need to be restored before being read.
 73005  **
 73006  ** Return SQLITE_OK on success or an error code if anything goes
 73007  ** wrong.  An error is returned if "offset+amt" is larger than
 73008  ** the available payload.
 73009  */
 73010  SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 73011    assert( cursorHoldsMutex(pCur) );
 73012    assert( pCur->eState==CURSOR_VALID );
 73013    assert( pCur->iPage>=0 && pCur->pPage );
 73014    assert( pCur->ix<pCur->pPage->nCell );
 73015    return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
 73016  }
 73017  
 73018  /*
 73019  ** This variant of sqlite3BtreePayload() works even if the cursor has not
 73020  ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
 73021  ** interface.
 73022  */
 73023  #ifndef SQLITE_OMIT_INCRBLOB
 73024  static SQLITE_NOINLINE int accessPayloadChecked(
 73025    BtCursor *pCur,
 73026    u32 offset,
 73027    u32 amt,
 73028    void *pBuf
 73029  ){
 73030    int rc;
 73031    if ( pCur->eState==CURSOR_INVALID ){
 73032      return SQLITE_ABORT;
 73033    }
 73034    assert( cursorOwnsBtShared(pCur) );
 73035    rc = btreeRestoreCursorPosition(pCur);
 73036    return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
 73037  }
 73038  SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
 73039    if( pCur->eState==CURSOR_VALID ){
 73040      assert( cursorOwnsBtShared(pCur) );
 73041      return accessPayload(pCur, offset, amt, pBuf, 0);
 73042    }else{
 73043      return accessPayloadChecked(pCur, offset, amt, pBuf);
 73044    }
 73045  }
 73046  #endif /* SQLITE_OMIT_INCRBLOB */
 73047  
 73048  /*
 73049  ** Return a pointer to payload information from the entry that the 
 73050  ** pCur cursor is pointing to.  The pointer is to the beginning of
 73051  ** the key if index btrees (pPage->intKey==0) and is the data for
 73052  ** table btrees (pPage->intKey==1). The number of bytes of available
 73053  ** key/data is written into *pAmt.  If *pAmt==0, then the value
 73054  ** returned will not be a valid pointer.
 73055  **
 73056  ** This routine is an optimization.  It is common for the entire key
 73057  ** and data to fit on the local page and for there to be no overflow
 73058  ** pages.  When that is so, this routine can be used to access the
 73059  ** key and data without making a copy.  If the key and/or data spills
 73060  ** onto overflow pages, then accessPayload() must be used to reassemble
 73061  ** the key/data and copy it into a preallocated buffer.
 73062  **
 73063  ** The pointer returned by this routine looks directly into the cached
 73064  ** page of the database.  The data might change or move the next time
 73065  ** any btree routine is called.
 73066  */
 73067  static const void *fetchPayload(
 73068    BtCursor *pCur,      /* Cursor pointing to entry to read from */
 73069    u32 *pAmt            /* Write the number of available bytes here */
 73070  ){
 73071    int amt;
 73072    assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
 73073    assert( pCur->eState==CURSOR_VALID );
 73074    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 73075    assert( cursorOwnsBtShared(pCur) );
 73076    assert( pCur->ix<pCur->pPage->nCell );
 73077    assert( pCur->info.nSize>0 );
 73078    assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
 73079    assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
 73080    amt = pCur->info.nLocal;
 73081    if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
 73082      /* There is too little space on the page for the expected amount
 73083      ** of local content. Database must be corrupt. */
 73084      assert( CORRUPT_DB );
 73085      amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
 73086    }
 73087    *pAmt = (u32)amt;
 73088    return (void*)pCur->info.pPayload;
 73089  }
 73090  
 73091  
 73092  /*
 73093  ** For the entry that cursor pCur is point to, return as
 73094  ** many bytes of the key or data as are available on the local
 73095  ** b-tree page.  Write the number of available bytes into *pAmt.
 73096  **
 73097  ** The pointer returned is ephemeral.  The key/data may move
 73098  ** or be destroyed on the next call to any Btree routine,
 73099  ** including calls from other threads against the same cache.
 73100  ** Hence, a mutex on the BtShared should be held prior to calling
 73101  ** this routine.
 73102  **
 73103  ** These routines is used to get quick access to key and data
 73104  ** in the common case where no overflow pages are used.
 73105  */
 73106  SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
 73107    return fetchPayload(pCur, pAmt);
 73108  }
 73109  
 73110  
 73111  /*
 73112  ** Move the cursor down to a new child page.  The newPgno argument is the
 73113  ** page number of the child page to move to.
 73114  **
 73115  ** This function returns SQLITE_CORRUPT if the page-header flags field of
 73116  ** the new child page does not match the flags field of the parent (i.e.
 73117  ** if an intkey page appears to be the parent of a non-intkey page, or
 73118  ** vice-versa).
 73119  */
 73120  static int moveToChild(BtCursor *pCur, u32 newPgno){
 73121    BtShared *pBt = pCur->pBt;
 73122  
 73123    assert( cursorOwnsBtShared(pCur) );
 73124    assert( pCur->eState==CURSOR_VALID );
 73125    assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
 73126    assert( pCur->iPage>=0 );
 73127    if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
 73128      return SQLITE_CORRUPT_BKPT;
 73129    }
 73130    pCur->info.nSize = 0;
 73131    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 73132    pCur->aiIdx[pCur->iPage] = pCur->ix;
 73133    pCur->apPage[pCur->iPage] = pCur->pPage;
 73134    pCur->ix = 0;
 73135    pCur->iPage++;
 73136    return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
 73137  }
 73138  
 73139  #ifdef SQLITE_DEBUG
 73140  /*
 73141  ** Page pParent is an internal (non-leaf) tree page. This function 
 73142  ** asserts that page number iChild is the left-child if the iIdx'th
 73143  ** cell in page pParent. Or, if iIdx is equal to the total number of
 73144  ** cells in pParent, that page number iChild is the right-child of
 73145  ** the page.
 73146  */
 73147  static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
 73148    if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
 73149                              ** in a corrupt database */
 73150    assert( iIdx<=pParent->nCell );
 73151    if( iIdx==pParent->nCell ){
 73152      assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
 73153    }else{
 73154      assert( get4byte(findCell(pParent, iIdx))==iChild );
 73155    }
 73156  }
 73157  #else
 73158  #  define assertParentIndex(x,y,z) 
 73159  #endif
 73160  
 73161  /*
 73162  ** Move the cursor up to the parent page.
 73163  **
 73164  ** pCur->idx is set to the cell index that contains the pointer
 73165  ** to the page we are coming from.  If we are coming from the
 73166  ** right-most child page then pCur->idx is set to one more than
 73167  ** the largest cell index.
 73168  */
 73169  static void moveToParent(BtCursor *pCur){
 73170    MemPage *pLeaf;
 73171    assert( cursorOwnsBtShared(pCur) );
 73172    assert( pCur->eState==CURSOR_VALID );
 73173    assert( pCur->iPage>0 );
 73174    assert( pCur->pPage );
 73175    assertParentIndex(
 73176      pCur->apPage[pCur->iPage-1], 
 73177      pCur->aiIdx[pCur->iPage-1], 
 73178      pCur->pPage->pgno
 73179    );
 73180    testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
 73181    pCur->info.nSize = 0;
 73182    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 73183    pCur->ix = pCur->aiIdx[pCur->iPage-1];
 73184    pLeaf = pCur->pPage;
 73185    pCur->pPage = pCur->apPage[--pCur->iPage];
 73186    releasePageNotNull(pLeaf);
 73187  }
 73188  
 73189  /*
 73190  ** Move the cursor to point to the root page of its b-tree structure.
 73191  **
 73192  ** If the table has a virtual root page, then the cursor is moved to point
 73193  ** to the virtual root page instead of the actual root page. A table has a
 73194  ** virtual root page when the actual root page contains no cells and a 
 73195  ** single child page. This can only happen with the table rooted at page 1.
 73196  **
 73197  ** If the b-tree structure is empty, the cursor state is set to 
 73198  ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
 73199  ** the cursor is set to point to the first cell located on the root
 73200  ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
 73201  **
 73202  ** If this function returns successfully, it may be assumed that the
 73203  ** page-header flags indicate that the [virtual] root-page is the expected 
 73204  ** kind of b-tree page (i.e. if when opening the cursor the caller did not
 73205  ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
 73206  ** indicating a table b-tree, or if the caller did specify a KeyInfo 
 73207  ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
 73208  ** b-tree).
 73209  */
 73210  static int moveToRoot(BtCursor *pCur){
 73211    MemPage *pRoot;
 73212    int rc = SQLITE_OK;
 73213  
 73214    assert( cursorOwnsBtShared(pCur) );
 73215    assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
 73216    assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
 73217    assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
 73218    assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
 73219    assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
 73220  
 73221    if( pCur->iPage>=0 ){
 73222      if( pCur->iPage ){
 73223        releasePageNotNull(pCur->pPage);
 73224        while( --pCur->iPage ){
 73225          releasePageNotNull(pCur->apPage[pCur->iPage]);
 73226        }
 73227        pCur->pPage = pCur->apPage[0];
 73228        goto skip_init;
 73229      }
 73230    }else if( pCur->pgnoRoot==0 ){
 73231      pCur->eState = CURSOR_INVALID;
 73232      return SQLITE_EMPTY;
 73233    }else{
 73234      assert( pCur->iPage==(-1) );
 73235      if( pCur->eState>=CURSOR_REQUIRESEEK ){
 73236        if( pCur->eState==CURSOR_FAULT ){
 73237          assert( pCur->skipNext!=SQLITE_OK );
 73238          return pCur->skipNext;
 73239        }
 73240        sqlite3BtreeClearCursor(pCur);
 73241      }
 73242      rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
 73243                          0, pCur->curPagerFlags);
 73244      if( rc!=SQLITE_OK ){
 73245        pCur->eState = CURSOR_INVALID;
 73246        return rc;
 73247      }
 73248      pCur->iPage = 0;
 73249      pCur->curIntKey = pCur->pPage->intKey;
 73250    }
 73251    pRoot = pCur->pPage;
 73252    assert( pRoot->pgno==pCur->pgnoRoot );
 73253  
 73254    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
 73255    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
 73256    ** NULL, the caller expects a table b-tree. If this is not the case,
 73257    ** return an SQLITE_CORRUPT error. 
 73258    **
 73259    ** Earlier versions of SQLite assumed that this test could not fail
 73260    ** if the root page was already loaded when this function was called (i.e.
 73261    ** if pCur->iPage>=0). But this is not so if the database is corrupted 
 73262    ** in such a way that page pRoot is linked into a second b-tree table 
 73263    ** (or the freelist).  */
 73264    assert( pRoot->intKey==1 || pRoot->intKey==0 );
 73265    if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
 73266      return SQLITE_CORRUPT_PAGE(pCur->pPage);
 73267    }
 73268  
 73269  skip_init:  
 73270    pCur->ix = 0;
 73271    pCur->info.nSize = 0;
 73272    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
 73273  
 73274    pRoot = pCur->pPage;
 73275    if( pRoot->nCell>0 ){
 73276      pCur->eState = CURSOR_VALID;
 73277    }else if( !pRoot->leaf ){
 73278      Pgno subpage;
 73279      if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
 73280      subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
 73281      pCur->eState = CURSOR_VALID;
 73282      rc = moveToChild(pCur, subpage);
 73283    }else{
 73284      pCur->eState = CURSOR_INVALID;
 73285      rc = SQLITE_EMPTY;
 73286    }
 73287    return rc;
 73288  }
 73289  
 73290  /*
 73291  ** Move the cursor down to the left-most leaf entry beneath the
 73292  ** entry to which it is currently pointing.
 73293  **
 73294  ** The left-most leaf is the one with the smallest key - the first
 73295  ** in ascending order.
 73296  */
 73297  static int moveToLeftmost(BtCursor *pCur){
 73298    Pgno pgno;
 73299    int rc = SQLITE_OK;
 73300    MemPage *pPage;
 73301  
 73302    assert( cursorOwnsBtShared(pCur) );
 73303    assert( pCur->eState==CURSOR_VALID );
 73304    while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
 73305      assert( pCur->ix<pPage->nCell );
 73306      pgno = get4byte(findCell(pPage, pCur->ix));
 73307      rc = moveToChild(pCur, pgno);
 73308    }
 73309    return rc;
 73310  }
 73311  
 73312  /*
 73313  ** Move the cursor down to the right-most leaf entry beneath the
 73314  ** page to which it is currently pointing.  Notice the difference
 73315  ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
 73316  ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
 73317  ** finds the right-most entry beneath the *page*.
 73318  **
 73319  ** The right-most entry is the one with the largest key - the last
 73320  ** key in ascending order.
 73321  */
 73322  static int moveToRightmost(BtCursor *pCur){
 73323    Pgno pgno;
 73324    int rc = SQLITE_OK;
 73325    MemPage *pPage = 0;
 73326  
 73327    assert( cursorOwnsBtShared(pCur) );
 73328    assert( pCur->eState==CURSOR_VALID );
 73329    while( !(pPage = pCur->pPage)->leaf ){
 73330      pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 73331      pCur->ix = pPage->nCell;
 73332      rc = moveToChild(pCur, pgno);
 73333      if( rc ) return rc;
 73334    }
 73335    pCur->ix = pPage->nCell-1;
 73336    assert( pCur->info.nSize==0 );
 73337    assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
 73338    return SQLITE_OK;
 73339  }
 73340  
 73341  /* Move the cursor to the first entry in the table.  Return SQLITE_OK
 73342  ** on success.  Set *pRes to 0 if the cursor actually points to something
 73343  ** or set *pRes to 1 if the table is empty.
 73344  */
 73345  SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
 73346    int rc;
 73347  
 73348    assert( cursorOwnsBtShared(pCur) );
 73349    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 73350    rc = moveToRoot(pCur);
 73351    if( rc==SQLITE_OK ){
 73352      assert( pCur->pPage->nCell>0 );
 73353      *pRes = 0;
 73354      rc = moveToLeftmost(pCur);
 73355    }else if( rc==SQLITE_EMPTY ){
 73356      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 73357      *pRes = 1;
 73358      rc = SQLITE_OK;
 73359    }
 73360    return rc;
 73361  }
 73362  
 73363  /*
 73364  ** This function is a no-op if cursor pCur does not point to a valid row.
 73365  ** Otherwise, if pCur is valid, configure it so that the next call to
 73366  ** sqlite3BtreeNext() is a no-op.
 73367  */
 73368  #ifndef SQLITE_OMIT_WINDOWFUNC
 73369  SQLITE_PRIVATE void sqlite3BtreeSkipNext(BtCursor *pCur){
 73370    /* We believe that the cursor must always be in the valid state when
 73371    ** this routine is called, but the proof is difficult, so we add an
 73372    ** ALWaYS() test just in case we are wrong. */
 73373    if( ALWAYS(pCur->eState==CURSOR_VALID) ){
 73374      pCur->eState = CURSOR_SKIPNEXT;
 73375      pCur->skipNext = 1;
 73376    }
 73377  }
 73378  #endif /* SQLITE_OMIT_WINDOWFUNC */
 73379  
 73380  /* Move the cursor to the last entry in the table.  Return SQLITE_OK
 73381  ** on success.  Set *pRes to 0 if the cursor actually points to something
 73382  ** or set *pRes to 1 if the table is empty.
 73383  */
 73384  SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 73385    int rc;
 73386   
 73387    assert( cursorOwnsBtShared(pCur) );
 73388    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 73389  
 73390    /* If the cursor already points to the last entry, this is a no-op. */
 73391    if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
 73392  #ifdef SQLITE_DEBUG
 73393      /* This block serves to assert() that the cursor really does point 
 73394      ** to the last entry in the b-tree. */
 73395      int ii;
 73396      for(ii=0; ii<pCur->iPage; ii++){
 73397        assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
 73398      }
 73399      assert( pCur->ix==pCur->pPage->nCell-1 );
 73400      assert( pCur->pPage->leaf );
 73401  #endif
 73402      return SQLITE_OK;
 73403    }
 73404  
 73405    rc = moveToRoot(pCur);
 73406    if( rc==SQLITE_OK ){
 73407      assert( pCur->eState==CURSOR_VALID );
 73408      *pRes = 0;
 73409      rc = moveToRightmost(pCur);
 73410      if( rc==SQLITE_OK ){
 73411        pCur->curFlags |= BTCF_AtLast;
 73412      }else{
 73413        pCur->curFlags &= ~BTCF_AtLast;
 73414      }
 73415    }else if( rc==SQLITE_EMPTY ){
 73416      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 73417      *pRes = 1;
 73418      rc = SQLITE_OK;
 73419    }
 73420    return rc;
 73421  }
 73422  
 73423  /* Move the cursor so that it points to an entry near the key 
 73424  ** specified by pIdxKey or intKey.   Return a success code.
 73425  **
 73426  ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
 73427  ** must be NULL.  For index tables, pIdxKey is used and intKey
 73428  ** is ignored.
 73429  **
 73430  ** If an exact match is not found, then the cursor is always
 73431  ** left pointing at a leaf page which would hold the entry if it
 73432  ** were present.  The cursor might point to an entry that comes
 73433  ** before or after the key.
 73434  **
 73435  ** An integer is written into *pRes which is the result of
 73436  ** comparing the key with the entry to which the cursor is 
 73437  ** pointing.  The meaning of the integer written into
 73438  ** *pRes is as follows:
 73439  **
 73440  **     *pRes<0      The cursor is left pointing at an entry that
 73441  **                  is smaller than intKey/pIdxKey or if the table is empty
 73442  **                  and the cursor is therefore left point to nothing.
 73443  **
 73444  **     *pRes==0     The cursor is left pointing at an entry that
 73445  **                  exactly matches intKey/pIdxKey.
 73446  **
 73447  **     *pRes>0      The cursor is left pointing at an entry that
 73448  **                  is larger than intKey/pIdxKey.
 73449  **
 73450  ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
 73451  ** exists an entry in the table that exactly matches pIdxKey.  
 73452  */
 73453  SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
 73454    BtCursor *pCur,          /* The cursor to be moved */
 73455    UnpackedRecord *pIdxKey, /* Unpacked index key */
 73456    i64 intKey,              /* The table key */
 73457    int biasRight,           /* If true, bias the search to the high end */
 73458    int *pRes                /* Write search results here */
 73459  ){
 73460    int rc;
 73461    RecordCompare xRecordCompare;
 73462  
 73463    assert( cursorOwnsBtShared(pCur) );
 73464    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 73465    assert( pRes );
 73466    assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
 73467    assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
 73468  
 73469    /* If the cursor is already positioned at the point we are trying
 73470    ** to move to, then just return without doing any work */
 73471    if( pIdxKey==0
 73472     && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
 73473    ){
 73474      if( pCur->info.nKey==intKey ){
 73475        *pRes = 0;
 73476        return SQLITE_OK;
 73477      }
 73478      if( pCur->info.nKey<intKey ){
 73479        if( (pCur->curFlags & BTCF_AtLast)!=0 ){
 73480          *pRes = -1;
 73481          return SQLITE_OK;
 73482        }
 73483        /* If the requested key is one more than the previous key, then
 73484        ** try to get there using sqlite3BtreeNext() rather than a full
 73485        ** binary search.  This is an optimization only.  The correct answer
 73486        ** is still obtained without this case, only a little more slowely */
 73487        if( pCur->info.nKey+1==intKey ){
 73488          *pRes = 0;
 73489          rc = sqlite3BtreeNext(pCur, 0);
 73490          if( rc==SQLITE_OK ){
 73491            getCellInfo(pCur);
 73492            if( pCur->info.nKey==intKey ){
 73493              return SQLITE_OK;
 73494            }
 73495          }else if( rc==SQLITE_DONE ){
 73496            rc = SQLITE_OK;
 73497          }else{
 73498            return rc;
 73499          }
 73500        }
 73501      }
 73502    }
 73503  
 73504    if( pIdxKey ){
 73505      xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
 73506      pIdxKey->errCode = 0;
 73507      assert( pIdxKey->default_rc==1 
 73508           || pIdxKey->default_rc==0 
 73509           || pIdxKey->default_rc==-1
 73510      );
 73511    }else{
 73512      xRecordCompare = 0; /* All keys are integers */
 73513    }
 73514  
 73515    rc = moveToRoot(pCur);
 73516    if( rc ){
 73517      if( rc==SQLITE_EMPTY ){
 73518        assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
 73519        *pRes = -1;
 73520        return SQLITE_OK;
 73521      }
 73522      return rc;
 73523    }
 73524    assert( pCur->pPage );
 73525    assert( pCur->pPage->isInit );
 73526    assert( pCur->eState==CURSOR_VALID );
 73527    assert( pCur->pPage->nCell > 0 );
 73528    assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
 73529    assert( pCur->curIntKey || pIdxKey );
 73530    for(;;){
 73531      int lwr, upr, idx, c;
 73532      Pgno chldPg;
 73533      MemPage *pPage = pCur->pPage;
 73534      u8 *pCell;                          /* Pointer to current cell in pPage */
 73535  
 73536      /* pPage->nCell must be greater than zero. If this is the root-page
 73537      ** the cursor would have been INVALID above and this for(;;) loop
 73538      ** not run. If this is not the root-page, then the moveToChild() routine
 73539      ** would have already detected db corruption. Similarly, pPage must
 73540      ** be the right kind (index or table) of b-tree page. Otherwise
 73541      ** a moveToChild() or moveToRoot() call would have detected corruption.  */
 73542      assert( pPage->nCell>0 );
 73543      assert( pPage->intKey==(pIdxKey==0) );
 73544      lwr = 0;
 73545      upr = pPage->nCell-1;
 73546      assert( biasRight==0 || biasRight==1 );
 73547      idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
 73548      pCur->ix = (u16)idx;
 73549      if( xRecordCompare==0 ){
 73550        for(;;){
 73551          i64 nCellKey;
 73552          pCell = findCellPastPtr(pPage, idx);
 73553          if( pPage->intKeyLeaf ){
 73554            while( 0x80 <= *(pCell++) ){
 73555              if( pCell>=pPage->aDataEnd ){
 73556                return SQLITE_CORRUPT_PAGE(pPage);
 73557              }
 73558            }
 73559          }
 73560          getVarint(pCell, (u64*)&nCellKey);
 73561          if( nCellKey<intKey ){
 73562            lwr = idx+1;
 73563            if( lwr>upr ){ c = -1; break; }
 73564          }else if( nCellKey>intKey ){
 73565            upr = idx-1;
 73566            if( lwr>upr ){ c = +1; break; }
 73567          }else{
 73568            assert( nCellKey==intKey );
 73569            pCur->ix = (u16)idx;
 73570            if( !pPage->leaf ){
 73571              lwr = idx;
 73572              goto moveto_next_layer;
 73573            }else{
 73574              pCur->curFlags |= BTCF_ValidNKey;
 73575              pCur->info.nKey = nCellKey;
 73576              pCur->info.nSize = 0;
 73577              *pRes = 0;
 73578              return SQLITE_OK;
 73579            }
 73580          }
 73581          assert( lwr+upr>=0 );
 73582          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
 73583        }
 73584      }else{
 73585        for(;;){
 73586          int nCell;  /* Size of the pCell cell in bytes */
 73587          pCell = findCellPastPtr(pPage, idx);
 73588  
 73589          /* The maximum supported page-size is 65536 bytes. This means that
 73590          ** the maximum number of record bytes stored on an index B-Tree
 73591          ** page is less than 16384 bytes and may be stored as a 2-byte
 73592          ** varint. This information is used to attempt to avoid parsing 
 73593          ** the entire cell by checking for the cases where the record is 
 73594          ** stored entirely within the b-tree page by inspecting the first 
 73595          ** 2 bytes of the cell.
 73596          */
 73597          nCell = pCell[0];
 73598          if( nCell<=pPage->max1bytePayload ){
 73599            /* This branch runs if the record-size field of the cell is a
 73600            ** single byte varint and the record fits entirely on the main
 73601            ** b-tree page.  */
 73602            testcase( pCell+nCell+1==pPage->aDataEnd );
 73603            c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
 73604          }else if( !(pCell[1] & 0x80) 
 73605            && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
 73606          ){
 73607            /* The record-size field is a 2 byte varint and the record 
 73608            ** fits entirely on the main b-tree page.  */
 73609            testcase( pCell+nCell+2==pPage->aDataEnd );
 73610            c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
 73611          }else{
 73612            /* The record flows over onto one or more overflow pages. In
 73613            ** this case the whole cell needs to be parsed, a buffer allocated
 73614            ** and accessPayload() used to retrieve the record into the
 73615            ** buffer before VdbeRecordCompare() can be called. 
 73616            **
 73617            ** If the record is corrupt, the xRecordCompare routine may read
 73618            ** up to two varints past the end of the buffer. An extra 18 
 73619            ** bytes of padding is allocated at the end of the buffer in
 73620            ** case this happens.  */
 73621            void *pCellKey;
 73622            u8 * const pCellBody = pCell - pPage->childPtrSize;
 73623            pPage->xParseCell(pPage, pCellBody, &pCur->info);
 73624            nCell = (int)pCur->info.nKey;
 73625            testcase( nCell<0 );   /* True if key size is 2^32 or more */
 73626            testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
 73627            testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
 73628            testcase( nCell==2 );  /* Minimum legal index key size */
 73629            if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
 73630              rc = SQLITE_CORRUPT_PAGE(pPage);
 73631              goto moveto_finish;
 73632            }
 73633            pCellKey = sqlite3Malloc( nCell+18 );
 73634            if( pCellKey==0 ){
 73635              rc = SQLITE_NOMEM_BKPT;
 73636              goto moveto_finish;
 73637            }
 73638            pCur->ix = (u16)idx;
 73639            rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
 73640            pCur->curFlags &= ~BTCF_ValidOvfl;
 73641            if( rc ){
 73642              sqlite3_free(pCellKey);
 73643              goto moveto_finish;
 73644            }
 73645            c = xRecordCompare(nCell, pCellKey, pIdxKey);
 73646            sqlite3_free(pCellKey);
 73647          }
 73648          assert( 
 73649              (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
 73650           && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
 73651          );
 73652          if( c<0 ){
 73653            lwr = idx+1;
 73654          }else if( c>0 ){
 73655            upr = idx-1;
 73656          }else{
 73657            assert( c==0 );
 73658            *pRes = 0;
 73659            rc = SQLITE_OK;
 73660            pCur->ix = (u16)idx;
 73661            if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
 73662            goto moveto_finish;
 73663          }
 73664          if( lwr>upr ) break;
 73665          assert( lwr+upr>=0 );
 73666          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
 73667        }
 73668      }
 73669      assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
 73670      assert( pPage->isInit );
 73671      if( pPage->leaf ){
 73672        assert( pCur->ix<pCur->pPage->nCell );
 73673        pCur->ix = (u16)idx;
 73674        *pRes = c;
 73675        rc = SQLITE_OK;
 73676        goto moveto_finish;
 73677      }
 73678  moveto_next_layer:
 73679      if( lwr>=pPage->nCell ){
 73680        chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 73681      }else{
 73682        chldPg = get4byte(findCell(pPage, lwr));
 73683      }
 73684      pCur->ix = (u16)lwr;
 73685      rc = moveToChild(pCur, chldPg);
 73686      if( rc ) break;
 73687    }
 73688  moveto_finish:
 73689    pCur->info.nSize = 0;
 73690    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
 73691    return rc;
 73692  }
 73693  
 73694  
 73695  /*
 73696  ** Return TRUE if the cursor is not pointing at an entry of the table.
 73697  **
 73698  ** TRUE will be returned after a call to sqlite3BtreeNext() moves
 73699  ** past the last entry in the table or sqlite3BtreePrev() moves past
 73700  ** the first entry.  TRUE is also returned if the table is empty.
 73701  */
 73702  SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
 73703    /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
 73704    ** have been deleted? This API will need to change to return an error code
 73705    ** as well as the boolean result value.
 73706    */
 73707    return (CURSOR_VALID!=pCur->eState);
 73708  }
 73709  
 73710  /*
 73711  ** Return an estimate for the number of rows in the table that pCur is
 73712  ** pointing to.  Return a negative number if no estimate is currently 
 73713  ** available.
 73714  */
 73715  SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
 73716    i64 n;
 73717    u8 i;
 73718  
 73719    assert( cursorOwnsBtShared(pCur) );
 73720    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 73721  
 73722    /* Currently this interface is only called by the OP_IfSmaller
 73723    ** opcode, and it that case the cursor will always be valid and
 73724    ** will always point to a leaf node. */
 73725    if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
 73726    if( NEVER(pCur->pPage->leaf==0) ) return -1;
 73727  
 73728    n = pCur->pPage->nCell;
 73729    for(i=0; i<pCur->iPage; i++){
 73730      n *= pCur->apPage[i]->nCell;
 73731    }
 73732    return n;
 73733  }
 73734  
 73735  /*
 73736  ** Advance the cursor to the next entry in the database. 
 73737  ** Return value:
 73738  **
 73739  **    SQLITE_OK        success
 73740  **    SQLITE_DONE      cursor is already pointing at the last element
 73741  **    otherwise        some kind of error occurred
 73742  **
 73743  ** The main entry point is sqlite3BtreeNext().  That routine is optimized
 73744  ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
 73745  ** to the next cell on the current page.  The (slower) btreeNext() helper
 73746  ** routine is called when it is necessary to move to a different page or
 73747  ** to restore the cursor.
 73748  **
 73749  ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
 73750  ** cursor corresponds to an SQL index and this routine could have been
 73751  ** skipped if the SQL index had been a unique index.  The F argument
 73752  ** is a hint to the implement.  SQLite btree implementation does not use
 73753  ** this hint, but COMDB2 does.
 73754  */
 73755  static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
 73756    int rc;
 73757    int idx;
 73758    MemPage *pPage;
 73759  
 73760    assert( cursorOwnsBtShared(pCur) );
 73761    if( pCur->eState!=CURSOR_VALID ){
 73762      assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
 73763      rc = restoreCursorPosition(pCur);
 73764      if( rc!=SQLITE_OK ){
 73765        return rc;
 73766      }
 73767      if( CURSOR_INVALID==pCur->eState ){
 73768        return SQLITE_DONE;
 73769      }
 73770      if( pCur->eState==CURSOR_SKIPNEXT ){
 73771        pCur->eState = CURSOR_VALID;
 73772        if( pCur->skipNext>0 ) return SQLITE_OK;
 73773      }
 73774    }
 73775  
 73776    pPage = pCur->pPage;
 73777    idx = ++pCur->ix;
 73778    if( !pPage->isInit ){
 73779      /* The only known way for this to happen is for there to be a
 73780      ** recursive SQL function that does a DELETE operation as part of a
 73781      ** SELECT which deletes content out from under an active cursor
 73782      ** in a corrupt database file where the table being DELETE-ed from
 73783      ** has pages in common with the table being queried.  See TH3
 73784      ** module cov1/btree78.test testcase 220 (2018-06-08) for an
 73785      ** example. */
 73786      return SQLITE_CORRUPT_BKPT;
 73787    }
 73788  
 73789    /* If the database file is corrupt, it is possible for the value of idx 
 73790    ** to be invalid here. This can only occur if a second cursor modifies
 73791    ** the page while cursor pCur is holding a reference to it. Which can
 73792    ** only happen if the database is corrupt in such a way as to link the
 73793    ** page into more than one b-tree structure. */
 73794    testcase( idx>pPage->nCell );
 73795  
 73796    if( idx>=pPage->nCell ){
 73797      if( !pPage->leaf ){
 73798        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 73799        if( rc ) return rc;
 73800        return moveToLeftmost(pCur);
 73801      }
 73802      do{
 73803        if( pCur->iPage==0 ){
 73804          pCur->eState = CURSOR_INVALID;
 73805          return SQLITE_DONE;
 73806        }
 73807        moveToParent(pCur);
 73808        pPage = pCur->pPage;
 73809      }while( pCur->ix>=pPage->nCell );
 73810      if( pPage->intKey ){
 73811        return sqlite3BtreeNext(pCur, 0);
 73812      }else{
 73813        return SQLITE_OK;
 73814      }
 73815    }
 73816    if( pPage->leaf ){
 73817      return SQLITE_OK;
 73818    }else{
 73819      return moveToLeftmost(pCur);
 73820    }
 73821  }
 73822  SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
 73823    MemPage *pPage;
 73824    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
 73825    assert( cursorOwnsBtShared(pCur) );
 73826    assert( flags==0 || flags==1 );
 73827    pCur->info.nSize = 0;
 73828    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
 73829    if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
 73830    pPage = pCur->pPage;
 73831    if( (++pCur->ix)>=pPage->nCell ){
 73832      pCur->ix--;
 73833      return btreeNext(pCur);
 73834    }
 73835    if( pPage->leaf ){
 73836      return SQLITE_OK;
 73837    }else{
 73838      return moveToLeftmost(pCur);
 73839    }
 73840  }
 73841  
 73842  /*
 73843  ** Step the cursor to the back to the previous entry in the database.
 73844  ** Return values:
 73845  **
 73846  **     SQLITE_OK     success
 73847  **     SQLITE_DONE   the cursor is already on the first element of the table
 73848  **     otherwise     some kind of error occurred
 73849  **
 73850  ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
 73851  ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
 73852  ** to the previous cell on the current page.  The (slower) btreePrevious()
 73853  ** helper routine is called when it is necessary to move to a different page
 73854  ** or to restore the cursor.
 73855  **
 73856  ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
 73857  ** the cursor corresponds to an SQL index and this routine could have been
 73858  ** skipped if the SQL index had been a unique index.  The F argument is a
 73859  ** hint to the implement.  The native SQLite btree implementation does not
 73860  ** use this hint, but COMDB2 does.
 73861  */
 73862  static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
 73863    int rc;
 73864    MemPage *pPage;
 73865  
 73866    assert( cursorOwnsBtShared(pCur) );
 73867    assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
 73868    assert( pCur->info.nSize==0 );
 73869    if( pCur->eState!=CURSOR_VALID ){
 73870      rc = restoreCursorPosition(pCur);
 73871      if( rc!=SQLITE_OK ){
 73872        return rc;
 73873      }
 73874      if( CURSOR_INVALID==pCur->eState ){
 73875        return SQLITE_DONE;
 73876      }
 73877      if( CURSOR_SKIPNEXT==pCur->eState ){
 73878        pCur->eState = CURSOR_VALID;
 73879        if( pCur->skipNext<0 ) return SQLITE_OK;
 73880      }
 73881    }
 73882  
 73883    pPage = pCur->pPage;
 73884    assert( pPage->isInit );
 73885    if( !pPage->leaf ){
 73886      int idx = pCur->ix;
 73887      rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
 73888      if( rc ) return rc;
 73889      rc = moveToRightmost(pCur);
 73890    }else{
 73891      while( pCur->ix==0 ){
 73892        if( pCur->iPage==0 ){
 73893          pCur->eState = CURSOR_INVALID;
 73894          return SQLITE_DONE;
 73895        }
 73896        moveToParent(pCur);
 73897      }
 73898      assert( pCur->info.nSize==0 );
 73899      assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
 73900  
 73901      pCur->ix--;
 73902      pPage = pCur->pPage;
 73903      if( pPage->intKey && !pPage->leaf ){
 73904        rc = sqlite3BtreePrevious(pCur, 0);
 73905      }else{
 73906        rc = SQLITE_OK;
 73907      }
 73908    }
 73909    return rc;
 73910  }
 73911  SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
 73912    assert( cursorOwnsBtShared(pCur) );
 73913    assert( flags==0 || flags==1 );
 73914    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
 73915    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
 73916    pCur->info.nSize = 0;
 73917    if( pCur->eState!=CURSOR_VALID
 73918     || pCur->ix==0
 73919     || pCur->pPage->leaf==0
 73920    ){
 73921      return btreePrevious(pCur);
 73922    }
 73923    pCur->ix--;
 73924    return SQLITE_OK;
 73925  }
 73926  
 73927  /*
 73928  ** Allocate a new page from the database file.
 73929  **
 73930  ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
 73931  ** has already been called on the new page.)  The new page has also
 73932  ** been referenced and the calling routine is responsible for calling
 73933  ** sqlite3PagerUnref() on the new page when it is done.
 73934  **
 73935  ** SQLITE_OK is returned on success.  Any other return value indicates
 73936  ** an error.  *ppPage is set to NULL in the event of an error.
 73937  **
 73938  ** If the "nearby" parameter is not 0, then an effort is made to 
 73939  ** locate a page close to the page number "nearby".  This can be used in an
 73940  ** attempt to keep related pages close to each other in the database file,
 73941  ** which in turn can make database access faster.
 73942  **
 73943  ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
 73944  ** anywhere on the free-list, then it is guaranteed to be returned.  If
 73945  ** eMode is BTALLOC_LT then the page returned will be less than or equal
 73946  ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
 73947  ** are no restrictions on which page is returned.
 73948  */
 73949  static int allocateBtreePage(
 73950    BtShared *pBt,         /* The btree */
 73951    MemPage **ppPage,      /* Store pointer to the allocated page here */
 73952    Pgno *pPgno,           /* Store the page number here */
 73953    Pgno nearby,           /* Search for a page near this one */
 73954    u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
 73955  ){
 73956    MemPage *pPage1;
 73957    int rc;
 73958    u32 n;     /* Number of pages on the freelist */
 73959    u32 k;     /* Number of leaves on the trunk of the freelist */
 73960    MemPage *pTrunk = 0;
 73961    MemPage *pPrevTrunk = 0;
 73962    Pgno mxPage;     /* Total size of the database file */
 73963  
 73964    assert( sqlite3_mutex_held(pBt->mutex) );
 73965    assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
 73966    pPage1 = pBt->pPage1;
 73967    mxPage = btreePagecount(pBt);
 73968    /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
 73969    ** stores stores the total number of pages on the freelist. */
 73970    n = get4byte(&pPage1->aData[36]);
 73971    testcase( n==mxPage-1 );
 73972    if( n>=mxPage ){
 73973      return SQLITE_CORRUPT_BKPT;
 73974    }
 73975    if( n>0 ){
 73976      /* There are pages on the freelist.  Reuse one of those pages. */
 73977      Pgno iTrunk;
 73978      u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
 73979      u32 nSearch = 0;   /* Count of the number of search attempts */
 73980      
 73981      /* If eMode==BTALLOC_EXACT and a query of the pointer-map
 73982      ** shows that the page 'nearby' is somewhere on the free-list, then
 73983      ** the entire-list will be searched for that page.
 73984      */
 73985  #ifndef SQLITE_OMIT_AUTOVACUUM
 73986      if( eMode==BTALLOC_EXACT ){
 73987        if( nearby<=mxPage ){
 73988          u8 eType;
 73989          assert( nearby>0 );
 73990          assert( pBt->autoVacuum );
 73991          rc = ptrmapGet(pBt, nearby, &eType, 0);
 73992          if( rc ) return rc;
 73993          if( eType==PTRMAP_FREEPAGE ){
 73994            searchList = 1;
 73995          }
 73996        }
 73997      }else if( eMode==BTALLOC_LE ){
 73998        searchList = 1;
 73999      }
 74000  #endif
 74001  
 74002      /* Decrement the free-list count by 1. Set iTrunk to the index of the
 74003      ** first free-list trunk page. iPrevTrunk is initially 1.
 74004      */
 74005      rc = sqlite3PagerWrite(pPage1->pDbPage);
 74006      if( rc ) return rc;
 74007      put4byte(&pPage1->aData[36], n-1);
 74008  
 74009      /* The code within this loop is run only once if the 'searchList' variable
 74010      ** is not true. Otherwise, it runs once for each trunk-page on the
 74011      ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
 74012      ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
 74013      */
 74014      do {
 74015        pPrevTrunk = pTrunk;
 74016        if( pPrevTrunk ){
 74017          /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
 74018          ** is the page number of the next freelist trunk page in the list or
 74019          ** zero if this is the last freelist trunk page. */
 74020          iTrunk = get4byte(&pPrevTrunk->aData[0]);
 74021        }else{
 74022          /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
 74023          ** stores the page number of the first page of the freelist, or zero if
 74024          ** the freelist is empty. */
 74025          iTrunk = get4byte(&pPage1->aData[32]);
 74026        }
 74027        testcase( iTrunk==mxPage );
 74028        if( iTrunk>mxPage || nSearch++ > n ){
 74029          rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
 74030        }else{
 74031          rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
 74032        }
 74033        if( rc ){
 74034          pTrunk = 0;
 74035          goto end_allocate_page;
 74036        }
 74037        assert( pTrunk!=0 );
 74038        assert( pTrunk->aData!=0 );
 74039        /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
 74040        ** is the number of leaf page pointers to follow. */
 74041        k = get4byte(&pTrunk->aData[4]);
 74042        if( k==0 && !searchList ){
 74043          /* The trunk has no leaves and the list is not being searched. 
 74044          ** So extract the trunk page itself and use it as the newly 
 74045          ** allocated page */
 74046          assert( pPrevTrunk==0 );
 74047          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 74048          if( rc ){
 74049            goto end_allocate_page;
 74050          }
 74051          *pPgno = iTrunk;
 74052          memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 74053          *ppPage = pTrunk;
 74054          pTrunk = 0;
 74055          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 74056        }else if( k>(u32)(pBt->usableSize/4 - 2) ){
 74057          /* Value of k is out of range.  Database corruption */
 74058          rc = SQLITE_CORRUPT_PGNO(iTrunk);
 74059          goto end_allocate_page;
 74060  #ifndef SQLITE_OMIT_AUTOVACUUM
 74061        }else if( searchList 
 74062              && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
 74063        ){
 74064          /* The list is being searched and this trunk page is the page
 74065          ** to allocate, regardless of whether it has leaves.
 74066          */
 74067          *pPgno = iTrunk;
 74068          *ppPage = pTrunk;
 74069          searchList = 0;
 74070          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 74071          if( rc ){
 74072            goto end_allocate_page;
 74073          }
 74074          if( k==0 ){
 74075            if( !pPrevTrunk ){
 74076              memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
 74077            }else{
 74078              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 74079              if( rc!=SQLITE_OK ){
 74080                goto end_allocate_page;
 74081              }
 74082              memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
 74083            }
 74084          }else{
 74085            /* The trunk page is required by the caller but it contains 
 74086            ** pointers to free-list leaves. The first leaf becomes a trunk
 74087            ** page in this case.
 74088            */
 74089            MemPage *pNewTrunk;
 74090            Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
 74091            if( iNewTrunk>mxPage ){ 
 74092              rc = SQLITE_CORRUPT_PGNO(iTrunk);
 74093              goto end_allocate_page;
 74094            }
 74095            testcase( iNewTrunk==mxPage );
 74096            rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
 74097            if( rc!=SQLITE_OK ){
 74098              goto end_allocate_page;
 74099            }
 74100            rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
 74101            if( rc!=SQLITE_OK ){
 74102              releasePage(pNewTrunk);
 74103              goto end_allocate_page;
 74104            }
 74105            memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
 74106            put4byte(&pNewTrunk->aData[4], k-1);
 74107            memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
 74108            releasePage(pNewTrunk);
 74109            if( !pPrevTrunk ){
 74110              assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
 74111              put4byte(&pPage1->aData[32], iNewTrunk);
 74112            }else{
 74113              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 74114              if( rc ){
 74115                goto end_allocate_page;
 74116              }
 74117              put4byte(&pPrevTrunk->aData[0], iNewTrunk);
 74118            }
 74119          }
 74120          pTrunk = 0;
 74121          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
 74122  #endif
 74123        }else if( k>0 ){
 74124          /* Extract a leaf from the trunk */
 74125          u32 closest;
 74126          Pgno iPage;
 74127          unsigned char *aData = pTrunk->aData;
 74128          if( nearby>0 ){
 74129            u32 i;
 74130            closest = 0;
 74131            if( eMode==BTALLOC_LE ){
 74132              for(i=0; i<k; i++){
 74133                iPage = get4byte(&aData[8+i*4]);
 74134                if( iPage<=nearby ){
 74135                  closest = i;
 74136                  break;
 74137                }
 74138              }
 74139            }else{
 74140              int dist;
 74141              dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
 74142              for(i=1; i<k; i++){
 74143                int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
 74144                if( d2<dist ){
 74145                  closest = i;
 74146                  dist = d2;
 74147                }
 74148              }
 74149            }
 74150          }else{
 74151            closest = 0;
 74152          }
 74153  
 74154          iPage = get4byte(&aData[8+closest*4]);
 74155          testcase( iPage==mxPage );
 74156          if( iPage>mxPage ){
 74157            rc = SQLITE_CORRUPT_PGNO(iTrunk);
 74158            goto end_allocate_page;
 74159          }
 74160          testcase( iPage==mxPage );
 74161          if( !searchList 
 74162           || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
 74163          ){
 74164            int noContent;
 74165            *pPgno = iPage;
 74166            TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
 74167                   ": %d more free pages\n",
 74168                   *pPgno, closest+1, k, pTrunk->pgno, n-1));
 74169            rc = sqlite3PagerWrite(pTrunk->pDbPage);
 74170            if( rc ) goto end_allocate_page;
 74171            if( closest<k-1 ){
 74172              memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
 74173            }
 74174            put4byte(&aData[4], k-1);
 74175            noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
 74176            rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
 74177            if( rc==SQLITE_OK ){
 74178              rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 74179              if( rc!=SQLITE_OK ){
 74180                releasePage(*ppPage);
 74181                *ppPage = 0;
 74182              }
 74183            }
 74184            searchList = 0;
 74185          }
 74186        }
 74187        releasePage(pPrevTrunk);
 74188        pPrevTrunk = 0;
 74189      }while( searchList );
 74190    }else{
 74191      /* There are no pages on the freelist, so append a new page to the
 74192      ** database image.
 74193      **
 74194      ** Normally, new pages allocated by this block can be requested from the
 74195      ** pager layer with the 'no-content' flag set. This prevents the pager
 74196      ** from trying to read the pages content from disk. However, if the
 74197      ** current transaction has already run one or more incremental-vacuum
 74198      ** steps, then the page we are about to allocate may contain content
 74199      ** that is required in the event of a rollback. In this case, do
 74200      ** not set the no-content flag. This causes the pager to load and journal
 74201      ** the current page content before overwriting it.
 74202      **
 74203      ** Note that the pager will not actually attempt to load or journal 
 74204      ** content for any page that really does lie past the end of the database
 74205      ** file on disk. So the effects of disabling the no-content optimization
 74206      ** here are confined to those pages that lie between the end of the
 74207      ** database image and the end of the database file.
 74208      */
 74209      int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
 74210  
 74211      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 74212      if( rc ) return rc;
 74213      pBt->nPage++;
 74214      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
 74215  
 74216  #ifndef SQLITE_OMIT_AUTOVACUUM
 74217      if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
 74218        /* If *pPgno refers to a pointer-map page, allocate two new pages
 74219        ** at the end of the file instead of one. The first allocated page
 74220        ** becomes a new pointer-map page, the second is used by the caller.
 74221        */
 74222        MemPage *pPg = 0;
 74223        TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
 74224        assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
 74225        rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
 74226        if( rc==SQLITE_OK ){
 74227          rc = sqlite3PagerWrite(pPg->pDbPage);
 74228          releasePage(pPg);
 74229        }
 74230        if( rc ) return rc;
 74231        pBt->nPage++;
 74232        if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
 74233      }
 74234  #endif
 74235      put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
 74236      *pPgno = pBt->nPage;
 74237  
 74238      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
 74239      rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
 74240      if( rc ) return rc;
 74241      rc = sqlite3PagerWrite((*ppPage)->pDbPage);
 74242      if( rc!=SQLITE_OK ){
 74243        releasePage(*ppPage);
 74244        *ppPage = 0;
 74245      }
 74246      TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
 74247    }
 74248  
 74249    assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
 74250  
 74251  end_allocate_page:
 74252    releasePage(pTrunk);
 74253    releasePage(pPrevTrunk);
 74254    assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
 74255    assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
 74256    return rc;
 74257  }
 74258  
 74259  /*
 74260  ** This function is used to add page iPage to the database file free-list. 
 74261  ** It is assumed that the page is not already a part of the free-list.
 74262  **
 74263  ** The value passed as the second argument to this function is optional.
 74264  ** If the caller happens to have a pointer to the MemPage object 
 74265  ** corresponding to page iPage handy, it may pass it as the second value. 
 74266  ** Otherwise, it may pass NULL.
 74267  **
 74268  ** If a pointer to a MemPage object is passed as the second argument,
 74269  ** its reference count is not altered by this function.
 74270  */
 74271  static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
 74272    MemPage *pTrunk = 0;                /* Free-list trunk page */
 74273    Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
 74274    MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
 74275    MemPage *pPage;                     /* Page being freed. May be NULL. */
 74276    int rc;                             /* Return Code */
 74277    int nFree;                          /* Initial number of pages on free-list */
 74278  
 74279    assert( sqlite3_mutex_held(pBt->mutex) );
 74280    assert( CORRUPT_DB || iPage>1 );
 74281    assert( !pMemPage || pMemPage->pgno==iPage );
 74282  
 74283    if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
 74284    if( pMemPage ){
 74285      pPage = pMemPage;
 74286      sqlite3PagerRef(pPage->pDbPage);
 74287    }else{
 74288      pPage = btreePageLookup(pBt, iPage);
 74289    }
 74290  
 74291    /* Increment the free page count on pPage1 */
 74292    rc = sqlite3PagerWrite(pPage1->pDbPage);
 74293    if( rc ) goto freepage_out;
 74294    nFree = get4byte(&pPage1->aData[36]);
 74295    put4byte(&pPage1->aData[36], nFree+1);
 74296  
 74297    if( pBt->btsFlags & BTS_SECURE_DELETE ){
 74298      /* If the secure_delete option is enabled, then
 74299      ** always fully overwrite deleted information with zeros.
 74300      */
 74301      if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
 74302       ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
 74303      ){
 74304        goto freepage_out;
 74305      }
 74306      memset(pPage->aData, 0, pPage->pBt->pageSize);
 74307    }
 74308  
 74309    /* If the database supports auto-vacuum, write an entry in the pointer-map
 74310    ** to indicate that the page is free.
 74311    */
 74312    if( ISAUTOVACUUM ){
 74313      ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
 74314      if( rc ) goto freepage_out;
 74315    }
 74316  
 74317    /* Now manipulate the actual database free-list structure. There are two
 74318    ** possibilities. If the free-list is currently empty, or if the first
 74319    ** trunk page in the free-list is full, then this page will become a
 74320    ** new free-list trunk page. Otherwise, it will become a leaf of the
 74321    ** first trunk page in the current free-list. This block tests if it
 74322    ** is possible to add the page as a new free-list leaf.
 74323    */
 74324    if( nFree!=0 ){
 74325      u32 nLeaf;                /* Initial number of leaf cells on trunk page */
 74326  
 74327      iTrunk = get4byte(&pPage1->aData[32]);
 74328      rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
 74329      if( rc!=SQLITE_OK ){
 74330        goto freepage_out;
 74331      }
 74332  
 74333      nLeaf = get4byte(&pTrunk->aData[4]);
 74334      assert( pBt->usableSize>32 );
 74335      if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
 74336        rc = SQLITE_CORRUPT_BKPT;
 74337        goto freepage_out;
 74338      }
 74339      if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
 74340        /* In this case there is room on the trunk page to insert the page
 74341        ** being freed as a new leaf.
 74342        **
 74343        ** Note that the trunk page is not really full until it contains
 74344        ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
 74345        ** coded.  But due to a coding error in versions of SQLite prior to
 74346        ** 3.6.0, databases with freelist trunk pages holding more than
 74347        ** usableSize/4 - 8 entries will be reported as corrupt.  In order
 74348        ** to maintain backwards compatibility with older versions of SQLite,
 74349        ** we will continue to restrict the number of entries to usableSize/4 - 8
 74350        ** for now.  At some point in the future (once everyone has upgraded
 74351        ** to 3.6.0 or later) we should consider fixing the conditional above
 74352        ** to read "usableSize/4-2" instead of "usableSize/4-8".
 74353        **
 74354        ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
 74355        ** avoid using the last six entries in the freelist trunk page array in
 74356        ** order that database files created by newer versions of SQLite can be
 74357        ** read by older versions of SQLite.
 74358        */
 74359        rc = sqlite3PagerWrite(pTrunk->pDbPage);
 74360        if( rc==SQLITE_OK ){
 74361          put4byte(&pTrunk->aData[4], nLeaf+1);
 74362          put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
 74363          if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
 74364            sqlite3PagerDontWrite(pPage->pDbPage);
 74365          }
 74366          rc = btreeSetHasContent(pBt, iPage);
 74367        }
 74368        TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
 74369        goto freepage_out;
 74370      }
 74371    }
 74372  
 74373    /* If control flows to this point, then it was not possible to add the
 74374    ** the page being freed as a leaf page of the first trunk in the free-list.
 74375    ** Possibly because the free-list is empty, or possibly because the 
 74376    ** first trunk in the free-list is full. Either way, the page being freed
 74377    ** will become the new first trunk page in the free-list.
 74378    */
 74379    if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
 74380      goto freepage_out;
 74381    }
 74382    rc = sqlite3PagerWrite(pPage->pDbPage);
 74383    if( rc!=SQLITE_OK ){
 74384      goto freepage_out;
 74385    }
 74386    put4byte(pPage->aData, iTrunk);
 74387    put4byte(&pPage->aData[4], 0);
 74388    put4byte(&pPage1->aData[32], iPage);
 74389    TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
 74390  
 74391  freepage_out:
 74392    if( pPage ){
 74393      pPage->isInit = 0;
 74394    }
 74395    releasePage(pPage);
 74396    releasePage(pTrunk);
 74397    return rc;
 74398  }
 74399  static void freePage(MemPage *pPage, int *pRC){
 74400    if( (*pRC)==SQLITE_OK ){
 74401      *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
 74402    }
 74403  }
 74404  
 74405  /*
 74406  ** Free any overflow pages associated with the given Cell.  Store
 74407  ** size information about the cell in pInfo.
 74408  */
 74409  static int clearCell(
 74410    MemPage *pPage,          /* The page that contains the Cell */
 74411    unsigned char *pCell,    /* First byte of the Cell */
 74412    CellInfo *pInfo          /* Size information about the cell */
 74413  ){
 74414    BtShared *pBt;
 74415    Pgno ovflPgno;
 74416    int rc;
 74417    int nOvfl;
 74418    u32 ovflPageSize;
 74419  
 74420    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 74421    pPage->xParseCell(pPage, pCell, pInfo);
 74422    if( pInfo->nLocal==pInfo->nPayload ){
 74423      return SQLITE_OK;  /* No overflow pages. Return without doing anything */
 74424    }
 74425    testcase( pCell + pInfo->nSize == pPage->aDataEnd );
 74426    testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
 74427    if( pCell + pInfo->nSize > pPage->aDataEnd ){
 74428      /* Cell extends past end of page */
 74429      return SQLITE_CORRUPT_PAGE(pPage);
 74430    }
 74431    ovflPgno = get4byte(pCell + pInfo->nSize - 4);
 74432    pBt = pPage->pBt;
 74433    assert( pBt->usableSize > 4 );
 74434    ovflPageSize = pBt->usableSize - 4;
 74435    nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
 74436    assert( nOvfl>0 || 
 74437      (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
 74438    );
 74439    while( nOvfl-- ){
 74440      Pgno iNext = 0;
 74441      MemPage *pOvfl = 0;
 74442      if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
 74443        /* 0 is not a legal page number and page 1 cannot be an 
 74444        ** overflow page. Therefore if ovflPgno<2 or past the end of the 
 74445        ** file the database must be corrupt. */
 74446        return SQLITE_CORRUPT_BKPT;
 74447      }
 74448      if( nOvfl ){
 74449        rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
 74450        if( rc ) return rc;
 74451      }
 74452  
 74453      if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
 74454       && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
 74455      ){
 74456        /* There is no reason any cursor should have an outstanding reference 
 74457        ** to an overflow page belonging to a cell that is being deleted/updated.
 74458        ** So if there exists more than one reference to this page, then it 
 74459        ** must not really be an overflow page and the database must be corrupt. 
 74460        ** It is helpful to detect this before calling freePage2(), as 
 74461        ** freePage2() may zero the page contents if secure-delete mode is
 74462        ** enabled. If this 'overflow' page happens to be a page that the
 74463        ** caller is iterating through or using in some other way, this
 74464        ** can be problematic.
 74465        */
 74466        rc = SQLITE_CORRUPT_BKPT;
 74467      }else{
 74468        rc = freePage2(pBt, pOvfl, ovflPgno);
 74469      }
 74470  
 74471      if( pOvfl ){
 74472        sqlite3PagerUnref(pOvfl->pDbPage);
 74473      }
 74474      if( rc ) return rc;
 74475      ovflPgno = iNext;
 74476    }
 74477    return SQLITE_OK;
 74478  }
 74479  
 74480  /*
 74481  ** Create the byte sequence used to represent a cell on page pPage
 74482  ** and write that byte sequence into pCell[].  Overflow pages are
 74483  ** allocated and filled in as necessary.  The calling procedure
 74484  ** is responsible for making sure sufficient space has been allocated
 74485  ** for pCell[].
 74486  **
 74487  ** Note that pCell does not necessary need to point to the pPage->aData
 74488  ** area.  pCell might point to some temporary storage.  The cell will
 74489  ** be constructed in this temporary area then copied into pPage->aData
 74490  ** later.
 74491  */
 74492  static int fillInCell(
 74493    MemPage *pPage,                /* The page that contains the cell */
 74494    unsigned char *pCell,          /* Complete text of the cell */
 74495    const BtreePayload *pX,        /* Payload with which to construct the cell */
 74496    int *pnSize                    /* Write cell size here */
 74497  ){
 74498    int nPayload;
 74499    const u8 *pSrc;
 74500    int nSrc, n, rc, mn;
 74501    int spaceLeft;
 74502    MemPage *pToRelease;
 74503    unsigned char *pPrior;
 74504    unsigned char *pPayload;
 74505    BtShared *pBt;
 74506    Pgno pgnoOvfl;
 74507    int nHeader;
 74508  
 74509    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 74510  
 74511    /* pPage is not necessarily writeable since pCell might be auxiliary
 74512    ** buffer space that is separate from the pPage buffer area */
 74513    assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
 74514              || sqlite3PagerIswriteable(pPage->pDbPage) );
 74515  
 74516    /* Fill in the header. */
 74517    nHeader = pPage->childPtrSize;
 74518    if( pPage->intKey ){
 74519      nPayload = pX->nData + pX->nZero;
 74520      pSrc = pX->pData;
 74521      nSrc = pX->nData;
 74522      assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
 74523      nHeader += putVarint32(&pCell[nHeader], nPayload);
 74524      nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
 74525    }else{
 74526      assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
 74527      nSrc = nPayload = (int)pX->nKey;
 74528      pSrc = pX->pKey;
 74529      nHeader += putVarint32(&pCell[nHeader], nPayload);
 74530    }
 74531    
 74532    /* Fill in the payload */
 74533    pPayload = &pCell[nHeader];
 74534    if( nPayload<=pPage->maxLocal ){
 74535      /* This is the common case where everything fits on the btree page
 74536      ** and no overflow pages are required. */
 74537      n = nHeader + nPayload;
 74538      testcase( n==3 );
 74539      testcase( n==4 );
 74540      if( n<4 ) n = 4;
 74541      *pnSize = n;
 74542      assert( nSrc<=nPayload );
 74543      testcase( nSrc<nPayload );
 74544      memcpy(pPayload, pSrc, nSrc);
 74545      memset(pPayload+nSrc, 0, nPayload-nSrc);
 74546      return SQLITE_OK;
 74547    }
 74548  
 74549    /* If we reach this point, it means that some of the content will need
 74550    ** to spill onto overflow pages.
 74551    */
 74552    mn = pPage->minLocal;
 74553    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
 74554    testcase( n==pPage->maxLocal );
 74555    testcase( n==pPage->maxLocal+1 );
 74556    if( n > pPage->maxLocal ) n = mn;
 74557    spaceLeft = n;
 74558    *pnSize = n + nHeader + 4;
 74559    pPrior = &pCell[nHeader+n];
 74560    pToRelease = 0;
 74561    pgnoOvfl = 0;
 74562    pBt = pPage->pBt;
 74563  
 74564    /* At this point variables should be set as follows:
 74565    **
 74566    **   nPayload           Total payload size in bytes
 74567    **   pPayload           Begin writing payload here
 74568    **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
 74569    **                      that means content must spill into overflow pages.
 74570    **   *pnSize            Size of the local cell (not counting overflow pages)
 74571    **   pPrior             Where to write the pgno of the first overflow page
 74572    **
 74573    ** Use a call to btreeParseCellPtr() to verify that the values above
 74574    ** were computed correctly.
 74575    */
 74576  #ifdef SQLITE_DEBUG
 74577    {
 74578      CellInfo info;
 74579      pPage->xParseCell(pPage, pCell, &info);
 74580      assert( nHeader==(int)(info.pPayload - pCell) );
 74581      assert( info.nKey==pX->nKey );
 74582      assert( *pnSize == info.nSize );
 74583      assert( spaceLeft == info.nLocal );
 74584    }
 74585  #endif
 74586  
 74587    /* Write the payload into the local Cell and any extra into overflow pages */
 74588    while( 1 ){
 74589      n = nPayload;
 74590      if( n>spaceLeft ) n = spaceLeft;
 74591  
 74592      /* If pToRelease is not zero than pPayload points into the data area
 74593      ** of pToRelease.  Make sure pToRelease is still writeable. */
 74594      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 74595  
 74596      /* If pPayload is part of the data area of pPage, then make sure pPage
 74597      ** is still writeable */
 74598      assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
 74599              || sqlite3PagerIswriteable(pPage->pDbPage) );
 74600  
 74601      if( nSrc>=n ){
 74602        memcpy(pPayload, pSrc, n);
 74603      }else if( nSrc>0 ){
 74604        n = nSrc;
 74605        memcpy(pPayload, pSrc, n);
 74606      }else{
 74607        memset(pPayload, 0, n);
 74608      }
 74609      nPayload -= n;
 74610      if( nPayload<=0 ) break;
 74611      pPayload += n;
 74612      pSrc += n;
 74613      nSrc -= n;
 74614      spaceLeft -= n;
 74615      if( spaceLeft==0 ){
 74616        MemPage *pOvfl = 0;
 74617  #ifndef SQLITE_OMIT_AUTOVACUUM
 74618        Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
 74619        if( pBt->autoVacuum ){
 74620          do{
 74621            pgnoOvfl++;
 74622          } while( 
 74623            PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
 74624          );
 74625        }
 74626  #endif
 74627        rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
 74628  #ifndef SQLITE_OMIT_AUTOVACUUM
 74629        /* If the database supports auto-vacuum, and the second or subsequent
 74630        ** overflow page is being allocated, add an entry to the pointer-map
 74631        ** for that page now. 
 74632        **
 74633        ** If this is the first overflow page, then write a partial entry 
 74634        ** to the pointer-map. If we write nothing to this pointer-map slot,
 74635        ** then the optimistic overflow chain processing in clearCell()
 74636        ** may misinterpret the uninitialized values and delete the
 74637        ** wrong pages from the database.
 74638        */
 74639        if( pBt->autoVacuum && rc==SQLITE_OK ){
 74640          u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
 74641          ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
 74642          if( rc ){
 74643            releasePage(pOvfl);
 74644          }
 74645        }
 74646  #endif
 74647        if( rc ){
 74648          releasePage(pToRelease);
 74649          return rc;
 74650        }
 74651  
 74652        /* If pToRelease is not zero than pPrior points into the data area
 74653        ** of pToRelease.  Make sure pToRelease is still writeable. */
 74654        assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
 74655  
 74656        /* If pPrior is part of the data area of pPage, then make sure pPage
 74657        ** is still writeable */
 74658        assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
 74659              || sqlite3PagerIswriteable(pPage->pDbPage) );
 74660  
 74661        put4byte(pPrior, pgnoOvfl);
 74662        releasePage(pToRelease);
 74663        pToRelease = pOvfl;
 74664        pPrior = pOvfl->aData;
 74665        put4byte(pPrior, 0);
 74666        pPayload = &pOvfl->aData[4];
 74667        spaceLeft = pBt->usableSize - 4;
 74668      }
 74669    }
 74670    releasePage(pToRelease);
 74671    return SQLITE_OK;
 74672  }
 74673  
 74674  /*
 74675  ** Remove the i-th cell from pPage.  This routine effects pPage only.
 74676  ** The cell content is not freed or deallocated.  It is assumed that
 74677  ** the cell content has been copied someplace else.  This routine just
 74678  ** removes the reference to the cell from pPage.
 74679  **
 74680  ** "sz" must be the number of bytes in the cell.
 74681  */
 74682  static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
 74683    u32 pc;         /* Offset to cell content of cell being deleted */
 74684    u8 *data;       /* pPage->aData */
 74685    u8 *ptr;        /* Used to move bytes around within data[] */
 74686    int rc;         /* The return code */
 74687    int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
 74688  
 74689    if( *pRC ) return;
 74690    assert( idx>=0 && idx<pPage->nCell );
 74691    assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
 74692    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 74693    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 74694    data = pPage->aData;
 74695    ptr = &pPage->aCellIdx[2*idx];
 74696    pc = get2byte(ptr);
 74697    hdr = pPage->hdrOffset;
 74698    testcase( pc==get2byte(&data[hdr+5]) );
 74699    testcase( pc+sz==pPage->pBt->usableSize );
 74700    if( pc+sz > pPage->pBt->usableSize ){
 74701      *pRC = SQLITE_CORRUPT_BKPT;
 74702      return;
 74703    }
 74704    rc = freeSpace(pPage, pc, sz);
 74705    if( rc ){
 74706      *pRC = rc;
 74707      return;
 74708    }
 74709    pPage->nCell--;
 74710    if( pPage->nCell==0 ){
 74711      memset(&data[hdr+1], 0, 4);
 74712      data[hdr+7] = 0;
 74713      put2byte(&data[hdr+5], pPage->pBt->usableSize);
 74714      pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
 74715                         - pPage->childPtrSize - 8;
 74716    }else{
 74717      memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
 74718      put2byte(&data[hdr+3], pPage->nCell);
 74719      pPage->nFree += 2;
 74720    }
 74721  }
 74722  
 74723  /*
 74724  ** Insert a new cell on pPage at cell index "i".  pCell points to the
 74725  ** content of the cell.
 74726  **
 74727  ** If the cell content will fit on the page, then put it there.  If it
 74728  ** will not fit, then make a copy of the cell content into pTemp if
 74729  ** pTemp is not null.  Regardless of pTemp, allocate a new entry
 74730  ** in pPage->apOvfl[] and make it point to the cell content (either
 74731  ** in pTemp or the original pCell) and also record its index. 
 74732  ** Allocating a new entry in pPage->aCell[] implies that 
 74733  ** pPage->nOverflow is incremented.
 74734  **
 74735  ** *pRC must be SQLITE_OK when this routine is called.
 74736  */
 74737  static void insertCell(
 74738    MemPage *pPage,   /* Page into which we are copying */
 74739    int i,            /* New cell becomes the i-th cell of the page */
 74740    u8 *pCell,        /* Content of the new cell */
 74741    int sz,           /* Bytes of content in pCell */
 74742    u8 *pTemp,        /* Temp storage space for pCell, if needed */
 74743    Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
 74744    int *pRC          /* Read and write return code from here */
 74745  ){
 74746    int idx = 0;      /* Where to write new cell content in data[] */
 74747    int j;            /* Loop counter */
 74748    u8 *data;         /* The content of the whole page */
 74749    u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
 74750  
 74751    assert( *pRC==SQLITE_OK );
 74752    assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
 74753    assert( MX_CELL(pPage->pBt)<=10921 );
 74754    assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
 74755    assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
 74756    assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
 74757    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 74758    /* The cell should normally be sized correctly.  However, when moving a
 74759    ** malformed cell from a leaf page to an interior page, if the cell size
 74760    ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
 74761    ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
 74762    ** the term after the || in the following assert(). */
 74763    assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
 74764    if( pPage->nOverflow || sz+2>pPage->nFree ){
 74765      if( pTemp ){
 74766        memcpy(pTemp, pCell, sz);
 74767        pCell = pTemp;
 74768      }
 74769      if( iChild ){
 74770        put4byte(pCell, iChild);
 74771      }
 74772      j = pPage->nOverflow++;
 74773      /* Comparison against ArraySize-1 since we hold back one extra slot
 74774      ** as a contingency.  In other words, never need more than 3 overflow
 74775      ** slots but 4 are allocated, just to be safe. */
 74776      assert( j < ArraySize(pPage->apOvfl)-1 );
 74777      pPage->apOvfl[j] = pCell;
 74778      pPage->aiOvfl[j] = (u16)i;
 74779  
 74780      /* When multiple overflows occur, they are always sequential and in
 74781      ** sorted order.  This invariants arise because multiple overflows can
 74782      ** only occur when inserting divider cells into the parent page during
 74783      ** balancing, and the dividers are adjacent and sorted.
 74784      */
 74785      assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
 74786      assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
 74787    }else{
 74788      int rc = sqlite3PagerWrite(pPage->pDbPage);
 74789      if( rc!=SQLITE_OK ){
 74790        *pRC = rc;
 74791        return;
 74792      }
 74793      assert( sqlite3PagerIswriteable(pPage->pDbPage) );
 74794      data = pPage->aData;
 74795      assert( &data[pPage->cellOffset]==pPage->aCellIdx );
 74796      rc = allocateSpace(pPage, sz, &idx);
 74797      if( rc ){ *pRC = rc; return; }
 74798      /* The allocateSpace() routine guarantees the following properties
 74799      ** if it returns successfully */
 74800      assert( idx >= 0 );
 74801      assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
 74802      assert( idx+sz <= (int)pPage->pBt->usableSize );
 74803      pPage->nFree -= (u16)(2 + sz);
 74804      if( iChild ){
 74805        /* In a corrupt database where an entry in the cell index section of
 74806        ** a btree page has a value of 3 or less, the pCell value might point
 74807        ** as many as 4 bytes in front of the start of the aData buffer for
 74808        ** the source page.  Make sure this does not cause problems by not
 74809        ** reading the first 4 bytes */
 74810        memcpy(&data[idx+4], pCell+4, sz-4);
 74811        put4byte(&data[idx], iChild);
 74812      }else{
 74813        memcpy(&data[idx], pCell, sz);
 74814      }
 74815      pIns = pPage->aCellIdx + i*2;
 74816      memmove(pIns+2, pIns, 2*(pPage->nCell - i));
 74817      put2byte(pIns, idx);
 74818      pPage->nCell++;
 74819      /* increment the cell count */
 74820      if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
 74821      assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
 74822  #ifndef SQLITE_OMIT_AUTOVACUUM
 74823      if( pPage->pBt->autoVacuum ){
 74824        /* The cell may contain a pointer to an overflow page. If so, write
 74825        ** the entry for the overflow page into the pointer map.
 74826        */
 74827        ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
 74828      }
 74829  #endif
 74830    }
 74831  }
 74832  
 74833  /*
 74834  ** The following parameters determine how many adjacent pages get involved
 74835  ** in a balancing operation.  NN is the number of neighbors on either side
 74836  ** of the page that participate in the balancing operation.  NB is the
 74837  ** total number of pages that participate, including the target page and
 74838  ** NN neighbors on either side.
 74839  **
 74840  ** The minimum value of NN is 1 (of course).  Increasing NN above 1
 74841  ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
 74842  ** in exchange for a larger degradation in INSERT and UPDATE performance.
 74843  ** The value of NN appears to give the best results overall.
 74844  **
 74845  ** (Later:) The description above makes it seem as if these values are
 74846  ** tunable - as if you could change them and recompile and it would all work.
 74847  ** But that is unlikely.  NB has been 3 since the inception of SQLite and
 74848  ** we have never tested any other value.
 74849  */
 74850  #define NN 1             /* Number of neighbors on either side of pPage */
 74851  #define NB 3             /* (NN*2+1): Total pages involved in the balance */
 74852  
 74853  /*
 74854  ** A CellArray object contains a cache of pointers and sizes for a
 74855  ** consecutive sequence of cells that might be held on multiple pages.
 74856  **
 74857  ** The cells in this array are the divider cell or cells from the pParent
 74858  ** page plus up to three child pages.  There are a total of nCell cells.
 74859  **
 74860  ** pRef is a pointer to one of the pages that contributes cells.  This is
 74861  ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
 74862  ** which should be common to all pages that contribute cells to this array.
 74863  **
 74864  ** apCell[] and szCell[] hold, respectively, pointers to the start of each
 74865  ** cell and the size of each cell.  Some of the apCell[] pointers might refer
 74866  ** to overflow cells.  In other words, some apCel[] pointers might not point
 74867  ** to content area of the pages.
 74868  **
 74869  ** A szCell[] of zero means the size of that cell has not yet been computed.
 74870  **
 74871  ** The cells come from as many as four different pages:
 74872  **
 74873  **             -----------
 74874  **             | Parent  |
 74875  **             -----------
 74876  **            /     |     \
 74877  **           /      |      \
 74878  **  ---------   ---------   ---------
 74879  **  |Child-1|   |Child-2|   |Child-3|
 74880  **  ---------   ---------   ---------
 74881  **
 74882  ** The order of cells is in the array is for an index btree is:
 74883  **
 74884  **       1.  All cells from Child-1 in order
 74885  **       2.  The first divider cell from Parent
 74886  **       3.  All cells from Child-2 in order
 74887  **       4.  The second divider cell from Parent
 74888  **       5.  All cells from Child-3 in order
 74889  **
 74890  ** For a table-btree (with rowids) the items 2 and 4 are empty because
 74891  ** content exists only in leaves and there are no divider cells.
 74892  **
 74893  ** For an index btree, the apEnd[] array holds pointer to the end of page
 74894  ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
 74895  ** respectively. The ixNx[] array holds the number of cells contained in
 74896  ** each of these 5 stages, and all stages to the left.  Hence:
 74897  **
 74898  **    ixNx[0] = Number of cells in Child-1.
 74899  **    ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
 74900  **    ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
 74901  **    ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
 74902  **    ixNx[4] = Total number of cells.
 74903  **
 74904  ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
 74905  ** are used and they point to the leaf pages only, and the ixNx value are:
 74906  **
 74907  **    ixNx[0] = Number of cells in Child-1.
 74908  **    ixNx[1] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
 74909  **    ixNx[2] = Number of cells in Child-1 and Child-2 + both divider cells
 74910  */
 74911  typedef struct CellArray CellArray;
 74912  struct CellArray {
 74913    int nCell;              /* Number of cells in apCell[] */
 74914    MemPage *pRef;          /* Reference page */
 74915    u8 **apCell;            /* All cells begin balanced */
 74916    u16 *szCell;            /* Local size of all cells in apCell[] */
 74917    u8 *apEnd[NB*2];        /* MemPage.aDataEnd values */
 74918    int ixNx[NB*2];         /* Index of at which we move to the next apEnd[] */
 74919  };
 74920  
 74921  /*
 74922  ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
 74923  ** computed.
 74924  */
 74925  static void populateCellCache(CellArray *p, int idx, int N){
 74926    assert( idx>=0 && idx+N<=p->nCell );
 74927    while( N>0 ){
 74928      assert( p->apCell[idx]!=0 );
 74929      if( p->szCell[idx]==0 ){
 74930        p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
 74931      }else{
 74932        assert( CORRUPT_DB ||
 74933                p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
 74934      }
 74935      idx++;
 74936      N--;
 74937    }
 74938  }
 74939  
 74940  /*
 74941  ** Return the size of the Nth element of the cell array
 74942  */
 74943  static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
 74944    assert( N>=0 && N<p->nCell );
 74945    assert( p->szCell[N]==0 );
 74946    p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
 74947    return p->szCell[N];
 74948  }
 74949  static u16 cachedCellSize(CellArray *p, int N){
 74950    assert( N>=0 && N<p->nCell );
 74951    if( p->szCell[N] ) return p->szCell[N];
 74952    return computeCellSize(p, N);
 74953  }
 74954  
 74955  /*
 74956  ** Array apCell[] contains pointers to nCell b-tree page cells. The 
 74957  ** szCell[] array contains the size in bytes of each cell. This function
 74958  ** replaces the current contents of page pPg with the contents of the cell
 74959  ** array.
 74960  **
 74961  ** Some of the cells in apCell[] may currently be stored in pPg. This
 74962  ** function works around problems caused by this by making a copy of any 
 74963  ** such cells before overwriting the page data.
 74964  **
 74965  ** The MemPage.nFree field is invalidated by this function. It is the 
 74966  ** responsibility of the caller to set it correctly.
 74967  */
 74968  static int rebuildPage(
 74969    CellArray *pCArray,             /* Content to be added to page pPg */
 74970    int iFirst,                     /* First cell in pCArray to use */
 74971    int nCell,                      /* Final number of cells on page */
 74972    MemPage *pPg                    /* The page to be reconstructed */
 74973  ){
 74974    const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
 74975    u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
 74976    const int usableSize = pPg->pBt->usableSize;
 74977    u8 * const pEnd = &aData[usableSize];
 74978    int i = iFirst;                 /* Which cell to copy from pCArray*/
 74979    u32 j;                          /* Start of cell content area */
 74980    int iEnd = i+nCell;             /* Loop terminator */
 74981    u8 *pCellptr = pPg->aCellIdx;
 74982    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
 74983    u8 *pData;
 74984    int k;                          /* Current slot in pCArray->apEnd[] */
 74985    u8 *pSrcEnd;                    /* Current pCArray->apEnd[k] value */
 74986  
 74987    assert( i<iEnd );
 74988    j = get2byte(&aData[hdr+5]);
 74989    if( NEVER(j>(u32)usableSize) ){ j = 0; }
 74990    memcpy(&pTmp[j], &aData[j], usableSize - j);
 74991  
 74992    for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
 74993    pSrcEnd = pCArray->apEnd[k];
 74994  
 74995    pData = pEnd;
 74996    while( 1/*exit by break*/ ){
 74997      u8 *pCell = pCArray->apCell[i];
 74998      u16 sz = pCArray->szCell[i];
 74999      assert( sz>0 );
 75000      if( SQLITE_WITHIN(pCell,aData,pEnd) ){
 75001        if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
 75002        pCell = &pTmp[pCell - aData];
 75003      }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
 75004             && (uptr)(pCell)<(uptr)pSrcEnd
 75005      ){
 75006        return SQLITE_CORRUPT_BKPT;
 75007      }
 75008  
 75009      pData -= sz;
 75010      put2byte(pCellptr, (pData - aData));
 75011      pCellptr += 2;
 75012      if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
 75013      memcpy(pData, pCell, sz);
 75014      assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
 75015      testcase( sz!=pPg->xCellSize(pPg,pCell) );
 75016      i++;
 75017      if( i>=iEnd ) break;
 75018      if( pCArray->ixNx[k]<=i ){
 75019        k++;
 75020        pSrcEnd = pCArray->apEnd[k];
 75021      }
 75022    }
 75023  
 75024    /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
 75025    pPg->nCell = nCell;
 75026    pPg->nOverflow = 0;
 75027  
 75028    put2byte(&aData[hdr+1], 0);
 75029    put2byte(&aData[hdr+3], pPg->nCell);
 75030    put2byte(&aData[hdr+5], pData - aData);
 75031    aData[hdr+7] = 0x00;
 75032    return SQLITE_OK;
 75033  }
 75034  
 75035  /*
 75036  ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
 75037  ** This function attempts to add the cells stored in the array to page pPg.
 75038  ** If it cannot (because the page needs to be defragmented before the cells
 75039  ** will fit), non-zero is returned. Otherwise, if the cells are added
 75040  ** successfully, zero is returned.
 75041  **
 75042  ** Argument pCellptr points to the first entry in the cell-pointer array
 75043  ** (part of page pPg) to populate. After cell apCell[0] is written to the
 75044  ** page body, a 16-bit offset is written to pCellptr. And so on, for each
 75045  ** cell in the array. It is the responsibility of the caller to ensure
 75046  ** that it is safe to overwrite this part of the cell-pointer array.
 75047  **
 75048  ** When this function is called, *ppData points to the start of the 
 75049  ** content area on page pPg. If the size of the content area is extended,
 75050  ** *ppData is updated to point to the new start of the content area
 75051  ** before returning.
 75052  **
 75053  ** Finally, argument pBegin points to the byte immediately following the
 75054  ** end of the space required by this page for the cell-pointer area (for
 75055  ** all cells - not just those inserted by the current call). If the content
 75056  ** area must be extended to before this point in order to accomodate all
 75057  ** cells in apCell[], then the cells do not fit and non-zero is returned.
 75058  */
 75059  static int pageInsertArray(
 75060    MemPage *pPg,                   /* Page to add cells to */
 75061    u8 *pBegin,                     /* End of cell-pointer array */
 75062    u8 **ppData,                    /* IN/OUT: Page content-area pointer */
 75063    u8 *pCellptr,                   /* Pointer to cell-pointer area */
 75064    int iFirst,                     /* Index of first cell to add */
 75065    int nCell,                      /* Number of cells to add to pPg */
 75066    CellArray *pCArray              /* Array of cells */
 75067  ){
 75068    int i = iFirst;                 /* Loop counter - cell index to insert */
 75069    u8 *aData = pPg->aData;         /* Complete page */
 75070    u8 *pData = *ppData;            /* Content area.  A subset of aData[] */
 75071    int iEnd = iFirst + nCell;      /* End of loop. One past last cell to ins */
 75072    int k;                          /* Current slot in pCArray->apEnd[] */
 75073    u8 *pEnd;                       /* Maximum extent of cell data */
 75074    assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
 75075    if( iEnd<=iFirst ) return 0;
 75076    for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
 75077    pEnd = pCArray->apEnd[k];
 75078    while( 1 /*Exit by break*/ ){
 75079      int sz, rc;
 75080      u8 *pSlot;
 75081      sz = cachedCellSize(pCArray, i);
 75082      if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
 75083        if( (pData - pBegin)<sz ) return 1;
 75084        pData -= sz;
 75085        pSlot = pData;
 75086      }
 75087      /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
 75088      ** database.  But they might for a corrupt database.  Hence use memmove()
 75089      ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
 75090      assert( (pSlot+sz)<=pCArray->apCell[i]
 75091           || pSlot>=(pCArray->apCell[i]+sz)
 75092           || CORRUPT_DB );
 75093      if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
 75094       && (uptr)(pCArray->apCell[i])<(uptr)pEnd
 75095      ){
 75096        assert( CORRUPT_DB );
 75097        (void)SQLITE_CORRUPT_BKPT;
 75098        return 1;
 75099      }
 75100      memmove(pSlot, pCArray->apCell[i], sz);
 75101      put2byte(pCellptr, (pSlot - aData));
 75102      pCellptr += 2;
 75103      i++;
 75104      if( i>=iEnd ) break;
 75105      if( pCArray->ixNx[k]<=i ){
 75106        k++;
 75107        pEnd = pCArray->apEnd[k];
 75108      }
 75109    }
 75110    *ppData = pData;
 75111    return 0;
 75112  }
 75113  
 75114  /*
 75115  ** The pCArray object contains pointers to b-tree cells and their sizes.
 75116  **
 75117  ** This function adds the space associated with each cell in the array
 75118  ** that is currently stored within the body of pPg to the pPg free-list.
 75119  ** The cell-pointers and other fields of the page are not updated.
 75120  **
 75121  ** This function returns the total number of cells added to the free-list.
 75122  */
 75123  static int pageFreeArray(
 75124    MemPage *pPg,                   /* Page to edit */
 75125    int iFirst,                     /* First cell to delete */
 75126    int nCell,                      /* Cells to delete */
 75127    CellArray *pCArray              /* Array of cells */
 75128  ){
 75129    u8 * const aData = pPg->aData;
 75130    u8 * const pEnd = &aData[pPg->pBt->usableSize];
 75131    u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
 75132    int nRet = 0;
 75133    int i;
 75134    int iEnd = iFirst + nCell;
 75135    u8 *pFree = 0;
 75136    int szFree = 0;
 75137  
 75138    for(i=iFirst; i<iEnd; i++){
 75139      u8 *pCell = pCArray->apCell[i];
 75140      if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
 75141        int sz;
 75142        /* No need to use cachedCellSize() here.  The sizes of all cells that
 75143        ** are to be freed have already been computing while deciding which
 75144        ** cells need freeing */
 75145        sz = pCArray->szCell[i];  assert( sz>0 );
 75146        if( pFree!=(pCell + sz) ){
 75147          if( pFree ){
 75148            assert( pFree>aData && (pFree - aData)<65536 );
 75149            freeSpace(pPg, (u16)(pFree - aData), szFree);
 75150          }
 75151          pFree = pCell;
 75152          szFree = sz;
 75153          if( pFree+sz>pEnd ) return 0;
 75154        }else{
 75155          pFree = pCell;
 75156          szFree += sz;
 75157        }
 75158        nRet++;
 75159      }
 75160    }
 75161    if( pFree ){
 75162      assert( pFree>aData && (pFree - aData)<65536 );
 75163      freeSpace(pPg, (u16)(pFree - aData), szFree);
 75164    }
 75165    return nRet;
 75166  }
 75167  
 75168  /*
 75169  ** pCArray contains pointers to and sizes of all cells in the page being
 75170  ** balanced.  The current page, pPg, has pPg->nCell cells starting with
 75171  ** pCArray->apCell[iOld].  After balancing, this page should hold nNew cells
 75172  ** starting at apCell[iNew].
 75173  **
 75174  ** This routine makes the necessary adjustments to pPg so that it contains
 75175  ** the correct cells after being balanced.
 75176  **
 75177  ** The pPg->nFree field is invalid when this function returns. It is the
 75178  ** responsibility of the caller to set it correctly.
 75179  */
 75180  static int editPage(
 75181    MemPage *pPg,                   /* Edit this page */
 75182    int iOld,                       /* Index of first cell currently on page */
 75183    int iNew,                       /* Index of new first cell on page */
 75184    int nNew,                       /* Final number of cells on page */
 75185    CellArray *pCArray              /* Array of cells and sizes */
 75186  ){
 75187    u8 * const aData = pPg->aData;
 75188    const int hdr = pPg->hdrOffset;
 75189    u8 *pBegin = &pPg->aCellIdx[nNew * 2];
 75190    int nCell = pPg->nCell;       /* Cells stored on pPg */
 75191    u8 *pData;
 75192    u8 *pCellptr;
 75193    int i;
 75194    int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
 75195    int iNewEnd = iNew + nNew;
 75196  
 75197  #ifdef SQLITE_DEBUG
 75198    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
 75199    memcpy(pTmp, aData, pPg->pBt->usableSize);
 75200  #endif
 75201  
 75202    /* Remove cells from the start and end of the page */
 75203    assert( nCell>=0 );
 75204    if( iOld<iNew ){
 75205      int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
 75206      if( nShift>nCell ) return SQLITE_CORRUPT_BKPT;
 75207      memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
 75208      nCell -= nShift;
 75209    }
 75210    if( iNewEnd < iOldEnd ){
 75211      int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
 75212      assert( nCell>=nTail );
 75213      nCell -= nTail;
 75214    }
 75215  
 75216    pData = &aData[get2byteNotZero(&aData[hdr+5])];
 75217    if( pData<pBegin ) goto editpage_fail;
 75218  
 75219    /* Add cells to the start of the page */
 75220    if( iNew<iOld ){
 75221      int nAdd = MIN(nNew,iOld-iNew);
 75222      assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
 75223      assert( nAdd>=0 );
 75224      pCellptr = pPg->aCellIdx;
 75225      memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
 75226      if( pageInsertArray(
 75227            pPg, pBegin, &pData, pCellptr,
 75228            iNew, nAdd, pCArray
 75229      ) ) goto editpage_fail;
 75230      nCell += nAdd;
 75231    }
 75232  
 75233    /* Add any overflow cells */
 75234    for(i=0; i<pPg->nOverflow; i++){
 75235      int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
 75236      if( iCell>=0 && iCell<nNew ){
 75237        pCellptr = &pPg->aCellIdx[iCell * 2];
 75238        assert( nCell>=iCell );
 75239        memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
 75240        nCell++;
 75241        if( pageInsertArray(
 75242              pPg, pBegin, &pData, pCellptr,
 75243              iCell+iNew, 1, pCArray
 75244        ) ) goto editpage_fail;
 75245      }
 75246    }
 75247  
 75248    /* Append cells to the end of the page */
 75249    assert( nCell>=0 );
 75250    pCellptr = &pPg->aCellIdx[nCell*2];
 75251    if( pageInsertArray(
 75252          pPg, pBegin, &pData, pCellptr,
 75253          iNew+nCell, nNew-nCell, pCArray
 75254    ) ) goto editpage_fail;
 75255  
 75256    pPg->nCell = nNew;
 75257    pPg->nOverflow = 0;
 75258  
 75259    put2byte(&aData[hdr+3], pPg->nCell);
 75260    put2byte(&aData[hdr+5], pData - aData);
 75261  
 75262  #ifdef SQLITE_DEBUG
 75263    for(i=0; i<nNew && !CORRUPT_DB; i++){
 75264      u8 *pCell = pCArray->apCell[i+iNew];
 75265      int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
 75266      if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
 75267        pCell = &pTmp[pCell - aData];
 75268      }
 75269      assert( 0==memcmp(pCell, &aData[iOff],
 75270              pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
 75271    }
 75272  #endif
 75273  
 75274    return SQLITE_OK;
 75275   editpage_fail:
 75276    /* Unable to edit this page. Rebuild it from scratch instead. */
 75277    populateCellCache(pCArray, iNew, nNew);
 75278    return rebuildPage(pCArray, iNew, nNew, pPg);
 75279  }
 75280  
 75281  
 75282  #ifndef SQLITE_OMIT_QUICKBALANCE
 75283  /*
 75284  ** This version of balance() handles the common special case where
 75285  ** a new entry is being inserted on the extreme right-end of the
 75286  ** tree, in other words, when the new entry will become the largest
 75287  ** entry in the tree.
 75288  **
 75289  ** Instead of trying to balance the 3 right-most leaf pages, just add
 75290  ** a new page to the right-hand side and put the one new entry in
 75291  ** that page.  This leaves the right side of the tree somewhat
 75292  ** unbalanced.  But odds are that we will be inserting new entries
 75293  ** at the end soon afterwards so the nearly empty page will quickly
 75294  ** fill up.  On average.
 75295  **
 75296  ** pPage is the leaf page which is the right-most page in the tree.
 75297  ** pParent is its parent.  pPage must have a single overflow entry
 75298  ** which is also the right-most entry on the page.
 75299  **
 75300  ** The pSpace buffer is used to store a temporary copy of the divider
 75301  ** cell that will be inserted into pParent. Such a cell consists of a 4
 75302  ** byte page number followed by a variable length integer. In other
 75303  ** words, at most 13 bytes. Hence the pSpace buffer must be at
 75304  ** least 13 bytes in size.
 75305  */
 75306  static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
 75307    BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
 75308    MemPage *pNew;                       /* Newly allocated page */
 75309    int rc;                              /* Return Code */
 75310    Pgno pgnoNew;                        /* Page number of pNew */
 75311  
 75312    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
 75313    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 75314    assert( pPage->nOverflow==1 );
 75315  
 75316    if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
 75317  
 75318    /* Allocate a new page. This page will become the right-sibling of 
 75319    ** pPage. Make the parent page writable, so that the new divider cell
 75320    ** may be inserted. If both these operations are successful, proceed.
 75321    */
 75322    rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
 75323  
 75324    if( rc==SQLITE_OK ){
 75325  
 75326      u8 *pOut = &pSpace[4];
 75327      u8 *pCell = pPage->apOvfl[0];
 75328      u16 szCell = pPage->xCellSize(pPage, pCell);
 75329      u8 *pStop;
 75330      CellArray b;
 75331  
 75332      assert( sqlite3PagerIswriteable(pNew->pDbPage) );
 75333      assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
 75334      zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
 75335      b.nCell = 1;
 75336      b.pRef = pPage;
 75337      b.apCell = &pCell;
 75338      b.szCell = &szCell;
 75339      b.apEnd[0] = pPage->aDataEnd;
 75340      b.ixNx[0] = 2;
 75341      rc = rebuildPage(&b, 0, 1, pNew);
 75342      if( NEVER(rc) ){
 75343        releasePage(pNew);
 75344        return rc;
 75345      }
 75346      pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
 75347  
 75348      /* If this is an auto-vacuum database, update the pointer map
 75349      ** with entries for the new page, and any pointer from the 
 75350      ** cell on the page to an overflow page. If either of these
 75351      ** operations fails, the return code is set, but the contents
 75352      ** of the parent page are still manipulated by thh code below.
 75353      ** That is Ok, at this point the parent page is guaranteed to
 75354      ** be marked as dirty. Returning an error code will cause a
 75355      ** rollback, undoing any changes made to the parent page.
 75356      */
 75357      if( ISAUTOVACUUM ){
 75358        ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
 75359        if( szCell>pNew->minLocal ){
 75360          ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
 75361        }
 75362      }
 75363    
 75364      /* Create a divider cell to insert into pParent. The divider cell
 75365      ** consists of a 4-byte page number (the page number of pPage) and
 75366      ** a variable length key value (which must be the same value as the
 75367      ** largest key on pPage).
 75368      **
 75369      ** To find the largest key value on pPage, first find the right-most 
 75370      ** cell on pPage. The first two fields of this cell are the 
 75371      ** record-length (a variable length integer at most 32-bits in size)
 75372      ** and the key value (a variable length integer, may have any value).
 75373      ** The first of the while(...) loops below skips over the record-length
 75374      ** field. The second while(...) loop copies the key value from the
 75375      ** cell on pPage into the pSpace buffer.
 75376      */
 75377      pCell = findCell(pPage, pPage->nCell-1);
 75378      pStop = &pCell[9];
 75379      while( (*(pCell++)&0x80) && pCell<pStop );
 75380      pStop = &pCell[9];
 75381      while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
 75382  
 75383      /* Insert the new divider cell into pParent. */
 75384      if( rc==SQLITE_OK ){
 75385        insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
 75386                     0, pPage->pgno, &rc);
 75387      }
 75388  
 75389      /* Set the right-child pointer of pParent to point to the new page. */
 75390      put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
 75391    
 75392      /* Release the reference to the new page. */
 75393      releasePage(pNew);
 75394    }
 75395  
 75396    return rc;
 75397  }
 75398  #endif /* SQLITE_OMIT_QUICKBALANCE */
 75399  
 75400  #if 0
 75401  /*
 75402  ** This function does not contribute anything to the operation of SQLite.
 75403  ** it is sometimes activated temporarily while debugging code responsible 
 75404  ** for setting pointer-map entries.
 75405  */
 75406  static int ptrmapCheckPages(MemPage **apPage, int nPage){
 75407    int i, j;
 75408    for(i=0; i<nPage; i++){
 75409      Pgno n;
 75410      u8 e;
 75411      MemPage *pPage = apPage[i];
 75412      BtShared *pBt = pPage->pBt;
 75413      assert( pPage->isInit );
 75414  
 75415      for(j=0; j<pPage->nCell; j++){
 75416        CellInfo info;
 75417        u8 *z;
 75418       
 75419        z = findCell(pPage, j);
 75420        pPage->xParseCell(pPage, z, &info);
 75421        if( info.nLocal<info.nPayload ){
 75422          Pgno ovfl = get4byte(&z[info.nSize-4]);
 75423          ptrmapGet(pBt, ovfl, &e, &n);
 75424          assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
 75425        }
 75426        if( !pPage->leaf ){
 75427          Pgno child = get4byte(z);
 75428          ptrmapGet(pBt, child, &e, &n);
 75429          assert( n==pPage->pgno && e==PTRMAP_BTREE );
 75430        }
 75431      }
 75432      if( !pPage->leaf ){
 75433        Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
 75434        ptrmapGet(pBt, child, &e, &n);
 75435        assert( n==pPage->pgno && e==PTRMAP_BTREE );
 75436      }
 75437    }
 75438    return 1;
 75439  }
 75440  #endif
 75441  
 75442  /*
 75443  ** This function is used to copy the contents of the b-tree node stored 
 75444  ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
 75445  ** the pointer-map entries for each child page are updated so that the
 75446  ** parent page stored in the pointer map is page pTo. If pFrom contained
 75447  ** any cells with overflow page pointers, then the corresponding pointer
 75448  ** map entries are also updated so that the parent page is page pTo.
 75449  **
 75450  ** If pFrom is currently carrying any overflow cells (entries in the
 75451  ** MemPage.apOvfl[] array), they are not copied to pTo. 
 75452  **
 75453  ** Before returning, page pTo is reinitialized using btreeInitPage().
 75454  **
 75455  ** The performance of this function is not critical. It is only used by 
 75456  ** the balance_shallower() and balance_deeper() procedures, neither of
 75457  ** which are called often under normal circumstances.
 75458  */
 75459  static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 75460    if( (*pRC)==SQLITE_OK ){
 75461      BtShared * const pBt = pFrom->pBt;
 75462      u8 * const aFrom = pFrom->aData;
 75463      u8 * const aTo = pTo->aData;
 75464      int const iFromHdr = pFrom->hdrOffset;
 75465      int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
 75466      int rc;
 75467      int iData;
 75468    
 75469    
 75470      assert( pFrom->isInit );
 75471      assert( pFrom->nFree>=iToHdr );
 75472      assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
 75473    
 75474      /* Copy the b-tree node content from page pFrom to page pTo. */
 75475      iData = get2byte(&aFrom[iFromHdr+5]);
 75476      memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
 75477      memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
 75478    
 75479      /* Reinitialize page pTo so that the contents of the MemPage structure
 75480      ** match the new data. The initialization of pTo can actually fail under
 75481      ** fairly obscure circumstances, even though it is a copy of initialized 
 75482      ** page pFrom.
 75483      */
 75484      pTo->isInit = 0;
 75485      rc = btreeInitPage(pTo);
 75486      if( rc!=SQLITE_OK ){
 75487        *pRC = rc;
 75488        return;
 75489      }
 75490    
 75491      /* If this is an auto-vacuum database, update the pointer-map entries
 75492      ** for any b-tree or overflow pages that pTo now contains the pointers to.
 75493      */
 75494      if( ISAUTOVACUUM ){
 75495        *pRC = setChildPtrmaps(pTo);
 75496      }
 75497    }
 75498  }
 75499  
 75500  /*
 75501  ** This routine redistributes cells on the iParentIdx'th child of pParent
 75502  ** (hereafter "the page") and up to 2 siblings so that all pages have about the
 75503  ** same amount of free space. Usually a single sibling on either side of the
 75504  ** page are used in the balancing, though both siblings might come from one
 75505  ** side if the page is the first or last child of its parent. If the page 
 75506  ** has fewer than 2 siblings (something which can only happen if the page
 75507  ** is a root page or a child of a root page) then all available siblings
 75508  ** participate in the balancing.
 75509  **
 75510  ** The number of siblings of the page might be increased or decreased by 
 75511  ** one or two in an effort to keep pages nearly full but not over full. 
 75512  **
 75513  ** Note that when this routine is called, some of the cells on the page
 75514  ** might not actually be stored in MemPage.aData[]. This can happen
 75515  ** if the page is overfull. This routine ensures that all cells allocated
 75516  ** to the page and its siblings fit into MemPage.aData[] before returning.
 75517  **
 75518  ** In the course of balancing the page and its siblings, cells may be
 75519  ** inserted into or removed from the parent page (pParent). Doing so
 75520  ** may cause the parent page to become overfull or underfull. If this
 75521  ** happens, it is the responsibility of the caller to invoke the correct
 75522  ** balancing routine to fix this problem (see the balance() routine). 
 75523  **
 75524  ** If this routine fails for any reason, it might leave the database
 75525  ** in a corrupted state. So if this routine fails, the database should
 75526  ** be rolled back.
 75527  **
 75528  ** The third argument to this function, aOvflSpace, is a pointer to a
 75529  ** buffer big enough to hold one page. If while inserting cells into the parent
 75530  ** page (pParent) the parent page becomes overfull, this buffer is
 75531  ** used to store the parent's overflow cells. Because this function inserts
 75532  ** a maximum of four divider cells into the parent page, and the maximum
 75533  ** size of a cell stored within an internal node is always less than 1/4
 75534  ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
 75535  ** enough for all overflow cells.
 75536  **
 75537  ** If aOvflSpace is set to a null pointer, this function returns 
 75538  ** SQLITE_NOMEM.
 75539  */
 75540  static int balance_nonroot(
 75541    MemPage *pParent,               /* Parent page of siblings being balanced */
 75542    int iParentIdx,                 /* Index of "the page" in pParent */
 75543    u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
 75544    int isRoot,                     /* True if pParent is a root-page */
 75545    int bBulk                       /* True if this call is part of a bulk load */
 75546  ){
 75547    BtShared *pBt;               /* The whole database */
 75548    int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
 75549    int nNew = 0;                /* Number of pages in apNew[] */
 75550    int nOld;                    /* Number of pages in apOld[] */
 75551    int i, j, k;                 /* Loop counters */
 75552    int nxDiv;                   /* Next divider slot in pParent->aCell[] */
 75553    int rc = SQLITE_OK;          /* The return code */
 75554    u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
 75555    int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
 75556    int usableSpace;             /* Bytes in pPage beyond the header */
 75557    int pageFlags;               /* Value of pPage->aData[0] */
 75558    int iSpace1 = 0;             /* First unused byte of aSpace1[] */
 75559    int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
 75560    int szScratch;               /* Size of scratch memory requested */
 75561    MemPage *apOld[NB];          /* pPage and up to two siblings */
 75562    MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
 75563    u8 *pRight;                  /* Location in parent of right-sibling pointer */
 75564    u8 *apDiv[NB-1];             /* Divider cells in pParent */
 75565    int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
 75566    int cntOld[NB+2];            /* Old index in b.apCell[] */
 75567    int szNew[NB+2];             /* Combined size of cells placed on i-th page */
 75568    u8 *aSpace1;                 /* Space for copies of dividers cells */
 75569    Pgno pgno;                   /* Temp var to store a page number in */
 75570    u8 abDone[NB+2];             /* True after i'th new page is populated */
 75571    Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
 75572    Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
 75573    u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
 75574    CellArray b;                  /* Parsed information on cells being balanced */
 75575  
 75576    memset(abDone, 0, sizeof(abDone));
 75577    b.nCell = 0;
 75578    b.apCell = 0;
 75579    pBt = pParent->pBt;
 75580    assert( sqlite3_mutex_held(pBt->mutex) );
 75581    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 75582  
 75583    /* At this point pParent may have at most one overflow cell. And if
 75584    ** this overflow cell is present, it must be the cell with 
 75585    ** index iParentIdx. This scenario comes about when this function
 75586    ** is called (indirectly) from sqlite3BtreeDelete().
 75587    */
 75588    assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
 75589    assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
 75590  
 75591    if( !aOvflSpace ){
 75592      return SQLITE_NOMEM_BKPT;
 75593    }
 75594  
 75595    /* Find the sibling pages to balance. Also locate the cells in pParent 
 75596    ** that divide the siblings. An attempt is made to find NN siblings on 
 75597    ** either side of pPage. More siblings are taken from one side, however, 
 75598    ** if there are fewer than NN siblings on the other side. If pParent
 75599    ** has NB or fewer children then all children of pParent are taken.  
 75600    **
 75601    ** This loop also drops the divider cells from the parent page. This
 75602    ** way, the remainder of the function does not have to deal with any
 75603    ** overflow cells in the parent page, since if any existed they will
 75604    ** have already been removed.
 75605    */
 75606    i = pParent->nOverflow + pParent->nCell;
 75607    if( i<2 ){
 75608      nxDiv = 0;
 75609    }else{
 75610      assert( bBulk==0 || bBulk==1 );
 75611      if( iParentIdx==0 ){                 
 75612        nxDiv = 0;
 75613      }else if( iParentIdx==i ){
 75614        nxDiv = i-2+bBulk;
 75615      }else{
 75616        nxDiv = iParentIdx-1;
 75617      }
 75618      i = 2-bBulk;
 75619    }
 75620    nOld = i+1;
 75621    if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
 75622      pRight = &pParent->aData[pParent->hdrOffset+8];
 75623    }else{
 75624      pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
 75625    }
 75626    pgno = get4byte(pRight);
 75627    while( 1 ){
 75628      rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
 75629      if( rc ){
 75630        memset(apOld, 0, (i+1)*sizeof(MemPage*));
 75631        goto balance_cleanup;
 75632      }
 75633      nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
 75634      if( (i--)==0 ) break;
 75635  
 75636      if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
 75637        apDiv[i] = pParent->apOvfl[0];
 75638        pgno = get4byte(apDiv[i]);
 75639        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
 75640        pParent->nOverflow = 0;
 75641      }else{
 75642        apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
 75643        pgno = get4byte(apDiv[i]);
 75644        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
 75645  
 75646        /* Drop the cell from the parent page. apDiv[i] still points to
 75647        ** the cell within the parent, even though it has been dropped.
 75648        ** This is safe because dropping a cell only overwrites the first
 75649        ** four bytes of it, and this function does not need the first
 75650        ** four bytes of the divider cell. So the pointer is safe to use
 75651        ** later on.  
 75652        **
 75653        ** But not if we are in secure-delete mode. In secure-delete mode,
 75654        ** the dropCell() routine will overwrite the entire cell with zeroes.
 75655        ** In this case, temporarily copy the cell into the aOvflSpace[]
 75656        ** buffer. It will be copied out again as soon as the aSpace[] buffer
 75657        ** is allocated.  */
 75658        if( pBt->btsFlags & BTS_FAST_SECURE ){
 75659          int iOff;
 75660  
 75661          iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
 75662          if( (iOff+szNew[i])>(int)pBt->usableSize ){
 75663            rc = SQLITE_CORRUPT_BKPT;
 75664            memset(apOld, 0, (i+1)*sizeof(MemPage*));
 75665            goto balance_cleanup;
 75666          }else{
 75667            memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
 75668            apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
 75669          }
 75670        }
 75671        dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
 75672      }
 75673    }
 75674  
 75675    /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
 75676    ** alignment */
 75677    nMaxCells = (nMaxCells + 3)&~3;
 75678  
 75679    /*
 75680    ** Allocate space for memory structures
 75681    */
 75682    szScratch =
 75683         nMaxCells*sizeof(u8*)                       /* b.apCell */
 75684       + nMaxCells*sizeof(u16)                       /* b.szCell */
 75685       + pBt->pageSize;                              /* aSpace1 */
 75686  
 75687    assert( szScratch<=6*(int)pBt->pageSize );
 75688    b.apCell = sqlite3StackAllocRaw(0, szScratch );
 75689    if( b.apCell==0 ){
 75690      rc = SQLITE_NOMEM_BKPT;
 75691      goto balance_cleanup;
 75692    }
 75693    b.szCell = (u16*)&b.apCell[nMaxCells];
 75694    aSpace1 = (u8*)&b.szCell[nMaxCells];
 75695    assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
 75696  
 75697    /*
 75698    ** Load pointers to all cells on sibling pages and the divider cells
 75699    ** into the local b.apCell[] array.  Make copies of the divider cells
 75700    ** into space obtained from aSpace1[]. The divider cells have already
 75701    ** been removed from pParent.
 75702    **
 75703    ** If the siblings are on leaf pages, then the child pointers of the
 75704    ** divider cells are stripped from the cells before they are copied
 75705    ** into aSpace1[].  In this way, all cells in b.apCell[] are without
 75706    ** child pointers.  If siblings are not leaves, then all cell in
 75707    ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
 75708    ** are alike.
 75709    **
 75710    ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
 75711    **       leafData:  1 if pPage holds key+data and pParent holds only keys.
 75712    */
 75713    b.pRef = apOld[0];
 75714    leafCorrection = b.pRef->leaf*4;
 75715    leafData = b.pRef->intKeyLeaf;
 75716    for(i=0; i<nOld; i++){
 75717      MemPage *pOld = apOld[i];
 75718      int limit = pOld->nCell;
 75719      u8 *aData = pOld->aData;
 75720      u16 maskPage = pOld->maskPage;
 75721      u8 *piCell = aData + pOld->cellOffset;
 75722      u8 *piEnd;
 75723  
 75724      /* Verify that all sibling pages are of the same "type" (table-leaf,
 75725      ** table-interior, index-leaf, or index-interior).
 75726      */
 75727      if( pOld->aData[0]!=apOld[0]->aData[0] ){
 75728        rc = SQLITE_CORRUPT_BKPT;
 75729        goto balance_cleanup;
 75730      }
 75731  
 75732      /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
 75733      ** contains overflow cells, include them in the b.apCell[] array
 75734      ** in the correct spot.
 75735      **
 75736      ** Note that when there are multiple overflow cells, it is always the
 75737      ** case that they are sequential and adjacent.  This invariant arises
 75738      ** because multiple overflows can only occurs when inserting divider
 75739      ** cells into a parent on a prior balance, and divider cells are always
 75740      ** adjacent and are inserted in order.  There is an assert() tagged
 75741      ** with "NOTE 1" in the overflow cell insertion loop to prove this
 75742      ** invariant.
 75743      **
 75744      ** This must be done in advance.  Once the balance starts, the cell
 75745      ** offset section of the btree page will be overwritten and we will no
 75746      ** long be able to find the cells if a pointer to each cell is not saved
 75747      ** first.
 75748      */
 75749      memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
 75750      if( pOld->nOverflow>0 ){
 75751        limit = pOld->aiOvfl[0];
 75752        for(j=0; j<limit; j++){
 75753          b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
 75754          piCell += 2;
 75755          b.nCell++;
 75756        }
 75757        for(k=0; k<pOld->nOverflow; k++){
 75758          assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
 75759          b.apCell[b.nCell] = pOld->apOvfl[k];
 75760          b.nCell++;
 75761        }
 75762      }
 75763      piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
 75764      while( piCell<piEnd ){
 75765        assert( b.nCell<nMaxCells );
 75766        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
 75767        piCell += 2;
 75768        b.nCell++;
 75769      }
 75770  
 75771      cntOld[i] = b.nCell;
 75772      if( i<nOld-1 && !leafData){
 75773        u16 sz = (u16)szNew[i];
 75774        u8 *pTemp;
 75775        assert( b.nCell<nMaxCells );
 75776        b.szCell[b.nCell] = sz;
 75777        pTemp = &aSpace1[iSpace1];
 75778        iSpace1 += sz;
 75779        assert( sz<=pBt->maxLocal+23 );
 75780        assert( iSpace1 <= (int)pBt->pageSize );
 75781        memcpy(pTemp, apDiv[i], sz);
 75782        b.apCell[b.nCell] = pTemp+leafCorrection;
 75783        assert( leafCorrection==0 || leafCorrection==4 );
 75784        b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
 75785        if( !pOld->leaf ){
 75786          assert( leafCorrection==0 );
 75787          assert( pOld->hdrOffset==0 );
 75788          /* The right pointer of the child page pOld becomes the left
 75789          ** pointer of the divider cell */
 75790          memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
 75791        }else{
 75792          assert( leafCorrection==4 );
 75793          while( b.szCell[b.nCell]<4 ){
 75794            /* Do not allow any cells smaller than 4 bytes. If a smaller cell
 75795            ** does exist, pad it with 0x00 bytes. */
 75796            assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
 75797            assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
 75798            aSpace1[iSpace1++] = 0x00;
 75799            b.szCell[b.nCell]++;
 75800          }
 75801        }
 75802        b.nCell++;
 75803      }
 75804    }
 75805  
 75806    /*
 75807    ** Figure out the number of pages needed to hold all b.nCell cells.
 75808    ** Store this number in "k".  Also compute szNew[] which is the total
 75809    ** size of all cells on the i-th page and cntNew[] which is the index
 75810    ** in b.apCell[] of the cell that divides page i from page i+1.  
 75811    ** cntNew[k] should equal b.nCell.
 75812    **
 75813    ** Values computed by this block:
 75814    **
 75815    **           k: The total number of sibling pages
 75816    **    szNew[i]: Spaced used on the i-th sibling page.
 75817    **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
 75818    **              the right of the i-th sibling page.
 75819    ** usableSpace: Number of bytes of space available on each sibling.
 75820    ** 
 75821    */
 75822    usableSpace = pBt->usableSize - 12 + leafCorrection;
 75823    for(i=k=0; i<nOld; i++, k++){
 75824      MemPage *p = apOld[i];
 75825      b.apEnd[k] = p->aDataEnd;
 75826      b.ixNx[k] = cntOld[i];
 75827      if( !leafData ){
 75828        k++;
 75829        b.apEnd[k] = pParent->aDataEnd;
 75830        b.ixNx[k] = cntOld[i]+1;
 75831      }
 75832      szNew[i] = usableSpace - p->nFree;
 75833      for(j=0; j<p->nOverflow; j++){
 75834        szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
 75835      }
 75836      cntNew[i] = cntOld[i];
 75837    }
 75838    k = nOld;
 75839    for(i=0; i<k; i++){
 75840      int sz;
 75841      while( szNew[i]>usableSpace ){
 75842        if( i+1>=k ){
 75843          k = i+2;
 75844          if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
 75845          szNew[k-1] = 0;
 75846          cntNew[k-1] = b.nCell;
 75847        }
 75848        sz = 2 + cachedCellSize(&b, cntNew[i]-1);
 75849        szNew[i] -= sz;
 75850        if( !leafData ){
 75851          if( cntNew[i]<b.nCell ){
 75852            sz = 2 + cachedCellSize(&b, cntNew[i]);
 75853          }else{
 75854            sz = 0;
 75855          }
 75856        }
 75857        szNew[i+1] += sz;
 75858        cntNew[i]--;
 75859      }
 75860      while( cntNew[i]<b.nCell ){
 75861        sz = 2 + cachedCellSize(&b, cntNew[i]);
 75862        if( szNew[i]+sz>usableSpace ) break;
 75863        szNew[i] += sz;
 75864        cntNew[i]++;
 75865        if( !leafData ){
 75866          if( cntNew[i]<b.nCell ){
 75867            sz = 2 + cachedCellSize(&b, cntNew[i]);
 75868          }else{
 75869            sz = 0;
 75870          }
 75871        }
 75872        szNew[i+1] -= sz;
 75873      }
 75874      if( cntNew[i]>=b.nCell ){
 75875        k = i+1;
 75876      }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
 75877        rc = SQLITE_CORRUPT_BKPT;
 75878        goto balance_cleanup;
 75879      }
 75880    }
 75881  
 75882    /*
 75883    ** The packing computed by the previous block is biased toward the siblings
 75884    ** on the left side (siblings with smaller keys). The left siblings are
 75885    ** always nearly full, while the right-most sibling might be nearly empty.
 75886    ** The next block of code attempts to adjust the packing of siblings to
 75887    ** get a better balance.
 75888    **
 75889    ** This adjustment is more than an optimization.  The packing above might
 75890    ** be so out of balance as to be illegal.  For example, the right-most
 75891    ** sibling might be completely empty.  This adjustment is not optional.
 75892    */
 75893    for(i=k-1; i>0; i--){
 75894      int szRight = szNew[i];  /* Size of sibling on the right */
 75895      int szLeft = szNew[i-1]; /* Size of sibling on the left */
 75896      int r;              /* Index of right-most cell in left sibling */
 75897      int d;              /* Index of first cell to the left of right sibling */
 75898  
 75899      r = cntNew[i-1] - 1;
 75900      d = r + 1 - leafData;
 75901      (void)cachedCellSize(&b, d);
 75902      do{
 75903        assert( d<nMaxCells );
 75904        assert( r<nMaxCells );
 75905        (void)cachedCellSize(&b, r);
 75906        if( szRight!=0
 75907         && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
 75908          break;
 75909        }
 75910        szRight += b.szCell[d] + 2;
 75911        szLeft -= b.szCell[r] + 2;
 75912        cntNew[i-1] = r;
 75913        r--;
 75914        d--;
 75915      }while( r>=0 );
 75916      szNew[i] = szRight;
 75917      szNew[i-1] = szLeft;
 75918      if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
 75919        rc = SQLITE_CORRUPT_BKPT;
 75920        goto balance_cleanup;
 75921      }
 75922    }
 75923  
 75924    /* Sanity check:  For a non-corrupt database file one of the follwing
 75925    ** must be true:
 75926    **    (1) We found one or more cells (cntNew[0])>0), or
 75927    **    (2) pPage is a virtual root page.  A virtual root page is when
 75928    **        the real root page is page 1 and we are the only child of
 75929    **        that page.
 75930    */
 75931    assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
 75932    TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
 75933      apOld[0]->pgno, apOld[0]->nCell,
 75934      nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
 75935      nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
 75936    ));
 75937  
 75938    /*
 75939    ** Allocate k new pages.  Reuse old pages where possible.
 75940    */
 75941    pageFlags = apOld[0]->aData[0];
 75942    for(i=0; i<k; i++){
 75943      MemPage *pNew;
 75944      if( i<nOld ){
 75945        pNew = apNew[i] = apOld[i];
 75946        apOld[i] = 0;
 75947        rc = sqlite3PagerWrite(pNew->pDbPage);
 75948        nNew++;
 75949        if( rc ) goto balance_cleanup;
 75950      }else{
 75951        assert( i>0 );
 75952        rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
 75953        if( rc ) goto balance_cleanup;
 75954        zeroPage(pNew, pageFlags);
 75955        apNew[i] = pNew;
 75956        nNew++;
 75957        cntOld[i] = b.nCell;
 75958  
 75959        /* Set the pointer-map entry for the new sibling page. */
 75960        if( ISAUTOVACUUM ){
 75961          ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
 75962          if( rc!=SQLITE_OK ){
 75963            goto balance_cleanup;
 75964          }
 75965        }
 75966      }
 75967    }
 75968  
 75969    /*
 75970    ** Reassign page numbers so that the new pages are in ascending order. 
 75971    ** This helps to keep entries in the disk file in order so that a scan
 75972    ** of the table is closer to a linear scan through the file. That in turn 
 75973    ** helps the operating system to deliver pages from the disk more rapidly.
 75974    **
 75975    ** An O(n^2) insertion sort algorithm is used, but since n is never more 
 75976    ** than (NB+2) (a small constant), that should not be a problem.
 75977    **
 75978    ** When NB==3, this one optimization makes the database about 25% faster 
 75979    ** for large insertions and deletions.
 75980    */
 75981    for(i=0; i<nNew; i++){
 75982      aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
 75983      aPgFlags[i] = apNew[i]->pDbPage->flags;
 75984      for(j=0; j<i; j++){
 75985        if( aPgno[j]==aPgno[i] ){
 75986          /* This branch is taken if the set of sibling pages somehow contains
 75987          ** duplicate entries. This can happen if the database is corrupt. 
 75988          ** It would be simpler to detect this as part of the loop below, but
 75989          ** we do the detection here in order to avoid populating the pager
 75990          ** cache with two separate objects associated with the same
 75991          ** page number.  */
 75992          assert( CORRUPT_DB );
 75993          rc = SQLITE_CORRUPT_BKPT;
 75994          goto balance_cleanup;
 75995        }
 75996      }
 75997    }
 75998    for(i=0; i<nNew; i++){
 75999      int iBest = 0;                /* aPgno[] index of page number to use */
 76000      for(j=1; j<nNew; j++){
 76001        if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
 76002      }
 76003      pgno = aPgOrder[iBest];
 76004      aPgOrder[iBest] = 0xffffffff;
 76005      if( iBest!=i ){
 76006        if( iBest>i ){
 76007          sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
 76008        }
 76009        sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
 76010        apNew[i]->pgno = pgno;
 76011      }
 76012    }
 76013  
 76014    TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
 76015           "%d(%d nc=%d) %d(%d nc=%d)\n",
 76016      apNew[0]->pgno, szNew[0], cntNew[0],
 76017      nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
 76018      nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
 76019      nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
 76020      nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
 76021      nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
 76022      nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
 76023      nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
 76024      nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
 76025    ));
 76026  
 76027    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 76028    put4byte(pRight, apNew[nNew-1]->pgno);
 76029  
 76030    /* If the sibling pages are not leaves, ensure that the right-child pointer
 76031    ** of the right-most new sibling page is set to the value that was 
 76032    ** originally in the same field of the right-most old sibling page. */
 76033    if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
 76034      MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
 76035      memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
 76036    }
 76037  
 76038    /* Make any required updates to pointer map entries associated with 
 76039    ** cells stored on sibling pages following the balance operation. Pointer
 76040    ** map entries associated with divider cells are set by the insertCell()
 76041    ** routine. The associated pointer map entries are:
 76042    **
 76043    **   a) if the cell contains a reference to an overflow chain, the
 76044    **      entry associated with the first page in the overflow chain, and
 76045    **
 76046    **   b) if the sibling pages are not leaves, the child page associated
 76047    **      with the cell.
 76048    **
 76049    ** If the sibling pages are not leaves, then the pointer map entry 
 76050    ** associated with the right-child of each sibling may also need to be 
 76051    ** updated. This happens below, after the sibling pages have been 
 76052    ** populated, not here.
 76053    */
 76054    if( ISAUTOVACUUM ){
 76055      MemPage *pOld;
 76056      MemPage *pNew = pOld = apNew[0];
 76057      u8 *aOld = pNew->aData;
 76058      int cntOldNext = pNew->nCell + pNew->nOverflow;
 76059      int usableSize = pBt->usableSize;
 76060      int iNew = 0;
 76061      int iOld = 0;
 76062  
 76063      for(i=0; i<b.nCell; i++){
 76064        u8 *pCell = b.apCell[i];
 76065        if( i==cntOldNext ){
 76066          pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
 76067          cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
 76068          aOld = pOld->aData;
 76069        }
 76070        if( i==cntNew[iNew] ){
 76071          pNew = apNew[++iNew];
 76072          if( !leafData ) continue;
 76073        }
 76074  
 76075        /* Cell pCell is destined for new sibling page pNew. Originally, it
 76076        ** was either part of sibling page iOld (possibly an overflow cell), 
 76077        ** or else the divider cell to the left of sibling page iOld. So,
 76078        ** if sibling page iOld had the same page number as pNew, and if
 76079        ** pCell really was a part of sibling page iOld (not a divider or
 76080        ** overflow cell), we can skip updating the pointer map entries.  */
 76081        if( iOld>=nNew
 76082         || pNew->pgno!=aPgno[iOld]
 76083         || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
 76084        ){
 76085          if( !leafCorrection ){
 76086            ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
 76087          }
 76088          if( cachedCellSize(&b,i)>pNew->minLocal ){
 76089            ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
 76090          }
 76091          if( rc ) goto balance_cleanup;
 76092        }
 76093      }
 76094    }
 76095  
 76096    /* Insert new divider cells into pParent. */
 76097    for(i=0; i<nNew-1; i++){
 76098      u8 *pCell;
 76099      u8 *pTemp;
 76100      int sz;
 76101      MemPage *pNew = apNew[i];
 76102      j = cntNew[i];
 76103  
 76104      assert( j<nMaxCells );
 76105      assert( b.apCell[j]!=0 );
 76106      pCell = b.apCell[j];
 76107      sz = b.szCell[j] + leafCorrection;
 76108      pTemp = &aOvflSpace[iOvflSpace];
 76109      if( !pNew->leaf ){
 76110        memcpy(&pNew->aData[8], pCell, 4);
 76111      }else if( leafData ){
 76112        /* If the tree is a leaf-data tree, and the siblings are leaves, 
 76113        ** then there is no divider cell in b.apCell[]. Instead, the divider 
 76114        ** cell consists of the integer key for the right-most cell of 
 76115        ** the sibling-page assembled above only.
 76116        */
 76117        CellInfo info;
 76118        j--;
 76119        pNew->xParseCell(pNew, b.apCell[j], &info);
 76120        pCell = pTemp;
 76121        sz = 4 + putVarint(&pCell[4], info.nKey);
 76122        pTemp = 0;
 76123      }else{
 76124        pCell -= 4;
 76125        /* Obscure case for non-leaf-data trees: If the cell at pCell was
 76126        ** previously stored on a leaf node, and its reported size was 4
 76127        ** bytes, then it may actually be smaller than this 
 76128        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
 76129        ** any cell). But it is important to pass the correct size to 
 76130        ** insertCell(), so reparse the cell now.
 76131        **
 76132        ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
 76133        ** and WITHOUT ROWID tables with exactly one column which is the
 76134        ** primary key.
 76135        */
 76136        if( b.szCell[j]==4 ){
 76137          assert(leafCorrection==4);
 76138          sz = pParent->xCellSize(pParent, pCell);
 76139        }
 76140      }
 76141      iOvflSpace += sz;
 76142      assert( sz<=pBt->maxLocal+23 );
 76143      assert( iOvflSpace <= (int)pBt->pageSize );
 76144      insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
 76145      if( rc!=SQLITE_OK ) goto balance_cleanup;
 76146      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 76147    }
 76148  
 76149    /* Now update the actual sibling pages. The order in which they are updated
 76150    ** is important, as this code needs to avoid disrupting any page from which
 76151    ** cells may still to be read. In practice, this means:
 76152    **
 76153    **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
 76154    **      then it is not safe to update page apNew[iPg] until after
 76155    **      the left-hand sibling apNew[iPg-1] has been updated.
 76156    **
 76157    **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
 76158    **      then it is not safe to update page apNew[iPg] until after
 76159    **      the right-hand sibling apNew[iPg+1] has been updated.
 76160    **
 76161    ** If neither of the above apply, the page is safe to update.
 76162    **
 76163    ** The iPg value in the following loop starts at nNew-1 goes down
 76164    ** to 0, then back up to nNew-1 again, thus making two passes over
 76165    ** the pages.  On the initial downward pass, only condition (1) above
 76166    ** needs to be tested because (2) will always be true from the previous
 76167    ** step.  On the upward pass, both conditions are always true, so the
 76168    ** upwards pass simply processes pages that were missed on the downward
 76169    ** pass.
 76170    */
 76171    for(i=1-nNew; i<nNew; i++){
 76172      int iPg = i<0 ? -i : i;
 76173      assert( iPg>=0 && iPg<nNew );
 76174      if( abDone[iPg] ) continue;         /* Skip pages already processed */
 76175      if( i>=0                            /* On the upwards pass, or... */
 76176       || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
 76177      ){
 76178        int iNew;
 76179        int iOld;
 76180        int nNewCell;
 76181  
 76182        /* Verify condition (1):  If cells are moving left, update iPg
 76183        ** only after iPg-1 has already been updated. */
 76184        assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
 76185  
 76186        /* Verify condition (2):  If cells are moving right, update iPg
 76187        ** only after iPg+1 has already been updated. */
 76188        assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
 76189  
 76190        if( iPg==0 ){
 76191          iNew = iOld = 0;
 76192          nNewCell = cntNew[0];
 76193        }else{
 76194          iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
 76195          iNew = cntNew[iPg-1] + !leafData;
 76196          nNewCell = cntNew[iPg] - iNew;
 76197        }
 76198  
 76199        rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
 76200        if( rc ) goto balance_cleanup;
 76201        abDone[iPg]++;
 76202        apNew[iPg]->nFree = usableSpace-szNew[iPg];
 76203        assert( apNew[iPg]->nOverflow==0 );
 76204        assert( apNew[iPg]->nCell==nNewCell );
 76205      }
 76206    }
 76207  
 76208    /* All pages have been processed exactly once */
 76209    assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
 76210  
 76211    assert( nOld>0 );
 76212    assert( nNew>0 );
 76213  
 76214    if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
 76215      /* The root page of the b-tree now contains no cells. The only sibling
 76216      ** page is the right-child of the parent. Copy the contents of the
 76217      ** child page into the parent, decreasing the overall height of the
 76218      ** b-tree structure by one. This is described as the "balance-shallower"
 76219      ** sub-algorithm in some documentation.
 76220      **
 76221      ** If this is an auto-vacuum database, the call to copyNodeContent() 
 76222      ** sets all pointer-map entries corresponding to database image pages 
 76223      ** for which the pointer is stored within the content being copied.
 76224      **
 76225      ** It is critical that the child page be defragmented before being
 76226      ** copied into the parent, because if the parent is page 1 then it will
 76227      ** by smaller than the child due to the database header, and so all the
 76228      ** free space needs to be up front.
 76229      */
 76230      assert( nNew==1 || CORRUPT_DB );
 76231      rc = defragmentPage(apNew[0], -1);
 76232      testcase( rc!=SQLITE_OK );
 76233      assert( apNew[0]->nFree == 
 76234          (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
 76235        || rc!=SQLITE_OK
 76236      );
 76237      copyNodeContent(apNew[0], pParent, &rc);
 76238      freePage(apNew[0], &rc);
 76239    }else if( ISAUTOVACUUM && !leafCorrection ){
 76240      /* Fix the pointer map entries associated with the right-child of each
 76241      ** sibling page. All other pointer map entries have already been taken
 76242      ** care of.  */
 76243      for(i=0; i<nNew; i++){
 76244        u32 key = get4byte(&apNew[i]->aData[8]);
 76245        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
 76246      }
 76247    }
 76248  
 76249    assert( pParent->isInit );
 76250    TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
 76251            nOld, nNew, b.nCell));
 76252  
 76253    /* Free any old pages that were not reused as new pages.
 76254    */
 76255    for(i=nNew; i<nOld; i++){
 76256      freePage(apOld[i], &rc);
 76257    }
 76258  
 76259  #if 0
 76260    if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
 76261      /* The ptrmapCheckPages() contains assert() statements that verify that
 76262      ** all pointer map pages are set correctly. This is helpful while 
 76263      ** debugging. This is usually disabled because a corrupt database may
 76264      ** cause an assert() statement to fail.  */
 76265      ptrmapCheckPages(apNew, nNew);
 76266      ptrmapCheckPages(&pParent, 1);
 76267    }
 76268  #endif
 76269  
 76270    /*
 76271    ** Cleanup before returning.
 76272    */
 76273  balance_cleanup:
 76274    sqlite3StackFree(0, b.apCell);
 76275    for(i=0; i<nOld; i++){
 76276      releasePage(apOld[i]);
 76277    }
 76278    for(i=0; i<nNew; i++){
 76279      releasePage(apNew[i]);
 76280    }
 76281  
 76282    return rc;
 76283  }
 76284  
 76285  
 76286  /*
 76287  ** This function is called when the root page of a b-tree structure is
 76288  ** overfull (has one or more overflow pages).
 76289  **
 76290  ** A new child page is allocated and the contents of the current root
 76291  ** page, including overflow cells, are copied into the child. The root
 76292  ** page is then overwritten to make it an empty page with the right-child 
 76293  ** pointer pointing to the new page.
 76294  **
 76295  ** Before returning, all pointer-map entries corresponding to pages 
 76296  ** that the new child-page now contains pointers to are updated. The
 76297  ** entry corresponding to the new right-child pointer of the root
 76298  ** page is also updated.
 76299  **
 76300  ** If successful, *ppChild is set to contain a reference to the child 
 76301  ** page and SQLITE_OK is returned. In this case the caller is required
 76302  ** to call releasePage() on *ppChild exactly once. If an error occurs,
 76303  ** an error code is returned and *ppChild is set to 0.
 76304  */
 76305  static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
 76306    int rc;                        /* Return value from subprocedures */
 76307    MemPage *pChild = 0;           /* Pointer to a new child page */
 76308    Pgno pgnoChild = 0;            /* Page number of the new child page */
 76309    BtShared *pBt = pRoot->pBt;    /* The BTree */
 76310  
 76311    assert( pRoot->nOverflow>0 );
 76312    assert( sqlite3_mutex_held(pBt->mutex) );
 76313  
 76314    /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
 76315    ** page that will become the new right-child of pPage. Copy the contents
 76316    ** of the node stored on pRoot into the new child page.
 76317    */
 76318    rc = sqlite3PagerWrite(pRoot->pDbPage);
 76319    if( rc==SQLITE_OK ){
 76320      rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
 76321      copyNodeContent(pRoot, pChild, &rc);
 76322      if( ISAUTOVACUUM ){
 76323        ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
 76324      }
 76325    }
 76326    if( rc ){
 76327      *ppChild = 0;
 76328      releasePage(pChild);
 76329      return rc;
 76330    }
 76331    assert( sqlite3PagerIswriteable(pChild->pDbPage) );
 76332    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 76333    assert( pChild->nCell==pRoot->nCell );
 76334  
 76335    TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
 76336  
 76337    /* Copy the overflow cells from pRoot to pChild */
 76338    memcpy(pChild->aiOvfl, pRoot->aiOvfl,
 76339           pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
 76340    memcpy(pChild->apOvfl, pRoot->apOvfl,
 76341           pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
 76342    pChild->nOverflow = pRoot->nOverflow;
 76343  
 76344    /* Zero the contents of pRoot. Then install pChild as the right-child. */
 76345    zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
 76346    put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
 76347  
 76348    *ppChild = pChild;
 76349    return SQLITE_OK;
 76350  }
 76351  
 76352  /*
 76353  ** The page that pCur currently points to has just been modified in
 76354  ** some way. This function figures out if this modification means the
 76355  ** tree needs to be balanced, and if so calls the appropriate balancing 
 76356  ** routine. Balancing routines are:
 76357  **
 76358  **   balance_quick()
 76359  **   balance_deeper()
 76360  **   balance_nonroot()
 76361  */
 76362  static int balance(BtCursor *pCur){
 76363    int rc = SQLITE_OK;
 76364    const int nMin = pCur->pBt->usableSize * 2 / 3;
 76365    u8 aBalanceQuickSpace[13];
 76366    u8 *pFree = 0;
 76367  
 76368    VVA_ONLY( int balance_quick_called = 0 );
 76369    VVA_ONLY( int balance_deeper_called = 0 );
 76370  
 76371    do {
 76372      int iPage = pCur->iPage;
 76373      MemPage *pPage = pCur->pPage;
 76374  
 76375      if( iPage==0 ){
 76376        if( pPage->nOverflow ){
 76377          /* The root page of the b-tree is overfull. In this case call the
 76378          ** balance_deeper() function to create a new child for the root-page
 76379          ** and copy the current contents of the root-page to it. The
 76380          ** next iteration of the do-loop will balance the child page.
 76381          */ 
 76382          assert( balance_deeper_called==0 );
 76383          VVA_ONLY( balance_deeper_called++ );
 76384          rc = balance_deeper(pPage, &pCur->apPage[1]);
 76385          if( rc==SQLITE_OK ){
 76386            pCur->iPage = 1;
 76387            pCur->ix = 0;
 76388            pCur->aiIdx[0] = 0;
 76389            pCur->apPage[0] = pPage;
 76390            pCur->pPage = pCur->apPage[1];
 76391            assert( pCur->pPage->nOverflow );
 76392          }
 76393        }else{
 76394          break;
 76395        }
 76396      }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
 76397        break;
 76398      }else{
 76399        MemPage * const pParent = pCur->apPage[iPage-1];
 76400        int const iIdx = pCur->aiIdx[iPage-1];
 76401  
 76402        rc = sqlite3PagerWrite(pParent->pDbPage);
 76403        if( rc==SQLITE_OK ){
 76404  #ifndef SQLITE_OMIT_QUICKBALANCE
 76405          if( pPage->intKeyLeaf
 76406           && pPage->nOverflow==1
 76407           && pPage->aiOvfl[0]==pPage->nCell
 76408           && pParent->pgno!=1
 76409           && pParent->nCell==iIdx
 76410          ){
 76411            /* Call balance_quick() to create a new sibling of pPage on which
 76412            ** to store the overflow cell. balance_quick() inserts a new cell
 76413            ** into pParent, which may cause pParent overflow. If this
 76414            ** happens, the next iteration of the do-loop will balance pParent 
 76415            ** use either balance_nonroot() or balance_deeper(). Until this
 76416            ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
 76417            ** buffer. 
 76418            **
 76419            ** The purpose of the following assert() is to check that only a
 76420            ** single call to balance_quick() is made for each call to this
 76421            ** function. If this were not verified, a subtle bug involving reuse
 76422            ** of the aBalanceQuickSpace[] might sneak in.
 76423            */
 76424            assert( balance_quick_called==0 ); 
 76425            VVA_ONLY( balance_quick_called++ );
 76426            rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
 76427          }else
 76428  #endif
 76429          {
 76430            /* In this case, call balance_nonroot() to redistribute cells
 76431            ** between pPage and up to 2 of its sibling pages. This involves
 76432            ** modifying the contents of pParent, which may cause pParent to
 76433            ** become overfull or underfull. The next iteration of the do-loop
 76434            ** will balance the parent page to correct this.
 76435            ** 
 76436            ** If the parent page becomes overfull, the overflow cell or cells
 76437            ** are stored in the pSpace buffer allocated immediately below. 
 76438            ** A subsequent iteration of the do-loop will deal with this by
 76439            ** calling balance_nonroot() (balance_deeper() may be called first,
 76440            ** but it doesn't deal with overflow cells - just moves them to a
 76441            ** different page). Once this subsequent call to balance_nonroot() 
 76442            ** has completed, it is safe to release the pSpace buffer used by
 76443            ** the previous call, as the overflow cell data will have been 
 76444            ** copied either into the body of a database page or into the new
 76445            ** pSpace buffer passed to the latter call to balance_nonroot().
 76446            */
 76447            u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
 76448            rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
 76449                                 pCur->hints&BTREE_BULKLOAD);
 76450            if( pFree ){
 76451              /* If pFree is not NULL, it points to the pSpace buffer used 
 76452              ** by a previous call to balance_nonroot(). Its contents are
 76453              ** now stored either on real database pages or within the 
 76454              ** new pSpace buffer, so it may be safely freed here. */
 76455              sqlite3PageFree(pFree);
 76456            }
 76457  
 76458            /* The pSpace buffer will be freed after the next call to
 76459            ** balance_nonroot(), or just before this function returns, whichever
 76460            ** comes first. */
 76461            pFree = pSpace;
 76462          }
 76463        }
 76464  
 76465        pPage->nOverflow = 0;
 76466  
 76467        /* The next iteration of the do-loop balances the parent page. */
 76468        releasePage(pPage);
 76469        pCur->iPage--;
 76470        assert( pCur->iPage>=0 );
 76471        pCur->pPage = pCur->apPage[pCur->iPage];
 76472      }
 76473    }while( rc==SQLITE_OK );
 76474  
 76475    if( pFree ){
 76476      sqlite3PageFree(pFree);
 76477    }
 76478    return rc;
 76479  }
 76480  
 76481  /* Overwrite content from pX into pDest.  Only do the write if the
 76482  ** content is different from what is already there.
 76483  */
 76484  static int btreeOverwriteContent(
 76485    MemPage *pPage,           /* MemPage on which writing will occur */
 76486    u8 *pDest,                /* Pointer to the place to start writing */
 76487    const BtreePayload *pX,   /* Source of data to write */
 76488    int iOffset,              /* Offset of first byte to write */
 76489    int iAmt                  /* Number of bytes to be written */
 76490  ){
 76491    int nData = pX->nData - iOffset;
 76492    if( nData<=0 ){
 76493      /* Overwritting with zeros */
 76494      int i;
 76495      for(i=0; i<iAmt && pDest[i]==0; i++){}
 76496      if( i<iAmt ){
 76497        int rc = sqlite3PagerWrite(pPage->pDbPage);
 76498        if( rc ) return rc;
 76499        memset(pDest + i, 0, iAmt - i);
 76500      }
 76501    }else{
 76502      if( nData<iAmt ){
 76503        /* Mixed read data and zeros at the end.  Make a recursive call
 76504        ** to write the zeros then fall through to write the real data */
 76505        int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
 76506                                   iAmt-nData);
 76507        if( rc ) return rc;
 76508        iAmt = nData;
 76509      }
 76510      if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
 76511        int rc = sqlite3PagerWrite(pPage->pDbPage);
 76512        if( rc ) return rc;
 76513        /* In a corrupt database, it is possible for the source and destination
 76514        ** buffers to overlap.  This is harmless since the database is already
 76515        ** corrupt but it does cause valgrind and ASAN warnings.  So use
 76516        ** memmove(). */
 76517        memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
 76518      }
 76519    }
 76520    return SQLITE_OK;
 76521  }
 76522  
 76523  /*
 76524  ** Overwrite the cell that cursor pCur is pointing to with fresh content
 76525  ** contained in pX.
 76526  */
 76527  static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
 76528    int iOffset;                        /* Next byte of pX->pData to write */
 76529    int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
 76530    int rc;                             /* Return code */
 76531    MemPage *pPage = pCur->pPage;       /* Page being written */
 76532    BtShared *pBt;                      /* Btree */
 76533    Pgno ovflPgno;                      /* Next overflow page to write */
 76534    u32 ovflPageSize;                   /* Size to write on overflow page */
 76535  
 76536    if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
 76537      return SQLITE_CORRUPT_BKPT;
 76538    }
 76539    /* Overwrite the local portion first */
 76540    rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
 76541                               0, pCur->info.nLocal);
 76542    if( rc ) return rc;
 76543    if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
 76544  
 76545    /* Now overwrite the overflow pages */
 76546    iOffset = pCur->info.nLocal;
 76547    assert( nTotal>=0 );
 76548    assert( iOffset>=0 );
 76549    ovflPgno = get4byte(pCur->info.pPayload + iOffset);
 76550    pBt = pPage->pBt;
 76551    ovflPageSize = pBt->usableSize - 4;
 76552    do{
 76553      rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
 76554      if( rc ) return rc;
 76555      if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
 76556        rc = SQLITE_CORRUPT_BKPT;
 76557      }else{
 76558        if( iOffset+ovflPageSize<(u32)nTotal ){
 76559          ovflPgno = get4byte(pPage->aData);
 76560        }else{
 76561          ovflPageSize = nTotal - iOffset;
 76562        }
 76563        rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
 76564                                   iOffset, ovflPageSize);
 76565      }
 76566      sqlite3PagerUnref(pPage->pDbPage);
 76567      if( rc ) return rc;
 76568      iOffset += ovflPageSize;
 76569    }while( iOffset<nTotal );
 76570    return SQLITE_OK;    
 76571  }
 76572  
 76573  
 76574  /*
 76575  ** Insert a new record into the BTree.  The content of the new record
 76576  ** is described by the pX object.  The pCur cursor is used only to
 76577  ** define what table the record should be inserted into, and is left
 76578  ** pointing at a random location.
 76579  **
 76580  ** For a table btree (used for rowid tables), only the pX.nKey value of
 76581  ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
 76582  ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
 76583  ** hold the content of the row.
 76584  **
 76585  ** For an index btree (used for indexes and WITHOUT ROWID tables), the
 76586  ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The 
 76587  ** pX.pData,nData,nZero fields must be zero.
 76588  **
 76589  ** If the seekResult parameter is non-zero, then a successful call to
 76590  ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
 76591  ** been performed.  In other words, if seekResult!=0 then the cursor
 76592  ** is currently pointing to a cell that will be adjacent to the cell
 76593  ** to be inserted.  If seekResult<0 then pCur points to a cell that is
 76594  ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
 76595  ** that is larger than (pKey,nKey).
 76596  **
 76597  ** If seekResult==0, that means pCur is pointing at some unknown location.
 76598  ** In that case, this routine must seek the cursor to the correct insertion
 76599  ** point for (pKey,nKey) before doing the insertion.  For index btrees,
 76600  ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
 76601  ** key values and pX->aMem can be used instead of pX->pKey to avoid having
 76602  ** to decode the key.
 76603  */
 76604  SQLITE_PRIVATE int sqlite3BtreeInsert(
 76605    BtCursor *pCur,                /* Insert data into the table of this cursor */
 76606    const BtreePayload *pX,        /* Content of the row to be inserted */
 76607    int flags,                     /* True if this is likely an append */
 76608    int seekResult                 /* Result of prior MovetoUnpacked() call */
 76609  ){
 76610    int rc;
 76611    int loc = seekResult;          /* -1: before desired location  +1: after */
 76612    int szNew = 0;
 76613    int idx;
 76614    MemPage *pPage;
 76615    Btree *p = pCur->pBtree;
 76616    BtShared *pBt = p->pBt;
 76617    unsigned char *oldCell;
 76618    unsigned char *newCell = 0;
 76619  
 76620    assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
 76621  
 76622    if( pCur->eState==CURSOR_FAULT ){
 76623      assert( pCur->skipNext!=SQLITE_OK );
 76624      return pCur->skipNext;
 76625    }
 76626  
 76627    assert( cursorOwnsBtShared(pCur) );
 76628    assert( (pCur->curFlags & BTCF_WriteFlag)!=0
 76629                && pBt->inTransaction==TRANS_WRITE
 76630                && (pBt->btsFlags & BTS_READ_ONLY)==0 );
 76631    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 76632  
 76633    /* Assert that the caller has been consistent. If this cursor was opened
 76634    ** expecting an index b-tree, then the caller should be inserting blob
 76635    ** keys with no associated data. If the cursor was opened expecting an
 76636    ** intkey table, the caller should be inserting integer keys with a
 76637    ** blob of associated data.  */
 76638    assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
 76639  
 76640    /* Save the positions of any other cursors open on this table.
 76641    **
 76642    ** In some cases, the call to btreeMoveto() below is a no-op. For
 76643    ** example, when inserting data into a table with auto-generated integer
 76644    ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
 76645    ** integer key to use. It then calls this function to actually insert the 
 76646    ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
 76647    ** that the cursor is already where it needs to be and returns without
 76648    ** doing any work. To avoid thwarting these optimizations, it is important
 76649    ** not to clear the cursor here.
 76650    */
 76651    if( pCur->curFlags & BTCF_Multiple ){
 76652      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 76653      if( rc ) return rc;
 76654    }
 76655  
 76656    if( pCur->pKeyInfo==0 ){
 76657      assert( pX->pKey==0 );
 76658      /* If this is an insert into a table b-tree, invalidate any incrblob 
 76659      ** cursors open on the row being replaced */
 76660      invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
 76661  
 76662      /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
 76663      ** to a row with the same key as the new entry being inserted.
 76664      */
 76665  #ifdef SQLITE_DEBUG
 76666      if( flags & BTREE_SAVEPOSITION ){
 76667        assert( pCur->curFlags & BTCF_ValidNKey );
 76668        assert( pX->nKey==pCur->info.nKey );
 76669        assert( pCur->info.nSize!=0 );
 76670        assert( loc==0 );
 76671      }
 76672  #endif
 76673  
 76674      /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
 76675      ** that the cursor is not pointing to a row to be overwritten.
 76676      ** So do a complete check.
 76677      */
 76678      if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
 76679        /* The cursor is pointing to the entry that is to be
 76680        ** overwritten */
 76681        assert( pX->nData>=0 && pX->nZero>=0 );
 76682        if( pCur->info.nSize!=0
 76683         && pCur->info.nPayload==(u32)pX->nData+pX->nZero
 76684        ){
 76685          /* New entry is the same size as the old.  Do an overwrite */
 76686          return btreeOverwriteCell(pCur, pX);
 76687        }
 76688        assert( loc==0 );
 76689      }else if( loc==0 ){
 76690        /* The cursor is *not* pointing to the cell to be overwritten, nor
 76691        ** to an adjacent cell.  Move the cursor so that it is pointing either
 76692        ** to the cell to be overwritten or an adjacent cell.
 76693        */
 76694        rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
 76695        if( rc ) return rc;
 76696      }
 76697    }else{
 76698      /* This is an index or a WITHOUT ROWID table */
 76699  
 76700      /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
 76701      ** to a row with the same key as the new entry being inserted.
 76702      */
 76703      assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
 76704  
 76705      /* If the cursor is not already pointing either to the cell to be
 76706      ** overwritten, or if a new cell is being inserted, if the cursor is
 76707      ** not pointing to an immediately adjacent cell, then move the cursor
 76708      ** so that it does.
 76709      */
 76710      if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
 76711        if( pX->nMem ){
 76712          UnpackedRecord r;
 76713          r.pKeyInfo = pCur->pKeyInfo;
 76714          r.aMem = pX->aMem;
 76715          r.nField = pX->nMem;
 76716          r.default_rc = 0;
 76717          r.errCode = 0;
 76718          r.r1 = 0;
 76719          r.r2 = 0;
 76720          r.eqSeen = 0;
 76721          rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
 76722        }else{
 76723          rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
 76724        }
 76725        if( rc ) return rc;
 76726      }
 76727  
 76728      /* If the cursor is currently pointing to an entry to be overwritten
 76729      ** and the new content is the same as as the old, then use the
 76730      ** overwrite optimization.
 76731      */
 76732      if( loc==0 ){
 76733        getCellInfo(pCur);
 76734        if( pCur->info.nKey==pX->nKey ){
 76735          BtreePayload x2;
 76736          x2.pData = pX->pKey;
 76737          x2.nData = pX->nKey;
 76738          x2.nZero = 0;
 76739          return btreeOverwriteCell(pCur, &x2);
 76740        }
 76741      }
 76742  
 76743    }
 76744    assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
 76745  
 76746    pPage = pCur->pPage;
 76747    assert( pPage->intKey || pX->nKey>=0 );
 76748    assert( pPage->leaf || !pPage->intKey );
 76749  
 76750    TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
 76751            pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
 76752            loc==0 ? "overwrite" : "new entry"));
 76753    assert( pPage->isInit );
 76754    newCell = pBt->pTmpSpace;
 76755    assert( newCell!=0 );
 76756    rc = fillInCell(pPage, newCell, pX, &szNew);
 76757    if( rc ) goto end_insert;
 76758    assert( szNew==pPage->xCellSize(pPage, newCell) );
 76759    assert( szNew <= MX_CELL_SIZE(pBt) );
 76760    idx = pCur->ix;
 76761    if( loc==0 ){
 76762      CellInfo info;
 76763      assert( idx<pPage->nCell );
 76764      rc = sqlite3PagerWrite(pPage->pDbPage);
 76765      if( rc ){
 76766        goto end_insert;
 76767      }
 76768      oldCell = findCell(pPage, idx);
 76769      if( !pPage->leaf ){
 76770        memcpy(newCell, oldCell, 4);
 76771      }
 76772      rc = clearCell(pPage, oldCell, &info);
 76773      if( info.nSize==szNew && info.nLocal==info.nPayload 
 76774       && (!ISAUTOVACUUM || szNew<pPage->minLocal)
 76775      ){
 76776        /* Overwrite the old cell with the new if they are the same size.
 76777        ** We could also try to do this if the old cell is smaller, then add
 76778        ** the leftover space to the free list.  But experiments show that
 76779        ** doing that is no faster then skipping this optimization and just
 76780        ** calling dropCell() and insertCell(). 
 76781        **
 76782        ** This optimization cannot be used on an autovacuum database if the
 76783        ** new entry uses overflow pages, as the insertCell() call below is
 76784        ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
 76785        assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
 76786        if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
 76787        memcpy(oldCell, newCell, szNew);
 76788        return SQLITE_OK;
 76789      }
 76790      dropCell(pPage, idx, info.nSize, &rc);
 76791      if( rc ) goto end_insert;
 76792    }else if( loc<0 && pPage->nCell>0 ){
 76793      assert( pPage->leaf );
 76794      idx = ++pCur->ix;
 76795      pCur->curFlags &= ~BTCF_ValidNKey;
 76796    }else{
 76797      assert( pPage->leaf );
 76798    }
 76799    insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
 76800    assert( pPage->nOverflow==0 || rc==SQLITE_OK );
 76801    assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
 76802  
 76803    /* If no error has occurred and pPage has an overflow cell, call balance() 
 76804    ** to redistribute the cells within the tree. Since balance() may move
 76805    ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
 76806    ** variables.
 76807    **
 76808    ** Previous versions of SQLite called moveToRoot() to move the cursor
 76809    ** back to the root page as balance() used to invalidate the contents
 76810    ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
 76811    ** set the cursor state to "invalid". This makes common insert operations
 76812    ** slightly faster.
 76813    **
 76814    ** There is a subtle but important optimization here too. When inserting
 76815    ** multiple records into an intkey b-tree using a single cursor (as can
 76816    ** happen while processing an "INSERT INTO ... SELECT" statement), it
 76817    ** is advantageous to leave the cursor pointing to the last entry in
 76818    ** the b-tree if possible. If the cursor is left pointing to the last
 76819    ** entry in the table, and the next row inserted has an integer key
 76820    ** larger than the largest existing key, it is possible to insert the
 76821    ** row without seeking the cursor. This can be a big performance boost.
 76822    */
 76823    pCur->info.nSize = 0;
 76824    if( pPage->nOverflow ){
 76825      assert( rc==SQLITE_OK );
 76826      pCur->curFlags &= ~(BTCF_ValidNKey);
 76827      rc = balance(pCur);
 76828  
 76829      /* Must make sure nOverflow is reset to zero even if the balance()
 76830      ** fails. Internal data structure corruption will result otherwise. 
 76831      ** Also, set the cursor state to invalid. This stops saveCursorPosition()
 76832      ** from trying to save the current position of the cursor.  */
 76833      pCur->pPage->nOverflow = 0;
 76834      pCur->eState = CURSOR_INVALID;
 76835      if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
 76836        btreeReleaseAllCursorPages(pCur);
 76837        if( pCur->pKeyInfo ){
 76838          assert( pCur->pKey==0 );
 76839          pCur->pKey = sqlite3Malloc( pX->nKey );
 76840          if( pCur->pKey==0 ){
 76841            rc = SQLITE_NOMEM;
 76842          }else{
 76843            memcpy(pCur->pKey, pX->pKey, pX->nKey);
 76844          }
 76845        }
 76846        pCur->eState = CURSOR_REQUIRESEEK;
 76847        pCur->nKey = pX->nKey;
 76848      }
 76849    }
 76850    assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
 76851  
 76852  end_insert:
 76853    return rc;
 76854  }
 76855  
 76856  /*
 76857  ** Delete the entry that the cursor is pointing to. 
 76858  **
 76859  ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
 76860  ** the cursor is left pointing at an arbitrary location after the delete.
 76861  ** But if that bit is set, then the cursor is left in a state such that
 76862  ** the next call to BtreeNext() or BtreePrev() moves it to the same row
 76863  ** as it would have been on if the call to BtreeDelete() had been omitted.
 76864  **
 76865  ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
 76866  ** associated with a single table entry and its indexes.  Only one of those
 76867  ** deletes is considered the "primary" delete.  The primary delete occurs
 76868  ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
 76869  ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
 76870  ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
 76871  ** but which might be used by alternative storage engines.
 76872  */
 76873  SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
 76874    Btree *p = pCur->pBtree;
 76875    BtShared *pBt = p->pBt;              
 76876    int rc;                              /* Return code */
 76877    MemPage *pPage;                      /* Page to delete cell from */
 76878    unsigned char *pCell;                /* Pointer to cell to delete */
 76879    int iCellIdx;                        /* Index of cell to delete */
 76880    int iCellDepth;                      /* Depth of node containing pCell */ 
 76881    CellInfo info;                       /* Size of the cell being deleted */
 76882    int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
 76883    u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
 76884  
 76885    assert( cursorOwnsBtShared(pCur) );
 76886    assert( pBt->inTransaction==TRANS_WRITE );
 76887    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 76888    assert( pCur->curFlags & BTCF_WriteFlag );
 76889    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
 76890    assert( !hasReadConflicts(p, pCur->pgnoRoot) );
 76891    assert( pCur->ix<pCur->pPage->nCell );
 76892    assert( pCur->eState==CURSOR_VALID );
 76893    assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
 76894  
 76895    iCellDepth = pCur->iPage;
 76896    iCellIdx = pCur->ix;
 76897    pPage = pCur->pPage;
 76898    pCell = findCell(pPage, iCellIdx);
 76899  
 76900    /* If the bPreserve flag is set to true, then the cursor position must
 76901    ** be preserved following this delete operation. If the current delete
 76902    ** will cause a b-tree rebalance, then this is done by saving the cursor
 76903    ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 
 76904    ** returning. 
 76905    **
 76906    ** Or, if the current delete will not cause a rebalance, then the cursor
 76907    ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
 76908    ** before or after the deleted entry. In this case set bSkipnext to true.  */
 76909    if( bPreserve ){
 76910      if( !pPage->leaf 
 76911       || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
 76912       || pPage->nCell==1  /* See dbfuzz001.test for a test case */
 76913      ){
 76914        /* A b-tree rebalance will be required after deleting this entry.
 76915        ** Save the cursor key.  */
 76916        rc = saveCursorKey(pCur);
 76917        if( rc ) return rc;
 76918      }else{
 76919        bSkipnext = 1;
 76920      }
 76921    }
 76922  
 76923    /* If the page containing the entry to delete is not a leaf page, move
 76924    ** the cursor to the largest entry in the tree that is smaller than
 76925    ** the entry being deleted. This cell will replace the cell being deleted
 76926    ** from the internal node. The 'previous' entry is used for this instead
 76927    ** of the 'next' entry, as the previous entry is always a part of the
 76928    ** sub-tree headed by the child page of the cell being deleted. This makes
 76929    ** balancing the tree following the delete operation easier.  */
 76930    if( !pPage->leaf ){
 76931      rc = sqlite3BtreePrevious(pCur, 0);
 76932      assert( rc!=SQLITE_DONE );
 76933      if( rc ) return rc;
 76934    }
 76935  
 76936    /* Save the positions of any other cursors open on this table before
 76937    ** making any modifications.  */
 76938    if( pCur->curFlags & BTCF_Multiple ){
 76939      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
 76940      if( rc ) return rc;
 76941    }
 76942  
 76943    /* If this is a delete operation to remove a row from a table b-tree,
 76944    ** invalidate any incrblob cursors open on the row being deleted.  */
 76945    if( pCur->pKeyInfo==0 ){
 76946      invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
 76947    }
 76948  
 76949    /* Make the page containing the entry to be deleted writable. Then free any
 76950    ** overflow pages associated with the entry and finally remove the cell
 76951    ** itself from within the page.  */
 76952    rc = sqlite3PagerWrite(pPage->pDbPage);
 76953    if( rc ) return rc;
 76954    rc = clearCell(pPage, pCell, &info);
 76955    dropCell(pPage, iCellIdx, info.nSize, &rc);
 76956    if( rc ) return rc;
 76957  
 76958    /* If the cell deleted was not located on a leaf page, then the cursor
 76959    ** is currently pointing to the largest entry in the sub-tree headed
 76960    ** by the child-page of the cell that was just deleted from an internal
 76961    ** node. The cell from the leaf node needs to be moved to the internal
 76962    ** node to replace the deleted cell.  */
 76963    if( !pPage->leaf ){
 76964      MemPage *pLeaf = pCur->pPage;
 76965      int nCell;
 76966      Pgno n;
 76967      unsigned char *pTmp;
 76968  
 76969      if( iCellDepth<pCur->iPage-1 ){
 76970        n = pCur->apPage[iCellDepth+1]->pgno;
 76971      }else{
 76972        n = pCur->pPage->pgno;
 76973      }
 76974      pCell = findCell(pLeaf, pLeaf->nCell-1);
 76975      if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
 76976      nCell = pLeaf->xCellSize(pLeaf, pCell);
 76977      assert( MX_CELL_SIZE(pBt) >= nCell );
 76978      pTmp = pBt->pTmpSpace;
 76979      assert( pTmp!=0 );
 76980      rc = sqlite3PagerWrite(pLeaf->pDbPage);
 76981      if( rc==SQLITE_OK ){
 76982        insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
 76983      }
 76984      dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
 76985      if( rc ) return rc;
 76986    }
 76987  
 76988    /* Balance the tree. If the entry deleted was located on a leaf page,
 76989    ** then the cursor still points to that page. In this case the first
 76990    ** call to balance() repairs the tree, and the if(...) condition is
 76991    ** never true.
 76992    **
 76993    ** Otherwise, if the entry deleted was on an internal node page, then
 76994    ** pCur is pointing to the leaf page from which a cell was removed to
 76995    ** replace the cell deleted from the internal node. This is slightly
 76996    ** tricky as the leaf node may be underfull, and the internal node may
 76997    ** be either under or overfull. In this case run the balancing algorithm
 76998    ** on the leaf node first. If the balance proceeds far enough up the
 76999    ** tree that we can be sure that any problem in the internal node has
 77000    ** been corrected, so be it. Otherwise, after balancing the leaf node,
 77001    ** walk the cursor up the tree to the internal node and balance it as 
 77002    ** well.  */
 77003    rc = balance(pCur);
 77004    if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
 77005      releasePageNotNull(pCur->pPage);
 77006      pCur->iPage--;
 77007      while( pCur->iPage>iCellDepth ){
 77008        releasePage(pCur->apPage[pCur->iPage--]);
 77009      }
 77010      pCur->pPage = pCur->apPage[pCur->iPage];
 77011      rc = balance(pCur);
 77012    }
 77013  
 77014    if( rc==SQLITE_OK ){
 77015      if( bSkipnext ){
 77016        assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
 77017        assert( pPage==pCur->pPage || CORRUPT_DB );
 77018        assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
 77019        pCur->eState = CURSOR_SKIPNEXT;
 77020        if( iCellIdx>=pPage->nCell ){
 77021          pCur->skipNext = -1;
 77022          pCur->ix = pPage->nCell-1;
 77023        }else{
 77024          pCur->skipNext = 1;
 77025        }
 77026      }else{
 77027        rc = moveToRoot(pCur);
 77028        if( bPreserve ){
 77029          btreeReleaseAllCursorPages(pCur);
 77030          pCur->eState = CURSOR_REQUIRESEEK;
 77031        }
 77032        if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
 77033      }
 77034    }
 77035    return rc;
 77036  }
 77037  
 77038  /*
 77039  ** Create a new BTree table.  Write into *piTable the page
 77040  ** number for the root page of the new table.
 77041  **
 77042  ** The type of type is determined by the flags parameter.  Only the
 77043  ** following values of flags are currently in use.  Other values for
 77044  ** flags might not work:
 77045  **
 77046  **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
 77047  **     BTREE_ZERODATA                  Used for SQL indices
 77048  */
 77049  static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
 77050    BtShared *pBt = p->pBt;
 77051    MemPage *pRoot;
 77052    Pgno pgnoRoot;
 77053    int rc;
 77054    int ptfFlags;          /* Page-type flage for the root page of new table */
 77055  
 77056    assert( sqlite3BtreeHoldsMutex(p) );
 77057    assert( pBt->inTransaction==TRANS_WRITE );
 77058    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
 77059  
 77060  #ifdef SQLITE_OMIT_AUTOVACUUM
 77061    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 77062    if( rc ){
 77063      return rc;
 77064    }
 77065  #else
 77066    if( pBt->autoVacuum ){
 77067      Pgno pgnoMove;      /* Move a page here to make room for the root-page */
 77068      MemPage *pPageMove; /* The page to move to. */
 77069  
 77070      /* Creating a new table may probably require moving an existing database
 77071      ** to make room for the new tables root page. In case this page turns
 77072      ** out to be an overflow page, delete all overflow page-map caches
 77073      ** held by open cursors.
 77074      */
 77075      invalidateAllOverflowCache(pBt);
 77076  
 77077      /* Read the value of meta[3] from the database to determine where the
 77078      ** root page of the new table should go. meta[3] is the largest root-page
 77079      ** created so far, so the new root-page is (meta[3]+1).
 77080      */
 77081      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
 77082      pgnoRoot++;
 77083  
 77084      /* The new root-page may not be allocated on a pointer-map page, or the
 77085      ** PENDING_BYTE page.
 77086      */
 77087      while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
 77088          pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
 77089        pgnoRoot++;
 77090      }
 77091      assert( pgnoRoot>=3 || CORRUPT_DB );
 77092      testcase( pgnoRoot<3 );
 77093  
 77094      /* Allocate a page. The page that currently resides at pgnoRoot will
 77095      ** be moved to the allocated page (unless the allocated page happens
 77096      ** to reside at pgnoRoot).
 77097      */
 77098      rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
 77099      if( rc!=SQLITE_OK ){
 77100        return rc;
 77101      }
 77102  
 77103      if( pgnoMove!=pgnoRoot ){
 77104        /* pgnoRoot is the page that will be used for the root-page of
 77105        ** the new table (assuming an error did not occur). But we were
 77106        ** allocated pgnoMove. If required (i.e. if it was not allocated
 77107        ** by extending the file), the current page at position pgnoMove
 77108        ** is already journaled.
 77109        */
 77110        u8 eType = 0;
 77111        Pgno iPtrPage = 0;
 77112  
 77113        /* Save the positions of any open cursors. This is required in
 77114        ** case they are holding a reference to an xFetch reference
 77115        ** corresponding to page pgnoRoot.  */
 77116        rc = saveAllCursors(pBt, 0, 0);
 77117        releasePage(pPageMove);
 77118        if( rc!=SQLITE_OK ){
 77119          return rc;
 77120        }
 77121  
 77122        /* Move the page currently at pgnoRoot to pgnoMove. */
 77123        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 77124        if( rc!=SQLITE_OK ){
 77125          return rc;
 77126        }
 77127        rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
 77128        if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
 77129          rc = SQLITE_CORRUPT_BKPT;
 77130        }
 77131        if( rc!=SQLITE_OK ){
 77132          releasePage(pRoot);
 77133          return rc;
 77134        }
 77135        assert( eType!=PTRMAP_ROOTPAGE );
 77136        assert( eType!=PTRMAP_FREEPAGE );
 77137        rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
 77138        releasePage(pRoot);
 77139  
 77140        /* Obtain the page at pgnoRoot */
 77141        if( rc!=SQLITE_OK ){
 77142          return rc;
 77143        }
 77144        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
 77145        if( rc!=SQLITE_OK ){
 77146          return rc;
 77147        }
 77148        rc = sqlite3PagerWrite(pRoot->pDbPage);
 77149        if( rc!=SQLITE_OK ){
 77150          releasePage(pRoot);
 77151          return rc;
 77152        }
 77153      }else{
 77154        pRoot = pPageMove;
 77155      } 
 77156  
 77157      /* Update the pointer-map and meta-data with the new root-page number. */
 77158      ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
 77159      if( rc ){
 77160        releasePage(pRoot);
 77161        return rc;
 77162      }
 77163  
 77164      /* When the new root page was allocated, page 1 was made writable in
 77165      ** order either to increase the database filesize, or to decrement the
 77166      ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
 77167      */
 77168      assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
 77169      rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
 77170      if( NEVER(rc) ){
 77171        releasePage(pRoot);
 77172        return rc;
 77173      }
 77174  
 77175    }else{
 77176      rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
 77177      if( rc ) return rc;
 77178    }
 77179  #endif
 77180    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
 77181    if( createTabFlags & BTREE_INTKEY ){
 77182      ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
 77183    }else{
 77184      ptfFlags = PTF_ZERODATA | PTF_LEAF;
 77185    }
 77186    zeroPage(pRoot, ptfFlags);
 77187    sqlite3PagerUnref(pRoot->pDbPage);
 77188    assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
 77189    *piTable = (int)pgnoRoot;
 77190    return SQLITE_OK;
 77191  }
 77192  SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
 77193    int rc;
 77194    sqlite3BtreeEnter(p);
 77195    rc = btreeCreateTable(p, piTable, flags);
 77196    sqlite3BtreeLeave(p);
 77197    return rc;
 77198  }
 77199  
 77200  /*
 77201  ** Erase the given database page and all its children.  Return
 77202  ** the page to the freelist.
 77203  */
 77204  static int clearDatabasePage(
 77205    BtShared *pBt,           /* The BTree that contains the table */
 77206    Pgno pgno,               /* Page number to clear */
 77207    int freePageFlag,        /* Deallocate page if true */
 77208    int *pnChange            /* Add number of Cells freed to this counter */
 77209  ){
 77210    MemPage *pPage;
 77211    int rc;
 77212    unsigned char *pCell;
 77213    int i;
 77214    int hdr;
 77215    CellInfo info;
 77216  
 77217    assert( sqlite3_mutex_held(pBt->mutex) );
 77218    if( pgno>btreePagecount(pBt) ){
 77219      return SQLITE_CORRUPT_BKPT;
 77220    }
 77221    rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
 77222    if( rc ) return rc;
 77223    if( pPage->bBusy ){
 77224      rc = SQLITE_CORRUPT_BKPT;
 77225      goto cleardatabasepage_out;
 77226    }
 77227    pPage->bBusy = 1;
 77228    hdr = pPage->hdrOffset;
 77229    for(i=0; i<pPage->nCell; i++){
 77230      pCell = findCell(pPage, i);
 77231      if( !pPage->leaf ){
 77232        rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
 77233        if( rc ) goto cleardatabasepage_out;
 77234      }
 77235      rc = clearCell(pPage, pCell, &info);
 77236      if( rc ) goto cleardatabasepage_out;
 77237    }
 77238    if( !pPage->leaf ){
 77239      rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
 77240      if( rc ) goto cleardatabasepage_out;
 77241    }else if( pnChange ){
 77242      assert( pPage->intKey || CORRUPT_DB );
 77243      testcase( !pPage->intKey );
 77244      *pnChange += pPage->nCell;
 77245    }
 77246    if( freePageFlag ){
 77247      freePage(pPage, &rc);
 77248    }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
 77249      zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
 77250    }
 77251  
 77252  cleardatabasepage_out:
 77253    pPage->bBusy = 0;
 77254    releasePage(pPage);
 77255    return rc;
 77256  }
 77257  
 77258  /*
 77259  ** Delete all information from a single table in the database.  iTable is
 77260  ** the page number of the root of the table.  After this routine returns,
 77261  ** the root page is empty, but still exists.
 77262  **
 77263  ** This routine will fail with SQLITE_LOCKED if there are any open
 77264  ** read cursors on the table.  Open write cursors are moved to the
 77265  ** root of the table.
 77266  **
 77267  ** If pnChange is not NULL, then table iTable must be an intkey table. The
 77268  ** integer value pointed to by pnChange is incremented by the number of
 77269  ** entries in the table.
 77270  */
 77271  SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
 77272    int rc;
 77273    BtShared *pBt = p->pBt;
 77274    sqlite3BtreeEnter(p);
 77275    assert( p->inTrans==TRANS_WRITE );
 77276  
 77277    rc = saveAllCursors(pBt, (Pgno)iTable, 0);
 77278  
 77279    if( SQLITE_OK==rc ){
 77280      /* Invalidate all incrblob cursors open on table iTable (assuming iTable
 77281      ** is the root of a table b-tree - if it is not, the following call is
 77282      ** a no-op).  */
 77283      invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
 77284      rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
 77285    }
 77286    sqlite3BtreeLeave(p);
 77287    return rc;
 77288  }
 77289  
 77290  /*
 77291  ** Delete all information from the single table that pCur is open on.
 77292  **
 77293  ** This routine only work for pCur on an ephemeral table.
 77294  */
 77295  SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
 77296    return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
 77297  }
 77298  
 77299  /*
 77300  ** Erase all information in a table and add the root of the table to
 77301  ** the freelist.  Except, the root of the principle table (the one on
 77302  ** page 1) is never added to the freelist.
 77303  **
 77304  ** This routine will fail with SQLITE_LOCKED if there are any open
 77305  ** cursors on the table.
 77306  **
 77307  ** If AUTOVACUUM is enabled and the page at iTable is not the last
 77308  ** root page in the database file, then the last root page 
 77309  ** in the database file is moved into the slot formerly occupied by
 77310  ** iTable and that last slot formerly occupied by the last root page
 77311  ** is added to the freelist instead of iTable.  In this say, all
 77312  ** root pages are kept at the beginning of the database file, which
 77313  ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
 77314  ** page number that used to be the last root page in the file before
 77315  ** the move.  If no page gets moved, *piMoved is set to 0.
 77316  ** The last root page is recorded in meta[3] and the value of
 77317  ** meta[3] is updated by this procedure.
 77318  */
 77319  static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
 77320    int rc;
 77321    MemPage *pPage = 0;
 77322    BtShared *pBt = p->pBt;
 77323  
 77324    assert( sqlite3BtreeHoldsMutex(p) );
 77325    assert( p->inTrans==TRANS_WRITE );
 77326    assert( iTable>=2 );
 77327  
 77328    rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
 77329    if( rc ) return rc;
 77330    rc = sqlite3BtreeClearTable(p, iTable, 0);
 77331    if( rc ){
 77332      releasePage(pPage);
 77333      return rc;
 77334    }
 77335  
 77336    *piMoved = 0;
 77337  
 77338  #ifdef SQLITE_OMIT_AUTOVACUUM
 77339    freePage(pPage, &rc);
 77340    releasePage(pPage);
 77341  #else
 77342    if( pBt->autoVacuum ){
 77343      Pgno maxRootPgno;
 77344      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
 77345  
 77346      if( iTable==maxRootPgno ){
 77347        /* If the table being dropped is the table with the largest root-page
 77348        ** number in the database, put the root page on the free list. 
 77349        */
 77350        freePage(pPage, &rc);
 77351        releasePage(pPage);
 77352        if( rc!=SQLITE_OK ){
 77353          return rc;
 77354        }
 77355      }else{
 77356        /* The table being dropped does not have the largest root-page
 77357        ** number in the database. So move the page that does into the 
 77358        ** gap left by the deleted root-page.
 77359        */
 77360        MemPage *pMove;
 77361        releasePage(pPage);
 77362        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 77363        if( rc!=SQLITE_OK ){
 77364          return rc;
 77365        }
 77366        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
 77367        releasePage(pMove);
 77368        if( rc!=SQLITE_OK ){
 77369          return rc;
 77370        }
 77371        pMove = 0;
 77372        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
 77373        freePage(pMove, &rc);
 77374        releasePage(pMove);
 77375        if( rc!=SQLITE_OK ){
 77376          return rc;
 77377        }
 77378        *piMoved = maxRootPgno;
 77379      }
 77380  
 77381      /* Set the new 'max-root-page' value in the database header. This
 77382      ** is the old value less one, less one more if that happens to
 77383      ** be a root-page number, less one again if that is the
 77384      ** PENDING_BYTE_PAGE.
 77385      */
 77386      maxRootPgno--;
 77387      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
 77388             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
 77389        maxRootPgno--;
 77390      }
 77391      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
 77392  
 77393      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
 77394    }else{
 77395      freePage(pPage, &rc);
 77396      releasePage(pPage);
 77397    }
 77398  #endif
 77399    return rc;  
 77400  }
 77401  SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
 77402    int rc;
 77403    sqlite3BtreeEnter(p);
 77404    rc = btreeDropTable(p, iTable, piMoved);
 77405    sqlite3BtreeLeave(p);
 77406    return rc;
 77407  }
 77408  
 77409  
 77410  /*
 77411  ** This function may only be called if the b-tree connection already
 77412  ** has a read or write transaction open on the database.
 77413  **
 77414  ** Read the meta-information out of a database file.  Meta[0]
 77415  ** is the number of free pages currently in the database.  Meta[1]
 77416  ** through meta[15] are available for use by higher layers.  Meta[0]
 77417  ** is read-only, the others are read/write.
 77418  ** 
 77419  ** The schema layer numbers meta values differently.  At the schema
 77420  ** layer (and the SetCookie and ReadCookie opcodes) the number of
 77421  ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
 77422  **
 77423  ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
 77424  ** of reading the value out of the header, it instead loads the "DataVersion"
 77425  ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
 77426  ** database file.  It is a number computed by the pager.  But its access
 77427  ** pattern is the same as header meta values, and so it is convenient to
 77428  ** read it from this routine.
 77429  */
 77430  SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
 77431    BtShared *pBt = p->pBt;
 77432  
 77433    sqlite3BtreeEnter(p);
 77434    assert( p->inTrans>TRANS_NONE );
 77435    assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
 77436    assert( pBt->pPage1 );
 77437    assert( idx>=0 && idx<=15 );
 77438  
 77439    if( idx==BTREE_DATA_VERSION ){
 77440      *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
 77441    }else{
 77442      *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
 77443    }
 77444  
 77445    /* If auto-vacuum is disabled in this build and this is an auto-vacuum
 77446    ** database, mark the database as read-only.  */
 77447  #ifdef SQLITE_OMIT_AUTOVACUUM
 77448    if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
 77449      pBt->btsFlags |= BTS_READ_ONLY;
 77450    }
 77451  #endif
 77452  
 77453    sqlite3BtreeLeave(p);
 77454  }
 77455  
 77456  /*
 77457  ** Write meta-information back into the database.  Meta[0] is
 77458  ** read-only and may not be written.
 77459  */
 77460  SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
 77461    BtShared *pBt = p->pBt;
 77462    unsigned char *pP1;
 77463    int rc;
 77464    assert( idx>=1 && idx<=15 );
 77465    sqlite3BtreeEnter(p);
 77466    assert( p->inTrans==TRANS_WRITE );
 77467    assert( pBt->pPage1!=0 );
 77468    pP1 = pBt->pPage1->aData;
 77469    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 77470    if( rc==SQLITE_OK ){
 77471      put4byte(&pP1[36 + idx*4], iMeta);
 77472  #ifndef SQLITE_OMIT_AUTOVACUUM
 77473      if( idx==BTREE_INCR_VACUUM ){
 77474        assert( pBt->autoVacuum || iMeta==0 );
 77475        assert( iMeta==0 || iMeta==1 );
 77476        pBt->incrVacuum = (u8)iMeta;
 77477      }
 77478  #endif
 77479    }
 77480    sqlite3BtreeLeave(p);
 77481    return rc;
 77482  }
 77483  
 77484  #ifndef SQLITE_OMIT_BTREECOUNT
 77485  /*
 77486  ** The first argument, pCur, is a cursor opened on some b-tree. Count the
 77487  ** number of entries in the b-tree and write the result to *pnEntry.
 77488  **
 77489  ** SQLITE_OK is returned if the operation is successfully executed. 
 77490  ** Otherwise, if an error is encountered (i.e. an IO error or database
 77491  ** corruption) an SQLite error code is returned.
 77492  */
 77493  SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
 77494    i64 nEntry = 0;                      /* Value to return in *pnEntry */
 77495    int rc;                              /* Return code */
 77496  
 77497    rc = moveToRoot(pCur);
 77498    if( rc==SQLITE_EMPTY ){
 77499      *pnEntry = 0;
 77500      return SQLITE_OK;
 77501    }
 77502  
 77503    /* Unless an error occurs, the following loop runs one iteration for each
 77504    ** page in the B-Tree structure (not including overflow pages). 
 77505    */
 77506    while( rc==SQLITE_OK ){
 77507      int iIdx;                          /* Index of child node in parent */
 77508      MemPage *pPage;                    /* Current page of the b-tree */
 77509  
 77510      /* If this is a leaf page or the tree is not an int-key tree, then 
 77511      ** this page contains countable entries. Increment the entry counter
 77512      ** accordingly.
 77513      */
 77514      pPage = pCur->pPage;
 77515      if( pPage->leaf || !pPage->intKey ){
 77516        nEntry += pPage->nCell;
 77517      }
 77518  
 77519      /* pPage is a leaf node. This loop navigates the cursor so that it 
 77520      ** points to the first interior cell that it points to the parent of
 77521      ** the next page in the tree that has not yet been visited. The
 77522      ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
 77523      ** of the page, or to the number of cells in the page if the next page
 77524      ** to visit is the right-child of its parent.
 77525      **
 77526      ** If all pages in the tree have been visited, return SQLITE_OK to the
 77527      ** caller.
 77528      */
 77529      if( pPage->leaf ){
 77530        do {
 77531          if( pCur->iPage==0 ){
 77532            /* All pages of the b-tree have been visited. Return successfully. */
 77533            *pnEntry = nEntry;
 77534            return moveToRoot(pCur);
 77535          }
 77536          moveToParent(pCur);
 77537        }while ( pCur->ix>=pCur->pPage->nCell );
 77538  
 77539        pCur->ix++;
 77540        pPage = pCur->pPage;
 77541      }
 77542  
 77543      /* Descend to the child node of the cell that the cursor currently 
 77544      ** points at. This is the right-child if (iIdx==pPage->nCell).
 77545      */
 77546      iIdx = pCur->ix;
 77547      if( iIdx==pPage->nCell ){
 77548        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
 77549      }else{
 77550        rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
 77551      }
 77552    }
 77553  
 77554    /* An error has occurred. Return an error code. */
 77555    return rc;
 77556  }
 77557  #endif
 77558  
 77559  /*
 77560  ** Return the pager associated with a BTree.  This routine is used for
 77561  ** testing and debugging only.
 77562  */
 77563  SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
 77564    return p->pBt->pPager;
 77565  }
 77566  
 77567  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 77568  /*
 77569  ** Append a message to the error message string.
 77570  */
 77571  static void checkAppendMsg(
 77572    IntegrityCk *pCheck,
 77573    const char *zFormat,
 77574    ...
 77575  ){
 77576    va_list ap;
 77577    if( !pCheck->mxErr ) return;
 77578    pCheck->mxErr--;
 77579    pCheck->nErr++;
 77580    va_start(ap, zFormat);
 77581    if( pCheck->errMsg.nChar ){
 77582      sqlite3_str_append(&pCheck->errMsg, "\n", 1);
 77583    }
 77584    if( pCheck->zPfx ){
 77585      sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
 77586    }
 77587    sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
 77588    va_end(ap);
 77589    if( pCheck->errMsg.accError==SQLITE_NOMEM ){
 77590      pCheck->mallocFailed = 1;
 77591    }
 77592  }
 77593  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 77594  
 77595  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 77596  
 77597  /*
 77598  ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
 77599  ** corresponds to page iPg is already set.
 77600  */
 77601  static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 77602    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 77603    return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
 77604  }
 77605  
 77606  /*
 77607  ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
 77608  */
 77609  static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
 77610    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
 77611    pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
 77612  }
 77613  
 77614  
 77615  /*
 77616  ** Add 1 to the reference count for page iPage.  If this is the second
 77617  ** reference to the page, add an error message to pCheck->zErrMsg.
 77618  ** Return 1 if there are 2 or more references to the page and 0 if
 77619  ** if this is the first reference to the page.
 77620  **
 77621  ** Also check that the page number is in bounds.
 77622  */
 77623  static int checkRef(IntegrityCk *pCheck, Pgno iPage){
 77624    if( iPage>pCheck->nPage || iPage==0 ){
 77625      checkAppendMsg(pCheck, "invalid page number %d", iPage);
 77626      return 1;
 77627    }
 77628    if( getPageReferenced(pCheck, iPage) ){
 77629      checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
 77630      return 1;
 77631    }
 77632    setPageReferenced(pCheck, iPage);
 77633    return 0;
 77634  }
 77635  
 77636  #ifndef SQLITE_OMIT_AUTOVACUUM
 77637  /*
 77638  ** Check that the entry in the pointer-map for page iChild maps to 
 77639  ** page iParent, pointer type ptrType. If not, append an error message
 77640  ** to pCheck.
 77641  */
 77642  static void checkPtrmap(
 77643    IntegrityCk *pCheck,   /* Integrity check context */
 77644    Pgno iChild,           /* Child page number */
 77645    u8 eType,              /* Expected pointer map type */
 77646    Pgno iParent           /* Expected pointer map parent page number */
 77647  ){
 77648    int rc;
 77649    u8 ePtrmapType;
 77650    Pgno iPtrmapParent;
 77651  
 77652    rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
 77653    if( rc!=SQLITE_OK ){
 77654      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
 77655      checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
 77656      return;
 77657    }
 77658  
 77659    if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
 77660      checkAppendMsg(pCheck,
 77661        "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
 77662        iChild, eType, iParent, ePtrmapType, iPtrmapParent);
 77663    }
 77664  }
 77665  #endif
 77666  
 77667  /*
 77668  ** Check the integrity of the freelist or of an overflow page list.
 77669  ** Verify that the number of pages on the list is N.
 77670  */
 77671  static void checkList(
 77672    IntegrityCk *pCheck,  /* Integrity checking context */
 77673    int isFreeList,       /* True for a freelist.  False for overflow page list */
 77674    int iPage,            /* Page number for first page in the list */
 77675    int N                 /* Expected number of pages in the list */
 77676  ){
 77677    int i;
 77678    int expected = N;
 77679    int nErrAtStart = pCheck->nErr;
 77680    while( iPage!=0 && pCheck->mxErr ){
 77681      DbPage *pOvflPage;
 77682      unsigned char *pOvflData;
 77683      if( checkRef(pCheck, iPage) ) break;
 77684      N--;
 77685      if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
 77686        checkAppendMsg(pCheck, "failed to get page %d", iPage);
 77687        break;
 77688      }
 77689      pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
 77690      if( isFreeList ){
 77691        u32 n = (u32)get4byte(&pOvflData[4]);
 77692  #ifndef SQLITE_OMIT_AUTOVACUUM
 77693        if( pCheck->pBt->autoVacuum ){
 77694          checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
 77695        }
 77696  #endif
 77697        if( n>pCheck->pBt->usableSize/4-2 ){
 77698          checkAppendMsg(pCheck,
 77699             "freelist leaf count too big on page %d", iPage);
 77700          N--;
 77701        }else{
 77702          for(i=0; i<(int)n; i++){
 77703            Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
 77704  #ifndef SQLITE_OMIT_AUTOVACUUM
 77705            if( pCheck->pBt->autoVacuum ){
 77706              checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
 77707            }
 77708  #endif
 77709            checkRef(pCheck, iFreePage);
 77710          }
 77711          N -= n;
 77712        }
 77713      }
 77714  #ifndef SQLITE_OMIT_AUTOVACUUM
 77715      else{
 77716        /* If this database supports auto-vacuum and iPage is not the last
 77717        ** page in this overflow list, check that the pointer-map entry for
 77718        ** the following page matches iPage.
 77719        */
 77720        if( pCheck->pBt->autoVacuum && N>0 ){
 77721          i = get4byte(pOvflData);
 77722          checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
 77723        }
 77724      }
 77725  #endif
 77726      iPage = get4byte(pOvflData);
 77727      sqlite3PagerUnref(pOvflPage);
 77728    }
 77729    if( N && nErrAtStart==pCheck->nErr ){
 77730      checkAppendMsg(pCheck,
 77731        "%s is %d but should be %d",
 77732        isFreeList ? "size" : "overflow list length",
 77733        expected-N, expected);
 77734    }
 77735  }
 77736  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 77737  
 77738  /*
 77739  ** An implementation of a min-heap.
 77740  **
 77741  ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
 77742  ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
 77743  ** and aHeap[N*2+1].
 77744  **
 77745  ** The heap property is this:  Every node is less than or equal to both
 77746  ** of its daughter nodes.  A consequence of the heap property is that the
 77747  ** root node aHeap[1] is always the minimum value currently in the heap.
 77748  **
 77749  ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
 77750  ** the heap, preserving the heap property.  The btreeHeapPull() routine
 77751  ** removes the root element from the heap (the minimum value in the heap)
 77752  ** and then moves other nodes around as necessary to preserve the heap
 77753  ** property.
 77754  **
 77755  ** This heap is used for cell overlap and coverage testing.  Each u32
 77756  ** entry represents the span of a cell or freeblock on a btree page.  
 77757  ** The upper 16 bits are the index of the first byte of a range and the
 77758  ** lower 16 bits are the index of the last byte of that range.
 77759  */
 77760  static void btreeHeapInsert(u32 *aHeap, u32 x){
 77761    u32 j, i = ++aHeap[0];
 77762    aHeap[i] = x;
 77763    while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
 77764      x = aHeap[j];
 77765      aHeap[j] = aHeap[i];
 77766      aHeap[i] = x;
 77767      i = j;
 77768    }
 77769  }
 77770  static int btreeHeapPull(u32 *aHeap, u32 *pOut){
 77771    u32 j, i, x;
 77772    if( (x = aHeap[0])==0 ) return 0;
 77773    *pOut = aHeap[1];
 77774    aHeap[1] = aHeap[x];
 77775    aHeap[x] = 0xffffffff;
 77776    aHeap[0]--;
 77777    i = 1;
 77778    while( (j = i*2)<=aHeap[0] ){
 77779      if( aHeap[j]>aHeap[j+1] ) j++;
 77780      if( aHeap[i]<aHeap[j] ) break;
 77781      x = aHeap[i];
 77782      aHeap[i] = aHeap[j];
 77783      aHeap[j] = x;
 77784      i = j;
 77785    }
 77786    return 1;  
 77787  }
 77788  
 77789  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 77790  /*
 77791  ** Do various sanity checks on a single page of a tree.  Return
 77792  ** the tree depth.  Root pages return 0.  Parents of root pages
 77793  ** return 1, and so forth.
 77794  ** 
 77795  ** These checks are done:
 77796  **
 77797  **      1.  Make sure that cells and freeblocks do not overlap
 77798  **          but combine to completely cover the page.
 77799  **      2.  Make sure integer cell keys are in order.
 77800  **      3.  Check the integrity of overflow pages.
 77801  **      4.  Recursively call checkTreePage on all children.
 77802  **      5.  Verify that the depth of all children is the same.
 77803  */
 77804  static int checkTreePage(
 77805    IntegrityCk *pCheck,  /* Context for the sanity check */
 77806    int iPage,            /* Page number of the page to check */
 77807    i64 *piMinKey,        /* Write minimum integer primary key here */
 77808    i64 maxKey            /* Error if integer primary key greater than this */
 77809  ){
 77810    MemPage *pPage = 0;      /* The page being analyzed */
 77811    int i;                   /* Loop counter */
 77812    int rc;                  /* Result code from subroutine call */
 77813    int depth = -1, d2;      /* Depth of a subtree */
 77814    int pgno;                /* Page number */
 77815    int nFrag;               /* Number of fragmented bytes on the page */
 77816    int hdr;                 /* Offset to the page header */
 77817    int cellStart;           /* Offset to the start of the cell pointer array */
 77818    int nCell;               /* Number of cells */
 77819    int doCoverageCheck = 1; /* True if cell coverage checking should be done */
 77820    int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
 77821                             ** False if IPK must be strictly less than maxKey */
 77822    u8 *data;                /* Page content */
 77823    u8 *pCell;               /* Cell content */
 77824    u8 *pCellIdx;            /* Next element of the cell pointer array */
 77825    BtShared *pBt;           /* The BtShared object that owns pPage */
 77826    u32 pc;                  /* Address of a cell */
 77827    u32 usableSize;          /* Usable size of the page */
 77828    u32 contentOffset;       /* Offset to the start of the cell content area */
 77829    u32 *heap = 0;           /* Min-heap used for checking cell coverage */
 77830    u32 x, prev = 0;         /* Next and previous entry on the min-heap */
 77831    const char *saved_zPfx = pCheck->zPfx;
 77832    int saved_v1 = pCheck->v1;
 77833    int saved_v2 = pCheck->v2;
 77834    u8 savedIsInit = 0;
 77835  
 77836    /* Check that the page exists
 77837    */
 77838    pBt = pCheck->pBt;
 77839    usableSize = pBt->usableSize;
 77840    if( iPage==0 ) return 0;
 77841    if( checkRef(pCheck, iPage) ) return 0;
 77842    pCheck->zPfx = "Page %d: ";
 77843    pCheck->v1 = iPage;
 77844    if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
 77845      checkAppendMsg(pCheck,
 77846         "unable to get the page. error code=%d", rc);
 77847      goto end_of_check;
 77848    }
 77849  
 77850    /* Clear MemPage.isInit to make sure the corruption detection code in
 77851    ** btreeInitPage() is executed.  */
 77852    savedIsInit = pPage->isInit;
 77853    pPage->isInit = 0;
 77854    if( (rc = btreeInitPage(pPage))!=0 ){
 77855      assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
 77856      checkAppendMsg(pCheck,
 77857                     "btreeInitPage() returns error code %d", rc);
 77858      goto end_of_check;
 77859    }
 77860    data = pPage->aData;
 77861    hdr = pPage->hdrOffset;
 77862  
 77863    /* Set up for cell analysis */
 77864    pCheck->zPfx = "On tree page %d cell %d: ";
 77865    contentOffset = get2byteNotZero(&data[hdr+5]);
 77866    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
 77867  
 77868    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
 77869    ** number of cells on the page. */
 77870    nCell = get2byte(&data[hdr+3]);
 77871    assert( pPage->nCell==nCell );
 77872  
 77873    /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
 77874    ** immediately follows the b-tree page header. */
 77875    cellStart = hdr + 12 - 4*pPage->leaf;
 77876    assert( pPage->aCellIdx==&data[cellStart] );
 77877    pCellIdx = &data[cellStart + 2*(nCell-1)];
 77878  
 77879    if( !pPage->leaf ){
 77880      /* Analyze the right-child page of internal pages */
 77881      pgno = get4byte(&data[hdr+8]);
 77882  #ifndef SQLITE_OMIT_AUTOVACUUM
 77883      if( pBt->autoVacuum ){
 77884        pCheck->zPfx = "On page %d at right child: ";
 77885        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
 77886      }
 77887  #endif
 77888      depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
 77889      keyCanBeEqual = 0;
 77890    }else{
 77891      /* For leaf pages, the coverage check will occur in the same loop
 77892      ** as the other cell checks, so initialize the heap.  */
 77893      heap = pCheck->heap;
 77894      heap[0] = 0;
 77895    }
 77896  
 77897    /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
 77898    ** integer offsets to the cell contents. */
 77899    for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
 77900      CellInfo info;
 77901  
 77902      /* Check cell size */
 77903      pCheck->v2 = i;
 77904      assert( pCellIdx==&data[cellStart + i*2] );
 77905      pc = get2byteAligned(pCellIdx);
 77906      pCellIdx -= 2;
 77907      if( pc<contentOffset || pc>usableSize-4 ){
 77908        checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
 77909                               pc, contentOffset, usableSize-4);
 77910        doCoverageCheck = 0;
 77911        continue;
 77912      }
 77913      pCell = &data[pc];
 77914      pPage->xParseCell(pPage, pCell, &info);
 77915      if( pc+info.nSize>usableSize ){
 77916        checkAppendMsg(pCheck, "Extends off end of page");
 77917        doCoverageCheck = 0;
 77918        continue;
 77919      }
 77920  
 77921      /* Check for integer primary key out of range */
 77922      if( pPage->intKey ){
 77923        if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
 77924          checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
 77925        }
 77926        maxKey = info.nKey;
 77927        keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
 77928      }
 77929  
 77930      /* Check the content overflow list */
 77931      if( info.nPayload>info.nLocal ){
 77932        int nPage;       /* Number of pages on the overflow chain */
 77933        Pgno pgnoOvfl;   /* First page of the overflow chain */
 77934        assert( pc + info.nSize - 4 <= usableSize );
 77935        nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
 77936        pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
 77937  #ifndef SQLITE_OMIT_AUTOVACUUM
 77938        if( pBt->autoVacuum ){
 77939          checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
 77940        }
 77941  #endif
 77942        checkList(pCheck, 0, pgnoOvfl, nPage);
 77943      }
 77944  
 77945      if( !pPage->leaf ){
 77946        /* Check sanity of left child page for internal pages */
 77947        pgno = get4byte(pCell);
 77948  #ifndef SQLITE_OMIT_AUTOVACUUM
 77949        if( pBt->autoVacuum ){
 77950          checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
 77951        }
 77952  #endif
 77953        d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
 77954        keyCanBeEqual = 0;
 77955        if( d2!=depth ){
 77956          checkAppendMsg(pCheck, "Child page depth differs");
 77957          depth = d2;
 77958        }
 77959      }else{
 77960        /* Populate the coverage-checking heap for leaf pages */
 77961        btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
 77962      }
 77963    }
 77964    *piMinKey = maxKey;
 77965  
 77966    /* Check for complete coverage of the page
 77967    */
 77968    pCheck->zPfx = 0;
 77969    if( doCoverageCheck && pCheck->mxErr>0 ){
 77970      /* For leaf pages, the min-heap has already been initialized and the
 77971      ** cells have already been inserted.  But for internal pages, that has
 77972      ** not yet been done, so do it now */
 77973      if( !pPage->leaf ){
 77974        heap = pCheck->heap;
 77975        heap[0] = 0;
 77976        for(i=nCell-1; i>=0; i--){
 77977          u32 size;
 77978          pc = get2byteAligned(&data[cellStart+i*2]);
 77979          size = pPage->xCellSize(pPage, &data[pc]);
 77980          btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
 77981        }
 77982      }
 77983      /* Add the freeblocks to the min-heap
 77984      **
 77985      ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
 77986      ** is the offset of the first freeblock, or zero if there are no
 77987      ** freeblocks on the page. 
 77988      */
 77989      i = get2byte(&data[hdr+1]);
 77990      while( i>0 ){
 77991        int size, j;
 77992        assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
 77993        size = get2byte(&data[i+2]);
 77994        assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
 77995        btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
 77996        /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
 77997        ** big-endian integer which is the offset in the b-tree page of the next
 77998        ** freeblock in the chain, or zero if the freeblock is the last on the
 77999        ** chain. */
 78000        j = get2byte(&data[i]);
 78001        /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
 78002        ** increasing offset. */
 78003        assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
 78004        assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
 78005        i = j;
 78006      }
 78007      /* Analyze the min-heap looking for overlap between cells and/or 
 78008      ** freeblocks, and counting the number of untracked bytes in nFrag.
 78009      ** 
 78010      ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
 78011      ** There is an implied first entry the covers the page header, the cell
 78012      ** pointer index, and the gap between the cell pointer index and the start
 78013      ** of cell content.  
 78014      **
 78015      ** The loop below pulls entries from the min-heap in order and compares
 78016      ** the start_address against the previous end_address.  If there is an
 78017      ** overlap, that means bytes are used multiple times.  If there is a gap,
 78018      ** that gap is added to the fragmentation count.
 78019      */
 78020      nFrag = 0;
 78021      prev = contentOffset - 1;   /* Implied first min-heap entry */
 78022      while( btreeHeapPull(heap,&x) ){
 78023        if( (prev&0xffff)>=(x>>16) ){
 78024          checkAppendMsg(pCheck,
 78025            "Multiple uses for byte %u of page %d", x>>16, iPage);
 78026          break;
 78027        }else{
 78028          nFrag += (x>>16) - (prev&0xffff) - 1;
 78029          prev = x;
 78030        }
 78031      }
 78032      nFrag += usableSize - (prev&0xffff) - 1;
 78033      /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
 78034      ** is stored in the fifth field of the b-tree page header.
 78035      ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
 78036      ** number of fragmented free bytes within the cell content area.
 78037      */
 78038      if( heap[0]==0 && nFrag!=data[hdr+7] ){
 78039        checkAppendMsg(pCheck,
 78040            "Fragmentation of %d bytes reported as %d on page %d",
 78041            nFrag, data[hdr+7], iPage);
 78042      }
 78043    }
 78044  
 78045  end_of_check:
 78046    if( !doCoverageCheck ) pPage->isInit = savedIsInit;
 78047    releasePage(pPage);
 78048    pCheck->zPfx = saved_zPfx;
 78049    pCheck->v1 = saved_v1;
 78050    pCheck->v2 = saved_v2;
 78051    return depth+1;
 78052  }
 78053  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 78054  
 78055  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 78056  /*
 78057  ** This routine does a complete check of the given BTree file.  aRoot[] is
 78058  ** an array of pages numbers were each page number is the root page of
 78059  ** a table.  nRoot is the number of entries in aRoot.
 78060  **
 78061  ** A read-only or read-write transaction must be opened before calling
 78062  ** this function.
 78063  **
 78064  ** Write the number of error seen in *pnErr.  Except for some memory
 78065  ** allocation errors,  an error message held in memory obtained from
 78066  ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
 78067  ** returned.  If a memory allocation error occurs, NULL is returned.
 78068  */
 78069  SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 78070    Btree *p,     /* The btree to be checked */
 78071    int *aRoot,   /* An array of root pages numbers for individual trees */
 78072    int nRoot,    /* Number of entries in aRoot[] */
 78073    int mxErr,    /* Stop reporting errors after this many */
 78074    int *pnErr    /* Write number of errors seen to this variable */
 78075  ){
 78076    Pgno i;
 78077    IntegrityCk sCheck;
 78078    BtShared *pBt = p->pBt;
 78079    u64 savedDbFlags = pBt->db->flags;
 78080    char zErr[100];
 78081    VVA_ONLY( int nRef );
 78082  
 78083    sqlite3BtreeEnter(p);
 78084    assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
 78085    VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
 78086    assert( nRef>=0 );
 78087    sCheck.pBt = pBt;
 78088    sCheck.pPager = pBt->pPager;
 78089    sCheck.nPage = btreePagecount(sCheck.pBt);
 78090    sCheck.mxErr = mxErr;
 78091    sCheck.nErr = 0;
 78092    sCheck.mallocFailed = 0;
 78093    sCheck.zPfx = 0;
 78094    sCheck.v1 = 0;
 78095    sCheck.v2 = 0;
 78096    sCheck.aPgRef = 0;
 78097    sCheck.heap = 0;
 78098    sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
 78099    sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
 78100    if( sCheck.nPage==0 ){
 78101      goto integrity_ck_cleanup;
 78102    }
 78103  
 78104    sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
 78105    if( !sCheck.aPgRef ){
 78106      sCheck.mallocFailed = 1;
 78107      goto integrity_ck_cleanup;
 78108    }
 78109    sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
 78110    if( sCheck.heap==0 ){
 78111      sCheck.mallocFailed = 1;
 78112      goto integrity_ck_cleanup;
 78113    }
 78114  
 78115    i = PENDING_BYTE_PAGE(pBt);
 78116    if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
 78117  
 78118    /* Check the integrity of the freelist
 78119    */
 78120    sCheck.zPfx = "Main freelist: ";
 78121    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
 78122              get4byte(&pBt->pPage1->aData[36]));
 78123    sCheck.zPfx = 0;
 78124  
 78125    /* Check all the tables.
 78126    */
 78127  #ifndef SQLITE_OMIT_AUTOVACUUM
 78128    if( pBt->autoVacuum ){
 78129      int mx = 0;
 78130      int mxInHdr;
 78131      for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
 78132      mxInHdr = get4byte(&pBt->pPage1->aData[52]);
 78133      if( mx!=mxInHdr ){
 78134        checkAppendMsg(&sCheck,
 78135          "max rootpage (%d) disagrees with header (%d)",
 78136          mx, mxInHdr
 78137        );
 78138      }
 78139    }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
 78140      checkAppendMsg(&sCheck,
 78141        "incremental_vacuum enabled with a max rootpage of zero"
 78142      );
 78143    }
 78144  #endif
 78145    testcase( pBt->db->flags & SQLITE_CellSizeCk );
 78146    pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
 78147    for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
 78148      i64 notUsed;
 78149      if( aRoot[i]==0 ) continue;
 78150  #ifndef SQLITE_OMIT_AUTOVACUUM
 78151      if( pBt->autoVacuum && aRoot[i]>1 ){
 78152        checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
 78153      }
 78154  #endif
 78155      checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
 78156    }
 78157    pBt->db->flags = savedDbFlags;
 78158  
 78159    /* Make sure every page in the file is referenced
 78160    */
 78161    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
 78162  #ifdef SQLITE_OMIT_AUTOVACUUM
 78163      if( getPageReferenced(&sCheck, i)==0 ){
 78164        checkAppendMsg(&sCheck, "Page %d is never used", i);
 78165      }
 78166  #else
 78167      /* If the database supports auto-vacuum, make sure no tables contain
 78168      ** references to pointer-map pages.
 78169      */
 78170      if( getPageReferenced(&sCheck, i)==0 && 
 78171         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
 78172        checkAppendMsg(&sCheck, "Page %d is never used", i);
 78173      }
 78174      if( getPageReferenced(&sCheck, i)!=0 && 
 78175         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
 78176        checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
 78177      }
 78178  #endif
 78179    }
 78180  
 78181    /* Clean  up and report errors.
 78182    */
 78183  integrity_ck_cleanup:
 78184    sqlite3PageFree(sCheck.heap);
 78185    sqlite3_free(sCheck.aPgRef);
 78186    if( sCheck.mallocFailed ){
 78187      sqlite3_str_reset(&sCheck.errMsg);
 78188      sCheck.nErr++;
 78189    }
 78190    *pnErr = sCheck.nErr;
 78191    if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
 78192    /* Make sure this analysis did not leave any unref() pages. */
 78193    assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
 78194    sqlite3BtreeLeave(p);
 78195    return sqlite3StrAccumFinish(&sCheck.errMsg);
 78196  }
 78197  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 78198  
 78199  /*
 78200  ** Return the full pathname of the underlying database file.  Return
 78201  ** an empty string if the database is in-memory or a TEMP database.
 78202  **
 78203  ** The pager filename is invariant as long as the pager is
 78204  ** open so it is safe to access without the BtShared mutex.
 78205  */
 78206  SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
 78207    assert( p->pBt->pPager!=0 );
 78208    return sqlite3PagerFilename(p->pBt->pPager, 1);
 78209  }
 78210  
 78211  /*
 78212  ** Return the pathname of the journal file for this database. The return
 78213  ** value of this routine is the same regardless of whether the journal file
 78214  ** has been created or not.
 78215  **
 78216  ** The pager journal filename is invariant as long as the pager is
 78217  ** open so it is safe to access without the BtShared mutex.
 78218  */
 78219  SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
 78220    assert( p->pBt->pPager!=0 );
 78221    return sqlite3PagerJournalname(p->pBt->pPager);
 78222  }
 78223  
 78224  /*
 78225  ** Return non-zero if a transaction is active.
 78226  */
 78227  SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
 78228    assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
 78229    return (p && (p->inTrans==TRANS_WRITE));
 78230  }
 78231  
 78232  #ifndef SQLITE_OMIT_WAL
 78233  /*
 78234  ** Run a checkpoint on the Btree passed as the first argument.
 78235  **
 78236  ** Return SQLITE_LOCKED if this or any other connection has an open 
 78237  ** transaction on the shared-cache the argument Btree is connected to.
 78238  **
 78239  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 78240  */
 78241  SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
 78242    int rc = SQLITE_OK;
 78243    if( p ){
 78244      BtShared *pBt = p->pBt;
 78245      sqlite3BtreeEnter(p);
 78246      if( pBt->inTransaction!=TRANS_NONE ){
 78247        rc = SQLITE_LOCKED;
 78248      }else{
 78249        rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
 78250      }
 78251      sqlite3BtreeLeave(p);
 78252    }
 78253    return rc;
 78254  }
 78255  #endif
 78256  
 78257  /*
 78258  ** Return non-zero if a read (or write) transaction is active.
 78259  */
 78260  SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
 78261    assert( p );
 78262    assert( sqlite3_mutex_held(p->db->mutex) );
 78263    return p->inTrans!=TRANS_NONE;
 78264  }
 78265  
 78266  SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
 78267    assert( p );
 78268    assert( sqlite3_mutex_held(p->db->mutex) );
 78269    return p->nBackup!=0;
 78270  }
 78271  
 78272  /*
 78273  ** This function returns a pointer to a blob of memory associated with
 78274  ** a single shared-btree. The memory is used by client code for its own
 78275  ** purposes (for example, to store a high-level schema associated with 
 78276  ** the shared-btree). The btree layer manages reference counting issues.
 78277  **
 78278  ** The first time this is called on a shared-btree, nBytes bytes of memory
 78279  ** are allocated, zeroed, and returned to the caller. For each subsequent 
 78280  ** call the nBytes parameter is ignored and a pointer to the same blob
 78281  ** of memory returned. 
 78282  **
 78283  ** If the nBytes parameter is 0 and the blob of memory has not yet been
 78284  ** allocated, a null pointer is returned. If the blob has already been
 78285  ** allocated, it is returned as normal.
 78286  **
 78287  ** Just before the shared-btree is closed, the function passed as the 
 78288  ** xFree argument when the memory allocation was made is invoked on the 
 78289  ** blob of allocated memory. The xFree function should not call sqlite3_free()
 78290  ** on the memory, the btree layer does that.
 78291  */
 78292  SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
 78293    BtShared *pBt = p->pBt;
 78294    sqlite3BtreeEnter(p);
 78295    if( !pBt->pSchema && nBytes ){
 78296      pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
 78297      pBt->xFreeSchema = xFree;
 78298    }
 78299    sqlite3BtreeLeave(p);
 78300    return pBt->pSchema;
 78301  }
 78302  
 78303  /*
 78304  ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
 78305  ** btree as the argument handle holds an exclusive lock on the 
 78306  ** sqlite_master table. Otherwise SQLITE_OK.
 78307  */
 78308  SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
 78309    int rc;
 78310    assert( sqlite3_mutex_held(p->db->mutex) );
 78311    sqlite3BtreeEnter(p);
 78312    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
 78313    assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
 78314    sqlite3BtreeLeave(p);
 78315    return rc;
 78316  }
 78317  
 78318  
 78319  #ifndef SQLITE_OMIT_SHARED_CACHE
 78320  /*
 78321  ** Obtain a lock on the table whose root page is iTab.  The
 78322  ** lock is a write lock if isWritelock is true or a read lock
 78323  ** if it is false.
 78324  */
 78325  SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
 78326    int rc = SQLITE_OK;
 78327    assert( p->inTrans!=TRANS_NONE );
 78328    if( p->sharable ){
 78329      u8 lockType = READ_LOCK + isWriteLock;
 78330      assert( READ_LOCK+1==WRITE_LOCK );
 78331      assert( isWriteLock==0 || isWriteLock==1 );
 78332  
 78333      sqlite3BtreeEnter(p);
 78334      rc = querySharedCacheTableLock(p, iTab, lockType);
 78335      if( rc==SQLITE_OK ){
 78336        rc = setSharedCacheTableLock(p, iTab, lockType);
 78337      }
 78338      sqlite3BtreeLeave(p);
 78339    }
 78340    return rc;
 78341  }
 78342  #endif
 78343  
 78344  #ifndef SQLITE_OMIT_INCRBLOB
 78345  /*
 78346  ** Argument pCsr must be a cursor opened for writing on an 
 78347  ** INTKEY table currently pointing at a valid table entry. 
 78348  ** This function modifies the data stored as part of that entry.
 78349  **
 78350  ** Only the data content may only be modified, it is not possible to 
 78351  ** change the length of the data stored. If this function is called with
 78352  ** parameters that attempt to write past the end of the existing data,
 78353  ** no modifications are made and SQLITE_CORRUPT is returned.
 78354  */
 78355  SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
 78356    int rc;
 78357    assert( cursorOwnsBtShared(pCsr) );
 78358    assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
 78359    assert( pCsr->curFlags & BTCF_Incrblob );
 78360  
 78361    rc = restoreCursorPosition(pCsr);
 78362    if( rc!=SQLITE_OK ){
 78363      return rc;
 78364    }
 78365    assert( pCsr->eState!=CURSOR_REQUIRESEEK );
 78366    if( pCsr->eState!=CURSOR_VALID ){
 78367      return SQLITE_ABORT;
 78368    }
 78369  
 78370    /* Save the positions of all other cursors open on this table. This is
 78371    ** required in case any of them are holding references to an xFetch
 78372    ** version of the b-tree page modified by the accessPayload call below.
 78373    **
 78374    ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
 78375    ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
 78376    ** saveAllCursors can only return SQLITE_OK.
 78377    */
 78378    VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
 78379    assert( rc==SQLITE_OK );
 78380  
 78381    /* Check some assumptions: 
 78382    **   (a) the cursor is open for writing,
 78383    **   (b) there is a read/write transaction open,
 78384    **   (c) the connection holds a write-lock on the table (if required),
 78385    **   (d) there are no conflicting read-locks, and
 78386    **   (e) the cursor points at a valid row of an intKey table.
 78387    */
 78388    if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
 78389      return SQLITE_READONLY;
 78390    }
 78391    assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
 78392                && pCsr->pBt->inTransaction==TRANS_WRITE );
 78393    assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
 78394    assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
 78395    assert( pCsr->pPage->intKey );
 78396  
 78397    return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
 78398  }
 78399  
 78400  /* 
 78401  ** Mark this cursor as an incremental blob cursor.
 78402  */
 78403  SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
 78404    pCur->curFlags |= BTCF_Incrblob;
 78405    pCur->pBtree->hasIncrblobCur = 1;
 78406  }
 78407  #endif
 78408  
 78409  /*
 78410  ** Set both the "read version" (single byte at byte offset 18) and 
 78411  ** "write version" (single byte at byte offset 19) fields in the database
 78412  ** header to iVersion.
 78413  */
 78414  SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
 78415    BtShared *pBt = pBtree->pBt;
 78416    int rc;                         /* Return code */
 78417   
 78418    assert( iVersion==1 || iVersion==2 );
 78419  
 78420    /* If setting the version fields to 1, do not automatically open the
 78421    ** WAL connection, even if the version fields are currently set to 2.
 78422    */
 78423    pBt->btsFlags &= ~BTS_NO_WAL;
 78424    if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
 78425  
 78426    rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
 78427    if( rc==SQLITE_OK ){
 78428      u8 *aData = pBt->pPage1->aData;
 78429      if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
 78430        rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
 78431        if( rc==SQLITE_OK ){
 78432          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 78433          if( rc==SQLITE_OK ){
 78434            aData[18] = (u8)iVersion;
 78435            aData[19] = (u8)iVersion;
 78436          }
 78437        }
 78438      }
 78439    }
 78440  
 78441    pBt->btsFlags &= ~BTS_NO_WAL;
 78442    return rc;
 78443  }
 78444  
 78445  /*
 78446  ** Return true if the cursor has a hint specified.  This routine is
 78447  ** only used from within assert() statements
 78448  */
 78449  SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
 78450    return (pCsr->hints & mask)!=0;
 78451  }
 78452  
 78453  /*
 78454  ** Return true if the given Btree is read-only.
 78455  */
 78456  SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
 78457    return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
 78458  }
 78459  
 78460  /*
 78461  ** Return the size of the header added to each page by this module.
 78462  */
 78463  SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
 78464  
 78465  #if !defined(SQLITE_OMIT_SHARED_CACHE)
 78466  /*
 78467  ** Return true if the Btree passed as the only argument is sharable.
 78468  */
 78469  SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
 78470    return p->sharable;
 78471  }
 78472  
 78473  /*
 78474  ** Return the number of connections to the BtShared object accessed by
 78475  ** the Btree handle passed as the only argument. For private caches 
 78476  ** this is always 1. For shared caches it may be 1 or greater.
 78477  */
 78478  SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
 78479    testcase( p->sharable );
 78480    return p->pBt->nRef;
 78481  }
 78482  #endif
 78483  
 78484  /************** End of btree.c ***********************************************/
 78485  /************** Begin file backup.c ******************************************/
 78486  /*
 78487  ** 2009 January 28
 78488  **
 78489  ** The author disclaims copyright to this source code.  In place of
 78490  ** a legal notice, here is a blessing:
 78491  **
 78492  **    May you do good and not evil.
 78493  **    May you find forgiveness for yourself and forgive others.
 78494  **    May you share freely, never taking more than you give.
 78495  **
 78496  *************************************************************************
 78497  ** This file contains the implementation of the sqlite3_backup_XXX() 
 78498  ** API functions and the related features.
 78499  */
 78500  /* #include "sqliteInt.h" */
 78501  /* #include "btreeInt.h" */
 78502  
 78503  /*
 78504  ** Structure allocated for each backup operation.
 78505  */
 78506  struct sqlite3_backup {
 78507    sqlite3* pDestDb;        /* Destination database handle */
 78508    Btree *pDest;            /* Destination b-tree file */
 78509    u32 iDestSchema;         /* Original schema cookie in destination */
 78510    int bDestLocked;         /* True once a write-transaction is open on pDest */
 78511  
 78512    Pgno iNext;              /* Page number of the next source page to copy */
 78513    sqlite3* pSrcDb;         /* Source database handle */
 78514    Btree *pSrc;             /* Source b-tree file */
 78515  
 78516    int rc;                  /* Backup process error code */
 78517  
 78518    /* These two variables are set by every call to backup_step(). They are
 78519    ** read by calls to backup_remaining() and backup_pagecount().
 78520    */
 78521    Pgno nRemaining;         /* Number of pages left to copy */
 78522    Pgno nPagecount;         /* Total number of pages to copy */
 78523  
 78524    int isAttached;          /* True once backup has been registered with pager */
 78525    sqlite3_backup *pNext;   /* Next backup associated with source pager */
 78526  };
 78527  
 78528  /*
 78529  ** THREAD SAFETY NOTES:
 78530  **
 78531  **   Once it has been created using backup_init(), a single sqlite3_backup
 78532  **   structure may be accessed via two groups of thread-safe entry points:
 78533  **
 78534  **     * Via the sqlite3_backup_XXX() API function backup_step() and 
 78535  **       backup_finish(). Both these functions obtain the source database
 78536  **       handle mutex and the mutex associated with the source BtShared 
 78537  **       structure, in that order.
 78538  **
 78539  **     * Via the BackupUpdate() and BackupRestart() functions, which are
 78540  **       invoked by the pager layer to report various state changes in
 78541  **       the page cache associated with the source database. The mutex
 78542  **       associated with the source database BtShared structure will always 
 78543  **       be held when either of these functions are invoked.
 78544  **
 78545  **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
 78546  **   backup_pagecount() are not thread-safe functions. If they are called
 78547  **   while some other thread is calling backup_step() or backup_finish(),
 78548  **   the values returned may be invalid. There is no way for a call to
 78549  **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
 78550  **   or backup_pagecount().
 78551  **
 78552  **   Depending on the SQLite configuration, the database handles and/or
 78553  **   the Btree objects may have their own mutexes that require locking.
 78554  **   Non-sharable Btrees (in-memory databases for example), do not have
 78555  **   associated mutexes.
 78556  */
 78557  
 78558  /*
 78559  ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
 78560  ** in connection handle pDb. If such a database cannot be found, return
 78561  ** a NULL pointer and write an error message to pErrorDb.
 78562  **
 78563  ** If the "temp" database is requested, it may need to be opened by this 
 78564  ** function. If an error occurs while doing so, return 0 and write an 
 78565  ** error message to pErrorDb.
 78566  */
 78567  static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
 78568    int i = sqlite3FindDbName(pDb, zDb);
 78569  
 78570    if( i==1 ){
 78571      Parse sParse;
 78572      int rc = 0;
 78573      memset(&sParse, 0, sizeof(sParse));
 78574      sParse.db = pDb;
 78575      if( sqlite3OpenTempDatabase(&sParse) ){
 78576        sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
 78577        rc = SQLITE_ERROR;
 78578      }
 78579      sqlite3DbFree(pErrorDb, sParse.zErrMsg);
 78580      sqlite3ParserReset(&sParse);
 78581      if( rc ){
 78582        return 0;
 78583      }
 78584    }
 78585  
 78586    if( i<0 ){
 78587      sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
 78588      return 0;
 78589    }
 78590  
 78591    return pDb->aDb[i].pBt;
 78592  }
 78593  
 78594  /*
 78595  ** Attempt to set the page size of the destination to match the page size
 78596  ** of the source.
 78597  */
 78598  static int setDestPgsz(sqlite3_backup *p){
 78599    int rc;
 78600    rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
 78601    return rc;
 78602  }
 78603  
 78604  /*
 78605  ** Check that there is no open read-transaction on the b-tree passed as the
 78606  ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
 78607  ** is an open read-transaction, return SQLITE_ERROR and leave an error 
 78608  ** message in database handle db.
 78609  */
 78610  static int checkReadTransaction(sqlite3 *db, Btree *p){
 78611    if( sqlite3BtreeIsInReadTrans(p) ){
 78612      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
 78613      return SQLITE_ERROR;
 78614    }
 78615    return SQLITE_OK;
 78616  }
 78617  
 78618  /*
 78619  ** Create an sqlite3_backup process to copy the contents of zSrcDb from
 78620  ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
 78621  ** a pointer to the new sqlite3_backup object.
 78622  **
 78623  ** If an error occurs, NULL is returned and an error code and error message
 78624  ** stored in database handle pDestDb.
 78625  */
 78626  SQLITE_API sqlite3_backup *sqlite3_backup_init(
 78627    sqlite3* pDestDb,                     /* Database to write to */
 78628    const char *zDestDb,                  /* Name of database within pDestDb */
 78629    sqlite3* pSrcDb,                      /* Database connection to read from */
 78630    const char *zSrcDb                    /* Name of database within pSrcDb */
 78631  ){
 78632    sqlite3_backup *p;                    /* Value to return */
 78633  
 78634  #ifdef SQLITE_ENABLE_API_ARMOR
 78635    if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
 78636      (void)SQLITE_MISUSE_BKPT;
 78637      return 0;
 78638    }
 78639  #endif
 78640  
 78641    /* Lock the source database handle. The destination database
 78642    ** handle is not locked in this routine, but it is locked in
 78643    ** sqlite3_backup_step(). The user is required to ensure that no
 78644    ** other thread accesses the destination handle for the duration
 78645    ** of the backup operation.  Any attempt to use the destination
 78646    ** database connection while a backup is in progress may cause
 78647    ** a malfunction or a deadlock.
 78648    */
 78649    sqlite3_mutex_enter(pSrcDb->mutex);
 78650    sqlite3_mutex_enter(pDestDb->mutex);
 78651  
 78652    if( pSrcDb==pDestDb ){
 78653      sqlite3ErrorWithMsg(
 78654          pDestDb, SQLITE_ERROR, "source and destination must be distinct"
 78655      );
 78656      p = 0;
 78657    }else {
 78658      /* Allocate space for a new sqlite3_backup object...
 78659      ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 78660      ** call to sqlite3_backup_init() and is destroyed by a call to
 78661      ** sqlite3_backup_finish(). */
 78662      p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
 78663      if( !p ){
 78664        sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
 78665      }
 78666    }
 78667  
 78668    /* If the allocation succeeded, populate the new object. */
 78669    if( p ){
 78670      p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
 78671      p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
 78672      p->pDestDb = pDestDb;
 78673      p->pSrcDb = pSrcDb;
 78674      p->iNext = 1;
 78675      p->isAttached = 0;
 78676  
 78677      if( 0==p->pSrc || 0==p->pDest 
 78678       || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
 78679       ){
 78680        /* One (or both) of the named databases did not exist or an OOM
 78681        ** error was hit. Or there is a transaction open on the destination
 78682        ** database. The error has already been written into the pDestDb 
 78683        ** handle. All that is left to do here is free the sqlite3_backup 
 78684        ** structure.  */
 78685        sqlite3_free(p);
 78686        p = 0;
 78687      }
 78688    }
 78689    if( p ){
 78690      p->pSrc->nBackup++;
 78691    }
 78692  
 78693    sqlite3_mutex_leave(pDestDb->mutex);
 78694    sqlite3_mutex_leave(pSrcDb->mutex);
 78695    return p;
 78696  }
 78697  
 78698  /*
 78699  ** Argument rc is an SQLite error code. Return true if this error is 
 78700  ** considered fatal if encountered during a backup operation. All errors
 78701  ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
 78702  */
 78703  static int isFatalError(int rc){
 78704    return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
 78705  }
 78706  
 78707  /*
 78708  ** Parameter zSrcData points to a buffer containing the data for 
 78709  ** page iSrcPg from the source database. Copy this data into the 
 78710  ** destination database.
 78711  */
 78712  static int backupOnePage(
 78713    sqlite3_backup *p,              /* Backup handle */
 78714    Pgno iSrcPg,                    /* Source database page to backup */
 78715    const u8 *zSrcData,             /* Source database page data */
 78716    int bUpdate                     /* True for an update, false otherwise */
 78717  ){
 78718    Pager * const pDestPager = sqlite3BtreePager(p->pDest);
 78719    const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
 78720    int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
 78721    const int nCopy = MIN(nSrcPgsz, nDestPgsz);
 78722    const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
 78723  #ifdef SQLITE_HAS_CODEC
 78724    /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
 78725    ** guaranteed that the shared-mutex is held by this thread, handle
 78726    ** p->pSrc may not actually be the owner.  */
 78727    int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
 78728    int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
 78729  #endif
 78730    int rc = SQLITE_OK;
 78731    i64 iOff;
 78732  
 78733    assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
 78734    assert( p->bDestLocked );
 78735    assert( !isFatalError(p->rc) );
 78736    assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
 78737    assert( zSrcData );
 78738  
 78739    /* Catch the case where the destination is an in-memory database and the
 78740    ** page sizes of the source and destination differ. 
 78741    */
 78742    if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
 78743      rc = SQLITE_READONLY;
 78744    }
 78745  
 78746  #ifdef SQLITE_HAS_CODEC
 78747    /* Backup is not possible if the page size of the destination is changing
 78748    ** and a codec is in use.
 78749    */
 78750    if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
 78751      rc = SQLITE_READONLY;
 78752    }
 78753  
 78754    /* Backup is not possible if the number of bytes of reserve space differ
 78755    ** between source and destination.  If there is a difference, try to
 78756    ** fix the destination to agree with the source.  If that is not possible,
 78757    ** then the backup cannot proceed.
 78758    */
 78759    if( nSrcReserve!=nDestReserve ){
 78760      u32 newPgsz = nSrcPgsz;
 78761      rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
 78762      if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
 78763    }
 78764  #endif
 78765  
 78766    /* This loop runs once for each destination page spanned by the source 
 78767    ** page. For each iteration, variable iOff is set to the byte offset
 78768    ** of the destination page.
 78769    */
 78770    for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
 78771      DbPage *pDestPg = 0;
 78772      Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
 78773      if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
 78774      if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
 78775       && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
 78776      ){
 78777        const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
 78778        u8 *zDestData = sqlite3PagerGetData(pDestPg);
 78779        u8 *zOut = &zDestData[iOff%nDestPgsz];
 78780  
 78781        /* Copy the data from the source page into the destination page.
 78782        ** Then clear the Btree layer MemPage.isInit flag. Both this module
 78783        ** and the pager code use this trick (clearing the first byte
 78784        ** of the page 'extra' space to invalidate the Btree layers
 78785        ** cached parse of the page). MemPage.isInit is marked 
 78786        ** "MUST BE FIRST" for this purpose.
 78787        */
 78788        memcpy(zOut, zIn, nCopy);
 78789        ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
 78790        if( iOff==0 && bUpdate==0 ){
 78791          sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
 78792        }
 78793      }
 78794      sqlite3PagerUnref(pDestPg);
 78795    }
 78796  
 78797    return rc;
 78798  }
 78799  
 78800  /*
 78801  ** If pFile is currently larger than iSize bytes, then truncate it to
 78802  ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
 78803  ** this function is a no-op.
 78804  **
 78805  ** Return SQLITE_OK if everything is successful, or an SQLite error 
 78806  ** code if an error occurs.
 78807  */
 78808  static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
 78809    i64 iCurrent;
 78810    int rc = sqlite3OsFileSize(pFile, &iCurrent);
 78811    if( rc==SQLITE_OK && iCurrent>iSize ){
 78812      rc = sqlite3OsTruncate(pFile, iSize);
 78813    }
 78814    return rc;
 78815  }
 78816  
 78817  /*
 78818  ** Register this backup object with the associated source pager for
 78819  ** callbacks when pages are changed or the cache invalidated.
 78820  */
 78821  static void attachBackupObject(sqlite3_backup *p){
 78822    sqlite3_backup **pp;
 78823    assert( sqlite3BtreeHoldsMutex(p->pSrc) );
 78824    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 78825    p->pNext = *pp;
 78826    *pp = p;
 78827    p->isAttached = 1;
 78828  }
 78829  
 78830  /*
 78831  ** Copy nPage pages from the source b-tree to the destination.
 78832  */
 78833  SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
 78834    int rc;
 78835    int destMode;       /* Destination journal mode */
 78836    int pgszSrc = 0;    /* Source page size */
 78837    int pgszDest = 0;   /* Destination page size */
 78838  
 78839  #ifdef SQLITE_ENABLE_API_ARMOR
 78840    if( p==0 ) return SQLITE_MISUSE_BKPT;
 78841  #endif
 78842    sqlite3_mutex_enter(p->pSrcDb->mutex);
 78843    sqlite3BtreeEnter(p->pSrc);
 78844    if( p->pDestDb ){
 78845      sqlite3_mutex_enter(p->pDestDb->mutex);
 78846    }
 78847  
 78848    rc = p->rc;
 78849    if( !isFatalError(rc) ){
 78850      Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
 78851      Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
 78852      int ii;                            /* Iterator variable */
 78853      int nSrcPage = -1;                 /* Size of source db in pages */
 78854      int bCloseTrans = 0;               /* True if src db requires unlocking */
 78855  
 78856      /* If the source pager is currently in a write-transaction, return
 78857      ** SQLITE_BUSY immediately.
 78858      */
 78859      if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
 78860        rc = SQLITE_BUSY;
 78861      }else{
 78862        rc = SQLITE_OK;
 78863      }
 78864  
 78865      /* If there is no open read-transaction on the source database, open
 78866      ** one now. If a transaction is opened here, then it will be closed
 78867      ** before this function exits.
 78868      */
 78869      if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
 78870        rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
 78871        bCloseTrans = 1;
 78872      }
 78873  
 78874      /* If the destination database has not yet been locked (i.e. if this
 78875      ** is the first call to backup_step() for the current backup operation),
 78876      ** try to set its page size to the same as the source database. This
 78877      ** is especially important on ZipVFS systems, as in that case it is
 78878      ** not possible to create a database file that uses one page size by
 78879      ** writing to it with another.  */
 78880      if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
 78881        rc = SQLITE_NOMEM;
 78882      }
 78883  
 78884      /* Lock the destination database, if it is not locked already. */
 78885      if( SQLITE_OK==rc && p->bDestLocked==0
 78886       && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
 78887                                                  (int*)&p->iDestSchema)) 
 78888      ){
 78889        p->bDestLocked = 1;
 78890      }
 78891  
 78892      /* Do not allow backup if the destination database is in WAL mode
 78893      ** and the page sizes are different between source and destination */
 78894      pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
 78895      pgszDest = sqlite3BtreeGetPageSize(p->pDest);
 78896      destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
 78897      if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
 78898        rc = SQLITE_READONLY;
 78899      }
 78900    
 78901      /* Now that there is a read-lock on the source database, query the
 78902      ** source pager for the number of pages in the database.
 78903      */
 78904      nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
 78905      assert( nSrcPage>=0 );
 78906      for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
 78907        const Pgno iSrcPg = p->iNext;                 /* Source page number */
 78908        if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
 78909          DbPage *pSrcPg;                             /* Source page object */
 78910          rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
 78911          if( rc==SQLITE_OK ){
 78912            rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
 78913            sqlite3PagerUnref(pSrcPg);
 78914          }
 78915        }
 78916        p->iNext++;
 78917      }
 78918      if( rc==SQLITE_OK ){
 78919        p->nPagecount = nSrcPage;
 78920        p->nRemaining = nSrcPage+1-p->iNext;
 78921        if( p->iNext>(Pgno)nSrcPage ){
 78922          rc = SQLITE_DONE;
 78923        }else if( !p->isAttached ){
 78924          attachBackupObject(p);
 78925        }
 78926      }
 78927    
 78928      /* Update the schema version field in the destination database. This
 78929      ** is to make sure that the schema-version really does change in
 78930      ** the case where the source and destination databases have the
 78931      ** same schema version.
 78932      */
 78933      if( rc==SQLITE_DONE ){
 78934        if( nSrcPage==0 ){
 78935          rc = sqlite3BtreeNewDb(p->pDest);
 78936          nSrcPage = 1;
 78937        }
 78938        if( rc==SQLITE_OK || rc==SQLITE_DONE ){
 78939          rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
 78940        }
 78941        if( rc==SQLITE_OK ){
 78942          if( p->pDestDb ){
 78943            sqlite3ResetAllSchemasOfConnection(p->pDestDb);
 78944          }
 78945          if( destMode==PAGER_JOURNALMODE_WAL ){
 78946            rc = sqlite3BtreeSetVersion(p->pDest, 2);
 78947          }
 78948        }
 78949        if( rc==SQLITE_OK ){
 78950          int nDestTruncate;
 78951          /* Set nDestTruncate to the final number of pages in the destination
 78952          ** database. The complication here is that the destination page
 78953          ** size may be different to the source page size. 
 78954          **
 78955          ** If the source page size is smaller than the destination page size, 
 78956          ** round up. In this case the call to sqlite3OsTruncate() below will
 78957          ** fix the size of the file. However it is important to call
 78958          ** sqlite3PagerTruncateImage() here so that any pages in the 
 78959          ** destination file that lie beyond the nDestTruncate page mark are
 78960          ** journalled by PagerCommitPhaseOne() before they are destroyed
 78961          ** by the file truncation.
 78962          */
 78963          assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
 78964          assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
 78965          if( pgszSrc<pgszDest ){
 78966            int ratio = pgszDest/pgszSrc;
 78967            nDestTruncate = (nSrcPage+ratio-1)/ratio;
 78968            if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
 78969              nDestTruncate--;
 78970            }
 78971          }else{
 78972            nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
 78973          }
 78974          assert( nDestTruncate>0 );
 78975  
 78976          if( pgszSrc<pgszDest ){
 78977            /* If the source page-size is smaller than the destination page-size,
 78978            ** two extra things may need to happen:
 78979            **
 78980            **   * The destination may need to be truncated, and
 78981            **
 78982            **   * Data stored on the pages immediately following the 
 78983            **     pending-byte page in the source database may need to be
 78984            **     copied into the destination database.
 78985            */
 78986            const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
 78987            sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
 78988            Pgno iPg;
 78989            int nDstPage;
 78990            i64 iOff;
 78991            i64 iEnd;
 78992  
 78993            assert( pFile );
 78994            assert( nDestTruncate==0 
 78995                || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
 78996                  nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
 78997               && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
 78998            ));
 78999  
 79000            /* This block ensures that all data required to recreate the original
 79001            ** database has been stored in the journal for pDestPager and the
 79002            ** journal synced to disk. So at this point we may safely modify
 79003            ** the database file in any way, knowing that if a power failure
 79004            ** occurs, the original database will be reconstructed from the 
 79005            ** journal file.  */
 79006            sqlite3PagerPagecount(pDestPager, &nDstPage);
 79007            for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
 79008              if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
 79009                DbPage *pPg;
 79010                rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
 79011                if( rc==SQLITE_OK ){
 79012                  rc = sqlite3PagerWrite(pPg);
 79013                  sqlite3PagerUnref(pPg);
 79014                }
 79015              }
 79016            }
 79017            if( rc==SQLITE_OK ){
 79018              rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
 79019            }
 79020  
 79021            /* Write the extra pages and truncate the database file as required */
 79022            iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
 79023            for(
 79024              iOff=PENDING_BYTE+pgszSrc; 
 79025              rc==SQLITE_OK && iOff<iEnd; 
 79026              iOff+=pgszSrc
 79027            ){
 79028              PgHdr *pSrcPg = 0;
 79029              const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
 79030              rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
 79031              if( rc==SQLITE_OK ){
 79032                u8 *zData = sqlite3PagerGetData(pSrcPg);
 79033                rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
 79034              }
 79035              sqlite3PagerUnref(pSrcPg);
 79036            }
 79037            if( rc==SQLITE_OK ){
 79038              rc = backupTruncateFile(pFile, iSize);
 79039            }
 79040  
 79041            /* Sync the database file to disk. */
 79042            if( rc==SQLITE_OK ){
 79043              rc = sqlite3PagerSync(pDestPager, 0);
 79044            }
 79045          }else{
 79046            sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
 79047            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
 79048          }
 79049      
 79050          /* Finish committing the transaction to the destination database. */
 79051          if( SQLITE_OK==rc
 79052           && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
 79053          ){
 79054            rc = SQLITE_DONE;
 79055          }
 79056        }
 79057      }
 79058    
 79059      /* If bCloseTrans is true, then this function opened a read transaction
 79060      ** on the source database. Close the read transaction here. There is
 79061      ** no need to check the return values of the btree methods here, as
 79062      ** "committing" a read-only transaction cannot fail.
 79063      */
 79064      if( bCloseTrans ){
 79065        TESTONLY( int rc2 );
 79066        TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
 79067        TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
 79068        assert( rc2==SQLITE_OK );
 79069      }
 79070    
 79071      if( rc==SQLITE_IOERR_NOMEM ){
 79072        rc = SQLITE_NOMEM_BKPT;
 79073      }
 79074      p->rc = rc;
 79075    }
 79076    if( p->pDestDb ){
 79077      sqlite3_mutex_leave(p->pDestDb->mutex);
 79078    }
 79079    sqlite3BtreeLeave(p->pSrc);
 79080    sqlite3_mutex_leave(p->pSrcDb->mutex);
 79081    return rc;
 79082  }
 79083  
 79084  /*
 79085  ** Release all resources associated with an sqlite3_backup* handle.
 79086  */
 79087  SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
 79088    sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
 79089    sqlite3 *pSrcDb;                     /* Source database connection */
 79090    int rc;                              /* Value to return */
 79091  
 79092    /* Enter the mutexes */
 79093    if( p==0 ) return SQLITE_OK;
 79094    pSrcDb = p->pSrcDb;
 79095    sqlite3_mutex_enter(pSrcDb->mutex);
 79096    sqlite3BtreeEnter(p->pSrc);
 79097    if( p->pDestDb ){
 79098      sqlite3_mutex_enter(p->pDestDb->mutex);
 79099    }
 79100  
 79101    /* Detach this backup from the source pager. */
 79102    if( p->pDestDb ){
 79103      p->pSrc->nBackup--;
 79104    }
 79105    if( p->isAttached ){
 79106      pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
 79107      while( *pp!=p ){
 79108        pp = &(*pp)->pNext;
 79109      }
 79110      *pp = p->pNext;
 79111    }
 79112  
 79113    /* If a transaction is still open on the Btree, roll it back. */
 79114    sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
 79115  
 79116    /* Set the error code of the destination database handle. */
 79117    rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
 79118    if( p->pDestDb ){
 79119      sqlite3Error(p->pDestDb, rc);
 79120  
 79121      /* Exit the mutexes and free the backup context structure. */
 79122      sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
 79123    }
 79124    sqlite3BtreeLeave(p->pSrc);
 79125    if( p->pDestDb ){
 79126      /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
 79127      ** call to sqlite3_backup_init() and is destroyed by a call to
 79128      ** sqlite3_backup_finish(). */
 79129      sqlite3_free(p);
 79130    }
 79131    sqlite3LeaveMutexAndCloseZombie(pSrcDb);
 79132    return rc;
 79133  }
 79134  
 79135  /*
 79136  ** Return the number of pages still to be backed up as of the most recent
 79137  ** call to sqlite3_backup_step().
 79138  */
 79139  SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
 79140  #ifdef SQLITE_ENABLE_API_ARMOR
 79141    if( p==0 ){
 79142      (void)SQLITE_MISUSE_BKPT;
 79143      return 0;
 79144    }
 79145  #endif
 79146    return p->nRemaining;
 79147  }
 79148  
 79149  /*
 79150  ** Return the total number of pages in the source database as of the most 
 79151  ** recent call to sqlite3_backup_step().
 79152  */
 79153  SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
 79154  #ifdef SQLITE_ENABLE_API_ARMOR
 79155    if( p==0 ){
 79156      (void)SQLITE_MISUSE_BKPT;
 79157      return 0;
 79158    }
 79159  #endif
 79160    return p->nPagecount;
 79161  }
 79162  
 79163  /*
 79164  ** This function is called after the contents of page iPage of the
 79165  ** source database have been modified. If page iPage has already been 
 79166  ** copied into the destination database, then the data written to the
 79167  ** destination is now invalidated. The destination copy of iPage needs
 79168  ** to be updated with the new data before the backup operation is
 79169  ** complete.
 79170  **
 79171  ** It is assumed that the mutex associated with the BtShared object
 79172  ** corresponding to the source database is held when this function is
 79173  ** called.
 79174  */
 79175  static SQLITE_NOINLINE void backupUpdate(
 79176    sqlite3_backup *p,
 79177    Pgno iPage,
 79178    const u8 *aData
 79179  ){
 79180    assert( p!=0 );
 79181    do{
 79182      assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 79183      if( !isFatalError(p->rc) && iPage<p->iNext ){
 79184        /* The backup process p has already copied page iPage. But now it
 79185        ** has been modified by a transaction on the source pager. Copy
 79186        ** the new data into the backup.
 79187        */
 79188        int rc;
 79189        assert( p->pDestDb );
 79190        sqlite3_mutex_enter(p->pDestDb->mutex);
 79191        rc = backupOnePage(p, iPage, aData, 1);
 79192        sqlite3_mutex_leave(p->pDestDb->mutex);
 79193        assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
 79194        if( rc!=SQLITE_OK ){
 79195          p->rc = rc;
 79196        }
 79197      }
 79198    }while( (p = p->pNext)!=0 );
 79199  }
 79200  SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
 79201    if( pBackup ) backupUpdate(pBackup, iPage, aData);
 79202  }
 79203  
 79204  /*
 79205  ** Restart the backup process. This is called when the pager layer
 79206  ** detects that the database has been modified by an external database
 79207  ** connection. In this case there is no way of knowing which of the
 79208  ** pages that have been copied into the destination database are still 
 79209  ** valid and which are not, so the entire process needs to be restarted.
 79210  **
 79211  ** It is assumed that the mutex associated with the BtShared object
 79212  ** corresponding to the source database is held when this function is
 79213  ** called.
 79214  */
 79215  SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
 79216    sqlite3_backup *p;                   /* Iterator variable */
 79217    for(p=pBackup; p; p=p->pNext){
 79218      assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
 79219      p->iNext = 1;
 79220    }
 79221  }
 79222  
 79223  #ifndef SQLITE_OMIT_VACUUM
 79224  /*
 79225  ** Copy the complete content of pBtFrom into pBtTo.  A transaction
 79226  ** must be active for both files.
 79227  **
 79228  ** The size of file pTo may be reduced by this operation. If anything 
 79229  ** goes wrong, the transaction on pTo is rolled back. If successful, the 
 79230  ** transaction is committed before returning.
 79231  */
 79232  SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
 79233    int rc;
 79234    sqlite3_file *pFd;              /* File descriptor for database pTo */
 79235    sqlite3_backup b;
 79236    sqlite3BtreeEnter(pTo);
 79237    sqlite3BtreeEnter(pFrom);
 79238  
 79239    assert( sqlite3BtreeIsInTrans(pTo) );
 79240    pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
 79241    if( pFd->pMethods ){
 79242      i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
 79243      rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
 79244      if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
 79245      if( rc ) goto copy_finished;
 79246    }
 79247  
 79248    /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
 79249    ** to 0. This is used by the implementations of sqlite3_backup_step()
 79250    ** and sqlite3_backup_finish() to detect that they are being called
 79251    ** from this function, not directly by the user.
 79252    */
 79253    memset(&b, 0, sizeof(b));
 79254    b.pSrcDb = pFrom->db;
 79255    b.pSrc = pFrom;
 79256    b.pDest = pTo;
 79257    b.iNext = 1;
 79258  
 79259  #ifdef SQLITE_HAS_CODEC
 79260    sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
 79261  #endif
 79262  
 79263    /* 0x7FFFFFFF is the hard limit for the number of pages in a database
 79264    ** file. By passing this as the number of pages to copy to
 79265    ** sqlite3_backup_step(), we can guarantee that the copy finishes 
 79266    ** within a single call (unless an error occurs). The assert() statement
 79267    ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
 79268    ** or an error code.  */
 79269    sqlite3_backup_step(&b, 0x7FFFFFFF);
 79270    assert( b.rc!=SQLITE_OK );
 79271  
 79272    rc = sqlite3_backup_finish(&b);
 79273    if( rc==SQLITE_OK ){
 79274      pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
 79275    }else{
 79276      sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
 79277    }
 79278  
 79279    assert( sqlite3BtreeIsInTrans(pTo)==0 );
 79280  copy_finished:
 79281    sqlite3BtreeLeave(pFrom);
 79282    sqlite3BtreeLeave(pTo);
 79283    return rc;
 79284  }
 79285  #endif /* SQLITE_OMIT_VACUUM */
 79286  
 79287  /************** End of backup.c **********************************************/
 79288  /************** Begin file vdbemem.c *****************************************/
 79289  /*
 79290  ** 2004 May 26
 79291  **
 79292  ** The author disclaims copyright to this source code.  In place of
 79293  ** a legal notice, here is a blessing:
 79294  **
 79295  **    May you do good and not evil.
 79296  **    May you find forgiveness for yourself and forgive others.
 79297  **    May you share freely, never taking more than you give.
 79298  **
 79299  *************************************************************************
 79300  **
 79301  ** This file contains code use to manipulate "Mem" structure.  A "Mem"
 79302  ** stores a single value in the VDBE.  Mem is an opaque structure visible
 79303  ** only within the VDBE.  Interface routines refer to a Mem using the
 79304  ** name sqlite_value
 79305  */
 79306  /* #include "sqliteInt.h" */
 79307  /* #include "vdbeInt.h" */
 79308  
 79309  #ifdef SQLITE_DEBUG
 79310  /*
 79311  ** Check invariants on a Mem object.
 79312  **
 79313  ** This routine is intended for use inside of assert() statements, like
 79314  ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 79315  */
 79316  SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
 79317    /* If MEM_Dyn is set then Mem.xDel!=0.  
 79318    ** Mem.xDel might not be initialized if MEM_Dyn is clear.
 79319    */
 79320    assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
 79321  
 79322    /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
 79323    ** ensure that if Mem.szMalloc>0 then it is safe to do
 79324    ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
 79325    ** That saves a few cycles in inner loops. */
 79326    assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
 79327  
 79328    /* Cannot be both MEM_Int and MEM_Real at the same time */
 79329    assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
 79330  
 79331    if( p->flags & MEM_Null ){
 79332      /* Cannot be both MEM_Null and some other type */
 79333      assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
 79334  
 79335      /* If MEM_Null is set, then either the value is a pure NULL (the usual
 79336      ** case) or it is a pointer set using sqlite3_bind_pointer() or
 79337      ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
 79338      ** set.
 79339      */
 79340      if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
 79341        /* This is a pointer type.  There may be a flag to indicate what to
 79342        ** do with the pointer. */
 79343        assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
 79344                ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
 79345                ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
 79346  
 79347        /* No other bits set */
 79348        assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
 79349                             |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
 79350      }else{
 79351        /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
 79352        ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
 79353      }
 79354    }else{
 79355      /* The MEM_Cleared bit is only allowed on NULLs */
 79356      assert( (p->flags & MEM_Cleared)==0 );
 79357    }
 79358  
 79359    /* The szMalloc field holds the correct memory allocation size */
 79360    assert( p->szMalloc==0
 79361         || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
 79362  
 79363    /* If p holds a string or blob, the Mem.z must point to exactly
 79364    ** one of the following:
 79365    **
 79366    **   (1) Memory in Mem.zMalloc and managed by the Mem object
 79367    **   (2) Memory to be freed using Mem.xDel
 79368    **   (3) An ephemeral string or blob
 79369    **   (4) A static string or blob
 79370    */
 79371    if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
 79372      assert( 
 79373        ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
 79374        ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
 79375        ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
 79376        ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
 79377      );
 79378    }
 79379    return 1;
 79380  }
 79381  #endif
 79382  
 79383  #ifdef SQLITE_DEBUG
 79384  /*
 79385  ** Check that string value of pMem agrees with its integer or real value.
 79386  **
 79387  ** A single int or real value always converts to the same strings.  But
 79388  ** many different strings can be converted into the same int or real.
 79389  ** If a table contains a numeric value and an index is based on the
 79390  ** corresponding string value, then it is important that the string be
 79391  ** derived from the numeric value, not the other way around, to ensure
 79392  ** that the index and table are consistent.  See ticket
 79393  ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
 79394  ** an example.
 79395  **
 79396  ** This routine looks at pMem to verify that if it has both a numeric
 79397  ** representation and a string representation then the string rep has
 79398  ** been derived from the numeric and not the other way around.  It returns
 79399  ** true if everything is ok and false if there is a problem.
 79400  **
 79401  ** This routine is for use inside of assert() statements only.
 79402  */
 79403  SQLITE_PRIVATE int sqlite3VdbeMemConsistentDualRep(Mem *p){
 79404    char zBuf[100];
 79405    char *z;
 79406    int i, j, incr;
 79407    if( (p->flags & MEM_Str)==0 ) return 1;
 79408    if( (p->flags & (MEM_Int|MEM_Real))==0 ) return 1;
 79409    if( p->flags & MEM_Int ){
 79410      sqlite3_snprintf(sizeof(zBuf),zBuf,"%lld",p->u.i);
 79411    }else{
 79412      sqlite3_snprintf(sizeof(zBuf),zBuf,"%!.15g",p->u.r);
 79413    }
 79414    z = p->z;
 79415    i = j = 0;
 79416    incr = 1;
 79417    if( p->enc!=SQLITE_UTF8 ){
 79418      incr = 2;
 79419      if( p->enc==SQLITE_UTF16BE ) z++;
 79420    }
 79421    while( zBuf[j] ){
 79422      if( zBuf[j++]!=z[i] ) return 0;
 79423      i += incr;
 79424    }
 79425    return 1;
 79426  }
 79427  #endif /* SQLITE_DEBUG */
 79428  
 79429  /*
 79430  ** If pMem is an object with a valid string representation, this routine
 79431  ** ensures the internal encoding for the string representation is
 79432  ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
 79433  **
 79434  ** If pMem is not a string object, or the encoding of the string
 79435  ** representation is already stored using the requested encoding, then this
 79436  ** routine is a no-op.
 79437  **
 79438  ** SQLITE_OK is returned if the conversion is successful (or not required).
 79439  ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
 79440  ** between formats.
 79441  */
 79442  SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
 79443  #ifndef SQLITE_OMIT_UTF16
 79444    int rc;
 79445  #endif
 79446    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79447    assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
 79448             || desiredEnc==SQLITE_UTF16BE );
 79449    if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
 79450      return SQLITE_OK;
 79451    }
 79452    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79453  #ifdef SQLITE_OMIT_UTF16
 79454    return SQLITE_ERROR;
 79455  #else
 79456  
 79457    /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
 79458    ** then the encoding of the value may not have changed.
 79459    */
 79460    rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
 79461    assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
 79462    assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
 79463    assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
 79464    return rc;
 79465  #endif
 79466  }
 79467  
 79468  /*
 79469  ** Make sure pMem->z points to a writable allocation of at least 
 79470  ** min(n,32) bytes.
 79471  **
 79472  ** If the bPreserve argument is true, then copy of the content of
 79473  ** pMem->z into the new allocation.  pMem must be either a string or
 79474  ** blob if bPreserve is true.  If bPreserve is false, any prior content
 79475  ** in pMem->z is discarded.
 79476  */
 79477  SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
 79478    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 79479    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79480    testcase( pMem->db==0 );
 79481  
 79482    /* If the bPreserve flag is set to true, then the memory cell must already
 79483    ** contain a valid string or blob value.  */
 79484    assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
 79485    testcase( bPreserve && pMem->z==0 );
 79486  
 79487    assert( pMem->szMalloc==0
 79488         || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
 79489    if( n<32 ) n = 32;
 79490    if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
 79491      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
 79492      bPreserve = 0;
 79493    }else{
 79494      if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
 79495      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
 79496    }
 79497    if( pMem->zMalloc==0 ){
 79498      sqlite3VdbeMemSetNull(pMem);
 79499      pMem->z = 0;
 79500      pMem->szMalloc = 0;
 79501      return SQLITE_NOMEM_BKPT;
 79502    }else{
 79503      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 79504    }
 79505  
 79506    if( bPreserve && pMem->z ){
 79507      assert( pMem->z!=pMem->zMalloc );
 79508      memcpy(pMem->zMalloc, pMem->z, pMem->n);
 79509    }
 79510    if( (pMem->flags&MEM_Dyn)!=0 ){
 79511      assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
 79512      pMem->xDel((void *)(pMem->z));
 79513    }
 79514  
 79515    pMem->z = pMem->zMalloc;
 79516    pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
 79517    return SQLITE_OK;
 79518  }
 79519  
 79520  /*
 79521  ** Change the pMem->zMalloc allocation to be at least szNew bytes.
 79522  ** If pMem->zMalloc already meets or exceeds the requested size, this
 79523  ** routine is a no-op.
 79524  **
 79525  ** Any prior string or blob content in the pMem object may be discarded.
 79526  ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
 79527  ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
 79528  ** values are preserved.
 79529  **
 79530  ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
 79531  ** if unable to complete the resizing.
 79532  */
 79533  SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
 79534    assert( CORRUPT_DB || szNew>0 );
 79535    assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
 79536    if( pMem->szMalloc<szNew ){
 79537      return sqlite3VdbeMemGrow(pMem, szNew, 0);
 79538    }
 79539    assert( (pMem->flags & MEM_Dyn)==0 );
 79540    pMem->z = pMem->zMalloc;
 79541    pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
 79542    return SQLITE_OK;
 79543  }
 79544  
 79545  /*
 79546  ** It is already known that pMem contains an unterminated string.
 79547  ** Add the zero terminator.
 79548  */
 79549  static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
 79550    if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
 79551      return SQLITE_NOMEM_BKPT;
 79552    }
 79553    pMem->z[pMem->n] = 0;
 79554    pMem->z[pMem->n+1] = 0;
 79555    pMem->flags |= MEM_Term;
 79556    return SQLITE_OK;
 79557  }
 79558  
 79559  /*
 79560  ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
 79561  ** MEM.zMalloc, where it can be safely written.
 79562  **
 79563  ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
 79564  */
 79565  SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
 79566    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79567    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79568    if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
 79569      if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
 79570      if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
 79571        int rc = vdbeMemAddTerminator(pMem);
 79572        if( rc ) return rc;
 79573      }
 79574    }
 79575    pMem->flags &= ~MEM_Ephem;
 79576  #ifdef SQLITE_DEBUG
 79577    pMem->pScopyFrom = 0;
 79578  #endif
 79579  
 79580    return SQLITE_OK;
 79581  }
 79582  
 79583  /*
 79584  ** If the given Mem* has a zero-filled tail, turn it into an ordinary
 79585  ** blob stored in dynamically allocated space.
 79586  */
 79587  #ifndef SQLITE_OMIT_INCRBLOB
 79588  SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
 79589    int nByte;
 79590    assert( pMem->flags & MEM_Zero );
 79591    assert( pMem->flags&MEM_Blob );
 79592    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79593    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79594  
 79595    /* Set nByte to the number of bytes required to store the expanded blob. */
 79596    nByte = pMem->n + pMem->u.nZero;
 79597    if( nByte<=0 ){
 79598      nByte = 1;
 79599    }
 79600    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
 79601      return SQLITE_NOMEM_BKPT;
 79602    }
 79603  
 79604    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
 79605    pMem->n += pMem->u.nZero;
 79606    pMem->flags &= ~(MEM_Zero|MEM_Term);
 79607    return SQLITE_OK;
 79608  }
 79609  #endif
 79610  
 79611  /*
 79612  ** Make sure the given Mem is \u0000 terminated.
 79613  */
 79614  SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
 79615    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79616    testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
 79617    testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
 79618    if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
 79619      return SQLITE_OK;   /* Nothing to do */
 79620    }else{
 79621      return vdbeMemAddTerminator(pMem);
 79622    }
 79623  }
 79624  
 79625  /*
 79626  ** Add MEM_Str to the set of representations for the given Mem.  Numbers
 79627  ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
 79628  ** is a no-op.
 79629  **
 79630  ** Existing representations MEM_Int and MEM_Real are invalidated if
 79631  ** bForce is true but are retained if bForce is false.
 79632  **
 79633  ** A MEM_Null value will never be passed to this function. This function is
 79634  ** used for converting values to text for returning to the user (i.e. via
 79635  ** sqlite3_value_text()), or for ensuring that values to be used as btree
 79636  ** keys are strings. In the former case a NULL pointer is returned the
 79637  ** user and the latter is an internal programming error.
 79638  */
 79639  SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
 79640    int fg = pMem->flags;
 79641    const int nByte = 32;
 79642  
 79643    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79644    assert( !(fg&MEM_Zero) );
 79645    assert( !(fg&(MEM_Str|MEM_Blob)) );
 79646    assert( fg&(MEM_Int|MEM_Real) );
 79647    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79648    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79649  
 79650  
 79651    if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 79652      pMem->enc = 0;
 79653      return SQLITE_NOMEM_BKPT;
 79654    }
 79655  
 79656    /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
 79657    ** string representation of the value. Then, if the required encoding
 79658    ** is UTF-16le or UTF-16be do a translation.
 79659    ** 
 79660    ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
 79661    */
 79662    if( fg & MEM_Int ){
 79663      sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
 79664    }else{
 79665      assert( fg & MEM_Real );
 79666      sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
 79667    }
 79668    assert( pMem->z!=0 );
 79669    pMem->n = sqlite3Strlen30NN(pMem->z);
 79670    pMem->enc = SQLITE_UTF8;
 79671    pMem->flags |= MEM_Str|MEM_Term;
 79672    if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
 79673    sqlite3VdbeChangeEncoding(pMem, enc);
 79674    return SQLITE_OK;
 79675  }
 79676  
 79677  /*
 79678  ** Memory cell pMem contains the context of an aggregate function.
 79679  ** This routine calls the finalize method for that function.  The
 79680  ** result of the aggregate is stored back into pMem.
 79681  **
 79682  ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
 79683  ** otherwise.
 79684  */
 79685  SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
 79686    sqlite3_context ctx;
 79687    Mem t;
 79688    assert( pFunc!=0 );
 79689    assert( pFunc->xFinalize!=0 );
 79690    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
 79691    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79692    memset(&ctx, 0, sizeof(ctx));
 79693    memset(&t, 0, sizeof(t));
 79694    t.flags = MEM_Null;
 79695    t.db = pMem->db;
 79696    ctx.pOut = &t;
 79697    ctx.pMem = pMem;
 79698    ctx.pFunc = pFunc;
 79699    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
 79700    assert( (pMem->flags & MEM_Dyn)==0 );
 79701    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
 79702    memcpy(pMem, &t, sizeof(t));
 79703    return ctx.isError;
 79704  }
 79705  
 79706  /*
 79707  ** Memory cell pAccum contains the context of an aggregate function.
 79708  ** This routine calls the xValue method for that function and stores
 79709  ** the results in memory cell pMem.
 79710  **
 79711  ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK 
 79712  ** otherwise.
 79713  */
 79714  #ifndef SQLITE_OMIT_WINDOWFUNC
 79715  SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
 79716    sqlite3_context ctx;
 79717    Mem t;
 79718    assert( pFunc!=0 );
 79719    assert( pFunc->xValue!=0 );
 79720    assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
 79721    assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
 79722    memset(&ctx, 0, sizeof(ctx));
 79723    memset(&t, 0, sizeof(t));
 79724    t.flags = MEM_Null;
 79725    t.db = pAccum->db;
 79726    sqlite3VdbeMemSetNull(pOut);
 79727    ctx.pOut = pOut;
 79728    ctx.pMem = pAccum;
 79729    ctx.pFunc = pFunc;
 79730    pFunc->xValue(&ctx);
 79731    return ctx.isError;
 79732  }
 79733  #endif /* SQLITE_OMIT_WINDOWFUNC */
 79734  
 79735  /*
 79736  ** If the memory cell contains a value that must be freed by
 79737  ** invoking the external callback in Mem.xDel, then this routine
 79738  ** will free that value.  It also sets Mem.flags to MEM_Null.
 79739  **
 79740  ** This is a helper routine for sqlite3VdbeMemSetNull() and
 79741  ** for sqlite3VdbeMemRelease().  Use those other routines as the
 79742  ** entry point for releasing Mem resources.
 79743  */
 79744  static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
 79745    assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
 79746    assert( VdbeMemDynamic(p) );
 79747    if( p->flags&MEM_Agg ){
 79748      sqlite3VdbeMemFinalize(p, p->u.pDef);
 79749      assert( (p->flags & MEM_Agg)==0 );
 79750      testcase( p->flags & MEM_Dyn );
 79751    }
 79752    if( p->flags&MEM_Dyn ){
 79753      assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
 79754      p->xDel((void *)p->z);
 79755    }
 79756    p->flags = MEM_Null;
 79757  }
 79758  
 79759  /*
 79760  ** Release memory held by the Mem p, both external memory cleared
 79761  ** by p->xDel and memory in p->zMalloc.
 79762  **
 79763  ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
 79764  ** the unusual case where there really is memory in p that needs
 79765  ** to be freed.
 79766  */
 79767  static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
 79768    if( VdbeMemDynamic(p) ){
 79769      vdbeMemClearExternAndSetNull(p);
 79770    }
 79771    if( p->szMalloc ){
 79772      sqlite3DbFreeNN(p->db, p->zMalloc);
 79773      p->szMalloc = 0;
 79774    }
 79775    p->z = 0;
 79776  }
 79777  
 79778  /*
 79779  ** Release any memory resources held by the Mem.  Both the memory that is
 79780  ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
 79781  **
 79782  ** Use this routine prior to clean up prior to abandoning a Mem, or to
 79783  ** reset a Mem back to its minimum memory utilization.
 79784  **
 79785  ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
 79786  ** prior to inserting new content into the Mem.
 79787  */
 79788  SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
 79789    assert( sqlite3VdbeCheckMemInvariants(p) );
 79790    if( VdbeMemDynamic(p) || p->szMalloc ){
 79791      vdbeMemClear(p);
 79792    }
 79793  }
 79794  
 79795  /*
 79796  ** Convert a 64-bit IEEE double into a 64-bit signed integer.
 79797  ** If the double is out of range of a 64-bit signed integer then
 79798  ** return the closest available 64-bit signed integer.
 79799  */
 79800  static SQLITE_NOINLINE i64 doubleToInt64(double r){
 79801  #ifdef SQLITE_OMIT_FLOATING_POINT
 79802    /* When floating-point is omitted, double and int64 are the same thing */
 79803    return r;
 79804  #else
 79805    /*
 79806    ** Many compilers we encounter do not define constants for the
 79807    ** minimum and maximum 64-bit integers, or they define them
 79808    ** inconsistently.  And many do not understand the "LL" notation.
 79809    ** So we define our own static constants here using nothing
 79810    ** larger than a 32-bit integer constant.
 79811    */
 79812    static const i64 maxInt = LARGEST_INT64;
 79813    static const i64 minInt = SMALLEST_INT64;
 79814  
 79815    if( r<=(double)minInt ){
 79816      return minInt;
 79817    }else if( r>=(double)maxInt ){
 79818      return maxInt;
 79819    }else{
 79820      return (i64)r;
 79821    }
 79822  #endif
 79823  }
 79824  
 79825  /*
 79826  ** Return some kind of integer value which is the best we can do
 79827  ** at representing the value that *pMem describes as an integer.
 79828  ** If pMem is an integer, then the value is exact.  If pMem is
 79829  ** a floating-point then the value returned is the integer part.
 79830  ** If pMem is a string or blob, then we make an attempt to convert
 79831  ** it into an integer and return that.  If pMem represents an
 79832  ** an SQL-NULL value, return 0.
 79833  **
 79834  ** If pMem represents a string value, its encoding might be changed.
 79835  */
 79836  static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
 79837    i64 value = 0;
 79838    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
 79839    return value;
 79840  }
 79841  SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
 79842    int flags;
 79843    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79844    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79845    flags = pMem->flags;
 79846    if( flags & MEM_Int ){
 79847      return pMem->u.i;
 79848    }else if( flags & MEM_Real ){
 79849      return doubleToInt64(pMem->u.r);
 79850    }else if( flags & (MEM_Str|MEM_Blob) ){
 79851      assert( pMem->z || pMem->n==0 );
 79852      return memIntValue(pMem);
 79853    }else{
 79854      return 0;
 79855    }
 79856  }
 79857  
 79858  /*
 79859  ** Return the best representation of pMem that we can get into a
 79860  ** double.  If pMem is already a double or an integer, return its
 79861  ** value.  If it is a string or blob, try to convert it to a double.
 79862  ** If it is a NULL, return 0.0.
 79863  */
 79864  static SQLITE_NOINLINE double memRealValue(Mem *pMem){
 79865    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 79866    double val = (double)0;
 79867    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
 79868    return val;
 79869  }
 79870  SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
 79871    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79872    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79873    if( pMem->flags & MEM_Real ){
 79874      return pMem->u.r;
 79875    }else if( pMem->flags & MEM_Int ){
 79876      return (double)pMem->u.i;
 79877    }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
 79878      return memRealValue(pMem);
 79879    }else{
 79880      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 79881      return (double)0;
 79882    }
 79883  }
 79884  
 79885  /*
 79886  ** Return 1 if pMem represents true, and return 0 if pMem represents false.
 79887  ** Return the value ifNull if pMem is NULL.  
 79888  */
 79889  SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
 79890    if( pMem->flags & MEM_Int ) return pMem->u.i!=0;
 79891    if( pMem->flags & MEM_Null ) return ifNull;
 79892    return sqlite3VdbeRealValue(pMem)!=0.0;
 79893  }
 79894  
 79895  /*
 79896  ** The MEM structure is already a MEM_Real.  Try to also make it a
 79897  ** MEM_Int if we can.
 79898  */
 79899  SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
 79900    i64 ix;
 79901    assert( pMem->flags & MEM_Real );
 79902    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79903    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79904    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79905  
 79906    ix = doubleToInt64(pMem->u.r);
 79907  
 79908    /* Only mark the value as an integer if
 79909    **
 79910    **    (1) the round-trip conversion real->int->real is a no-op, and
 79911    **    (2) The integer is neither the largest nor the smallest
 79912    **        possible integer (ticket #3922)
 79913    **
 79914    ** The second and third terms in the following conditional enforces
 79915    ** the second condition under the assumption that addition overflow causes
 79916    ** values to wrap around.
 79917    */
 79918    if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
 79919      pMem->u.i = ix;
 79920      MemSetTypeFlag(pMem, MEM_Int);
 79921    }
 79922  }
 79923  
 79924  /*
 79925  ** Convert pMem to type integer.  Invalidate any prior representations.
 79926  */
 79927  SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
 79928    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79929    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 79930    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79931  
 79932    pMem->u.i = sqlite3VdbeIntValue(pMem);
 79933    MemSetTypeFlag(pMem, MEM_Int);
 79934    return SQLITE_OK;
 79935  }
 79936  
 79937  /*
 79938  ** Convert pMem so that it is of type MEM_Real.
 79939  ** Invalidate any prior representations.
 79940  */
 79941  SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
 79942    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79943    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 79944  
 79945    pMem->u.r = sqlite3VdbeRealValue(pMem);
 79946    MemSetTypeFlag(pMem, MEM_Real);
 79947    return SQLITE_OK;
 79948  }
 79949  
 79950  /* Compare a floating point value to an integer.  Return true if the two
 79951  ** values are the same within the precision of the floating point value.
 79952  **
 79953  ** For some versions of GCC on 32-bit machines, if you do the more obvious
 79954  ** comparison of "r1==(double)i" you sometimes get an answer of false even
 79955  ** though the r1 and (double)i values are bit-for-bit the same.
 79956  */
 79957  static int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
 79958    double r2 = (double)i;
 79959    return memcmp(&r1, &r2, sizeof(r1))==0;
 79960  }
 79961  
 79962  /*
 79963  ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
 79964  ** Invalidate any prior representations.
 79965  **
 79966  ** Every effort is made to force the conversion, even if the input
 79967  ** is a string that does not look completely like a number.  Convert
 79968  ** as much of the string as we can and ignore the rest.
 79969  */
 79970  SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
 79971    if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
 79972      int rc;
 79973      assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
 79974      assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 79975      rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
 79976      if( rc==0 ){
 79977        MemSetTypeFlag(pMem, MEM_Int);
 79978      }else{
 79979        i64 i = pMem->u.i;
 79980        sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
 79981        if( rc==1 && sqlite3RealSameAsInt(pMem->u.r, i) ){
 79982          pMem->u.i = i;
 79983          MemSetTypeFlag(pMem, MEM_Int);
 79984        }else{
 79985          MemSetTypeFlag(pMem, MEM_Real);
 79986        }
 79987      }
 79988    }
 79989    assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
 79990    pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
 79991    return SQLITE_OK;
 79992  }
 79993  
 79994  /*
 79995  ** Cast the datatype of the value in pMem according to the affinity
 79996  ** "aff".  Casting is different from applying affinity in that a cast
 79997  ** is forced.  In other words, the value is converted into the desired
 79998  ** affinity even if that results in loss of data.  This routine is
 79999  ** used (for example) to implement the SQL "cast()" operator.
 80000  */
 80001  SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
 80002    if( pMem->flags & MEM_Null ) return;
 80003    switch( aff ){
 80004      case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
 80005        if( (pMem->flags & MEM_Blob)==0 ){
 80006          sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
 80007          assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
 80008          if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
 80009        }else{
 80010          pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
 80011        }
 80012        break;
 80013      }
 80014      case SQLITE_AFF_NUMERIC: {
 80015        sqlite3VdbeMemNumerify(pMem);
 80016        break;
 80017      }
 80018      case SQLITE_AFF_INTEGER: {
 80019        sqlite3VdbeMemIntegerify(pMem);
 80020        break;
 80021      }
 80022      case SQLITE_AFF_REAL: {
 80023        sqlite3VdbeMemRealify(pMem);
 80024        break;
 80025      }
 80026      default: {
 80027        assert( aff==SQLITE_AFF_TEXT );
 80028        assert( MEM_Str==(MEM_Blob>>3) );
 80029        pMem->flags |= (pMem->flags&MEM_Blob)>>3;
 80030        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
 80031        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
 80032        pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
 80033        break;
 80034      }
 80035    }
 80036  }
 80037  
 80038  /*
 80039  ** Initialize bulk memory to be a consistent Mem object.
 80040  **
 80041  ** The minimum amount of initialization feasible is performed.
 80042  */
 80043  SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
 80044    assert( (flags & ~MEM_TypeMask)==0 );
 80045    pMem->flags = flags;
 80046    pMem->db = db;
 80047    pMem->szMalloc = 0;
 80048  }
 80049  
 80050  
 80051  /*
 80052  ** Delete any previous value and set the value stored in *pMem to NULL.
 80053  **
 80054  ** This routine calls the Mem.xDel destructor to dispose of values that
 80055  ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
 80056  ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
 80057  ** routine to invoke the destructor and deallocates Mem.zMalloc.
 80058  **
 80059  ** Use this routine to reset the Mem prior to insert a new value.
 80060  **
 80061  ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
 80062  */
 80063  SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
 80064    if( VdbeMemDynamic(pMem) ){
 80065      vdbeMemClearExternAndSetNull(pMem);
 80066    }else{
 80067      pMem->flags = MEM_Null;
 80068    }
 80069  }
 80070  SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
 80071    sqlite3VdbeMemSetNull((Mem*)p); 
 80072  }
 80073  
 80074  /*
 80075  ** Delete any previous value and set the value to be a BLOB of length
 80076  ** n containing all zeros.
 80077  */
 80078  SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
 80079    sqlite3VdbeMemRelease(pMem);
 80080    pMem->flags = MEM_Blob|MEM_Zero;
 80081    pMem->n = 0;
 80082    if( n<0 ) n = 0;
 80083    pMem->u.nZero = n;
 80084    pMem->enc = SQLITE_UTF8;
 80085    pMem->z = 0;
 80086  }
 80087  
 80088  /*
 80089  ** The pMem is known to contain content that needs to be destroyed prior
 80090  ** to a value change.  So invoke the destructor, then set the value to
 80091  ** a 64-bit integer.
 80092  */
 80093  static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
 80094    sqlite3VdbeMemSetNull(pMem);
 80095    pMem->u.i = val;
 80096    pMem->flags = MEM_Int;
 80097  }
 80098  
 80099  /*
 80100  ** Delete any previous value and set the value stored in *pMem to val,
 80101  ** manifest type INTEGER.
 80102  */
 80103  SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
 80104    if( VdbeMemDynamic(pMem) ){
 80105      vdbeReleaseAndSetInt64(pMem, val);
 80106    }else{
 80107      pMem->u.i = val;
 80108      pMem->flags = MEM_Int;
 80109    }
 80110  }
 80111  
 80112  /* A no-op destructor */
 80113  SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
 80114  
 80115  /*
 80116  ** Set the value stored in *pMem should already be a NULL.
 80117  ** Also store a pointer to go with it.
 80118  */
 80119  SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
 80120    Mem *pMem,
 80121    void *pPtr,
 80122    const char *zPType,
 80123    void (*xDestructor)(void*)
 80124  ){
 80125    assert( pMem->flags==MEM_Null );
 80126    pMem->u.zPType = zPType ? zPType : "";
 80127    pMem->z = pPtr;
 80128    pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
 80129    pMem->eSubtype = 'p';
 80130    pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
 80131  }
 80132  
 80133  #ifndef SQLITE_OMIT_FLOATING_POINT
 80134  /*
 80135  ** Delete any previous value and set the value stored in *pMem to val,
 80136  ** manifest type REAL.
 80137  */
 80138  SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
 80139    sqlite3VdbeMemSetNull(pMem);
 80140    if( !sqlite3IsNaN(val) ){
 80141      pMem->u.r = val;
 80142      pMem->flags = MEM_Real;
 80143    }
 80144  }
 80145  #endif
 80146  
 80147  #ifdef SQLITE_DEBUG
 80148  /*
 80149  ** Return true if the Mem holds a RowSet object.  This routine is intended
 80150  ** for use inside of assert() statements.
 80151  */
 80152  SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
 80153    return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
 80154           && pMem->xDel==sqlite3RowSetDelete;
 80155  }
 80156  #endif
 80157  
 80158  /*
 80159  ** Delete any previous value and set the value of pMem to be an
 80160  ** empty boolean index.
 80161  **
 80162  ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
 80163  ** error occurs.
 80164  */
 80165  SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
 80166    sqlite3 *db = pMem->db;
 80167    RowSet *p;
 80168    assert( db!=0 );
 80169    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 80170    sqlite3VdbeMemRelease(pMem);
 80171    p = sqlite3RowSetInit(db);
 80172    if( p==0 ) return SQLITE_NOMEM;
 80173    pMem->z = (char*)p;
 80174    pMem->flags = MEM_Blob|MEM_Dyn;
 80175    pMem->xDel = sqlite3RowSetDelete;
 80176    return SQLITE_OK;
 80177  }
 80178  
 80179  /*
 80180  ** Return true if the Mem object contains a TEXT or BLOB that is
 80181  ** too large - whose size exceeds SQLITE_MAX_LENGTH.
 80182  */
 80183  SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
 80184    assert( p->db!=0 );
 80185    if( p->flags & (MEM_Str|MEM_Blob) ){
 80186      int n = p->n;
 80187      if( p->flags & MEM_Zero ){
 80188        n += p->u.nZero;
 80189      }
 80190      return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
 80191    }
 80192    return 0; 
 80193  }
 80194  
 80195  #ifdef SQLITE_DEBUG
 80196  /*
 80197  ** This routine prepares a memory cell for modification by breaking
 80198  ** its link to a shallow copy and by marking any current shallow
 80199  ** copies of this cell as invalid.
 80200  **
 80201  ** This is used for testing and debugging only - to make sure shallow
 80202  ** copies are not misused.
 80203  */
 80204  SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
 80205    int i;
 80206    Mem *pX;
 80207    for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
 80208      if( pX->pScopyFrom==pMem ){
 80209        /* If pX is marked as a shallow copy of pMem, then verify that
 80210        ** no significant changes have been made to pX since the OP_SCopy.
 80211        ** A significant change would indicated a missed call to this
 80212        ** function for pX.  Minor changes, such as adding or removing a
 80213        ** dual type, are allowed, as long as the underlying value is the
 80214        ** same. */
 80215        u16 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
 80216        assert( (mFlags&MEM_Int)==0 || pMem->u.i==pX->u.i );
 80217        assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r );
 80218        assert( (mFlags&MEM_Str)==0  || (pMem->n==pX->n && pMem->z==pX->z) );
 80219        assert( (mFlags&MEM_Blob)==0  || sqlite3BlobCompare(pMem,pX)==0 );
 80220        
 80221        /* pMem is the register that is changing.  But also mark pX as
 80222        ** undefined so that we can quickly detect the shallow-copy error */
 80223        pX->flags = MEM_Undefined;
 80224        pX->pScopyFrom = 0;
 80225      }
 80226    }
 80227    pMem->pScopyFrom = 0;
 80228  }
 80229  #endif /* SQLITE_DEBUG */
 80230  
 80231  
 80232  /*
 80233  ** Make an shallow copy of pFrom into pTo.  Prior contents of
 80234  ** pTo are freed.  The pFrom->z field is not duplicated.  If
 80235  ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
 80236  ** and flags gets srcType (either MEM_Ephem or MEM_Static).
 80237  */
 80238  static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
 80239    vdbeMemClearExternAndSetNull(pTo);
 80240    assert( !VdbeMemDynamic(pTo) );
 80241    sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
 80242  }
 80243  SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
 80244    assert( !sqlite3VdbeMemIsRowSet(pFrom) );
 80245    assert( pTo->db==pFrom->db );
 80246    if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
 80247    memcpy(pTo, pFrom, MEMCELLSIZE);
 80248    if( (pFrom->flags&MEM_Static)==0 ){
 80249      pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
 80250      assert( srcType==MEM_Ephem || srcType==MEM_Static );
 80251      pTo->flags |= srcType;
 80252    }
 80253  }
 80254  
 80255  /*
 80256  ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
 80257  ** freed before the copy is made.
 80258  */
 80259  SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
 80260    int rc = SQLITE_OK;
 80261  
 80262    assert( !sqlite3VdbeMemIsRowSet(pFrom) );
 80263    if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
 80264    memcpy(pTo, pFrom, MEMCELLSIZE);
 80265    pTo->flags &= ~MEM_Dyn;
 80266    if( pTo->flags&(MEM_Str|MEM_Blob) ){
 80267      if( 0==(pFrom->flags&MEM_Static) ){
 80268        pTo->flags |= MEM_Ephem;
 80269        rc = sqlite3VdbeMemMakeWriteable(pTo);
 80270      }
 80271    }
 80272  
 80273    return rc;
 80274  }
 80275  
 80276  /*
 80277  ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
 80278  ** freed. If pFrom contains ephemeral data, a copy is made.
 80279  **
 80280  ** pFrom contains an SQL NULL when this routine returns.
 80281  */
 80282  SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
 80283    assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
 80284    assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
 80285    assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
 80286  
 80287    sqlite3VdbeMemRelease(pTo);
 80288    memcpy(pTo, pFrom, sizeof(Mem));
 80289    pFrom->flags = MEM_Null;
 80290    pFrom->szMalloc = 0;
 80291  }
 80292  
 80293  /*
 80294  ** Change the value of a Mem to be a string or a BLOB.
 80295  **
 80296  ** The memory management strategy depends on the value of the xDel
 80297  ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
 80298  ** string is copied into a (possibly existing) buffer managed by the 
 80299  ** Mem structure. Otherwise, any existing buffer is freed and the
 80300  ** pointer copied.
 80301  **
 80302  ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
 80303  ** size limit) then no memory allocation occurs.  If the string can be
 80304  ** stored without allocating memory, then it is.  If a memory allocation
 80305  ** is required to store the string, then value of pMem is unchanged.  In
 80306  ** either case, SQLITE_TOOBIG is returned.
 80307  */
 80308  SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 80309    Mem *pMem,          /* Memory cell to set to string value */
 80310    const char *z,      /* String pointer */
 80311    int n,              /* Bytes in string, or negative */
 80312    u8 enc,             /* Encoding of z.  0 for BLOBs */
 80313    void (*xDel)(void*) /* Destructor function */
 80314  ){
 80315    int nByte = n;      /* New value for pMem->n */
 80316    int iLimit;         /* Maximum allowed string or blob size */
 80317    u16 flags = 0;      /* New value for pMem->flags */
 80318  
 80319    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
 80320    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 80321  
 80322    /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
 80323    if( !z ){
 80324      sqlite3VdbeMemSetNull(pMem);
 80325      return SQLITE_OK;
 80326    }
 80327  
 80328    if( pMem->db ){
 80329      iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
 80330    }else{
 80331      iLimit = SQLITE_MAX_LENGTH;
 80332    }
 80333    flags = (enc==0?MEM_Blob:MEM_Str);
 80334    if( nByte<0 ){
 80335      assert( enc!=0 );
 80336      if( enc==SQLITE_UTF8 ){
 80337        nByte = 0x7fffffff & (int)strlen(z);
 80338        if( nByte>iLimit ) nByte = iLimit+1;
 80339      }else{
 80340        for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
 80341      }
 80342      flags |= MEM_Term;
 80343    }
 80344  
 80345    /* The following block sets the new values of Mem.z and Mem.xDel. It
 80346    ** also sets a flag in local variable "flags" to indicate the memory
 80347    ** management (one of MEM_Dyn or MEM_Static).
 80348    */
 80349    if( xDel==SQLITE_TRANSIENT ){
 80350      int nAlloc = nByte;
 80351      if( flags&MEM_Term ){
 80352        nAlloc += (enc==SQLITE_UTF8?1:2);
 80353      }
 80354      if( nByte>iLimit ){
 80355        return SQLITE_TOOBIG;
 80356      }
 80357      testcase( nAlloc==0 );
 80358      testcase( nAlloc==31 );
 80359      testcase( nAlloc==32 );
 80360      if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
 80361        return SQLITE_NOMEM_BKPT;
 80362      }
 80363      memcpy(pMem->z, z, nAlloc);
 80364    }else if( xDel==SQLITE_DYNAMIC ){
 80365      sqlite3VdbeMemRelease(pMem);
 80366      pMem->zMalloc = pMem->z = (char *)z;
 80367      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
 80368    }else{
 80369      sqlite3VdbeMemRelease(pMem);
 80370      pMem->z = (char *)z;
 80371      pMem->xDel = xDel;
 80372      flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
 80373    }
 80374  
 80375    pMem->n = nByte;
 80376    pMem->flags = flags;
 80377    pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
 80378  
 80379  #ifndef SQLITE_OMIT_UTF16
 80380    if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
 80381      return SQLITE_NOMEM_BKPT;
 80382    }
 80383  #endif
 80384  
 80385    if( nByte>iLimit ){
 80386      return SQLITE_TOOBIG;
 80387    }
 80388  
 80389    return SQLITE_OK;
 80390  }
 80391  
 80392  /*
 80393  ** Move data out of a btree key or data field and into a Mem structure.
 80394  ** The data is payload from the entry that pCur is currently pointing
 80395  ** to.  offset and amt determine what portion of the data or key to retrieve.
 80396  ** The result is written into the pMem element.
 80397  **
 80398  ** The pMem object must have been initialized.  This routine will use
 80399  ** pMem->zMalloc to hold the content from the btree, if possible.  New
 80400  ** pMem->zMalloc space will be allocated if necessary.  The calling routine
 80401  ** is responsible for making sure that the pMem object is eventually
 80402  ** destroyed.
 80403  **
 80404  ** If this routine fails for any reason (malloc returns NULL or unable
 80405  ** to read from the disk) then the pMem is left in an inconsistent state.
 80406  */
 80407  static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
 80408    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
 80409    u32 offset,       /* Offset from the start of data to return bytes from. */
 80410    u32 amt,          /* Number of bytes to return. */
 80411    Mem *pMem         /* OUT: Return data in this Mem structure. */
 80412  ){
 80413    int rc;
 80414    pMem->flags = MEM_Null;
 80415    if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
 80416      return SQLITE_CORRUPT_BKPT;
 80417    }
 80418    if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
 80419      rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
 80420      if( rc==SQLITE_OK ){
 80421        pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
 80422        pMem->flags = MEM_Blob;
 80423        pMem->n = (int)amt;
 80424      }else{
 80425        sqlite3VdbeMemRelease(pMem);
 80426      }
 80427    }
 80428    return rc;
 80429  }
 80430  SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
 80431    BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
 80432    u32 offset,       /* Offset from the start of data to return bytes from. */
 80433    u32 amt,          /* Number of bytes to return. */
 80434    Mem *pMem         /* OUT: Return data in this Mem structure. */
 80435  ){
 80436    char *zData;        /* Data from the btree layer */
 80437    u32 available = 0;  /* Number of bytes available on the local btree page */
 80438    int rc = SQLITE_OK; /* Return code */
 80439  
 80440    assert( sqlite3BtreeCursorIsValid(pCur) );
 80441    assert( !VdbeMemDynamic(pMem) );
 80442  
 80443    /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
 80444    ** that both the BtShared and database handle mutexes are held. */
 80445    assert( !sqlite3VdbeMemIsRowSet(pMem) );
 80446    zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
 80447    assert( zData!=0 );
 80448  
 80449    if( offset+amt<=available ){
 80450      pMem->z = &zData[offset];
 80451      pMem->flags = MEM_Blob|MEM_Ephem;
 80452      pMem->n = (int)amt;
 80453    }else{
 80454      rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
 80455    }
 80456  
 80457    return rc;
 80458  }
 80459  
 80460  /*
 80461  ** The pVal argument is known to be a value other than NULL.
 80462  ** Convert it into a string with encoding enc and return a pointer
 80463  ** to a zero-terminated version of that string.
 80464  */
 80465  static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
 80466    assert( pVal!=0 );
 80467    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
 80468    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
 80469    assert( !sqlite3VdbeMemIsRowSet(pVal) );
 80470    assert( (pVal->flags & (MEM_Null))==0 );
 80471    if( pVal->flags & (MEM_Blob|MEM_Str) ){
 80472      if( ExpandBlob(pVal) ) return 0;
 80473      pVal->flags |= MEM_Str;
 80474      if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
 80475        sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
 80476      }
 80477      if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
 80478        assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
 80479        if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
 80480          return 0;
 80481        }
 80482      }
 80483      sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
 80484    }else{
 80485      sqlite3VdbeMemStringify(pVal, enc, 0);
 80486      assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
 80487    }
 80488    assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
 80489                || pVal->db->mallocFailed );
 80490    if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
 80491      assert( sqlite3VdbeMemConsistentDualRep(pVal) );
 80492      return pVal->z;
 80493    }else{
 80494      return 0;
 80495    }
 80496  }
 80497  
 80498  /* This function is only available internally, it is not part of the
 80499  ** external API. It works in a similar way to sqlite3_value_text(),
 80500  ** except the data returned is in the encoding specified by the second
 80501  ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
 80502  ** SQLITE_UTF8.
 80503  **
 80504  ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
 80505  ** If that is the case, then the result must be aligned on an even byte
 80506  ** boundary.
 80507  */
 80508  SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
 80509    if( !pVal ) return 0;
 80510    assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
 80511    assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
 80512    assert( !sqlite3VdbeMemIsRowSet(pVal) );
 80513    if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
 80514      assert( sqlite3VdbeMemConsistentDualRep(pVal) );
 80515      return pVal->z;
 80516    }
 80517    if( pVal->flags&MEM_Null ){
 80518      return 0;
 80519    }
 80520    return valueToText(pVal, enc);
 80521  }
 80522  
 80523  /*
 80524  ** Create a new sqlite3_value object.
 80525  */
 80526  SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
 80527    Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
 80528    if( p ){
 80529      p->flags = MEM_Null;
 80530      p->db = db;
 80531    }
 80532    return p;
 80533  }
 80534  
 80535  /*
 80536  ** Context object passed by sqlite3Stat4ProbeSetValue() through to 
 80537  ** valueNew(). See comments above valueNew() for details.
 80538  */
 80539  struct ValueNewStat4Ctx {
 80540    Parse *pParse;
 80541    Index *pIdx;
 80542    UnpackedRecord **ppRec;
 80543    int iVal;
 80544  };
 80545  
 80546  /*
 80547  ** Allocate and return a pointer to a new sqlite3_value object. If
 80548  ** the second argument to this function is NULL, the object is allocated
 80549  ** by calling sqlite3ValueNew().
 80550  **
 80551  ** Otherwise, if the second argument is non-zero, then this function is 
 80552  ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
 80553  ** already been allocated, allocate the UnpackedRecord structure that 
 80554  ** that function will return to its caller here. Then return a pointer to
 80555  ** an sqlite3_value within the UnpackedRecord.a[] array.
 80556  */
 80557  static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
 80558  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80559    if( p ){
 80560      UnpackedRecord *pRec = p->ppRec[0];
 80561  
 80562      if( pRec==0 ){
 80563        Index *pIdx = p->pIdx;      /* Index being probed */
 80564        int nByte;                  /* Bytes of space to allocate */
 80565        int i;                      /* Counter variable */
 80566        int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
 80567    
 80568        nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
 80569        pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
 80570        if( pRec ){
 80571          pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
 80572          if( pRec->pKeyInfo ){
 80573            assert( pRec->pKeyInfo->nAllField==nCol );
 80574            assert( pRec->pKeyInfo->enc==ENC(db) );
 80575            pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
 80576            for(i=0; i<nCol; i++){
 80577              pRec->aMem[i].flags = MEM_Null;
 80578              pRec->aMem[i].db = db;
 80579            }
 80580          }else{
 80581            sqlite3DbFreeNN(db, pRec);
 80582            pRec = 0;
 80583          }
 80584        }
 80585        if( pRec==0 ) return 0;
 80586        p->ppRec[0] = pRec;
 80587      }
 80588    
 80589      pRec->nField = p->iVal+1;
 80590      return &pRec->aMem[p->iVal];
 80591    }
 80592  #else
 80593    UNUSED_PARAMETER(p);
 80594  #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 80595    return sqlite3ValueNew(db);
 80596  }
 80597  
 80598  /*
 80599  ** The expression object indicated by the second argument is guaranteed
 80600  ** to be a scalar SQL function. If
 80601  **
 80602  **   * all function arguments are SQL literals,
 80603  **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
 80604  **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
 80605  **
 80606  ** then this routine attempts to invoke the SQL function. Assuming no
 80607  ** error occurs, output parameter (*ppVal) is set to point to a value 
 80608  ** object containing the result before returning SQLITE_OK.
 80609  **
 80610  ** Affinity aff is applied to the result of the function before returning.
 80611  ** If the result is a text value, the sqlite3_value object uses encoding 
 80612  ** enc.
 80613  **
 80614  ** If the conditions above are not met, this function returns SQLITE_OK
 80615  ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
 80616  ** NULL and an SQLite error code returned.
 80617  */
 80618  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80619  static int valueFromFunction(
 80620    sqlite3 *db,                    /* The database connection */
 80621    Expr *p,                        /* The expression to evaluate */
 80622    u8 enc,                         /* Encoding to use */
 80623    u8 aff,                         /* Affinity to use */
 80624    sqlite3_value **ppVal,          /* Write the new value here */
 80625    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
 80626  ){
 80627    sqlite3_context ctx;            /* Context object for function invocation */
 80628    sqlite3_value **apVal = 0;      /* Function arguments */
 80629    int nVal = 0;                   /* Size of apVal[] array */
 80630    FuncDef *pFunc = 0;             /* Function definition */
 80631    sqlite3_value *pVal = 0;        /* New value */
 80632    int rc = SQLITE_OK;             /* Return code */
 80633    ExprList *pList = 0;            /* Function arguments */
 80634    int i;                          /* Iterator variable */
 80635  
 80636    assert( pCtx!=0 );
 80637    assert( (p->flags & EP_TokenOnly)==0 );
 80638    pList = p->x.pList;
 80639    if( pList ) nVal = pList->nExpr;
 80640    pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
 80641    assert( pFunc );
 80642    if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 
 80643     || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
 80644    ){
 80645      return SQLITE_OK;
 80646    }
 80647  
 80648    if( pList ){
 80649      apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
 80650      if( apVal==0 ){
 80651        rc = SQLITE_NOMEM_BKPT;
 80652        goto value_from_function_out;
 80653      }
 80654      for(i=0; i<nVal; i++){
 80655        rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
 80656        if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
 80657      }
 80658    }
 80659  
 80660    pVal = valueNew(db, pCtx);
 80661    if( pVal==0 ){
 80662      rc = SQLITE_NOMEM_BKPT;
 80663      goto value_from_function_out;
 80664    }
 80665  
 80666    assert( pCtx->pParse->rc==SQLITE_OK );
 80667    memset(&ctx, 0, sizeof(ctx));
 80668    ctx.pOut = pVal;
 80669    ctx.pFunc = pFunc;
 80670    pFunc->xSFunc(&ctx, nVal, apVal);
 80671    if( ctx.isError ){
 80672      rc = ctx.isError;
 80673      sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
 80674    }else{
 80675      sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
 80676      assert( rc==SQLITE_OK );
 80677      rc = sqlite3VdbeChangeEncoding(pVal, enc);
 80678      if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
 80679        rc = SQLITE_TOOBIG;
 80680        pCtx->pParse->nErr++;
 80681      }
 80682    }
 80683    pCtx->pParse->rc = rc;
 80684  
 80685   value_from_function_out:
 80686    if( rc!=SQLITE_OK ){
 80687      pVal = 0;
 80688    }
 80689    if( apVal ){
 80690      for(i=0; i<nVal; i++){
 80691        sqlite3ValueFree(apVal[i]);
 80692      }
 80693      sqlite3DbFreeNN(db, apVal);
 80694    }
 80695  
 80696    *ppVal = pVal;
 80697    return rc;
 80698  }
 80699  #else
 80700  # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
 80701  #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 80702  
 80703  /*
 80704  ** Extract a value from the supplied expression in the manner described
 80705  ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
 80706  ** using valueNew().
 80707  **
 80708  ** If pCtx is NULL and an error occurs after the sqlite3_value object
 80709  ** has been allocated, it is freed before returning. Or, if pCtx is not
 80710  ** NULL, it is assumed that the caller will free any allocated object
 80711  ** in all cases.
 80712  */
 80713  static int valueFromExpr(
 80714    sqlite3 *db,                    /* The database connection */
 80715    Expr *pExpr,                    /* The expression to evaluate */
 80716    u8 enc,                         /* Encoding to use */
 80717    u8 affinity,                    /* Affinity to use */
 80718    sqlite3_value **ppVal,          /* Write the new value here */
 80719    struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
 80720  ){
 80721    int op;
 80722    char *zVal = 0;
 80723    sqlite3_value *pVal = 0;
 80724    int negInt = 1;
 80725    const char *zNeg = "";
 80726    int rc = SQLITE_OK;
 80727  
 80728    assert( pExpr!=0 );
 80729    while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
 80730  #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
 80731    if( op==TK_REGISTER ) op = pExpr->op2;
 80732  #else
 80733    if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
 80734  #endif
 80735  
 80736    /* Compressed expressions only appear when parsing the DEFAULT clause
 80737    ** on a table column definition, and hence only when pCtx==0.  This
 80738    ** check ensures that an EP_TokenOnly expression is never passed down
 80739    ** into valueFromFunction(). */
 80740    assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
 80741  
 80742    if( op==TK_CAST ){
 80743      u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
 80744      rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
 80745      testcase( rc!=SQLITE_OK );
 80746      if( *ppVal ){
 80747        sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
 80748        sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
 80749      }
 80750      return rc;
 80751    }
 80752  
 80753    /* Handle negative integers in a single step.  This is needed in the
 80754    ** case when the value is -9223372036854775808.
 80755    */
 80756    if( op==TK_UMINUS
 80757     && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
 80758      pExpr = pExpr->pLeft;
 80759      op = pExpr->op;
 80760      negInt = -1;
 80761      zNeg = "-";
 80762    }
 80763  
 80764    if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
 80765      pVal = valueNew(db, pCtx);
 80766      if( pVal==0 ) goto no_mem;
 80767      if( ExprHasProperty(pExpr, EP_IntValue) ){
 80768        sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
 80769      }else{
 80770        zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
 80771        if( zVal==0 ) goto no_mem;
 80772        sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
 80773      }
 80774      if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
 80775        sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
 80776      }else{
 80777        sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
 80778      }
 80779      if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
 80780      if( enc!=SQLITE_UTF8 ){
 80781        rc = sqlite3VdbeChangeEncoding(pVal, enc);
 80782      }
 80783    }else if( op==TK_UMINUS ) {
 80784      /* This branch happens for multiple negative signs.  Ex: -(-5) */
 80785      if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) 
 80786       && pVal!=0
 80787      ){
 80788        sqlite3VdbeMemNumerify(pVal);
 80789        if( pVal->flags & MEM_Real ){
 80790          pVal->u.r = -pVal->u.r;
 80791        }else if( pVal->u.i==SMALLEST_INT64 ){
 80792          pVal->u.r = -(double)SMALLEST_INT64;
 80793          MemSetTypeFlag(pVal, MEM_Real);
 80794        }else{
 80795          pVal->u.i = -pVal->u.i;
 80796        }
 80797        sqlite3ValueApplyAffinity(pVal, affinity, enc);
 80798      }
 80799    }else if( op==TK_NULL ){
 80800      pVal = valueNew(db, pCtx);
 80801      if( pVal==0 ) goto no_mem;
 80802      sqlite3VdbeMemNumerify(pVal);
 80803    }
 80804  #ifndef SQLITE_OMIT_BLOB_LITERAL
 80805    else if( op==TK_BLOB ){
 80806      int nVal;
 80807      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
 80808      assert( pExpr->u.zToken[1]=='\'' );
 80809      pVal = valueNew(db, pCtx);
 80810      if( !pVal ) goto no_mem;
 80811      zVal = &pExpr->u.zToken[2];
 80812      nVal = sqlite3Strlen30(zVal)-1;
 80813      assert( zVal[nVal]=='\'' );
 80814      sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
 80815                           0, SQLITE_DYNAMIC);
 80816    }
 80817  #endif
 80818  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80819    else if( op==TK_FUNCTION && pCtx!=0 ){
 80820      rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
 80821    }
 80822  #endif
 80823    else if( op==TK_TRUEFALSE ){
 80824      pVal = valueNew(db, pCtx);
 80825      if( pVal ){
 80826        pVal->flags = MEM_Int;
 80827        pVal->u.i = pExpr->u.zToken[4]==0;
 80828      }
 80829    }
 80830  
 80831    *ppVal = pVal;
 80832    return rc;
 80833  
 80834  no_mem:
 80835  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80836    if( pCtx==0 || pCtx->pParse->nErr==0 )
 80837  #endif
 80838      sqlite3OomFault(db);
 80839    sqlite3DbFree(db, zVal);
 80840    assert( *ppVal==0 );
 80841  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80842    if( pCtx==0 ) sqlite3ValueFree(pVal);
 80843  #else
 80844    assert( pCtx==0 ); sqlite3ValueFree(pVal);
 80845  #endif
 80846    return SQLITE_NOMEM_BKPT;
 80847  }
 80848  
 80849  /*
 80850  ** Create a new sqlite3_value object, containing the value of pExpr.
 80851  **
 80852  ** This only works for very simple expressions that consist of one constant
 80853  ** token (i.e. "5", "5.1", "'a string'"). If the expression can
 80854  ** be converted directly into a value, then the value is allocated and
 80855  ** a pointer written to *ppVal. The caller is responsible for deallocating
 80856  ** the value by passing it to sqlite3ValueFree() later on. If the expression
 80857  ** cannot be converted to a value, then *ppVal is set to NULL.
 80858  */
 80859  SQLITE_PRIVATE int sqlite3ValueFromExpr(
 80860    sqlite3 *db,              /* The database connection */
 80861    Expr *pExpr,              /* The expression to evaluate */
 80862    u8 enc,                   /* Encoding to use */
 80863    u8 affinity,              /* Affinity to use */
 80864    sqlite3_value **ppVal     /* Write the new value here */
 80865  ){
 80866    return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
 80867  }
 80868  
 80869  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 80870  /*
 80871  ** The implementation of the sqlite_record() function. This function accepts
 80872  ** a single argument of any type. The return value is a formatted database 
 80873  ** record (a blob) containing the argument value.
 80874  **
 80875  ** This is used to convert the value stored in the 'sample' column of the
 80876  ** sqlite_stat3 table to the record format SQLite uses internally.
 80877  */
 80878  static void recordFunc(
 80879    sqlite3_context *context,
 80880    int argc,
 80881    sqlite3_value **argv
 80882  ){
 80883    const int file_format = 1;
 80884    u32 iSerial;                    /* Serial type */
 80885    int nSerial;                    /* Bytes of space for iSerial as varint */
 80886    u32 nVal;                       /* Bytes of space required for argv[0] */
 80887    int nRet;
 80888    sqlite3 *db;
 80889    u8 *aRet;
 80890  
 80891    UNUSED_PARAMETER( argc );
 80892    iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
 80893    nSerial = sqlite3VarintLen(iSerial);
 80894    db = sqlite3_context_db_handle(context);
 80895  
 80896    nRet = 1 + nSerial + nVal;
 80897    aRet = sqlite3DbMallocRawNN(db, nRet);
 80898    if( aRet==0 ){
 80899      sqlite3_result_error_nomem(context);
 80900    }else{
 80901      aRet[0] = nSerial+1;
 80902      putVarint32(&aRet[1], iSerial);
 80903      sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
 80904      sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
 80905      sqlite3DbFreeNN(db, aRet);
 80906    }
 80907  }
 80908  
 80909  /*
 80910  ** Register built-in functions used to help read ANALYZE data.
 80911  */
 80912  SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
 80913    static FuncDef aAnalyzeTableFuncs[] = {
 80914      FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
 80915    };
 80916    sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
 80917  }
 80918  
 80919  /*
 80920  ** Attempt to extract a value from pExpr and use it to construct *ppVal.
 80921  **
 80922  ** If pAlloc is not NULL, then an UnpackedRecord object is created for
 80923  ** pAlloc if one does not exist and the new value is added to the
 80924  ** UnpackedRecord object.
 80925  **
 80926  ** A value is extracted in the following cases:
 80927  **
 80928  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
 80929  **
 80930  **  * The expression is a bound variable, and this is a reprepare, or
 80931  **
 80932  **  * The expression is a literal value.
 80933  **
 80934  ** On success, *ppVal is made to point to the extracted value.  The caller
 80935  ** is responsible for ensuring that the value is eventually freed.
 80936  */
 80937  static int stat4ValueFromExpr(
 80938    Parse *pParse,                  /* Parse context */
 80939    Expr *pExpr,                    /* The expression to extract a value from */
 80940    u8 affinity,                    /* Affinity to use */
 80941    struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
 80942    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
 80943  ){
 80944    int rc = SQLITE_OK;
 80945    sqlite3_value *pVal = 0;
 80946    sqlite3 *db = pParse->db;
 80947  
 80948    /* Skip over any TK_COLLATE nodes */
 80949    pExpr = sqlite3ExprSkipCollate(pExpr);
 80950  
 80951    assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
 80952    if( !pExpr ){
 80953      pVal = valueNew(db, pAlloc);
 80954      if( pVal ){
 80955        sqlite3VdbeMemSetNull((Mem*)pVal);
 80956      }
 80957    }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
 80958      Vdbe *v;
 80959      int iBindVar = pExpr->iColumn;
 80960      sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
 80961      if( (v = pParse->pReprepare)!=0 ){
 80962        pVal = valueNew(db, pAlloc);
 80963        if( pVal ){
 80964          rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
 80965          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
 80966          pVal->db = pParse->db;
 80967        }
 80968      }
 80969    }else{
 80970      rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
 80971    }
 80972  
 80973    assert( pVal==0 || pVal->db==db );
 80974    *ppVal = pVal;
 80975    return rc;
 80976  }
 80977  
 80978  /*
 80979  ** This function is used to allocate and populate UnpackedRecord 
 80980  ** structures intended to be compared against sample index keys stored 
 80981  ** in the sqlite_stat4 table.
 80982  **
 80983  ** A single call to this function populates zero or more fields of the
 80984  ** record starting with field iVal (fields are numbered from left to
 80985  ** right starting with 0). A single field is populated if:
 80986  **
 80987  **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
 80988  **
 80989  **  * The expression is a bound variable, and this is a reprepare, or
 80990  **
 80991  **  * The sqlite3ValueFromExpr() function is able to extract a value 
 80992  **    from the expression (i.e. the expression is a literal value).
 80993  **
 80994  ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
 80995  ** vector components that match either of the two latter criteria listed
 80996  ** above.
 80997  **
 80998  ** Before any value is appended to the record, the affinity of the 
 80999  ** corresponding column within index pIdx is applied to it. Before
 81000  ** this function returns, output parameter *pnExtract is set to the
 81001  ** number of values appended to the record.
 81002  **
 81003  ** When this function is called, *ppRec must either point to an object
 81004  ** allocated by an earlier call to this function, or must be NULL. If it
 81005  ** is NULL and a value can be successfully extracted, a new UnpackedRecord
 81006  ** is allocated (and *ppRec set to point to it) before returning.
 81007  **
 81008  ** Unless an error is encountered, SQLITE_OK is returned. It is not an
 81009  ** error if a value cannot be extracted from pExpr. If an error does
 81010  ** occur, an SQLite error code is returned.
 81011  */
 81012  SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 81013    Parse *pParse,                  /* Parse context */
 81014    Index *pIdx,                    /* Index being probed */
 81015    UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
 81016    Expr *pExpr,                    /* The expression to extract a value from */
 81017    int nElem,                      /* Maximum number of values to append */
 81018    int iVal,                       /* Array element to populate */
 81019    int *pnExtract                  /* OUT: Values appended to the record */
 81020  ){
 81021    int rc = SQLITE_OK;
 81022    int nExtract = 0;
 81023  
 81024    if( pExpr==0 || pExpr->op!=TK_SELECT ){
 81025      int i;
 81026      struct ValueNewStat4Ctx alloc;
 81027  
 81028      alloc.pParse = pParse;
 81029      alloc.pIdx = pIdx;
 81030      alloc.ppRec = ppRec;
 81031  
 81032      for(i=0; i<nElem; i++){
 81033        sqlite3_value *pVal = 0;
 81034        Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
 81035        u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
 81036        alloc.iVal = iVal+i;
 81037        rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
 81038        if( !pVal ) break;
 81039        nExtract++;
 81040      }
 81041    }
 81042  
 81043    *pnExtract = nExtract;
 81044    return rc;
 81045  }
 81046  
 81047  /*
 81048  ** Attempt to extract a value from expression pExpr using the methods
 81049  ** as described for sqlite3Stat4ProbeSetValue() above. 
 81050  **
 81051  ** If successful, set *ppVal to point to a new value object and return 
 81052  ** SQLITE_OK. If no value can be extracted, but no other error occurs
 81053  ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
 81054  ** does occur, return an SQLite error code. The final value of *ppVal
 81055  ** is undefined in this case.
 81056  */
 81057  SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
 81058    Parse *pParse,                  /* Parse context */
 81059    Expr *pExpr,                    /* The expression to extract a value from */
 81060    u8 affinity,                    /* Affinity to use */
 81061    sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
 81062  ){
 81063    return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
 81064  }
 81065  
 81066  /*
 81067  ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
 81068  ** the column value into *ppVal.  If *ppVal is initially NULL then a new
 81069  ** sqlite3_value object is allocated.
 81070  **
 81071  ** If *ppVal is initially NULL then the caller is responsible for 
 81072  ** ensuring that the value written into *ppVal is eventually freed.
 81073  */
 81074  SQLITE_PRIVATE int sqlite3Stat4Column(
 81075    sqlite3 *db,                    /* Database handle */
 81076    const void *pRec,               /* Pointer to buffer containing record */
 81077    int nRec,                       /* Size of buffer pRec in bytes */
 81078    int iCol,                       /* Column to extract */
 81079    sqlite3_value **ppVal           /* OUT: Extracted value */
 81080  ){
 81081    u32 t = 0;                      /* a column type code */
 81082    int nHdr;                       /* Size of the header in the record */
 81083    int iHdr;                       /* Next unread header byte */
 81084    int iField;                     /* Next unread data byte */
 81085    int szField = 0;                /* Size of the current data field */
 81086    int i;                          /* Column index */
 81087    u8 *a = (u8*)pRec;              /* Typecast byte array */
 81088    Mem *pMem = *ppVal;             /* Write result into this Mem object */
 81089  
 81090    assert( iCol>0 );
 81091    iHdr = getVarint32(a, nHdr);
 81092    if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
 81093    iField = nHdr;
 81094    for(i=0; i<=iCol; i++){
 81095      iHdr += getVarint32(&a[iHdr], t);
 81096      testcase( iHdr==nHdr );
 81097      testcase( iHdr==nHdr+1 );
 81098      if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
 81099      szField = sqlite3VdbeSerialTypeLen(t);
 81100      iField += szField;
 81101    }
 81102    testcase( iField==nRec );
 81103    testcase( iField==nRec+1 );
 81104    if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
 81105    if( pMem==0 ){
 81106      pMem = *ppVal = sqlite3ValueNew(db);
 81107      if( pMem==0 ) return SQLITE_NOMEM_BKPT;
 81108    }
 81109    sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
 81110    pMem->enc = ENC(db);
 81111    return SQLITE_OK;
 81112  }
 81113  
 81114  /*
 81115  ** Unless it is NULL, the argument must be an UnpackedRecord object returned
 81116  ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
 81117  ** the object.
 81118  */
 81119  SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
 81120    if( pRec ){
 81121      int i;
 81122      int nCol = pRec->pKeyInfo->nAllField;
 81123      Mem *aMem = pRec->aMem;
 81124      sqlite3 *db = aMem[0].db;
 81125      for(i=0; i<nCol; i++){
 81126        sqlite3VdbeMemRelease(&aMem[i]);
 81127      }
 81128      sqlite3KeyInfoUnref(pRec->pKeyInfo);
 81129      sqlite3DbFreeNN(db, pRec);
 81130    }
 81131  }
 81132  #endif /* ifdef SQLITE_ENABLE_STAT4 */
 81133  
 81134  /*
 81135  ** Change the string value of an sqlite3_value object
 81136  */
 81137  SQLITE_PRIVATE void sqlite3ValueSetStr(
 81138    sqlite3_value *v,     /* Value to be set */
 81139    int n,                /* Length of string z */
 81140    const void *z,        /* Text of the new string */
 81141    u8 enc,               /* Encoding to use */
 81142    void (*xDel)(void*)   /* Destructor for the string */
 81143  ){
 81144    if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
 81145  }
 81146  
 81147  /*
 81148  ** Free an sqlite3_value object
 81149  */
 81150  SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
 81151    if( !v ) return;
 81152    sqlite3VdbeMemRelease((Mem *)v);
 81153    sqlite3DbFreeNN(((Mem*)v)->db, v);
 81154  }
 81155  
 81156  /*
 81157  ** The sqlite3ValueBytes() routine returns the number of bytes in the
 81158  ** sqlite3_value object assuming that it uses the encoding "enc".
 81159  ** The valueBytes() routine is a helper function.
 81160  */
 81161  static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
 81162    return valueToText(pVal, enc)!=0 ? pVal->n : 0;
 81163  }
 81164  SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
 81165    Mem *p = (Mem*)pVal;
 81166    assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
 81167    if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
 81168      return p->n;
 81169    }
 81170    if( (p->flags & MEM_Blob)!=0 ){
 81171      if( p->flags & MEM_Zero ){
 81172        return p->n + p->u.nZero;
 81173      }else{
 81174        return p->n;
 81175      }
 81176    }
 81177    if( p->flags & MEM_Null ) return 0;
 81178    return valueBytes(pVal, enc);
 81179  }
 81180  
 81181  /************** End of vdbemem.c *********************************************/
 81182  /************** Begin file vdbeaux.c *****************************************/
 81183  /*
 81184  ** 2003 September 6
 81185  **
 81186  ** The author disclaims copyright to this source code.  In place of
 81187  ** a legal notice, here is a blessing:
 81188  **
 81189  **    May you do good and not evil.
 81190  **    May you find forgiveness for yourself and forgive others.
 81191  **    May you share freely, never taking more than you give.
 81192  **
 81193  *************************************************************************
 81194  ** This file contains code used for creating, destroying, and populating
 81195  ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) 
 81196  */
 81197  /* #include "sqliteInt.h" */
 81198  /* #include "vdbeInt.h" */
 81199  
 81200  /*
 81201  ** Create a new virtual database engine.
 81202  */
 81203  SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
 81204    sqlite3 *db = pParse->db;
 81205    Vdbe *p;
 81206    p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
 81207    if( p==0 ) return 0;
 81208    memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
 81209    p->db = db;
 81210    if( db->pVdbe ){
 81211      db->pVdbe->pPrev = p;
 81212    }
 81213    p->pNext = db->pVdbe;
 81214    p->pPrev = 0;
 81215    db->pVdbe = p;
 81216    p->magic = VDBE_MAGIC_INIT;
 81217    p->pParse = pParse;
 81218    pParse->pVdbe = p;
 81219    assert( pParse->aLabel==0 );
 81220    assert( pParse->nLabel==0 );
 81221    assert( p->nOpAlloc==0 );
 81222    assert( pParse->szOpAlloc==0 );
 81223    sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
 81224    return p;
 81225  }
 81226  
 81227  /*
 81228  ** Change the error string stored in Vdbe.zErrMsg
 81229  */
 81230  SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
 81231    va_list ap;
 81232    sqlite3DbFree(p->db, p->zErrMsg);
 81233    va_start(ap, zFormat);
 81234    p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
 81235    va_end(ap);
 81236  }
 81237  
 81238  /*
 81239  ** Remember the SQL string for a prepared statement.
 81240  */
 81241  SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
 81242    if( p==0 ) return;
 81243    p->prepFlags = prepFlags;
 81244    if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
 81245      p->expmask = 0;
 81246    }
 81247    assert( p->zSql==0 );
 81248    p->zSql = sqlite3DbStrNDup(p->db, z, n);
 81249  }
 81250  
 81251  #ifdef SQLITE_ENABLE_NORMALIZE
 81252  /*
 81253  ** Add a new element to the Vdbe->pDblStr list.
 81254  */
 81255  SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
 81256    if( p ){
 81257      int n = sqlite3Strlen30(z);
 81258      DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
 81259                              sizeof(*pStr)+n+1-sizeof(pStr->z));
 81260      if( pStr ){
 81261        pStr->pNextStr = p->pDblStr;
 81262        p->pDblStr = pStr;
 81263        memcpy(pStr->z, z, n+1);
 81264      }
 81265    }
 81266  }
 81267  #endif
 81268  
 81269  #ifdef SQLITE_ENABLE_NORMALIZE
 81270  /*
 81271  ** zId of length nId is a double-quoted identifier.  Check to see if
 81272  ** that identifier is really used as a string literal.
 81273  */
 81274  SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
 81275    Vdbe *pVdbe,            /* The prepared statement */
 81276    const char *zId         /* The double-quoted identifier, already dequoted */
 81277  ){
 81278    DblquoteStr *pStr;
 81279    assert( zId!=0 );
 81280    if( pVdbe->pDblStr==0 ) return 0;
 81281    for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
 81282      if( strcmp(zId, pStr->z)==0 ) return 1;
 81283    }
 81284    return 0;
 81285  }
 81286  #endif
 81287  
 81288  /*
 81289  ** Swap all content between two VDBE structures.
 81290  */
 81291  SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
 81292    Vdbe tmp, *pTmp;
 81293    char *zTmp;
 81294    assert( pA->db==pB->db );
 81295    tmp = *pA;
 81296    *pA = *pB;
 81297    *pB = tmp;
 81298    pTmp = pA->pNext;
 81299    pA->pNext = pB->pNext;
 81300    pB->pNext = pTmp;
 81301    pTmp = pA->pPrev;
 81302    pA->pPrev = pB->pPrev;
 81303    pB->pPrev = pTmp;
 81304    zTmp = pA->zSql;
 81305    pA->zSql = pB->zSql;
 81306    pB->zSql = zTmp;
 81307  #if 0
 81308    zTmp = pA->zNormSql;
 81309    pA->zNormSql = pB->zNormSql;
 81310    pB->zNormSql = zTmp;
 81311  #endif
 81312    pB->expmask = pA->expmask;
 81313    pB->prepFlags = pA->prepFlags;
 81314    memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
 81315    pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
 81316  }
 81317  
 81318  /*
 81319  ** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
 81320  ** than its current size. nOp is guaranteed to be less than or equal
 81321  ** to 1024/sizeof(Op).
 81322  **
 81323  ** If an out-of-memory error occurs while resizing the array, return
 81324  ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
 81325  ** unchanged (this is so that any opcodes already allocated can be 
 81326  ** correctly deallocated along with the rest of the Vdbe).
 81327  */
 81328  static int growOpArray(Vdbe *v, int nOp){
 81329    VdbeOp *pNew;
 81330    Parse *p = v->pParse;
 81331  
 81332    /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
 81333    ** more frequent reallocs and hence provide more opportunities for 
 81334    ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
 81335    ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
 81336    ** by the minimum* amount required until the size reaches 512.  Normal
 81337    ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
 81338    ** size of the op array or add 1KB of space, whichever is smaller. */
 81339  #ifdef SQLITE_TEST_REALLOC_STRESS
 81340    int nNew = (v->nOpAlloc>=512 ? v->nOpAlloc*2 : v->nOpAlloc+nOp);
 81341  #else
 81342    int nNew = (v->nOpAlloc ? v->nOpAlloc*2 : (int)(1024/sizeof(Op)));
 81343    UNUSED_PARAMETER(nOp);
 81344  #endif
 81345  
 81346    /* Ensure that the size of a VDBE does not grow too large */
 81347    if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
 81348      sqlite3OomFault(p->db);
 81349      return SQLITE_NOMEM;
 81350    }
 81351  
 81352    assert( nOp<=(1024/sizeof(Op)) );
 81353    assert( nNew>=(v->nOpAlloc+nOp) );
 81354    pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
 81355    if( pNew ){
 81356      p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
 81357      v->nOpAlloc = p->szOpAlloc/sizeof(Op);
 81358      v->aOp = pNew;
 81359    }
 81360    return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
 81361  }
 81362  
 81363  #ifdef SQLITE_DEBUG
 81364  /* This routine is just a convenient place to set a breakpoint that will
 81365  ** fire after each opcode is inserted and displayed using
 81366  ** "PRAGMA vdbe_addoptrace=on".
 81367  */
 81368  static void test_addop_breakpoint(void){
 81369    static int n = 0;
 81370    n++;
 81371  }
 81372  #endif
 81373  
 81374  /*
 81375  ** Add a new instruction to the list of instructions current in the
 81376  ** VDBE.  Return the address of the new instruction.
 81377  **
 81378  ** Parameters:
 81379  **
 81380  **    p               Pointer to the VDBE
 81381  **
 81382  **    op              The opcode for this instruction
 81383  **
 81384  **    p1, p2, p3      Operands
 81385  **
 81386  ** Use the sqlite3VdbeResolveLabel() function to fix an address and
 81387  ** the sqlite3VdbeChangeP4() function to change the value of the P4
 81388  ** operand.
 81389  */
 81390  static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
 81391    assert( p->nOpAlloc<=p->nOp );
 81392    if( growOpArray(p, 1) ) return 1;
 81393    assert( p->nOpAlloc>p->nOp );
 81394    return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 81395  }
 81396  SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
 81397    int i;
 81398    VdbeOp *pOp;
 81399  
 81400    i = p->nOp;
 81401    assert( p->magic==VDBE_MAGIC_INIT );
 81402    assert( op>=0 && op<0xff );
 81403    if( p->nOpAlloc<=i ){
 81404      return growOp3(p, op, p1, p2, p3);
 81405    }
 81406    p->nOp++;
 81407    pOp = &p->aOp[i];
 81408    pOp->opcode = (u8)op;
 81409    pOp->p5 = 0;
 81410    pOp->p1 = p1;
 81411    pOp->p2 = p2;
 81412    pOp->p3 = p3;
 81413    pOp->p4.p = 0;
 81414    pOp->p4type = P4_NOTUSED;
 81415  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 81416    pOp->zComment = 0;
 81417  #endif
 81418  #ifdef SQLITE_DEBUG
 81419    if( p->db->flags & SQLITE_VdbeAddopTrace ){
 81420      sqlite3VdbePrintOp(0, i, &p->aOp[i]);
 81421      test_addop_breakpoint();
 81422    }
 81423  #endif
 81424  #ifdef VDBE_PROFILE
 81425    pOp->cycles = 0;
 81426    pOp->cnt = 0;
 81427  #endif
 81428  #ifdef SQLITE_VDBE_COVERAGE
 81429    pOp->iSrcLine = 0;
 81430  #endif
 81431    return i;
 81432  }
 81433  SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
 81434    return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
 81435  }
 81436  SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
 81437    return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
 81438  }
 81439  SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
 81440    return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
 81441  }
 81442  
 81443  /* Generate code for an unconditional jump to instruction iDest
 81444  */
 81445  SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
 81446    return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
 81447  }
 81448  
 81449  /* Generate code to cause the string zStr to be loaded into
 81450  ** register iDest
 81451  */
 81452  SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
 81453    return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
 81454  }
 81455  
 81456  /*
 81457  ** Generate code that initializes multiple registers to string or integer
 81458  ** constants.  The registers begin with iDest and increase consecutively.
 81459  ** One register is initialized for each characgter in zTypes[].  For each
 81460  ** "s" character in zTypes[], the register is a string if the argument is
 81461  ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
 81462  ** in zTypes[], the register is initialized to an integer.
 81463  **
 81464  ** If the input string does not end with "X" then an OP_ResultRow instruction
 81465  ** is generated for the values inserted.
 81466  */
 81467  SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
 81468    va_list ap;
 81469    int i;
 81470    char c;
 81471    va_start(ap, zTypes);
 81472    for(i=0; (c = zTypes[i])!=0; i++){
 81473      if( c=='s' ){
 81474        const char *z = va_arg(ap, const char*);
 81475        sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
 81476      }else if( c=='i' ){
 81477        sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
 81478      }else if( c=='u' ){
 81479        u64 value = va_arg(ap, u64);
 81480        sqlite3VdbeAddOp4Dup8(p, OP_Int64, 0, iDest+i, 0, (const u8*)&value, P4_INT64);
 81481      }else{
 81482        goto skip_op_resultrow;
 81483      }
 81484    }
 81485    sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
 81486  skip_op_resultrow:
 81487    va_end(ap);
 81488  }
 81489  
 81490  /*
 81491  ** Add an opcode that includes the p4 value as a pointer.
 81492  */
 81493  SQLITE_PRIVATE int sqlite3VdbeAddOp4(
 81494    Vdbe *p,            /* Add the opcode to this VM */
 81495    int op,             /* The new opcode */
 81496    int p1,             /* The P1 operand */
 81497    int p2,             /* The P2 operand */
 81498    int p3,             /* The P3 operand */
 81499    const char *zP4,    /* The P4 operand */
 81500    int p4type          /* P4 operand type */
 81501  ){
 81502    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 81503    sqlite3VdbeChangeP4(p, addr, zP4, p4type);
 81504    return addr;
 81505  }
 81506  
 81507  /*
 81508  ** Add an opcode that includes the p4 value with a P4_INT64 or
 81509  ** P4_REAL type.
 81510  */
 81511  SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
 81512    Vdbe *p,            /* Add the opcode to this VM */
 81513    int op,             /* The new opcode */
 81514    int p1,             /* The P1 operand */
 81515    int p2,             /* The P2 operand */
 81516    int p3,             /* The P3 operand */
 81517    const u8 *zP4,      /* The P4 operand */
 81518    int p4type          /* P4 operand type */
 81519  ){
 81520    char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
 81521    if( p4copy ) memcpy(p4copy, zP4, 8);
 81522    return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
 81523  }
 81524  
 81525  #ifndef SQLITE_OMIT_EXPLAIN
 81526  /*
 81527  ** Return the address of the current EXPLAIN QUERY PLAN baseline.
 81528  ** 0 means "none".
 81529  */
 81530  SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
 81531    VdbeOp *pOp;
 81532    if( pParse->addrExplain==0 ) return 0;
 81533    pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
 81534    return pOp->p2;
 81535  }
 81536  
 81537  /*
 81538  ** Set a debugger breakpoint on the following routine in order to
 81539  ** monitor the EXPLAIN QUERY PLAN code generation.
 81540  */
 81541  #if defined(SQLITE_DEBUG)
 81542  SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
 81543    (void)z1;
 81544    (void)z2;
 81545  }
 81546  #endif
 81547  
 81548  /*
 81549  ** Add a new OP_ opcode.
 81550  **
 81551  ** If the bPush flag is true, then make this opcode the parent for
 81552  ** subsequent Explains until sqlite3VdbeExplainPop() is called.
 81553  */
 81554  SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
 81555  #ifndef SQLITE_DEBUG
 81556    /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
 81557    ** But omit them (for performance) during production builds */
 81558    if( pParse->explain==2 )
 81559  #endif
 81560    {
 81561      char *zMsg;
 81562      Vdbe *v;
 81563      va_list ap;
 81564      int iThis;
 81565      va_start(ap, zFmt);
 81566      zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
 81567      va_end(ap);
 81568      v = pParse->pVdbe;
 81569      iThis = v->nOp;
 81570      sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
 81571                        zMsg, P4_DYNAMIC);
 81572      sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
 81573      if( bPush){
 81574        pParse->addrExplain = iThis;
 81575      }
 81576    }
 81577  }
 81578  
 81579  /*
 81580  ** Pop the EXPLAIN QUERY PLAN stack one level.
 81581  */
 81582  SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
 81583    sqlite3ExplainBreakpoint("POP", 0);
 81584    pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
 81585  }
 81586  #endif /* SQLITE_OMIT_EXPLAIN */
 81587  
 81588  /*
 81589  ** Add an OP_ParseSchema opcode.  This routine is broken out from
 81590  ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
 81591  ** as having been used.
 81592  **
 81593  ** The zWhere string must have been obtained from sqlite3_malloc().
 81594  ** This routine will take ownership of the allocated memory.
 81595  */
 81596  SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
 81597    int j;
 81598    sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
 81599    for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
 81600  }
 81601  
 81602  /*
 81603  ** Add an opcode that includes the p4 value as an integer.
 81604  */
 81605  SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
 81606    Vdbe *p,            /* Add the opcode to this VM */
 81607    int op,             /* The new opcode */
 81608    int p1,             /* The P1 operand */
 81609    int p2,             /* The P2 operand */
 81610    int p3,             /* The P3 operand */
 81611    int p4              /* The P4 operand as an integer */
 81612  ){
 81613    int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
 81614    if( p->db->mallocFailed==0 ){
 81615      VdbeOp *pOp = &p->aOp[addr];
 81616      pOp->p4type = P4_INT32;
 81617      pOp->p4.i = p4;
 81618    }
 81619    return addr;
 81620  }
 81621  
 81622  /* Insert the end of a co-routine
 81623  */
 81624  SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
 81625    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
 81626  
 81627    /* Clear the temporary register cache, thereby ensuring that each
 81628    ** co-routine has its own independent set of registers, because co-routines
 81629    ** might expect their registers to be preserved across an OP_Yield, and
 81630    ** that could cause problems if two or more co-routines are using the same
 81631    ** temporary register.
 81632    */
 81633    v->pParse->nTempReg = 0;
 81634    v->pParse->nRangeReg = 0;
 81635  }
 81636  
 81637  /*
 81638  ** Create a new symbolic label for an instruction that has yet to be
 81639  ** coded.  The symbolic label is really just a negative number.  The
 81640  ** label can be used as the P2 value of an operation.  Later, when
 81641  ** the label is resolved to a specific address, the VDBE will scan
 81642  ** through its operation list and change all values of P2 which match
 81643  ** the label into the resolved address.
 81644  **
 81645  ** The VDBE knows that a P2 value is a label because labels are
 81646  ** always negative and P2 values are suppose to be non-negative.
 81647  ** Hence, a negative P2 value is a label that has yet to be resolved.
 81648  ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
 81649  ** property.
 81650  **
 81651  ** Variable usage notes:
 81652  **
 81653  **     Parse.aLabel[x]     Stores the address that the x-th label resolves
 81654  **                         into.  For testing (SQLITE_DEBUG), unresolved
 81655  **                         labels stores -1, but that is not required.
 81656  **     Parse.nLabelAlloc   Number of slots allocated to Parse.aLabel[]
 81657  **     Parse.nLabel        The *negative* of the number of labels that have
 81658  **                         been issued.  The negative is stored because
 81659  **                         that gives a performance improvement over storing
 81660  **                         the equivalent positive value.
 81661  */
 81662  SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
 81663    return --pParse->nLabel;
 81664  }
 81665  
 81666  /*
 81667  ** Resolve label "x" to be the address of the next instruction to
 81668  ** be inserted.  The parameter "x" must have been obtained from
 81669  ** a prior call to sqlite3VdbeMakeLabel().
 81670  */
 81671  static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
 81672    int nNewSize = 10 - p->nLabel;
 81673    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
 81674                       nNewSize*sizeof(p->aLabel[0]));
 81675    if( p->aLabel==0 ){
 81676      p->nLabelAlloc = 0;
 81677    }else{
 81678  #ifdef SQLITE_DEBUG
 81679      int i;
 81680      for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
 81681  #endif
 81682      p->nLabelAlloc = nNewSize;
 81683      p->aLabel[j] = v->nOp;
 81684    }
 81685  }
 81686  SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
 81687    Parse *p = v->pParse;
 81688    int j = ADDR(x);
 81689    assert( v->magic==VDBE_MAGIC_INIT );
 81690    assert( j<-p->nLabel );
 81691    assert( j>=0 );
 81692  #ifdef SQLITE_DEBUG
 81693    if( p->db->flags & SQLITE_VdbeAddopTrace ){
 81694      printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
 81695    }
 81696  #endif
 81697    if( p->nLabelAlloc + p->nLabel < 0 ){
 81698      resizeResolveLabel(p,v,j);
 81699    }else{
 81700      assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
 81701      p->aLabel[j] = v->nOp;
 81702    }
 81703  }
 81704  
 81705  /*
 81706  ** Mark the VDBE as one that can only be run one time.
 81707  */
 81708  SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
 81709    p->runOnlyOnce = 1;
 81710  }
 81711  
 81712  /*
 81713  ** Mark the VDBE as one that can only be run multiple times.
 81714  */
 81715  SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
 81716    p->runOnlyOnce = 0;
 81717  }
 81718  
 81719  #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
 81720  
 81721  /*
 81722  ** The following type and function are used to iterate through all opcodes
 81723  ** in a Vdbe main program and each of the sub-programs (triggers) it may 
 81724  ** invoke directly or indirectly. It should be used as follows:
 81725  **
 81726  **   Op *pOp;
 81727  **   VdbeOpIter sIter;
 81728  **
 81729  **   memset(&sIter, 0, sizeof(sIter));
 81730  **   sIter.v = v;                            // v is of type Vdbe* 
 81731  **   while( (pOp = opIterNext(&sIter)) ){
 81732  **     // Do something with pOp
 81733  **   }
 81734  **   sqlite3DbFree(v->db, sIter.apSub);
 81735  ** 
 81736  */
 81737  typedef struct VdbeOpIter VdbeOpIter;
 81738  struct VdbeOpIter {
 81739    Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
 81740    SubProgram **apSub;        /* Array of subprograms */
 81741    int nSub;                  /* Number of entries in apSub */
 81742    int iAddr;                 /* Address of next instruction to return */
 81743    int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
 81744  };
 81745  static Op *opIterNext(VdbeOpIter *p){
 81746    Vdbe *v = p->v;
 81747    Op *pRet = 0;
 81748    Op *aOp;
 81749    int nOp;
 81750  
 81751    if( p->iSub<=p->nSub ){
 81752  
 81753      if( p->iSub==0 ){
 81754        aOp = v->aOp;
 81755        nOp = v->nOp;
 81756      }else{
 81757        aOp = p->apSub[p->iSub-1]->aOp;
 81758        nOp = p->apSub[p->iSub-1]->nOp;
 81759      }
 81760      assert( p->iAddr<nOp );
 81761  
 81762      pRet = &aOp[p->iAddr];
 81763      p->iAddr++;
 81764      if( p->iAddr==nOp ){
 81765        p->iSub++;
 81766        p->iAddr = 0;
 81767      }
 81768    
 81769      if( pRet->p4type==P4_SUBPROGRAM ){
 81770        int nByte = (p->nSub+1)*sizeof(SubProgram*);
 81771        int j;
 81772        for(j=0; j<p->nSub; j++){
 81773          if( p->apSub[j]==pRet->p4.pProgram ) break;
 81774        }
 81775        if( j==p->nSub ){
 81776          p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
 81777          if( !p->apSub ){
 81778            pRet = 0;
 81779          }else{
 81780            p->apSub[p->nSub++] = pRet->p4.pProgram;
 81781          }
 81782        }
 81783      }
 81784    }
 81785  
 81786    return pRet;
 81787  }
 81788  
 81789  /*
 81790  ** Check if the program stored in the VM associated with pParse may
 81791  ** throw an ABORT exception (causing the statement, but not entire transaction
 81792  ** to be rolled back). This condition is true if the main program or any
 81793  ** sub-programs contains any of the following:
 81794  **
 81795  **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 81796  **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 81797  **   *  OP_Destroy
 81798  **   *  OP_VUpdate
 81799  **   *  OP_VRename
 81800  **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
 81801  **   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine 
 81802  **      (for CREATE TABLE AS SELECT ...)
 81803  **
 81804  ** Then check that the value of Parse.mayAbort is true if an
 81805  ** ABORT may be thrown, or false otherwise. Return true if it does
 81806  ** match, or false otherwise. This function is intended to be used as
 81807  ** part of an assert statement in the compiler. Similar to:
 81808  **
 81809  **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
 81810  */
 81811  SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
 81812    int hasAbort = 0;
 81813    int hasFkCounter = 0;
 81814    int hasCreateTable = 0;
 81815    int hasInitCoroutine = 0;
 81816    Op *pOp;
 81817    VdbeOpIter sIter;
 81818    memset(&sIter, 0, sizeof(sIter));
 81819    sIter.v = v;
 81820  
 81821    while( (pOp = opIterNext(&sIter))!=0 ){
 81822      int opcode = pOp->opcode;
 81823      if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
 81824       || opcode==OP_VDestroy
 81825       || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
 81826        && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
 81827      ){
 81828        hasAbort = 1;
 81829        break;
 81830      }
 81831      if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
 81832      if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
 81833  #ifndef SQLITE_OMIT_FOREIGN_KEY
 81834      if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
 81835        hasFkCounter = 1;
 81836      }
 81837  #endif
 81838    }
 81839    sqlite3DbFree(v->db, sIter.apSub);
 81840  
 81841    /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
 81842    ** If malloc failed, then the while() loop above may not have iterated
 81843    ** through all opcodes and hasAbort may be set incorrectly. Return
 81844    ** true for this case to prevent the assert() in the callers frame
 81845    ** from failing.  */
 81846    return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
 81847                || (hasCreateTable && hasInitCoroutine) );
 81848  }
 81849  #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
 81850  
 81851  #ifdef SQLITE_DEBUG
 81852  /*
 81853  ** Increment the nWrite counter in the VDBE if the cursor is not an
 81854  ** ephemeral cursor, or if the cursor argument is NULL.
 81855  */
 81856  SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
 81857    if( pC==0
 81858     || (pC->eCurType!=CURTYPE_SORTER
 81859         && pC->eCurType!=CURTYPE_PSEUDO
 81860         && !pC->isEphemeral)
 81861    ){
 81862      p->nWrite++;
 81863    }
 81864  }
 81865  #endif
 81866  
 81867  #ifdef SQLITE_DEBUG
 81868  /*
 81869  ** Assert if an Abort at this point in time might result in a corrupt
 81870  ** database.
 81871  */
 81872  SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
 81873    assert( p->nWrite==0 || p->usesStmtJournal );
 81874  }
 81875  #endif
 81876  
 81877  /*
 81878  ** This routine is called after all opcodes have been inserted.  It loops
 81879  ** through all the opcodes and fixes up some details.
 81880  **
 81881  ** (1) For each jump instruction with a negative P2 value (a label)
 81882  **     resolve the P2 value to an actual address.
 81883  **
 81884  ** (2) Compute the maximum number of arguments used by any SQL function
 81885  **     and store that value in *pMaxFuncArgs.
 81886  **
 81887  ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
 81888  **     indicate what the prepared statement actually does.
 81889  **
 81890  ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
 81891  **
 81892  ** (5) Reclaim the memory allocated for storing labels.
 81893  **
 81894  ** This routine will only function correctly if the mkopcodeh.tcl generator
 81895  ** script numbers the opcodes correctly.  Changes to this routine must be
 81896  ** coordinated with changes to mkopcodeh.tcl.
 81897  */
 81898  static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
 81899    int nMaxArgs = *pMaxFuncArgs;
 81900    Op *pOp;
 81901    Parse *pParse = p->pParse;
 81902    int *aLabel = pParse->aLabel;
 81903    p->readOnly = 1;
 81904    p->bIsReader = 0;
 81905    pOp = &p->aOp[p->nOp-1];
 81906    while(1){
 81907  
 81908      /* Only JUMP opcodes and the short list of special opcodes in the switch
 81909      ** below need to be considered.  The mkopcodeh.tcl generator script groups
 81910      ** all these opcodes together near the front of the opcode list.  Skip
 81911      ** any opcode that does not need processing by virtual of the fact that
 81912      ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
 81913      */
 81914      if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
 81915        /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
 81916        ** cases from this switch! */
 81917        switch( pOp->opcode ){
 81918          case OP_Transaction: {
 81919            if( pOp->p2!=0 ) p->readOnly = 0;
 81920            /* fall thru */
 81921          }
 81922          case OP_AutoCommit:
 81923          case OP_Savepoint: {
 81924            p->bIsReader = 1;
 81925            break;
 81926          }
 81927  #ifndef SQLITE_OMIT_WAL
 81928          case OP_Checkpoint:
 81929  #endif
 81930          case OP_Vacuum:
 81931          case OP_JournalMode: {
 81932            p->readOnly = 0;
 81933            p->bIsReader = 1;
 81934            break;
 81935          }
 81936          case OP_Next:
 81937          case OP_SorterNext: {
 81938            pOp->p4.xAdvance = sqlite3BtreeNext;
 81939            pOp->p4type = P4_ADVANCE;
 81940            /* The code generator never codes any of these opcodes as a jump
 81941            ** to a label.  They are always coded as a jump backwards to a 
 81942            ** known address */
 81943            assert( pOp->p2>=0 );
 81944            break;
 81945          }
 81946          case OP_Prev: {
 81947            pOp->p4.xAdvance = sqlite3BtreePrevious;
 81948            pOp->p4type = P4_ADVANCE;
 81949            /* The code generator never codes any of these opcodes as a jump
 81950            ** to a label.  They are always coded as a jump backwards to a 
 81951            ** known address */
 81952            assert( pOp->p2>=0 );
 81953            break;
 81954          }
 81955  #ifndef SQLITE_OMIT_VIRTUALTABLE
 81956          case OP_VUpdate: {
 81957            if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
 81958            break;
 81959          }
 81960          case OP_VFilter: {
 81961            int n;
 81962            assert( (pOp - p->aOp) >= 3 );
 81963            assert( pOp[-1].opcode==OP_Integer );
 81964            n = pOp[-1].p1;
 81965            if( n>nMaxArgs ) nMaxArgs = n;
 81966            /* Fall through into the default case */
 81967          }
 81968  #endif
 81969          default: {
 81970            if( pOp->p2<0 ){
 81971              /* The mkopcodeh.tcl script has so arranged things that the only
 81972              ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
 81973              ** have non-negative values for P2. */
 81974              assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
 81975              assert( ADDR(pOp->p2)<-pParse->nLabel );
 81976              pOp->p2 = aLabel[ADDR(pOp->p2)];
 81977            }
 81978            break;
 81979          }
 81980        }
 81981        /* The mkopcodeh.tcl script has so arranged things that the only
 81982        ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
 81983        ** have non-negative values for P2. */
 81984        assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
 81985      }
 81986      if( pOp==p->aOp ) break;
 81987      pOp--;
 81988    }
 81989    sqlite3DbFree(p->db, pParse->aLabel);
 81990    pParse->aLabel = 0;
 81991    pParse->nLabel = 0;
 81992    *pMaxFuncArgs = nMaxArgs;
 81993    assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
 81994  }
 81995  
 81996  /*
 81997  ** Return the address of the next instruction to be inserted.
 81998  */
 81999  SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
 82000    assert( p->magic==VDBE_MAGIC_INIT );
 82001    return p->nOp;
 82002  }
 82003  
 82004  /*
 82005  ** Verify that at least N opcode slots are available in p without
 82006  ** having to malloc for more space (except when compiled using
 82007  ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
 82008  ** to verify that certain calls to sqlite3VdbeAddOpList() can never
 82009  ** fail due to a OOM fault and hence that the return value from
 82010  ** sqlite3VdbeAddOpList() will always be non-NULL.
 82011  */
 82012  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 82013  SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
 82014    assert( p->nOp + N <= p->nOpAlloc );
 82015  }
 82016  #endif
 82017  
 82018  /*
 82019  ** Verify that the VM passed as the only argument does not contain
 82020  ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
 82021  ** by code in pragma.c to ensure that the implementation of certain
 82022  ** pragmas comports with the flags specified in the mkpragmatab.tcl
 82023  ** script.
 82024  */
 82025  #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 82026  SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
 82027    int i;
 82028    for(i=0; i<p->nOp; i++){
 82029      assert( p->aOp[i].opcode!=OP_ResultRow );
 82030    }
 82031  }
 82032  #endif
 82033  
 82034  /*
 82035  ** Generate code (a single OP_Abortable opcode) that will
 82036  ** verify that the VDBE program can safely call Abort in the current
 82037  ** context.
 82038  */
 82039  #if defined(SQLITE_DEBUG)
 82040  SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
 82041    if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
 82042  }
 82043  #endif
 82044  
 82045  /*
 82046  ** This function returns a pointer to the array of opcodes associated with
 82047  ** the Vdbe passed as the first argument. It is the callers responsibility
 82048  ** to arrange for the returned array to be eventually freed using the 
 82049  ** vdbeFreeOpArray() function.
 82050  **
 82051  ** Before returning, *pnOp is set to the number of entries in the returned
 82052  ** array. Also, *pnMaxArg is set to the larger of its current value and 
 82053  ** the number of entries in the Vdbe.apArg[] array required to execute the 
 82054  ** returned program.
 82055  */
 82056  SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
 82057    VdbeOp *aOp = p->aOp;
 82058    assert( aOp && !p->db->mallocFailed );
 82059  
 82060    /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
 82061    assert( DbMaskAllZero(p->btreeMask) );
 82062  
 82063    resolveP2Values(p, pnMaxArg);
 82064    *pnOp = p->nOp;
 82065    p->aOp = 0;
 82066    return aOp;
 82067  }
 82068  
 82069  /*
 82070  ** Add a whole list of operations to the operation stack.  Return a
 82071  ** pointer to the first operation inserted.
 82072  **
 82073  ** Non-zero P2 arguments to jump instructions are automatically adjusted
 82074  ** so that the jump target is relative to the first operation inserted.
 82075  */
 82076  SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
 82077    Vdbe *p,                     /* Add opcodes to the prepared statement */
 82078    int nOp,                     /* Number of opcodes to add */
 82079    VdbeOpList const *aOp,       /* The opcodes to be added */
 82080    int iLineno                  /* Source-file line number of first opcode */
 82081  ){
 82082    int i;
 82083    VdbeOp *pOut, *pFirst;
 82084    assert( nOp>0 );
 82085    assert( p->magic==VDBE_MAGIC_INIT );
 82086    if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
 82087      return 0;
 82088    }
 82089    pFirst = pOut = &p->aOp[p->nOp];
 82090    for(i=0; i<nOp; i++, aOp++, pOut++){
 82091      pOut->opcode = aOp->opcode;
 82092      pOut->p1 = aOp->p1;
 82093      pOut->p2 = aOp->p2;
 82094      assert( aOp->p2>=0 );
 82095      if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
 82096        pOut->p2 += p->nOp;
 82097      }
 82098      pOut->p3 = aOp->p3;
 82099      pOut->p4type = P4_NOTUSED;
 82100      pOut->p4.p = 0;
 82101      pOut->p5 = 0;
 82102  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 82103      pOut->zComment = 0;
 82104  #endif
 82105  #ifdef SQLITE_VDBE_COVERAGE
 82106      pOut->iSrcLine = iLineno+i;
 82107  #else
 82108      (void)iLineno;
 82109  #endif
 82110  #ifdef SQLITE_DEBUG
 82111      if( p->db->flags & SQLITE_VdbeAddopTrace ){
 82112        sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
 82113      }
 82114  #endif
 82115    }
 82116    p->nOp += nOp;
 82117    return pFirst;
 82118  }
 82119  
 82120  #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
 82121  /*
 82122  ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
 82123  */
 82124  SQLITE_PRIVATE void sqlite3VdbeScanStatus(
 82125    Vdbe *p,                        /* VM to add scanstatus() to */
 82126    int addrExplain,                /* Address of OP_Explain (or 0) */
 82127    int addrLoop,                   /* Address of loop counter */ 
 82128    int addrVisit,                  /* Address of rows visited counter */
 82129    LogEst nEst,                    /* Estimated number of output rows */
 82130    const char *zName               /* Name of table or index being scanned */
 82131  ){
 82132    int nByte = (p->nScan+1) * sizeof(ScanStatus);
 82133    ScanStatus *aNew;
 82134    aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
 82135    if( aNew ){
 82136      ScanStatus *pNew = &aNew[p->nScan++];
 82137      pNew->addrExplain = addrExplain;
 82138      pNew->addrLoop = addrLoop;
 82139      pNew->addrVisit = addrVisit;
 82140      pNew->nEst = nEst;
 82141      pNew->zName = sqlite3DbStrDup(p->db, zName);
 82142      p->aScan = aNew;
 82143    }
 82144  }
 82145  #endif
 82146  
 82147  
 82148  /*
 82149  ** Change the value of the opcode, or P1, P2, P3, or P5 operands
 82150  ** for a specific instruction.
 82151  */
 82152  SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
 82153    sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
 82154  }
 82155  SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
 82156    sqlite3VdbeGetOp(p,addr)->p1 = val;
 82157  }
 82158  SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
 82159    sqlite3VdbeGetOp(p,addr)->p2 = val;
 82160  }
 82161  SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
 82162    sqlite3VdbeGetOp(p,addr)->p3 = val;
 82163  }
 82164  SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
 82165    assert( p->nOp>0 || p->db->mallocFailed );
 82166    if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
 82167  }
 82168  
 82169  /*
 82170  ** Change the P2 operand of instruction addr so that it points to
 82171  ** the address of the next instruction to be coded.
 82172  */
 82173  SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
 82174    sqlite3VdbeChangeP2(p, addr, p->nOp);
 82175  }
 82176  
 82177  
 82178  /*
 82179  ** If the input FuncDef structure is ephemeral, then free it.  If
 82180  ** the FuncDef is not ephermal, then do nothing.
 82181  */
 82182  static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
 82183    if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
 82184      sqlite3DbFreeNN(db, pDef);
 82185    }
 82186  }
 82187  
 82188  static void vdbeFreeOpArray(sqlite3 *, Op *, int);
 82189  
 82190  /*
 82191  ** Delete a P4 value if necessary.
 82192  */
 82193  static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
 82194    if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
 82195    sqlite3DbFreeNN(db, p);
 82196  }
 82197  static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
 82198    freeEphemeralFunction(db, p->pFunc);
 82199   sqlite3DbFreeNN(db, p);
 82200  }
 82201  static void freeP4(sqlite3 *db, int p4type, void *p4){
 82202    assert( db );
 82203    switch( p4type ){
 82204      case P4_FUNCCTX: {
 82205        freeP4FuncCtx(db, (sqlite3_context*)p4);
 82206        break;
 82207      }
 82208      case P4_REAL:
 82209      case P4_INT64:
 82210      case P4_DYNAMIC:
 82211      case P4_DYNBLOB:
 82212      case P4_INTARRAY: {
 82213        sqlite3DbFree(db, p4);
 82214        break;
 82215      }
 82216      case P4_KEYINFO: {
 82217        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
 82218        break;
 82219      }
 82220  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 82221      case P4_EXPR: {
 82222        sqlite3ExprDelete(db, (Expr*)p4);
 82223        break;
 82224      }
 82225  #endif
 82226      case P4_FUNCDEF: {
 82227        freeEphemeralFunction(db, (FuncDef*)p4);
 82228        break;
 82229      }
 82230      case P4_MEM: {
 82231        if( db->pnBytesFreed==0 ){
 82232          sqlite3ValueFree((sqlite3_value*)p4);
 82233        }else{
 82234          freeP4Mem(db, (Mem*)p4);
 82235        }
 82236        break;
 82237      }
 82238      case P4_VTAB : {
 82239        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
 82240        break;
 82241      }
 82242    }
 82243  }
 82244  
 82245  /*
 82246  ** Free the space allocated for aOp and any p4 values allocated for the
 82247  ** opcodes contained within. If aOp is not NULL it is assumed to contain 
 82248  ** nOp entries. 
 82249  */
 82250  static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
 82251    if( aOp ){
 82252      Op *pOp;
 82253      for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
 82254        if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
 82255  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 82256        sqlite3DbFree(db, pOp->zComment);
 82257  #endif     
 82258      }
 82259      sqlite3DbFreeNN(db, aOp);
 82260    }
 82261  }
 82262  
 82263  /*
 82264  ** Link the SubProgram object passed as the second argument into the linked
 82265  ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
 82266  ** objects when the VM is no longer required.
 82267  */
 82268  SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
 82269    p->pNext = pVdbe->pProgram;
 82270    pVdbe->pProgram = p;
 82271  }
 82272  
 82273  /*
 82274  ** Change the opcode at addr into OP_Noop
 82275  */
 82276  SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
 82277    VdbeOp *pOp;
 82278    if( p->db->mallocFailed ) return 0;
 82279    assert( addr>=0 && addr<p->nOp );
 82280    pOp = &p->aOp[addr];
 82281    freeP4(p->db, pOp->p4type, pOp->p4.p);
 82282    pOp->p4type = P4_NOTUSED;
 82283    pOp->p4.z = 0;
 82284    pOp->opcode = OP_Noop;
 82285    return 1;
 82286  }
 82287  
 82288  /*
 82289  ** If the last opcode is "op" and it is not a jump destination,
 82290  ** then remove it.  Return true if and only if an opcode was removed.
 82291  */
 82292  SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
 82293    if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
 82294      return sqlite3VdbeChangeToNoop(p, p->nOp-1);
 82295    }else{
 82296      return 0;
 82297    }
 82298  }
 82299  
 82300  /*
 82301  ** Change the value of the P4 operand for a specific instruction.
 82302  ** This routine is useful when a large program is loaded from a
 82303  ** static array using sqlite3VdbeAddOpList but we want to make a
 82304  ** few minor changes to the program.
 82305  **
 82306  ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
 82307  ** the string is made into memory obtained from sqlite3_malloc().
 82308  ** A value of n==0 means copy bytes of zP4 up to and including the
 82309  ** first null byte.  If n>0 then copy n+1 bytes of zP4.
 82310  ** 
 82311  ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
 82312  ** to a string or structure that is guaranteed to exist for the lifetime of
 82313  ** the Vdbe. In these cases we can just copy the pointer.
 82314  **
 82315  ** If addr<0 then change P4 on the most recently inserted instruction.
 82316  */
 82317  static void SQLITE_NOINLINE vdbeChangeP4Full(
 82318    Vdbe *p,
 82319    Op *pOp,
 82320    const char *zP4,
 82321    int n
 82322  ){
 82323    if( pOp->p4type ){
 82324      freeP4(p->db, pOp->p4type, pOp->p4.p);
 82325      pOp->p4type = 0;
 82326      pOp->p4.p = 0;
 82327    }
 82328    if( n<0 ){
 82329      sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
 82330    }else{
 82331      if( n==0 ) n = sqlite3Strlen30(zP4);
 82332      pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
 82333      pOp->p4type = P4_DYNAMIC;
 82334    }
 82335  }
 82336  SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
 82337    Op *pOp;
 82338    sqlite3 *db;
 82339    assert( p!=0 );
 82340    db = p->db;
 82341    assert( p->magic==VDBE_MAGIC_INIT );
 82342    assert( p->aOp!=0 || db->mallocFailed );
 82343    if( db->mallocFailed ){
 82344      if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
 82345      return;
 82346    }
 82347    assert( p->nOp>0 );
 82348    assert( addr<p->nOp );
 82349    if( addr<0 ){
 82350      addr = p->nOp - 1;
 82351    }
 82352    pOp = &p->aOp[addr];
 82353    if( n>=0 || pOp->p4type ){
 82354      vdbeChangeP4Full(p, pOp, zP4, n);
 82355      return;
 82356    }
 82357    if( n==P4_INT32 ){
 82358      /* Note: this cast is safe, because the origin data point was an int
 82359      ** that was cast to a (const char *). */
 82360      pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
 82361      pOp->p4type = P4_INT32;
 82362    }else if( zP4!=0 ){
 82363      assert( n<0 );
 82364      pOp->p4.p = (void*)zP4;
 82365      pOp->p4type = (signed char)n;
 82366      if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
 82367    }
 82368  }
 82369  
 82370  /*
 82371  ** Change the P4 operand of the most recently coded instruction 
 82372  ** to the value defined by the arguments.  This is a high-speed
 82373  ** version of sqlite3VdbeChangeP4().
 82374  **
 82375  ** The P4 operand must not have been previously defined.  And the new
 82376  ** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
 82377  ** those cases.
 82378  */
 82379  SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
 82380    VdbeOp *pOp;
 82381    assert( n!=P4_INT32 && n!=P4_VTAB );
 82382    assert( n<=0 );
 82383    if( p->db->mallocFailed ){
 82384      freeP4(p->db, n, pP4);
 82385    }else{
 82386      assert( pP4!=0 );
 82387      assert( p->nOp>0 );
 82388      pOp = &p->aOp[p->nOp-1];
 82389      assert( pOp->p4type==P4_NOTUSED );
 82390      pOp->p4type = n;
 82391      pOp->p4.p = pP4;
 82392    }
 82393  }
 82394  
 82395  /*
 82396  ** Set the P4 on the most recently added opcode to the KeyInfo for the
 82397  ** index given.
 82398  */
 82399  SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
 82400    Vdbe *v = pParse->pVdbe;
 82401    KeyInfo *pKeyInfo;
 82402    assert( v!=0 );
 82403    assert( pIdx!=0 );
 82404    pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
 82405    if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
 82406  }
 82407  
 82408  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 82409  /*
 82410  ** Change the comment on the most recently coded instruction.  Or
 82411  ** insert a No-op and add the comment to that new instruction.  This
 82412  ** makes the code easier to read during debugging.  None of this happens
 82413  ** in a production build.
 82414  */
 82415  static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
 82416    assert( p->nOp>0 || p->aOp==0 );
 82417    assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
 82418    if( p->nOp ){
 82419      assert( p->aOp );
 82420      sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
 82421      p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
 82422    }
 82423  }
 82424  SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
 82425    va_list ap;
 82426    if( p ){
 82427      va_start(ap, zFormat);
 82428      vdbeVComment(p, zFormat, ap);
 82429      va_end(ap);
 82430    }
 82431  }
 82432  SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
 82433    va_list ap;
 82434    if( p ){
 82435      sqlite3VdbeAddOp0(p, OP_Noop);
 82436      va_start(ap, zFormat);
 82437      vdbeVComment(p, zFormat, ap);
 82438      va_end(ap);
 82439    }
 82440  }
 82441  #endif  /* NDEBUG */
 82442  
 82443  #ifdef SQLITE_VDBE_COVERAGE
 82444  /*
 82445  ** Set the value if the iSrcLine field for the previously coded instruction.
 82446  */
 82447  SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
 82448    sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
 82449  }
 82450  #endif /* SQLITE_VDBE_COVERAGE */
 82451  
 82452  /*
 82453  ** Return the opcode for a given address.  If the address is -1, then
 82454  ** return the most recently inserted opcode.
 82455  **
 82456  ** If a memory allocation error has occurred prior to the calling of this
 82457  ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
 82458  ** is readable but not writable, though it is cast to a writable value.
 82459  ** The return of a dummy opcode allows the call to continue functioning
 82460  ** after an OOM fault without having to check to see if the return from 
 82461  ** this routine is a valid pointer.  But because the dummy.opcode is 0,
 82462  ** dummy will never be written to.  This is verified by code inspection and
 82463  ** by running with Valgrind.
 82464  */
 82465  SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
 82466    /* C89 specifies that the constant "dummy" will be initialized to all
 82467    ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
 82468    static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
 82469    assert( p->magic==VDBE_MAGIC_INIT );
 82470    if( addr<0 ){
 82471      addr = p->nOp - 1;
 82472    }
 82473    assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
 82474    if( p->db->mallocFailed ){
 82475      return (VdbeOp*)&dummy;
 82476    }else{
 82477      return &p->aOp[addr];
 82478    }
 82479  }
 82480  
 82481  #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
 82482  /*
 82483  ** Return an integer value for one of the parameters to the opcode pOp
 82484  ** determined by character c.
 82485  */
 82486  static int translateP(char c, const Op *pOp){
 82487    if( c=='1' ) return pOp->p1;
 82488    if( c=='2' ) return pOp->p2;
 82489    if( c=='3' ) return pOp->p3;
 82490    if( c=='4' ) return pOp->p4.i;
 82491    return pOp->p5;
 82492  }
 82493  
 82494  /*
 82495  ** Compute a string for the "comment" field of a VDBE opcode listing.
 82496  **
 82497  ** The Synopsis: field in comments in the vdbe.c source file gets converted
 82498  ** to an extra string that is appended to the sqlite3OpcodeName().  In the
 82499  ** absence of other comments, this synopsis becomes the comment on the opcode.
 82500  ** Some translation occurs:
 82501  **
 82502  **       "PX"      ->  "r[X]"
 82503  **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
 82504  **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
 82505  **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
 82506  */
 82507  static int displayComment(
 82508    const Op *pOp,     /* The opcode to be commented */
 82509    const char *zP4,   /* Previously obtained value for P4 */
 82510    char *zTemp,       /* Write result here */
 82511    int nTemp          /* Space available in zTemp[] */
 82512  ){
 82513    const char *zOpName;
 82514    const char *zSynopsis;
 82515    int nOpName;
 82516    int ii, jj;
 82517    char zAlt[50];
 82518    zOpName = sqlite3OpcodeName(pOp->opcode);
 82519    nOpName = sqlite3Strlen30(zOpName);
 82520    if( zOpName[nOpName+1] ){
 82521      int seenCom = 0;
 82522      char c;
 82523      zSynopsis = zOpName += nOpName + 1;
 82524      if( strncmp(zSynopsis,"IF ",3)==0 ){
 82525        if( pOp->p5 & SQLITE_STOREP2 ){
 82526          sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
 82527        }else{
 82528          sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
 82529        }
 82530        zSynopsis = zAlt;
 82531      }
 82532      for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
 82533        if( c=='P' ){
 82534          c = zSynopsis[++ii];
 82535          if( c=='4' ){
 82536            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
 82537          }else if( c=='X' ){
 82538            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
 82539            seenCom = 1;
 82540          }else{
 82541            int v1 = translateP(c, pOp);
 82542            int v2;
 82543            sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
 82544            if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
 82545              ii += 3;
 82546              jj += sqlite3Strlen30(zTemp+jj);
 82547              v2 = translateP(zSynopsis[ii], pOp);
 82548              if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
 82549                ii += 2;
 82550                v2++;
 82551              }
 82552              if( v2>1 ){
 82553                sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
 82554              }
 82555            }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
 82556              ii += 4;
 82557            }
 82558          }
 82559          jj += sqlite3Strlen30(zTemp+jj);
 82560        }else{
 82561          zTemp[jj++] = c;
 82562        }
 82563      }
 82564      if( !seenCom && jj<nTemp-5 && pOp->zComment ){
 82565        sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
 82566        jj += sqlite3Strlen30(zTemp+jj);
 82567      }
 82568      if( jj<nTemp ) zTemp[jj] = 0;
 82569    }else if( pOp->zComment ){
 82570      sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
 82571      jj = sqlite3Strlen30(zTemp);
 82572    }else{
 82573      zTemp[0] = 0;
 82574      jj = 0;
 82575    }
 82576    return jj;
 82577  }
 82578  #endif /* SQLITE_DEBUG */
 82579  
 82580  #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
 82581  /*
 82582  ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
 82583  ** that can be displayed in the P4 column of EXPLAIN output.
 82584  */
 82585  static void displayP4Expr(StrAccum *p, Expr *pExpr){
 82586    const char *zOp = 0;
 82587    switch( pExpr->op ){
 82588      case TK_STRING:
 82589        sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
 82590        break;
 82591      case TK_INTEGER:
 82592        sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
 82593        break;
 82594      case TK_NULL:
 82595        sqlite3_str_appendf(p, "NULL");
 82596        break;
 82597      case TK_REGISTER: {
 82598        sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
 82599        break;
 82600      }
 82601      case TK_COLUMN: {
 82602        if( pExpr->iColumn<0 ){
 82603          sqlite3_str_appendf(p, "rowid");
 82604        }else{
 82605          sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
 82606        }
 82607        break;
 82608      }
 82609      case TK_LT:      zOp = "LT";      break;
 82610      case TK_LE:      zOp = "LE";      break;
 82611      case TK_GT:      zOp = "GT";      break;
 82612      case TK_GE:      zOp = "GE";      break;
 82613      case TK_NE:      zOp = "NE";      break;
 82614      case TK_EQ:      zOp = "EQ";      break;
 82615      case TK_IS:      zOp = "IS";      break;
 82616      case TK_ISNOT:   zOp = "ISNOT";   break;
 82617      case TK_AND:     zOp = "AND";     break;
 82618      case TK_OR:      zOp = "OR";      break;
 82619      case TK_PLUS:    zOp = "ADD";     break;
 82620      case TK_STAR:    zOp = "MUL";     break;
 82621      case TK_MINUS:   zOp = "SUB";     break;
 82622      case TK_REM:     zOp = "REM";     break;
 82623      case TK_BITAND:  zOp = "BITAND";  break;
 82624      case TK_BITOR:   zOp = "BITOR";   break;
 82625      case TK_SLASH:   zOp = "DIV";     break;
 82626      case TK_LSHIFT:  zOp = "LSHIFT";  break;
 82627      case TK_RSHIFT:  zOp = "RSHIFT";  break;
 82628      case TK_CONCAT:  zOp = "CONCAT";  break;
 82629      case TK_UMINUS:  zOp = "MINUS";   break;
 82630      case TK_UPLUS:   zOp = "PLUS";    break;
 82631      case TK_BITNOT:  zOp = "BITNOT";  break;
 82632      case TK_NOT:     zOp = "NOT";     break;
 82633      case TK_ISNULL:  zOp = "ISNULL";  break;
 82634      case TK_NOTNULL: zOp = "NOTNULL"; break;
 82635  
 82636      default:
 82637        sqlite3_str_appendf(p, "%s", "expr");
 82638        break;
 82639    }
 82640  
 82641    if( zOp ){
 82642      sqlite3_str_appendf(p, "%s(", zOp);
 82643      displayP4Expr(p, pExpr->pLeft);
 82644      if( pExpr->pRight ){
 82645        sqlite3_str_append(p, ",", 1);
 82646        displayP4Expr(p, pExpr->pRight);
 82647      }
 82648      sqlite3_str_append(p, ")", 1);
 82649    }
 82650  }
 82651  #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
 82652  
 82653  
 82654  #if VDBE_DISPLAY_P4
 82655  /*
 82656  ** Compute a string that describes the P4 parameter for an opcode.
 82657  ** Use zTemp for any required temporary buffer space.
 82658  */
 82659  static char *displayP4(Op *pOp, char *zTemp, int nTemp){
 82660    char *zP4 = zTemp;
 82661    StrAccum x;
 82662    assert( nTemp>=20 );
 82663    sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
 82664    switch( pOp->p4type ){
 82665      case P4_KEYINFO: {
 82666        int j;
 82667        KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
 82668        assert( pKeyInfo->aSortOrder!=0 );
 82669        sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
 82670        for(j=0; j<pKeyInfo->nKeyField; j++){
 82671          CollSeq *pColl = pKeyInfo->aColl[j];
 82672          const char *zColl = pColl ? pColl->zName : "";
 82673          if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
 82674          sqlite3_str_appendf(&x, ",%s%s", 
 82675                 pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
 82676        }
 82677        sqlite3_str_append(&x, ")", 1);
 82678        break;
 82679      }
 82680  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 82681      case P4_EXPR: {
 82682        displayP4Expr(&x, pOp->p4.pExpr);
 82683        break;
 82684      }
 82685  #endif
 82686      case P4_COLLSEQ: {
 82687        CollSeq *pColl = pOp->p4.pColl;
 82688        sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
 82689        break;
 82690      }
 82691      case P4_FUNCDEF: {
 82692        FuncDef *pDef = pOp->p4.pFunc;
 82693        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 82694        break;
 82695      }
 82696  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 82697      case P4_FUNCCTX: {
 82698        FuncDef *pDef = pOp->p4.pCtx->pFunc;
 82699        sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
 82700        break;
 82701      }
 82702  #endif
 82703      case P4_INT64: {
 82704        sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
 82705        break;
 82706      }
 82707      case P4_INT32: {
 82708        sqlite3_str_appendf(&x, "%d", pOp->p4.i);
 82709        break;
 82710      }
 82711      case P4_REAL: {
 82712        sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
 82713        break;
 82714      }
 82715      case P4_MEM: {
 82716        Mem *pMem = pOp->p4.pMem;
 82717        if( pMem->flags & MEM_Str ){
 82718          zP4 = pMem->z;
 82719        }else if( pMem->flags & MEM_Int ){
 82720          sqlite3_str_appendf(&x, "%lld", pMem->u.i);
 82721        }else if( pMem->flags & MEM_Real ){
 82722          sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
 82723        }else if( pMem->flags & MEM_Null ){
 82724          zP4 = "NULL";
 82725        }else{
 82726          assert( pMem->flags & MEM_Blob );
 82727          zP4 = "(blob)";
 82728        }
 82729        break;
 82730      }
 82731  #ifndef SQLITE_OMIT_VIRTUALTABLE
 82732      case P4_VTAB: {
 82733        sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
 82734        sqlite3_str_appendf(&x, "vtab:%p", pVtab);
 82735        break;
 82736      }
 82737  #endif
 82738      case P4_INTARRAY: {
 82739        int i;
 82740        int *ai = pOp->p4.ai;
 82741        int n = ai[0];   /* The first element of an INTARRAY is always the
 82742                         ** count of the number of elements to follow */
 82743        for(i=1; i<=n; i++){
 82744          sqlite3_str_appendf(&x, ",%d", ai[i]);
 82745        }
 82746        zTemp[0] = '[';
 82747        sqlite3_str_append(&x, "]", 1);
 82748        break;
 82749      }
 82750      case P4_SUBPROGRAM: {
 82751        sqlite3_str_appendf(&x, "program");
 82752        break;
 82753      }
 82754      case P4_DYNBLOB:
 82755      case P4_ADVANCE: {
 82756        zTemp[0] = 0;
 82757        break;
 82758      }
 82759      case P4_TABLE: {
 82760        sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
 82761        break;
 82762      }
 82763      default: {
 82764        zP4 = pOp->p4.z;
 82765        if( zP4==0 ){
 82766          zP4 = zTemp;
 82767          zTemp[0] = 0;
 82768        }
 82769      }
 82770    }
 82771    sqlite3StrAccumFinish(&x);
 82772    assert( zP4!=0 );
 82773    return zP4;
 82774  }
 82775  #endif /* VDBE_DISPLAY_P4 */
 82776  
 82777  /*
 82778  ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
 82779  **
 82780  ** The prepared statements need to know in advance the complete set of
 82781  ** attached databases that will be use.  A mask of these databases
 82782  ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
 82783  ** p->btreeMask of databases that will require a lock.
 82784  */
 82785  SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
 82786    assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
 82787    assert( i<(int)sizeof(p->btreeMask)*8 );
 82788    DbMaskSet(p->btreeMask, i);
 82789    if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
 82790      DbMaskSet(p->lockMask, i);
 82791    }
 82792  }
 82793  
 82794  #if !defined(SQLITE_OMIT_SHARED_CACHE)
 82795  /*
 82796  ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
 82797  ** this routine obtains the mutex associated with each BtShared structure
 82798  ** that may be accessed by the VM passed as an argument. In doing so it also
 82799  ** sets the BtShared.db member of each of the BtShared structures, ensuring
 82800  ** that the correct busy-handler callback is invoked if required.
 82801  **
 82802  ** If SQLite is not threadsafe but does support shared-cache mode, then
 82803  ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
 82804  ** of all of BtShared structures accessible via the database handle 
 82805  ** associated with the VM.
 82806  **
 82807  ** If SQLite is not threadsafe and does not support shared-cache mode, this
 82808  ** function is a no-op.
 82809  **
 82810  ** The p->btreeMask field is a bitmask of all btrees that the prepared 
 82811  ** statement p will ever use.  Let N be the number of bits in p->btreeMask
 82812  ** corresponding to btrees that use shared cache.  Then the runtime of
 82813  ** this routine is N*N.  But as N is rarely more than 1, this should not
 82814  ** be a problem.
 82815  */
 82816  SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
 82817    int i;
 82818    sqlite3 *db;
 82819    Db *aDb;
 82820    int nDb;
 82821    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
 82822    db = p->db;
 82823    aDb = db->aDb;
 82824    nDb = db->nDb;
 82825    for(i=0; i<nDb; i++){
 82826      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
 82827        sqlite3BtreeEnter(aDb[i].pBt);
 82828      }
 82829    }
 82830  }
 82831  #endif
 82832  
 82833  #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
 82834  /*
 82835  ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
 82836  */
 82837  static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
 82838    int i;
 82839    sqlite3 *db;
 82840    Db *aDb;
 82841    int nDb;
 82842    db = p->db;
 82843    aDb = db->aDb;
 82844    nDb = db->nDb;
 82845    for(i=0; i<nDb; i++){
 82846      if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
 82847        sqlite3BtreeLeave(aDb[i].pBt);
 82848      }
 82849    }
 82850  }
 82851  SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
 82852    if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
 82853    vdbeLeave(p);
 82854  }
 82855  #endif
 82856  
 82857  #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
 82858  /*
 82859  ** Print a single opcode.  This routine is used for debugging only.
 82860  */
 82861  SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
 82862    char *zP4;
 82863    char zPtr[50];
 82864    char zCom[100];
 82865    static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
 82866    if( pOut==0 ) pOut = stdout;
 82867    zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
 82868  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 82869    displayComment(pOp, zP4, zCom, sizeof(zCom));
 82870  #else
 82871    zCom[0] = 0;
 82872  #endif
 82873    /* NB:  The sqlite3OpcodeName() function is implemented by code created
 82874    ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
 82875    ** information from the vdbe.c source text */
 82876    fprintf(pOut, zFormat1, pc, 
 82877        sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
 82878        zCom
 82879    );
 82880    fflush(pOut);
 82881  }
 82882  #endif
 82883  
 82884  /*
 82885  ** Initialize an array of N Mem element.
 82886  */
 82887  static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
 82888    while( (N--)>0 ){
 82889      p->db = db;
 82890      p->flags = flags;
 82891      p->szMalloc = 0;
 82892  #ifdef SQLITE_DEBUG
 82893      p->pScopyFrom = 0;
 82894  #endif
 82895      p++;
 82896    }
 82897  }
 82898  
 82899  /*
 82900  ** Release an array of N Mem elements
 82901  */
 82902  static void releaseMemArray(Mem *p, int N){
 82903    if( p && N ){
 82904      Mem *pEnd = &p[N];
 82905      sqlite3 *db = p->db;
 82906      if( db->pnBytesFreed ){
 82907        do{
 82908          if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
 82909        }while( (++p)<pEnd );
 82910        return;
 82911      }
 82912      do{
 82913        assert( (&p[1])==pEnd || p[0].db==p[1].db );
 82914        assert( sqlite3VdbeCheckMemInvariants(p) );
 82915  
 82916        /* This block is really an inlined version of sqlite3VdbeMemRelease()
 82917        ** that takes advantage of the fact that the memory cell value is 
 82918        ** being set to NULL after releasing any dynamic resources.
 82919        **
 82920        ** The justification for duplicating code is that according to 
 82921        ** callgrind, this causes a certain test case to hit the CPU 4.7 
 82922        ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
 82923        ** sqlite3MemRelease() were called from here. With -O2, this jumps
 82924        ** to 6.6 percent. The test case is inserting 1000 rows into a table 
 82925        ** with no indexes using a single prepared INSERT statement, bind() 
 82926        ** and reset(). Inserts are grouped into a transaction.
 82927        */
 82928        testcase( p->flags & MEM_Agg );
 82929        testcase( p->flags & MEM_Dyn );
 82930        testcase( p->xDel==sqlite3VdbeFrameMemDel );
 82931        if( p->flags&(MEM_Agg|MEM_Dyn) ){
 82932          sqlite3VdbeMemRelease(p);
 82933        }else if( p->szMalloc ){
 82934          sqlite3DbFreeNN(db, p->zMalloc);
 82935          p->szMalloc = 0;
 82936        }
 82937  
 82938        p->flags = MEM_Undefined;
 82939      }while( (++p)<pEnd );
 82940    }
 82941  }
 82942  
 82943  #ifdef SQLITE_DEBUG
 82944  /*
 82945  ** Verify that pFrame is a valid VdbeFrame pointer.  Return true if it is
 82946  ** and false if something is wrong.
 82947  **
 82948  ** This routine is intended for use inside of assert() statements only.
 82949  */
 82950  SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
 82951    if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
 82952    return 1;
 82953  }
 82954  #endif
 82955  
 82956  
 82957  /*
 82958  ** This is a destructor on a Mem object (which is really an sqlite3_value)
 82959  ** that deletes the Frame object that is attached to it as a blob.
 82960  **
 82961  ** This routine does not delete the Frame right away.  It merely adds the
 82962  ** frame to a list of frames to be deleted when the Vdbe halts.
 82963  */
 82964  SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
 82965    VdbeFrame *pFrame = (VdbeFrame*)pArg;
 82966    assert( sqlite3VdbeFrameIsValid(pFrame) );
 82967    pFrame->pParent = pFrame->v->pDelFrame;
 82968    pFrame->v->pDelFrame = pFrame;
 82969  }
 82970  
 82971  
 82972  /*
 82973  ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
 82974  ** allocated by the OP_Program opcode in sqlite3VdbeExec().
 82975  */
 82976  SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
 82977    int i;
 82978    Mem *aMem = VdbeFrameMem(p);
 82979    VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
 82980    assert( sqlite3VdbeFrameIsValid(p) );
 82981    for(i=0; i<p->nChildCsr; i++){
 82982      sqlite3VdbeFreeCursor(p->v, apCsr[i]);
 82983    }
 82984    releaseMemArray(aMem, p->nChildMem);
 82985    sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
 82986    sqlite3DbFree(p->v->db, p);
 82987  }
 82988  
 82989  #ifndef SQLITE_OMIT_EXPLAIN
 82990  /*
 82991  ** Give a listing of the program in the virtual machine.
 82992  **
 82993  ** The interface is the same as sqlite3VdbeExec().  But instead of
 82994  ** running the code, it invokes the callback once for each instruction.
 82995  ** This feature is used to implement "EXPLAIN".
 82996  **
 82997  ** When p->explain==1, each instruction is listed.  When
 82998  ** p->explain==2, only OP_Explain instructions are listed and these
 82999  ** are shown in a different format.  p->explain==2 is used to implement
 83000  ** EXPLAIN QUERY PLAN.
 83001  ** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
 83002  ** are also shown, so that the boundaries between the main program and
 83003  ** each trigger are clear.
 83004  **
 83005  ** When p->explain==1, first the main program is listed, then each of
 83006  ** the trigger subprograms are listed one by one.
 83007  */
 83008  SQLITE_PRIVATE int sqlite3VdbeList(
 83009    Vdbe *p                   /* The VDBE */
 83010  ){
 83011    int nRow;                            /* Stop when row count reaches this */
 83012    int nSub = 0;                        /* Number of sub-vdbes seen so far */
 83013    SubProgram **apSub = 0;              /* Array of sub-vdbes */
 83014    Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
 83015    sqlite3 *db = p->db;                 /* The database connection */
 83016    int i;                               /* Loop counter */
 83017    int rc = SQLITE_OK;                  /* Return code */
 83018    Mem *pMem = &p->aMem[1];             /* First Mem of result set */
 83019    int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
 83020    Op *pOp = 0;
 83021  
 83022    assert( p->explain );
 83023    assert( p->magic==VDBE_MAGIC_RUN );
 83024    assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
 83025  
 83026    /* Even though this opcode does not use dynamic strings for
 83027    ** the result, result columns may become dynamic if the user calls
 83028    ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
 83029    */
 83030    releaseMemArray(pMem, 8);
 83031    p->pResultSet = 0;
 83032  
 83033    if( p->rc==SQLITE_NOMEM ){
 83034      /* This happens if a malloc() inside a call to sqlite3_column_text() or
 83035      ** sqlite3_column_text16() failed.  */
 83036      sqlite3OomFault(db);
 83037      return SQLITE_ERROR;
 83038    }
 83039  
 83040    /* When the number of output rows reaches nRow, that means the
 83041    ** listing has finished and sqlite3_step() should return SQLITE_DONE.
 83042    ** nRow is the sum of the number of rows in the main program, plus
 83043    ** the sum of the number of rows in all trigger subprograms encountered
 83044    ** so far.  The nRow value will increase as new trigger subprograms are
 83045    ** encountered, but p->pc will eventually catch up to nRow.
 83046    */
 83047    nRow = p->nOp;
 83048    if( bListSubprogs ){
 83049      /* The first 8 memory cells are used for the result set.  So we will
 83050      ** commandeer the 9th cell to use as storage for an array of pointers
 83051      ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
 83052      ** cells.  */
 83053      assert( p->nMem>9 );
 83054      pSub = &p->aMem[9];
 83055      if( pSub->flags&MEM_Blob ){
 83056        /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
 83057        ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
 83058        nSub = pSub->n/sizeof(Vdbe*);
 83059        apSub = (SubProgram **)pSub->z;
 83060      }
 83061      for(i=0; i<nSub; i++){
 83062        nRow += apSub[i]->nOp;
 83063      }
 83064    }
 83065  
 83066    while(1){  /* Loop exits via break */
 83067      i = p->pc++;
 83068      if( i>=nRow ){
 83069        p->rc = SQLITE_OK;
 83070        rc = SQLITE_DONE;
 83071        break;
 83072      }
 83073      if( i<p->nOp ){
 83074        /* The output line number is small enough that we are still in the
 83075        ** main program. */
 83076        pOp = &p->aOp[i];
 83077      }else{
 83078        /* We are currently listing subprograms.  Figure out which one and
 83079        ** pick up the appropriate opcode. */
 83080        int j;
 83081        i -= p->nOp;
 83082        for(j=0; i>=apSub[j]->nOp; j++){
 83083          i -= apSub[j]->nOp;
 83084        }
 83085        pOp = &apSub[j]->aOp[i];
 83086      }
 83087  
 83088      /* When an OP_Program opcode is encounter (the only opcode that has
 83089      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
 83090      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
 83091      ** has not already been seen.
 83092      */
 83093      if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
 83094        int nByte = (nSub+1)*sizeof(SubProgram*);
 83095        int j;
 83096        for(j=0; j<nSub; j++){
 83097          if( apSub[j]==pOp->p4.pProgram ) break;
 83098        }
 83099        if( j==nSub ){
 83100          p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
 83101          if( p->rc!=SQLITE_OK ){
 83102            rc = SQLITE_ERROR;
 83103            break;
 83104          }
 83105          apSub = (SubProgram **)pSub->z;
 83106          apSub[nSub++] = pOp->p4.pProgram;
 83107          pSub->flags |= MEM_Blob;
 83108          pSub->n = nSub*sizeof(SubProgram*);
 83109          nRow += pOp->p4.pProgram->nOp;
 83110        }
 83111      }
 83112      if( p->explain<2 ) break;
 83113      if( pOp->opcode==OP_Explain ) break;
 83114      if( pOp->opcode==OP_Init && p->pc>1 ) break;
 83115    }
 83116  
 83117    if( rc==SQLITE_OK ){
 83118      if( db->u1.isInterrupted ){
 83119        p->rc = SQLITE_INTERRUPT;
 83120        rc = SQLITE_ERROR;
 83121        sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
 83122      }else{
 83123        char *zP4;
 83124        if( p->explain==1 ){
 83125          pMem->flags = MEM_Int;
 83126          pMem->u.i = i;                                /* Program counter */
 83127          pMem++;
 83128      
 83129          pMem->flags = MEM_Static|MEM_Str|MEM_Term;
 83130          pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
 83131          assert( pMem->z!=0 );
 83132          pMem->n = sqlite3Strlen30(pMem->z);
 83133          pMem->enc = SQLITE_UTF8;
 83134          pMem++;
 83135        }
 83136  
 83137        pMem->flags = MEM_Int;
 83138        pMem->u.i = pOp->p1;                          /* P1 */
 83139        pMem++;
 83140  
 83141        pMem->flags = MEM_Int;
 83142        pMem->u.i = pOp->p2;                          /* P2 */
 83143        pMem++;
 83144  
 83145        pMem->flags = MEM_Int;
 83146        pMem->u.i = pOp->p3;                          /* P3 */
 83147        pMem++;
 83148  
 83149        if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
 83150          assert( p->db->mallocFailed );
 83151          return SQLITE_ERROR;
 83152        }
 83153        pMem->flags = MEM_Str|MEM_Term;
 83154        zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
 83155        if( zP4!=pMem->z ){
 83156          pMem->n = 0;
 83157          sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
 83158        }else{
 83159          assert( pMem->z!=0 );
 83160          pMem->n = sqlite3Strlen30(pMem->z);
 83161          pMem->enc = SQLITE_UTF8;
 83162        }
 83163        pMem++;
 83164  
 83165        if( p->explain==1 ){
 83166          if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
 83167            assert( p->db->mallocFailed );
 83168            return SQLITE_ERROR;
 83169          }
 83170          pMem->flags = MEM_Str|MEM_Term;
 83171          pMem->n = 2;
 83172          sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
 83173          pMem->enc = SQLITE_UTF8;
 83174          pMem++;
 83175      
 83176  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
 83177          if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
 83178            assert( p->db->mallocFailed );
 83179            return SQLITE_ERROR;
 83180          }
 83181          pMem->flags = MEM_Str|MEM_Term;
 83182          pMem->n = displayComment(pOp, zP4, pMem->z, 500);
 83183          pMem->enc = SQLITE_UTF8;
 83184  #else
 83185          pMem->flags = MEM_Null;                       /* Comment */
 83186  #endif
 83187        }
 83188  
 83189        p->nResColumn = 8 - 4*(p->explain-1);
 83190        p->pResultSet = &p->aMem[1];
 83191        p->rc = SQLITE_OK;
 83192        rc = SQLITE_ROW;
 83193      }
 83194    }
 83195    return rc;
 83196  }
 83197  #endif /* SQLITE_OMIT_EXPLAIN */
 83198  
 83199  #ifdef SQLITE_DEBUG
 83200  /*
 83201  ** Print the SQL that was used to generate a VDBE program.
 83202  */
 83203  SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
 83204    const char *z = 0;
 83205    if( p->zSql ){
 83206      z = p->zSql;
 83207    }else if( p->nOp>=1 ){
 83208      const VdbeOp *pOp = &p->aOp[0];
 83209      if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 83210        z = pOp->p4.z;
 83211        while( sqlite3Isspace(*z) ) z++;
 83212      }
 83213    }
 83214    if( z ) printf("SQL: [%s]\n", z);
 83215  }
 83216  #endif
 83217  
 83218  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
 83219  /*
 83220  ** Print an IOTRACE message showing SQL content.
 83221  */
 83222  SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
 83223    int nOp = p->nOp;
 83224    VdbeOp *pOp;
 83225    if( sqlite3IoTrace==0 ) return;
 83226    if( nOp<1 ) return;
 83227    pOp = &p->aOp[0];
 83228    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
 83229      int i, j;
 83230      char z[1000];
 83231      sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
 83232      for(i=0; sqlite3Isspace(z[i]); i++){}
 83233      for(j=0; z[i]; i++){
 83234        if( sqlite3Isspace(z[i]) ){
 83235          if( z[i-1]!=' ' ){
 83236            z[j++] = ' ';
 83237          }
 83238        }else{
 83239          z[j++] = z[i];
 83240        }
 83241      }
 83242      z[j] = 0;
 83243      sqlite3IoTrace("SQL %s\n", z);
 83244    }
 83245  }
 83246  #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
 83247  
 83248  /* An instance of this object describes bulk memory available for use
 83249  ** by subcomponents of a prepared statement.  Space is allocated out
 83250  ** of a ReusableSpace object by the allocSpace() routine below.
 83251  */
 83252  struct ReusableSpace {
 83253    u8 *pSpace;          /* Available memory */
 83254    int nFree;           /* Bytes of available memory */
 83255    int nNeeded;         /* Total bytes that could not be allocated */
 83256  };
 83257  
 83258  /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
 83259  ** from the ReusableSpace object.  Return a pointer to the allocated
 83260  ** memory on success.  If insufficient memory is available in the
 83261  ** ReusableSpace object, increase the ReusableSpace.nNeeded
 83262  ** value by the amount needed and return NULL.
 83263  **
 83264  ** If pBuf is not initially NULL, that means that the memory has already
 83265  ** been allocated by a prior call to this routine, so just return a copy
 83266  ** of pBuf and leave ReusableSpace unchanged.
 83267  **
 83268  ** This allocator is employed to repurpose unused slots at the end of the
 83269  ** opcode array of prepared state for other memory needs of the prepared
 83270  ** statement.
 83271  */
 83272  static void *allocSpace(
 83273    struct ReusableSpace *p,  /* Bulk memory available for allocation */
 83274    void *pBuf,               /* Pointer to a prior allocation */
 83275    int nByte                 /* Bytes of memory needed */
 83276  ){
 83277    assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
 83278    if( pBuf==0 ){
 83279      nByte = ROUND8(nByte);
 83280      if( nByte <= p->nFree ){
 83281        p->nFree -= nByte;
 83282        pBuf = &p->pSpace[p->nFree];
 83283      }else{
 83284        p->nNeeded += nByte;
 83285      }
 83286    }
 83287    assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
 83288    return pBuf;
 83289  }
 83290  
 83291  /*
 83292  ** Rewind the VDBE back to the beginning in preparation for
 83293  ** running it.
 83294  */
 83295  SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
 83296  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 83297    int i;
 83298  #endif
 83299    assert( p!=0 );
 83300    assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
 83301  
 83302    /* There should be at least one opcode.
 83303    */
 83304    assert( p->nOp>0 );
 83305  
 83306    /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
 83307    p->magic = VDBE_MAGIC_RUN;
 83308  
 83309  #ifdef SQLITE_DEBUG
 83310    for(i=0; i<p->nMem; i++){
 83311      assert( p->aMem[i].db==p->db );
 83312    }
 83313  #endif
 83314    p->pc = -1;
 83315    p->rc = SQLITE_OK;
 83316    p->errorAction = OE_Abort;
 83317    p->nChange = 0;
 83318    p->cacheCtr = 1;
 83319    p->minWriteFileFormat = 255;
 83320    p->iStatement = 0;
 83321    p->nFkConstraint = 0;
 83322  #ifdef VDBE_PROFILE
 83323    for(i=0; i<p->nOp; i++){
 83324      p->aOp[i].cnt = 0;
 83325      p->aOp[i].cycles = 0;
 83326    }
 83327  #endif
 83328  }
 83329  
 83330  /*
 83331  ** Prepare a virtual machine for execution for the first time after
 83332  ** creating the virtual machine.  This involves things such
 83333  ** as allocating registers and initializing the program counter.
 83334  ** After the VDBE has be prepped, it can be executed by one or more
 83335  ** calls to sqlite3VdbeExec().  
 83336  **
 83337  ** This function may be called exactly once on each virtual machine.
 83338  ** After this routine is called the VM has been "packaged" and is ready
 83339  ** to run.  After this routine is called, further calls to 
 83340  ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
 83341  ** the Vdbe from the Parse object that helped generate it so that the
 83342  ** the Vdbe becomes an independent entity and the Parse object can be
 83343  ** destroyed.
 83344  **
 83345  ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
 83346  ** to its initial state after it has been run.
 83347  */
 83348  SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 83349    Vdbe *p,                       /* The VDBE */
 83350    Parse *pParse                  /* Parsing context */
 83351  ){
 83352    sqlite3 *db;                   /* The database connection */
 83353    int nVar;                      /* Number of parameters */
 83354    int nMem;                      /* Number of VM memory registers */
 83355    int nCursor;                   /* Number of cursors required */
 83356    int nArg;                      /* Number of arguments in subprograms */
 83357    int n;                         /* Loop counter */
 83358    struct ReusableSpace x;        /* Reusable bulk memory */
 83359  
 83360    assert( p!=0 );
 83361    assert( p->nOp>0 );
 83362    assert( pParse!=0 );
 83363    assert( p->magic==VDBE_MAGIC_INIT );
 83364    assert( pParse==p->pParse );
 83365    db = p->db;
 83366    assert( db->mallocFailed==0 );
 83367    nVar = pParse->nVar;
 83368    nMem = pParse->nMem;
 83369    nCursor = pParse->nTab;
 83370    nArg = pParse->nMaxArg;
 83371    
 83372    /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
 83373    ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
 83374    ** space at the end of aMem[] for cursors 1 and greater.
 83375    ** See also: allocateCursor().
 83376    */
 83377    nMem += nCursor;
 83378    if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
 83379  
 83380    /* Figure out how much reusable memory is available at the end of the
 83381    ** opcode array.  This extra memory will be reallocated for other elements
 83382    ** of the prepared statement.
 83383    */
 83384    n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
 83385    x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
 83386    assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
 83387    x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
 83388    assert( x.nFree>=0 );
 83389    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
 83390  
 83391    resolveP2Values(p, &nArg);
 83392    p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
 83393    if( pParse->explain && nMem<10 ){
 83394      nMem = 10;
 83395    }
 83396    p->expired = 0;
 83397  
 83398    /* Memory for registers, parameters, cursor, etc, is allocated in one or two
 83399    ** passes.  On the first pass, we try to reuse unused memory at the 
 83400    ** end of the opcode array.  If we are unable to satisfy all memory
 83401    ** requirements by reusing the opcode array tail, then the second
 83402    ** pass will fill in the remainder using a fresh memory allocation.  
 83403    **
 83404    ** This two-pass approach that reuses as much memory as possible from
 83405    ** the leftover memory at the end of the opcode array.  This can significantly
 83406    ** reduce the amount of memory held by a prepared statement.
 83407    */
 83408    x.nNeeded = 0;
 83409    p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
 83410    p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
 83411    p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
 83412    p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
 83413  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 83414    p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
 83415  #endif
 83416    if( x.nNeeded ){
 83417      x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
 83418      x.nFree = x.nNeeded;
 83419      if( !db->mallocFailed ){
 83420        p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
 83421        p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
 83422        p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
 83423        p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
 83424  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 83425        p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
 83426  #endif
 83427      }
 83428    }
 83429  
 83430    p->pVList = pParse->pVList;
 83431    pParse->pVList =  0;
 83432    p->explain = pParse->explain;
 83433    if( db->mallocFailed ){
 83434      p->nVar = 0;
 83435      p->nCursor = 0;
 83436      p->nMem = 0;
 83437    }else{
 83438      p->nCursor = nCursor;
 83439      p->nVar = (ynVar)nVar;
 83440      initMemArray(p->aVar, nVar, db, MEM_Null);
 83441      p->nMem = nMem;
 83442      initMemArray(p->aMem, nMem, db, MEM_Undefined);
 83443      memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
 83444  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 83445      memset(p->anExec, 0, p->nOp*sizeof(i64));
 83446  #endif
 83447    }
 83448    sqlite3VdbeRewind(p);
 83449  }
 83450  
 83451  /*
 83452  ** Close a VDBE cursor and release all the resources that cursor 
 83453  ** happens to hold.
 83454  */
 83455  SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
 83456    if( pCx==0 ){
 83457      return;
 83458    }
 83459    assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
 83460    switch( pCx->eCurType ){
 83461      case CURTYPE_SORTER: {
 83462        sqlite3VdbeSorterClose(p->db, pCx);
 83463        break;
 83464      }
 83465      case CURTYPE_BTREE: {
 83466        if( pCx->isEphemeral ){
 83467          if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
 83468          /* The pCx->pCursor will be close automatically, if it exists, by
 83469          ** the call above. */
 83470        }else{
 83471          assert( pCx->uc.pCursor!=0 );
 83472          sqlite3BtreeCloseCursor(pCx->uc.pCursor);
 83473        }
 83474        break;
 83475      }
 83476  #ifndef SQLITE_OMIT_VIRTUALTABLE
 83477      case CURTYPE_VTAB: {
 83478        sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
 83479        const sqlite3_module *pModule = pVCur->pVtab->pModule;
 83480        assert( pVCur->pVtab->nRef>0 );
 83481        pVCur->pVtab->nRef--;
 83482        pModule->xClose(pVCur);
 83483        break;
 83484      }
 83485  #endif
 83486    }
 83487  }
 83488  
 83489  /*
 83490  ** Close all cursors in the current frame.
 83491  */
 83492  static void closeCursorsInFrame(Vdbe *p){
 83493    if( p->apCsr ){
 83494      int i;
 83495      for(i=0; i<p->nCursor; i++){
 83496        VdbeCursor *pC = p->apCsr[i];
 83497        if( pC ){
 83498          sqlite3VdbeFreeCursor(p, pC);
 83499          p->apCsr[i] = 0;
 83500        }
 83501      }
 83502    }
 83503  }
 83504  
 83505  /*
 83506  ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
 83507  ** is used, for example, when a trigger sub-program is halted to restore
 83508  ** control to the main program.
 83509  */
 83510  SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
 83511    Vdbe *v = pFrame->v;
 83512    closeCursorsInFrame(v);
 83513  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 83514    v->anExec = pFrame->anExec;
 83515  #endif
 83516    v->aOp = pFrame->aOp;
 83517    v->nOp = pFrame->nOp;
 83518    v->aMem = pFrame->aMem;
 83519    v->nMem = pFrame->nMem;
 83520    v->apCsr = pFrame->apCsr;
 83521    v->nCursor = pFrame->nCursor;
 83522    v->db->lastRowid = pFrame->lastRowid;
 83523    v->nChange = pFrame->nChange;
 83524    v->db->nChange = pFrame->nDbChange;
 83525    sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
 83526    v->pAuxData = pFrame->pAuxData;
 83527    pFrame->pAuxData = 0;
 83528    return pFrame->pc;
 83529  }
 83530  
 83531  /*
 83532  ** Close all cursors.
 83533  **
 83534  ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
 83535  ** cell array. This is necessary as the memory cell array may contain
 83536  ** pointers to VdbeFrame objects, which may in turn contain pointers to
 83537  ** open cursors.
 83538  */
 83539  static void closeAllCursors(Vdbe *p){
 83540    if( p->pFrame ){
 83541      VdbeFrame *pFrame;
 83542      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 83543      sqlite3VdbeFrameRestore(pFrame);
 83544      p->pFrame = 0;
 83545      p->nFrame = 0;
 83546    }
 83547    assert( p->nFrame==0 );
 83548    closeCursorsInFrame(p);
 83549    if( p->aMem ){
 83550      releaseMemArray(p->aMem, p->nMem);
 83551    }
 83552    while( p->pDelFrame ){
 83553      VdbeFrame *pDel = p->pDelFrame;
 83554      p->pDelFrame = pDel->pParent;
 83555      sqlite3VdbeFrameDelete(pDel);
 83556    }
 83557  
 83558    /* Delete any auxdata allocations made by the VM */
 83559    if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
 83560    assert( p->pAuxData==0 );
 83561  }
 83562  
 83563  /*
 83564  ** Set the number of result columns that will be returned by this SQL
 83565  ** statement. This is now set at compile time, rather than during
 83566  ** execution of the vdbe program so that sqlite3_column_count() can
 83567  ** be called on an SQL statement before sqlite3_step().
 83568  */
 83569  SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
 83570    int n;
 83571    sqlite3 *db = p->db;
 83572  
 83573    if( p->nResColumn ){
 83574      releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 83575      sqlite3DbFree(db, p->aColName);
 83576    }
 83577    n = nResColumn*COLNAME_N;
 83578    p->nResColumn = (u16)nResColumn;
 83579    p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
 83580    if( p->aColName==0 ) return;
 83581    initMemArray(p->aColName, n, db, MEM_Null);
 83582  }
 83583  
 83584  /*
 83585  ** Set the name of the idx'th column to be returned by the SQL statement.
 83586  ** zName must be a pointer to a nul terminated string.
 83587  **
 83588  ** This call must be made after a call to sqlite3VdbeSetNumCols().
 83589  **
 83590  ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
 83591  ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
 83592  ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
 83593  */
 83594  SQLITE_PRIVATE int sqlite3VdbeSetColName(
 83595    Vdbe *p,                         /* Vdbe being configured */
 83596    int idx,                         /* Index of column zName applies to */
 83597    int var,                         /* One of the COLNAME_* constants */
 83598    const char *zName,               /* Pointer to buffer containing name */
 83599    void (*xDel)(void*)              /* Memory management strategy for zName */
 83600  ){
 83601    int rc;
 83602    Mem *pColName;
 83603    assert( idx<p->nResColumn );
 83604    assert( var<COLNAME_N );
 83605    if( p->db->mallocFailed ){
 83606      assert( !zName || xDel!=SQLITE_DYNAMIC );
 83607      return SQLITE_NOMEM_BKPT;
 83608    }
 83609    assert( p->aColName!=0 );
 83610    pColName = &(p->aColName[idx+var*p->nResColumn]);
 83611    rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
 83612    assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
 83613    return rc;
 83614  }
 83615  
 83616  /*
 83617  ** A read or write transaction may or may not be active on database handle
 83618  ** db. If a transaction is active, commit it. If there is a
 83619  ** write-transaction spanning more than one database file, this routine
 83620  ** takes care of the master journal trickery.
 83621  */
 83622  static int vdbeCommit(sqlite3 *db, Vdbe *p){
 83623    int i;
 83624    int nTrans = 0;  /* Number of databases with an active write-transaction
 83625                     ** that are candidates for a two-phase commit using a
 83626                     ** master-journal */
 83627    int rc = SQLITE_OK;
 83628    int needXcommit = 0;
 83629  
 83630  #ifdef SQLITE_OMIT_VIRTUALTABLE
 83631    /* With this option, sqlite3VtabSync() is defined to be simply 
 83632    ** SQLITE_OK so p is not used. 
 83633    */
 83634    UNUSED_PARAMETER(p);
 83635  #endif
 83636  
 83637    /* Before doing anything else, call the xSync() callback for any
 83638    ** virtual module tables written in this transaction. This has to
 83639    ** be done before determining whether a master journal file is 
 83640    ** required, as an xSync() callback may add an attached database
 83641    ** to the transaction.
 83642    */
 83643    rc = sqlite3VtabSync(db, p);
 83644  
 83645    /* This loop determines (a) if the commit hook should be invoked and
 83646    ** (b) how many database files have open write transactions, not 
 83647    ** including the temp database. (b) is important because if more than 
 83648    ** one database file has an open write transaction, a master journal
 83649    ** file is required for an atomic commit.
 83650    */ 
 83651    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 83652      Btree *pBt = db->aDb[i].pBt;
 83653      if( sqlite3BtreeIsInTrans(pBt) ){
 83654        /* Whether or not a database might need a master journal depends upon
 83655        ** its journal mode (among other things).  This matrix determines which
 83656        ** journal modes use a master journal and which do not */
 83657        static const u8 aMJNeeded[] = {
 83658          /* DELETE   */  1,
 83659          /* PERSIST   */ 1,
 83660          /* OFF       */ 0,
 83661          /* TRUNCATE  */ 1,
 83662          /* MEMORY    */ 0,
 83663          /* WAL       */ 0
 83664        };
 83665        Pager *pPager;   /* Pager associated with pBt */
 83666        needXcommit = 1;
 83667        sqlite3BtreeEnter(pBt);
 83668        pPager = sqlite3BtreePager(pBt);
 83669        if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
 83670         && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
 83671         && sqlite3PagerIsMemdb(pPager)==0
 83672        ){ 
 83673          assert( i!=1 );
 83674          nTrans++;
 83675        }
 83676        rc = sqlite3PagerExclusiveLock(pPager);
 83677        sqlite3BtreeLeave(pBt);
 83678      }
 83679    }
 83680    if( rc!=SQLITE_OK ){
 83681      return rc;
 83682    }
 83683  
 83684    /* If there are any write-transactions at all, invoke the commit hook */
 83685    if( needXcommit && db->xCommitCallback ){
 83686      rc = db->xCommitCallback(db->pCommitArg);
 83687      if( rc ){
 83688        return SQLITE_CONSTRAINT_COMMITHOOK;
 83689      }
 83690    }
 83691  
 83692    /* The simple case - no more than one database file (not counting the
 83693    ** TEMP database) has a transaction active.   There is no need for the
 83694    ** master-journal.
 83695    **
 83696    ** If the return value of sqlite3BtreeGetFilename() is a zero length
 83697    ** string, it means the main database is :memory: or a temp file.  In 
 83698    ** that case we do not support atomic multi-file commits, so use the 
 83699    ** simple case then too.
 83700    */
 83701    if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
 83702     || nTrans<=1
 83703    ){
 83704      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 83705        Btree *pBt = db->aDb[i].pBt;
 83706        if( pBt ){
 83707          rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
 83708        }
 83709      }
 83710  
 83711      /* Do the commit only if all databases successfully complete phase 1. 
 83712      ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
 83713      ** IO error while deleting or truncating a journal file. It is unlikely,
 83714      ** but could happen. In this case abandon processing and return the error.
 83715      */
 83716      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
 83717        Btree *pBt = db->aDb[i].pBt;
 83718        if( pBt ){
 83719          rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
 83720        }
 83721      }
 83722      if( rc==SQLITE_OK ){
 83723        sqlite3VtabCommit(db);
 83724      }
 83725    }
 83726  
 83727    /* The complex case - There is a multi-file write-transaction active.
 83728    ** This requires a master journal file to ensure the transaction is
 83729    ** committed atomically.
 83730    */
 83731  #ifndef SQLITE_OMIT_DISKIO
 83732    else{
 83733      sqlite3_vfs *pVfs = db->pVfs;
 83734      char *zMaster = 0;   /* File-name for the master journal */
 83735      char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
 83736      sqlite3_file *pMaster = 0;
 83737      i64 offset = 0;
 83738      int res;
 83739      int retryCount = 0;
 83740      int nMainFile;
 83741  
 83742      /* Select a master journal file name */
 83743      nMainFile = sqlite3Strlen30(zMainFile);
 83744      zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
 83745      if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
 83746      do {
 83747        u32 iRandom;
 83748        if( retryCount ){
 83749          if( retryCount>100 ){
 83750            sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
 83751            sqlite3OsDelete(pVfs, zMaster, 0);
 83752            break;
 83753          }else if( retryCount==1 ){
 83754            sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
 83755          }
 83756        }
 83757        retryCount++;
 83758        sqlite3_randomness(sizeof(iRandom), &iRandom);
 83759        sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
 83760                                 (iRandom>>8)&0xffffff, iRandom&0xff);
 83761        /* The antipenultimate character of the master journal name must
 83762        ** be "9" to avoid name collisions when using 8+3 filenames. */
 83763        assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
 83764        sqlite3FileSuffix3(zMainFile, zMaster);
 83765        rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
 83766      }while( rc==SQLITE_OK && res );
 83767      if( rc==SQLITE_OK ){
 83768        /* Open the master journal. */
 83769        rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
 83770            SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
 83771            SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
 83772        );
 83773      }
 83774      if( rc!=SQLITE_OK ){
 83775        sqlite3DbFree(db, zMaster);
 83776        return rc;
 83777      }
 83778   
 83779      /* Write the name of each database file in the transaction into the new
 83780      ** master journal file. If an error occurs at this point close
 83781      ** and delete the master journal file. All the individual journal files
 83782      ** still have 'null' as the master journal pointer, so they will roll
 83783      ** back independently if a failure occurs.
 83784      */
 83785      for(i=0; i<db->nDb; i++){
 83786        Btree *pBt = db->aDb[i].pBt;
 83787        if( sqlite3BtreeIsInTrans(pBt) ){
 83788          char const *zFile = sqlite3BtreeGetJournalname(pBt);
 83789          if( zFile==0 ){
 83790            continue;  /* Ignore TEMP and :memory: databases */
 83791          }
 83792          assert( zFile[0]!=0 );
 83793          rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
 83794          offset += sqlite3Strlen30(zFile)+1;
 83795          if( rc!=SQLITE_OK ){
 83796            sqlite3OsCloseFree(pMaster);
 83797            sqlite3OsDelete(pVfs, zMaster, 0);
 83798            sqlite3DbFree(db, zMaster);
 83799            return rc;
 83800          }
 83801        }
 83802      }
 83803  
 83804      /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
 83805      ** flag is set this is not required.
 83806      */
 83807      if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
 83808       && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
 83809      ){
 83810        sqlite3OsCloseFree(pMaster);
 83811        sqlite3OsDelete(pVfs, zMaster, 0);
 83812        sqlite3DbFree(db, zMaster);
 83813        return rc;
 83814      }
 83815  
 83816      /* Sync all the db files involved in the transaction. The same call
 83817      ** sets the master journal pointer in each individual journal. If
 83818      ** an error occurs here, do not delete the master journal file.
 83819      **
 83820      ** If the error occurs during the first call to
 83821      ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
 83822      ** master journal file will be orphaned. But we cannot delete it,
 83823      ** in case the master journal file name was written into the journal
 83824      ** file before the failure occurred.
 83825      */
 83826      for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
 83827        Btree *pBt = db->aDb[i].pBt;
 83828        if( pBt ){
 83829          rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
 83830        }
 83831      }
 83832      sqlite3OsCloseFree(pMaster);
 83833      assert( rc!=SQLITE_BUSY );
 83834      if( rc!=SQLITE_OK ){
 83835        sqlite3DbFree(db, zMaster);
 83836        return rc;
 83837      }
 83838  
 83839      /* Delete the master journal file. This commits the transaction. After
 83840      ** doing this the directory is synced again before any individual
 83841      ** transaction files are deleted.
 83842      */
 83843      rc = sqlite3OsDelete(pVfs, zMaster, 1);
 83844      sqlite3DbFree(db, zMaster);
 83845      zMaster = 0;
 83846      if( rc ){
 83847        return rc;
 83848      }
 83849  
 83850      /* All files and directories have already been synced, so the following
 83851      ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
 83852      ** deleting or truncating journals. If something goes wrong while
 83853      ** this is happening we don't really care. The integrity of the
 83854      ** transaction is already guaranteed, but some stray 'cold' journals
 83855      ** may be lying around. Returning an error code won't help matters.
 83856      */
 83857      disable_simulated_io_errors();
 83858      sqlite3BeginBenignMalloc();
 83859      for(i=0; i<db->nDb; i++){ 
 83860        Btree *pBt = db->aDb[i].pBt;
 83861        if( pBt ){
 83862          sqlite3BtreeCommitPhaseTwo(pBt, 1);
 83863        }
 83864      }
 83865      sqlite3EndBenignMalloc();
 83866      enable_simulated_io_errors();
 83867  
 83868      sqlite3VtabCommit(db);
 83869    }
 83870  #endif
 83871  
 83872    return rc;
 83873  }
 83874  
 83875  /* 
 83876  ** This routine checks that the sqlite3.nVdbeActive count variable
 83877  ** matches the number of vdbe's in the list sqlite3.pVdbe that are
 83878  ** currently active. An assertion fails if the two counts do not match.
 83879  ** This is an internal self-check only - it is not an essential processing
 83880  ** step.
 83881  **
 83882  ** This is a no-op if NDEBUG is defined.
 83883  */
 83884  #ifndef NDEBUG
 83885  static void checkActiveVdbeCnt(sqlite3 *db){
 83886    Vdbe *p;
 83887    int cnt = 0;
 83888    int nWrite = 0;
 83889    int nRead = 0;
 83890    p = db->pVdbe;
 83891    while( p ){
 83892      if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
 83893        cnt++;
 83894        if( p->readOnly==0 ) nWrite++;
 83895        if( p->bIsReader ) nRead++;
 83896      }
 83897      p = p->pNext;
 83898    }
 83899    assert( cnt==db->nVdbeActive );
 83900    assert( nWrite==db->nVdbeWrite );
 83901    assert( nRead==db->nVdbeRead );
 83902  }
 83903  #else
 83904  #define checkActiveVdbeCnt(x)
 83905  #endif
 83906  
 83907  /*
 83908  ** If the Vdbe passed as the first argument opened a statement-transaction,
 83909  ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
 83910  ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
 83911  ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
 83912  ** statement transaction is committed.
 83913  **
 83914  ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
 83915  ** Otherwise SQLITE_OK.
 83916  */
 83917  static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
 83918    sqlite3 *const db = p->db;
 83919    int rc = SQLITE_OK;
 83920    int i;
 83921    const int iSavepoint = p->iStatement-1;
 83922  
 83923    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
 83924    assert( db->nStatement>0 );
 83925    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
 83926  
 83927    for(i=0; i<db->nDb; i++){ 
 83928      int rc2 = SQLITE_OK;
 83929      Btree *pBt = db->aDb[i].pBt;
 83930      if( pBt ){
 83931        if( eOp==SAVEPOINT_ROLLBACK ){
 83932          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
 83933        }
 83934        if( rc2==SQLITE_OK ){
 83935          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
 83936        }
 83937        if( rc==SQLITE_OK ){
 83938          rc = rc2;
 83939        }
 83940      }
 83941    }
 83942    db->nStatement--;
 83943    p->iStatement = 0;
 83944  
 83945    if( rc==SQLITE_OK ){
 83946      if( eOp==SAVEPOINT_ROLLBACK ){
 83947        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
 83948      }
 83949      if( rc==SQLITE_OK ){
 83950        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
 83951      }
 83952    }
 83953  
 83954    /* If the statement transaction is being rolled back, also restore the 
 83955    ** database handles deferred constraint counter to the value it had when 
 83956    ** the statement transaction was opened.  */
 83957    if( eOp==SAVEPOINT_ROLLBACK ){
 83958      db->nDeferredCons = p->nStmtDefCons;
 83959      db->nDeferredImmCons = p->nStmtDefImmCons;
 83960    }
 83961    return rc;
 83962  }
 83963  SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
 83964    if( p->db->nStatement && p->iStatement ){
 83965      return vdbeCloseStatement(p, eOp);
 83966    }
 83967    return SQLITE_OK;
 83968  }
 83969  
 83970  
 83971  /*
 83972  ** This function is called when a transaction opened by the database 
 83973  ** handle associated with the VM passed as an argument is about to be 
 83974  ** committed. If there are outstanding deferred foreign key constraint
 83975  ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
 83976  **
 83977  ** If there are outstanding FK violations and this function returns 
 83978  ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
 83979  ** and write an error message to it. Then return SQLITE_ERROR.
 83980  */
 83981  #ifndef SQLITE_OMIT_FOREIGN_KEY
 83982  SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
 83983    sqlite3 *db = p->db;
 83984    if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
 83985     || (!deferred && p->nFkConstraint>0) 
 83986    ){
 83987      p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 83988      p->errorAction = OE_Abort;
 83989      sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
 83990      return SQLITE_ERROR;
 83991    }
 83992    return SQLITE_OK;
 83993  }
 83994  #endif
 83995  
 83996  /*
 83997  ** This routine is called the when a VDBE tries to halt.  If the VDBE
 83998  ** has made changes and is in autocommit mode, then commit those
 83999  ** changes.  If a rollback is needed, then do the rollback.
 84000  **
 84001  ** This routine is the only way to move the state of a VM from
 84002  ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
 84003  ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
 84004  **
 84005  ** Return an error code.  If the commit could not complete because of
 84006  ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
 84007  ** means the close did not happen and needs to be repeated.
 84008  */
 84009  SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
 84010    int rc;                         /* Used to store transient return codes */
 84011    sqlite3 *db = p->db;
 84012  
 84013    /* This function contains the logic that determines if a statement or
 84014    ** transaction will be committed or rolled back as a result of the
 84015    ** execution of this virtual machine. 
 84016    **
 84017    ** If any of the following errors occur:
 84018    **
 84019    **     SQLITE_NOMEM
 84020    **     SQLITE_IOERR
 84021    **     SQLITE_FULL
 84022    **     SQLITE_INTERRUPT
 84023    **
 84024    ** Then the internal cache might have been left in an inconsistent
 84025    ** state.  We need to rollback the statement transaction, if there is
 84026    ** one, or the complete transaction if there is no statement transaction.
 84027    */
 84028  
 84029    if( p->magic!=VDBE_MAGIC_RUN ){
 84030      return SQLITE_OK;
 84031    }
 84032    if( db->mallocFailed ){
 84033      p->rc = SQLITE_NOMEM_BKPT;
 84034    }
 84035    closeAllCursors(p);
 84036    checkActiveVdbeCnt(db);
 84037  
 84038    /* No commit or rollback needed if the program never started or if the
 84039    ** SQL statement does not read or write a database file.  */
 84040    if( p->pc>=0 && p->bIsReader ){
 84041      int mrc;   /* Primary error code from p->rc */
 84042      int eStatementOp = 0;
 84043      int isSpecialError;            /* Set to true if a 'special' error */
 84044  
 84045      /* Lock all btrees used by the statement */
 84046      sqlite3VdbeEnter(p);
 84047  
 84048      /* Check for one of the special errors */
 84049      mrc = p->rc & 0xff;
 84050      isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
 84051                       || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
 84052      if( isSpecialError ){
 84053        /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
 84054        ** no rollback is necessary. Otherwise, at least a savepoint 
 84055        ** transaction must be rolled back to restore the database to a 
 84056        ** consistent state.
 84057        **
 84058        ** Even if the statement is read-only, it is important to perform
 84059        ** a statement or transaction rollback operation. If the error 
 84060        ** occurred while writing to the journal, sub-journal or database
 84061        ** file as part of an effort to free up cache space (see function
 84062        ** pagerStress() in pager.c), the rollback is required to restore 
 84063        ** the pager to a consistent state.
 84064        */
 84065        if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
 84066          if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
 84067            eStatementOp = SAVEPOINT_ROLLBACK;
 84068          }else{
 84069            /* We are forced to roll back the active transaction. Before doing
 84070            ** so, abort any other statements this handle currently has active.
 84071            */
 84072            sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 84073            sqlite3CloseSavepoints(db);
 84074            db->autoCommit = 1;
 84075            p->nChange = 0;
 84076          }
 84077        }
 84078      }
 84079  
 84080      /* Check for immediate foreign key violations. */
 84081      if( p->rc==SQLITE_OK ){
 84082        sqlite3VdbeCheckFk(p, 0);
 84083      }
 84084    
 84085      /* If the auto-commit flag is set and this is the only active writer 
 84086      ** VM, then we do either a commit or rollback of the current transaction. 
 84087      **
 84088      ** Note: This block also runs if one of the special errors handled 
 84089      ** above has occurred. 
 84090      */
 84091      if( !sqlite3VtabInSync(db) 
 84092       && db->autoCommit 
 84093       && db->nVdbeWrite==(p->readOnly==0) 
 84094      ){
 84095        if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
 84096          rc = sqlite3VdbeCheckFk(p, 1);
 84097          if( rc!=SQLITE_OK ){
 84098            if( NEVER(p->readOnly) ){
 84099              sqlite3VdbeLeave(p);
 84100              return SQLITE_ERROR;
 84101            }
 84102            rc = SQLITE_CONSTRAINT_FOREIGNKEY;
 84103          }else{ 
 84104            /* The auto-commit flag is true, the vdbe program was successful 
 84105            ** or hit an 'OR FAIL' constraint and there are no deferred foreign
 84106            ** key constraints to hold up the transaction. This means a commit 
 84107            ** is required. */
 84108            rc = vdbeCommit(db, p);
 84109          }
 84110          if( rc==SQLITE_BUSY && p->readOnly ){
 84111            sqlite3VdbeLeave(p);
 84112            return SQLITE_BUSY;
 84113          }else if( rc!=SQLITE_OK ){
 84114            p->rc = rc;
 84115            sqlite3RollbackAll(db, SQLITE_OK);
 84116            p->nChange = 0;
 84117          }else{
 84118            db->nDeferredCons = 0;
 84119            db->nDeferredImmCons = 0;
 84120            db->flags &= ~(u64)SQLITE_DeferFKs;
 84121            sqlite3CommitInternalChanges(db);
 84122          }
 84123        }else{
 84124          sqlite3RollbackAll(db, SQLITE_OK);
 84125          p->nChange = 0;
 84126        }
 84127        db->nStatement = 0;
 84128      }else if( eStatementOp==0 ){
 84129        if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
 84130          eStatementOp = SAVEPOINT_RELEASE;
 84131        }else if( p->errorAction==OE_Abort ){
 84132          eStatementOp = SAVEPOINT_ROLLBACK;
 84133        }else{
 84134          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 84135          sqlite3CloseSavepoints(db);
 84136          db->autoCommit = 1;
 84137          p->nChange = 0;
 84138        }
 84139      }
 84140    
 84141      /* If eStatementOp is non-zero, then a statement transaction needs to
 84142      ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
 84143      ** do so. If this operation returns an error, and the current statement
 84144      ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
 84145      ** current statement error code.
 84146      */
 84147      if( eStatementOp ){
 84148        rc = sqlite3VdbeCloseStatement(p, eStatementOp);
 84149        if( rc ){
 84150          if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
 84151            p->rc = rc;
 84152            sqlite3DbFree(db, p->zErrMsg);
 84153            p->zErrMsg = 0;
 84154          }
 84155          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 84156          sqlite3CloseSavepoints(db);
 84157          db->autoCommit = 1;
 84158          p->nChange = 0;
 84159        }
 84160      }
 84161    
 84162      /* If this was an INSERT, UPDATE or DELETE and no statement transaction
 84163      ** has been rolled back, update the database connection change-counter. 
 84164      */
 84165      if( p->changeCntOn ){
 84166        if( eStatementOp!=SAVEPOINT_ROLLBACK ){
 84167          sqlite3VdbeSetChanges(db, p->nChange);
 84168        }else{
 84169          sqlite3VdbeSetChanges(db, 0);
 84170        }
 84171        p->nChange = 0;
 84172      }
 84173  
 84174      /* Release the locks */
 84175      sqlite3VdbeLeave(p);
 84176    }
 84177  
 84178    /* We have successfully halted and closed the VM.  Record this fact. */
 84179    if( p->pc>=0 ){
 84180      db->nVdbeActive--;
 84181      if( !p->readOnly ) db->nVdbeWrite--;
 84182      if( p->bIsReader ) db->nVdbeRead--;
 84183      assert( db->nVdbeActive>=db->nVdbeRead );
 84184      assert( db->nVdbeRead>=db->nVdbeWrite );
 84185      assert( db->nVdbeWrite>=0 );
 84186    }
 84187    p->magic = VDBE_MAGIC_HALT;
 84188    checkActiveVdbeCnt(db);
 84189    if( db->mallocFailed ){
 84190      p->rc = SQLITE_NOMEM_BKPT;
 84191    }
 84192  
 84193    /* If the auto-commit flag is set to true, then any locks that were held
 84194    ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
 84195    ** to invoke any required unlock-notify callbacks.
 84196    */
 84197    if( db->autoCommit ){
 84198      sqlite3ConnectionUnlocked(db);
 84199    }
 84200  
 84201    assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
 84202    return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
 84203  }
 84204  
 84205  
 84206  /*
 84207  ** Each VDBE holds the result of the most recent sqlite3_step() call
 84208  ** in p->rc.  This routine sets that result back to SQLITE_OK.
 84209  */
 84210  SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
 84211    p->rc = SQLITE_OK;
 84212  }
 84213  
 84214  /*
 84215  ** Copy the error code and error message belonging to the VDBE passed
 84216  ** as the first argument to its database handle (so that they will be 
 84217  ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
 84218  **
 84219  ** This function does not clear the VDBE error code or message, just
 84220  ** copies them to the database handle.
 84221  */
 84222  SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
 84223    sqlite3 *db = p->db;
 84224    int rc = p->rc;
 84225    if( p->zErrMsg ){
 84226      db->bBenignMalloc++;
 84227      sqlite3BeginBenignMalloc();
 84228      if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
 84229      sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
 84230      sqlite3EndBenignMalloc();
 84231      db->bBenignMalloc--;
 84232    }else if( db->pErr ){
 84233      sqlite3ValueSetNull(db->pErr);
 84234    }
 84235    db->errCode = rc;
 84236    return rc;
 84237  }
 84238  
 84239  #ifdef SQLITE_ENABLE_SQLLOG
 84240  /*
 84241  ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
 84242  ** invoke it.
 84243  */
 84244  static void vdbeInvokeSqllog(Vdbe *v){
 84245    if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
 84246      char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
 84247      assert( v->db->init.busy==0 );
 84248      if( zExpanded ){
 84249        sqlite3GlobalConfig.xSqllog(
 84250            sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
 84251        );
 84252        sqlite3DbFree(v->db, zExpanded);
 84253      }
 84254    }
 84255  }
 84256  #else
 84257  # define vdbeInvokeSqllog(x)
 84258  #endif
 84259  
 84260  /*
 84261  ** Clean up a VDBE after execution but do not delete the VDBE just yet.
 84262  ** Write any error messages into *pzErrMsg.  Return the result code.
 84263  **
 84264  ** After this routine is run, the VDBE should be ready to be executed
 84265  ** again.
 84266  **
 84267  ** To look at it another way, this routine resets the state of the
 84268  ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
 84269  ** VDBE_MAGIC_INIT.
 84270  */
 84271  SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
 84272  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 84273    int i;
 84274  #endif
 84275  
 84276    sqlite3 *db;
 84277    db = p->db;
 84278  
 84279    /* If the VM did not run to completion or if it encountered an
 84280    ** error, then it might not have been halted properly.  So halt
 84281    ** it now.
 84282    */
 84283    sqlite3VdbeHalt(p);
 84284  
 84285    /* If the VDBE has been run even partially, then transfer the error code
 84286    ** and error message from the VDBE into the main database structure.  But
 84287    ** if the VDBE has just been set to run but has not actually executed any
 84288    ** instructions yet, leave the main database error information unchanged.
 84289    */
 84290    if( p->pc>=0 ){
 84291      vdbeInvokeSqllog(p);
 84292      sqlite3VdbeTransferError(p);
 84293      if( p->runOnlyOnce ) p->expired = 1;
 84294    }else if( p->rc && p->expired ){
 84295      /* The expired flag was set on the VDBE before the first call
 84296      ** to sqlite3_step(). For consistency (since sqlite3_step() was
 84297      ** called), set the database error in this case as well.
 84298      */
 84299      sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
 84300    }
 84301  
 84302    /* Reset register contents and reclaim error message memory.
 84303    */
 84304  #ifdef SQLITE_DEBUG
 84305    /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
 84306    ** Vdbe.aMem[] arrays have already been cleaned up.  */
 84307    if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
 84308    if( p->aMem ){
 84309      for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
 84310    }
 84311  #endif
 84312    sqlite3DbFree(db, p->zErrMsg);
 84313    p->zErrMsg = 0;
 84314    p->pResultSet = 0;
 84315  #ifdef SQLITE_DEBUG
 84316    p->nWrite = 0;
 84317  #endif
 84318  
 84319    /* Save profiling information from this VDBE run.
 84320    */
 84321  #ifdef VDBE_PROFILE
 84322    {
 84323      FILE *out = fopen("vdbe_profile.out", "a");
 84324      if( out ){
 84325        fprintf(out, "---- ");
 84326        for(i=0; i<p->nOp; i++){
 84327          fprintf(out, "%02x", p->aOp[i].opcode);
 84328        }
 84329        fprintf(out, "\n");
 84330        if( p->zSql ){
 84331          char c, pc = 0;
 84332          fprintf(out, "-- ");
 84333          for(i=0; (c = p->zSql[i])!=0; i++){
 84334            if( pc=='\n' ) fprintf(out, "-- ");
 84335            putc(c, out);
 84336            pc = c;
 84337          }
 84338          if( pc!='\n' ) fprintf(out, "\n");
 84339        }
 84340        for(i=0; i<p->nOp; i++){
 84341          char zHdr[100];
 84342          sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
 84343             p->aOp[i].cnt,
 84344             p->aOp[i].cycles,
 84345             p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
 84346          );
 84347          fprintf(out, "%s", zHdr);
 84348          sqlite3VdbePrintOp(out, i, &p->aOp[i]);
 84349        }
 84350        fclose(out);
 84351      }
 84352    }
 84353  #endif
 84354    p->magic = VDBE_MAGIC_RESET;
 84355    return p->rc & db->errMask;
 84356  }
 84357   
 84358  /*
 84359  ** Clean up and delete a VDBE after execution.  Return an integer which is
 84360  ** the result code.  Write any error message text into *pzErrMsg.
 84361  */
 84362  SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
 84363    int rc = SQLITE_OK;
 84364    if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
 84365      rc = sqlite3VdbeReset(p);
 84366      assert( (rc & p->db->errMask)==rc );
 84367    }
 84368    sqlite3VdbeDelete(p);
 84369    return rc;
 84370  }
 84371  
 84372  /*
 84373  ** If parameter iOp is less than zero, then invoke the destructor for
 84374  ** all auxiliary data pointers currently cached by the VM passed as
 84375  ** the first argument.
 84376  **
 84377  ** Or, if iOp is greater than or equal to zero, then the destructor is
 84378  ** only invoked for those auxiliary data pointers created by the user 
 84379  ** function invoked by the OP_Function opcode at instruction iOp of 
 84380  ** VM pVdbe, and only then if:
 84381  **
 84382  **    * the associated function parameter is the 32nd or later (counting
 84383  **      from left to right), or
 84384  **
 84385  **    * the corresponding bit in argument mask is clear (where the first
 84386  **      function parameter corresponds to bit 0 etc.).
 84387  */
 84388  SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
 84389    while( *pp ){
 84390      AuxData *pAux = *pp;
 84391      if( (iOp<0)
 84392       || (pAux->iAuxOp==iOp
 84393            && pAux->iAuxArg>=0
 84394            && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
 84395      ){
 84396        testcase( pAux->iAuxArg==31 );
 84397        if( pAux->xDeleteAux ){
 84398          pAux->xDeleteAux(pAux->pAux);
 84399        }
 84400        *pp = pAux->pNextAux;
 84401        sqlite3DbFree(db, pAux);
 84402      }else{
 84403        pp= &pAux->pNextAux;
 84404      }
 84405    }
 84406  }
 84407  
 84408  /*
 84409  ** Free all memory associated with the Vdbe passed as the second argument,
 84410  ** except for object itself, which is preserved.
 84411  **
 84412  ** The difference between this function and sqlite3VdbeDelete() is that
 84413  ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
 84414  ** the database connection and frees the object itself.
 84415  */
 84416  SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
 84417    SubProgram *pSub, *pNext;
 84418    assert( p->db==0 || p->db==db );
 84419    releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
 84420    for(pSub=p->pProgram; pSub; pSub=pNext){
 84421      pNext = pSub->pNext;
 84422      vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
 84423      sqlite3DbFree(db, pSub);
 84424    }
 84425    if( p->magic!=VDBE_MAGIC_INIT ){
 84426      releaseMemArray(p->aVar, p->nVar);
 84427      sqlite3DbFree(db, p->pVList);
 84428      sqlite3DbFree(db, p->pFree);
 84429    }
 84430    vdbeFreeOpArray(db, p->aOp, p->nOp);
 84431    sqlite3DbFree(db, p->aColName);
 84432    sqlite3DbFree(db, p->zSql);
 84433  #ifdef SQLITE_ENABLE_NORMALIZE
 84434    sqlite3DbFree(db, p->zNormSql);
 84435    {
 84436      DblquoteStr *pThis, *pNext;
 84437      for(pThis=p->pDblStr; pThis; pThis=pNext){
 84438        pNext = pThis->pNextStr;
 84439        sqlite3DbFree(db, pThis);
 84440      }
 84441    }
 84442  #endif
 84443  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 84444    {
 84445      int i;
 84446      for(i=0; i<p->nScan; i++){
 84447        sqlite3DbFree(db, p->aScan[i].zName);
 84448      }
 84449      sqlite3DbFree(db, p->aScan);
 84450    }
 84451  #endif
 84452  }
 84453  
 84454  /*
 84455  ** Delete an entire VDBE.
 84456  */
 84457  SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
 84458    sqlite3 *db;
 84459  
 84460    assert( p!=0 );
 84461    db = p->db;
 84462    assert( sqlite3_mutex_held(db->mutex) );
 84463    sqlite3VdbeClearObject(db, p);
 84464    if( p->pPrev ){
 84465      p->pPrev->pNext = p->pNext;
 84466    }else{
 84467      assert( db->pVdbe==p );
 84468      db->pVdbe = p->pNext;
 84469    }
 84470    if( p->pNext ){
 84471      p->pNext->pPrev = p->pPrev;
 84472    }
 84473    p->magic = VDBE_MAGIC_DEAD;
 84474    p->db = 0;
 84475    sqlite3DbFreeNN(db, p);
 84476  }
 84477  
 84478  /*
 84479  ** The cursor "p" has a pending seek operation that has not yet been
 84480  ** carried out.  Seek the cursor now.  If an error occurs, return
 84481  ** the appropriate error code.
 84482  */
 84483  static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
 84484    int res, rc;
 84485  #ifdef SQLITE_TEST
 84486    extern int sqlite3_search_count;
 84487  #endif
 84488    assert( p->deferredMoveto );
 84489    assert( p->isTable );
 84490    assert( p->eCurType==CURTYPE_BTREE );
 84491    rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
 84492    if( rc ) return rc;
 84493    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
 84494  #ifdef SQLITE_TEST
 84495    sqlite3_search_count++;
 84496  #endif
 84497    p->deferredMoveto = 0;
 84498    p->cacheStatus = CACHE_STALE;
 84499    return SQLITE_OK;
 84500  }
 84501  
 84502  /*
 84503  ** Something has moved cursor "p" out of place.  Maybe the row it was
 84504  ** pointed to was deleted out from under it.  Or maybe the btree was
 84505  ** rebalanced.  Whatever the cause, try to restore "p" to the place it
 84506  ** is supposed to be pointing.  If the row was deleted out from under the
 84507  ** cursor, set the cursor to point to a NULL row.
 84508  */
 84509  static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
 84510    int isDifferentRow, rc;
 84511    assert( p->eCurType==CURTYPE_BTREE );
 84512    assert( p->uc.pCursor!=0 );
 84513    assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
 84514    rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
 84515    p->cacheStatus = CACHE_STALE;
 84516    if( isDifferentRow ) p->nullRow = 1;
 84517    return rc;
 84518  }
 84519  
 84520  /*
 84521  ** Check to ensure that the cursor is valid.  Restore the cursor
 84522  ** if need be.  Return any I/O error from the restore operation.
 84523  */
 84524  SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
 84525    assert( p->eCurType==CURTYPE_BTREE );
 84526    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
 84527      return handleMovedCursor(p);
 84528    }
 84529    return SQLITE_OK;
 84530  }
 84531  
 84532  /*
 84533  ** Make sure the cursor p is ready to read or write the row to which it
 84534  ** was last positioned.  Return an error code if an OOM fault or I/O error
 84535  ** prevents us from positioning the cursor to its correct position.
 84536  **
 84537  ** If a MoveTo operation is pending on the given cursor, then do that
 84538  ** MoveTo now.  If no move is pending, check to see if the row has been
 84539  ** deleted out from under the cursor and if it has, mark the row as
 84540  ** a NULL row.
 84541  **
 84542  ** If the cursor is already pointing to the correct row and that row has
 84543  ** not been deleted out from under the cursor, then this routine is a no-op.
 84544  */
 84545  SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
 84546    VdbeCursor *p = *pp;
 84547    assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
 84548    if( p->deferredMoveto ){
 84549      int iMap;
 84550      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
 84551        *pp = p->pAltCursor;
 84552        *piCol = iMap - 1;
 84553        return SQLITE_OK;
 84554      }
 84555      return handleDeferredMoveto(p);
 84556    }
 84557    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
 84558      return handleMovedCursor(p);
 84559    }
 84560    return SQLITE_OK;
 84561  }
 84562  
 84563  /*
 84564  ** The following functions:
 84565  **
 84566  ** sqlite3VdbeSerialType()
 84567  ** sqlite3VdbeSerialTypeLen()
 84568  ** sqlite3VdbeSerialLen()
 84569  ** sqlite3VdbeSerialPut()
 84570  ** sqlite3VdbeSerialGet()
 84571  **
 84572  ** encapsulate the code that serializes values for storage in SQLite
 84573  ** data and index records. Each serialized value consists of a
 84574  ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
 84575  ** integer, stored as a varint.
 84576  **
 84577  ** In an SQLite index record, the serial type is stored directly before
 84578  ** the blob of data that it corresponds to. In a table record, all serial
 84579  ** types are stored at the start of the record, and the blobs of data at
 84580  ** the end. Hence these functions allow the caller to handle the
 84581  ** serial-type and data blob separately.
 84582  **
 84583  ** The following table describes the various storage classes for data:
 84584  **
 84585  **   serial type        bytes of data      type
 84586  **   --------------     ---------------    ---------------
 84587  **      0                     0            NULL
 84588  **      1                     1            signed integer
 84589  **      2                     2            signed integer
 84590  **      3                     3            signed integer
 84591  **      4                     4            signed integer
 84592  **      5                     6            signed integer
 84593  **      6                     8            signed integer
 84594  **      7                     8            IEEE float
 84595  **      8                     0            Integer constant 0
 84596  **      9                     0            Integer constant 1
 84597  **     10,11                               reserved for expansion
 84598  **    N>=12 and even       (N-12)/2        BLOB
 84599  **    N>=13 and odd        (N-13)/2        text
 84600  **
 84601  ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
 84602  ** of SQLite will not understand those serial types.
 84603  */
 84604  
 84605  /*
 84606  ** Return the serial-type for the value stored in pMem.
 84607  */
 84608  SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
 84609    int flags = pMem->flags;
 84610    u32 n;
 84611  
 84612    assert( pLen!=0 );
 84613    if( flags&MEM_Null ){
 84614      *pLen = 0;
 84615      return 0;
 84616    }
 84617    if( flags&MEM_Int ){
 84618      /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
 84619  #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
 84620      i64 i = pMem->u.i;
 84621      u64 u;
 84622      if( i<0 ){
 84623        u = ~i;
 84624      }else{
 84625        u = i;
 84626      }
 84627      if( u<=127 ){
 84628        if( (i&1)==i && file_format>=4 ){
 84629          *pLen = 0;
 84630          return 8+(u32)u;
 84631        }else{
 84632          *pLen = 1;
 84633          return 1;
 84634        }
 84635      }
 84636      if( u<=32767 ){ *pLen = 2; return 2; }
 84637      if( u<=8388607 ){ *pLen = 3; return 3; }
 84638      if( u<=2147483647 ){ *pLen = 4; return 4; }
 84639      if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
 84640      *pLen = 8;
 84641      return 6;
 84642    }
 84643    if( flags&MEM_Real ){
 84644      *pLen = 8;
 84645      return 7;
 84646    }
 84647    assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
 84648    assert( pMem->n>=0 );
 84649    n = (u32)pMem->n;
 84650    if( flags & MEM_Zero ){
 84651      n += pMem->u.nZero;
 84652    }
 84653    *pLen = n;
 84654    return ((n*2) + 12 + ((flags&MEM_Str)!=0));
 84655  }
 84656  
 84657  /*
 84658  ** The sizes for serial types less than 128
 84659  */
 84660  static const u8 sqlite3SmallTypeSizes[] = {
 84661          /*  0   1   2   3   4   5   6   7   8   9 */   
 84662  /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
 84663  /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
 84664  /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
 84665  /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
 84666  /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
 84667  /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
 84668  /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
 84669  /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
 84670  /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
 84671  /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
 84672  /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
 84673  /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
 84674  /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
 84675  };
 84676  
 84677  /*
 84678  ** Return the length of the data corresponding to the supplied serial-type.
 84679  */
 84680  SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
 84681    if( serial_type>=128 ){
 84682      return (serial_type-12)/2;
 84683    }else{
 84684      assert( serial_type<12 
 84685              || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
 84686      return sqlite3SmallTypeSizes[serial_type];
 84687    }
 84688  }
 84689  SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
 84690    assert( serial_type<128 );
 84691    return sqlite3SmallTypeSizes[serial_type];  
 84692  }
 84693  
 84694  /*
 84695  ** If we are on an architecture with mixed-endian floating 
 84696  ** points (ex: ARM7) then swap the lower 4 bytes with the 
 84697  ** upper 4 bytes.  Return the result.
 84698  **
 84699  ** For most architectures, this is a no-op.
 84700  **
 84701  ** (later):  It is reported to me that the mixed-endian problem
 84702  ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
 84703  ** that early versions of GCC stored the two words of a 64-bit
 84704  ** float in the wrong order.  And that error has been propagated
 84705  ** ever since.  The blame is not necessarily with GCC, though.
 84706  ** GCC might have just copying the problem from a prior compiler.
 84707  ** I am also told that newer versions of GCC that follow a different
 84708  ** ABI get the byte order right.
 84709  **
 84710  ** Developers using SQLite on an ARM7 should compile and run their
 84711  ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
 84712  ** enabled, some asserts below will ensure that the byte order of
 84713  ** floating point values is correct.
 84714  **
 84715  ** (2007-08-30)  Frank van Vugt has studied this problem closely
 84716  ** and has send his findings to the SQLite developers.  Frank
 84717  ** writes that some Linux kernels offer floating point hardware
 84718  ** emulation that uses only 32-bit mantissas instead of a full 
 84719  ** 48-bits as required by the IEEE standard.  (This is the
 84720  ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
 84721  ** byte swapping becomes very complicated.  To avoid problems,
 84722  ** the necessary byte swapping is carried out using a 64-bit integer
 84723  ** rather than a 64-bit float.  Frank assures us that the code here
 84724  ** works for him.  We, the developers, have no way to independently
 84725  ** verify this, but Frank seems to know what he is talking about
 84726  ** so we trust him.
 84727  */
 84728  #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
 84729  static u64 floatSwap(u64 in){
 84730    union {
 84731      u64 r;
 84732      u32 i[2];
 84733    } u;
 84734    u32 t;
 84735  
 84736    u.r = in;
 84737    t = u.i[0];
 84738    u.i[0] = u.i[1];
 84739    u.i[1] = t;
 84740    return u.r;
 84741  }
 84742  # define swapMixedEndianFloat(X)  X = floatSwap(X)
 84743  #else
 84744  # define swapMixedEndianFloat(X)
 84745  #endif
 84746  
 84747  /*
 84748  ** Write the serialized data blob for the value stored in pMem into 
 84749  ** buf. It is assumed that the caller has allocated sufficient space.
 84750  ** Return the number of bytes written.
 84751  **
 84752  ** nBuf is the amount of space left in buf[].  The caller is responsible
 84753  ** for allocating enough space to buf[] to hold the entire field, exclusive
 84754  ** of the pMem->u.nZero bytes for a MEM_Zero value.
 84755  **
 84756  ** Return the number of bytes actually written into buf[].  The number
 84757  ** of bytes in the zero-filled tail is included in the return value only
 84758  ** if those bytes were zeroed in buf[].
 84759  */ 
 84760  SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
 84761    u32 len;
 84762  
 84763    /* Integer and Real */
 84764    if( serial_type<=7 && serial_type>0 ){
 84765      u64 v;
 84766      u32 i;
 84767      if( serial_type==7 ){
 84768        assert( sizeof(v)==sizeof(pMem->u.r) );
 84769        memcpy(&v, &pMem->u.r, sizeof(v));
 84770        swapMixedEndianFloat(v);
 84771      }else{
 84772        v = pMem->u.i;
 84773      }
 84774      len = i = sqlite3SmallTypeSizes[serial_type];
 84775      assert( i>0 );
 84776      do{
 84777        buf[--i] = (u8)(v&0xFF);
 84778        v >>= 8;
 84779      }while( i );
 84780      return len;
 84781    }
 84782  
 84783    /* String or blob */
 84784    if( serial_type>=12 ){
 84785      assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
 84786               == (int)sqlite3VdbeSerialTypeLen(serial_type) );
 84787      len = pMem->n;
 84788      if( len>0 ) memcpy(buf, pMem->z, len);
 84789      return len;
 84790    }
 84791  
 84792    /* NULL or constants 0 or 1 */
 84793    return 0;
 84794  }
 84795  
 84796  /* Input "x" is a sequence of unsigned characters that represent a
 84797  ** big-endian integer.  Return the equivalent native integer
 84798  */
 84799  #define ONE_BYTE_INT(x)    ((i8)(x)[0])
 84800  #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
 84801  #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
 84802  #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
 84803  #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
 84804  
 84805  /*
 84806  ** Deserialize the data blob pointed to by buf as serial type serial_type
 84807  ** and store the result in pMem.  Return the number of bytes read.
 84808  **
 84809  ** This function is implemented as two separate routines for performance.
 84810  ** The few cases that require local variables are broken out into a separate
 84811  ** routine so that in most cases the overhead of moving the stack pointer
 84812  ** is avoided.
 84813  */ 
 84814  static u32 SQLITE_NOINLINE serialGet(
 84815    const unsigned char *buf,     /* Buffer to deserialize from */
 84816    u32 serial_type,              /* Serial type to deserialize */
 84817    Mem *pMem                     /* Memory cell to write value into */
 84818  ){
 84819    u64 x = FOUR_BYTE_UINT(buf);
 84820    u32 y = FOUR_BYTE_UINT(buf+4);
 84821    x = (x<<32) + y;
 84822    if( serial_type==6 ){
 84823      /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
 84824      ** twos-complement integer. */
 84825      pMem->u.i = *(i64*)&x;
 84826      pMem->flags = MEM_Int;
 84827      testcase( pMem->u.i<0 );
 84828    }else{
 84829      /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
 84830      ** floating point number. */
 84831  #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
 84832      /* Verify that integers and floating point values use the same
 84833      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
 84834      ** defined that 64-bit floating point values really are mixed
 84835      ** endian.
 84836      */
 84837      static const u64 t1 = ((u64)0x3ff00000)<<32;
 84838      static const double r1 = 1.0;
 84839      u64 t2 = t1;
 84840      swapMixedEndianFloat(t2);
 84841      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
 84842  #endif
 84843      assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
 84844      swapMixedEndianFloat(x);
 84845      memcpy(&pMem->u.r, &x, sizeof(x));
 84846      pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
 84847    }
 84848    return 8;
 84849  }
 84850  SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
 84851    const unsigned char *buf,     /* Buffer to deserialize from */
 84852    u32 serial_type,              /* Serial type to deserialize */
 84853    Mem *pMem                     /* Memory cell to write value into */
 84854  ){
 84855    switch( serial_type ){
 84856      case 10: { /* Internal use only: NULL with virtual table
 84857                 ** UPDATE no-change flag set */
 84858        pMem->flags = MEM_Null|MEM_Zero;
 84859        pMem->n = 0;
 84860        pMem->u.nZero = 0;
 84861        break;
 84862      }
 84863      case 11:   /* Reserved for future use */
 84864      case 0: {  /* Null */
 84865        /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
 84866        pMem->flags = MEM_Null;
 84867        break;
 84868      }
 84869      case 1: {
 84870        /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
 84871        ** integer. */
 84872        pMem->u.i = ONE_BYTE_INT(buf);
 84873        pMem->flags = MEM_Int;
 84874        testcase( pMem->u.i<0 );
 84875        return 1;
 84876      }
 84877      case 2: { /* 2-byte signed integer */
 84878        /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
 84879        ** twos-complement integer. */
 84880        pMem->u.i = TWO_BYTE_INT(buf);
 84881        pMem->flags = MEM_Int;
 84882        testcase( pMem->u.i<0 );
 84883        return 2;
 84884      }
 84885      case 3: { /* 3-byte signed integer */
 84886        /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
 84887        ** twos-complement integer. */
 84888        pMem->u.i = THREE_BYTE_INT(buf);
 84889        pMem->flags = MEM_Int;
 84890        testcase( pMem->u.i<0 );
 84891        return 3;
 84892      }
 84893      case 4: { /* 4-byte signed integer */
 84894        /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
 84895        ** twos-complement integer. */
 84896        pMem->u.i = FOUR_BYTE_INT(buf);
 84897  #ifdef __HP_cc 
 84898        /* Work around a sign-extension bug in the HP compiler for HP/UX */
 84899        if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
 84900  #endif
 84901        pMem->flags = MEM_Int;
 84902        testcase( pMem->u.i<0 );
 84903        return 4;
 84904      }
 84905      case 5: { /* 6-byte signed integer */
 84906        /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
 84907        ** twos-complement integer. */
 84908        pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
 84909        pMem->flags = MEM_Int;
 84910        testcase( pMem->u.i<0 );
 84911        return 6;
 84912      }
 84913      case 6:   /* 8-byte signed integer */
 84914      case 7: { /* IEEE floating point */
 84915        /* These use local variables, so do them in a separate routine
 84916        ** to avoid having to move the frame pointer in the common case */
 84917        return serialGet(buf,serial_type,pMem);
 84918      }
 84919      case 8:    /* Integer 0 */
 84920      case 9: {  /* Integer 1 */
 84921        /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
 84922        /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
 84923        pMem->u.i = serial_type-8;
 84924        pMem->flags = MEM_Int;
 84925        return 0;
 84926      }
 84927      default: {
 84928        /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
 84929        ** length.
 84930        ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
 84931        ** (N-13)/2 bytes in length. */
 84932        static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
 84933        pMem->z = (char *)buf;
 84934        pMem->n = (serial_type-12)/2;
 84935        pMem->flags = aFlag[serial_type&1];
 84936        return pMem->n;
 84937      }
 84938    }
 84939    return 0;
 84940  }
 84941  /*
 84942  ** This routine is used to allocate sufficient space for an UnpackedRecord
 84943  ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
 84944  ** the first argument is a pointer to KeyInfo structure pKeyInfo.
 84945  **
 84946  ** The space is either allocated using sqlite3DbMallocRaw() or from within
 84947  ** the unaligned buffer passed via the second and third arguments (presumably
 84948  ** stack space). If the former, then *ppFree is set to a pointer that should
 84949  ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
 84950  ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
 84951  ** before returning.
 84952  **
 84953  ** If an OOM error occurs, NULL is returned.
 84954  */
 84955  SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
 84956    KeyInfo *pKeyInfo               /* Description of the record */
 84957  ){
 84958    UnpackedRecord *p;              /* Unpacked record to return */
 84959    int nByte;                      /* Number of bytes required for *p */
 84960    nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
 84961    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
 84962    if( !p ) return 0;
 84963    p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
 84964    assert( pKeyInfo->aSortOrder!=0 );
 84965    p->pKeyInfo = pKeyInfo;
 84966    p->nField = pKeyInfo->nKeyField + 1;
 84967    return p;
 84968  }
 84969  
 84970  /*
 84971  ** Given the nKey-byte encoding of a record in pKey[], populate the 
 84972  ** UnpackedRecord structure indicated by the fourth argument with the
 84973  ** contents of the decoded record.
 84974  */ 
 84975  SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
 84976    KeyInfo *pKeyInfo,     /* Information about the record format */
 84977    int nKey,              /* Size of the binary record */
 84978    const void *pKey,      /* The binary record */
 84979    UnpackedRecord *p      /* Populate this structure before returning. */
 84980  ){
 84981    const unsigned char *aKey = (const unsigned char *)pKey;
 84982    u32 d; 
 84983    u32 idx;                        /* Offset in aKey[] to read from */
 84984    u16 u;                          /* Unsigned loop counter */
 84985    u32 szHdr;
 84986    Mem *pMem = p->aMem;
 84987  
 84988    p->default_rc = 0;
 84989    assert( EIGHT_BYTE_ALIGNMENT(pMem) );
 84990    idx = getVarint32(aKey, szHdr);
 84991    d = szHdr;
 84992    u = 0;
 84993    while( idx<szHdr && d<=(u32)nKey ){
 84994      u32 serial_type;
 84995  
 84996      idx += getVarint32(&aKey[idx], serial_type);
 84997      pMem->enc = pKeyInfo->enc;
 84998      pMem->db = pKeyInfo->db;
 84999      /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
 85000      pMem->szMalloc = 0;
 85001      pMem->z = 0;
 85002      d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
 85003      pMem++;
 85004      if( (++u)>=p->nField ) break;
 85005    }
 85006    if( d>(u32)nKey && u ){
 85007      assert( CORRUPT_DB );
 85008      /* In a corrupt record entry, the last pMem might have been set up using 
 85009      ** uninitialized memory. Overwrite its value with NULL, to prevent
 85010      ** warnings from MSAN. */
 85011      sqlite3VdbeMemSetNull(pMem-1);
 85012    }
 85013    assert( u<=pKeyInfo->nKeyField + 1 );
 85014    p->nField = u;
 85015  }
 85016  
 85017  #ifdef SQLITE_DEBUG
 85018  /*
 85019  ** This function compares two index or table record keys in the same way
 85020  ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
 85021  ** this function deserializes and compares values using the
 85022  ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
 85023  ** in assert() statements to ensure that the optimized code in
 85024  ** sqlite3VdbeRecordCompare() returns results with these two primitives.
 85025  **
 85026  ** Return true if the result of comparison is equivalent to desiredResult.
 85027  ** Return false if there is a disagreement.
 85028  */
 85029  static int vdbeRecordCompareDebug(
 85030    int nKey1, const void *pKey1, /* Left key */
 85031    const UnpackedRecord *pPKey2, /* Right key */
 85032    int desiredResult             /* Correct answer */
 85033  ){
 85034    u32 d1;            /* Offset into aKey[] of next data element */
 85035    u32 idx1;          /* Offset into aKey[] of next header element */
 85036    u32 szHdr1;        /* Number of bytes in header */
 85037    int i = 0;
 85038    int rc = 0;
 85039    const unsigned char *aKey1 = (const unsigned char *)pKey1;
 85040    KeyInfo *pKeyInfo;
 85041    Mem mem1;
 85042  
 85043    pKeyInfo = pPKey2->pKeyInfo;
 85044    if( pKeyInfo->db==0 ) return 1;
 85045    mem1.enc = pKeyInfo->enc;
 85046    mem1.db = pKeyInfo->db;
 85047    /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
 85048    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
 85049  
 85050    /* Compilers may complain that mem1.u.i is potentially uninitialized.
 85051    ** We could initialize it, as shown here, to silence those complaints.
 85052    ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
 85053    ** the unnecessary initialization has a measurable negative performance
 85054    ** impact, since this routine is a very high runner.  And so, we choose
 85055    ** to ignore the compiler warnings and leave this variable uninitialized.
 85056    */
 85057    /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
 85058    
 85059    idx1 = getVarint32(aKey1, szHdr1);
 85060    if( szHdr1>98307 ) return SQLITE_CORRUPT;
 85061    d1 = szHdr1;
 85062    assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
 85063    assert( pKeyInfo->aSortOrder!=0 );
 85064    assert( pKeyInfo->nKeyField>0 );
 85065    assert( idx1<=szHdr1 || CORRUPT_DB );
 85066    do{
 85067      u32 serial_type1;
 85068  
 85069      /* Read the serial types for the next element in each key. */
 85070      idx1 += getVarint32( aKey1+idx1, serial_type1 );
 85071  
 85072      /* Verify that there is enough key space remaining to avoid
 85073      ** a buffer overread.  The "d1+serial_type1+2" subexpression will
 85074      ** always be greater than or equal to the amount of required key space.
 85075      ** Use that approximation to avoid the more expensive call to
 85076      ** sqlite3VdbeSerialTypeLen() in the common case.
 85077      */
 85078      if( d1+(u64)serial_type1+2>(u64)nKey1
 85079       && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1 
 85080      ){
 85081        break;
 85082      }
 85083  
 85084      /* Extract the values to be compared.
 85085      */
 85086      d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
 85087  
 85088      /* Do the comparison
 85089      */
 85090      rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
 85091                             pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
 85092      if( rc!=0 ){
 85093        assert( mem1.szMalloc==0 );  /* See comment below */
 85094        if( pKeyInfo->aSortOrder[i] ){
 85095          rc = -rc;  /* Invert the result for DESC sort order. */
 85096        }
 85097        goto debugCompareEnd;
 85098      }
 85099      i++;
 85100    }while( idx1<szHdr1 && i<pPKey2->nField );
 85101  
 85102    /* No memory allocation is ever used on mem1.  Prove this using
 85103    ** the following assert().  If the assert() fails, it indicates a
 85104    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
 85105    */
 85106    assert( mem1.szMalloc==0 );
 85107  
 85108    /* rc==0 here means that one of the keys ran out of fields and
 85109    ** all the fields up to that point were equal. Return the default_rc
 85110    ** value.  */
 85111    rc = pPKey2->default_rc;
 85112  
 85113  debugCompareEnd:
 85114    if( desiredResult==0 && rc==0 ) return 1;
 85115    if( desiredResult<0 && rc<0 ) return 1;
 85116    if( desiredResult>0 && rc>0 ) return 1;
 85117    if( CORRUPT_DB ) return 1;
 85118    if( pKeyInfo->db->mallocFailed ) return 1;
 85119    return 0;
 85120  }
 85121  #endif
 85122  
 85123  #ifdef SQLITE_DEBUG
 85124  /*
 85125  ** Count the number of fields (a.k.a. columns) in the record given by
 85126  ** pKey,nKey.  The verify that this count is less than or equal to the
 85127  ** limit given by pKeyInfo->nAllField.
 85128  **
 85129  ** If this constraint is not satisfied, it means that the high-speed
 85130  ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
 85131  ** not work correctly.  If this assert() ever fires, it probably means
 85132  ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
 85133  ** incorrectly.
 85134  */
 85135  static void vdbeAssertFieldCountWithinLimits(
 85136    int nKey, const void *pKey,   /* The record to verify */ 
 85137    const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
 85138  ){
 85139    int nField = 0;
 85140    u32 szHdr;
 85141    u32 idx;
 85142    u32 notUsed;
 85143    const unsigned char *aKey = (const unsigned char*)pKey;
 85144  
 85145    if( CORRUPT_DB ) return;
 85146    idx = getVarint32(aKey, szHdr);
 85147    assert( nKey>=0 );
 85148    assert( szHdr<=(u32)nKey );
 85149    while( idx<szHdr ){
 85150      idx += getVarint32(aKey+idx, notUsed);
 85151      nField++;
 85152    }
 85153    assert( nField <= pKeyInfo->nAllField );
 85154  }
 85155  #else
 85156  # define vdbeAssertFieldCountWithinLimits(A,B,C)
 85157  #endif
 85158  
 85159  /*
 85160  ** Both *pMem1 and *pMem2 contain string values. Compare the two values
 85161  ** using the collation sequence pColl. As usual, return a negative , zero
 85162  ** or positive value if *pMem1 is less than, equal to or greater than 
 85163  ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
 85164  */
 85165  static int vdbeCompareMemString(
 85166    const Mem *pMem1,
 85167    const Mem *pMem2,
 85168    const CollSeq *pColl,
 85169    u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
 85170  ){
 85171    if( pMem1->enc==pColl->enc ){
 85172      /* The strings are already in the correct encoding.  Call the
 85173       ** comparison function directly */
 85174      return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
 85175    }else{
 85176      int rc;
 85177      const void *v1, *v2;
 85178      Mem c1;
 85179      Mem c2;
 85180      sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
 85181      sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
 85182      sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
 85183      sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
 85184      v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
 85185      v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
 85186      if( (v1==0 || v2==0) ){
 85187        if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
 85188        rc = 0;
 85189      }else{
 85190        rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
 85191      }
 85192      sqlite3VdbeMemRelease(&c1);
 85193      sqlite3VdbeMemRelease(&c2);
 85194      return rc;
 85195    }
 85196  }
 85197  
 85198  /*
 85199  ** The input pBlob is guaranteed to be a Blob that is not marked
 85200  ** with MEM_Zero.  Return true if it could be a zero-blob.
 85201  */
 85202  static int isAllZero(const char *z, int n){
 85203    int i;
 85204    for(i=0; i<n; i++){
 85205      if( z[i] ) return 0;
 85206    }
 85207    return 1;
 85208  }
 85209  
 85210  /*
 85211  ** Compare two blobs.  Return negative, zero, or positive if the first
 85212  ** is less than, equal to, or greater than the second, respectively.
 85213  ** If one blob is a prefix of the other, then the shorter is the lessor.
 85214  */
 85215  SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
 85216    int c;
 85217    int n1 = pB1->n;
 85218    int n2 = pB2->n;
 85219  
 85220    /* It is possible to have a Blob value that has some non-zero content
 85221    ** followed by zero content.  But that only comes up for Blobs formed
 85222    ** by the OP_MakeRecord opcode, and such Blobs never get passed into
 85223    ** sqlite3MemCompare(). */
 85224    assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
 85225    assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
 85226  
 85227    if( (pB1->flags|pB2->flags) & MEM_Zero ){
 85228      if( pB1->flags & pB2->flags & MEM_Zero ){
 85229        return pB1->u.nZero - pB2->u.nZero;
 85230      }else if( pB1->flags & MEM_Zero ){
 85231        if( !isAllZero(pB2->z, pB2->n) ) return -1;
 85232        return pB1->u.nZero - n2;
 85233      }else{
 85234        if( !isAllZero(pB1->z, pB1->n) ) return +1;
 85235        return n1 - pB2->u.nZero;
 85236      }
 85237    }
 85238    c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
 85239    if( c ) return c;
 85240    return n1 - n2;
 85241  }
 85242  
 85243  /*
 85244  ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
 85245  ** number.  Return negative, zero, or positive if the first (i64) is less than,
 85246  ** equal to, or greater than the second (double).
 85247  */
 85248  static int sqlite3IntFloatCompare(i64 i, double r){
 85249    if( sizeof(LONGDOUBLE_TYPE)>8 ){
 85250      LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
 85251      if( x<r ) return -1;
 85252      if( x>r ) return +1;
 85253      return 0;
 85254    }else{
 85255      i64 y;
 85256      double s;
 85257      if( r<-9223372036854775808.0 ) return +1;
 85258      if( r>=9223372036854775808.0 ) return -1;
 85259      y = (i64)r;
 85260      if( i<y ) return -1;
 85261      if( i>y ) return +1;
 85262      s = (double)i;
 85263      if( s<r ) return -1;
 85264      if( s>r ) return +1;
 85265      return 0;
 85266    }
 85267  }
 85268  
 85269  /*
 85270  ** Compare the values contained by the two memory cells, returning
 85271  ** negative, zero or positive if pMem1 is less than, equal to, or greater
 85272  ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
 85273  ** and reals) sorted numerically, followed by text ordered by the collating
 85274  ** sequence pColl and finally blob's ordered by memcmp().
 85275  **
 85276  ** Two NULL values are considered equal by this function.
 85277  */
 85278  SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
 85279    int f1, f2;
 85280    int combined_flags;
 85281  
 85282    f1 = pMem1->flags;
 85283    f2 = pMem2->flags;
 85284    combined_flags = f1|f2;
 85285    assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
 85286   
 85287    /* If one value is NULL, it is less than the other. If both values
 85288    ** are NULL, return 0.
 85289    */
 85290    if( combined_flags&MEM_Null ){
 85291      return (f2&MEM_Null) - (f1&MEM_Null);
 85292    }
 85293  
 85294    /* At least one of the two values is a number
 85295    */
 85296    if( combined_flags&(MEM_Int|MEM_Real) ){
 85297      if( (f1 & f2 & MEM_Int)!=0 ){
 85298        if( pMem1->u.i < pMem2->u.i ) return -1;
 85299        if( pMem1->u.i > pMem2->u.i ) return +1;
 85300        return 0;
 85301      }
 85302      if( (f1 & f2 & MEM_Real)!=0 ){
 85303        if( pMem1->u.r < pMem2->u.r ) return -1;
 85304        if( pMem1->u.r > pMem2->u.r ) return +1;
 85305        return 0;
 85306      }
 85307      if( (f1&MEM_Int)!=0 ){
 85308        if( (f2&MEM_Real)!=0 ){
 85309          return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
 85310        }else{
 85311          return -1;
 85312        }
 85313      }
 85314      if( (f1&MEM_Real)!=0 ){
 85315        if( (f2&MEM_Int)!=0 ){
 85316          return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
 85317        }else{
 85318          return -1;
 85319        }
 85320      }
 85321      return +1;
 85322    }
 85323  
 85324    /* If one value is a string and the other is a blob, the string is less.
 85325    ** If both are strings, compare using the collating functions.
 85326    */
 85327    if( combined_flags&MEM_Str ){
 85328      if( (f1 & MEM_Str)==0 ){
 85329        return 1;
 85330      }
 85331      if( (f2 & MEM_Str)==0 ){
 85332        return -1;
 85333      }
 85334  
 85335      assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
 85336      assert( pMem1->enc==SQLITE_UTF8 || 
 85337              pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
 85338  
 85339      /* The collation sequence must be defined at this point, even if
 85340      ** the user deletes the collation sequence after the vdbe program is
 85341      ** compiled (this was not always the case).
 85342      */
 85343      assert( !pColl || pColl->xCmp );
 85344  
 85345      if( pColl ){
 85346        return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
 85347      }
 85348      /* If a NULL pointer was passed as the collate function, fall through
 85349      ** to the blob case and use memcmp().  */
 85350    }
 85351   
 85352    /* Both values must be blobs.  Compare using memcmp().  */
 85353    return sqlite3BlobCompare(pMem1, pMem2);
 85354  }
 85355  
 85356  
 85357  /*
 85358  ** The first argument passed to this function is a serial-type that
 85359  ** corresponds to an integer - all values between 1 and 9 inclusive 
 85360  ** except 7. The second points to a buffer containing an integer value
 85361  ** serialized according to serial_type. This function deserializes
 85362  ** and returns the value.
 85363  */
 85364  static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
 85365    u32 y;
 85366    assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
 85367    switch( serial_type ){
 85368      case 0:
 85369      case 1:
 85370        testcase( aKey[0]&0x80 );
 85371        return ONE_BYTE_INT(aKey);
 85372      case 2:
 85373        testcase( aKey[0]&0x80 );
 85374        return TWO_BYTE_INT(aKey);
 85375      case 3:
 85376        testcase( aKey[0]&0x80 );
 85377        return THREE_BYTE_INT(aKey);
 85378      case 4: {
 85379        testcase( aKey[0]&0x80 );
 85380        y = FOUR_BYTE_UINT(aKey);
 85381        return (i64)*(int*)&y;
 85382      }
 85383      case 5: {
 85384        testcase( aKey[0]&0x80 );
 85385        return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 85386      }
 85387      case 6: {
 85388        u64 x = FOUR_BYTE_UINT(aKey);
 85389        testcase( aKey[0]&0x80 );
 85390        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 85391        return (i64)*(i64*)&x;
 85392      }
 85393    }
 85394  
 85395    return (serial_type - 8);
 85396  }
 85397  
 85398  /*
 85399  ** This function compares the two table rows or index records
 85400  ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
 85401  ** or positive integer if key1 is less than, equal to or 
 85402  ** greater than key2.  The {nKey1, pKey1} key must be a blob
 85403  ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
 85404  ** key must be a parsed key such as obtained from
 85405  ** sqlite3VdbeParseRecord.
 85406  **
 85407  ** If argument bSkip is non-zero, it is assumed that the caller has already
 85408  ** determined that the first fields of the keys are equal.
 85409  **
 85410  ** Key1 and Key2 do not have to contain the same number of fields. If all 
 85411  ** fields that appear in both keys are equal, then pPKey2->default_rc is 
 85412  ** returned.
 85413  **
 85414  ** If database corruption is discovered, set pPKey2->errCode to 
 85415  ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, 
 85416  ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
 85417  ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
 85418  */
 85419  SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
 85420    int nKey1, const void *pKey1,   /* Left key */
 85421    UnpackedRecord *pPKey2,         /* Right key */
 85422    int bSkip                       /* If true, skip the first field */
 85423  ){
 85424    u32 d1;                         /* Offset into aKey[] of next data element */
 85425    int i;                          /* Index of next field to compare */
 85426    u32 szHdr1;                     /* Size of record header in bytes */
 85427    u32 idx1;                       /* Offset of first type in header */
 85428    int rc = 0;                     /* Return value */
 85429    Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
 85430    KeyInfo *pKeyInfo;
 85431    const unsigned char *aKey1 = (const unsigned char *)pKey1;
 85432    Mem mem1;
 85433  
 85434    /* If bSkip is true, then the caller has already determined that the first
 85435    ** two elements in the keys are equal. Fix the various stack variables so
 85436    ** that this routine begins comparing at the second field. */
 85437    if( bSkip ){
 85438      u32 s1;
 85439      idx1 = 1 + getVarint32(&aKey1[1], s1);
 85440      szHdr1 = aKey1[0];
 85441      d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
 85442      i = 1;
 85443      pRhs++;
 85444    }else{
 85445      idx1 = getVarint32(aKey1, szHdr1);
 85446      d1 = szHdr1;
 85447      i = 0;
 85448    }
 85449    if( d1>(unsigned)nKey1 ){ 
 85450      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 85451      return 0;  /* Corruption */
 85452    }
 85453  
 85454    VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
 85455    assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField 
 85456         || CORRUPT_DB );
 85457    assert( pPKey2->pKeyInfo->aSortOrder!=0 );
 85458    assert( pPKey2->pKeyInfo->nKeyField>0 );
 85459    assert( idx1<=szHdr1 || CORRUPT_DB );
 85460    do{
 85461      u32 serial_type;
 85462  
 85463      /* RHS is an integer */
 85464      if( pRhs->flags & MEM_Int ){
 85465        serial_type = aKey1[idx1];
 85466        testcase( serial_type==12 );
 85467        if( serial_type>=10 ){
 85468          rc = +1;
 85469        }else if( serial_type==0 ){
 85470          rc = -1;
 85471        }else if( serial_type==7 ){
 85472          sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 85473          rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
 85474        }else{
 85475          i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
 85476          i64 rhs = pRhs->u.i;
 85477          if( lhs<rhs ){
 85478            rc = -1;
 85479          }else if( lhs>rhs ){
 85480            rc = +1;
 85481          }
 85482        }
 85483      }
 85484  
 85485      /* RHS is real */
 85486      else if( pRhs->flags & MEM_Real ){
 85487        serial_type = aKey1[idx1];
 85488        if( serial_type>=10 ){
 85489          /* Serial types 12 or greater are strings and blobs (greater than
 85490          ** numbers). Types 10 and 11 are currently "reserved for future 
 85491          ** use", so it doesn't really matter what the results of comparing
 85492          ** them to numberic values are.  */
 85493          rc = +1;
 85494        }else if( serial_type==0 ){
 85495          rc = -1;
 85496        }else{
 85497          sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
 85498          if( serial_type==7 ){
 85499            if( mem1.u.r<pRhs->u.r ){
 85500              rc = -1;
 85501            }else if( mem1.u.r>pRhs->u.r ){
 85502              rc = +1;
 85503            }
 85504          }else{
 85505            rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
 85506          }
 85507        }
 85508      }
 85509  
 85510      /* RHS is a string */
 85511      else if( pRhs->flags & MEM_Str ){
 85512        getVarint32(&aKey1[idx1], serial_type);
 85513        testcase( serial_type==12 );
 85514        if( serial_type<12 ){
 85515          rc = -1;
 85516        }else if( !(serial_type & 0x01) ){
 85517          rc = +1;
 85518        }else{
 85519          mem1.n = (serial_type - 12) / 2;
 85520          testcase( (d1+mem1.n)==(unsigned)nKey1 );
 85521          testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
 85522          if( (d1+mem1.n) > (unsigned)nKey1
 85523           || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
 85524          ){
 85525            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 85526            return 0;                /* Corruption */
 85527          }else if( pKeyInfo->aColl[i] ){
 85528            mem1.enc = pKeyInfo->enc;
 85529            mem1.db = pKeyInfo->db;
 85530            mem1.flags = MEM_Str;
 85531            mem1.z = (char*)&aKey1[d1];
 85532            rc = vdbeCompareMemString(
 85533                &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
 85534            );
 85535          }else{
 85536            int nCmp = MIN(mem1.n, pRhs->n);
 85537            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 85538            if( rc==0 ) rc = mem1.n - pRhs->n; 
 85539          }
 85540        }
 85541      }
 85542  
 85543      /* RHS is a blob */
 85544      else if( pRhs->flags & MEM_Blob ){
 85545        assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
 85546        getVarint32(&aKey1[idx1], serial_type);
 85547        testcase( serial_type==12 );
 85548        if( serial_type<12 || (serial_type & 0x01) ){
 85549          rc = -1;
 85550        }else{
 85551          int nStr = (serial_type - 12) / 2;
 85552          testcase( (d1+nStr)==(unsigned)nKey1 );
 85553          testcase( (d1+nStr+1)==(unsigned)nKey1 );
 85554          if( (d1+nStr) > (unsigned)nKey1 ){
 85555            pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 85556            return 0;                /* Corruption */
 85557          }else if( pRhs->flags & MEM_Zero ){
 85558            if( !isAllZero((const char*)&aKey1[d1],nStr) ){
 85559              rc = 1;
 85560            }else{
 85561              rc = nStr - pRhs->u.nZero;
 85562            }
 85563          }else{
 85564            int nCmp = MIN(nStr, pRhs->n);
 85565            rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
 85566            if( rc==0 ) rc = nStr - pRhs->n;
 85567          }
 85568        }
 85569      }
 85570  
 85571      /* RHS is null */
 85572      else{
 85573        serial_type = aKey1[idx1];
 85574        rc = (serial_type!=0);
 85575      }
 85576  
 85577      if( rc!=0 ){
 85578        if( pPKey2->pKeyInfo->aSortOrder[i] ){
 85579          rc = -rc;
 85580        }
 85581        assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
 85582        assert( mem1.szMalloc==0 );  /* See comment below */
 85583        return rc;
 85584      }
 85585  
 85586      i++;
 85587      if( i==pPKey2->nField ) break;
 85588      pRhs++;
 85589      d1 += sqlite3VdbeSerialTypeLen(serial_type);
 85590      idx1 += sqlite3VarintLen(serial_type);
 85591    }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
 85592  
 85593    /* No memory allocation is ever used on mem1.  Prove this using
 85594    ** the following assert().  If the assert() fails, it indicates a
 85595    ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
 85596    assert( mem1.szMalloc==0 );
 85597  
 85598    /* rc==0 here means that one or both of the keys ran out of fields and
 85599    ** all the fields up to that point were equal. Return the default_rc
 85600    ** value.  */
 85601    assert( CORRUPT_DB 
 85602         || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) 
 85603         || pPKey2->pKeyInfo->db->mallocFailed
 85604    );
 85605    pPKey2->eqSeen = 1;
 85606    return pPKey2->default_rc;
 85607  }
 85608  SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
 85609    int nKey1, const void *pKey1,   /* Left key */
 85610    UnpackedRecord *pPKey2          /* Right key */
 85611  ){
 85612    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
 85613  }
 85614  
 85615  
 85616  /*
 85617  ** This function is an optimized version of sqlite3VdbeRecordCompare() 
 85618  ** that (a) the first field of pPKey2 is an integer, and (b) the 
 85619  ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
 85620  ** byte (i.e. is less than 128).
 85621  **
 85622  ** To avoid concerns about buffer overreads, this routine is only used
 85623  ** on schemas where the maximum valid header size is 63 bytes or less.
 85624  */
 85625  static int vdbeRecordCompareInt(
 85626    int nKey1, const void *pKey1, /* Left key */
 85627    UnpackedRecord *pPKey2        /* Right key */
 85628  ){
 85629    const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
 85630    int serial_type = ((const u8*)pKey1)[1];
 85631    int res;
 85632    u32 y;
 85633    u64 x;
 85634    i64 v;
 85635    i64 lhs;
 85636  
 85637    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
 85638    assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
 85639    switch( serial_type ){
 85640      case 1: { /* 1-byte signed integer */
 85641        lhs = ONE_BYTE_INT(aKey);
 85642        testcase( lhs<0 );
 85643        break;
 85644      }
 85645      case 2: { /* 2-byte signed integer */
 85646        lhs = TWO_BYTE_INT(aKey);
 85647        testcase( lhs<0 );
 85648        break;
 85649      }
 85650      case 3: { /* 3-byte signed integer */
 85651        lhs = THREE_BYTE_INT(aKey);
 85652        testcase( lhs<0 );
 85653        break;
 85654      }
 85655      case 4: { /* 4-byte signed integer */
 85656        y = FOUR_BYTE_UINT(aKey);
 85657        lhs = (i64)*(int*)&y;
 85658        testcase( lhs<0 );
 85659        break;
 85660      }
 85661      case 5: { /* 6-byte signed integer */
 85662        lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
 85663        testcase( lhs<0 );
 85664        break;
 85665      }
 85666      case 6: { /* 8-byte signed integer */
 85667        x = FOUR_BYTE_UINT(aKey);
 85668        x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
 85669        lhs = *(i64*)&x;
 85670        testcase( lhs<0 );
 85671        break;
 85672      }
 85673      case 8: 
 85674        lhs = 0;
 85675        break;
 85676      case 9:
 85677        lhs = 1;
 85678        break;
 85679  
 85680      /* This case could be removed without changing the results of running
 85681      ** this code. Including it causes gcc to generate a faster switch 
 85682      ** statement (since the range of switch targets now starts at zero and
 85683      ** is contiguous) but does not cause any duplicate code to be generated
 85684      ** (as gcc is clever enough to combine the two like cases). Other 
 85685      ** compilers might be similar.  */ 
 85686      case 0: case 7:
 85687        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
 85688  
 85689      default:
 85690        return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
 85691    }
 85692  
 85693    v = pPKey2->aMem[0].u.i;
 85694    if( v>lhs ){
 85695      res = pPKey2->r1;
 85696    }else if( v<lhs ){
 85697      res = pPKey2->r2;
 85698    }else if( pPKey2->nField>1 ){
 85699      /* The first fields of the two keys are equal. Compare the trailing 
 85700      ** fields.  */
 85701      res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
 85702    }else{
 85703      /* The first fields of the two keys are equal and there are no trailing
 85704      ** fields. Return pPKey2->default_rc in this case. */
 85705      res = pPKey2->default_rc;
 85706      pPKey2->eqSeen = 1;
 85707    }
 85708  
 85709    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
 85710    return res;
 85711  }
 85712  
 85713  /*
 85714  ** This function is an optimized version of sqlite3VdbeRecordCompare() 
 85715  ** that (a) the first field of pPKey2 is a string, that (b) the first field
 85716  ** uses the collation sequence BINARY and (c) that the size-of-header varint 
 85717  ** at the start of (pKey1/nKey1) fits in a single byte.
 85718  */
 85719  static int vdbeRecordCompareString(
 85720    int nKey1, const void *pKey1, /* Left key */
 85721    UnpackedRecord *pPKey2        /* Right key */
 85722  ){
 85723    const u8 *aKey1 = (const u8*)pKey1;
 85724    int serial_type;
 85725    int res;
 85726  
 85727    assert( pPKey2->aMem[0].flags & MEM_Str );
 85728    vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
 85729    getVarint32(&aKey1[1], serial_type);
 85730    if( serial_type<12 ){
 85731      res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
 85732    }else if( !(serial_type & 0x01) ){ 
 85733      res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
 85734    }else{
 85735      int nCmp;
 85736      int nStr;
 85737      int szHdr = aKey1[0];
 85738  
 85739      nStr = (serial_type-12) / 2;
 85740      if( (szHdr + nStr) > nKey1 ){
 85741        pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
 85742        return 0;    /* Corruption */
 85743      }
 85744      nCmp = MIN( pPKey2->aMem[0].n, nStr );
 85745      res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
 85746  
 85747      if( res==0 ){
 85748        res = nStr - pPKey2->aMem[0].n;
 85749        if( res==0 ){
 85750          if( pPKey2->nField>1 ){
 85751            res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
 85752          }else{
 85753            res = pPKey2->default_rc;
 85754            pPKey2->eqSeen = 1;
 85755          }
 85756        }else if( res>0 ){
 85757          res = pPKey2->r2;
 85758        }else{
 85759          res = pPKey2->r1;
 85760        }
 85761      }else if( res>0 ){
 85762        res = pPKey2->r2;
 85763      }else{
 85764        res = pPKey2->r1;
 85765      }
 85766    }
 85767  
 85768    assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
 85769         || CORRUPT_DB
 85770         || pPKey2->pKeyInfo->db->mallocFailed
 85771    );
 85772    return res;
 85773  }
 85774  
 85775  /*
 85776  ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
 85777  ** suitable for comparing serialized records to the unpacked record passed
 85778  ** as the only argument.
 85779  */
 85780  SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
 85781    /* varintRecordCompareInt() and varintRecordCompareString() both assume
 85782    ** that the size-of-header varint that occurs at the start of each record
 85783    ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
 85784    ** also assumes that it is safe to overread a buffer by at least the 
 85785    ** maximum possible legal header size plus 8 bytes. Because there is
 85786    ** guaranteed to be at least 74 (but not 136) bytes of padding following each
 85787    ** buffer passed to varintRecordCompareInt() this makes it convenient to
 85788    ** limit the size of the header to 64 bytes in cases where the first field
 85789    ** is an integer.
 85790    **
 85791    ** The easiest way to enforce this limit is to consider only records with
 85792    ** 13 fields or less. If the first field is an integer, the maximum legal
 85793    ** header size is (12*5 + 1 + 1) bytes.  */
 85794    if( p->pKeyInfo->nAllField<=13 ){
 85795      int flags = p->aMem[0].flags;
 85796      if( p->pKeyInfo->aSortOrder[0] ){
 85797        p->r1 = 1;
 85798        p->r2 = -1;
 85799      }else{
 85800        p->r1 = -1;
 85801        p->r2 = 1;
 85802      }
 85803      if( (flags & MEM_Int) ){
 85804        return vdbeRecordCompareInt;
 85805      }
 85806      testcase( flags & MEM_Real );
 85807      testcase( flags & MEM_Null );
 85808      testcase( flags & MEM_Blob );
 85809      if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
 85810        assert( flags & MEM_Str );
 85811        return vdbeRecordCompareString;
 85812      }
 85813    }
 85814  
 85815    return sqlite3VdbeRecordCompare;
 85816  }
 85817  
 85818  /*
 85819  ** pCur points at an index entry created using the OP_MakeRecord opcode.
 85820  ** Read the rowid (the last field in the record) and store it in *rowid.
 85821  ** Return SQLITE_OK if everything works, or an error code otherwise.
 85822  **
 85823  ** pCur might be pointing to text obtained from a corrupt database file.
 85824  ** So the content cannot be trusted.  Do appropriate checks on the content.
 85825  */
 85826  SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
 85827    i64 nCellKey = 0;
 85828    int rc;
 85829    u32 szHdr;        /* Size of the header */
 85830    u32 typeRowid;    /* Serial type of the rowid */
 85831    u32 lenRowid;     /* Size of the rowid */
 85832    Mem m, v;
 85833  
 85834    /* Get the size of the index entry.  Only indices entries of less
 85835    ** than 2GiB are support - anything large must be database corruption.
 85836    ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
 85837    ** this code can safely assume that nCellKey is 32-bits  
 85838    */
 85839    assert( sqlite3BtreeCursorIsValid(pCur) );
 85840    nCellKey = sqlite3BtreePayloadSize(pCur);
 85841    assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
 85842  
 85843    /* Read in the complete content of the index entry */
 85844    sqlite3VdbeMemInit(&m, db, 0);
 85845    rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
 85846    if( rc ){
 85847      return rc;
 85848    }
 85849  
 85850    /* The index entry must begin with a header size */
 85851    (void)getVarint32((u8*)m.z, szHdr);
 85852    testcase( szHdr==3 );
 85853    testcase( szHdr==m.n );
 85854    testcase( szHdr>0x7fffffff );
 85855    assert( m.n>=0 );
 85856    if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
 85857      goto idx_rowid_corruption;
 85858    }
 85859  
 85860    /* The last field of the index should be an integer - the ROWID.
 85861    ** Verify that the last entry really is an integer. */
 85862    (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
 85863    testcase( typeRowid==1 );
 85864    testcase( typeRowid==2 );
 85865    testcase( typeRowid==3 );
 85866    testcase( typeRowid==4 );
 85867    testcase( typeRowid==5 );
 85868    testcase( typeRowid==6 );
 85869    testcase( typeRowid==8 );
 85870    testcase( typeRowid==9 );
 85871    if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
 85872      goto idx_rowid_corruption;
 85873    }
 85874    lenRowid = sqlite3SmallTypeSizes[typeRowid];
 85875    testcase( (u32)m.n==szHdr+lenRowid );
 85876    if( unlikely((u32)m.n<szHdr+lenRowid) ){
 85877      goto idx_rowid_corruption;
 85878    }
 85879  
 85880    /* Fetch the integer off the end of the index record */
 85881    sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
 85882    *rowid = v.u.i;
 85883    sqlite3VdbeMemRelease(&m);
 85884    return SQLITE_OK;
 85885  
 85886    /* Jump here if database corruption is detected after m has been
 85887    ** allocated.  Free the m object and return SQLITE_CORRUPT. */
 85888  idx_rowid_corruption:
 85889    testcase( m.szMalloc!=0 );
 85890    sqlite3VdbeMemRelease(&m);
 85891    return SQLITE_CORRUPT_BKPT;
 85892  }
 85893  
 85894  /*
 85895  ** Compare the key of the index entry that cursor pC is pointing to against
 85896  ** the key string in pUnpacked.  Write into *pRes a number
 85897  ** that is negative, zero, or positive if pC is less than, equal to,
 85898  ** or greater than pUnpacked.  Return SQLITE_OK on success.
 85899  **
 85900  ** pUnpacked is either created without a rowid or is truncated so that it
 85901  ** omits the rowid at the end.  The rowid at the end of the index entry
 85902  ** is ignored as well.  Hence, this routine only compares the prefixes 
 85903  ** of the keys prior to the final rowid, not the entire key.
 85904  */
 85905  SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
 85906    sqlite3 *db,                     /* Database connection */
 85907    VdbeCursor *pC,                  /* The cursor to compare against */
 85908    UnpackedRecord *pUnpacked,       /* Unpacked version of key */
 85909    int *res                         /* Write the comparison result here */
 85910  ){
 85911    i64 nCellKey = 0;
 85912    int rc;
 85913    BtCursor *pCur;
 85914    Mem m;
 85915  
 85916    assert( pC->eCurType==CURTYPE_BTREE );
 85917    pCur = pC->uc.pCursor;
 85918    assert( sqlite3BtreeCursorIsValid(pCur) );
 85919    nCellKey = sqlite3BtreePayloadSize(pCur);
 85920    /* nCellKey will always be between 0 and 0xffffffff because of the way
 85921    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
 85922    if( nCellKey<=0 || nCellKey>0x7fffffff ){
 85923      *res = 0;
 85924      return SQLITE_CORRUPT_BKPT;
 85925    }
 85926    sqlite3VdbeMemInit(&m, db, 0);
 85927    rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
 85928    if( rc ){
 85929      return rc;
 85930    }
 85931    *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
 85932    sqlite3VdbeMemRelease(&m);
 85933    return SQLITE_OK;
 85934  }
 85935  
 85936  /*
 85937  ** This routine sets the value to be returned by subsequent calls to
 85938  ** sqlite3_changes() on the database handle 'db'. 
 85939  */
 85940  SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
 85941    assert( sqlite3_mutex_held(db->mutex) );
 85942    db->nChange = nChange;
 85943    db->nTotalChange += nChange;
 85944  }
 85945  
 85946  /*
 85947  ** Set a flag in the vdbe to update the change counter when it is finalised
 85948  ** or reset.
 85949  */
 85950  SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
 85951    v->changeCntOn = 1;
 85952  }
 85953  
 85954  /*
 85955  ** Mark every prepared statement associated with a database connection
 85956  ** as expired.
 85957  **
 85958  ** An expired statement means that recompilation of the statement is
 85959  ** recommend.  Statements expire when things happen that make their
 85960  ** programs obsolete.  Removing user-defined functions or collating
 85961  ** sequences, or changing an authorization function are the types of
 85962  ** things that make prepared statements obsolete.
 85963  **
 85964  ** If iCode is 1, then expiration is advisory.  The statement should
 85965  ** be reprepared before being restarted, but if it is already running
 85966  ** it is allowed to run to completion.
 85967  **
 85968  ** Internally, this function just sets the Vdbe.expired flag on all
 85969  ** prepared statements.  The flag is set to 1 for an immediate expiration
 85970  ** and set to 2 for an advisory expiration.
 85971  */
 85972  SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
 85973    Vdbe *p;
 85974    for(p = db->pVdbe; p; p=p->pNext){
 85975      p->expired = iCode+1;
 85976    }
 85977  }
 85978  
 85979  /*
 85980  ** Return the database associated with the Vdbe.
 85981  */
 85982  SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
 85983    return v->db;
 85984  }
 85985  
 85986  /*
 85987  ** Return the SQLITE_PREPARE flags for a Vdbe.
 85988  */
 85989  SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
 85990    return v->prepFlags;
 85991  }
 85992  
 85993  /*
 85994  ** Return a pointer to an sqlite3_value structure containing the value bound
 85995  ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
 85996  ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
 85997  ** constants) to the value before returning it.
 85998  **
 85999  ** The returned value must be freed by the caller using sqlite3ValueFree().
 86000  */
 86001  SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
 86002    assert( iVar>0 );
 86003    if( v ){
 86004      Mem *pMem = &v->aVar[iVar-1];
 86005      assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
 86006      if( 0==(pMem->flags & MEM_Null) ){
 86007        sqlite3_value *pRet = sqlite3ValueNew(v->db);
 86008        if( pRet ){
 86009          sqlite3VdbeMemCopy((Mem *)pRet, pMem);
 86010          sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
 86011        }
 86012        return pRet;
 86013      }
 86014    }
 86015    return 0;
 86016  }
 86017  
 86018  /*
 86019  ** Configure SQL variable iVar so that binding a new value to it signals
 86020  ** to sqlite3_reoptimize() that re-preparing the statement may result
 86021  ** in a better query plan.
 86022  */
 86023  SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
 86024    assert( iVar>0 );
 86025    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
 86026    if( iVar>=32 ){
 86027      v->expmask |= 0x80000000;
 86028    }else{
 86029      v->expmask |= ((u32)1 << (iVar-1));
 86030    }
 86031  }
 86032  
 86033  /*
 86034  ** Cause a function to throw an error if it was call from OP_PureFunc
 86035  ** rather than OP_Function.
 86036  **
 86037  ** OP_PureFunc means that the function must be deterministic, and should
 86038  ** throw an error if it is given inputs that would make it non-deterministic.
 86039  ** This routine is invoked by date/time functions that use non-deterministic
 86040  ** features such as 'now'.
 86041  */
 86042  SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
 86043  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 86044    if( pCtx->pVdbe==0 ) return 1;
 86045  #endif
 86046    if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
 86047      sqlite3_result_error(pCtx, 
 86048         "non-deterministic function in index expression or CHECK constraint",
 86049         -1);
 86050      return 0;
 86051    }
 86052    return 1;
 86053  }
 86054  
 86055  #ifndef SQLITE_OMIT_VIRTUALTABLE
 86056  /*
 86057  ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
 86058  ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
 86059  ** in memory obtained from sqlite3DbMalloc).
 86060  */
 86061  SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
 86062    if( pVtab->zErrMsg ){
 86063      sqlite3 *db = p->db;
 86064      sqlite3DbFree(db, p->zErrMsg);
 86065      p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
 86066      sqlite3_free(pVtab->zErrMsg);
 86067      pVtab->zErrMsg = 0;
 86068    }
 86069  }
 86070  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 86071  
 86072  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 86073  
 86074  /*
 86075  ** If the second argument is not NULL, release any allocations associated 
 86076  ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
 86077  ** structure itself, using sqlite3DbFree().
 86078  **
 86079  ** This function is used to free UnpackedRecord structures allocated by
 86080  ** the vdbeUnpackRecord() function found in vdbeapi.c.
 86081  */
 86082  static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
 86083    if( p ){
 86084      int i;
 86085      for(i=0; i<nField; i++){
 86086        Mem *pMem = &p->aMem[i];
 86087        if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
 86088      }
 86089      sqlite3DbFreeNN(db, p);
 86090    }
 86091  }
 86092  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 86093  
 86094  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 86095  /*
 86096  ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
 86097  ** then cursor passed as the second argument should point to the row about
 86098  ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
 86099  ** the required value will be read from the row the cursor points to.
 86100  */
 86101  SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
 86102    Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
 86103    VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
 86104    int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
 86105    const char *zDb,                /* Database name */
 86106    Table *pTab,                    /* Modified table */
 86107    i64 iKey1,                      /* Initial key value */
 86108    int iReg                        /* Register for new.* record */
 86109  ){
 86110    sqlite3 *db = v->db;
 86111    i64 iKey2;
 86112    PreUpdate preupdate;
 86113    const char *zTbl = pTab->zName;
 86114    static const u8 fakeSortOrder = 0;
 86115  
 86116    assert( db->pPreUpdate==0 );
 86117    memset(&preupdate, 0, sizeof(PreUpdate));
 86118    if( HasRowid(pTab)==0 ){
 86119      iKey1 = iKey2 = 0;
 86120      preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
 86121    }else{
 86122      if( op==SQLITE_UPDATE ){
 86123        iKey2 = v->aMem[iReg].u.i;
 86124      }else{
 86125        iKey2 = iKey1;
 86126      }
 86127    }
 86128  
 86129    assert( pCsr->nField==pTab->nCol 
 86130         || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
 86131    );
 86132  
 86133    preupdate.v = v;
 86134    preupdate.pCsr = pCsr;
 86135    preupdate.op = op;
 86136    preupdate.iNewReg = iReg;
 86137    preupdate.keyinfo.db = db;
 86138    preupdate.keyinfo.enc = ENC(db);
 86139    preupdate.keyinfo.nKeyField = pTab->nCol;
 86140    preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
 86141    preupdate.iKey1 = iKey1;
 86142    preupdate.iKey2 = iKey2;
 86143    preupdate.pTab = pTab;
 86144  
 86145    db->pPreUpdate = &preupdate;
 86146    db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
 86147    db->pPreUpdate = 0;
 86148    sqlite3DbFree(db, preupdate.aRecord);
 86149    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
 86150    vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
 86151    if( preupdate.aNew ){
 86152      int i;
 86153      for(i=0; i<pCsr->nField; i++){
 86154        sqlite3VdbeMemRelease(&preupdate.aNew[i]);
 86155      }
 86156      sqlite3DbFreeNN(db, preupdate.aNew);
 86157    }
 86158  }
 86159  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 86160  
 86161  /************** End of vdbeaux.c *********************************************/
 86162  /************** Begin file vdbeapi.c *****************************************/
 86163  /*
 86164  ** 2004 May 26
 86165  **
 86166  ** The author disclaims copyright to this source code.  In place of
 86167  ** a legal notice, here is a blessing:
 86168  **
 86169  **    May you do good and not evil.
 86170  **    May you find forgiveness for yourself and forgive others.
 86171  **    May you share freely, never taking more than you give.
 86172  **
 86173  *************************************************************************
 86174  **
 86175  ** This file contains code use to implement APIs that are part of the
 86176  ** VDBE.
 86177  */
 86178  /* #include "sqliteInt.h" */
 86179  /* #include "vdbeInt.h" */
 86180  
 86181  #ifndef SQLITE_OMIT_DEPRECATED
 86182  /*
 86183  ** Return TRUE (non-zero) of the statement supplied as an argument needs
 86184  ** to be recompiled.  A statement needs to be recompiled whenever the
 86185  ** execution environment changes in a way that would alter the program
 86186  ** that sqlite3_prepare() generates.  For example, if new functions or
 86187  ** collating sequences are registered or if an authorizer function is
 86188  ** added or changed.
 86189  */
 86190  SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
 86191    Vdbe *p = (Vdbe*)pStmt;
 86192    return p==0 || p->expired;
 86193  }
 86194  #endif
 86195  
 86196  /*
 86197  ** Check on a Vdbe to make sure it has not been finalized.  Log
 86198  ** an error and return true if it has been finalized (or is otherwise
 86199  ** invalid).  Return false if it is ok.
 86200  */
 86201  static int vdbeSafety(Vdbe *p){
 86202    if( p->db==0 ){
 86203      sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
 86204      return 1;
 86205    }else{
 86206      return 0;
 86207    }
 86208  }
 86209  static int vdbeSafetyNotNull(Vdbe *p){
 86210    if( p==0 ){
 86211      sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
 86212      return 1;
 86213    }else{
 86214      return vdbeSafety(p);
 86215    }
 86216  }
 86217  
 86218  #ifndef SQLITE_OMIT_TRACE
 86219  /*
 86220  ** Invoke the profile callback.  This routine is only called if we already
 86221  ** know that the profile callback is defined and needs to be invoked.
 86222  */
 86223  static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
 86224    sqlite3_int64 iNow;
 86225    sqlite3_int64 iElapse;
 86226    assert( p->startTime>0 );
 86227    assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
 86228    assert( db->init.busy==0 );
 86229    assert( p->zSql!=0 );
 86230    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
 86231    iElapse = (iNow - p->startTime)*1000000;
 86232  #ifndef SQLITE_OMIT_DEPRECATED  	
 86233    if( db->xProfile ){
 86234      db->xProfile(db->pProfileArg, p->zSql, iElapse);
 86235    }
 86236  #endif
 86237    if( db->mTrace & SQLITE_TRACE_PROFILE ){
 86238      db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
 86239    }
 86240    p->startTime = 0;
 86241  }
 86242  /*
 86243  ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
 86244  ** is needed, and it invokes the callback if it is needed.
 86245  */
 86246  # define checkProfileCallback(DB,P) \
 86247     if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
 86248  #else
 86249  # define checkProfileCallback(DB,P)  /*no-op*/
 86250  #endif
 86251  
 86252  /*
 86253  ** The following routine destroys a virtual machine that is created by
 86254  ** the sqlite3_compile() routine. The integer returned is an SQLITE_
 86255  ** success/failure code that describes the result of executing the virtual
 86256  ** machine.
 86257  **
 86258  ** This routine sets the error code and string returned by
 86259  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 86260  */
 86261  SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
 86262    int rc;
 86263    if( pStmt==0 ){
 86264      /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
 86265      ** pointer is a harmless no-op. */
 86266      rc = SQLITE_OK;
 86267    }else{
 86268      Vdbe *v = (Vdbe*)pStmt;
 86269      sqlite3 *db = v->db;
 86270      if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
 86271      sqlite3_mutex_enter(db->mutex);
 86272      checkProfileCallback(db, v);
 86273      rc = sqlite3VdbeFinalize(v);
 86274      rc = sqlite3ApiExit(db, rc);
 86275      sqlite3LeaveMutexAndCloseZombie(db);
 86276    }
 86277    return rc;
 86278  }
 86279  
 86280  /*
 86281  ** Terminate the current execution of an SQL statement and reset it
 86282  ** back to its starting state so that it can be reused. A success code from
 86283  ** the prior execution is returned.
 86284  **
 86285  ** This routine sets the error code and string returned by
 86286  ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
 86287  */
 86288  SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
 86289    int rc;
 86290    if( pStmt==0 ){
 86291      rc = SQLITE_OK;
 86292    }else{
 86293      Vdbe *v = (Vdbe*)pStmt;
 86294      sqlite3 *db = v->db;
 86295      sqlite3_mutex_enter(db->mutex);
 86296      checkProfileCallback(db, v);
 86297      rc = sqlite3VdbeReset(v);
 86298      sqlite3VdbeRewind(v);
 86299      assert( (rc & (db->errMask))==rc );
 86300      rc = sqlite3ApiExit(db, rc);
 86301      sqlite3_mutex_leave(db->mutex);
 86302    }
 86303    return rc;
 86304  }
 86305  
 86306  /*
 86307  ** Set all the parameters in the compiled SQL statement to NULL.
 86308  */
 86309  SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
 86310    int i;
 86311    int rc = SQLITE_OK;
 86312    Vdbe *p = (Vdbe*)pStmt;
 86313  #if SQLITE_THREADSAFE
 86314    sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
 86315  #endif
 86316    sqlite3_mutex_enter(mutex);
 86317    for(i=0; i<p->nVar; i++){
 86318      sqlite3VdbeMemRelease(&p->aVar[i]);
 86319      p->aVar[i].flags = MEM_Null;
 86320    }
 86321    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
 86322    if( p->expmask ){
 86323      p->expired = 1;
 86324    }
 86325    sqlite3_mutex_leave(mutex);
 86326    return rc;
 86327  }
 86328  
 86329  
 86330  /**************************** sqlite3_value_  *******************************
 86331  ** The following routines extract information from a Mem or sqlite3_value
 86332  ** structure.
 86333  */
 86334  SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
 86335    Mem *p = (Mem*)pVal;
 86336    if( p->flags & (MEM_Blob|MEM_Str) ){
 86337      if( ExpandBlob(p)!=SQLITE_OK ){
 86338        assert( p->flags==MEM_Null && p->z==0 );
 86339        return 0;
 86340      }
 86341      p->flags |= MEM_Blob;
 86342      return p->n ? p->z : 0;
 86343    }else{
 86344      return sqlite3_value_text(pVal);
 86345    }
 86346  }
 86347  SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
 86348    return sqlite3ValueBytes(pVal, SQLITE_UTF8);
 86349  }
 86350  SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
 86351    return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
 86352  }
 86353  SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
 86354    return sqlite3VdbeRealValue((Mem*)pVal);
 86355  }
 86356  SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
 86357    return (int)sqlite3VdbeIntValue((Mem*)pVal);
 86358  }
 86359  SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
 86360    return sqlite3VdbeIntValue((Mem*)pVal);
 86361  }
 86362  SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
 86363    Mem *pMem = (Mem*)pVal;
 86364    return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
 86365  }
 86366  SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
 86367    Mem *p = (Mem*)pVal;
 86368    if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
 86369                   (MEM_Null|MEM_Term|MEM_Subtype)
 86370     && zPType!=0
 86371     && p->eSubtype=='p'
 86372     && strcmp(p->u.zPType, zPType)==0
 86373    ){
 86374      return (void*)p->z;
 86375    }else{
 86376      return 0;
 86377    }
 86378  }
 86379  SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
 86380    return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
 86381  }
 86382  #ifndef SQLITE_OMIT_UTF16
 86383  SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
 86384    return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
 86385  }
 86386  SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
 86387    return sqlite3ValueText(pVal, SQLITE_UTF16BE);
 86388  }
 86389  SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
 86390    return sqlite3ValueText(pVal, SQLITE_UTF16LE);
 86391  }
 86392  #endif /* SQLITE_OMIT_UTF16 */
 86393  /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
 86394  ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
 86395  ** point number string BLOB NULL
 86396  */
 86397  SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
 86398    static const u8 aType[] = {
 86399       SQLITE_BLOB,     /* 0x00 */
 86400       SQLITE_NULL,     /* 0x01 */
 86401       SQLITE_TEXT,     /* 0x02 */
 86402       SQLITE_NULL,     /* 0x03 */
 86403       SQLITE_INTEGER,  /* 0x04 */
 86404       SQLITE_NULL,     /* 0x05 */
 86405       SQLITE_INTEGER,  /* 0x06 */
 86406       SQLITE_NULL,     /* 0x07 */
 86407       SQLITE_FLOAT,    /* 0x08 */
 86408       SQLITE_NULL,     /* 0x09 */
 86409       SQLITE_FLOAT,    /* 0x0a */
 86410       SQLITE_NULL,     /* 0x0b */
 86411       SQLITE_INTEGER,  /* 0x0c */
 86412       SQLITE_NULL,     /* 0x0d */
 86413       SQLITE_INTEGER,  /* 0x0e */
 86414       SQLITE_NULL,     /* 0x0f */
 86415       SQLITE_BLOB,     /* 0x10 */
 86416       SQLITE_NULL,     /* 0x11 */
 86417       SQLITE_TEXT,     /* 0x12 */
 86418       SQLITE_NULL,     /* 0x13 */
 86419       SQLITE_INTEGER,  /* 0x14 */
 86420       SQLITE_NULL,     /* 0x15 */
 86421       SQLITE_INTEGER,  /* 0x16 */
 86422       SQLITE_NULL,     /* 0x17 */
 86423       SQLITE_FLOAT,    /* 0x18 */
 86424       SQLITE_NULL,     /* 0x19 */
 86425       SQLITE_FLOAT,    /* 0x1a */
 86426       SQLITE_NULL,     /* 0x1b */
 86427       SQLITE_INTEGER,  /* 0x1c */
 86428       SQLITE_NULL,     /* 0x1d */
 86429       SQLITE_INTEGER,  /* 0x1e */
 86430       SQLITE_NULL,     /* 0x1f */
 86431    };
 86432    return aType[pVal->flags&MEM_AffMask];
 86433  }
 86434  
 86435  /* Return true if a parameter to xUpdate represents an unchanged column */
 86436  SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
 86437    return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
 86438  }
 86439  
 86440  /* Make a copy of an sqlite3_value object
 86441  */
 86442  SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
 86443    sqlite3_value *pNew;
 86444    if( pOrig==0 ) return 0;
 86445    pNew = sqlite3_malloc( sizeof(*pNew) );
 86446    if( pNew==0 ) return 0;
 86447    memset(pNew, 0, sizeof(*pNew));
 86448    memcpy(pNew, pOrig, MEMCELLSIZE);
 86449    pNew->flags &= ~MEM_Dyn;
 86450    pNew->db = 0;
 86451    if( pNew->flags&(MEM_Str|MEM_Blob) ){
 86452      pNew->flags &= ~(MEM_Static|MEM_Dyn);
 86453      pNew->flags |= MEM_Ephem;
 86454      if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
 86455        sqlite3ValueFree(pNew);
 86456        pNew = 0;
 86457      }
 86458    }
 86459    return pNew;
 86460  }
 86461  
 86462  /* Destroy an sqlite3_value object previously obtained from
 86463  ** sqlite3_value_dup().
 86464  */
 86465  SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
 86466    sqlite3ValueFree(pOld);
 86467  }
 86468    
 86469  
 86470  /**************************** sqlite3_result_  *******************************
 86471  ** The following routines are used by user-defined functions to specify
 86472  ** the function result.
 86473  **
 86474  ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
 86475  ** result as a string or blob but if the string or blob is too large, it
 86476  ** then sets the error code to SQLITE_TOOBIG
 86477  **
 86478  ** The invokeValueDestructor(P,X) routine invokes destructor function X()
 86479  ** on value P is not going to be used and need to be destroyed.
 86480  */
 86481  static void setResultStrOrError(
 86482    sqlite3_context *pCtx,  /* Function context */
 86483    const char *z,          /* String pointer */
 86484    int n,                  /* Bytes in string, or negative */
 86485    u8 enc,                 /* Encoding of z.  0 for BLOBs */
 86486    void (*xDel)(void*)     /* Destructor function */
 86487  ){
 86488    if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
 86489      sqlite3_result_error_toobig(pCtx);
 86490    }
 86491  }
 86492  static int invokeValueDestructor(
 86493    const void *p,             /* Value to destroy */
 86494    void (*xDel)(void*),       /* The destructor */
 86495    sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
 86496  ){
 86497    assert( xDel!=SQLITE_DYNAMIC );
 86498    if( xDel==0 ){
 86499      /* noop */
 86500    }else if( xDel==SQLITE_TRANSIENT ){
 86501      /* noop */
 86502    }else{
 86503      xDel((void*)p);
 86504    }
 86505    if( pCtx ) sqlite3_result_error_toobig(pCtx);
 86506    return SQLITE_TOOBIG;
 86507  }
 86508  SQLITE_API void sqlite3_result_blob(
 86509    sqlite3_context *pCtx, 
 86510    const void *z, 
 86511    int n, 
 86512    void (*xDel)(void *)
 86513  ){
 86514    assert( n>=0 );
 86515    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86516    setResultStrOrError(pCtx, z, n, 0, xDel);
 86517  }
 86518  SQLITE_API void sqlite3_result_blob64(
 86519    sqlite3_context *pCtx, 
 86520    const void *z, 
 86521    sqlite3_uint64 n,
 86522    void (*xDel)(void *)
 86523  ){
 86524    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86525    assert( xDel!=SQLITE_DYNAMIC );
 86526    if( n>0x7fffffff ){
 86527      (void)invokeValueDestructor(z, xDel, pCtx);
 86528    }else{
 86529      setResultStrOrError(pCtx, z, (int)n, 0, xDel);
 86530    }
 86531  }
 86532  SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
 86533    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86534    sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
 86535  }
 86536  SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
 86537    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86538    pCtx->isError = SQLITE_ERROR;
 86539    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
 86540  }
 86541  #ifndef SQLITE_OMIT_UTF16
 86542  SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
 86543    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86544    pCtx->isError = SQLITE_ERROR;
 86545    sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
 86546  }
 86547  #endif
 86548  SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
 86549    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86550    sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
 86551  }
 86552  SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
 86553    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86554    sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
 86555  }
 86556  SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
 86557    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86558    sqlite3VdbeMemSetNull(pCtx->pOut);
 86559  }
 86560  SQLITE_API void sqlite3_result_pointer(
 86561    sqlite3_context *pCtx,
 86562    void *pPtr,
 86563    const char *zPType,
 86564    void (*xDestructor)(void*)
 86565  ){
 86566    Mem *pOut = pCtx->pOut;
 86567    assert( sqlite3_mutex_held(pOut->db->mutex) );
 86568    sqlite3VdbeMemRelease(pOut);
 86569    pOut->flags = MEM_Null;
 86570    sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
 86571  }
 86572  SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
 86573    Mem *pOut = pCtx->pOut;
 86574    assert( sqlite3_mutex_held(pOut->db->mutex) );
 86575    pOut->eSubtype = eSubtype & 0xff;
 86576    pOut->flags |= MEM_Subtype;
 86577  }
 86578  SQLITE_API void sqlite3_result_text(
 86579    sqlite3_context *pCtx, 
 86580    const char *z, 
 86581    int n,
 86582    void (*xDel)(void *)
 86583  ){
 86584    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86585    setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
 86586  }
 86587  SQLITE_API void sqlite3_result_text64(
 86588    sqlite3_context *pCtx, 
 86589    const char *z, 
 86590    sqlite3_uint64 n,
 86591    void (*xDel)(void *),
 86592    unsigned char enc
 86593  ){
 86594    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86595    assert( xDel!=SQLITE_DYNAMIC );
 86596    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
 86597    if( n>0x7fffffff ){
 86598      (void)invokeValueDestructor(z, xDel, pCtx);
 86599    }else{
 86600      setResultStrOrError(pCtx, z, (int)n, enc, xDel);
 86601    }
 86602  }
 86603  #ifndef SQLITE_OMIT_UTF16
 86604  SQLITE_API void sqlite3_result_text16(
 86605    sqlite3_context *pCtx, 
 86606    const void *z, 
 86607    int n, 
 86608    void (*xDel)(void *)
 86609  ){
 86610    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86611    setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
 86612  }
 86613  SQLITE_API void sqlite3_result_text16be(
 86614    sqlite3_context *pCtx, 
 86615    const void *z, 
 86616    int n, 
 86617    void (*xDel)(void *)
 86618  ){
 86619    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86620    setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
 86621  }
 86622  SQLITE_API void sqlite3_result_text16le(
 86623    sqlite3_context *pCtx, 
 86624    const void *z, 
 86625    int n, 
 86626    void (*xDel)(void *)
 86627  ){
 86628    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86629    setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
 86630  }
 86631  #endif /* SQLITE_OMIT_UTF16 */
 86632  SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
 86633    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86634    sqlite3VdbeMemCopy(pCtx->pOut, pValue);
 86635  }
 86636  SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
 86637    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86638    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
 86639  }
 86640  SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
 86641    Mem *pOut = pCtx->pOut;
 86642    assert( sqlite3_mutex_held(pOut->db->mutex) );
 86643    if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
 86644      return SQLITE_TOOBIG;
 86645    }
 86646    sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
 86647    return SQLITE_OK;
 86648  }
 86649  SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
 86650    pCtx->isError = errCode ? errCode : -1;
 86651  #ifdef SQLITE_DEBUG
 86652    if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
 86653  #endif
 86654    if( pCtx->pOut->flags & MEM_Null ){
 86655      sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
 86656                           SQLITE_UTF8, SQLITE_STATIC);
 86657    }
 86658  }
 86659  
 86660  /* Force an SQLITE_TOOBIG error. */
 86661  SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
 86662    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86663    pCtx->isError = SQLITE_TOOBIG;
 86664    sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
 86665                         SQLITE_UTF8, SQLITE_STATIC);
 86666  }
 86667  
 86668  /* An SQLITE_NOMEM error. */
 86669  SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
 86670    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 86671    sqlite3VdbeMemSetNull(pCtx->pOut);
 86672    pCtx->isError = SQLITE_NOMEM_BKPT;
 86673    sqlite3OomFault(pCtx->pOut->db);
 86674  }
 86675  
 86676  /*
 86677  ** This function is called after a transaction has been committed. It 
 86678  ** invokes callbacks registered with sqlite3_wal_hook() as required.
 86679  */
 86680  static int doWalCallbacks(sqlite3 *db){
 86681    int rc = SQLITE_OK;
 86682  #ifndef SQLITE_OMIT_WAL
 86683    int i;
 86684    for(i=0; i<db->nDb; i++){
 86685      Btree *pBt = db->aDb[i].pBt;
 86686      if( pBt ){
 86687        int nEntry;
 86688        sqlite3BtreeEnter(pBt);
 86689        nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
 86690        sqlite3BtreeLeave(pBt);
 86691        if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
 86692          rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
 86693        }
 86694      }
 86695    }
 86696  #endif
 86697    return rc;
 86698  }
 86699  
 86700  
 86701  /*
 86702  ** Execute the statement pStmt, either until a row of data is ready, the
 86703  ** statement is completely executed or an error occurs.
 86704  **
 86705  ** This routine implements the bulk of the logic behind the sqlite_step()
 86706  ** API.  The only thing omitted is the automatic recompile if a 
 86707  ** schema change has occurred.  That detail is handled by the
 86708  ** outer sqlite3_step() wrapper procedure.
 86709  */
 86710  static int sqlite3Step(Vdbe *p){
 86711    sqlite3 *db;
 86712    int rc;
 86713  
 86714    assert(p);
 86715    if( p->magic!=VDBE_MAGIC_RUN ){
 86716      /* We used to require that sqlite3_reset() be called before retrying
 86717      ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
 86718      ** with version 3.7.0, we changed this so that sqlite3_reset() would
 86719      ** be called automatically instead of throwing the SQLITE_MISUSE error.
 86720      ** This "automatic-reset" change is not technically an incompatibility, 
 86721      ** since any application that receives an SQLITE_MISUSE is broken by
 86722      ** definition.
 86723      **
 86724      ** Nevertheless, some published applications that were originally written
 86725      ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
 86726      ** returns, and those were broken by the automatic-reset change.  As a
 86727      ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
 86728      ** legacy behavior of returning SQLITE_MISUSE for cases where the 
 86729      ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
 86730      ** or SQLITE_BUSY error.
 86731      */
 86732  #ifdef SQLITE_OMIT_AUTORESET
 86733      if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
 86734        sqlite3_reset((sqlite3_stmt*)p);
 86735      }else{
 86736        return SQLITE_MISUSE_BKPT;
 86737      }
 86738  #else
 86739      sqlite3_reset((sqlite3_stmt*)p);
 86740  #endif
 86741    }
 86742  
 86743    /* Check that malloc() has not failed. If it has, return early. */
 86744    db = p->db;
 86745    if( db->mallocFailed ){
 86746      p->rc = SQLITE_NOMEM;
 86747      return SQLITE_NOMEM_BKPT;
 86748    }
 86749  
 86750    if( p->pc<0 && p->expired ){
 86751      p->rc = SQLITE_SCHEMA;
 86752      rc = SQLITE_ERROR;
 86753      goto end_of_step;
 86754    }
 86755  
 86756  #ifndef OMIT_BRANCH_LOG
 86757    /* Process only top-level commands */
 86758    if( db->nVdbeExec==0 && p->pc<0 && !p->doingRerun ){
 86759      /* Check the first operation/instruction */
 86760      if( p->nOp>=1 ){
 86761        const VdbeOp *pOp = &p->aOp[0];
 86762        char *zSql = (pOp->p4.z ? pOp->p4.z : p->zSql);
 86763        if( pOp->opcode==OP_Init && zSql ){
 86764          /* Check the current SQL command for log */
 86765          litetreeCheckExecCommand(db, p, zSql);
 86766        }
 86767      }
 86768    }
 86769  #endif
 86770  
 86771    if( p->pc<0 ){
 86772      /* If there are no other statements currently running, then
 86773      ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
 86774      ** from interrupting a statement that has not yet started.
 86775      */
 86776      if( db->nVdbeActive==0 ){
 86777        db->u1.isInterrupted = 0;
 86778      }
 86779  
 86780      assert( db->nVdbeWrite>0 || db->autoCommit==0 
 86781          || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
 86782      );
 86783  
 86784  #ifndef SQLITE_OMIT_TRACE
 86785      if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
 86786          && !db->init.busy && p->zSql ){
 86787        sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
 86788      }else{
 86789        assert( p->startTime==0 );
 86790      }
 86791  #endif
 86792  
 86793      db->nVdbeActive++;
 86794      if( p->readOnly==0 ) db->nVdbeWrite++;
 86795      if( p->bIsReader ) db->nVdbeRead++;
 86796      p->pc = 0;
 86797    }
 86798  #ifdef SQLITE_DEBUG
 86799    p->rcApp = SQLITE_OK;
 86800  #endif
 86801  #ifndef SQLITE_OMIT_EXPLAIN
 86802    if( p->explain ){
 86803      rc = sqlite3VdbeList(p);
 86804    }else
 86805  #endif /* SQLITE_OMIT_EXPLAIN */
 86806    {
 86807      db->nVdbeExec++;
 86808      rc = sqlite3VdbeExec(p);
 86809      db->nVdbeExec--;
 86810    }
 86811  
 86812    if( rc!=SQLITE_ROW ){
 86813  #ifndef SQLITE_OMIT_TRACE
 86814      /* If the statement completed successfully, invoke the profile callback */
 86815      checkProfileCallback(db, p);
 86816  #endif
 86817  
 86818      if( rc==SQLITE_DONE && db->autoCommit ){
 86819        assert( p->rc==SQLITE_OK );
 86820        p->rc = doWalCallbacks(db);
 86821        if( p->rc!=SQLITE_OK ){
 86822          rc = SQLITE_ERROR;
 86823        }
 86824      }
 86825    }
 86826  
 86827  #ifndef OMIT_BRANCH_LOG
 86828    /* Process only top-level commands */
 86829    if( db->nVdbeExec==0 ){
 86830      litetreeCheckExecResult(db, rc);
 86831    }
 86832  #endif
 86833  
 86834    db->errCode = rc;
 86835    if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
 86836      p->rc = SQLITE_NOMEM_BKPT;
 86837    }
 86838  end_of_step:
 86839    /* At this point local variable rc holds the value that should be 
 86840    ** returned if this statement was compiled using the legacy 
 86841    ** sqlite3_prepare() interface. According to the docs, this can only
 86842    ** be one of the values in the first assert() below. Variable p->rc 
 86843    ** contains the value that would be returned if sqlite3_finalize() 
 86844    ** were called on statement p.
 86845    */
 86846    assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
 86847         || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
 86848    );
 86849    assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
 86850    if( rc!=SQLITE_ROW 
 86851     && rc!=SQLITE_DONE
 86852     && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
 86853    ){
 86854      /* If this statement was prepared using saved SQL and an 
 86855      ** error has occurred, then return the error code in p->rc to the
 86856      ** caller. Set the error code in the database handle to the same value.
 86857      */ 
 86858      rc = sqlite3VdbeTransferError(p);
 86859    }
 86860    return (rc&db->errMask);
 86861  }
 86862  
 86863  /*
 86864  ** This is the top-level implementation of sqlite3_step().  Call
 86865  ** sqlite3Step() to do most of the work.  If a schema error occurs,
 86866  ** call sqlite3Reprepare() and try again.
 86867  */
 86868  SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
 86869    int rc = SQLITE_OK;      /* Result from sqlite3Step() */
 86870    Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
 86871    int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
 86872    sqlite3 *db;             /* The database connection */
 86873  
 86874    if( vdbeSafetyNotNull(v) ){
 86875      return SQLITE_MISUSE_BKPT;
 86876    }
 86877    db = v->db;
 86878    sqlite3_mutex_enter(db->mutex);
 86879    v->doingRerun = 0;
 86880    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
 86881           && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
 86882      int savedPc = v->pc;
 86883      rc = sqlite3Reprepare(v);
 86884      if( rc!=SQLITE_OK ){
 86885        /* This case occurs after failing to recompile an sql statement. 
 86886        ** The error message from the SQL compiler has already been loaded 
 86887        ** into the database handle. This block copies the error message 
 86888        ** from the database handle into the statement and sets the statement
 86889        ** program counter to 0 to ensure that when the statement is 
 86890        ** finalized or reset the parser error message is available via
 86891        ** sqlite3_errmsg() and sqlite3_errcode().
 86892        */
 86893        const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
 86894        sqlite3DbFree(db, v->zErrMsg);
 86895        if( !db->mallocFailed ){
 86896          v->zErrMsg = sqlite3DbStrDup(db, zErr);
 86897          v->rc = rc = sqlite3ApiExit(db, rc);
 86898        } else {
 86899          v->zErrMsg = 0;
 86900          v->rc = rc = SQLITE_NOMEM_BKPT;
 86901        }
 86902        break;
 86903      }
 86904      sqlite3_reset(pStmt);
 86905      if( savedPc>=0 ) v->doingRerun = 1;
 86906      assert( v->expired==0 );
 86907    }
 86908    sqlite3_mutex_leave(db->mutex);
 86909    return rc;
 86910  }
 86911  
 86912  
 86913  /*
 86914  ** Extract the user data from a sqlite3_context structure and return a
 86915  ** pointer to it.
 86916  */
 86917  SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
 86918    assert( p && p->pFunc );
 86919    return p->pFunc->pUserData;
 86920  }
 86921  
 86922  /*
 86923  ** Extract the user data from a sqlite3_context structure and return a
 86924  ** pointer to it.
 86925  **
 86926  ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
 86927  ** returns a copy of the pointer to the database connection (the 1st
 86928  ** parameter) of the sqlite3_create_function() and
 86929  ** sqlite3_create_function16() routines that originally registered the
 86930  ** application defined function.
 86931  */
 86932  SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
 86933    assert( p && p->pOut );
 86934    return p->pOut->db;
 86935  }
 86936  
 86937  /*
 86938  ** If this routine is invoked from within an xColumn method of a virtual
 86939  ** table, then it returns true if and only if the the call is during an
 86940  ** UPDATE operation and the value of the column will not be modified
 86941  ** by the UPDATE.
 86942  **
 86943  ** If this routine is called from any context other than within the
 86944  ** xColumn method of a virtual table, then the return value is meaningless
 86945  ** and arbitrary.
 86946  **
 86947  ** Virtual table implements might use this routine to optimize their
 86948  ** performance by substituting a NULL result, or some other light-weight
 86949  ** value, as a signal to the xUpdate routine that the column is unchanged.
 86950  */
 86951  SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
 86952    assert( p );
 86953    return sqlite3_value_nochange(p->pOut);
 86954  }
 86955  
 86956  /*
 86957  ** Return the current time for a statement.  If the current time
 86958  ** is requested more than once within the same run of a single prepared
 86959  ** statement, the exact same time is returned for each invocation regardless
 86960  ** of the amount of time that elapses between invocations.  In other words,
 86961  ** the time returned is always the time of the first call.
 86962  */
 86963  SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
 86964    int rc;
 86965  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
 86966    sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
 86967    assert( p->pVdbe!=0 );
 86968  #else
 86969    sqlite3_int64 iTime = 0;
 86970    sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
 86971  #endif
 86972    if( *piTime==0 ){
 86973      rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
 86974      if( rc ) *piTime = 0;
 86975    }
 86976    return *piTime;
 86977  }
 86978  
 86979  /*
 86980  ** Create a new aggregate context for p and return a pointer to
 86981  ** its pMem->z element.
 86982  */
 86983  static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
 86984    Mem *pMem = p->pMem;
 86985    assert( (pMem->flags & MEM_Agg)==0 );
 86986    if( nByte<=0 ){
 86987      sqlite3VdbeMemSetNull(pMem);
 86988      pMem->z = 0;
 86989    }else{
 86990      sqlite3VdbeMemClearAndResize(pMem, nByte);
 86991      pMem->flags = MEM_Agg;
 86992      pMem->u.pDef = p->pFunc;
 86993      if( pMem->z ){
 86994        memset(pMem->z, 0, nByte);
 86995      }
 86996    }
 86997    return (void*)pMem->z;
 86998  }
 86999  
 87000  /*
 87001  ** Allocate or return the aggregate context for a user function.  A new
 87002  ** context is allocated on the first call.  Subsequent calls return the
 87003  ** same context that was returned on prior calls.
 87004  */
 87005  SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
 87006    assert( p && p->pFunc && p->pFunc->xFinalize );
 87007    assert( sqlite3_mutex_held(p->pOut->db->mutex) );
 87008    testcase( nByte<0 );
 87009    if( (p->pMem->flags & MEM_Agg)==0 ){
 87010      return createAggContext(p, nByte);
 87011    }else{
 87012      return (void*)p->pMem->z;
 87013    }
 87014  }
 87015  
 87016  /*
 87017  ** Return the auxiliary data pointer, if any, for the iArg'th argument to
 87018  ** the user-function defined by pCtx.
 87019  **
 87020  ** The left-most argument is 0.
 87021  **
 87022  ** Undocumented behavior:  If iArg is negative then access a cache of
 87023  ** auxiliary data pointers that is available to all functions within a
 87024  ** single prepared statement.  The iArg values must match.
 87025  */
 87026  SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
 87027    AuxData *pAuxData;
 87028  
 87029    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 87030  #if SQLITE_ENABLE_STAT3_OR_STAT4
 87031    if( pCtx->pVdbe==0 ) return 0;
 87032  #else
 87033    assert( pCtx->pVdbe!=0 );
 87034  #endif
 87035    for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
 87036      if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
 87037        return pAuxData->pAux;
 87038      }
 87039    }
 87040    return 0;
 87041  }
 87042  
 87043  /*
 87044  ** Set the auxiliary data pointer and delete function, for the iArg'th
 87045  ** argument to the user-function defined by pCtx. Any previous value is
 87046  ** deleted by calling the delete function specified when it was set.
 87047  **
 87048  ** The left-most argument is 0.
 87049  **
 87050  ** Undocumented behavior:  If iArg is negative then make the data available
 87051  ** to all functions within the current prepared statement using iArg as an
 87052  ** access code.
 87053  */
 87054  SQLITE_API void sqlite3_set_auxdata(
 87055    sqlite3_context *pCtx, 
 87056    int iArg, 
 87057    void *pAux, 
 87058    void (*xDelete)(void*)
 87059  ){
 87060    AuxData *pAuxData;
 87061    Vdbe *pVdbe = pCtx->pVdbe;
 87062  
 87063    assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
 87064  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 87065    if( pVdbe==0 ) goto failed;
 87066  #else
 87067    assert( pVdbe!=0 );
 87068  #endif
 87069  
 87070    for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
 87071      if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
 87072        break;
 87073      }
 87074    }
 87075    if( pAuxData==0 ){
 87076      pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
 87077      if( !pAuxData ) goto failed;
 87078      pAuxData->iAuxOp = pCtx->iOp;
 87079      pAuxData->iAuxArg = iArg;
 87080      pAuxData->pNextAux = pVdbe->pAuxData;
 87081      pVdbe->pAuxData = pAuxData;
 87082      if( pCtx->isError==0 ) pCtx->isError = -1;
 87083    }else if( pAuxData->xDeleteAux ){
 87084      pAuxData->xDeleteAux(pAuxData->pAux);
 87085    }
 87086  
 87087    pAuxData->pAux = pAux;
 87088    pAuxData->xDeleteAux = xDelete;
 87089    return;
 87090  
 87091  failed:
 87092    if( xDelete ){
 87093      xDelete(pAux);
 87094    }
 87095  }
 87096  
 87097  #ifndef SQLITE_OMIT_DEPRECATED
 87098  /*
 87099  ** Return the number of times the Step function of an aggregate has been 
 87100  ** called.
 87101  **
 87102  ** This function is deprecated.  Do not use it for new code.  It is
 87103  ** provide only to avoid breaking legacy code.  New aggregate function
 87104  ** implementations should keep their own counts within their aggregate
 87105  ** context.
 87106  */
 87107  SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
 87108    assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
 87109    return p->pMem->n;
 87110  }
 87111  #endif
 87112  
 87113  /*
 87114  ** Return the number of columns in the result set for the statement pStmt.
 87115  */
 87116  SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
 87117    Vdbe *pVm = (Vdbe *)pStmt;
 87118    return pVm ? pVm->nResColumn : 0;
 87119  }
 87120  
 87121  /*
 87122  ** Return the number of values available from the current row of the
 87123  ** currently executing statement pStmt.
 87124  */
 87125  SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
 87126    Vdbe *pVm = (Vdbe *)pStmt;
 87127    if( pVm==0 || pVm->pResultSet==0 ) return 0;
 87128    return pVm->nResColumn;
 87129  }
 87130  
 87131  /*
 87132  ** Return a pointer to static memory containing an SQL NULL value.
 87133  */
 87134  static const Mem *columnNullValue(void){
 87135    /* Even though the Mem structure contains an element
 87136    ** of type i64, on certain architectures (x86) with certain compiler
 87137    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
 87138    ** instead of an 8-byte one. This all works fine, except that when
 87139    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
 87140    ** that a Mem structure is located on an 8-byte boundary. To prevent
 87141    ** these assert()s from failing, when building with SQLITE_DEBUG defined
 87142    ** using gcc, we force nullMem to be 8-byte aligned using the magical
 87143    ** __attribute__((aligned(8))) macro.  */
 87144    static const Mem nullMem 
 87145  #if defined(SQLITE_DEBUG) && defined(__GNUC__)
 87146      __attribute__((aligned(8))) 
 87147  #endif
 87148      = {
 87149          /* .u          = */ {0},
 87150          /* .flags      = */ (u16)MEM_Null,
 87151          /* .enc        = */ (u8)0,
 87152          /* .eSubtype   = */ (u8)0,
 87153          /* .n          = */ (int)0,
 87154          /* .z          = */ (char*)0,
 87155          /* .zMalloc    = */ (char*)0,
 87156          /* .szMalloc   = */ (int)0,
 87157          /* .uTemp      = */ (u32)0,
 87158          /* .db         = */ (sqlite3*)0,
 87159          /* .xDel       = */ (void(*)(void*))0,
 87160  #ifdef SQLITE_DEBUG
 87161          /* .pScopyFrom = */ (Mem*)0,
 87162          /* .mScopyFlags= */ 0,
 87163  #endif
 87164        };
 87165    return &nullMem;
 87166  }
 87167  
 87168  /*
 87169  ** Check to see if column iCol of the given statement is valid.  If
 87170  ** it is, return a pointer to the Mem for the value of that column.
 87171  ** If iCol is not valid, return a pointer to a Mem which has a value
 87172  ** of NULL.
 87173  */
 87174  static Mem *columnMem(sqlite3_stmt *pStmt, int i){
 87175    Vdbe *pVm;
 87176    Mem *pOut;
 87177  
 87178    pVm = (Vdbe *)pStmt;
 87179    if( pVm==0 ) return (Mem*)columnNullValue();
 87180    assert( pVm->db );
 87181    sqlite3_mutex_enter(pVm->db->mutex);
 87182    if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
 87183      pOut = &pVm->pResultSet[i];
 87184    }else{
 87185      sqlite3Error(pVm->db, SQLITE_RANGE);
 87186      pOut = (Mem*)columnNullValue();
 87187    }
 87188    return pOut;
 87189  }
 87190  
 87191  /*
 87192  ** This function is called after invoking an sqlite3_value_XXX function on a 
 87193  ** column value (i.e. a value returned by evaluating an SQL expression in the
 87194  ** select list of a SELECT statement) that may cause a malloc() failure. If 
 87195  ** malloc() has failed, the threads mallocFailed flag is cleared and the result
 87196  ** code of statement pStmt set to SQLITE_NOMEM.
 87197  **
 87198  ** Specifically, this is called from within:
 87199  **
 87200  **     sqlite3_column_int()
 87201  **     sqlite3_column_int64()
 87202  **     sqlite3_column_text()
 87203  **     sqlite3_column_text16()
 87204  **     sqlite3_column_real()
 87205  **     sqlite3_column_bytes()
 87206  **     sqlite3_column_bytes16()
 87207  **     sqiite3_column_blob()
 87208  */
 87209  static void columnMallocFailure(sqlite3_stmt *pStmt)
 87210  {
 87211    /* If malloc() failed during an encoding conversion within an
 87212    ** sqlite3_column_XXX API, then set the return code of the statement to
 87213    ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
 87214    ** and _finalize() will return NOMEM.
 87215    */
 87216    Vdbe *p = (Vdbe *)pStmt;
 87217    if( p ){
 87218      assert( p->db!=0 );
 87219      assert( sqlite3_mutex_held(p->db->mutex) );
 87220      p->rc = sqlite3ApiExit(p->db, p->rc);
 87221      sqlite3_mutex_leave(p->db->mutex);
 87222    }
 87223  }
 87224  
 87225  /**************************** sqlite3_column_  *******************************
 87226  ** The following routines are used to access elements of the current row
 87227  ** in the result set.
 87228  */
 87229  SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
 87230    const void *val;
 87231    val = sqlite3_value_blob( columnMem(pStmt,i) );
 87232    /* Even though there is no encoding conversion, value_blob() might
 87233    ** need to call malloc() to expand the result of a zeroblob() 
 87234    ** expression. 
 87235    */
 87236    columnMallocFailure(pStmt);
 87237    return val;
 87238  }
 87239  SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
 87240    int val = sqlite3_value_bytes( columnMem(pStmt,i) );
 87241    columnMallocFailure(pStmt);
 87242    return val;
 87243  }
 87244  SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
 87245    int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
 87246    columnMallocFailure(pStmt);
 87247    return val;
 87248  }
 87249  SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
 87250    double val = sqlite3_value_double( columnMem(pStmt,i) );
 87251    columnMallocFailure(pStmt);
 87252    return val;
 87253  }
 87254  SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
 87255    int val = sqlite3_value_int( columnMem(pStmt,i) );
 87256    columnMallocFailure(pStmt);
 87257    return val;
 87258  }
 87259  SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
 87260    sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
 87261    columnMallocFailure(pStmt);
 87262    return val;
 87263  }
 87264  SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
 87265    const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
 87266    columnMallocFailure(pStmt);
 87267    return val;
 87268  }
 87269  SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
 87270    Mem *pOut = columnMem(pStmt, i);
 87271    if( pOut->flags&MEM_Static ){
 87272      pOut->flags &= ~MEM_Static;
 87273      pOut->flags |= MEM_Ephem;
 87274    }
 87275    columnMallocFailure(pStmt);
 87276    return (sqlite3_value *)pOut;
 87277  }
 87278  #ifndef SQLITE_OMIT_UTF16
 87279  SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
 87280    const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
 87281    columnMallocFailure(pStmt);
 87282    return val;
 87283  }
 87284  #endif /* SQLITE_OMIT_UTF16 */
 87285  SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
 87286    int iType = sqlite3_value_type( columnMem(pStmt,i) );
 87287    columnMallocFailure(pStmt);
 87288    return iType;
 87289  }
 87290  
 87291  /*
 87292  ** Convert the N-th element of pStmt->pColName[] into a string using
 87293  ** xFunc() then return that string.  If N is out of range, return 0.
 87294  **
 87295  ** There are up to 5 names for each column.  useType determines which
 87296  ** name is returned.  Here are the names:
 87297  **
 87298  **    0      The column name as it should be displayed for output
 87299  **    1      The datatype name for the column
 87300  **    2      The name of the database that the column derives from
 87301  **    3      The name of the table that the column derives from
 87302  **    4      The name of the table column that the result column derives from
 87303  **
 87304  ** If the result is not a simple column reference (if it is an expression
 87305  ** or a constant) then useTypes 2, 3, and 4 return NULL.
 87306  */
 87307  static const void *columnName(
 87308    sqlite3_stmt *pStmt,
 87309    int N,
 87310    const void *(*xFunc)(Mem*),
 87311    int useType
 87312  ){
 87313    const void *ret;
 87314    Vdbe *p;
 87315    int n;
 87316    sqlite3 *db;
 87317  #ifdef SQLITE_ENABLE_API_ARMOR
 87318    if( pStmt==0 ){
 87319      (void)SQLITE_MISUSE_BKPT;
 87320      return 0;
 87321    }
 87322  #endif
 87323    ret = 0;
 87324    p = (Vdbe *)pStmt;
 87325    db = p->db;
 87326    assert( db!=0 );
 87327    n = sqlite3_column_count(pStmt);
 87328    if( N<n && N>=0 ){
 87329      N += useType*n;
 87330      sqlite3_mutex_enter(db->mutex);
 87331      assert( db->mallocFailed==0 );
 87332      ret = xFunc(&p->aColName[N]);
 87333       /* A malloc may have failed inside of the xFunc() call. If this
 87334      ** is the case, clear the mallocFailed flag and return NULL.
 87335      */
 87336      if( db->mallocFailed ){
 87337        sqlite3OomClear(db);
 87338        ret = 0;
 87339      }
 87340      sqlite3_mutex_leave(db->mutex);
 87341    }
 87342    return ret;
 87343  }
 87344  
 87345  /*
 87346  ** Return the name of the Nth column of the result set returned by SQL
 87347  ** statement pStmt.
 87348  */
 87349  SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
 87350    return columnName(
 87351        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
 87352  }
 87353  #ifndef SQLITE_OMIT_UTF16
 87354  SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
 87355    return columnName(
 87356        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
 87357  }
 87358  #endif
 87359  
 87360  /*
 87361  ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
 87362  ** not define OMIT_DECLTYPE.
 87363  */
 87364  #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
 87365  # error "Must not define both SQLITE_OMIT_DECLTYPE \
 87366           and SQLITE_ENABLE_COLUMN_METADATA"
 87367  #endif
 87368  
 87369  #ifndef SQLITE_OMIT_DECLTYPE
 87370  /*
 87371  ** Return the column declaration type (if applicable) of the 'i'th column
 87372  ** of the result set of SQL statement pStmt.
 87373  */
 87374  SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
 87375    return columnName(
 87376        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
 87377  }
 87378  #ifndef SQLITE_OMIT_UTF16
 87379  SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
 87380    return columnName(
 87381        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
 87382  }
 87383  #endif /* SQLITE_OMIT_UTF16 */
 87384  #endif /* SQLITE_OMIT_DECLTYPE */
 87385  
 87386  #ifdef SQLITE_ENABLE_COLUMN_METADATA
 87387  /*
 87388  ** Return the name of the database from which a result column derives.
 87389  ** NULL is returned if the result column is an expression or constant or
 87390  ** anything else which is not an unambiguous reference to a database column.
 87391  */
 87392  SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
 87393    return columnName(
 87394        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
 87395  }
 87396  #ifndef SQLITE_OMIT_UTF16
 87397  SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
 87398    return columnName(
 87399        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
 87400  }
 87401  #endif /* SQLITE_OMIT_UTF16 */
 87402  
 87403  /*
 87404  ** Return the name of the table from which a result column derives.
 87405  ** NULL is returned if the result column is an expression or constant or
 87406  ** anything else which is not an unambiguous reference to a database column.
 87407  */
 87408  SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
 87409    return columnName(
 87410        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
 87411  }
 87412  #ifndef SQLITE_OMIT_UTF16
 87413  SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
 87414    return columnName(
 87415        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
 87416  }
 87417  #endif /* SQLITE_OMIT_UTF16 */
 87418  
 87419  /*
 87420  ** Return the name of the table column from which a result column derives.
 87421  ** NULL is returned if the result column is an expression or constant or
 87422  ** anything else which is not an unambiguous reference to a database column.
 87423  */
 87424  SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
 87425    return columnName(
 87426        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
 87427  }
 87428  #ifndef SQLITE_OMIT_UTF16
 87429  SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
 87430    return columnName(
 87431        pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
 87432  }
 87433  #endif /* SQLITE_OMIT_UTF16 */
 87434  #endif /* SQLITE_ENABLE_COLUMN_METADATA */
 87435  
 87436  
 87437  /******************************* sqlite3_bind_  ***************************
 87438  ** 
 87439  ** Routines used to attach values to wildcards in a compiled SQL statement.
 87440  */
 87441  /*
 87442  ** Unbind the value bound to variable i in virtual machine p. This is the 
 87443  ** the same as binding a NULL value to the column. If the "i" parameter is
 87444  ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
 87445  **
 87446  ** A successful evaluation of this routine acquires the mutex on p.
 87447  ** the mutex is released if any kind of error occurs.
 87448  **
 87449  ** The error code stored in database p->db is overwritten with the return
 87450  ** value in any case.
 87451  */
 87452  static int vdbeUnbind(Vdbe *p, int i){
 87453    Mem *pVar;
 87454    if( vdbeSafetyNotNull(p) ){
 87455      return SQLITE_MISUSE_BKPT;
 87456    }
 87457    sqlite3_mutex_enter(p->db->mutex);
 87458    if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
 87459      sqlite3Error(p->db, SQLITE_MISUSE);
 87460      sqlite3_mutex_leave(p->db->mutex);
 87461      sqlite3_log(SQLITE_MISUSE, 
 87462          "bind on a busy prepared statement: [%s]", p->zSql);
 87463      return SQLITE_MISUSE_BKPT;
 87464    }
 87465    if( i<1 || i>p->nVar ){
 87466      sqlite3Error(p->db, SQLITE_RANGE);
 87467      sqlite3_mutex_leave(p->db->mutex);
 87468      return SQLITE_RANGE;
 87469    }
 87470    i--;
 87471    pVar = &p->aVar[i];
 87472    sqlite3VdbeMemRelease(pVar);
 87473    pVar->flags = MEM_Null;
 87474    p->db->errCode = SQLITE_OK;
 87475  
 87476    /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
 87477    ** binding a new value to this variable invalidates the current query plan.
 87478    **
 87479    ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
 87480    ** parameter in the WHERE clause might influence the choice of query plan
 87481    ** for a statement, then the statement will be automatically recompiled,
 87482    ** as if there had been a schema change, on the first sqlite3_step() call
 87483    ** following any change to the bindings of that parameter.
 87484    */
 87485    assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
 87486    if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
 87487      p->expired = 1;
 87488    }
 87489    return SQLITE_OK;
 87490  }
 87491  
 87492  /*
 87493  ** Bind a text or BLOB value.
 87494  */
 87495  static int bindText(
 87496    sqlite3_stmt *pStmt,   /* The statement to bind against */
 87497    int i,                 /* Index of the parameter to bind */
 87498    const void *zData,     /* Pointer to the data to be bound */
 87499    int nData,             /* Number of bytes of data to be bound */
 87500    void (*xDel)(void*),   /* Destructor for the data */
 87501    u8 encoding            /* Encoding for the data */
 87502  ){
 87503    Vdbe *p = (Vdbe *)pStmt;
 87504    Mem *pVar;
 87505    int rc;
 87506  
 87507    rc = vdbeUnbind(p, i);
 87508    if( rc==SQLITE_OK ){
 87509      if( zData!=0 ){
 87510        pVar = &p->aVar[i-1];
 87511        rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
 87512        if( rc==SQLITE_OK && encoding!=0 ){
 87513          rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
 87514        }
 87515        if( rc ){
 87516          sqlite3Error(p->db, rc);
 87517          rc = sqlite3ApiExit(p->db, rc);
 87518        }
 87519      }
 87520      sqlite3_mutex_leave(p->db->mutex);
 87521    }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
 87522      xDel((void*)zData);
 87523    }
 87524    return rc;
 87525  }
 87526  
 87527  
 87528  /*
 87529  ** Bind a blob value to an SQL statement variable.
 87530  */
 87531  SQLITE_API int sqlite3_bind_blob(
 87532    sqlite3_stmt *pStmt, 
 87533    int i, 
 87534    const void *zData, 
 87535    int nData, 
 87536    void (*xDel)(void*)
 87537  ){
 87538  #ifdef SQLITE_ENABLE_API_ARMOR
 87539    if( nData<0 ) return SQLITE_MISUSE_BKPT;
 87540  #endif
 87541    return bindText(pStmt, i, zData, nData, xDel, 0);
 87542  }
 87543  SQLITE_API int sqlite3_bind_blob64(
 87544    sqlite3_stmt *pStmt, 
 87545    int i, 
 87546    const void *zData, 
 87547    sqlite3_uint64 nData, 
 87548    void (*xDel)(void*)
 87549  ){
 87550    assert( xDel!=SQLITE_DYNAMIC );
 87551    if( nData>0x7fffffff ){
 87552      return invokeValueDestructor(zData, xDel, 0);
 87553    }else{
 87554      return bindText(pStmt, i, zData, (int)nData, xDel, 0);
 87555    }
 87556  }
 87557  SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
 87558    int rc;
 87559    Vdbe *p = (Vdbe *)pStmt;
 87560    rc = vdbeUnbind(p, i);
 87561    if( rc==SQLITE_OK ){
 87562      sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
 87563      sqlite3_mutex_leave(p->db->mutex);
 87564    }
 87565    return rc;
 87566  }
 87567  SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
 87568    return sqlite3_bind_int64(p, i, (i64)iValue);
 87569  }
 87570  SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
 87571    int rc;
 87572    Vdbe *p = (Vdbe *)pStmt;
 87573    rc = vdbeUnbind(p, i);
 87574    if( rc==SQLITE_OK ){
 87575      sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
 87576      sqlite3_mutex_leave(p->db->mutex);
 87577    }
 87578    return rc;
 87579  }
 87580  SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
 87581    int rc;
 87582    Vdbe *p = (Vdbe*)pStmt;
 87583    rc = vdbeUnbind(p, i);
 87584    if( rc==SQLITE_OK ){
 87585      sqlite3_mutex_leave(p->db->mutex);
 87586    }
 87587    return rc;
 87588  }
 87589  SQLITE_API int sqlite3_bind_pointer(
 87590    sqlite3_stmt *pStmt,
 87591    int i,
 87592    void *pPtr,
 87593    const char *zPTtype,
 87594    void (*xDestructor)(void*)
 87595  ){
 87596    int rc;
 87597    Vdbe *p = (Vdbe*)pStmt;
 87598    rc = vdbeUnbind(p, i);
 87599    if( rc==SQLITE_OK ){
 87600      sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
 87601      sqlite3_mutex_leave(p->db->mutex);
 87602    }else if( xDestructor ){
 87603      xDestructor(pPtr);
 87604    }
 87605    return rc;
 87606  }
 87607  SQLITE_API int sqlite3_bind_text( 
 87608    sqlite3_stmt *pStmt, 
 87609    int i, 
 87610    const char *zData, 
 87611    int nData, 
 87612    void (*xDel)(void*)
 87613  ){
 87614    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
 87615  }
 87616  SQLITE_API int sqlite3_bind_text64( 
 87617    sqlite3_stmt *pStmt, 
 87618    int i, 
 87619    const char *zData, 
 87620    sqlite3_uint64 nData, 
 87621    void (*xDel)(void*),
 87622    unsigned char enc
 87623  ){
 87624    assert( xDel!=SQLITE_DYNAMIC );
 87625    if( nData>0x7fffffff ){
 87626      return invokeValueDestructor(zData, xDel, 0);
 87627    }else{
 87628      if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
 87629      return bindText(pStmt, i, zData, (int)nData, xDel, enc);
 87630    }
 87631  }
 87632  #ifndef SQLITE_OMIT_UTF16
 87633  SQLITE_API int sqlite3_bind_text16(
 87634    sqlite3_stmt *pStmt, 
 87635    int i, 
 87636    const void *zData, 
 87637    int nData, 
 87638    void (*xDel)(void*)
 87639  ){
 87640    return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
 87641  }
 87642  #endif /* SQLITE_OMIT_UTF16 */
 87643  SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
 87644    int rc;
 87645    switch( sqlite3_value_type((sqlite3_value*)pValue) ){
 87646      case SQLITE_INTEGER: {
 87647        rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
 87648        break;
 87649      }
 87650      case SQLITE_FLOAT: {
 87651        rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
 87652        break;
 87653      }
 87654      case SQLITE_BLOB: {
 87655        if( pValue->flags & MEM_Zero ){
 87656          rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
 87657        }else{
 87658          rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
 87659        }
 87660        break;
 87661      }
 87662      case SQLITE_TEXT: {
 87663        rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
 87664                                pValue->enc);
 87665        break;
 87666      }
 87667      default: {
 87668        rc = sqlite3_bind_null(pStmt, i);
 87669        break;
 87670      }
 87671    }
 87672    return rc;
 87673  }
 87674  SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
 87675    int rc;
 87676    Vdbe *p = (Vdbe *)pStmt;
 87677    rc = vdbeUnbind(p, i);
 87678    if( rc==SQLITE_OK ){
 87679      sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
 87680      sqlite3_mutex_leave(p->db->mutex);
 87681    }
 87682    return rc;
 87683  }
 87684  SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
 87685    int rc;
 87686    Vdbe *p = (Vdbe *)pStmt;
 87687    sqlite3_mutex_enter(p->db->mutex);
 87688    if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
 87689      rc = SQLITE_TOOBIG;
 87690    }else{
 87691      assert( (n & 0x7FFFFFFF)==n );
 87692      rc = sqlite3_bind_zeroblob(pStmt, i, n);
 87693    }
 87694    rc = sqlite3ApiExit(p->db, rc);
 87695    sqlite3_mutex_leave(p->db->mutex);
 87696    return rc;
 87697  }
 87698  
 87699  /*
 87700  ** Return the number of wildcards that can be potentially bound to.
 87701  ** This routine is added to support DBD::SQLite.  
 87702  */
 87703  SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
 87704    Vdbe *p = (Vdbe*)pStmt;
 87705    return p ? p->nVar : 0;
 87706  }
 87707  
 87708  /*
 87709  ** Return the name of a wildcard parameter.  Return NULL if the index
 87710  ** is out of range or if the wildcard is unnamed.
 87711  **
 87712  ** The result is always UTF-8.
 87713  */
 87714  SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
 87715    Vdbe *p = (Vdbe*)pStmt;
 87716    if( p==0 ) return 0;
 87717    return sqlite3VListNumToName(p->pVList, i);
 87718  }
 87719  
 87720  /*
 87721  ** Given a wildcard parameter name, return the index of the variable
 87722  ** with that name.  If there is no variable with the given name,
 87723  ** return 0.
 87724  */
 87725  SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
 87726    if( p==0 || zName==0 ) return 0;
 87727    return sqlite3VListNameToNum(p->pVList, zName, nName);
 87728  }
 87729  SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
 87730    return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
 87731  }
 87732  
 87733  /*
 87734  ** Transfer all bindings from the first statement over to the second.
 87735  */
 87736  SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 87737    Vdbe *pFrom = (Vdbe*)pFromStmt;
 87738    Vdbe *pTo = (Vdbe*)pToStmt;
 87739    int i;
 87740    assert( pTo->db==pFrom->db );
 87741    assert( pTo->nVar==pFrom->nVar );
 87742    sqlite3_mutex_enter(pTo->db->mutex);
 87743    for(i=0; i<pFrom->nVar; i++){
 87744      sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
 87745    }
 87746    sqlite3_mutex_leave(pTo->db->mutex);
 87747    return SQLITE_OK;
 87748  }
 87749  
 87750  #ifndef SQLITE_OMIT_DEPRECATED
 87751  /*
 87752  ** Deprecated external interface.  Internal/core SQLite code
 87753  ** should call sqlite3TransferBindings.
 87754  **
 87755  ** It is misuse to call this routine with statements from different
 87756  ** database connections.  But as this is a deprecated interface, we
 87757  ** will not bother to check for that condition.
 87758  **
 87759  ** If the two statements contain a different number of bindings, then
 87760  ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
 87761  ** SQLITE_OK is returned.
 87762  */
 87763  SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
 87764    Vdbe *pFrom = (Vdbe*)pFromStmt;
 87765    Vdbe *pTo = (Vdbe*)pToStmt;
 87766    if( pFrom->nVar!=pTo->nVar ){
 87767      return SQLITE_ERROR;
 87768    }
 87769    assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
 87770    if( pTo->expmask ){
 87771      pTo->expired = 1;
 87772    }
 87773    assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
 87774    if( pFrom->expmask ){
 87775      pFrom->expired = 1;
 87776    }
 87777    return sqlite3TransferBindings(pFromStmt, pToStmt);
 87778  }
 87779  #endif
 87780  
 87781  /*
 87782  ** Return the sqlite3* database handle to which the prepared statement given
 87783  ** in the argument belongs.  This is the same database handle that was
 87784  ** the first argument to the sqlite3_prepare() that was used to create
 87785  ** the statement in the first place.
 87786  */
 87787  SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
 87788    return pStmt ? ((Vdbe*)pStmt)->db : 0;
 87789  }
 87790  
 87791  /*
 87792  ** Return true if the prepared statement is guaranteed to not modify the
 87793  ** database.
 87794  */
 87795  SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
 87796    return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
 87797  }
 87798  
 87799  /*
 87800  ** Return true if the prepared statement is in need of being reset.
 87801  */
 87802  SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
 87803    Vdbe *v = (Vdbe*)pStmt;
 87804    return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
 87805  }
 87806  
 87807  /*
 87808  ** Return a pointer to the next prepared statement after pStmt associated
 87809  ** with database connection pDb.  If pStmt is NULL, return the first
 87810  ** prepared statement for the database connection.  Return NULL if there
 87811  ** are no more.
 87812  */
 87813  SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
 87814    sqlite3_stmt *pNext;
 87815  #ifdef SQLITE_ENABLE_API_ARMOR
 87816    if( !sqlite3SafetyCheckOk(pDb) ){
 87817      (void)SQLITE_MISUSE_BKPT;
 87818      return 0;
 87819    }
 87820  #endif
 87821    sqlite3_mutex_enter(pDb->mutex);
 87822    if( pStmt==0 ){
 87823      pNext = (sqlite3_stmt*)pDb->pVdbe;
 87824    }else{
 87825      pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
 87826    }
 87827    sqlite3_mutex_leave(pDb->mutex);
 87828    return pNext;
 87829  }
 87830  
 87831  /*
 87832  ** Return the value of a status counter for a prepared statement
 87833  */
 87834  SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
 87835    Vdbe *pVdbe = (Vdbe*)pStmt;
 87836    u32 v;
 87837  #ifdef SQLITE_ENABLE_API_ARMOR
 87838    if( !pStmt 
 87839     || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
 87840    ){
 87841      (void)SQLITE_MISUSE_BKPT;
 87842      return 0;
 87843    }
 87844  #endif
 87845    if( op==SQLITE_STMTSTATUS_MEMUSED ){
 87846      sqlite3 *db = pVdbe->db;
 87847      sqlite3_mutex_enter(db->mutex);
 87848      v = 0;
 87849      db->pnBytesFreed = (int*)&v;
 87850      sqlite3VdbeClearObject(db, pVdbe);
 87851      sqlite3DbFree(db, pVdbe);
 87852      db->pnBytesFreed = 0;
 87853      sqlite3_mutex_leave(db->mutex);
 87854    }else{
 87855      v = pVdbe->aCounter[op];
 87856      if( resetFlag ) pVdbe->aCounter[op] = 0;
 87857    }
 87858    return (int)v;
 87859  }
 87860  
 87861  /*
 87862  ** Return the SQL associated with a prepared statement
 87863  */
 87864  SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
 87865    Vdbe *p = (Vdbe *)pStmt;
 87866    return p ? p->zSql : 0;
 87867  }
 87868  
 87869  /*
 87870  ** Return the SQL associated with a prepared statement with
 87871  ** bound parameters expanded.  Space to hold the returned string is
 87872  ** obtained from sqlite3_malloc().  The caller is responsible for
 87873  ** freeing the returned string by passing it to sqlite3_free().
 87874  **
 87875  ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
 87876  ** expanded bound parameters.
 87877  */
 87878  SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
 87879  #ifdef SQLITE_OMIT_TRACE
 87880    return 0;
 87881  #else
 87882    char *z = 0;
 87883    const char *zSql = sqlite3_sql(pStmt);
 87884    if( zSql ){
 87885      Vdbe *p = (Vdbe *)pStmt;
 87886      sqlite3_mutex_enter(p->db->mutex);
 87887      z = sqlite3VdbeExpandSql(p, zSql);
 87888      sqlite3_mutex_leave(p->db->mutex);
 87889    }
 87890    return z;
 87891  #endif
 87892  }
 87893  
 87894  #ifdef SQLITE_ENABLE_NORMALIZE
 87895  /*
 87896  ** Return the normalized SQL associated with a prepared statement.
 87897  */
 87898  SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
 87899    Vdbe *p = (Vdbe *)pStmt;
 87900    if( p==0 ) return 0;
 87901    if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
 87902      sqlite3_mutex_enter(p->db->mutex);
 87903      p->zNormSql = sqlite3Normalize(p, p->zSql);
 87904      sqlite3_mutex_leave(p->db->mutex);
 87905    }
 87906    return p->zNormSql;
 87907  }
 87908  #endif /* SQLITE_ENABLE_NORMALIZE */
 87909  
 87910  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 87911  /*
 87912  ** Allocate and populate an UnpackedRecord structure based on the serialized
 87913  ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
 87914  ** if successful, or a NULL pointer if an OOM error is encountered.
 87915  */
 87916  static UnpackedRecord *vdbeUnpackRecord(
 87917    KeyInfo *pKeyInfo, 
 87918    int nKey, 
 87919    const void *pKey
 87920  ){
 87921    UnpackedRecord *pRet;           /* Return value */
 87922  
 87923    pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
 87924    if( pRet ){
 87925      memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
 87926      sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
 87927    }
 87928    return pRet;
 87929  }
 87930  
 87931  /*
 87932  ** This function is called from within a pre-update callback to retrieve
 87933  ** a field of the row currently being updated or deleted.
 87934  */
 87935  SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
 87936    PreUpdate *p = db->pPreUpdate;
 87937    Mem *pMem;
 87938    int rc = SQLITE_OK;
 87939  
 87940    /* Test that this call is being made from within an SQLITE_DELETE or
 87941    ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
 87942    if( !p || p->op==SQLITE_INSERT ){
 87943      rc = SQLITE_MISUSE_BKPT;
 87944      goto preupdate_old_out;
 87945    }
 87946    if( p->pPk ){
 87947      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
 87948    }
 87949    if( iIdx>=p->pCsr->nField || iIdx<0 ){
 87950      rc = SQLITE_RANGE;
 87951      goto preupdate_old_out;
 87952    }
 87953  
 87954    /* If the old.* record has not yet been loaded into memory, do so now. */
 87955    if( p->pUnpacked==0 ){
 87956      u32 nRec;
 87957      u8 *aRec;
 87958  
 87959      nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
 87960      aRec = sqlite3DbMallocRaw(db, nRec);
 87961      if( !aRec ) goto preupdate_old_out;
 87962      rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
 87963      if( rc==SQLITE_OK ){
 87964        p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
 87965        if( !p->pUnpacked ) rc = SQLITE_NOMEM;
 87966      }
 87967      if( rc!=SQLITE_OK ){
 87968        sqlite3DbFree(db, aRec);
 87969        goto preupdate_old_out;
 87970      }
 87971      p->aRecord = aRec;
 87972    }
 87973  
 87974    pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
 87975    if( iIdx==p->pTab->iPKey ){
 87976      sqlite3VdbeMemSetInt64(pMem, p->iKey1);
 87977    }else if( iIdx>=p->pUnpacked->nField ){
 87978      *ppValue = (sqlite3_value *)columnNullValue();
 87979    }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
 87980      if( pMem->flags & MEM_Int ){
 87981        sqlite3VdbeMemRealify(pMem);
 87982      }
 87983    }
 87984  
 87985   preupdate_old_out:
 87986    sqlite3Error(db, rc);
 87987    return sqlite3ApiExit(db, rc);
 87988  }
 87989  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 87990  
 87991  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 87992  /*
 87993  ** This function is called from within a pre-update callback to retrieve
 87994  ** the number of columns in the row being updated, deleted or inserted.
 87995  */
 87996  SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
 87997    PreUpdate *p = db->pPreUpdate;
 87998    return (p ? p->keyinfo.nKeyField : 0);
 87999  }
 88000  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 88001  
 88002  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 88003  /*
 88004  ** This function is designed to be called from within a pre-update callback
 88005  ** only. It returns zero if the change that caused the callback was made
 88006  ** immediately by a user SQL statement. Or, if the change was made by a
 88007  ** trigger program, it returns the number of trigger programs currently
 88008  ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a 
 88009  ** top-level trigger etc.).
 88010  **
 88011  ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
 88012  ** or SET DEFAULT action is considered a trigger.
 88013  */
 88014  SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
 88015    PreUpdate *p = db->pPreUpdate;
 88016    return (p ? p->v->nFrame : 0);
 88017  }
 88018  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 88019  
 88020  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 88021  /*
 88022  ** This function is called from within a pre-update callback to retrieve
 88023  ** a field of the row currently being updated or inserted.
 88024  */
 88025  SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
 88026    PreUpdate *p = db->pPreUpdate;
 88027    int rc = SQLITE_OK;
 88028    Mem *pMem;
 88029  
 88030    if( !p || p->op==SQLITE_DELETE ){
 88031      rc = SQLITE_MISUSE_BKPT;
 88032      goto preupdate_new_out;
 88033    }
 88034    if( p->pPk && p->op!=SQLITE_UPDATE ){
 88035      iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
 88036    }
 88037    if( iIdx>=p->pCsr->nField || iIdx<0 ){
 88038      rc = SQLITE_RANGE;
 88039      goto preupdate_new_out;
 88040    }
 88041  
 88042    if( p->op==SQLITE_INSERT ){
 88043      /* For an INSERT, memory cell p->iNewReg contains the serialized record
 88044      ** that is being inserted. Deserialize it. */
 88045      UnpackedRecord *pUnpack = p->pNewUnpacked;
 88046      if( !pUnpack ){
 88047        Mem *pData = &p->v->aMem[p->iNewReg];
 88048        rc = ExpandBlob(pData);
 88049        if( rc!=SQLITE_OK ) goto preupdate_new_out;
 88050        pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
 88051        if( !pUnpack ){
 88052          rc = SQLITE_NOMEM;
 88053          goto preupdate_new_out;
 88054        }
 88055        p->pNewUnpacked = pUnpack;
 88056      }
 88057      pMem = &pUnpack->aMem[iIdx];
 88058      if( iIdx==p->pTab->iPKey ){
 88059        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
 88060      }else if( iIdx>=pUnpack->nField ){
 88061        pMem = (sqlite3_value *)columnNullValue();
 88062      }
 88063    }else{
 88064      /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
 88065      ** value. Make a copy of the cell contents and return a pointer to it.
 88066      ** It is not safe to return a pointer to the memory cell itself as the
 88067      ** caller may modify the value text encoding.
 88068      */
 88069      assert( p->op==SQLITE_UPDATE );
 88070      if( !p->aNew ){
 88071        p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
 88072        if( !p->aNew ){
 88073          rc = SQLITE_NOMEM;
 88074          goto preupdate_new_out;
 88075        }
 88076      }
 88077      assert( iIdx>=0 && iIdx<p->pCsr->nField );
 88078      pMem = &p->aNew[iIdx];
 88079      if( pMem->flags==0 ){
 88080        if( iIdx==p->pTab->iPKey ){
 88081          sqlite3VdbeMemSetInt64(pMem, p->iKey2);
 88082        }else{
 88083          rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
 88084          if( rc!=SQLITE_OK ) goto preupdate_new_out;
 88085        }
 88086      }
 88087    }
 88088    *ppValue = pMem;
 88089  
 88090   preupdate_new_out:
 88091    sqlite3Error(db, rc);
 88092    return sqlite3ApiExit(db, rc);
 88093  }
 88094  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
 88095  
 88096  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 88097  /*
 88098  ** Return status data for a single loop within query pStmt.
 88099  */
 88100  SQLITE_API int sqlite3_stmt_scanstatus(
 88101    sqlite3_stmt *pStmt,            /* Prepared statement being queried */
 88102    int idx,                        /* Index of loop to report on */
 88103    int iScanStatusOp,              /* Which metric to return */
 88104    void *pOut                      /* OUT: Write the answer here */
 88105  ){
 88106    Vdbe *p = (Vdbe*)pStmt;
 88107    ScanStatus *pScan;
 88108    if( idx<0 || idx>=p->nScan ) return 1;
 88109    pScan = &p->aScan[idx];
 88110    switch( iScanStatusOp ){
 88111      case SQLITE_SCANSTAT_NLOOP: {
 88112        *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
 88113        break;
 88114      }
 88115      case SQLITE_SCANSTAT_NVISIT: {
 88116        *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
 88117        break;
 88118      }
 88119      case SQLITE_SCANSTAT_EST: {
 88120        double r = 1.0;
 88121        LogEst x = pScan->nEst;
 88122        while( x<100 ){
 88123          x += 10;
 88124          r *= 0.5;
 88125        }
 88126        *(double*)pOut = r*sqlite3LogEstToInt(x);
 88127        break;
 88128      }
 88129      case SQLITE_SCANSTAT_NAME: {
 88130        *(const char**)pOut = pScan->zName;
 88131        break;
 88132      }
 88133      case SQLITE_SCANSTAT_EXPLAIN: {
 88134        if( pScan->addrExplain ){
 88135          *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
 88136        }else{
 88137          *(const char**)pOut = 0;
 88138        }
 88139        break;
 88140      }
 88141      case SQLITE_SCANSTAT_SELECTID: {
 88142        if( pScan->addrExplain ){
 88143          *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
 88144        }else{
 88145          *(int*)pOut = -1;
 88146        }
 88147        break;
 88148      }
 88149      default: {
 88150        return 1;
 88151      }
 88152    }
 88153    return 0;
 88154  }
 88155  
 88156  /*
 88157  ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
 88158  */
 88159  SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
 88160    Vdbe *p = (Vdbe*)pStmt;
 88161    memset(p->anExec, 0, p->nOp * sizeof(i64));
 88162  }
 88163  #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
 88164  
 88165  /************** End of vdbeapi.c *********************************************/
 88166  /************** Begin file vdbetrace.c ***************************************/
 88167  /*
 88168  ** 2009 November 25
 88169  **
 88170  ** The author disclaims copyright to this source code.  In place of
 88171  ** a legal notice, here is a blessing:
 88172  **
 88173  **    May you do good and not evil.
 88174  **    May you find forgiveness for yourself and forgive others.
 88175  **    May you share freely, never taking more than you give.
 88176  **
 88177  *************************************************************************
 88178  **
 88179  ** This file contains code used to insert the values of host parameters
 88180  ** (aka "wildcards") into the SQL text output by sqlite3_trace().
 88181  **
 88182  ** The Vdbe parse-tree explainer is also found here.
 88183  */
 88184  /* #include "sqliteInt.h" */
 88185  /* #include "vdbeInt.h" */
 88186  
 88187  #ifndef SQLITE_OMIT_TRACE
 88188  
 88189  /*
 88190  ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
 88191  ** bytes in this text up to but excluding the first character in
 88192  ** a host parameter.  If the text contains no host parameters, return
 88193  ** the total number of bytes in the text.
 88194  */
 88195  static int findNextHostParameter(const char *zSql, int *pnToken){
 88196    int tokenType;
 88197    int nTotal = 0;
 88198    int n;
 88199  
 88200    *pnToken = 0;
 88201    while( zSql[0] ){
 88202      n = sqlite3GetToken((u8*)zSql, &tokenType);
 88203      assert( n>0 && tokenType!=TK_ILLEGAL );
 88204      if( tokenType==TK_VARIABLE ){
 88205        *pnToken = n;
 88206        break;
 88207      }
 88208      nTotal += n;
 88209      zSql += n;
 88210    }
 88211    return nTotal;
 88212  }
 88213  
 88214  /*
 88215  ** This function returns a pointer to a nul-terminated string in memory
 88216  ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
 88217  ** string contains a copy of zRawSql but with host parameters expanded to 
 88218  ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
 88219  ** then the returned string holds a copy of zRawSql with "-- " prepended
 88220  ** to each line of text.
 88221  **
 88222  ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
 88223  ** then long strings and blobs are truncated to that many bytes.  This
 88224  ** can be used to prevent unreasonably large trace strings when dealing
 88225  ** with large (multi-megabyte) strings and blobs.
 88226  **
 88227  ** The calling function is responsible for making sure the memory returned
 88228  ** is eventually freed.
 88229  **
 88230  ** ALGORITHM:  Scan the input string looking for host parameters in any of
 88231  ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
 88232  ** string literals, quoted identifier names, and comments.  For text forms,
 88233  ** the host parameter index is found by scanning the prepared
 88234  ** statement for the corresponding OP_Variable opcode.  Once the host
 88235  ** parameter index is known, locate the value in p->aVar[].  Then render
 88236  ** the value as a literal in place of the host parameter name.
 88237  */
 88238  SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
 88239    Vdbe *p,                 /* The prepared statement being evaluated */
 88240    const char *zRawSql      /* Raw text of the SQL statement */
 88241  ){
 88242    sqlite3 *db;             /* The database connection */
 88243    int idx = 0;             /* Index of a host parameter */
 88244    int nextIndex = 1;       /* Index of next ? host parameter */
 88245    int n;                   /* Length of a token prefix */
 88246    int nToken;              /* Length of the parameter token */
 88247    int i;                   /* Loop counter */
 88248    Mem *pVar;               /* Value of a host parameter */
 88249    StrAccum out;            /* Accumulate the output here */
 88250  #ifndef SQLITE_OMIT_UTF16
 88251    Mem utf8;                /* Used to convert UTF16 into UTF8 for display */
 88252  #endif
 88253    char zBase[100];         /* Initial working space */
 88254  
 88255    db = p->db;
 88256    sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), 
 88257                        db->aLimit[SQLITE_LIMIT_LENGTH]);
 88258    if( db->nVdbeExec>1 ){
 88259      while( *zRawSql ){
 88260        const char *zStart = zRawSql;
 88261        while( *(zRawSql++)!='\n' && *zRawSql );
 88262        sqlite3_str_append(&out, "-- ", 3);
 88263        assert( (zRawSql - zStart) > 0 );
 88264        sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
 88265      }
 88266    }else if( p->nVar==0 ){
 88267      sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
 88268    }else{
 88269      while( zRawSql[0] ){
 88270        n = findNextHostParameter(zRawSql, &nToken);
 88271        assert( n>0 );
 88272        sqlite3_str_append(&out, zRawSql, n);
 88273        zRawSql += n;
 88274        assert( zRawSql[0] || nToken==0 );
 88275        if( nToken==0 ) break;
 88276        if( zRawSql[0]=='?' ){
 88277          if( nToken>1 ){
 88278            assert( sqlite3Isdigit(zRawSql[1]) );
 88279            sqlite3GetInt32(&zRawSql[1], &idx);
 88280          }else{
 88281            idx = nextIndex;
 88282          }
 88283        }else{
 88284          assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
 88285                  zRawSql[0]=='@' || zRawSql[0]=='#' );
 88286          testcase( zRawSql[0]==':' );
 88287          testcase( zRawSql[0]=='$' );
 88288          testcase( zRawSql[0]=='@' );
 88289          testcase( zRawSql[0]=='#' );
 88290          idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
 88291          assert( idx>0 );
 88292        }
 88293        zRawSql += nToken;
 88294        nextIndex = idx + 1;
 88295        assert( idx>0 && idx<=p->nVar );
 88296        pVar = &p->aVar[idx-1];
 88297        if( pVar->flags & MEM_Null ){
 88298          sqlite3_str_append(&out, "NULL", 4);
 88299        }else if( pVar->flags & MEM_Int ){
 88300          sqlite3_str_appendf(&out, "%lld", pVar->u.i);
 88301        }else if( pVar->flags & MEM_Real ){
 88302          sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
 88303        }else if( pVar->flags & MEM_Str ){
 88304          int nOut;  /* Number of bytes of the string text to include in output */
 88305  #ifndef SQLITE_OMIT_UTF16
 88306          u8 enc = ENC(db);
 88307          if( enc!=SQLITE_UTF8 ){
 88308            memset(&utf8, 0, sizeof(utf8));
 88309            utf8.db = db;
 88310            sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
 88311            if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
 88312              out.accError = SQLITE_NOMEM;
 88313              out.nAlloc = 0;
 88314            }
 88315            pVar = &utf8;
 88316          }
 88317  #endif
 88318          nOut = pVar->n;
 88319  #ifdef SQLITE_TRACE_SIZE_LIMIT
 88320          if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
 88321            nOut = SQLITE_TRACE_SIZE_LIMIT;
 88322            while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
 88323          }
 88324  #endif    
 88325          sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
 88326  #ifdef SQLITE_TRACE_SIZE_LIMIT
 88327          if( nOut<pVar->n ){
 88328            sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
 88329          }
 88330  #endif
 88331  #ifndef SQLITE_OMIT_UTF16
 88332          if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
 88333  #endif
 88334        }else if( pVar->flags & MEM_Zero ){
 88335          sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
 88336        }else{
 88337          int nOut;  /* Number of bytes of the blob to include in output */
 88338          assert( pVar->flags & MEM_Blob );
 88339          sqlite3_str_append(&out, "x'", 2);
 88340          nOut = pVar->n;
 88341  #ifdef SQLITE_TRACE_SIZE_LIMIT
 88342          if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
 88343  #endif
 88344          for(i=0; i<nOut; i++){
 88345            sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
 88346          }
 88347          sqlite3_str_append(&out, "'", 1);
 88348  #ifdef SQLITE_TRACE_SIZE_LIMIT
 88349          if( nOut<pVar->n ){
 88350            sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
 88351          }
 88352  #endif
 88353        }
 88354      }
 88355    }
 88356    if( out.accError ) sqlite3_str_reset(&out);
 88357    return sqlite3StrAccumFinish(&out);
 88358  }
 88359  
 88360  #endif /* #ifndef SQLITE_OMIT_TRACE */
 88361  
 88362  /************** End of vdbetrace.c *******************************************/
 88363  /************** Begin file vdbe.c ********************************************/
 88364  /*
 88365  ** 2001 September 15
 88366  **
 88367  ** The author disclaims copyright to this source code.  In place of
 88368  ** a legal notice, here is a blessing:
 88369  **
 88370  **    May you do good and not evil.
 88371  **    May you find forgiveness for yourself and forgive others.
 88372  **    May you share freely, never taking more than you give.
 88373  **
 88374  *************************************************************************
 88375  ** The code in this file implements the function that runs the
 88376  ** bytecode of a prepared statement.
 88377  **
 88378  ** Various scripts scan this source file in order to generate HTML
 88379  ** documentation, headers files, or other derived files.  The formatting
 88380  ** of the code in this file is, therefore, important.  See other comments
 88381  ** in this file for details.  If in doubt, do not deviate from existing
 88382  ** commenting and indentation practices when changing or adding code.
 88383  */
 88384  /* #include "sqliteInt.h" */
 88385  /* #include "vdbeInt.h" */
 88386  
 88387  /*
 88388  ** Invoke this macro on memory cells just prior to changing the
 88389  ** value of the cell.  This macro verifies that shallow copies are
 88390  ** not misused.  A shallow copy of a string or blob just copies a
 88391  ** pointer to the string or blob, not the content.  If the original
 88392  ** is changed while the copy is still in use, the string or blob might
 88393  ** be changed out from under the copy.  This macro verifies that nothing
 88394  ** like that ever happens.
 88395  */
 88396  #ifdef SQLITE_DEBUG
 88397  # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
 88398  #else
 88399  # define memAboutToChange(P,M)
 88400  #endif
 88401  
 88402  /*
 88403  ** The following global variable is incremented every time a cursor
 88404  ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
 88405  ** procedures use this information to make sure that indices are
 88406  ** working correctly.  This variable has no function other than to
 88407  ** help verify the correct operation of the library.
 88408  */
 88409  #ifdef SQLITE_TEST
 88410  SQLITE_API int sqlite3_search_count = 0;
 88411  #endif
 88412  
 88413  /*
 88414  ** When this global variable is positive, it gets decremented once before
 88415  ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
 88416  ** field of the sqlite3 structure is set in order to simulate an interrupt.
 88417  **
 88418  ** This facility is used for testing purposes only.  It does not function
 88419  ** in an ordinary build.
 88420  */
 88421  #ifdef SQLITE_TEST
 88422  SQLITE_API int sqlite3_interrupt_count = 0;
 88423  #endif
 88424  
 88425  /*
 88426  ** The next global variable is incremented each type the OP_Sort opcode
 88427  ** is executed.  The test procedures use this information to make sure that
 88428  ** sorting is occurring or not occurring at appropriate times.   This variable
 88429  ** has no function other than to help verify the correct operation of the
 88430  ** library.
 88431  */
 88432  #ifdef SQLITE_TEST
 88433  SQLITE_API int sqlite3_sort_count = 0;
 88434  #endif
 88435  
 88436  /*
 88437  ** The next global variable records the size of the largest MEM_Blob
 88438  ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
 88439  ** use this information to make sure that the zero-blob functionality
 88440  ** is working correctly.   This variable has no function other than to
 88441  ** help verify the correct operation of the library.
 88442  */
 88443  #ifdef SQLITE_TEST
 88444  SQLITE_API int sqlite3_max_blobsize = 0;
 88445  static void updateMaxBlobsize(Mem *p){
 88446    if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
 88447      sqlite3_max_blobsize = p->n;
 88448    }
 88449  }
 88450  #endif
 88451  
 88452  /*
 88453  ** This macro evaluates to true if either the update hook or the preupdate
 88454  ** hook are enabled for database connect DB.
 88455  */
 88456  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 88457  # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
 88458  #else
 88459  # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
 88460  #endif
 88461  
 88462  /*
 88463  ** The next global variable is incremented each time the OP_Found opcode
 88464  ** is executed. This is used to test whether or not the foreign key
 88465  ** operation implemented using OP_FkIsZero is working. This variable
 88466  ** has no function other than to help verify the correct operation of the
 88467  ** library.
 88468  */
 88469  #ifdef SQLITE_TEST
 88470  SQLITE_API int sqlite3_found_count = 0;
 88471  #endif
 88472  
 88473  /*
 88474  ** Test a register to see if it exceeds the current maximum blob size.
 88475  ** If it does, record the new maximum blob size.
 88476  */
 88477  #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
 88478  # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
 88479  #else
 88480  # define UPDATE_MAX_BLOBSIZE(P)
 88481  #endif
 88482  
 88483  /*
 88484  ** Invoke the VDBE coverage callback, if that callback is defined.  This
 88485  ** feature is used for test suite validation only and does not appear an
 88486  ** production builds.
 88487  **
 88488  ** M is an integer between 2 and 4.  2 indicates a ordinary two-way
 88489  ** branch (I=0 means fall through and I=1 means taken).  3 indicates
 88490  ** a 3-way branch where the third way is when one of the operands is
 88491  ** NULL.  4 indicates the OP_Jump instruction which has three destinations
 88492  ** depending on whether the first operand is less than, equal to, or greater
 88493  ** than the second. 
 88494  **
 88495  ** iSrcLine is the source code line (from the __LINE__ macro) that
 88496  ** generated the VDBE instruction combined with flag bits.  The source
 88497  ** code line number is in the lower 24 bits of iSrcLine and the upper
 88498  ** 8 bytes are flags.  The lower three bits of the flags indicate
 88499  ** values for I that should never occur.  For example, if the branch is
 88500  ** always taken, the flags should be 0x05 since the fall-through and
 88501  ** alternate branch are never taken.  If a branch is never taken then
 88502  ** flags should be 0x06 since only the fall-through approach is allowed.
 88503  **
 88504  ** Bit 0x04 of the flags indicates an OP_Jump opcode that is only
 88505  ** interested in equal or not-equal.  In other words, I==0 and I==2
 88506  ** should be treated the same.
 88507  **
 88508  ** Since only a line number is retained, not the filename, this macro
 88509  ** only works for amalgamation builds.  But that is ok, since these macros
 88510  ** should be no-ops except for special builds used to measure test coverage.
 88511  */
 88512  #if !defined(SQLITE_VDBE_COVERAGE)
 88513  # define VdbeBranchTaken(I,M)
 88514  #else
 88515  # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
 88516    static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
 88517      u8 mNever;
 88518      assert( I<=2 );  /* 0: fall through,  1: taken,  2: alternate taken */
 88519      assert( M<=4 );  /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
 88520      assert( I<M );   /* I can only be 2 if M is 3 or 4 */
 88521      /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
 88522      I = 1<<I;
 88523      /* The upper 8 bits of iSrcLine are flags.  The lower three bits of
 88524      ** the flags indicate directions that the branch can never go.  If
 88525      ** a branch really does go in one of those directions, assert right
 88526      ** away. */
 88527      mNever = iSrcLine >> 24;
 88528      assert( (I & mNever)==0 );
 88529      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
 88530      I |= mNever;
 88531      if( M==2 ) I |= 0x04;
 88532      if( M==4 ){
 88533        I |= 0x08;
 88534        if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
 88535      }
 88536      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
 88537                                      iSrcLine&0xffffff, I, M);
 88538    }
 88539  #endif
 88540  
 88541  /*
 88542  ** Convert the given register into a string if it isn't one
 88543  ** already. Return non-zero if a malloc() fails.
 88544  */
 88545  #define Stringify(P, enc) \
 88546     if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
 88547       { goto no_mem; }
 88548  
 88549  /*
 88550  ** An ephemeral string value (signified by the MEM_Ephem flag) contains
 88551  ** a pointer to a dynamically allocated string where some other entity
 88552  ** is responsible for deallocating that string.  Because the register
 88553  ** does not control the string, it might be deleted without the register
 88554  ** knowing it.
 88555  **
 88556  ** This routine converts an ephemeral string into a dynamically allocated
 88557  ** string that the register itself controls.  In other words, it
 88558  ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
 88559  */
 88560  #define Deephemeralize(P) \
 88561     if( ((P)->flags&MEM_Ephem)!=0 \
 88562         && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
 88563  
 88564  /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
 88565  #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
 88566  
 88567  /*
 88568  ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
 88569  ** if we run out of memory.
 88570  */
 88571  static VdbeCursor *allocateCursor(
 88572    Vdbe *p,              /* The virtual machine */
 88573    int iCur,             /* Index of the new VdbeCursor */
 88574    int nField,           /* Number of fields in the table or index */
 88575    int iDb,              /* Database the cursor belongs to, or -1 */
 88576    u8 eCurType           /* Type of the new cursor */
 88577  ){
 88578    /* Find the memory cell that will be used to store the blob of memory
 88579    ** required for this VdbeCursor structure. It is convenient to use a 
 88580    ** vdbe memory cell to manage the memory allocation required for a
 88581    ** VdbeCursor structure for the following reasons:
 88582    **
 88583    **   * Sometimes cursor numbers are used for a couple of different
 88584    **     purposes in a vdbe program. The different uses might require
 88585    **     different sized allocations. Memory cells provide growable
 88586    **     allocations.
 88587    **
 88588    **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
 88589    **     be freed lazily via the sqlite3_release_memory() API. This
 88590    **     minimizes the number of malloc calls made by the system.
 88591    **
 88592    ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
 88593    ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
 88594    ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
 88595    */
 88596    Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
 88597  
 88598    int nByte;
 88599    VdbeCursor *pCx = 0;
 88600    nByte = 
 88601        ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
 88602        (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
 88603  
 88604    assert( iCur>=0 && iCur<p->nCursor );
 88605    if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
 88606      /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
 88607      ** is clear. Otherwise, if this is an ephemeral cursor created by 
 88608      ** OP_OpenDup, the cursor will not be closed and will still be part
 88609      ** of a BtShared.pCursor list.  */
 88610      p->apCsr[iCur]->isEphemeral = 0;
 88611      sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
 88612      p->apCsr[iCur] = 0;
 88613    }
 88614    if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
 88615      p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
 88616      memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
 88617      pCx->eCurType = eCurType;
 88618      pCx->iDb = iDb;
 88619      pCx->nField = nField;
 88620      pCx->aOffset = &pCx->aType[nField];
 88621      if( eCurType==CURTYPE_BTREE ){
 88622        pCx->uc.pCursor = (BtCursor*)
 88623            &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
 88624        sqlite3BtreeCursorZero(pCx->uc.pCursor);
 88625      }
 88626    }
 88627    return pCx;
 88628  }
 88629  
 88630  /*
 88631  ** Try to convert a value into a numeric representation if we can
 88632  ** do so without loss of information.  In other words, if the string
 88633  ** looks like a number, convert it into a number.  If it does not
 88634  ** look like a number, leave it alone.
 88635  **
 88636  ** If the bTryForInt flag is true, then extra effort is made to give
 88637  ** an integer representation.  Strings that look like floating point
 88638  ** values but which have no fractional component (example: '48.00')
 88639  ** will have a MEM_Int representation when bTryForInt is true.
 88640  **
 88641  ** If bTryForInt is false, then if the input string contains a decimal
 88642  ** point or exponential notation, the result is only MEM_Real, even
 88643  ** if there is an exact integer representation of the quantity.
 88644  */
 88645  static void applyNumericAffinity(Mem *pRec, int bTryForInt){
 88646    double rValue;
 88647    i64 iValue;
 88648    u8 enc = pRec->enc;
 88649    assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
 88650    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
 88651    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
 88652      pRec->u.i = iValue;
 88653      pRec->flags |= MEM_Int;
 88654    }else{
 88655      pRec->u.r = rValue;
 88656      pRec->flags |= MEM_Real;
 88657      if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
 88658    }
 88659    /* TEXT->NUMERIC is many->one.  Hence, it is important to invalidate the
 88660    ** string representation after computing a numeric equivalent, because the
 88661    ** string representation might not be the canonical representation for the
 88662    ** numeric value.  Ticket [343634942dd54ab57b7024] 2018-01-31. */
 88663    pRec->flags &= ~MEM_Str;
 88664  }
 88665  
 88666  /*
 88667  ** Processing is determine by the affinity parameter:
 88668  **
 88669  ** SQLITE_AFF_INTEGER:
 88670  ** SQLITE_AFF_REAL:
 88671  ** SQLITE_AFF_NUMERIC:
 88672  **    Try to convert pRec to an integer representation or a 
 88673  **    floating-point representation if an integer representation
 88674  **    is not possible.  Note that the integer representation is
 88675  **    always preferred, even if the affinity is REAL, because
 88676  **    an integer representation is more space efficient on disk.
 88677  **
 88678  ** SQLITE_AFF_TEXT:
 88679  **    Convert pRec to a text representation.
 88680  **
 88681  ** SQLITE_AFF_BLOB:
 88682  **    No-op.  pRec is unchanged.
 88683  */
 88684  static void applyAffinity(
 88685    Mem *pRec,          /* The value to apply affinity to */
 88686    char affinity,      /* The affinity to be applied */
 88687    u8 enc              /* Use this text encoding */
 88688  ){
 88689    if( affinity>=SQLITE_AFF_NUMERIC ){
 88690      assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
 88691               || affinity==SQLITE_AFF_NUMERIC );
 88692      if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
 88693        if( (pRec->flags & MEM_Real)==0 ){
 88694          if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
 88695        }else{
 88696          sqlite3VdbeIntegerAffinity(pRec);
 88697        }
 88698      }
 88699    }else if( affinity==SQLITE_AFF_TEXT ){
 88700      /* Only attempt the conversion to TEXT if there is an integer or real
 88701      ** representation (blob and NULL do not get converted) but no string
 88702      ** representation.  It would be harmless to repeat the conversion if 
 88703      ** there is already a string rep, but it is pointless to waste those
 88704      ** CPU cycles. */
 88705      if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
 88706        if( (pRec->flags&(MEM_Real|MEM_Int)) ){
 88707          sqlite3VdbeMemStringify(pRec, enc, 1);
 88708        }
 88709      }
 88710      pRec->flags &= ~(MEM_Real|MEM_Int);
 88711    }
 88712  }
 88713  
 88714  /*
 88715  ** Try to convert the type of a function argument or a result column
 88716  ** into a numeric representation.  Use either INTEGER or REAL whichever
 88717  ** is appropriate.  But only do the conversion if it is possible without
 88718  ** loss of information and return the revised type of the argument.
 88719  */
 88720  SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
 88721    int eType = sqlite3_value_type(pVal);
 88722    if( eType==SQLITE_TEXT ){
 88723      Mem *pMem = (Mem*)pVal;
 88724      applyNumericAffinity(pMem, 0);
 88725      eType = sqlite3_value_type(pVal);
 88726    }
 88727    return eType;
 88728  }
 88729  
 88730  /*
 88731  ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
 88732  ** not the internal Mem* type.
 88733  */
 88734  SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
 88735    sqlite3_value *pVal, 
 88736    u8 affinity, 
 88737    u8 enc
 88738  ){
 88739    applyAffinity((Mem *)pVal, affinity, enc);
 88740  }
 88741  
 88742  /*
 88743  ** pMem currently only holds a string type (or maybe a BLOB that we can
 88744  ** interpret as a string if we want to).  Compute its corresponding
 88745  ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
 88746  ** accordingly.
 88747  */
 88748  static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
 88749    assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
 88750    assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
 88751    ExpandBlob(pMem);
 88752    if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
 88753      return 0;
 88754    }
 88755    if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
 88756      return MEM_Int;
 88757    }
 88758    return MEM_Real;
 88759  }
 88760  
 88761  /*
 88762  ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
 88763  ** none.  
 88764  **
 88765  ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
 88766  ** But it does set pMem->u.r and pMem->u.i appropriately.
 88767  */
 88768  static u16 numericType(Mem *pMem){
 88769    if( pMem->flags & (MEM_Int|MEM_Real) ){
 88770      return pMem->flags & (MEM_Int|MEM_Real);
 88771    }
 88772    if( pMem->flags & (MEM_Str|MEM_Blob) ){
 88773      return computeNumericType(pMem);
 88774    }
 88775    return 0;
 88776  }
 88777  
 88778  #ifdef SQLITE_DEBUG
 88779  /*
 88780  ** Write a nice string representation of the contents of cell pMem
 88781  ** into buffer zBuf, length nBuf.
 88782  */
 88783  SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
 88784    char *zCsr = zBuf;
 88785    int f = pMem->flags;
 88786  
 88787    static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
 88788  
 88789    if( f&MEM_Blob ){
 88790      int i;
 88791      char c;
 88792      if( f & MEM_Dyn ){
 88793        c = 'z';
 88794        assert( (f & (MEM_Static|MEM_Ephem))==0 );
 88795      }else if( f & MEM_Static ){
 88796        c = 't';
 88797        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 88798      }else if( f & MEM_Ephem ){
 88799        c = 'e';
 88800        assert( (f & (MEM_Static|MEM_Dyn))==0 );
 88801      }else{
 88802        c = 's';
 88803      }
 88804      *(zCsr++) = c;
 88805      sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
 88806      zCsr += sqlite3Strlen30(zCsr);
 88807      for(i=0; i<16 && i<pMem->n; i++){
 88808        sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
 88809        zCsr += sqlite3Strlen30(zCsr);
 88810      }
 88811      for(i=0; i<16 && i<pMem->n; i++){
 88812        char z = pMem->z[i];
 88813        if( z<32 || z>126 ) *zCsr++ = '.';
 88814        else *zCsr++ = z;
 88815      }
 88816      *(zCsr++) = ']';
 88817      if( f & MEM_Zero ){
 88818        sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
 88819        zCsr += sqlite3Strlen30(zCsr);
 88820      }
 88821      *zCsr = '\0';
 88822    }else if( f & MEM_Str ){
 88823      int j, k;
 88824      zBuf[0] = ' ';
 88825      if( f & MEM_Dyn ){
 88826        zBuf[1] = 'z';
 88827        assert( (f & (MEM_Static|MEM_Ephem))==0 );
 88828      }else if( f & MEM_Static ){
 88829        zBuf[1] = 't';
 88830        assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
 88831      }else if( f & MEM_Ephem ){
 88832        zBuf[1] = 'e';
 88833        assert( (f & (MEM_Static|MEM_Dyn))==0 );
 88834      }else{
 88835        zBuf[1] = 's';
 88836      }
 88837      k = 2;
 88838      sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
 88839      k += sqlite3Strlen30(&zBuf[k]);
 88840      zBuf[k++] = '[';
 88841      for(j=0; j<15 && j<pMem->n; j++){
 88842        u8 c = pMem->z[j];
 88843        if( c>=0x20 && c<0x7f ){
 88844          zBuf[k++] = c;
 88845        }else{
 88846          zBuf[k++] = '.';
 88847        }
 88848      }
 88849      zBuf[k++] = ']';
 88850      sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
 88851      k += sqlite3Strlen30(&zBuf[k]);
 88852      zBuf[k++] = 0;
 88853    }
 88854  }
 88855  #endif
 88856  
 88857  #ifdef SQLITE_DEBUG
 88858  /*
 88859  ** Print the value of a register for tracing purposes:
 88860  */
 88861  static void memTracePrint(Mem *p){
 88862    if( p->flags & MEM_Undefined ){
 88863      printf(" undefined");
 88864    }else if( p->flags & MEM_Null ){
 88865      printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
 88866    }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
 88867      printf(" si:%lld", p->u.i);
 88868    }else if( p->flags & MEM_Int ){
 88869      printf(" i:%lld", p->u.i);
 88870  #ifndef SQLITE_OMIT_FLOATING_POINT
 88871    }else if( p->flags & MEM_Real ){
 88872      printf(" r:%g", p->u.r);
 88873  #endif
 88874    }else if( sqlite3VdbeMemIsRowSet(p) ){
 88875      printf(" (rowset)");
 88876    }else{
 88877      char zBuf[200];
 88878      sqlite3VdbeMemPrettyPrint(p, zBuf);
 88879      printf(" %s", zBuf);
 88880    }
 88881    if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
 88882  }
 88883  static void registerTrace(int iReg, Mem *p){
 88884    printf("REG[%d] = ", iReg);
 88885    memTracePrint(p);
 88886    printf("\n");
 88887    sqlite3VdbeCheckMemInvariants(p);
 88888  }
 88889  #endif
 88890  
 88891  #ifdef SQLITE_DEBUG
 88892  #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
 88893  #else
 88894  #  define REGISTER_TRACE(R,M)
 88895  #endif
 88896  
 88897  
 88898  #ifdef VDBE_PROFILE
 88899  
 88900  /* 
 88901  ** hwtime.h contains inline assembler code for implementing 
 88902  ** high-performance timing routines.
 88903  */
 88904  /************** Include hwtime.h in the middle of vdbe.c *********************/
 88905  /************** Begin file hwtime.h ******************************************/
 88906  /*
 88907  ** 2008 May 27
 88908  **
 88909  ** The author disclaims copyright to this source code.  In place of
 88910  ** a legal notice, here is a blessing:
 88911  **
 88912  **    May you do good and not evil.
 88913  **    May you find forgiveness for yourself and forgive others.
 88914  **    May you share freely, never taking more than you give.
 88915  **
 88916  ******************************************************************************
 88917  **
 88918  ** This file contains inline asm code for retrieving "high-performance"
 88919  ** counters for x86 class CPUs.
 88920  */
 88921  #ifndef SQLITE_HWTIME_H
 88922  #define SQLITE_HWTIME_H
 88923  
 88924  /*
 88925  ** The following routine only works on pentium-class (or newer) processors.
 88926  ** It uses the RDTSC opcode to read the cycle count value out of the
 88927  ** processor and returns that value.  This can be used for high-res
 88928  ** profiling.
 88929  */
 88930  #if (defined(__GNUC__) || defined(_MSC_VER)) && \
 88931        (defined(i386) || defined(__i386__) || defined(_M_IX86))
 88932  
 88933    #if defined(__GNUC__)
 88934  
 88935    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 88936       unsigned int lo, hi;
 88937       __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
 88938       return (sqlite_uint64)hi << 32 | lo;
 88939    }
 88940  
 88941    #elif defined(_MSC_VER)
 88942  
 88943    __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
 88944       __asm {
 88945          rdtsc
 88946          ret       ; return value at EDX:EAX
 88947       }
 88948    }
 88949  
 88950    #endif
 88951  
 88952  #elif (defined(__GNUC__) && defined(__x86_64__))
 88953  
 88954    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 88955        unsigned long val;
 88956        __asm__ __volatile__ ("rdtsc" : "=A" (val));
 88957        return val;
 88958    }
 88959   
 88960  #elif (defined(__GNUC__) && defined(__ppc__))
 88961  
 88962    __inline__ sqlite_uint64 sqlite3Hwtime(void){
 88963        unsigned long long retval;
 88964        unsigned long junk;
 88965        __asm__ __volatile__ ("\n\
 88966            1:      mftbu   %1\n\
 88967                    mftb    %L0\n\
 88968                    mftbu   %0\n\
 88969                    cmpw    %0,%1\n\
 88970                    bne     1b"
 88971                    : "=r" (retval), "=r" (junk));
 88972        return retval;
 88973    }
 88974  
 88975  #else
 88976  
 88977    #error Need implementation of sqlite3Hwtime() for your platform.
 88978  
 88979    /*
 88980    ** To compile without implementing sqlite3Hwtime() for your platform,
 88981    ** you can remove the above #error and use the following
 88982    ** stub function.  You will lose timing support for many
 88983    ** of the debugging and testing utilities, but it should at
 88984    ** least compile and run.
 88985    */
 88986  SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 88987  
 88988  #endif
 88989  
 88990  #endif /* !defined(SQLITE_HWTIME_H) */
 88991  
 88992  /************** End of hwtime.h **********************************************/
 88993  /************** Continuing where we left off in vdbe.c ***********************/
 88994  
 88995  #endif
 88996  
 88997  #ifndef NDEBUG
 88998  /*
 88999  ** This function is only called from within an assert() expression. It
 89000  ** checks that the sqlite3.nTransaction variable is correctly set to
 89001  ** the number of non-transaction savepoints currently in the 
 89002  ** linked list starting at sqlite3.pSavepoint.
 89003  ** 
 89004  ** Usage:
 89005  **
 89006  **     assert( checkSavepointCount(db) );
 89007  */
 89008  static int checkSavepointCount(sqlite3 *db){
 89009    int n = 0;
 89010    Savepoint *p;
 89011    for(p=db->pSavepoint; p; p=p->pNext) n++;
 89012    assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
 89013    return 1;
 89014  }
 89015  #endif
 89016  
 89017  /*
 89018  ** Return the register of pOp->p2 after first preparing it to be
 89019  ** overwritten with an integer value.
 89020  */
 89021  static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
 89022    sqlite3VdbeMemSetNull(pOut);
 89023    pOut->flags = MEM_Int;
 89024    return pOut;
 89025  }
 89026  static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
 89027    Mem *pOut;
 89028    assert( pOp->p2>0 );
 89029    assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 89030    pOut = &p->aMem[pOp->p2];
 89031    memAboutToChange(p, pOut);
 89032    if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
 89033      return out2PrereleaseWithClear(pOut);
 89034    }else{
 89035      pOut->flags = MEM_Int;
 89036      return pOut;
 89037    }
 89038  }
 89039  
 89040  
 89041  /*
 89042  ** Execute as much of a VDBE program as we can.
 89043  ** This is the core of sqlite3_step().  
 89044  */
 89045  SQLITE_PRIVATE int sqlite3VdbeExec(
 89046    Vdbe *p                    /* The VDBE */
 89047  ){
 89048    Op *aOp = p->aOp;          /* Copy of p->aOp */
 89049    Op *pOp = aOp;             /* Current operation */
 89050  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 89051    Op *pOrigOp;               /* Value of pOp at the top of the loop */
 89052  #endif
 89053  #ifdef SQLITE_DEBUG
 89054    int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
 89055  #endif
 89056    int rc = SQLITE_OK;        /* Value to return */
 89057    sqlite3 *db = p->db;       /* The database */
 89058    u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
 89059    u8 encoding = ENC(db);     /* The database encoding */
 89060    int iCompare = 0;          /* Result of last comparison */
 89061    unsigned nVmStep = 0;      /* Number of virtual machine steps */
 89062  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 89063    unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
 89064  #endif
 89065    Mem *aMem = p->aMem;       /* Copy of p->aMem */
 89066    Mem *pIn1 = 0;             /* 1st input operand */
 89067    Mem *pIn2 = 0;             /* 2nd input operand */
 89068    Mem *pIn3 = 0;             /* 3rd input operand */
 89069    Mem *pOut = 0;             /* Output operand */
 89070  #ifdef VDBE_PROFILE
 89071    u64 start;                 /* CPU clock count at start of opcode */
 89072  #endif
 89073    /*** INSERT STACK UNION HERE ***/
 89074  
 89075    assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
 89076    sqlite3VdbeEnter(p);
 89077    if( p->rc==SQLITE_NOMEM ){
 89078      /* This happens if a malloc() inside a call to sqlite3_column_text() or
 89079      ** sqlite3_column_text16() failed.  */
 89080      goto no_mem;
 89081    }
 89082    assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
 89083    assert( p->bIsReader || p->readOnly!=0 );
 89084    p->iCurrentTime = 0;
 89085    assert( p->explain==0 );
 89086    p->pResultSet = 0;
 89087    db->busyHandler.nBusy = 0;
 89088    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 89089    sqlite3VdbeIOTraceSql(p);
 89090  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 89091    if( db->xProgress ){
 89092      u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
 89093      assert( 0 < db->nProgressOps );
 89094      nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
 89095    }else{
 89096      nProgressLimit = 0xffffffff;
 89097    }
 89098  #endif
 89099  #ifdef SQLITE_DEBUG
 89100    sqlite3BeginBenignMalloc();
 89101    if( p->pc==0
 89102     && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
 89103    ){
 89104      int i;
 89105      int once = 1;
 89106      sqlite3VdbePrintSql(p);
 89107      if( p->db->flags & SQLITE_VdbeListing ){
 89108        printf("VDBE Program Listing:\n");
 89109        for(i=0; i<p->nOp; i++){
 89110          sqlite3VdbePrintOp(stdout, i, &aOp[i]);
 89111        }
 89112      }
 89113      if( p->db->flags & SQLITE_VdbeEQP ){
 89114        for(i=0; i<p->nOp; i++){
 89115          if( aOp[i].opcode==OP_Explain ){
 89116            if( once ) printf("VDBE Query Plan:\n");
 89117            printf("%s\n", aOp[i].p4.z);
 89118            once = 0;
 89119          }
 89120        }
 89121      }
 89122      if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
 89123    }
 89124    sqlite3EndBenignMalloc();
 89125  #endif
 89126    for(pOp=&aOp[p->pc]; 1; pOp++){
 89127      /* Errors are detected by individual opcodes, with an immediate
 89128      ** jumps to abort_due_to_error. */
 89129      assert( rc==SQLITE_OK );
 89130  
 89131      assert( pOp>=aOp && pOp<&aOp[p->nOp]);
 89132  #ifdef VDBE_PROFILE
 89133      start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
 89134  #endif
 89135      nVmStep++;
 89136  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 89137      if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
 89138  #endif
 89139  
 89140      /* Only allow tracing if SQLITE_DEBUG is defined.
 89141      */
 89142  #ifdef SQLITE_DEBUG
 89143      if( db->flags & SQLITE_VdbeTrace ){
 89144        sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
 89145      }
 89146  #endif
 89147        
 89148  
 89149      /* Check to see if we need to simulate an interrupt.  This only happens
 89150      ** if we have a special test build.
 89151      */
 89152  #ifdef SQLITE_TEST
 89153      if( sqlite3_interrupt_count>0 ){
 89154        sqlite3_interrupt_count--;
 89155        if( sqlite3_interrupt_count==0 ){
 89156          sqlite3_interrupt(db);
 89157        }
 89158      }
 89159  #endif
 89160  
 89161      /* Sanity checking on other operands */
 89162  #ifdef SQLITE_DEBUG
 89163      {
 89164        u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
 89165        if( (opProperty & OPFLG_IN1)!=0 ){
 89166          assert( pOp->p1>0 );
 89167          assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
 89168          assert( memIsValid(&aMem[pOp->p1]) );
 89169          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
 89170          REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
 89171        }
 89172        if( (opProperty & OPFLG_IN2)!=0 ){
 89173          assert( pOp->p2>0 );
 89174          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 89175          assert( memIsValid(&aMem[pOp->p2]) );
 89176          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
 89177          REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
 89178        }
 89179        if( (opProperty & OPFLG_IN3)!=0 ){
 89180          assert( pOp->p3>0 );
 89181          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 89182          assert( memIsValid(&aMem[pOp->p3]) );
 89183          assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
 89184          REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
 89185        }
 89186        if( (opProperty & OPFLG_OUT2)!=0 ){
 89187          assert( pOp->p2>0 );
 89188          assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
 89189          memAboutToChange(p, &aMem[pOp->p2]);
 89190        }
 89191        if( (opProperty & OPFLG_OUT3)!=0 ){
 89192          assert( pOp->p3>0 );
 89193          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 89194          memAboutToChange(p, &aMem[pOp->p3]);
 89195        }
 89196      }
 89197  #endif
 89198  #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
 89199      pOrigOp = pOp;
 89200  #endif
 89201    
 89202      switch( pOp->opcode ){
 89203  
 89204  /*****************************************************************************
 89205  ** What follows is a massive switch statement where each case implements a
 89206  ** separate instruction in the virtual machine.  If we follow the usual
 89207  ** indentation conventions, each case should be indented by 6 spaces.  But
 89208  ** that is a lot of wasted space on the left margin.  So the code within
 89209  ** the switch statement will break with convention and be flush-left. Another
 89210  ** big comment (similar to this one) will mark the point in the code where
 89211  ** we transition back to normal indentation.
 89212  **
 89213  ** The formatting of each case is important.  The makefile for SQLite
 89214  ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
 89215  ** file looking for lines that begin with "case OP_".  The opcodes.h files
 89216  ** will be filled with #defines that give unique integer values to each
 89217  ** opcode and the opcodes.c file is filled with an array of strings where
 89218  ** each string is the symbolic name for the corresponding opcode.  If the
 89219  ** case statement is followed by a comment of the form "/# same as ... #/"
 89220  ** that comment is used to determine the particular value of the opcode.
 89221  **
 89222  ** Other keywords in the comment that follows each case are used to
 89223  ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
 89224  ** Keywords include: in1, in2, in3, out2, out3.  See
 89225  ** the mkopcodeh.awk script for additional information.
 89226  **
 89227  ** Documentation about VDBE opcodes is generated by scanning this file
 89228  ** for lines of that contain "Opcode:".  That line and all subsequent
 89229  ** comment lines are used in the generation of the opcode.html documentation
 89230  ** file.
 89231  **
 89232  ** SUMMARY:
 89233  **
 89234  **     Formatting is important to scripts that scan this file.
 89235  **     Do not deviate from the formatting style currently in use.
 89236  **
 89237  *****************************************************************************/
 89238  
 89239  /* Opcode:  Goto * P2 * * *
 89240  **
 89241  ** An unconditional jump to address P2.
 89242  ** The next instruction executed will be 
 89243  ** the one at index P2 from the beginning of
 89244  ** the program.
 89245  **
 89246  ** The P1 parameter is not actually used by this opcode.  However, it
 89247  ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
 89248  ** that this Goto is the bottom of a loop and that the lines from P2 down
 89249  ** to the current line should be indented for EXPLAIN output.
 89250  */
 89251  case OP_Goto: {             /* jump */
 89252  jump_to_p2_and_check_for_interrupt:
 89253    pOp = &aOp[pOp->p2 - 1];
 89254  
 89255    /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
 89256    ** OP_VNext, or OP_SorterNext) all jump here upon
 89257    ** completion.  Check to see if sqlite3_interrupt() has been called
 89258    ** or if the progress callback needs to be invoked. 
 89259    **
 89260    ** This code uses unstructured "goto" statements and does not look clean.
 89261    ** But that is not due to sloppy coding habits. The code is written this
 89262    ** way for performance, to avoid having to run the interrupt and progress
 89263    ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
 89264    ** faster according to "valgrind --tool=cachegrind" */
 89265  check_for_interrupt:
 89266    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
 89267  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 89268    /* Call the progress callback if it is configured and the required number
 89269    ** of VDBE ops have been executed (either since this invocation of
 89270    ** sqlite3VdbeExec() or since last time the progress callback was called).
 89271    ** If the progress callback returns non-zero, exit the virtual machine with
 89272    ** a return code SQLITE_ABORT.
 89273    */
 89274    if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
 89275      assert( db->nProgressOps!=0 );
 89276      nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
 89277      if( db->xProgress(db->pProgressArg) ){
 89278        rc = SQLITE_INTERRUPT;
 89279        goto abort_due_to_error;
 89280      }
 89281    }
 89282  #endif
 89283    
 89284    break;
 89285  }
 89286  
 89287  /* Opcode:  Gosub P1 P2 * * *
 89288  **
 89289  ** Write the current address onto register P1
 89290  ** and then jump to address P2.
 89291  */
 89292  case OP_Gosub: {            /* jump */
 89293    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 89294    pIn1 = &aMem[pOp->p1];
 89295    assert( VdbeMemDynamic(pIn1)==0 );
 89296    memAboutToChange(p, pIn1);
 89297    pIn1->flags = MEM_Int;
 89298    pIn1->u.i = (int)(pOp-aOp);
 89299    REGISTER_TRACE(pOp->p1, pIn1);
 89300  
 89301    /* Most jump operations do a goto to this spot in order to update
 89302    ** the pOp pointer. */
 89303  jump_to_p2:
 89304    pOp = &aOp[pOp->p2 - 1];
 89305    break;
 89306  }
 89307  
 89308  /* Opcode:  Return P1 * * * *
 89309  **
 89310  ** Jump to the next instruction after the address in register P1.  After
 89311  ** the jump, register P1 becomes undefined.
 89312  */
 89313  case OP_Return: {           /* in1 */
 89314    pIn1 = &aMem[pOp->p1];
 89315    assert( pIn1->flags==MEM_Int );
 89316    pOp = &aOp[pIn1->u.i];
 89317    pIn1->flags = MEM_Undefined;
 89318    break;
 89319  }
 89320  
 89321  /* Opcode: InitCoroutine P1 P2 P3 * *
 89322  **
 89323  ** Set up register P1 so that it will Yield to the coroutine
 89324  ** located at address P3.
 89325  **
 89326  ** If P2!=0 then the coroutine implementation immediately follows
 89327  ** this opcode.  So jump over the coroutine implementation to
 89328  ** address P2.
 89329  **
 89330  ** See also: EndCoroutine
 89331  */
 89332  case OP_InitCoroutine: {     /* jump */
 89333    assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
 89334    assert( pOp->p2>=0 && pOp->p2<p->nOp );
 89335    assert( pOp->p3>=0 && pOp->p3<p->nOp );
 89336    pOut = &aMem[pOp->p1];
 89337    assert( !VdbeMemDynamic(pOut) );
 89338    pOut->u.i = pOp->p3 - 1;
 89339    pOut->flags = MEM_Int;
 89340    if( pOp->p2 ) goto jump_to_p2;
 89341    break;
 89342  }
 89343  
 89344  /* Opcode:  EndCoroutine P1 * * * *
 89345  **
 89346  ** The instruction at the address in register P1 is a Yield.
 89347  ** Jump to the P2 parameter of that Yield.
 89348  ** After the jump, register P1 becomes undefined.
 89349  **
 89350  ** See also: InitCoroutine
 89351  */
 89352  case OP_EndCoroutine: {           /* in1 */
 89353    VdbeOp *pCaller;
 89354    pIn1 = &aMem[pOp->p1];
 89355    assert( pIn1->flags==MEM_Int );
 89356    assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
 89357    pCaller = &aOp[pIn1->u.i];
 89358    assert( pCaller->opcode==OP_Yield );
 89359    assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
 89360    pOp = &aOp[pCaller->p2 - 1];
 89361    pIn1->flags = MEM_Undefined;
 89362    break;
 89363  }
 89364  
 89365  /* Opcode:  Yield P1 P2 * * *
 89366  **
 89367  ** Swap the program counter with the value in register P1.  This
 89368  ** has the effect of yielding to a coroutine.
 89369  **
 89370  ** If the coroutine that is launched by this instruction ends with
 89371  ** Yield or Return then continue to the next instruction.  But if
 89372  ** the coroutine launched by this instruction ends with
 89373  ** EndCoroutine, then jump to P2 rather than continuing with the
 89374  ** next instruction.
 89375  **
 89376  ** See also: InitCoroutine
 89377  */
 89378  case OP_Yield: {            /* in1, jump */
 89379    int pcDest;
 89380    pIn1 = &aMem[pOp->p1];
 89381    assert( VdbeMemDynamic(pIn1)==0 );
 89382    pIn1->flags = MEM_Int;
 89383    pcDest = (int)pIn1->u.i;
 89384    pIn1->u.i = (int)(pOp - aOp);
 89385    REGISTER_TRACE(pOp->p1, pIn1);
 89386    pOp = &aOp[pcDest];
 89387    break;
 89388  }
 89389  
 89390  /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
 89391  ** Synopsis: if r[P3]=null halt
 89392  **
 89393  ** Check the value in register P3.  If it is NULL then Halt using
 89394  ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
 89395  ** value in register P3 is not NULL, then this routine is a no-op.
 89396  ** The P5 parameter should be 1.
 89397  */
 89398  case OP_HaltIfNull: {      /* in3 */
 89399    pIn3 = &aMem[pOp->p3];
 89400  #ifdef SQLITE_DEBUG
 89401    if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
 89402  #endif
 89403    if( (pIn3->flags & MEM_Null)==0 ) break;
 89404    /* Fall through into OP_Halt */
 89405  }
 89406  
 89407  /* Opcode:  Halt P1 P2 * P4 P5
 89408  **
 89409  ** Exit immediately.  All open cursors, etc are closed
 89410  ** automatically.
 89411  **
 89412  ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
 89413  ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
 89414  ** For errors, it can be some other value.  If P1!=0 then P2 will determine
 89415  ** whether or not to rollback the current transaction.  Do not rollback
 89416  ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
 89417  ** then back out all changes that have occurred during this execution of the
 89418  ** VDBE, but do not rollback the transaction. 
 89419  **
 89420  ** If P4 is not null then it is an error message string.
 89421  **
 89422  ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
 89423  **
 89424  **    0:  (no change)
 89425  **    1:  NOT NULL contraint failed: P4
 89426  **    2:  UNIQUE constraint failed: P4
 89427  **    3:  CHECK constraint failed: P4
 89428  **    4:  FOREIGN KEY constraint failed: P4
 89429  **
 89430  ** If P5 is not zero and P4 is NULL, then everything after the ":" is
 89431  ** omitted.
 89432  **
 89433  ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
 89434  ** every program.  So a jump past the last instruction of the program
 89435  ** is the same as executing Halt.
 89436  */
 89437  case OP_Halt: {
 89438    VdbeFrame *pFrame;
 89439    int pcx;
 89440  
 89441    pcx = (int)(pOp - aOp);
 89442  #ifdef SQLITE_DEBUG
 89443    if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
 89444  #endif
 89445    if( pOp->p1==SQLITE_OK && p->pFrame ){
 89446      /* Halt the sub-program. Return control to the parent frame. */
 89447      pFrame = p->pFrame;
 89448      p->pFrame = pFrame->pParent;
 89449      p->nFrame--;
 89450      sqlite3VdbeSetChanges(db, p->nChange);
 89451      pcx = sqlite3VdbeFrameRestore(pFrame);
 89452      if( pOp->p2==OE_Ignore ){
 89453        /* Instruction pcx is the OP_Program that invoked the sub-program 
 89454        ** currently being halted. If the p2 instruction of this OP_Halt
 89455        ** instruction is set to OE_Ignore, then the sub-program is throwing
 89456        ** an IGNORE exception. In this case jump to the address specified
 89457        ** as the p2 of the calling OP_Program.  */
 89458        pcx = p->aOp[pcx].p2-1;
 89459      }
 89460      aOp = p->aOp;
 89461      aMem = p->aMem;
 89462      pOp = &aOp[pcx];
 89463      break;
 89464    }
 89465    p->rc = pOp->p1;
 89466    p->errorAction = (u8)pOp->p2;
 89467    p->pc = pcx;
 89468    assert( pOp->p5<=4 );
 89469    if( p->rc ){
 89470      if( pOp->p5 ){
 89471        static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
 89472                                               "FOREIGN KEY" };
 89473        testcase( pOp->p5==1 );
 89474        testcase( pOp->p5==2 );
 89475        testcase( pOp->p5==3 );
 89476        testcase( pOp->p5==4 );
 89477        sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
 89478        if( pOp->p4.z ){
 89479          p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
 89480        }
 89481      }else{
 89482        sqlite3VdbeError(p, "%s", pOp->p4.z);
 89483      }
 89484      sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
 89485    }
 89486    rc = sqlite3VdbeHalt(p);
 89487    assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
 89488    if( rc==SQLITE_BUSY ){
 89489      p->rc = SQLITE_BUSY;
 89490    }else{
 89491      assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
 89492      assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
 89493      rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
 89494    }
 89495    goto vdbe_return;
 89496  }
 89497  
 89498  /* Opcode: Integer P1 P2 * * *
 89499  ** Synopsis: r[P2]=P1
 89500  **
 89501  ** The 32-bit integer value P1 is written into register P2.
 89502  */
 89503  case OP_Integer: {         /* out2 */
 89504    pOut = out2Prerelease(p, pOp);
 89505    pOut->u.i = pOp->p1;
 89506    break;
 89507  }
 89508  
 89509  /* Opcode: Int64 * P2 * P4 *
 89510  ** Synopsis: r[P2]=P4
 89511  **
 89512  ** P4 is a pointer to a 64-bit integer value.
 89513  ** Write that value into register P2.
 89514  */
 89515  case OP_Int64: {           /* out2 */
 89516    pOut = out2Prerelease(p, pOp);
 89517    assert( pOp->p4.pI64!=0 );
 89518    pOut->u.i = *pOp->p4.pI64;
 89519    break;
 89520  }
 89521  
 89522  #ifndef SQLITE_OMIT_FLOATING_POINT
 89523  /* Opcode: Real * P2 * P4 *
 89524  ** Synopsis: r[P2]=P4
 89525  **
 89526  ** P4 is a pointer to a 64-bit floating point value.
 89527  ** Write that value into register P2.
 89528  */
 89529  case OP_Real: {            /* same as TK_FLOAT, out2 */
 89530    pOut = out2Prerelease(p, pOp);
 89531    pOut->flags = MEM_Real;
 89532    assert( !sqlite3IsNaN(*pOp->p4.pReal) );
 89533    pOut->u.r = *pOp->p4.pReal;
 89534    break;
 89535  }
 89536  #endif
 89537  
 89538  /* Opcode: String8 * P2 * P4 *
 89539  ** Synopsis: r[P2]='P4'
 89540  **
 89541  ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
 89542  ** into a String opcode before it is executed for the first time.  During
 89543  ** this transformation, the length of string P4 is computed and stored
 89544  ** as the P1 parameter.
 89545  */
 89546  case OP_String8: {         /* same as TK_STRING, out2 */
 89547    assert( pOp->p4.z!=0 );
 89548    pOut = out2Prerelease(p, pOp);
 89549    pOp->opcode = OP_String;
 89550    pOp->p1 = sqlite3Strlen30(pOp->p4.z);
 89551  
 89552  #ifndef SQLITE_OMIT_UTF16
 89553    if( encoding!=SQLITE_UTF8 ){
 89554      rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
 89555      assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
 89556      if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
 89557      assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
 89558      assert( VdbeMemDynamic(pOut)==0 );
 89559      pOut->szMalloc = 0;
 89560      pOut->flags |= MEM_Static;
 89561      if( pOp->p4type==P4_DYNAMIC ){
 89562        sqlite3DbFree(db, pOp->p4.z);
 89563      }
 89564      pOp->p4type = P4_DYNAMIC;
 89565      pOp->p4.z = pOut->z;
 89566      pOp->p1 = pOut->n;
 89567    }
 89568    testcase( rc==SQLITE_TOOBIG );
 89569  #endif
 89570    if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 89571      goto too_big;
 89572    }
 89573    assert( rc==SQLITE_OK );
 89574    /* Fall through to the next case, OP_String */
 89575  }
 89576    
 89577  /* Opcode: String P1 P2 P3 P4 P5
 89578  ** Synopsis: r[P2]='P4' (len=P1)
 89579  **
 89580  ** The string value P4 of length P1 (bytes) is stored in register P2.
 89581  **
 89582  ** If P3 is not zero and the content of register P3 is equal to P5, then
 89583  ** the datatype of the register P2 is converted to BLOB.  The content is
 89584  ** the same sequence of bytes, it is merely interpreted as a BLOB instead
 89585  ** of a string, as if it had been CAST.  In other words:
 89586  **
 89587  ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
 89588  */
 89589  case OP_String: {          /* out2 */
 89590    assert( pOp->p4.z!=0 );
 89591    pOut = out2Prerelease(p, pOp);
 89592    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 89593    pOut->z = pOp->p4.z;
 89594    pOut->n = pOp->p1;
 89595    pOut->enc = encoding;
 89596    UPDATE_MAX_BLOBSIZE(pOut);
 89597  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
 89598    if( pOp->p3>0 ){
 89599      assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 89600      pIn3 = &aMem[pOp->p3];
 89601      assert( pIn3->flags & MEM_Int );
 89602      if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
 89603    }
 89604  #endif
 89605    break;
 89606  }
 89607  
 89608  /* Opcode: Null P1 P2 P3 * *
 89609  ** Synopsis: r[P2..P3]=NULL
 89610  **
 89611  ** Write a NULL into registers P2.  If P3 greater than P2, then also write
 89612  ** NULL into register P3 and every register in between P2 and P3.  If P3
 89613  ** is less than P2 (typically P3 is zero) then only register P2 is
 89614  ** set to NULL.
 89615  **
 89616  ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
 89617  ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
 89618  ** OP_Ne or OP_Eq.
 89619  */
 89620  case OP_Null: {           /* out2 */
 89621    int cnt;
 89622    u16 nullFlag;
 89623    pOut = out2Prerelease(p, pOp);
 89624    cnt = pOp->p3-pOp->p2;
 89625    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 89626    pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
 89627    pOut->n = 0;
 89628  #ifdef SQLITE_DEBUG
 89629    pOut->uTemp = 0;
 89630  #endif
 89631    while( cnt>0 ){
 89632      pOut++;
 89633      memAboutToChange(p, pOut);
 89634      sqlite3VdbeMemSetNull(pOut);
 89635      pOut->flags = nullFlag;
 89636      pOut->n = 0;
 89637      cnt--;
 89638    }
 89639    break;
 89640  }
 89641  
 89642  /* Opcode: SoftNull P1 * * * *
 89643  ** Synopsis: r[P1]=NULL
 89644  **
 89645  ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
 89646  ** instruction, but do not free any string or blob memory associated with
 89647  ** the register, so that if the value was a string or blob that was
 89648  ** previously copied using OP_SCopy, the copies will continue to be valid.
 89649  */
 89650  case OP_SoftNull: {
 89651    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 89652    pOut = &aMem[pOp->p1];
 89653    pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
 89654    break;
 89655  }
 89656  
 89657  /* Opcode: Blob P1 P2 * P4 *
 89658  ** Synopsis: r[P2]=P4 (len=P1)
 89659  **
 89660  ** P4 points to a blob of data P1 bytes long.  Store this
 89661  ** blob in register P2.
 89662  */
 89663  case OP_Blob: {                /* out2 */
 89664    assert( pOp->p1 <= SQLITE_MAX_LENGTH );
 89665    pOut = out2Prerelease(p, pOp);
 89666    sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
 89667    pOut->enc = encoding;
 89668    UPDATE_MAX_BLOBSIZE(pOut);
 89669    break;
 89670  }
 89671  
 89672  /* Opcode: Variable P1 P2 * P4 *
 89673  ** Synopsis: r[P2]=parameter(P1,P4)
 89674  **
 89675  ** Transfer the values of bound parameter P1 into register P2
 89676  **
 89677  ** If the parameter is named, then its name appears in P4.
 89678  ** The P4 value is used by sqlite3_bind_parameter_name().
 89679  */
 89680  case OP_Variable: {            /* out2 */
 89681    Mem *pVar;       /* Value being transferred */
 89682  
 89683    assert( pOp->p1>0 && pOp->p1<=p->nVar );
 89684    assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
 89685    pVar = &p->aVar[pOp->p1 - 1];
 89686    if( sqlite3VdbeMemTooBig(pVar) ){
 89687      goto too_big;
 89688    }
 89689    pOut = &aMem[pOp->p2];
 89690    sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
 89691    UPDATE_MAX_BLOBSIZE(pOut);
 89692    break;
 89693  }
 89694  
 89695  /* Opcode: Move P1 P2 P3 * *
 89696  ** Synopsis: r[P2@P3]=r[P1@P3]
 89697  **
 89698  ** Move the P3 values in register P1..P1+P3-1 over into
 89699  ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
 89700  ** left holding a NULL.  It is an error for register ranges
 89701  ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
 89702  ** for P3 to be less than 1.
 89703  */
 89704  case OP_Move: {
 89705    int n;           /* Number of registers left to copy */
 89706    int p1;          /* Register to copy from */
 89707    int p2;          /* Register to copy to */
 89708  
 89709    n = pOp->p3;
 89710    p1 = pOp->p1;
 89711    p2 = pOp->p2;
 89712    assert( n>0 && p1>0 && p2>0 );
 89713    assert( p1+n<=p2 || p2+n<=p1 );
 89714  
 89715    pIn1 = &aMem[p1];
 89716    pOut = &aMem[p2];
 89717    do{
 89718      assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
 89719      assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
 89720      assert( memIsValid(pIn1) );
 89721      memAboutToChange(p, pOut);
 89722      sqlite3VdbeMemMove(pOut, pIn1);
 89723  #ifdef SQLITE_DEBUG
 89724      if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
 89725        pOut->pScopyFrom += pOp->p2 - p1;
 89726      }
 89727  #endif
 89728      Deephemeralize(pOut);
 89729      REGISTER_TRACE(p2++, pOut);
 89730      pIn1++;
 89731      pOut++;
 89732    }while( --n );
 89733    break;
 89734  }
 89735  
 89736  /* Opcode: Copy P1 P2 P3 * *
 89737  ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
 89738  **
 89739  ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
 89740  **
 89741  ** This instruction makes a deep copy of the value.  A duplicate
 89742  ** is made of any string or blob constant.  See also OP_SCopy.
 89743  */
 89744  case OP_Copy: {
 89745    int n;
 89746  
 89747    n = pOp->p3;
 89748    pIn1 = &aMem[pOp->p1];
 89749    pOut = &aMem[pOp->p2];
 89750    assert( pOut!=pIn1 );
 89751    while( 1 ){
 89752      memAboutToChange(p, pOut);
 89753      sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 89754      Deephemeralize(pOut);
 89755  #ifdef SQLITE_DEBUG
 89756      pOut->pScopyFrom = 0;
 89757  #endif
 89758      REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
 89759      if( (n--)==0 ) break;
 89760      pOut++;
 89761      pIn1++;
 89762    }
 89763    break;
 89764  }
 89765  
 89766  /* Opcode: SCopy P1 P2 * * *
 89767  ** Synopsis: r[P2]=r[P1]
 89768  **
 89769  ** Make a shallow copy of register P1 into register P2.
 89770  **
 89771  ** This instruction makes a shallow copy of the value.  If the value
 89772  ** is a string or blob, then the copy is only a pointer to the
 89773  ** original and hence if the original changes so will the copy.
 89774  ** Worse, if the original is deallocated, the copy becomes invalid.
 89775  ** Thus the program must guarantee that the original will not change
 89776  ** during the lifetime of the copy.  Use OP_Copy to make a complete
 89777  ** copy.
 89778  */
 89779  case OP_SCopy: {            /* out2 */
 89780    pIn1 = &aMem[pOp->p1];
 89781    pOut = &aMem[pOp->p2];
 89782    assert( pOut!=pIn1 );
 89783    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 89784  #ifdef SQLITE_DEBUG
 89785    pOut->pScopyFrom = pIn1;
 89786    pOut->mScopyFlags = pIn1->flags;
 89787  #endif
 89788    break;
 89789  }
 89790  
 89791  /* Opcode: IntCopy P1 P2 * * *
 89792  ** Synopsis: r[P2]=r[P1]
 89793  **
 89794  ** Transfer the integer value held in register P1 into register P2.
 89795  **
 89796  ** This is an optimized version of SCopy that works only for integer
 89797  ** values.
 89798  */
 89799  case OP_IntCopy: {            /* out2 */
 89800    pIn1 = &aMem[pOp->p1];
 89801    assert( (pIn1->flags & MEM_Int)!=0 );
 89802    pOut = &aMem[pOp->p2];
 89803    sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
 89804    break;
 89805  }
 89806  
 89807  /* Opcode: ResultRow P1 P2 * * *
 89808  ** Synopsis: output=r[P1@P2]
 89809  **
 89810  ** The registers P1 through P1+P2-1 contain a single row of
 89811  ** results. This opcode causes the sqlite3_step() call to terminate
 89812  ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
 89813  ** structure to provide access to the r(P1)..r(P1+P2-1) values as
 89814  ** the result row.
 89815  */
 89816  case OP_ResultRow: {
 89817    Mem *pMem;
 89818    int i;
 89819    assert( p->nResColumn==pOp->p2 );
 89820    assert( pOp->p1>0 );
 89821    assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
 89822  
 89823  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 89824    /* Run the progress counter just before returning.
 89825    */
 89826    if( db->xProgress!=0
 89827     && nVmStep>=nProgressLimit 
 89828     && db->xProgress(db->pProgressArg)!=0
 89829    ){
 89830      rc = SQLITE_INTERRUPT;
 89831      goto abort_due_to_error;
 89832    }
 89833  #endif
 89834  
 89835    /* If this statement has violated immediate foreign key constraints, do
 89836    ** not return the number of rows modified. And do not RELEASE the statement
 89837    ** transaction. It needs to be rolled back.  */
 89838    if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
 89839      assert( db->flags&SQLITE_CountRows );
 89840      assert( p->usesStmtJournal );
 89841      goto abort_due_to_error;
 89842    }
 89843  
 89844    /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
 89845    ** DML statements invoke this opcode to return the number of rows 
 89846    ** modified to the user. This is the only way that a VM that
 89847    ** opens a statement transaction may invoke this opcode.
 89848    **
 89849    ** In case this is such a statement, close any statement transaction
 89850    ** opened by this VM before returning control to the user. This is to
 89851    ** ensure that statement-transactions are always nested, not overlapping.
 89852    ** If the open statement-transaction is not closed here, then the user
 89853    ** may step another VM that opens its own statement transaction. This
 89854    ** may lead to overlapping statement transactions.
 89855    **
 89856    ** The statement transaction is never a top-level transaction.  Hence
 89857    ** the RELEASE call below can never fail.
 89858    */
 89859    assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
 89860    rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
 89861    assert( rc==SQLITE_OK );
 89862  
 89863    /* Invalidate all ephemeral cursor row caches */
 89864    p->cacheCtr = (p->cacheCtr + 2)|1;
 89865  
 89866    /* Make sure the results of the current row are \000 terminated
 89867    ** and have an assigned type.  The results are de-ephemeralized as
 89868    ** a side effect.
 89869    */
 89870    pMem = p->pResultSet = &aMem[pOp->p1];
 89871    for(i=0; i<pOp->p2; i++){
 89872      assert( memIsValid(&pMem[i]) );
 89873      Deephemeralize(&pMem[i]);
 89874      assert( (pMem[i].flags & MEM_Ephem)==0
 89875              || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
 89876      sqlite3VdbeMemNulTerminate(&pMem[i]);
 89877      REGISTER_TRACE(pOp->p1+i, &pMem[i]);
 89878    }
 89879    if( db->mallocFailed ) goto no_mem;
 89880  
 89881    if( db->mTrace & SQLITE_TRACE_ROW ){
 89882      db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
 89883    }
 89884  
 89885    /* Return SQLITE_ROW
 89886    */
 89887    p->pc = (int)(pOp - aOp) + 1;
 89888    rc = SQLITE_ROW;
 89889    goto vdbe_return;
 89890  }
 89891  
 89892  /* Opcode: Concat P1 P2 P3 * *
 89893  ** Synopsis: r[P3]=r[P2]+r[P1]
 89894  **
 89895  ** Add the text in register P1 onto the end of the text in
 89896  ** register P2 and store the result in register P3.
 89897  ** If either the P1 or P2 text are NULL then store NULL in P3.
 89898  **
 89899  **   P3 = P2 || P1
 89900  **
 89901  ** It is illegal for P1 and P3 to be the same register. Sometimes,
 89902  ** if P3 is the same register as P2, the implementation is able
 89903  ** to avoid a memcpy().
 89904  */
 89905  case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
 89906    i64 nByte;
 89907  
 89908    pIn1 = &aMem[pOp->p1];
 89909    pIn2 = &aMem[pOp->p2];
 89910    pOut = &aMem[pOp->p3];
 89911    assert( pIn1!=pOut );
 89912    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 89913      sqlite3VdbeMemSetNull(pOut);
 89914      break;
 89915    }
 89916    if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
 89917    Stringify(pIn1, encoding);
 89918    Stringify(pIn2, encoding);
 89919    nByte = pIn1->n + pIn2->n;
 89920    if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 89921      goto too_big;
 89922    }
 89923    if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
 89924      goto no_mem;
 89925    }
 89926    MemSetTypeFlag(pOut, MEM_Str);
 89927    if( pOut!=pIn2 ){
 89928      memcpy(pOut->z, pIn2->z, pIn2->n);
 89929    }
 89930    memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
 89931    pOut->z[nByte]=0;
 89932    pOut->z[nByte+1] = 0;
 89933    pOut->flags |= MEM_Term;
 89934    pOut->n = (int)nByte;
 89935    pOut->enc = encoding;
 89936    UPDATE_MAX_BLOBSIZE(pOut);
 89937    break;
 89938  }
 89939  
 89940  /* Opcode: Add P1 P2 P3 * *
 89941  ** Synopsis: r[P3]=r[P1]+r[P2]
 89942  **
 89943  ** Add the value in register P1 to the value in register P2
 89944  ** and store the result in register P3.
 89945  ** If either input is NULL, the result is NULL.
 89946  */
 89947  /* Opcode: Multiply P1 P2 P3 * *
 89948  ** Synopsis: r[P3]=r[P1]*r[P2]
 89949  **
 89950  **
 89951  ** Multiply the value in register P1 by the value in register P2
 89952  ** and store the result in register P3.
 89953  ** If either input is NULL, the result is NULL.
 89954  */
 89955  /* Opcode: Subtract P1 P2 P3 * *
 89956  ** Synopsis: r[P3]=r[P2]-r[P1]
 89957  **
 89958  ** Subtract the value in register P1 from the value in register P2
 89959  ** and store the result in register P3.
 89960  ** If either input is NULL, the result is NULL.
 89961  */
 89962  /* Opcode: Divide P1 P2 P3 * *
 89963  ** Synopsis: r[P3]=r[P2]/r[P1]
 89964  **
 89965  ** Divide the value in register P1 by the value in register P2
 89966  ** and store the result in register P3 (P3=P2/P1). If the value in 
 89967  ** register P1 is zero, then the result is NULL. If either input is 
 89968  ** NULL, the result is NULL.
 89969  */
 89970  /* Opcode: Remainder P1 P2 P3 * *
 89971  ** Synopsis: r[P3]=r[P2]%r[P1]
 89972  **
 89973  ** Compute the remainder after integer register P2 is divided by 
 89974  ** register P1 and store the result in register P3. 
 89975  ** If the value in register P1 is zero the result is NULL.
 89976  ** If either operand is NULL, the result is NULL.
 89977  */
 89978  case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
 89979  case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
 89980  case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
 89981  case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
 89982  case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
 89983    char bIntint;   /* Started out as two integer operands */
 89984    u16 flags;      /* Combined MEM_* flags from both inputs */
 89985    u16 type1;      /* Numeric type of left operand */
 89986    u16 type2;      /* Numeric type of right operand */
 89987    i64 iA;         /* Integer value of left operand */
 89988    i64 iB;         /* Integer value of right operand */
 89989    double rA;      /* Real value of left operand */
 89990    double rB;      /* Real value of right operand */
 89991  
 89992    pIn1 = &aMem[pOp->p1];
 89993    type1 = numericType(pIn1);
 89994    pIn2 = &aMem[pOp->p2];
 89995    type2 = numericType(pIn2);
 89996    pOut = &aMem[pOp->p3];
 89997    flags = pIn1->flags | pIn2->flags;
 89998    if( (type1 & type2 & MEM_Int)!=0 ){
 89999      iA = pIn1->u.i;
 90000      iB = pIn2->u.i;
 90001      bIntint = 1;
 90002      switch( pOp->opcode ){
 90003        case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
 90004        case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
 90005        case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
 90006        case OP_Divide: {
 90007          if( iA==0 ) goto arithmetic_result_is_null;
 90008          if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
 90009          iB /= iA;
 90010          break;
 90011        }
 90012        default: {
 90013          if( iA==0 ) goto arithmetic_result_is_null;
 90014          if( iA==-1 ) iA = 1;
 90015          iB %= iA;
 90016          break;
 90017        }
 90018      }
 90019      pOut->u.i = iB;
 90020      MemSetTypeFlag(pOut, MEM_Int);
 90021    }else if( (flags & MEM_Null)!=0 ){
 90022      goto arithmetic_result_is_null;
 90023    }else{
 90024      bIntint = 0;
 90025  fp_math:
 90026      rA = sqlite3VdbeRealValue(pIn1);
 90027      rB = sqlite3VdbeRealValue(pIn2);
 90028      switch( pOp->opcode ){
 90029        case OP_Add:         rB += rA;       break;
 90030        case OP_Subtract:    rB -= rA;       break;
 90031        case OP_Multiply:    rB *= rA;       break;
 90032        case OP_Divide: {
 90033          /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
 90034          if( rA==(double)0 ) goto arithmetic_result_is_null;
 90035          rB /= rA;
 90036          break;
 90037        }
 90038        default: {
 90039          iA = sqlite3VdbeIntValue(pIn1);
 90040          iB = sqlite3VdbeIntValue(pIn2);
 90041          if( iA==0 ) goto arithmetic_result_is_null;
 90042          if( iA==-1 ) iA = 1;
 90043          rB = (double)(iB % iA);
 90044          break;
 90045        }
 90046      }
 90047  #ifdef SQLITE_OMIT_FLOATING_POINT
 90048      pOut->u.i = rB;
 90049      MemSetTypeFlag(pOut, MEM_Int);
 90050  #else
 90051      if( sqlite3IsNaN(rB) ){
 90052        goto arithmetic_result_is_null;
 90053      }
 90054      pOut->u.r = rB;
 90055      MemSetTypeFlag(pOut, MEM_Real);
 90056      if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
 90057        sqlite3VdbeIntegerAffinity(pOut);
 90058      }
 90059  #endif
 90060    }
 90061    break;
 90062  
 90063  arithmetic_result_is_null:
 90064    sqlite3VdbeMemSetNull(pOut);
 90065    break;
 90066  }
 90067  
 90068  /* Opcode: CollSeq P1 * * P4
 90069  **
 90070  ** P4 is a pointer to a CollSeq object. If the next call to a user function
 90071  ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
 90072  ** be returned. This is used by the built-in min(), max() and nullif()
 90073  ** functions.
 90074  **
 90075  ** If P1 is not zero, then it is a register that a subsequent min() or
 90076  ** max() aggregate will set to 1 if the current row is not the minimum or
 90077  ** maximum.  The P1 register is initialized to 0 by this instruction.
 90078  **
 90079  ** The interface used by the implementation of the aforementioned functions
 90080  ** to retrieve the collation sequence set by this opcode is not available
 90081  ** publicly.  Only built-in functions have access to this feature.
 90082  */
 90083  case OP_CollSeq: {
 90084    assert( pOp->p4type==P4_COLLSEQ );
 90085    if( pOp->p1 ){
 90086      sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
 90087    }
 90088    break;
 90089  }
 90090  
 90091  /* Opcode: BitAnd P1 P2 P3 * *
 90092  ** Synopsis: r[P3]=r[P1]&r[P2]
 90093  **
 90094  ** Take the bit-wise AND of the values in register P1 and P2 and
 90095  ** store the result in register P3.
 90096  ** If either input is NULL, the result is NULL.
 90097  */
 90098  /* Opcode: BitOr P1 P2 P3 * *
 90099  ** Synopsis: r[P3]=r[P1]|r[P2]
 90100  **
 90101  ** Take the bit-wise OR of the values in register P1 and P2 and
 90102  ** store the result in register P3.
 90103  ** If either input is NULL, the result is NULL.
 90104  */
 90105  /* Opcode: ShiftLeft P1 P2 P3 * *
 90106  ** Synopsis: r[P3]=r[P2]<<r[P1]
 90107  **
 90108  ** Shift the integer value in register P2 to the left by the
 90109  ** number of bits specified by the integer in register P1.
 90110  ** Store the result in register P3.
 90111  ** If either input is NULL, the result is NULL.
 90112  */
 90113  /* Opcode: ShiftRight P1 P2 P3 * *
 90114  ** Synopsis: r[P3]=r[P2]>>r[P1]
 90115  **
 90116  ** Shift the integer value in register P2 to the right by the
 90117  ** number of bits specified by the integer in register P1.
 90118  ** Store the result in register P3.
 90119  ** If either input is NULL, the result is NULL.
 90120  */
 90121  case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
 90122  case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
 90123  case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
 90124  case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
 90125    i64 iA;
 90126    u64 uA;
 90127    i64 iB;
 90128    u8 op;
 90129  
 90130    pIn1 = &aMem[pOp->p1];
 90131    pIn2 = &aMem[pOp->p2];
 90132    pOut = &aMem[pOp->p3];
 90133    if( (pIn1->flags | pIn2->flags) & MEM_Null ){
 90134      sqlite3VdbeMemSetNull(pOut);
 90135      break;
 90136    }
 90137    iA = sqlite3VdbeIntValue(pIn2);
 90138    iB = sqlite3VdbeIntValue(pIn1);
 90139    op = pOp->opcode;
 90140    if( op==OP_BitAnd ){
 90141      iA &= iB;
 90142    }else if( op==OP_BitOr ){
 90143      iA |= iB;
 90144    }else if( iB!=0 ){
 90145      assert( op==OP_ShiftRight || op==OP_ShiftLeft );
 90146  
 90147      /* If shifting by a negative amount, shift in the other direction */
 90148      if( iB<0 ){
 90149        assert( OP_ShiftRight==OP_ShiftLeft+1 );
 90150        op = 2*OP_ShiftLeft + 1 - op;
 90151        iB = iB>(-64) ? -iB : 64;
 90152      }
 90153  
 90154      if( iB>=64 ){
 90155        iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
 90156      }else{
 90157        memcpy(&uA, &iA, sizeof(uA));
 90158        if( op==OP_ShiftLeft ){
 90159          uA <<= iB;
 90160        }else{
 90161          uA >>= iB;
 90162          /* Sign-extend on a right shift of a negative number */
 90163          if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
 90164        }
 90165        memcpy(&iA, &uA, sizeof(iA));
 90166      }
 90167    }
 90168    pOut->u.i = iA;
 90169    MemSetTypeFlag(pOut, MEM_Int);
 90170    break;
 90171  }
 90172  
 90173  /* Opcode: AddImm  P1 P2 * * *
 90174  ** Synopsis: r[P1]=r[P1]+P2
 90175  ** 
 90176  ** Add the constant P2 to the value in register P1.
 90177  ** The result is always an integer.
 90178  **
 90179  ** To force any register to be an integer, just add 0.
 90180  */
 90181  case OP_AddImm: {            /* in1 */
 90182    pIn1 = &aMem[pOp->p1];
 90183    memAboutToChange(p, pIn1);
 90184    sqlite3VdbeMemIntegerify(pIn1);
 90185    pIn1->u.i += pOp->p2;
 90186    break;
 90187  }
 90188  
 90189  /* Opcode: MustBeInt P1 P2 * * *
 90190  ** 
 90191  ** Force the value in register P1 to be an integer.  If the value
 90192  ** in P1 is not an integer and cannot be converted into an integer
 90193  ** without data loss, then jump immediately to P2, or if P2==0
 90194  ** raise an SQLITE_MISMATCH exception.
 90195  */
 90196  case OP_MustBeInt: {            /* jump, in1 */
 90197    pIn1 = &aMem[pOp->p1];
 90198    if( (pIn1->flags & MEM_Int)==0 ){
 90199      applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
 90200      VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
 90201      if( (pIn1->flags & MEM_Int)==0 ){
 90202        if( pOp->p2==0 ){
 90203          rc = SQLITE_MISMATCH;
 90204          goto abort_due_to_error;
 90205        }else{
 90206          goto jump_to_p2;
 90207        }
 90208      }
 90209    }
 90210    MemSetTypeFlag(pIn1, MEM_Int);
 90211    break;
 90212  }
 90213  
 90214  #ifndef SQLITE_OMIT_FLOATING_POINT
 90215  /* Opcode: RealAffinity P1 * * * *
 90216  **
 90217  ** If register P1 holds an integer convert it to a real value.
 90218  **
 90219  ** This opcode is used when extracting information from a column that
 90220  ** has REAL affinity.  Such column values may still be stored as
 90221  ** integers, for space efficiency, but after extraction we want them
 90222  ** to have only a real value.
 90223  */
 90224  case OP_RealAffinity: {                  /* in1 */
 90225    pIn1 = &aMem[pOp->p1];
 90226    if( pIn1->flags & MEM_Int ){
 90227      sqlite3VdbeMemRealify(pIn1);
 90228    }
 90229    break;
 90230  }
 90231  #endif
 90232  
 90233  #ifndef SQLITE_OMIT_CAST
 90234  /* Opcode: Cast P1 P2 * * *
 90235  ** Synopsis: affinity(r[P1])
 90236  **
 90237  ** Force the value in register P1 to be the type defined by P2.
 90238  ** 
 90239  ** <ul>
 90240  ** <li> P2=='A' &rarr; BLOB
 90241  ** <li> P2=='B' &rarr; TEXT
 90242  ** <li> P2=='C' &rarr; NUMERIC
 90243  ** <li> P2=='D' &rarr; INTEGER
 90244  ** <li> P2=='E' &rarr; REAL
 90245  ** </ul>
 90246  **
 90247  ** A NULL value is not changed by this routine.  It remains NULL.
 90248  */
 90249  case OP_Cast: {                  /* in1 */
 90250    assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
 90251    testcase( pOp->p2==SQLITE_AFF_TEXT );
 90252    testcase( pOp->p2==SQLITE_AFF_BLOB );
 90253    testcase( pOp->p2==SQLITE_AFF_NUMERIC );
 90254    testcase( pOp->p2==SQLITE_AFF_INTEGER );
 90255    testcase( pOp->p2==SQLITE_AFF_REAL );
 90256    pIn1 = &aMem[pOp->p1];
 90257    memAboutToChange(p, pIn1);
 90258    rc = ExpandBlob(pIn1);
 90259    sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
 90260    UPDATE_MAX_BLOBSIZE(pIn1);
 90261    if( rc ) goto abort_due_to_error;
 90262    break;
 90263  }
 90264  #endif /* SQLITE_OMIT_CAST */
 90265  
 90266  /* Opcode: Eq P1 P2 P3 P4 P5
 90267  ** Synopsis: IF r[P3]==r[P1]
 90268  **
 90269  ** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
 90270  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
 90271  ** store the result of comparison in register P2.
 90272  **
 90273  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 90274  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
 90275  ** to coerce both inputs according to this affinity before the
 90276  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 90277  ** affinity is used. Note that the affinity conversions are stored
 90278  ** back into the input registers P1 and P3.  So this opcode can cause
 90279  ** persistent changes to registers P1 and P3.
 90280  **
 90281  ** Once any conversions have taken place, and neither value is NULL, 
 90282  ** the values are compared. If both values are blobs then memcmp() is
 90283  ** used to determine the results of the comparison.  If both values
 90284  ** are text, then the appropriate collating function specified in
 90285  ** P4 is used to do the comparison.  If P4 is not specified then
 90286  ** memcmp() is used to compare text string.  If both values are
 90287  ** numeric, then a numeric comparison is used. If the two values
 90288  ** are of different types, then numbers are considered less than
 90289  ** strings and strings are considered less than blobs.
 90290  **
 90291  ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
 90292  ** true or false and is never NULL.  If both operands are NULL then the result
 90293  ** of comparison is true.  If either operand is NULL then the result is false.
 90294  ** If neither operand is NULL the result is the same as it would be if
 90295  ** the SQLITE_NULLEQ flag were omitted from P5.
 90296  **
 90297  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
 90298  ** content of r[P2] is only changed if the new value is NULL or 0 (false).
 90299  ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
 90300  */
 90301  /* Opcode: Ne P1 P2 P3 P4 P5
 90302  ** Synopsis: IF r[P3]!=r[P1]
 90303  **
 90304  ** This works just like the Eq opcode except that the jump is taken if
 90305  ** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
 90306  ** additional information.
 90307  **
 90308  ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
 90309  ** content of r[P2] is only changed if the new value is NULL or 1 (true).
 90310  ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
 90311  */
 90312  /* Opcode: Lt P1 P2 P3 P4 P5
 90313  ** Synopsis: IF r[P3]<r[P1]
 90314  **
 90315  ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
 90316  ** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
 90317  ** the result of comparison (0 or 1 or NULL) into register P2.
 90318  **
 90319  ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
 90320  ** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL 
 90321  ** bit is clear then fall through if either operand is NULL.
 90322  **
 90323  ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
 90324  ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
 90325  ** to coerce both inputs according to this affinity before the
 90326  ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 90327  ** affinity is used. Note that the affinity conversions are stored
 90328  ** back into the input registers P1 and P3.  So this opcode can cause
 90329  ** persistent changes to registers P1 and P3.
 90330  **
 90331  ** Once any conversions have taken place, and neither value is NULL, 
 90332  ** the values are compared. If both values are blobs then memcmp() is
 90333  ** used to determine the results of the comparison.  If both values
 90334  ** are text, then the appropriate collating function specified in
 90335  ** P4 is  used to do the comparison.  If P4 is not specified then
 90336  ** memcmp() is used to compare text string.  If both values are
 90337  ** numeric, then a numeric comparison is used. If the two values
 90338  ** are of different types, then numbers are considered less than
 90339  ** strings and strings are considered less than blobs.
 90340  */
 90341  /* Opcode: Le P1 P2 P3 P4 P5
 90342  ** Synopsis: IF r[P3]<=r[P1]
 90343  **
 90344  ** This works just like the Lt opcode except that the jump is taken if
 90345  ** the content of register P3 is less than or equal to the content of
 90346  ** register P1.  See the Lt opcode for additional information.
 90347  */
 90348  /* Opcode: Gt P1 P2 P3 P4 P5
 90349  ** Synopsis: IF r[P3]>r[P1]
 90350  **
 90351  ** This works just like the Lt opcode except that the jump is taken if
 90352  ** the content of register P3 is greater than the content of
 90353  ** register P1.  See the Lt opcode for additional information.
 90354  */
 90355  /* Opcode: Ge P1 P2 P3 P4 P5
 90356  ** Synopsis: IF r[P3]>=r[P1]
 90357  **
 90358  ** This works just like the Lt opcode except that the jump is taken if
 90359  ** the content of register P3 is greater than or equal to the content of
 90360  ** register P1.  See the Lt opcode for additional information.
 90361  */
 90362  case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
 90363  case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
 90364  case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
 90365  case OP_Le:               /* same as TK_LE, jump, in1, in3 */
 90366  case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
 90367  case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
 90368    int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
 90369    char affinity;      /* Affinity to use for comparison */
 90370    u16 flags1;         /* Copy of initial value of pIn1->flags */
 90371    u16 flags3;         /* Copy of initial value of pIn3->flags */
 90372  
 90373    pIn1 = &aMem[pOp->p1];
 90374    pIn3 = &aMem[pOp->p3];
 90375    flags1 = pIn1->flags;
 90376    flags3 = pIn3->flags;
 90377    if( (flags1 | flags3)&MEM_Null ){
 90378      /* One or both operands are NULL */
 90379      if( pOp->p5 & SQLITE_NULLEQ ){
 90380        /* If SQLITE_NULLEQ is set (which will only happen if the operator is
 90381        ** OP_Eq or OP_Ne) then take the jump or not depending on whether
 90382        ** or not both operands are null.
 90383        */
 90384        assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
 90385        assert( (flags1 & MEM_Cleared)==0 );
 90386        assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
 90387        testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
 90388        if( (flags1&flags3&MEM_Null)!=0
 90389         && (flags3&MEM_Cleared)==0
 90390        ){
 90391          res = 0;  /* Operands are equal */
 90392        }else{
 90393          res = 1;  /* Operands are not equal */
 90394        }
 90395      }else{
 90396        /* SQLITE_NULLEQ is clear and at least one operand is NULL,
 90397        ** then the result is always NULL.
 90398        ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
 90399        */
 90400        if( pOp->p5 & SQLITE_STOREP2 ){
 90401          pOut = &aMem[pOp->p2];
 90402          iCompare = 1;    /* Operands are not equal */
 90403          memAboutToChange(p, pOut);
 90404          MemSetTypeFlag(pOut, MEM_Null);
 90405          REGISTER_TRACE(pOp->p2, pOut);
 90406        }else{
 90407          VdbeBranchTaken(2,3);
 90408          if( pOp->p5 & SQLITE_JUMPIFNULL ){
 90409            goto jump_to_p2;
 90410          }
 90411        }
 90412        break;
 90413      }
 90414    }else{
 90415      /* Neither operand is NULL.  Do a comparison. */
 90416      affinity = pOp->p5 & SQLITE_AFF_MASK;
 90417      if( affinity>=SQLITE_AFF_NUMERIC ){
 90418        if( (flags1 | flags3)&MEM_Str ){
 90419          if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 90420            applyNumericAffinity(pIn1,0);
 90421            assert( flags3==pIn3->flags );
 90422            /* testcase( flags3!=pIn3->flags );
 90423            ** this used to be possible with pIn1==pIn3, but not since
 90424            ** the column cache was removed.  The following assignment
 90425            ** is essentially a no-op.  But, it provides defense-in-depth
 90426            ** in case our analysis is incorrect, so it is left in. */
 90427            flags3 = pIn3->flags;
 90428          }
 90429          if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 90430            applyNumericAffinity(pIn3,0);
 90431          }
 90432        }
 90433        /* Handle the common case of integer comparison here, as an
 90434        ** optimization, to avoid a call to sqlite3MemCompare() */
 90435        if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
 90436          if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
 90437          if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
 90438          res = 0;
 90439          goto compare_op;
 90440        }
 90441      }else if( affinity==SQLITE_AFF_TEXT ){
 90442        if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
 90443          testcase( pIn1->flags & MEM_Int );
 90444          testcase( pIn1->flags & MEM_Real );
 90445          sqlite3VdbeMemStringify(pIn1, encoding, 1);
 90446          testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
 90447          flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
 90448          assert( pIn1!=pIn3 );
 90449        }
 90450        if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
 90451          testcase( pIn3->flags & MEM_Int );
 90452          testcase( pIn3->flags & MEM_Real );
 90453          sqlite3VdbeMemStringify(pIn3, encoding, 1);
 90454          testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
 90455          flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
 90456        }
 90457      }
 90458      assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
 90459      res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
 90460    }
 90461  compare_op:
 90462    /* At this point, res is negative, zero, or positive if reg[P1] is
 90463    ** less than, equal to, or greater than reg[P3], respectively.  Compute
 90464    ** the answer to this operator in res2, depending on what the comparison
 90465    ** operator actually is.  The next block of code depends on the fact
 90466    ** that the 6 comparison operators are consecutive integers in this
 90467    ** order:  NE, EQ, GT, LE, LT, GE */
 90468    assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
 90469    assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
 90470    if( res<0 ){                        /* ne, eq, gt, le, lt, ge */
 90471      static const unsigned char aLTb[] = { 1,  0,  0,  1,  1,  0 };
 90472      res2 = aLTb[pOp->opcode - OP_Ne];
 90473    }else if( res==0 ){
 90474      static const unsigned char aEQb[] = { 0,  1,  0,  1,  0,  1 };
 90475      res2 = aEQb[pOp->opcode - OP_Ne];
 90476    }else{
 90477      static const unsigned char aGTb[] = { 1,  0,  1,  0,  0,  1 };
 90478      res2 = aGTb[pOp->opcode - OP_Ne];
 90479    }
 90480  
 90481    /* Undo any changes made by applyAffinity() to the input registers. */
 90482    assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
 90483    pIn1->flags = flags1;
 90484    assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
 90485    pIn3->flags = flags3;
 90486  
 90487    if( pOp->p5 & SQLITE_STOREP2 ){
 90488      pOut = &aMem[pOp->p2];
 90489      iCompare = res;
 90490      if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
 90491        /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
 90492        ** and prevents OP_Ne from overwriting NULL with 0.  This flag
 90493        ** is only used in contexts where either:
 90494        **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
 90495        **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
 90496        ** Therefore it is not necessary to check the content of r[P2] for
 90497        ** NULL. */
 90498        assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
 90499        assert( res2==0 || res2==1 );
 90500        testcase( res2==0 && pOp->opcode==OP_Eq );
 90501        testcase( res2==1 && pOp->opcode==OP_Eq );
 90502        testcase( res2==0 && pOp->opcode==OP_Ne );
 90503        testcase( res2==1 && pOp->opcode==OP_Ne );
 90504        if( (pOp->opcode==OP_Eq)==res2 ) break;
 90505      }
 90506      memAboutToChange(p, pOut);
 90507      MemSetTypeFlag(pOut, MEM_Int);
 90508      pOut->u.i = res2;
 90509      REGISTER_TRACE(pOp->p2, pOut);
 90510    }else{
 90511      VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
 90512      if( res2 ){
 90513        goto jump_to_p2;
 90514      }
 90515    }
 90516    break;
 90517  }
 90518  
 90519  /* Opcode: ElseNotEq * P2 * * *
 90520  **
 90521  ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
 90522  ** If result of an OP_Eq comparison on the same two operands
 90523  ** would have be NULL or false (0), then then jump to P2. 
 90524  ** If the result of an OP_Eq comparison on the two previous operands
 90525  ** would have been true (1), then fall through.
 90526  */
 90527  case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
 90528    assert( pOp>aOp );
 90529    assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
 90530    assert( pOp[-1].p5 & SQLITE_STOREP2 );
 90531    VdbeBranchTaken(iCompare!=0, 2);
 90532    if( iCompare!=0 ) goto jump_to_p2;
 90533    break;
 90534  }
 90535  
 90536  
 90537  /* Opcode: Permutation * * * P4 *
 90538  **
 90539  ** Set the permutation used by the OP_Compare operator in the next
 90540  ** instruction.  The permutation is stored in the P4 operand.
 90541  **
 90542  ** The permutation is only valid until the next OP_Compare that has
 90543  ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
 90544  ** occur immediately prior to the OP_Compare.
 90545  **
 90546  ** The first integer in the P4 integer array is the length of the array
 90547  ** and does not become part of the permutation.
 90548  */
 90549  case OP_Permutation: {
 90550    assert( pOp->p4type==P4_INTARRAY );
 90551    assert( pOp->p4.ai );
 90552    assert( pOp[1].opcode==OP_Compare );
 90553    assert( pOp[1].p5 & OPFLAG_PERMUTE );
 90554    break;
 90555  }
 90556  
 90557  /* Opcode: Compare P1 P2 P3 P4 P5
 90558  ** Synopsis: r[P1@P3] <-> r[P2@P3]
 90559  **
 90560  ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
 90561  ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
 90562  ** the comparison for use by the next OP_Jump instruct.
 90563  **
 90564  ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
 90565  ** determined by the most recent OP_Permutation operator.  If the
 90566  ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
 90567  ** order.
 90568  **
 90569  ** P4 is a KeyInfo structure that defines collating sequences and sort
 90570  ** orders for the comparison.  The permutation applies to registers
 90571  ** only.  The KeyInfo elements are used sequentially.
 90572  **
 90573  ** The comparison is a sort comparison, so NULLs compare equal,
 90574  ** NULLs are less than numbers, numbers are less than strings,
 90575  ** and strings are less than blobs.
 90576  */
 90577  case OP_Compare: {
 90578    int n;
 90579    int i;
 90580    int p1;
 90581    int p2;
 90582    const KeyInfo *pKeyInfo;
 90583    int idx;
 90584    CollSeq *pColl;    /* Collating sequence to use on this term */
 90585    int bRev;          /* True for DESCENDING sort order */
 90586    int *aPermute;     /* The permutation */
 90587  
 90588    if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
 90589      aPermute = 0;
 90590    }else{
 90591      assert( pOp>aOp );
 90592      assert( pOp[-1].opcode==OP_Permutation );
 90593      assert( pOp[-1].p4type==P4_INTARRAY );
 90594      aPermute = pOp[-1].p4.ai + 1;
 90595      assert( aPermute!=0 );
 90596    }
 90597    n = pOp->p3;
 90598    pKeyInfo = pOp->p4.pKeyInfo;
 90599    assert( n>0 );
 90600    assert( pKeyInfo!=0 );
 90601    p1 = pOp->p1;
 90602    p2 = pOp->p2;
 90603  #ifdef SQLITE_DEBUG
 90604    if( aPermute ){
 90605      int k, mx = 0;
 90606      for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
 90607      assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
 90608      assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
 90609    }else{
 90610      assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
 90611      assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
 90612    }
 90613  #endif /* SQLITE_DEBUG */
 90614    for(i=0; i<n; i++){
 90615      idx = aPermute ? aPermute[i] : i;
 90616      assert( memIsValid(&aMem[p1+idx]) );
 90617      assert( memIsValid(&aMem[p2+idx]) );
 90618      REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
 90619      REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
 90620      assert( i<pKeyInfo->nKeyField );
 90621      pColl = pKeyInfo->aColl[i];
 90622      bRev = pKeyInfo->aSortOrder[i];
 90623      iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
 90624      if( iCompare ){
 90625        if( bRev ) iCompare = -iCompare;
 90626        break;
 90627      }
 90628    }
 90629    break;
 90630  }
 90631  
 90632  /* Opcode: Jump P1 P2 P3 * *
 90633  **
 90634  ** Jump to the instruction at address P1, P2, or P3 depending on whether
 90635  ** in the most recent OP_Compare instruction the P1 vector was less than
 90636  ** equal to, or greater than the P2 vector, respectively.
 90637  */
 90638  case OP_Jump: {             /* jump */
 90639    if( iCompare<0 ){
 90640      VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
 90641    }else if( iCompare==0 ){
 90642      VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
 90643    }else{
 90644      VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
 90645    }
 90646    break;
 90647  }
 90648  
 90649  /* Opcode: And P1 P2 P3 * *
 90650  ** Synopsis: r[P3]=(r[P1] && r[P2])
 90651  **
 90652  ** Take the logical AND of the values in registers P1 and P2 and
 90653  ** write the result into register P3.
 90654  **
 90655  ** If either P1 or P2 is 0 (false) then the result is 0 even if
 90656  ** the other input is NULL.  A NULL and true or two NULLs give
 90657  ** a NULL output.
 90658  */
 90659  /* Opcode: Or P1 P2 P3 * *
 90660  ** Synopsis: r[P3]=(r[P1] || r[P2])
 90661  **
 90662  ** Take the logical OR of the values in register P1 and P2 and
 90663  ** store the answer in register P3.
 90664  **
 90665  ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
 90666  ** even if the other input is NULL.  A NULL and false or two NULLs
 90667  ** give a NULL output.
 90668  */
 90669  case OP_And:              /* same as TK_AND, in1, in2, out3 */
 90670  case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
 90671    int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 90672    int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
 90673  
 90674    v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
 90675    v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
 90676    if( pOp->opcode==OP_And ){
 90677      static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
 90678      v1 = and_logic[v1*3+v2];
 90679    }else{
 90680      static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
 90681      v1 = or_logic[v1*3+v2];
 90682    }
 90683    pOut = &aMem[pOp->p3];
 90684    if( v1==2 ){
 90685      MemSetTypeFlag(pOut, MEM_Null);
 90686    }else{
 90687      pOut->u.i = v1;
 90688      MemSetTypeFlag(pOut, MEM_Int);
 90689    }
 90690    break;
 90691  }
 90692  
 90693  /* Opcode: IsTrue P1 P2 P3 P4 *
 90694  ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
 90695  **
 90696  ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
 90697  ** IS NOT FALSE operators.
 90698  **
 90699  ** Interpret the value in register P1 as a boolean value.  Store that
 90700  ** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is 
 90701  ** NULL, then the P3 is stored in register P2.  Invert the answer if P4
 90702  ** is 1.
 90703  **
 90704  ** The logic is summarized like this:
 90705  **
 90706  ** <ul> 
 90707  ** <li> If P3==0 and P4==0  then  r[P2] := r[P1] IS TRUE
 90708  ** <li> If P3==1 and P4==1  then  r[P2] := r[P1] IS FALSE
 90709  ** <li> If P3==0 and P4==1  then  r[P2] := r[P1] IS NOT TRUE
 90710  ** <li> If P3==1 and P4==0  then  r[P2] := r[P1] IS NOT FALSE
 90711  ** </ul>
 90712  */
 90713  case OP_IsTrue: {               /* in1, out2 */
 90714    assert( pOp->p4type==P4_INT32 );
 90715    assert( pOp->p4.i==0 || pOp->p4.i==1 );
 90716    assert( pOp->p3==0 || pOp->p3==1 );
 90717    sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
 90718        sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
 90719    break;
 90720  }
 90721  
 90722  /* Opcode: Not P1 P2 * * *
 90723  ** Synopsis: r[P2]= !r[P1]
 90724  **
 90725  ** Interpret the value in register P1 as a boolean value.  Store the
 90726  ** boolean complement in register P2.  If the value in register P1 is 
 90727  ** NULL, then a NULL is stored in P2.
 90728  */
 90729  case OP_Not: {                /* same as TK_NOT, in1, out2 */
 90730    pIn1 = &aMem[pOp->p1];
 90731    pOut = &aMem[pOp->p2];
 90732    if( (pIn1->flags & MEM_Null)==0 ){
 90733      sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
 90734    }else{
 90735      sqlite3VdbeMemSetNull(pOut);
 90736    }
 90737    break;
 90738  }
 90739  
 90740  /* Opcode: BitNot P1 P2 * * *
 90741  ** Synopsis: r[P2]= ~r[P1]
 90742  **
 90743  ** Interpret the content of register P1 as an integer.  Store the
 90744  ** ones-complement of the P1 value into register P2.  If P1 holds
 90745  ** a NULL then store a NULL in P2.
 90746  */
 90747  case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
 90748    pIn1 = &aMem[pOp->p1];
 90749    pOut = &aMem[pOp->p2];
 90750    sqlite3VdbeMemSetNull(pOut);
 90751    if( (pIn1->flags & MEM_Null)==0 ){
 90752      pOut->flags = MEM_Int;
 90753      pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
 90754    }
 90755    break;
 90756  }
 90757  
 90758  /* Opcode: Once P1 P2 * * *
 90759  **
 90760  ** Fall through to the next instruction the first time this opcode is
 90761  ** encountered on each invocation of the byte-code program.  Jump to P2
 90762  ** on the second and all subsequent encounters during the same invocation.
 90763  **
 90764  ** Top-level programs determine first invocation by comparing the P1
 90765  ** operand against the P1 operand on the OP_Init opcode at the beginning
 90766  ** of the program.  If the P1 values differ, then fall through and make
 90767  ** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
 90768  ** the same then take the jump.
 90769  **
 90770  ** For subprograms, there is a bitmask in the VdbeFrame that determines
 90771  ** whether or not the jump should be taken.  The bitmask is necessary
 90772  ** because the self-altering code trick does not work for recursive
 90773  ** triggers.
 90774  */
 90775  case OP_Once: {             /* jump */
 90776    u32 iAddr;                /* Address of this instruction */
 90777    assert( p->aOp[0].opcode==OP_Init );
 90778    if( p->pFrame ){
 90779      iAddr = (int)(pOp - p->aOp);
 90780      if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
 90781        VdbeBranchTaken(1, 2);
 90782        goto jump_to_p2;
 90783      }
 90784      p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
 90785    }else{
 90786      if( p->aOp[0].p1==pOp->p1 ){
 90787        VdbeBranchTaken(1, 2);
 90788        goto jump_to_p2;
 90789      }
 90790    }
 90791    VdbeBranchTaken(0, 2);
 90792    pOp->p1 = p->aOp[0].p1;
 90793    break;
 90794  }
 90795  
 90796  /* Opcode: If P1 P2 P3 * *
 90797  **
 90798  ** Jump to P2 if the value in register P1 is true.  The value
 90799  ** is considered true if it is numeric and non-zero.  If the value
 90800  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
 90801  */
 90802  case OP_If:  {               /* jump, in1 */
 90803    int c;
 90804    c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
 90805    VdbeBranchTaken(c!=0, 2);
 90806    if( c ) goto jump_to_p2;
 90807    break;
 90808  }
 90809  
 90810  /* Opcode: IfNot P1 P2 P3 * *
 90811  **
 90812  ** Jump to P2 if the value in register P1 is False.  The value
 90813  ** is considered false if it has a numeric value of zero.  If the value
 90814  ** in P1 is NULL then take the jump if and only if P3 is non-zero.
 90815  */
 90816  case OP_IfNot: {            /* jump, in1 */
 90817    int c;
 90818    c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
 90819    VdbeBranchTaken(c!=0, 2);
 90820    if( c ) goto jump_to_p2;
 90821    break;
 90822  }
 90823  
 90824  /* Opcode: IsNull P1 P2 * * *
 90825  ** Synopsis: if r[P1]==NULL goto P2
 90826  **
 90827  ** Jump to P2 if the value in register P1 is NULL.
 90828  */
 90829  case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
 90830    pIn1 = &aMem[pOp->p1];
 90831    VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
 90832    if( (pIn1->flags & MEM_Null)!=0 ){
 90833      goto jump_to_p2;
 90834    }
 90835    break;
 90836  }
 90837  
 90838  /* Opcode: NotNull P1 P2 * * *
 90839  ** Synopsis: if r[P1]!=NULL goto P2
 90840  **
 90841  ** Jump to P2 if the value in register P1 is not NULL.  
 90842  */
 90843  case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
 90844    pIn1 = &aMem[pOp->p1];
 90845    VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
 90846    if( (pIn1->flags & MEM_Null)==0 ){
 90847      goto jump_to_p2;
 90848    }
 90849    break;
 90850  }
 90851  
 90852  /* Opcode: IfNullRow P1 P2 P3 * *
 90853  ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
 90854  **
 90855  ** Check the cursor P1 to see if it is currently pointing at a NULL row.
 90856  ** If it is, then set register P3 to NULL and jump immediately to P2.
 90857  ** If P1 is not on a NULL row, then fall through without making any
 90858  ** changes.
 90859  */
 90860  case OP_IfNullRow: {         /* jump */
 90861    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 90862    assert( p->apCsr[pOp->p1]!=0 );
 90863    if( p->apCsr[pOp->p1]->nullRow ){
 90864      sqlite3VdbeMemSetNull(aMem + pOp->p3);
 90865      goto jump_to_p2;
 90866    }
 90867    break;
 90868  }
 90869  
 90870  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
 90871  /* Opcode: Offset P1 P2 P3 * *
 90872  ** Synopsis: r[P3] = sqlite_offset(P1)
 90873  **
 90874  ** Store in register r[P3] the byte offset into the database file that is the
 90875  ** start of the payload for the record at which that cursor P1 is currently
 90876  ** pointing.
 90877  **
 90878  ** P2 is the column number for the argument to the sqlite_offset() function.
 90879  ** This opcode does not use P2 itself, but the P2 value is used by the
 90880  ** code generator.  The P1, P2, and P3 operands to this opcode are the
 90881  ** same as for OP_Column.
 90882  **
 90883  ** This opcode is only available if SQLite is compiled with the
 90884  ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
 90885  */
 90886  case OP_Offset: {          /* out3 */
 90887    VdbeCursor *pC;    /* The VDBE cursor */
 90888    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 90889    pC = p->apCsr[pOp->p1];
 90890    pOut = &p->aMem[pOp->p3];
 90891    if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
 90892      sqlite3VdbeMemSetNull(pOut);
 90893    }else{
 90894      sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
 90895    }
 90896    break;
 90897  }
 90898  #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
 90899  
 90900  /* Opcode: Column P1 P2 P3 P4 P5
 90901  ** Synopsis: r[P3]=PX
 90902  **
 90903  ** Interpret the data that cursor P1 points to as a structure built using
 90904  ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
 90905  ** information about the format of the data.)  Extract the P2-th column
 90906  ** from this record.  If there are less that (P2+1) 
 90907  ** values in the record, extract a NULL.
 90908  **
 90909  ** The value extracted is stored in register P3.
 90910  **
 90911  ** If the record contains fewer than P2 fields, then extract a NULL.  Or,
 90912  ** if the P4 argument is a P4_MEM use the value of the P4 argument as
 90913  ** the result.
 90914  **
 90915  ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
 90916  ** then the cache of the cursor is reset prior to extracting the column.
 90917  ** The first OP_Column against a pseudo-table after the value of the content
 90918  ** register has changed should have this bit set.
 90919  **
 90920  ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
 90921  ** the result is guaranteed to only be used as the argument of a length()
 90922  ** or typeof() function, respectively.  The loading of large blobs can be
 90923  ** skipped for length() and all content loading can be skipped for typeof().
 90924  */
 90925  case OP_Column: {
 90926    int p2;            /* column number to retrieve */
 90927    VdbeCursor *pC;    /* The VDBE cursor */
 90928    BtCursor *pCrsr;   /* The BTree cursor */
 90929    u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
 90930    int len;           /* The length of the serialized data for the column */
 90931    int i;             /* Loop counter */
 90932    Mem *pDest;        /* Where to write the extracted value */
 90933    Mem sMem;          /* For storing the record being decoded */
 90934    const u8 *zData;   /* Part of the record being decoded */
 90935    const u8 *zHdr;    /* Next unparsed byte of the header */
 90936    const u8 *zEndHdr; /* Pointer to first byte after the header */
 90937    u64 offset64;      /* 64-bit offset */
 90938    u32 t;             /* A type code from the record header */
 90939    Mem *pReg;         /* PseudoTable input register */
 90940  
 90941    pC = p->apCsr[pOp->p1];
 90942    p2 = pOp->p2;
 90943  
 90944    /* If the cursor cache is stale (meaning it is not currently point at
 90945    ** the correct row) then bring it up-to-date by doing the necessary 
 90946    ** B-Tree seek. */
 90947    rc = sqlite3VdbeCursorMoveto(&pC, &p2);
 90948    if( rc ) goto abort_due_to_error;
 90949  
 90950    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 90951    pDest = &aMem[pOp->p3];
 90952    memAboutToChange(p, pDest);
 90953    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 90954    assert( pC!=0 );
 90955    assert( p2<pC->nField );
 90956    aOffset = pC->aOffset;
 90957    assert( pC->eCurType!=CURTYPE_VTAB );
 90958    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
 90959    assert( pC->eCurType!=CURTYPE_SORTER );
 90960  
 90961    if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
 90962      if( pC->nullRow ){
 90963        if( pC->eCurType==CURTYPE_PSEUDO ){
 90964          /* For the special case of as pseudo-cursor, the seekResult field
 90965          ** identifies the register that holds the record */
 90966          assert( pC->seekResult>0 );
 90967          pReg = &aMem[pC->seekResult];
 90968          assert( pReg->flags & MEM_Blob );
 90969          assert( memIsValid(pReg) );
 90970          pC->payloadSize = pC->szRow = pReg->n;
 90971          pC->aRow = (u8*)pReg->z;
 90972        }else{
 90973          sqlite3VdbeMemSetNull(pDest);
 90974          goto op_column_out;
 90975        }
 90976      }else{
 90977        pCrsr = pC->uc.pCursor;
 90978        assert( pC->eCurType==CURTYPE_BTREE );
 90979        assert( pCrsr );
 90980        assert( sqlite3BtreeCursorIsValid(pCrsr) );
 90981        pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
 90982        pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
 90983        assert( pC->szRow<=pC->payloadSize );
 90984        assert( pC->szRow<=65536 );  /* Maximum page size is 64KiB */
 90985        if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 90986          goto too_big;
 90987        }
 90988      }
 90989      pC->cacheStatus = p->cacheCtr;
 90990      pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
 90991      pC->nHdrParsed = 0;
 90992  
 90993  
 90994      if( pC->szRow<aOffset[0] ){      /*OPTIMIZATION-IF-FALSE*/
 90995        /* pC->aRow does not have to hold the entire row, but it does at least
 90996        ** need to cover the header of the record.  If pC->aRow does not contain
 90997        ** the complete header, then set it to zero, forcing the header to be
 90998        ** dynamically allocated. */
 90999        pC->aRow = 0;
 91000        pC->szRow = 0;
 91001  
 91002        /* Make sure a corrupt database has not given us an oversize header.
 91003        ** Do this now to avoid an oversize memory allocation.
 91004        **
 91005        ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
 91006        ** types use so much data space that there can only be 4096 and 32 of
 91007        ** them, respectively.  So the maximum header length results from a
 91008        ** 3-byte type for each of the maximum of 32768 columns plus three
 91009        ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
 91010        */
 91011        if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
 91012          goto op_column_corrupt;
 91013        }
 91014      }else{
 91015        /* This is an optimization.  By skipping over the first few tests
 91016        ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
 91017        ** measurable performance gain.
 91018        **
 91019        ** This branch is taken even if aOffset[0]==0.  Such a record is never
 91020        ** generated by SQLite, and could be considered corruption, but we
 91021        ** accept it for historical reasons.  When aOffset[0]==0, the code this
 91022        ** branch jumps to reads past the end of the record, but never more
 91023        ** than a few bytes.  Even if the record occurs at the end of the page
 91024        ** content area, the "page header" comes after the page content and so
 91025        ** this overread is harmless.  Similar overreads can occur for a corrupt
 91026        ** database file.
 91027        */
 91028        zData = pC->aRow;
 91029        assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
 91030        testcase( aOffset[0]==0 );
 91031        goto op_column_read_header;
 91032      }
 91033    }
 91034  
 91035    /* Make sure at least the first p2+1 entries of the header have been
 91036    ** parsed and valid information is in aOffset[] and pC->aType[].
 91037    */
 91038    if( pC->nHdrParsed<=p2 ){
 91039      /* If there is more header available for parsing in the record, try
 91040      ** to extract additional fields up through the p2+1-th field 
 91041      */
 91042      if( pC->iHdrOffset<aOffset[0] ){
 91043        /* Make sure zData points to enough of the record to cover the header. */
 91044        if( pC->aRow==0 ){
 91045          memset(&sMem, 0, sizeof(sMem));
 91046          rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
 91047          if( rc!=SQLITE_OK ) goto abort_due_to_error;
 91048          zData = (u8*)sMem.z;
 91049        }else{
 91050          zData = pC->aRow;
 91051        }
 91052    
 91053        /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
 91054      op_column_read_header:
 91055        i = pC->nHdrParsed;
 91056        offset64 = aOffset[i];
 91057        zHdr = zData + pC->iHdrOffset;
 91058        zEndHdr = zData + aOffset[0];
 91059        testcase( zHdr>=zEndHdr );
 91060        do{
 91061          if( (t = zHdr[0])<0x80 ){
 91062            zHdr++;
 91063            offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
 91064          }else{
 91065            zHdr += sqlite3GetVarint32(zHdr, &t);
 91066            offset64 += sqlite3VdbeSerialTypeLen(t);
 91067          }
 91068          pC->aType[i++] = t;
 91069          aOffset[i] = (u32)(offset64 & 0xffffffff);
 91070        }while( i<=p2 && zHdr<zEndHdr );
 91071  
 91072        /* The record is corrupt if any of the following are true:
 91073        ** (1) the bytes of the header extend past the declared header size
 91074        ** (2) the entire header was used but not all data was used
 91075        ** (3) the end of the data extends beyond the end of the record.
 91076        */
 91077        if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
 91078         || (offset64 > pC->payloadSize)
 91079        ){
 91080          if( aOffset[0]==0 ){
 91081            i = 0;
 91082            zHdr = zEndHdr;
 91083          }else{
 91084            if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
 91085            goto op_column_corrupt;
 91086          }
 91087        }
 91088  
 91089        pC->nHdrParsed = i;
 91090        pC->iHdrOffset = (u32)(zHdr - zData);
 91091        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
 91092      }else{
 91093        t = 0;
 91094      }
 91095  
 91096      /* If after trying to extract new entries from the header, nHdrParsed is
 91097      ** still not up to p2, that means that the record has fewer than p2
 91098      ** columns.  So the result will be either the default value or a NULL.
 91099      */
 91100      if( pC->nHdrParsed<=p2 ){
 91101        if( pOp->p4type==P4_MEM ){
 91102          sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
 91103        }else{
 91104          sqlite3VdbeMemSetNull(pDest);
 91105        }
 91106        goto op_column_out;
 91107      }
 91108    }else{
 91109      t = pC->aType[p2];
 91110    }
 91111  
 91112    /* Extract the content for the p2+1-th column.  Control can only
 91113    ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
 91114    ** all valid.
 91115    */
 91116    assert( p2<pC->nHdrParsed );
 91117    assert( rc==SQLITE_OK );
 91118    assert( sqlite3VdbeCheckMemInvariants(pDest) );
 91119    if( VdbeMemDynamic(pDest) ){
 91120      sqlite3VdbeMemSetNull(pDest);
 91121    }
 91122    assert( t==pC->aType[p2] );
 91123    if( pC->szRow>=aOffset[p2+1] ){
 91124      /* This is the common case where the desired content fits on the original
 91125      ** page - where the content is not on an overflow page */
 91126      zData = pC->aRow + aOffset[p2];
 91127      if( t<12 ){
 91128        sqlite3VdbeSerialGet(zData, t, pDest);
 91129      }else{
 91130        /* If the column value is a string, we need a persistent value, not
 91131        ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
 91132        ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
 91133        */
 91134        static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
 91135        pDest->n = len = (t-12)/2;
 91136        pDest->enc = encoding;
 91137        if( pDest->szMalloc < len+2 ){
 91138          pDest->flags = MEM_Null;
 91139          if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
 91140        }else{
 91141          pDest->z = pDest->zMalloc;
 91142        }
 91143        memcpy(pDest->z, zData, len);
 91144        pDest->z[len] = 0;
 91145        pDest->z[len+1] = 0;
 91146        pDest->flags = aFlag[t&1];
 91147      }
 91148    }else{
 91149      pDest->enc = encoding;
 91150      /* This branch happens only when content is on overflow pages */
 91151      if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
 91152            && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
 91153       || (len = sqlite3VdbeSerialTypeLen(t))==0
 91154      ){
 91155        /* Content is irrelevant for
 91156        **    1. the typeof() function,
 91157        **    2. the length(X) function if X is a blob, and
 91158        **    3. if the content length is zero.
 91159        ** So we might as well use bogus content rather than reading
 91160        ** content from disk. 
 91161        **
 91162        ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
 91163        ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
 91164        ** read up to 16. So 16 bytes of bogus content is supplied.
 91165        */
 91166        static u8 aZero[16];  /* This is the bogus content */
 91167        sqlite3VdbeSerialGet(aZero, t, pDest);
 91168      }else{
 91169        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
 91170        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 91171        sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
 91172        pDest->flags &= ~MEM_Ephem;
 91173      }
 91174    }
 91175  
 91176  op_column_out:
 91177    UPDATE_MAX_BLOBSIZE(pDest);
 91178    REGISTER_TRACE(pOp->p3, pDest);
 91179    break;
 91180  
 91181  op_column_corrupt:
 91182    if( aOp[0].p3>0 ){
 91183      pOp = &aOp[aOp[0].p3-1];
 91184      break;
 91185    }else{
 91186      rc = SQLITE_CORRUPT_BKPT;
 91187      goto abort_due_to_error;
 91188    }
 91189  }
 91190  
 91191  /* Opcode: Affinity P1 P2 * P4 *
 91192  ** Synopsis: affinity(r[P1@P2])
 91193  **
 91194  ** Apply affinities to a range of P2 registers starting with P1.
 91195  **
 91196  ** P4 is a string that is P2 characters long. The N-th character of the
 91197  ** string indicates the column affinity that should be used for the N-th
 91198  ** memory cell in the range.
 91199  */
 91200  case OP_Affinity: {
 91201    const char *zAffinity;   /* The affinity to be applied */
 91202  
 91203    zAffinity = pOp->p4.z;
 91204    assert( zAffinity!=0 );
 91205    assert( pOp->p2>0 );
 91206    assert( zAffinity[pOp->p2]==0 );
 91207    pIn1 = &aMem[pOp->p1];
 91208    do{
 91209      assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
 91210      assert( memIsValid(pIn1) );
 91211      applyAffinity(pIn1, *(zAffinity++), encoding);
 91212      pIn1++;
 91213    }while( zAffinity[0] );
 91214    break;
 91215  }
 91216  
 91217  /* Opcode: MakeRecord P1 P2 P3 P4 *
 91218  ** Synopsis: r[P3]=mkrec(r[P1@P2])
 91219  **
 91220  ** Convert P2 registers beginning with P1 into the [record format]
 91221  ** use as a data record in a database table or as a key
 91222  ** in an index.  The OP_Column opcode can decode the record later.
 91223  **
 91224  ** P4 may be a string that is P2 characters long.  The N-th character of the
 91225  ** string indicates the column affinity that should be used for the N-th
 91226  ** field of the index key.
 91227  **
 91228  ** The mapping from character to affinity is given by the SQLITE_AFF_
 91229  ** macros defined in sqliteInt.h.
 91230  **
 91231  ** If P4 is NULL then all index fields have the affinity BLOB.
 91232  */
 91233  case OP_MakeRecord: {
 91234    u8 *zNewRecord;        /* A buffer to hold the data for the new record */
 91235    Mem *pRec;             /* The new record */
 91236    u64 nData;             /* Number of bytes of data space */
 91237    int nHdr;              /* Number of bytes of header space */
 91238    i64 nByte;             /* Data space required for this record */
 91239    i64 nZero;             /* Number of zero bytes at the end of the record */
 91240    int nVarint;           /* Number of bytes in a varint */
 91241    u32 serial_type;       /* Type field */
 91242    Mem *pData0;           /* First field to be combined into the record */
 91243    Mem *pLast;            /* Last field of the record */
 91244    int nField;            /* Number of fields in the record */
 91245    char *zAffinity;       /* The affinity string for the record */
 91246    int file_format;       /* File format to use for encoding */
 91247    int i;                 /* Space used in zNewRecord[] header */
 91248    int j;                 /* Space used in zNewRecord[] content */
 91249    u32 len;               /* Length of a field */
 91250  
 91251    /* Assuming the record contains N fields, the record format looks
 91252    ** like this:
 91253    **
 91254    ** ------------------------------------------------------------------------
 91255    ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
 91256    ** ------------------------------------------------------------------------
 91257    **
 91258    ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
 91259    ** and so forth.
 91260    **
 91261    ** Each type field is a varint representing the serial type of the 
 91262    ** corresponding data element (see sqlite3VdbeSerialType()). The
 91263    ** hdr-size field is also a varint which is the offset from the beginning
 91264    ** of the record to data0.
 91265    */
 91266    nData = 0;         /* Number of bytes of data space */
 91267    nHdr = 0;          /* Number of bytes of header space */
 91268    nZero = 0;         /* Number of zero bytes at the end of the record */
 91269    nField = pOp->p1;
 91270    zAffinity = pOp->p4.z;
 91271    assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
 91272    pData0 = &aMem[nField];
 91273    nField = pOp->p2;
 91274    pLast = &pData0[nField-1];
 91275    file_format = p->minWriteFileFormat;
 91276  
 91277    /* Identify the output register */
 91278    assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
 91279    pOut = &aMem[pOp->p3];
 91280    memAboutToChange(p, pOut);
 91281  
 91282    /* Apply the requested affinity to all inputs
 91283    */
 91284    assert( pData0<=pLast );
 91285    if( zAffinity ){
 91286      pRec = pData0;
 91287      do{
 91288        applyAffinity(pRec++, *(zAffinity++), encoding);
 91289        assert( zAffinity[0]==0 || pRec<=pLast );
 91290      }while( zAffinity[0] );
 91291    }
 91292  
 91293  #ifdef SQLITE_ENABLE_NULL_TRIM
 91294    /* NULLs can be safely trimmed from the end of the record, as long as
 91295    ** as the schema format is 2 or more and none of the omitted columns
 91296    ** have a non-NULL default value.  Also, the record must be left with
 91297    ** at least one field.  If P5>0 then it will be one more than the
 91298    ** index of the right-most column with a non-NULL default value */
 91299    if( pOp->p5 ){
 91300      while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
 91301        pLast--;
 91302        nField--;
 91303      }
 91304    }
 91305  #endif
 91306  
 91307    /* Loop through the elements that will make up the record to figure
 91308    ** out how much space is required for the new record.
 91309    */
 91310    pRec = pLast;
 91311    do{
 91312      assert( memIsValid(pRec) );
 91313      serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
 91314      if( pRec->flags & MEM_Zero ){
 91315        if( serial_type==0 ){
 91316          /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
 91317          ** table methods that never invoke sqlite3_result_xxxxx() while
 91318          ** computing an unchanging column value in an UPDATE statement.
 91319          ** Give such values a special internal-use-only serial-type of 10
 91320          ** so that they can be passed through to xUpdate and have
 91321          ** a true sqlite3_value_nochange(). */
 91322          assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
 91323          serial_type = 10;
 91324        }else if( nData ){
 91325          if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
 91326        }else{
 91327          nZero += pRec->u.nZero;
 91328          len -= pRec->u.nZero;
 91329        }
 91330      }
 91331      nData += len;
 91332      testcase( serial_type==127 );
 91333      testcase( serial_type==128 );
 91334      nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
 91335      pRec->uTemp = serial_type;
 91336      if( pRec==pData0 ) break;
 91337      pRec--;
 91338    }while(1);
 91339  
 91340    /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
 91341    ** which determines the total number of bytes in the header. The varint
 91342    ** value is the size of the header in bytes including the size varint
 91343    ** itself. */
 91344    testcase( nHdr==126 );
 91345    testcase( nHdr==127 );
 91346    if( nHdr<=126 ){
 91347      /* The common case */
 91348      nHdr += 1;
 91349    }else{
 91350      /* Rare case of a really large header */
 91351      nVarint = sqlite3VarintLen(nHdr);
 91352      nHdr += nVarint;
 91353      if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
 91354    }
 91355    nByte = nHdr+nData;
 91356  
 91357    /* Make sure the output register has a buffer large enough to store 
 91358    ** the new record. The output register (pOp->p3) is not allowed to
 91359    ** be one of the input registers (because the following call to
 91360    ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
 91361    */
 91362    if( nByte+nZero<=pOut->szMalloc ){
 91363      /* The output register is already large enough to hold the record.
 91364      ** No error checks or buffer enlargement is required */
 91365      pOut->z = pOut->zMalloc;
 91366    }else{
 91367      /* Need to make sure that the output is not too big and then enlarge
 91368      ** the output register to hold the full result */
 91369      if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
 91370        goto too_big;
 91371      }
 91372      if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
 91373        goto no_mem;
 91374      }
 91375    }
 91376    zNewRecord = (u8 *)pOut->z;
 91377  
 91378    /* Write the record */
 91379    i = putVarint32(zNewRecord, nHdr);
 91380    j = nHdr;
 91381    assert( pData0<=pLast );
 91382    pRec = pData0;
 91383    do{
 91384      serial_type = pRec->uTemp;
 91385      /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
 91386      ** additional varints, one per column. */
 91387      i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
 91388      /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
 91389      ** immediately follow the header. */
 91390      j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
 91391    }while( (++pRec)<=pLast );
 91392    assert( i==nHdr );
 91393    assert( j==nByte );
 91394  
 91395    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 91396    pOut->n = (int)nByte;
 91397    pOut->flags = MEM_Blob;
 91398    if( nZero ){
 91399      pOut->u.nZero = nZero;
 91400      pOut->flags |= MEM_Zero;
 91401    }
 91402    REGISTER_TRACE(pOp->p3, pOut);
 91403    UPDATE_MAX_BLOBSIZE(pOut);
 91404    break;
 91405  }
 91406  
 91407  /* Opcode: Count P1 P2 * * *
 91408  ** Synopsis: r[P2]=count()
 91409  **
 91410  ** Store the number of entries (an integer value) in the table or index 
 91411  ** opened by cursor P1 in register P2
 91412  */
 91413  #ifndef SQLITE_OMIT_BTREECOUNT
 91414  case OP_Count: {         /* out2 */
 91415    i64 nEntry;
 91416    BtCursor *pCrsr;
 91417  
 91418    assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
 91419    pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
 91420    assert( pCrsr );
 91421    nEntry = 0;  /* Not needed.  Only used to silence a warning. */
 91422    rc = sqlite3BtreeCount(pCrsr, &nEntry);
 91423    if( rc ) goto abort_due_to_error;
 91424    pOut = out2Prerelease(p, pOp);
 91425    pOut->u.i = nEntry;
 91426    break;
 91427  }
 91428  #endif
 91429  
 91430  /* Opcode: Savepoint P1 * * P4 *
 91431  **
 91432  ** Open, release or rollback the savepoint named by parameter P4, depending
 91433  ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
 91434  ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
 91435  */
 91436  case OP_Savepoint: {
 91437    int p1;                         /* Value of P1 operand */
 91438    char *zName;                    /* Name of savepoint */
 91439    int nName;
 91440    Savepoint *pNew;
 91441    Savepoint *pSavepoint;
 91442    Savepoint *pTmp;
 91443    int iSavepoint;
 91444    int ii;
 91445  
 91446    p1 = pOp->p1;
 91447    zName = pOp->p4.z;
 91448  
 91449    /* Assert that the p1 parameter is valid. Also that if there is no open
 91450    ** transaction, then there cannot be any savepoints. 
 91451    */
 91452    assert( db->pSavepoint==0 || db->autoCommit==0 );
 91453    assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
 91454    assert( db->pSavepoint || db->isTransactionSavepoint==0 );
 91455    assert( checkSavepointCount(db) );
 91456    assert( p->bIsReader );
 91457  
 91458    if( p1==SAVEPOINT_BEGIN ){
 91459      if( db->nVdbeWrite>0 ){
 91460        /* A new savepoint cannot be created if there are active write 
 91461        ** statements (i.e. open read/write incremental blob handles).
 91462        */
 91463        sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
 91464        rc = SQLITE_BUSY;
 91465      }else{
 91466        nName = sqlite3Strlen30(zName);
 91467  
 91468  #ifndef SQLITE_OMIT_VIRTUALTABLE
 91469        /* This call is Ok even if this savepoint is actually a transaction
 91470        ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
 91471        ** If this is a transaction savepoint being opened, it is guaranteed
 91472        ** that the db->aVTrans[] array is empty.  */
 91473        assert( db->autoCommit==0 || db->nVTrans==0 );
 91474        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
 91475                                  db->nStatement+db->nSavepoint);
 91476        if( rc!=SQLITE_OK ) goto abort_due_to_error;
 91477  #endif
 91478  
 91479        /* Create a new savepoint structure. */
 91480        pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
 91481        if( pNew ){
 91482          pNew->zName = (char *)&pNew[1];
 91483          memcpy(pNew->zName, zName, nName+1);
 91484      
 91485          /* If there is no open transaction, then mark this as a special
 91486          ** "transaction savepoint". */
 91487          if( db->autoCommit ){
 91488            db->autoCommit = 0;
 91489            db->isTransactionSavepoint = 1;
 91490          }else{
 91491            db->nSavepoint++;
 91492          }
 91493  
 91494          /* Link the new savepoint into the database handle's list. */
 91495          pNew->pNext = db->pSavepoint;
 91496          db->pSavepoint = pNew;
 91497          pNew->nDeferredCons = db->nDeferredCons;
 91498          pNew->nDeferredImmCons = db->nDeferredImmCons;
 91499        }
 91500      }
 91501    }else{
 91502      iSavepoint = 0;
 91503  
 91504      /* Find the named savepoint. If there is no such savepoint, then an
 91505      ** an error is returned to the user.  */
 91506      for(
 91507        pSavepoint = db->pSavepoint; 
 91508        pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
 91509        pSavepoint = pSavepoint->pNext
 91510      ){
 91511        iSavepoint++;
 91512      }
 91513      if( !pSavepoint ){
 91514        sqlite3VdbeError(p, "no such savepoint: %s", zName);
 91515        rc = SQLITE_ERROR;
 91516      }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
 91517        /* It is not possible to release (commit) a savepoint if there are 
 91518        ** active write statements.
 91519        */
 91520        sqlite3VdbeError(p, "cannot release savepoint - "
 91521                            "SQL statements in progress");
 91522        rc = SQLITE_BUSY;
 91523      }else{
 91524  
 91525        /* Determine whether or not this is a transaction savepoint. If so,
 91526        ** and this is a RELEASE command, then the current transaction 
 91527        ** is committed. 
 91528        */
 91529        int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
 91530        if( isTransaction && p1==SAVEPOINT_RELEASE ){
 91531          if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 91532            goto vdbe_return;
 91533          }
 91534          db->autoCommit = 1;
 91535          if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 91536            p->pc = (int)(pOp - aOp);
 91537            db->autoCommit = 0;
 91538            p->rc = rc = SQLITE_BUSY;
 91539            goto vdbe_return;
 91540          }
 91541          db->isTransactionSavepoint = 0;
 91542          rc = p->rc;
 91543        }else{
 91544          int isSchemaChange;
 91545          iSavepoint = db->nSavepoint - iSavepoint - 1;
 91546          if( p1==SAVEPOINT_ROLLBACK ){
 91547            isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
 91548            for(ii=0; ii<db->nDb; ii++){
 91549              rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
 91550                                         SQLITE_ABORT_ROLLBACK,
 91551                                         isSchemaChange==0);
 91552              if( rc!=SQLITE_OK ) goto abort_due_to_error;
 91553            }
 91554          }else{
 91555            isSchemaChange = 0;
 91556          }
 91557          for(ii=0; ii<db->nDb; ii++){
 91558            rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
 91559            if( rc!=SQLITE_OK ){
 91560              goto abort_due_to_error;
 91561            }
 91562          }
 91563          if( isSchemaChange ){
 91564            sqlite3ExpirePreparedStatements(db, 0);
 91565            sqlite3ResetAllSchemasOfConnection(db);
 91566            db->mDbFlags |= DBFLAG_SchemaChange;
 91567          }
 91568        }
 91569    
 91570        /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
 91571        ** savepoints nested inside of the savepoint being operated on. */
 91572        while( db->pSavepoint!=pSavepoint ){
 91573          pTmp = db->pSavepoint;
 91574          db->pSavepoint = pTmp->pNext;
 91575          sqlite3DbFree(db, pTmp);
 91576          db->nSavepoint--;
 91577        }
 91578  
 91579        /* If it is a RELEASE, then destroy the savepoint being operated on 
 91580        ** too. If it is a ROLLBACK TO, then set the number of deferred 
 91581        ** constraint violations present in the database to the value stored
 91582        ** when the savepoint was created.  */
 91583        if( p1==SAVEPOINT_RELEASE ){
 91584          assert( pSavepoint==db->pSavepoint );
 91585          db->pSavepoint = pSavepoint->pNext;
 91586          sqlite3DbFree(db, pSavepoint);
 91587          if( !isTransaction ){
 91588            db->nSavepoint--;
 91589          }
 91590        }else{
 91591          db->nDeferredCons = pSavepoint->nDeferredCons;
 91592          db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
 91593        }
 91594  
 91595        if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
 91596          rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
 91597          if( rc!=SQLITE_OK ) goto abort_due_to_error;
 91598        }
 91599      }
 91600    }
 91601    if( rc ) goto abort_due_to_error;
 91602  
 91603    break;
 91604  }
 91605  
 91606  /* Opcode: AutoCommit P1 P2 * * *
 91607  **
 91608  ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
 91609  ** back any currently active btree transactions. If there are any active
 91610  ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
 91611  ** there are active writing VMs or active VMs that use shared cache.
 91612  **
 91613  ** This instruction causes the VM to halt.
 91614  */
 91615  case OP_AutoCommit: {
 91616    int desiredAutoCommit;
 91617    int iRollback;
 91618  
 91619    desiredAutoCommit = pOp->p1;
 91620    iRollback = pOp->p2;
 91621    assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
 91622    assert( desiredAutoCommit==1 || iRollback==0 );
 91623    assert( db->nVdbeActive>0 );  /* At least this one VM is active */
 91624    assert( p->bIsReader );
 91625  
 91626    if( desiredAutoCommit!=db->autoCommit ){
 91627      if( iRollback ){
 91628        assert( desiredAutoCommit==1 );
 91629        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
 91630        db->autoCommit = 1;
 91631      }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
 91632        /* If this instruction implements a COMMIT and other VMs are writing
 91633        ** return an error indicating that the other VMs must complete first. 
 91634        */
 91635        sqlite3VdbeError(p, "cannot commit transaction - "
 91636                            "SQL statements in progress");
 91637        rc = SQLITE_BUSY;
 91638        goto abort_due_to_error;
 91639      }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
 91640        goto vdbe_return;
 91641      }else{
 91642        db->autoCommit = (u8)desiredAutoCommit;
 91643      }
 91644      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
 91645        p->pc = (int)(pOp - aOp);
 91646        db->autoCommit = (u8)(1-desiredAutoCommit);
 91647        p->rc = rc = SQLITE_BUSY;
 91648        goto vdbe_return;
 91649      }
 91650      assert( db->nStatement==0 );
 91651      sqlite3CloseSavepoints(db);
 91652      if( p->rc==SQLITE_OK ){
 91653        rc = SQLITE_DONE;
 91654      }else{
 91655        rc = SQLITE_ERROR;
 91656      }
 91657      goto vdbe_return;
 91658    }else{
 91659      sqlite3VdbeError(p,
 91660          (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
 91661          (iRollback)?"cannot rollback - no transaction is active":
 91662                     "cannot commit - no transaction is active"));
 91663           
 91664      rc = SQLITE_ERROR;
 91665      goto abort_due_to_error;
 91666    }
 91667    break;
 91668  }
 91669  
 91670  /* Opcode: Transaction P1 P2 P3 P4 P5
 91671  **
 91672  ** Begin a transaction on database P1 if a transaction is not already
 91673  ** active.
 91674  ** If P2 is non-zero, then a write-transaction is started, or if a 
 91675  ** read-transaction is already active, it is upgraded to a write-transaction.
 91676  ** If P2 is zero, then a read-transaction is started.
 91677  **
 91678  ** P1 is the index of the database file on which the transaction is
 91679  ** started.  Index 0 is the main database file and index 1 is the
 91680  ** file used for temporary tables.  Indices of 2 or more are used for
 91681  ** attached databases.
 91682  **
 91683  ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
 91684  ** true (this flag is set if the Vdbe may modify more than one row and may
 91685  ** throw an ABORT exception), a statement transaction may also be opened.
 91686  ** More specifically, a statement transaction is opened iff the database
 91687  ** connection is currently not in autocommit mode, or if there are other
 91688  ** active statements. A statement transaction allows the changes made by this
 91689  ** VDBE to be rolled back after an error without having to roll back the
 91690  ** entire transaction. If no error is encountered, the statement transaction
 91691  ** will automatically commit when the VDBE halts.
 91692  **
 91693  ** If P5!=0 then this opcode also checks the schema cookie against P3
 91694  ** and the schema generation counter against P4.
 91695  ** The cookie changes its value whenever the database schema changes.
 91696  ** This operation is used to detect when that the cookie has changed
 91697  ** and that the current process needs to reread the schema.  If the schema
 91698  ** cookie in P3 differs from the schema cookie in the database header or
 91699  ** if the schema generation counter in P4 differs from the current
 91700  ** generation counter, then an SQLITE_SCHEMA error is raised and execution
 91701  ** halts.  The sqlite3_step() wrapper function might then reprepare the
 91702  ** statement and rerun it from the beginning.
 91703  */
 91704  case OP_Transaction: {
 91705    Btree *pBt;
 91706    int iMeta = 0;
 91707  
 91708    assert( p->bIsReader );
 91709    assert( p->readOnly==0 || pOp->p2==0 );
 91710    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 91711    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 91712    if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
 91713      rc = SQLITE_READONLY;
 91714      goto abort_due_to_error;
 91715    }
 91716    pBt = db->aDb[pOp->p1].pBt;
 91717  
 91718    if( pBt ){
 91719      rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
 91720      testcase( rc==SQLITE_BUSY_SNAPSHOT );
 91721      testcase( rc==SQLITE_BUSY_RECOVERY );
 91722      if( rc!=SQLITE_OK ){
 91723        if( (rc&0xff)==SQLITE_BUSY ){
 91724          p->pc = (int)(pOp - aOp);
 91725          p->rc = rc;
 91726          goto vdbe_return;
 91727        }
 91728        goto abort_due_to_error;
 91729      }
 91730  
 91731      if( pOp->p2 && p->usesStmtJournal 
 91732       && (db->autoCommit==0 || db->nVdbeRead>1) 
 91733      ){
 91734        assert( sqlite3BtreeIsInTrans(pBt) );
 91735        if( p->iStatement==0 ){
 91736          assert( db->nStatement>=0 && db->nSavepoint>=0 );
 91737          db->nStatement++; 
 91738          p->iStatement = db->nSavepoint + db->nStatement;
 91739        }
 91740  
 91741        rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
 91742        if( rc==SQLITE_OK ){
 91743          rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
 91744        }
 91745  
 91746        /* Store the current value of the database handles deferred constraint
 91747        ** counter. If the statement transaction needs to be rolled back,
 91748        ** the value of this counter needs to be restored too.  */
 91749        p->nStmtDefCons = db->nDeferredCons;
 91750        p->nStmtDefImmCons = db->nDeferredImmCons;
 91751      }
 91752    }
 91753    assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
 91754    if( pOp->p5
 91755     && (iMeta!=pOp->p3
 91756        || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
 91757    ){
 91758      /*
 91759      ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
 91760      ** version is checked to ensure that the schema has not changed since the
 91761      ** SQL statement was prepared.
 91762      */
 91763      sqlite3DbFree(db, p->zErrMsg);
 91764      p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
 91765      /* If the schema-cookie from the database file matches the cookie 
 91766      ** stored with the in-memory representation of the schema, do
 91767      ** not reload the schema from the database file.
 91768      **
 91769      ** If virtual-tables are in use, this is not just an optimization.
 91770      ** Often, v-tables store their data in other SQLite tables, which
 91771      ** are queried from within xNext() and other v-table methods using
 91772      ** prepared queries. If such a query is out-of-date, we do not want to
 91773      ** discard the database schema, as the user code implementing the
 91774      ** v-table would have to be ready for the sqlite3_vtab structure itself
 91775      ** to be invalidated whenever sqlite3_step() is called from within 
 91776      ** a v-table method.
 91777      */
 91778      if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
 91779        sqlite3ResetOneSchema(db, pOp->p1);
 91780      }
 91781      p->expired = 1;
 91782      rc = SQLITE_SCHEMA;
 91783    }
 91784    if( rc ) goto abort_due_to_error;
 91785    break;
 91786  }
 91787  
 91788  /* Opcode: ReadCookie P1 P2 P3 * *
 91789  **
 91790  ** Read cookie number P3 from database P1 and write it into register P2.
 91791  ** P3==1 is the schema version.  P3==2 is the database format.
 91792  ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
 91793  ** the main database file and P1==1 is the database file used to store
 91794  ** temporary tables.
 91795  **
 91796  ** There must be a read-lock on the database (either a transaction
 91797  ** must be started or there must be an open cursor) before
 91798  ** executing this instruction.
 91799  */
 91800  case OP_ReadCookie: {               /* out2 */
 91801    int iMeta;
 91802    int iDb;
 91803    int iCookie;
 91804  
 91805    assert( p->bIsReader );
 91806    iDb = pOp->p1;
 91807    iCookie = pOp->p3;
 91808    assert( pOp->p3<SQLITE_N_BTREE_META );
 91809    assert( iDb>=0 && iDb<db->nDb );
 91810    assert( db->aDb[iDb].pBt!=0 );
 91811    assert( DbMaskTest(p->btreeMask, iDb) );
 91812  
 91813    sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
 91814    pOut = out2Prerelease(p, pOp);
 91815    pOut->u.i = iMeta;
 91816    break;
 91817  }
 91818  
 91819  /* Opcode: SetCookie P1 P2 P3 * *
 91820  **
 91821  ** Write the integer value P3 into cookie number P2 of database P1.
 91822  ** P2==1 is the schema version.  P2==2 is the database format.
 91823  ** P2==3 is the recommended pager cache 
 91824  ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
 91825  ** database file used to store temporary tables.
 91826  **
 91827  ** A transaction must be started before executing this opcode.
 91828  */
 91829  case OP_SetCookie: {
 91830    Db *pDb;
 91831  
 91832    sqlite3VdbeIncrWriteCounter(p, 0);
 91833    assert( pOp->p2<SQLITE_N_BTREE_META );
 91834    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 91835    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 91836    assert( p->readOnly==0 );
 91837    pDb = &db->aDb[pOp->p1];
 91838    assert( pDb->pBt!=0 );
 91839    assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
 91840    /* See note about index shifting on OP_ReadCookie */
 91841    rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
 91842    if( pOp->p2==BTREE_SCHEMA_VERSION ){
 91843      /* When the schema cookie changes, record the new cookie internally */
 91844      pDb->pSchema->schema_cookie = pOp->p3;
 91845      db->mDbFlags |= DBFLAG_SchemaChange;
 91846    }else if( pOp->p2==BTREE_FILE_FORMAT ){
 91847      /* Record changes in the file format */
 91848      pDb->pSchema->file_format = pOp->p3;
 91849    }
 91850    if( pOp->p1==1 ){
 91851      /* Invalidate all prepared statements whenever the TEMP database
 91852      ** schema is changed.  Ticket #1644 */
 91853      sqlite3ExpirePreparedStatements(db, 0);
 91854      p->expired = 0;
 91855    }
 91856    if( rc ) goto abort_due_to_error;
 91857    break;
 91858  }
 91859  
 91860  /* Opcode: OpenRead P1 P2 P3 P4 P5
 91861  ** Synopsis: root=P2 iDb=P3
 91862  **
 91863  ** Open a read-only cursor for the database table whose root page is
 91864  ** P2 in a database file.  The database file is determined by P3. 
 91865  ** P3==0 means the main database, P3==1 means the database used for 
 91866  ** temporary tables, and P3>1 means used the corresponding attached
 91867  ** database.  Give the new cursor an identifier of P1.  The P1
 91868  ** values need not be contiguous but all P1 values should be small integers.
 91869  ** It is an error for P1 to be negative.
 91870  **
 91871  ** Allowed P5 bits:
 91872  ** <ul>
 91873  ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 91874  **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
 91875  **       of OP_SeekLE/OP_IdxGT)
 91876  ** </ul>
 91877  **
 91878  ** The P4 value may be either an integer (P4_INT32) or a pointer to
 91879  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 91880  ** object, then table being opened must be an [index b-tree] where the
 91881  ** KeyInfo object defines the content and collating 
 91882  ** sequence of that index b-tree. Otherwise, if P4 is an integer 
 91883  ** value, then the table being opened must be a [table b-tree] with a
 91884  ** number of columns no less than the value of P4.
 91885  **
 91886  ** See also: OpenWrite, ReopenIdx
 91887  */
 91888  /* Opcode: ReopenIdx P1 P2 P3 P4 P5
 91889  ** Synopsis: root=P2 iDb=P3
 91890  **
 91891  ** The ReopenIdx opcode works like OP_OpenRead except that it first
 91892  ** checks to see if the cursor on P1 is already open on the same
 91893  ** b-tree and if it is this opcode becomes a no-op.  In other words,
 91894  ** if the cursor is already open, do not reopen it.
 91895  **
 91896  ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
 91897  ** and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must
 91898  ** be the same as every other ReopenIdx or OpenRead for the same cursor
 91899  ** number.
 91900  **
 91901  ** Allowed P5 bits:
 91902  ** <ul>
 91903  ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 91904  **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
 91905  **       of OP_SeekLE/OP_IdxGT)
 91906  ** </ul>
 91907  **
 91908  ** See also: OP_OpenRead, OP_OpenWrite
 91909  */
 91910  /* Opcode: OpenWrite P1 P2 P3 P4 P5
 91911  ** Synopsis: root=P2 iDb=P3
 91912  **
 91913  ** Open a read/write cursor named P1 on the table or index whose root
 91914  ** page is P2 (or whose root page is held in register P2 if the
 91915  ** OPFLAG_P2ISREG bit is set in P5 - see below).
 91916  **
 91917  ** The P4 value may be either an integer (P4_INT32) or a pointer to
 91918  ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
 91919  ** object, then table being opened must be an [index b-tree] where the
 91920  ** KeyInfo object defines the content and collating 
 91921  ** sequence of that index b-tree. Otherwise, if P4 is an integer 
 91922  ** value, then the table being opened must be a [table b-tree] with a
 91923  ** number of columns no less than the value of P4.
 91924  **
 91925  ** Allowed P5 bits:
 91926  ** <ul>
 91927  ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 91928  **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
 91929  **       of OP_SeekLE/OP_IdxGT)
 91930  ** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
 91931  **       and subsequently delete entries in an index btree.  This is a
 91932  **       hint to the storage engine that the storage engine is allowed to
 91933  **       ignore.  The hint is not used by the official SQLite b*tree storage
 91934  **       engine, but is used by COMDB2.
 91935  ** <li>  <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
 91936  **       as the root page, not the value of P2 itself.
 91937  ** </ul>
 91938  **
 91939  ** This instruction works like OpenRead except that it opens the cursor
 91940  ** in read/write mode.
 91941  **
 91942  ** See also: OP_OpenRead, OP_ReopenIdx
 91943  */
 91944  case OP_ReopenIdx: {
 91945    int nField;
 91946    KeyInfo *pKeyInfo;
 91947    int p2;
 91948    int iDb;
 91949    int wrFlag;
 91950    Btree *pX;
 91951    VdbeCursor *pCur;
 91952    Db *pDb;
 91953  
 91954    assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
 91955    assert( pOp->p4type==P4_KEYINFO );
 91956    pCur = p->apCsr[pOp->p1];
 91957    if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
 91958      assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
 91959      goto open_cursor_set_hints;
 91960    }
 91961    /* If the cursor is not currently open or is open on a different
 91962    ** index, then fall through into OP_OpenRead to force a reopen */
 91963  case OP_OpenRead:
 91964  case OP_OpenWrite:
 91965  
 91966    assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
 91967    assert( p->bIsReader );
 91968    assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
 91969            || p->readOnly==0 );
 91970  
 91971    if( p->expired==1 ){
 91972      rc = SQLITE_ABORT_ROLLBACK;
 91973      goto abort_due_to_error;
 91974    }
 91975  
 91976    nField = 0;
 91977    pKeyInfo = 0;
 91978    p2 = pOp->p2;
 91979    iDb = pOp->p3;
 91980    assert( iDb>=0 && iDb<db->nDb );
 91981    assert( DbMaskTest(p->btreeMask, iDb) );
 91982    pDb = &db->aDb[iDb];
 91983    pX = pDb->pBt;
 91984    assert( pX!=0 );
 91985    if( pOp->opcode==OP_OpenWrite ){
 91986      assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
 91987      wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
 91988      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 91989      if( pDb->pSchema->file_format < p->minWriteFileFormat ){
 91990        p->minWriteFileFormat = pDb->pSchema->file_format;
 91991      }
 91992    }else{
 91993      wrFlag = 0;
 91994    }
 91995    if( pOp->p5 & OPFLAG_P2ISREG ){
 91996      assert( p2>0 );
 91997      assert( p2<=(p->nMem+1 - p->nCursor) );
 91998      assert( pOp->opcode==OP_OpenWrite );
 91999      pIn2 = &aMem[p2];
 92000      assert( memIsValid(pIn2) );
 92001      assert( (pIn2->flags & MEM_Int)!=0 );
 92002      sqlite3VdbeMemIntegerify(pIn2);
 92003      p2 = (int)pIn2->u.i;
 92004      /* The p2 value always comes from a prior OP_CreateBtree opcode and
 92005      ** that opcode will always set the p2 value to 2 or more or else fail.
 92006      ** If there were a failure, the prepared statement would have halted
 92007      ** before reaching this instruction. */
 92008      assert( p2>=2 );
 92009    }
 92010    if( pOp->p4type==P4_KEYINFO ){
 92011      pKeyInfo = pOp->p4.pKeyInfo;
 92012      assert( pKeyInfo->enc==ENC(db) );
 92013      assert( pKeyInfo->db==db );
 92014      nField = pKeyInfo->nAllField;
 92015    }else if( pOp->p4type==P4_INT32 ){
 92016      nField = pOp->p4.i;
 92017    }
 92018    assert( pOp->p1>=0 );
 92019    assert( nField>=0 );
 92020    testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
 92021    pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
 92022    if( pCur==0 ) goto no_mem;
 92023    pCur->nullRow = 1;
 92024    pCur->isOrdered = 1;
 92025    pCur->pgnoRoot = p2;
 92026  #ifdef SQLITE_DEBUG
 92027    pCur->wrFlag = wrFlag;
 92028  #endif
 92029    rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
 92030    pCur->pKeyInfo = pKeyInfo;
 92031    /* Set the VdbeCursor.isTable variable. Previous versions of
 92032    ** SQLite used to check if the root-page flags were sane at this point
 92033    ** and report database corruption if they were not, but this check has
 92034    ** since moved into the btree layer.  */  
 92035    pCur->isTable = pOp->p4type!=P4_KEYINFO;
 92036  
 92037  open_cursor_set_hints:
 92038    assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
 92039    assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
 92040    testcase( pOp->p5 & OPFLAG_BULKCSR );
 92041  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 92042    testcase( pOp->p2 & OPFLAG_SEEKEQ );
 92043  #endif
 92044    sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
 92045                                 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
 92046    if( rc ) goto abort_due_to_error;
 92047    break;
 92048  }
 92049  
 92050  /* Opcode: OpenDup P1 P2 * * *
 92051  **
 92052  ** Open a new cursor P1 that points to the same ephemeral table as
 92053  ** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
 92054  ** opcode.  Only ephemeral cursors may be duplicated.
 92055  **
 92056  ** Duplicate ephemeral cursors are used for self-joins of materialized views.
 92057  */
 92058  case OP_OpenDup: {
 92059    VdbeCursor *pOrig;    /* The original cursor to be duplicated */
 92060    VdbeCursor *pCx;      /* The new cursor */
 92061  
 92062    pOrig = p->apCsr[pOp->p2];
 92063    assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
 92064  
 92065    pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
 92066    if( pCx==0 ) goto no_mem;
 92067    pCx->nullRow = 1;
 92068    pCx->isEphemeral = 1;
 92069    pCx->pKeyInfo = pOrig->pKeyInfo;
 92070    pCx->isTable = pOrig->isTable;
 92071    pCx->pgnoRoot = pOrig->pgnoRoot;
 92072    rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
 92073                            pCx->pKeyInfo, pCx->uc.pCursor);
 92074    /* The sqlite3BtreeCursor() routine can only fail for the first cursor
 92075    ** opened for a database.  Since there is already an open cursor when this
 92076    ** opcode is run, the sqlite3BtreeCursor() cannot fail */
 92077    assert( rc==SQLITE_OK );
 92078    break;
 92079  }
 92080  
 92081  
 92082  /* Opcode: OpenEphemeral P1 P2 * P4 P5
 92083  ** Synopsis: nColumn=P2
 92084  **
 92085  ** Open a new cursor P1 to a transient table.
 92086  ** The cursor is always opened read/write even if 
 92087  ** the main database is read-only.  The ephemeral
 92088  ** table is deleted automatically when the cursor is closed.
 92089  **
 92090  ** If the cursor P1 is already opened on an ephemeral table, the table
 92091  ** is cleared (all content is erased).
 92092  **
 92093  ** P2 is the number of columns in the ephemeral table.
 92094  ** The cursor points to a BTree table if P4==0 and to a BTree index
 92095  ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
 92096  ** that defines the format of keys in the index.
 92097  **
 92098  ** The P5 parameter can be a mask of the BTREE_* flags defined
 92099  ** in btree.h.  These flags control aspects of the operation of
 92100  ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
 92101  ** added automatically.
 92102  */
 92103  /* Opcode: OpenAutoindex P1 P2 * P4 *
 92104  ** Synopsis: nColumn=P2
 92105  **
 92106  ** This opcode works the same as OP_OpenEphemeral.  It has a
 92107  ** different name to distinguish its use.  Tables created using
 92108  ** by this opcode will be used for automatically created transient
 92109  ** indices in joins.
 92110  */
 92111  case OP_OpenAutoindex: 
 92112  case OP_OpenEphemeral: {
 92113    VdbeCursor *pCx;
 92114    KeyInfo *pKeyInfo;
 92115  
 92116    static const int vfsFlags = 
 92117        SQLITE_OPEN_READWRITE |
 92118        SQLITE_OPEN_CREATE |
 92119        SQLITE_OPEN_EXCLUSIVE |
 92120        SQLITE_OPEN_DELETEONCLOSE |
 92121        SQLITE_OPEN_TRANSIENT_DB;
 92122    assert( pOp->p1>=0 );
 92123    assert( pOp->p2>=0 );
 92124    pCx = p->apCsr[pOp->p1];
 92125    if( pCx ){
 92126      /* If the ephermeral table is already open, erase all existing content
 92127      ** so that the table is empty again, rather than creating a new table. */
 92128      rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
 92129    }else{
 92130      pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
 92131      if( pCx==0 ) goto no_mem;
 92132      pCx->nullRow = 1;
 92133      pCx->isEphemeral = 1;
 92134      rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 
 92135                            BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
 92136                            vfsFlags);
 92137      if( rc==SQLITE_OK ){
 92138        rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
 92139      }
 92140      if( rc==SQLITE_OK ){
 92141        /* If a transient index is required, create it by calling
 92142        ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
 92143        ** opening it. If a transient table is required, just use the
 92144        ** automatically created table with root-page 1 (an BLOB_INTKEY table).
 92145        */
 92146        if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
 92147          assert( pOp->p4type==P4_KEYINFO );
 92148          rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,
 92149                                       BTREE_BLOBKEY | pOp->p5); 
 92150          if( rc==SQLITE_OK ){
 92151            assert( pCx->pgnoRoot==MASTER_ROOT+1 );
 92152            assert( pKeyInfo->db==db );
 92153            assert( pKeyInfo->enc==ENC(db) );
 92154            rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
 92155                                    pKeyInfo, pCx->uc.pCursor);
 92156          }
 92157          pCx->isTable = 0;
 92158        }else{
 92159          pCx->pgnoRoot = MASTER_ROOT;
 92160          rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
 92161                                  0, pCx->uc.pCursor);
 92162          pCx->isTable = 1;
 92163        }
 92164      }
 92165      pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
 92166    }
 92167    if( rc ) goto abort_due_to_error;
 92168    break;
 92169  }
 92170  
 92171  /* Opcode: SorterOpen P1 P2 P3 P4 *
 92172  **
 92173  ** This opcode works like OP_OpenEphemeral except that it opens
 92174  ** a transient index that is specifically designed to sort large
 92175  ** tables using an external merge-sort algorithm.
 92176  **
 92177  ** If argument P3 is non-zero, then it indicates that the sorter may
 92178  ** assume that a stable sort considering the first P3 fields of each
 92179  ** key is sufficient to produce the required results.
 92180  */
 92181  case OP_SorterOpen: {
 92182    VdbeCursor *pCx;
 92183  
 92184    assert( pOp->p1>=0 );
 92185    assert( pOp->p2>=0 );
 92186    pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
 92187    if( pCx==0 ) goto no_mem;
 92188    pCx->pKeyInfo = pOp->p4.pKeyInfo;
 92189    assert( pCx->pKeyInfo->db==db );
 92190    assert( pCx->pKeyInfo->enc==ENC(db) );
 92191    rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
 92192    if( rc ) goto abort_due_to_error;
 92193    break;
 92194  }
 92195  
 92196  /* Opcode: SequenceTest P1 P2 * * *
 92197  ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
 92198  **
 92199  ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
 92200  ** to P2. Regardless of whether or not the jump is taken, increment the
 92201  ** the sequence value.
 92202  */
 92203  case OP_SequenceTest: {
 92204    VdbeCursor *pC;
 92205    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92206    pC = p->apCsr[pOp->p1];
 92207    assert( isSorter(pC) );
 92208    if( (pC->seqCount++)==0 ){
 92209      goto jump_to_p2;
 92210    }
 92211    break;
 92212  }
 92213  
 92214  /* Opcode: OpenPseudo P1 P2 P3 * *
 92215  ** Synopsis: P3 columns in r[P2]
 92216  **
 92217  ** Open a new cursor that points to a fake table that contains a single
 92218  ** row of data.  The content of that one row is the content of memory
 92219  ** register P2.  In other words, cursor P1 becomes an alias for the 
 92220  ** MEM_Blob content contained in register P2.
 92221  **
 92222  ** A pseudo-table created by this opcode is used to hold a single
 92223  ** row output from the sorter so that the row can be decomposed into
 92224  ** individual columns using the OP_Column opcode.  The OP_Column opcode
 92225  ** is the only cursor opcode that works with a pseudo-table.
 92226  **
 92227  ** P3 is the number of fields in the records that will be stored by
 92228  ** the pseudo-table.
 92229  */
 92230  case OP_OpenPseudo: {
 92231    VdbeCursor *pCx;
 92232  
 92233    assert( pOp->p1>=0 );
 92234    assert( pOp->p3>=0 );
 92235    pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
 92236    if( pCx==0 ) goto no_mem;
 92237    pCx->nullRow = 1;
 92238    pCx->seekResult = pOp->p2;
 92239    pCx->isTable = 1;
 92240    /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
 92241    ** can be safely passed to sqlite3VdbeCursorMoveto().  This avoids a test
 92242    ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
 92243    ** which is a performance optimization */
 92244    pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
 92245    assert( pOp->p5==0 );
 92246    break;
 92247  }
 92248  
 92249  /* Opcode: Close P1 * * * *
 92250  **
 92251  ** Close a cursor previously opened as P1.  If P1 is not
 92252  ** currently open, this instruction is a no-op.
 92253  */
 92254  case OP_Close: {
 92255    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92256    sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
 92257    p->apCsr[pOp->p1] = 0;
 92258    break;
 92259  }
 92260  
 92261  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
 92262  /* Opcode: ColumnsUsed P1 * * P4 *
 92263  **
 92264  ** This opcode (which only exists if SQLite was compiled with
 92265  ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
 92266  ** table or index for cursor P1 are used.  P4 is a 64-bit integer
 92267  ** (P4_INT64) in which the first 63 bits are one for each of the
 92268  ** first 63 columns of the table or index that are actually used
 92269  ** by the cursor.  The high-order bit is set if any column after
 92270  ** the 64th is used.
 92271  */
 92272  case OP_ColumnsUsed: {
 92273    VdbeCursor *pC;
 92274    pC = p->apCsr[pOp->p1];
 92275    assert( pC->eCurType==CURTYPE_BTREE );
 92276    pC->maskUsed = *(u64*)pOp->p4.pI64;
 92277    break;
 92278  }
 92279  #endif
 92280  
 92281  /* Opcode: SeekGE P1 P2 P3 P4 *
 92282  ** Synopsis: key=r[P3@P4]
 92283  **
 92284  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 92285  ** use the value in register P3 as the key.  If cursor P1 refers 
 92286  ** to an SQL index, then P3 is the first in an array of P4 registers 
 92287  ** that are used as an unpacked index key. 
 92288  **
 92289  ** Reposition cursor P1 so that  it points to the smallest entry that 
 92290  ** is greater than or equal to the key value. If there are no records 
 92291  ** greater than or equal to the key and P2 is not zero, then jump to P2.
 92292  **
 92293  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
 92294  ** opcode will always land on a record that equally equals the key, or
 92295  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
 92296  ** opcode must be followed by an IdxLE opcode with the same arguments.
 92297  ** The IdxLE opcode will be skipped if this opcode succeeds, but the
 92298  ** IdxLE opcode will be used on subsequent loop iterations.
 92299  **
 92300  ** This opcode leaves the cursor configured to move in forward order,
 92301  ** from the beginning toward the end.  In other words, the cursor is
 92302  ** configured to use Next, not Prev.
 92303  **
 92304  ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
 92305  */
 92306  /* Opcode: SeekGT P1 P2 P3 P4 *
 92307  ** Synopsis: key=r[P3@P4]
 92308  **
 92309  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 92310  ** use the value in register P3 as a key. If cursor P1 refers 
 92311  ** to an SQL index, then P3 is the first in an array of P4 registers 
 92312  ** that are used as an unpacked index key. 
 92313  **
 92314  ** Reposition cursor P1 so that  it points to the smallest entry that 
 92315  ** is greater than the key value. If there are no records greater than 
 92316  ** the key and P2 is not zero, then jump to P2.
 92317  **
 92318  ** This opcode leaves the cursor configured to move in forward order,
 92319  ** from the beginning toward the end.  In other words, the cursor is
 92320  ** configured to use Next, not Prev.
 92321  **
 92322  ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
 92323  */
 92324  /* Opcode: SeekLT P1 P2 P3 P4 * 
 92325  ** Synopsis: key=r[P3@P4]
 92326  **
 92327  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 92328  ** use the value in register P3 as a key. If cursor P1 refers 
 92329  ** to an SQL index, then P3 is the first in an array of P4 registers 
 92330  ** that are used as an unpacked index key. 
 92331  **
 92332  ** Reposition cursor P1 so that  it points to the largest entry that 
 92333  ** is less than the key value. If there are no records less than 
 92334  ** the key and P2 is not zero, then jump to P2.
 92335  **
 92336  ** This opcode leaves the cursor configured to move in reverse order,
 92337  ** from the end toward the beginning.  In other words, the cursor is
 92338  ** configured to use Prev, not Next.
 92339  **
 92340  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
 92341  */
 92342  /* Opcode: SeekLE P1 P2 P3 P4 *
 92343  ** Synopsis: key=r[P3@P4]
 92344  **
 92345  ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
 92346  ** use the value in register P3 as a key. If cursor P1 refers 
 92347  ** to an SQL index, then P3 is the first in an array of P4 registers 
 92348  ** that are used as an unpacked index key. 
 92349  **
 92350  ** Reposition cursor P1 so that it points to the largest entry that 
 92351  ** is less than or equal to the key value. If there are no records 
 92352  ** less than or equal to the key and P2 is not zero, then jump to P2.
 92353  **
 92354  ** This opcode leaves the cursor configured to move in reverse order,
 92355  ** from the end toward the beginning.  In other words, the cursor is
 92356  ** configured to use Prev, not Next.
 92357  **
 92358  ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
 92359  ** opcode will always land on a record that equally equals the key, or
 92360  ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
 92361  ** opcode must be followed by an IdxGE opcode with the same arguments.
 92362  ** The IdxGE opcode will be skipped if this opcode succeeds, but the
 92363  ** IdxGE opcode will be used on subsequent loop iterations.
 92364  **
 92365  ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
 92366  */
 92367  case OP_SeekLT:         /* jump, in3, group */
 92368  case OP_SeekLE:         /* jump, in3, group */
 92369  case OP_SeekGE:         /* jump, in3, group */
 92370  case OP_SeekGT: {       /* jump, in3, group */
 92371    int res;           /* Comparison result */
 92372    int oc;            /* Opcode */
 92373    VdbeCursor *pC;    /* The cursor to seek */
 92374    UnpackedRecord r;  /* The key to seek for */
 92375    int nField;        /* Number of columns or fields in the key */
 92376    i64 iKey;          /* The rowid we are to seek to */
 92377    int eqOnly;        /* Only interested in == results */
 92378  
 92379    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92380    assert( pOp->p2!=0 );
 92381    pC = p->apCsr[pOp->p1];
 92382    assert( pC!=0 );
 92383    assert( pC->eCurType==CURTYPE_BTREE );
 92384    assert( OP_SeekLE == OP_SeekLT+1 );
 92385    assert( OP_SeekGE == OP_SeekLT+2 );
 92386    assert( OP_SeekGT == OP_SeekLT+3 );
 92387    assert( pC->isOrdered );
 92388    assert( pC->uc.pCursor!=0 );
 92389    oc = pOp->opcode;
 92390    eqOnly = 0;
 92391    pC->nullRow = 0;
 92392  #ifdef SQLITE_DEBUG
 92393    pC->seekOp = pOp->opcode;
 92394  #endif
 92395  
 92396    if( pC->isTable ){
 92397      /* The BTREE_SEEK_EQ flag is only set on index cursors */
 92398      assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
 92399                || CORRUPT_DB );
 92400  
 92401      /* The input value in P3 might be of any type: integer, real, string,
 92402      ** blob, or NULL.  But it needs to be an integer before we can do
 92403      ** the seek, so convert it. */
 92404      pIn3 = &aMem[pOp->p3];
 92405      if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
 92406        applyNumericAffinity(pIn3, 0);
 92407      }
 92408      iKey = sqlite3VdbeIntValue(pIn3);
 92409  
 92410      /* If the P3 value could not be converted into an integer without
 92411      ** loss of information, then special processing is required... */
 92412      if( (pIn3->flags & MEM_Int)==0 ){
 92413        if( (pIn3->flags & MEM_Real)==0 ){
 92414          /* If the P3 value cannot be converted into any kind of a number,
 92415          ** then the seek is not possible, so jump to P2 */
 92416          VdbeBranchTaken(1,2); goto jump_to_p2;
 92417          break;
 92418        }
 92419  
 92420        /* If the approximation iKey is larger than the actual real search
 92421        ** term, substitute >= for > and < for <=. e.g. if the search term
 92422        ** is 4.9 and the integer approximation 5:
 92423        **
 92424        **        (x >  4.9)    ->     (x >= 5)
 92425        **        (x <= 4.9)    ->     (x <  5)
 92426        */
 92427        if( pIn3->u.r<(double)iKey ){
 92428          assert( OP_SeekGE==(OP_SeekGT-1) );
 92429          assert( OP_SeekLT==(OP_SeekLE-1) );
 92430          assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
 92431          if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
 92432        }
 92433  
 92434        /* If the approximation iKey is smaller than the actual real search
 92435        ** term, substitute <= for < and > for >=.  */
 92436        else if( pIn3->u.r>(double)iKey ){
 92437          assert( OP_SeekLE==(OP_SeekLT+1) );
 92438          assert( OP_SeekGT==(OP_SeekGE+1) );
 92439          assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
 92440          if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
 92441        }
 92442      } 
 92443      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
 92444      pC->movetoTarget = iKey;  /* Used by OP_Delete */
 92445      if( rc!=SQLITE_OK ){
 92446        goto abort_due_to_error;
 92447      }
 92448    }else{
 92449      /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
 92450      ** OP_SeekLE opcodes are allowed, and these must be immediately followed
 92451      ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
 92452      */
 92453      if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
 92454        eqOnly = 1;
 92455        assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
 92456        assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
 92457        assert( pOp[1].p1==pOp[0].p1 );
 92458        assert( pOp[1].p2==pOp[0].p2 );
 92459        assert( pOp[1].p3==pOp[0].p3 );
 92460        assert( pOp[1].p4.i==pOp[0].p4.i );
 92461      }
 92462  
 92463      nField = pOp->p4.i;
 92464      assert( pOp->p4type==P4_INT32 );
 92465      assert( nField>0 );
 92466      r.pKeyInfo = pC->pKeyInfo;
 92467      r.nField = (u16)nField;
 92468  
 92469      /* The next line of code computes as follows, only faster:
 92470      **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
 92471      **     r.default_rc = -1;
 92472      **   }else{
 92473      **     r.default_rc = +1;
 92474      **   }
 92475      */
 92476      r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
 92477      assert( oc!=OP_SeekGT || r.default_rc==-1 );
 92478      assert( oc!=OP_SeekLE || r.default_rc==-1 );
 92479      assert( oc!=OP_SeekGE || r.default_rc==+1 );
 92480      assert( oc!=OP_SeekLT || r.default_rc==+1 );
 92481  
 92482      r.aMem = &aMem[pOp->p3];
 92483  #ifdef SQLITE_DEBUG
 92484      { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
 92485  #endif
 92486      r.eqSeen = 0;
 92487      rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
 92488      if( rc!=SQLITE_OK ){
 92489        goto abort_due_to_error;
 92490      }
 92491      if( eqOnly && r.eqSeen==0 ){
 92492        assert( res!=0 );
 92493        goto seek_not_found;
 92494      }
 92495    }
 92496    pC->deferredMoveto = 0;
 92497    pC->cacheStatus = CACHE_STALE;
 92498  #ifdef SQLITE_TEST
 92499    sqlite3_search_count++;
 92500  #endif
 92501    if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
 92502      if( res<0 || (res==0 && oc==OP_SeekGT) ){
 92503        res = 0;
 92504        rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
 92505        if( rc!=SQLITE_OK ){
 92506          if( rc==SQLITE_DONE ){
 92507            rc = SQLITE_OK;
 92508            res = 1;
 92509          }else{
 92510            goto abort_due_to_error;
 92511          }
 92512        }
 92513      }else{
 92514        res = 0;
 92515      }
 92516    }else{
 92517      assert( oc==OP_SeekLT || oc==OP_SeekLE );
 92518      if( res>0 || (res==0 && oc==OP_SeekLT) ){
 92519        res = 0;
 92520        rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
 92521        if( rc!=SQLITE_OK ){
 92522          if( rc==SQLITE_DONE ){
 92523            rc = SQLITE_OK;
 92524            res = 1;
 92525          }else{
 92526            goto abort_due_to_error;
 92527          }
 92528        }
 92529      }else{
 92530        /* res might be negative because the table is empty.  Check to
 92531        ** see if this is the case.
 92532        */
 92533        res = sqlite3BtreeEof(pC->uc.pCursor);
 92534      }
 92535    }
 92536  seek_not_found:
 92537    assert( pOp->p2>0 );
 92538    VdbeBranchTaken(res!=0,2);
 92539    if( res ){
 92540      goto jump_to_p2;
 92541    }else if( eqOnly ){
 92542      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
 92543      pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
 92544    }
 92545    break;
 92546  }
 92547  
 92548  /* Opcode: SeekHit P1 P2 * * *
 92549  ** Synopsis: seekHit=P2
 92550  **
 92551  ** Set the seekHit flag on cursor P1 to the value in P2.
 92552  ** The seekHit flag is used by the IfNoHope opcode.
 92553  **
 92554  ** P1 must be a valid b-tree cursor.  P2 must be a boolean value,
 92555  ** either 0 or 1.
 92556  */
 92557  case OP_SeekHit: {
 92558    VdbeCursor *pC;
 92559    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92560    pC = p->apCsr[pOp->p1];
 92561    assert( pC!=0 );
 92562    assert( pOp->p2==0 || pOp->p2==1 );
 92563    pC->seekHit = pOp->p2 & 1;
 92564    break;
 92565  }
 92566  
 92567  /* Opcode: Found P1 P2 P3 P4 *
 92568  ** Synopsis: key=r[P3@P4]
 92569  **
 92570  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 92571  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 92572  ** record.
 92573  **
 92574  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 92575  ** is a prefix of any entry in P1 then a jump is made to P2 and
 92576  ** P1 is left pointing at the matching entry.
 92577  **
 92578  ** This operation leaves the cursor in a state where it can be
 92579  ** advanced in the forward direction.  The Next instruction will work,
 92580  ** but not the Prev instruction.
 92581  **
 92582  ** See also: NotFound, NoConflict, NotExists. SeekGe
 92583  */
 92584  /* Opcode: NotFound P1 P2 P3 P4 *
 92585  ** Synopsis: key=r[P3@P4]
 92586  **
 92587  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 92588  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 92589  ** record.
 92590  ** 
 92591  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 92592  ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
 92593  ** does contain an entry whose prefix matches the P3/P4 record then control
 92594  ** falls through to the next instruction and P1 is left pointing at the
 92595  ** matching entry.
 92596  **
 92597  ** This operation leaves the cursor in a state where it cannot be
 92598  ** advanced in either direction.  In other words, the Next and Prev
 92599  ** opcodes do not work after this operation.
 92600  **
 92601  ** See also: Found, NotExists, NoConflict, IfNoHope
 92602  */
 92603  /* Opcode: IfNoHope P1 P2 P3 P4 *
 92604  ** Synopsis: key=r[P3@P4]
 92605  **
 92606  ** Register P3 is the first of P4 registers that form an unpacked
 92607  ** record.
 92608  **
 92609  ** Cursor P1 is on an index btree.  If the seekHit flag is set on P1, then
 92610  ** this opcode is a no-op.  But if the seekHit flag of P1 is clear, then
 92611  ** check to see if there is any entry in P1 that matches the
 92612  ** prefix identified by P3 and P4.  If no entry matches the prefix,
 92613  ** jump to P2.  Otherwise fall through.
 92614  **
 92615  ** This opcode behaves like OP_NotFound if the seekHit
 92616  ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
 92617  **
 92618  ** This opcode is used in IN clause processing for a multi-column key.
 92619  ** If an IN clause is attached to an element of the key other than the
 92620  ** left-most element, and if there are no matches on the most recent
 92621  ** seek over the whole key, then it might be that one of the key element
 92622  ** to the left is prohibiting a match, and hence there is "no hope" of
 92623  ** any match regardless of how many IN clause elements are checked.
 92624  ** In such a case, we abandon the IN clause search early, using this
 92625  ** opcode.  The opcode name comes from the fact that the
 92626  ** jump is taken if there is "no hope" of achieving a match.
 92627  **
 92628  ** See also: NotFound, SeekHit
 92629  */
 92630  /* Opcode: NoConflict P1 P2 P3 P4 *
 92631  ** Synopsis: key=r[P3@P4]
 92632  **
 92633  ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 92634  ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 92635  ** record.
 92636  ** 
 92637  ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 92638  ** contains any NULL value, jump immediately to P2.  If all terms of the
 92639  ** record are not-NULL then a check is done to determine if any row in the
 92640  ** P1 index btree has a matching key prefix.  If there are no matches, jump
 92641  ** immediately to P2.  If there is a match, fall through and leave the P1
 92642  ** cursor pointing to the matching row.
 92643  **
 92644  ** This opcode is similar to OP_NotFound with the exceptions that the
 92645  ** branch is always taken if any part of the search key input is NULL.
 92646  **
 92647  ** This operation leaves the cursor in a state where it cannot be
 92648  ** advanced in either direction.  In other words, the Next and Prev
 92649  ** opcodes do not work after this operation.
 92650  **
 92651  ** See also: NotFound, Found, NotExists
 92652  */
 92653  case OP_IfNoHope: {     /* jump, in3 */
 92654    VdbeCursor *pC;
 92655    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92656    pC = p->apCsr[pOp->p1];
 92657    assert( pC!=0 );
 92658    if( pC->seekHit ) break;
 92659    /* Fall through into OP_NotFound */
 92660  }
 92661  case OP_NoConflict:     /* jump, in3 */
 92662  case OP_NotFound:       /* jump, in3 */
 92663  case OP_Found: {        /* jump, in3 */
 92664    int alreadyExists;
 92665    int takeJump;
 92666    int ii;
 92667    VdbeCursor *pC;
 92668    int res;
 92669    UnpackedRecord *pFree;
 92670    UnpackedRecord *pIdxKey;
 92671    UnpackedRecord r;
 92672  
 92673  #ifdef SQLITE_TEST
 92674    if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
 92675  #endif
 92676  
 92677    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92678    assert( pOp->p4type==P4_INT32 );
 92679    pC = p->apCsr[pOp->p1];
 92680    assert( pC!=0 );
 92681  #ifdef SQLITE_DEBUG
 92682    pC->seekOp = pOp->opcode;
 92683  #endif
 92684    pIn3 = &aMem[pOp->p3];
 92685    assert( pC->eCurType==CURTYPE_BTREE );
 92686    assert( pC->uc.pCursor!=0 );
 92687    assert( pC->isTable==0 );
 92688    if( pOp->p4.i>0 ){
 92689      r.pKeyInfo = pC->pKeyInfo;
 92690      r.nField = (u16)pOp->p4.i;
 92691      r.aMem = pIn3;
 92692  #ifdef SQLITE_DEBUG
 92693      for(ii=0; ii<r.nField; ii++){
 92694        assert( memIsValid(&r.aMem[ii]) );
 92695        assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
 92696        if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
 92697      }
 92698  #endif
 92699      pIdxKey = &r;
 92700      pFree = 0;
 92701    }else{
 92702      assert( pIn3->flags & MEM_Blob );
 92703      rc = ExpandBlob(pIn3);
 92704      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
 92705      if( rc ) goto no_mem;
 92706      pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
 92707      if( pIdxKey==0 ) goto no_mem;
 92708      sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
 92709    }
 92710    pIdxKey->default_rc = 0;
 92711    takeJump = 0;
 92712    if( pOp->opcode==OP_NoConflict ){
 92713      /* For the OP_NoConflict opcode, take the jump if any of the
 92714      ** input fields are NULL, since any key with a NULL will not
 92715      ** conflict */
 92716      for(ii=0; ii<pIdxKey->nField; ii++){
 92717        if( pIdxKey->aMem[ii].flags & MEM_Null ){
 92718          takeJump = 1;
 92719          break;
 92720        }
 92721      }
 92722    }
 92723    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
 92724    if( pFree ) sqlite3DbFreeNN(db, pFree);
 92725    if( rc!=SQLITE_OK ){
 92726      goto abort_due_to_error;
 92727    }
 92728    pC->seekResult = res;
 92729    alreadyExists = (res==0);
 92730    pC->nullRow = 1-alreadyExists;
 92731    pC->deferredMoveto = 0;
 92732    pC->cacheStatus = CACHE_STALE;
 92733    if( pOp->opcode==OP_Found ){
 92734      VdbeBranchTaken(alreadyExists!=0,2);
 92735      if( alreadyExists ) goto jump_to_p2;
 92736    }else{
 92737      VdbeBranchTaken(takeJump||alreadyExists==0,2);
 92738      if( takeJump || !alreadyExists ) goto jump_to_p2;
 92739    }
 92740    break;
 92741  }
 92742  
 92743  /* Opcode: SeekRowid P1 P2 P3 * *
 92744  ** Synopsis: intkey=r[P3]
 92745  **
 92746  ** P1 is the index of a cursor open on an SQL table btree (with integer
 92747  ** keys).  If register P3 does not contain an integer or if P1 does not
 92748  ** contain a record with rowid P3 then jump immediately to P2.  
 92749  ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
 92750  ** a record with rowid P3 then 
 92751  ** leave the cursor pointing at that record and fall through to the next
 92752  ** instruction.
 92753  **
 92754  ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
 92755  ** the P3 register must be guaranteed to contain an integer value.  With this
 92756  ** opcode, register P3 might not contain an integer.
 92757  **
 92758  ** The OP_NotFound opcode performs the same operation on index btrees
 92759  ** (with arbitrary multi-value keys).
 92760  **
 92761  ** This opcode leaves the cursor in a state where it cannot be advanced
 92762  ** in either direction.  In other words, the Next and Prev opcodes will
 92763  ** not work following this opcode.
 92764  **
 92765  ** See also: Found, NotFound, NoConflict, SeekRowid
 92766  */
 92767  /* Opcode: NotExists P1 P2 P3 * *
 92768  ** Synopsis: intkey=r[P3]
 92769  **
 92770  ** P1 is the index of a cursor open on an SQL table btree (with integer
 92771  ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
 92772  ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
 92773  ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 
 92774  ** leave the cursor pointing at that record and fall through to the next
 92775  ** instruction.
 92776  **
 92777  ** The OP_SeekRowid opcode performs the same operation but also allows the
 92778  ** P3 register to contain a non-integer value, in which case the jump is
 92779  ** always taken.  This opcode requires that P3 always contain an integer.
 92780  **
 92781  ** The OP_NotFound opcode performs the same operation on index btrees
 92782  ** (with arbitrary multi-value keys).
 92783  **
 92784  ** This opcode leaves the cursor in a state where it cannot be advanced
 92785  ** in either direction.  In other words, the Next and Prev opcodes will
 92786  ** not work following this opcode.
 92787  **
 92788  ** See also: Found, NotFound, NoConflict, SeekRowid
 92789  */
 92790  case OP_SeekRowid: {        /* jump, in3 */
 92791    VdbeCursor *pC;
 92792    BtCursor *pCrsr;
 92793    int res;
 92794    u64 iKey;
 92795  
 92796    pIn3 = &aMem[pOp->p3];
 92797    if( (pIn3->flags & MEM_Int)==0 ){
 92798      /* Make sure pIn3->u.i contains a valid integer representation of
 92799      ** the key value, but do not change the datatype of the register, as
 92800      ** other parts of the perpared statement might be depending on the
 92801      ** current datatype. */
 92802      u16 origFlags = pIn3->flags;
 92803      int isNotInt;
 92804      applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
 92805      isNotInt = (pIn3->flags & MEM_Int)==0;
 92806      pIn3->flags = origFlags;
 92807      if( isNotInt ) goto jump_to_p2;
 92808    }
 92809    /* Fall through into OP_NotExists */
 92810  case OP_NotExists:          /* jump, in3 */
 92811    pIn3 = &aMem[pOp->p3];
 92812    assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
 92813    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92814    pC = p->apCsr[pOp->p1];
 92815    assert( pC!=0 );
 92816  #ifdef SQLITE_DEBUG
 92817    if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
 92818  #endif
 92819    assert( pC->isTable );
 92820    assert( pC->eCurType==CURTYPE_BTREE );
 92821    pCrsr = pC->uc.pCursor;
 92822    assert( pCrsr!=0 );
 92823    res = 0;
 92824    iKey = pIn3->u.i;
 92825    rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
 92826    assert( rc==SQLITE_OK || res==0 );
 92827    pC->movetoTarget = iKey;  /* Used by OP_Delete */
 92828    pC->nullRow = 0;
 92829    pC->cacheStatus = CACHE_STALE;
 92830    pC->deferredMoveto = 0;
 92831    VdbeBranchTaken(res!=0,2);
 92832    pC->seekResult = res;
 92833    if( res!=0 ){
 92834      assert( rc==SQLITE_OK );
 92835      if( pOp->p2==0 ){
 92836        rc = SQLITE_CORRUPT_BKPT;
 92837      }else{
 92838        goto jump_to_p2;
 92839      }
 92840    }
 92841    if( rc ) goto abort_due_to_error;
 92842    break;
 92843  }
 92844  
 92845  /* Opcode: Sequence P1 P2 * * *
 92846  ** Synopsis: r[P2]=cursor[P1].ctr++
 92847  **
 92848  ** Find the next available sequence number for cursor P1.
 92849  ** Write the sequence number into register P2.
 92850  ** The sequence number on the cursor is incremented after this
 92851  ** instruction.  
 92852  */
 92853  case OP_Sequence: {           /* out2 */
 92854    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92855    assert( p->apCsr[pOp->p1]!=0 );
 92856    assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
 92857    pOut = out2Prerelease(p, pOp);
 92858    pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
 92859    break;
 92860  }
 92861  
 92862  
 92863  /* Opcode: NewRowid P1 P2 P3 * *
 92864  ** Synopsis: r[P2]=rowid
 92865  **
 92866  ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
 92867  ** The record number is not previously used as a key in the database
 92868  ** table that cursor P1 points to.  The new record number is written
 92869  ** written to register P2.
 92870  **
 92871  ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
 92872  ** the largest previously generated record number. No new record numbers are
 92873  ** allowed to be less than this value. When this value reaches its maximum, 
 92874  ** an SQLITE_FULL error is generated. The P3 register is updated with the '
 92875  ** generated record number. This P3 mechanism is used to help implement the
 92876  ** AUTOINCREMENT feature.
 92877  */
 92878  case OP_NewRowid: {           /* out2 */
 92879    i64 v;                 /* The new rowid */
 92880    VdbeCursor *pC;        /* Cursor of table to get the new rowid */
 92881    int res;               /* Result of an sqlite3BtreeLast() */
 92882    int cnt;               /* Counter to limit the number of searches */
 92883    Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
 92884    VdbeFrame *pFrame;     /* Root frame of VDBE */
 92885  
 92886    v = 0;
 92887    res = 0;
 92888    pOut = out2Prerelease(p, pOp);
 92889    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 92890    pC = p->apCsr[pOp->p1];
 92891    assert( pC!=0 );
 92892    assert( pC->isTable );
 92893    assert( pC->eCurType==CURTYPE_BTREE );
 92894    assert( pC->uc.pCursor!=0 );
 92895    {
 92896      /* The next rowid or record number (different terms for the same
 92897      ** thing) is obtained in a two-step algorithm.
 92898      **
 92899      ** First we attempt to find the largest existing rowid and add one
 92900      ** to that.  But if the largest existing rowid is already the maximum
 92901      ** positive integer, we have to fall through to the second
 92902      ** probabilistic algorithm
 92903      **
 92904      ** The second algorithm is to select a rowid at random and see if
 92905      ** it already exists in the table.  If it does not exist, we have
 92906      ** succeeded.  If the random rowid does exist, we select a new one
 92907      ** and try again, up to 100 times.
 92908      */
 92909      assert( pC->isTable );
 92910  
 92911  #ifdef SQLITE_32BIT_ROWID
 92912  #   define MAX_ROWID 0x7fffffff
 92913  #else
 92914      /* Some compilers complain about constants of the form 0x7fffffffffffffff.
 92915      ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
 92916      ** to provide the constant while making all compilers happy.
 92917      */
 92918  #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
 92919  #endif
 92920  
 92921      if( !pC->useRandomRowid ){
 92922        rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
 92923        if( rc!=SQLITE_OK ){
 92924          goto abort_due_to_error;
 92925        }
 92926        if( res ){
 92927          v = 1;   /* IMP: R-61914-48074 */
 92928        }else{
 92929          assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
 92930          v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 92931          if( v>=MAX_ROWID ){
 92932            pC->useRandomRowid = 1;
 92933          }else{
 92934            v++;   /* IMP: R-29538-34987 */
 92935          }
 92936        }
 92937      }
 92938  
 92939  #ifndef SQLITE_OMIT_AUTOINCREMENT
 92940      if( pOp->p3 ){
 92941        /* Assert that P3 is a valid memory cell. */
 92942        assert( pOp->p3>0 );
 92943        if( p->pFrame ){
 92944          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 92945          /* Assert that P3 is a valid memory cell. */
 92946          assert( pOp->p3<=pFrame->nMem );
 92947          pMem = &pFrame->aMem[pOp->p3];
 92948        }else{
 92949          /* Assert that P3 is a valid memory cell. */
 92950          assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
 92951          pMem = &aMem[pOp->p3];
 92952          memAboutToChange(p, pMem);
 92953        }
 92954        assert( memIsValid(pMem) );
 92955  
 92956        REGISTER_TRACE(pOp->p3, pMem);
 92957        sqlite3VdbeMemIntegerify(pMem);
 92958        assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
 92959        if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
 92960          rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
 92961          goto abort_due_to_error;
 92962        }
 92963        if( v<pMem->u.i+1 ){
 92964          v = pMem->u.i + 1;
 92965        }
 92966        pMem->u.i = v;
 92967      }
 92968  #endif
 92969      if( pC->useRandomRowid ){
 92970        /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
 92971        ** largest possible integer (9223372036854775807) then the database
 92972        ** engine starts picking positive candidate ROWIDs at random until
 92973        ** it finds one that is not previously used. */
 92974        assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
 92975                               ** an AUTOINCREMENT table. */
 92976        rc = sqlite3BtreeCount(pC->uc.pCursor, &v);
 92977        if( rc ) goto abort_due_to_error;
 92978        cnt = 0; res = 0;
 92979        do{
 92980          if( v==MAX_ROWID ) break;  /* Ensure that v is greater than zero */
 92981          v++;
 92982        }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
 92983                                                   0, &res))==SQLITE_OK)
 92984              && (res==0)
 92985              && (++cnt<1000));
 92986        if( rc ) goto abort_due_to_error;
 92987        if( res==0 ){
 92988          rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
 92989          goto abort_due_to_error;
 92990        }
 92991        assert( v>0 );  /* EV: R-40812-03570 */
 92992      }
 92993      pC->deferredMoveto = 0;
 92994      pC->cacheStatus = CACHE_STALE;
 92995    }
 92996    pOut->u.i = v;
 92997    break;
 92998  }
 92999  
 93000  /* Opcode: Insert P1 P2 P3 P4 P5
 93001  ** Synopsis: intkey=r[P3] data=r[P2]
 93002  **
 93003  ** Write an entry into the table of cursor P1.  A new entry is
 93004  ** created if it doesn't already exist or the data for an existing
 93005  ** entry is overwritten.  The data is the value MEM_Blob stored in register
 93006  ** number P2. The key is stored in register P3. The key must
 93007  ** be a MEM_Int.
 93008  **
 93009  ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
 93010  ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
 93011  ** then rowid is stored for subsequent return by the
 93012  ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
 93013  **
 93014  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
 93015  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
 93016  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
 93017  ** seeks on the cursor or if the most recent seek used a key equal to P3.
 93018  **
 93019  ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
 93020  ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
 93021  ** is part of an INSERT operation.  The difference is only important to
 93022  ** the update hook.
 93023  **
 93024  ** Parameter P4 may point to a Table structure, or may be NULL. If it is 
 93025  ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 
 93026  ** following a successful insert.
 93027  **
 93028  ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
 93029  ** allocated, then ownership of P2 is transferred to the pseudo-cursor
 93030  ** and register P2 becomes ephemeral.  If the cursor is changed, the
 93031  ** value of register P2 will then change.  Make sure this does not
 93032  ** cause any problems.)
 93033  **
 93034  ** This instruction only works on tables.  The equivalent instruction
 93035  ** for indices is OP_IdxInsert.
 93036  */
 93037  case OP_Insert: {
 93038    Mem *pData;       /* MEM cell holding data for the record to be inserted */
 93039    Mem *pKey;        /* MEM cell holding key  for the record */
 93040    VdbeCursor *pC;   /* Cursor to table into which insert is written */
 93041    int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
 93042    const char *zDb;  /* database name - used by the update hook */
 93043    Table *pTab;      /* Table structure - used by update and pre-update hooks */
 93044    BtreePayload x;   /* Payload to be inserted */
 93045  
 93046    pData = &aMem[pOp->p2];
 93047    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93048    assert( memIsValid(pData) );
 93049    pC = p->apCsr[pOp->p1];
 93050    assert( pC!=0 );
 93051    assert( pC->eCurType==CURTYPE_BTREE );
 93052    assert( pC->uc.pCursor!=0 );
 93053    assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
 93054    assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
 93055    REGISTER_TRACE(pOp->p2, pData);
 93056    sqlite3VdbeIncrWriteCounter(p, pC);
 93057  
 93058    pKey = &aMem[pOp->p3];
 93059    assert( pKey->flags & MEM_Int );
 93060    assert( memIsValid(pKey) );
 93061    REGISTER_TRACE(pOp->p3, pKey);
 93062    x.nKey = pKey->u.i;
 93063  
 93064    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
 93065      assert( pC->iDb>=0 );
 93066      zDb = db->aDb[pC->iDb].zDbSName;
 93067      pTab = pOp->p4.pTab;
 93068      assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
 93069    }else{
 93070      pTab = 0;
 93071      zDb = 0;  /* Not needed.  Silence a compiler warning. */
 93072    }
 93073  
 93074  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 93075    /* Invoke the pre-update hook, if any */
 93076    if( pTab ){
 93077      if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
 93078        sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
 93079      }
 93080      if( db->xUpdateCallback==0 || pTab->aCol==0 ){
 93081        /* Prevent post-update hook from running in cases when it should not */
 93082        pTab = 0;
 93083      }
 93084    }
 93085    if( pOp->p5 & OPFLAG_ISNOOP ) break;
 93086  #endif
 93087  
 93088    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 93089    if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
 93090    assert( pData->flags & (MEM_Blob|MEM_Str) );
 93091    x.pData = pData->z;
 93092    x.nData = pData->n;
 93093    seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
 93094    if( pData->flags & MEM_Zero ){
 93095      x.nZero = pData->u.nZero;
 93096    }else{
 93097      x.nZero = 0;
 93098    }
 93099    x.pKey = 0;
 93100    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
 93101        (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
 93102    );
 93103    pC->deferredMoveto = 0;
 93104    pC->cacheStatus = CACHE_STALE;
 93105  
 93106    /* Invoke the update-hook if required. */
 93107    if( rc ) goto abort_due_to_error;
 93108    if( pTab ){
 93109      assert( db->xUpdateCallback!=0 );
 93110      assert( pTab->aCol!=0 );
 93111      db->xUpdateCallback(db->pUpdateArg,
 93112             (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
 93113             zDb, pTab->zName, x.nKey);
 93114    }
 93115    break;
 93116  }
 93117  
 93118  /* Opcode: Delete P1 P2 P3 P4 P5
 93119  **
 93120  ** Delete the record at which the P1 cursor is currently pointing.
 93121  **
 93122  ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
 93123  ** the cursor will be left pointing at  either the next or the previous
 93124  ** record in the table. If it is left pointing at the next record, then
 93125  ** the next Next instruction will be a no-op. As a result, in this case
 93126  ** it is ok to delete a record from within a Next loop. If 
 93127  ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
 93128  ** left in an undefined state.
 93129  **
 93130  ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
 93131  ** delete one of several associated with deleting a table row and all its
 93132  ** associated index entries.  Exactly one of those deletes is the "primary"
 93133  ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
 93134  ** marked with the AUXDELETE flag.
 93135  **
 93136  ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
 93137  ** change count is incremented (otherwise not).
 93138  **
 93139  ** P1 must not be pseudo-table.  It has to be a real table with
 93140  ** multiple rows.
 93141  **
 93142  ** If P4 is not NULL then it points to a Table object. In this case either 
 93143  ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
 93144  ** have been positioned using OP_NotFound prior to invoking this opcode in 
 93145  ** this case. Specifically, if one is configured, the pre-update hook is 
 93146  ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 
 93147  ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
 93148  **
 93149  ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
 93150  ** of the memory cell that contains the value that the rowid of the row will
 93151  ** be set to by the update.
 93152  */
 93153  case OP_Delete: {
 93154    VdbeCursor *pC;
 93155    const char *zDb;
 93156    Table *pTab;
 93157    int opflags;
 93158  
 93159    opflags = pOp->p2;
 93160    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93161    pC = p->apCsr[pOp->p1];
 93162    assert( pC!=0 );
 93163    assert( pC->eCurType==CURTYPE_BTREE );
 93164    assert( pC->uc.pCursor!=0 );
 93165    assert( pC->deferredMoveto==0 );
 93166    sqlite3VdbeIncrWriteCounter(p, pC);
 93167  
 93168  #ifdef SQLITE_DEBUG
 93169    if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
 93170      /* If p5 is zero, the seek operation that positioned the cursor prior to
 93171      ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
 93172      ** the row that is being deleted */
 93173      i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 93174      assert( pC->movetoTarget==iKey );
 93175    }
 93176  #endif
 93177  
 93178    /* If the update-hook or pre-update-hook will be invoked, set zDb to
 93179    ** the name of the db to pass as to it. Also set local pTab to a copy
 93180    ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
 93181    ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
 93182    ** VdbeCursor.movetoTarget to the current rowid.  */
 93183    if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
 93184      assert( pC->iDb>=0 );
 93185      assert( pOp->p4.pTab!=0 );
 93186      zDb = db->aDb[pC->iDb].zDbSName;
 93187      pTab = pOp->p4.pTab;
 93188      if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
 93189        pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 93190      }
 93191    }else{
 93192      zDb = 0;   /* Not needed.  Silence a compiler warning. */
 93193      pTab = 0;  /* Not needed.  Silence a compiler warning. */
 93194    }
 93195  
 93196  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 93197    /* Invoke the pre-update-hook if required. */
 93198    if( db->xPreUpdateCallback && pOp->p4.pTab ){
 93199      assert( !(opflags & OPFLAG_ISUPDATE) 
 93200           || HasRowid(pTab)==0 
 93201           || (aMem[pOp->p3].flags & MEM_Int) 
 93202      );
 93203      sqlite3VdbePreUpdateHook(p, pC,
 93204          (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 
 93205          zDb, pTab, pC->movetoTarget,
 93206          pOp->p3
 93207      );
 93208    }
 93209    if( opflags & OPFLAG_ISNOOP ) break;
 93210  #endif
 93211   
 93212    /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 
 93213    assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
 93214    assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
 93215    assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
 93216  
 93217  #ifdef SQLITE_DEBUG
 93218    if( p->pFrame==0 ){
 93219      if( pC->isEphemeral==0
 93220          && (pOp->p5 & OPFLAG_AUXDELETE)==0
 93221          && (pC->wrFlag & OPFLAG_FORDELETE)==0
 93222        ){
 93223        nExtraDelete++;
 93224      }
 93225      if( pOp->p2 & OPFLAG_NCHANGE ){
 93226        nExtraDelete--;
 93227      }
 93228    }
 93229  #endif
 93230  
 93231    rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
 93232    pC->cacheStatus = CACHE_STALE;
 93233    pC->seekResult = 0;
 93234    if( rc ) goto abort_due_to_error;
 93235  
 93236    /* Invoke the update-hook if required. */
 93237    if( opflags & OPFLAG_NCHANGE ){
 93238      p->nChange++;
 93239      if( db->xUpdateCallback && HasRowid(pTab) ){
 93240        db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
 93241            pC->movetoTarget);
 93242        assert( pC->iDb>=0 );
 93243      }
 93244    }
 93245  
 93246    break;
 93247  }
 93248  /* Opcode: ResetCount * * * * *
 93249  **
 93250  ** The value of the change counter is copied to the database handle
 93251  ** change counter (returned by subsequent calls to sqlite3_changes()).
 93252  ** Then the VMs internal change counter resets to 0.
 93253  ** This is used by trigger programs.
 93254  */
 93255  case OP_ResetCount: {
 93256    sqlite3VdbeSetChanges(db, p->nChange);
 93257    p->nChange = 0;
 93258    break;
 93259  }
 93260  
 93261  /* Opcode: SorterCompare P1 P2 P3 P4
 93262  ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
 93263  **
 93264  ** P1 is a sorter cursor. This instruction compares a prefix of the
 93265  ** record blob in register P3 against a prefix of the entry that 
 93266  ** the sorter cursor currently points to.  Only the first P4 fields
 93267  ** of r[P3] and the sorter record are compared.
 93268  **
 93269  ** If either P3 or the sorter contains a NULL in one of their significant
 93270  ** fields (not counting the P4 fields at the end which are ignored) then
 93271  ** the comparison is assumed to be equal.
 93272  **
 93273  ** Fall through to next instruction if the two records compare equal to
 93274  ** each other.  Jump to P2 if they are different.
 93275  */
 93276  case OP_SorterCompare: {
 93277    VdbeCursor *pC;
 93278    int res;
 93279    int nKeyCol;
 93280  
 93281    pC = p->apCsr[pOp->p1];
 93282    assert( isSorter(pC) );
 93283    assert( pOp->p4type==P4_INT32 );
 93284    pIn3 = &aMem[pOp->p3];
 93285    nKeyCol = pOp->p4.i;
 93286    res = 0;
 93287    rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
 93288    VdbeBranchTaken(res!=0,2);
 93289    if( rc ) goto abort_due_to_error;
 93290    if( res ) goto jump_to_p2;
 93291    break;
 93292  };
 93293  
 93294  /* Opcode: SorterData P1 P2 P3 * *
 93295  ** Synopsis: r[P2]=data
 93296  **
 93297  ** Write into register P2 the current sorter data for sorter cursor P1.
 93298  ** Then clear the column header cache on cursor P3.
 93299  **
 93300  ** This opcode is normally use to move a record out of the sorter and into
 93301  ** a register that is the source for a pseudo-table cursor created using
 93302  ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
 93303  ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
 93304  ** us from having to issue a separate NullRow instruction to clear that cache.
 93305  */
 93306  case OP_SorterData: {
 93307    VdbeCursor *pC;
 93308  
 93309    pOut = &aMem[pOp->p2];
 93310    pC = p->apCsr[pOp->p1];
 93311    assert( isSorter(pC) );
 93312    rc = sqlite3VdbeSorterRowkey(pC, pOut);
 93313    assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
 93314    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93315    if( rc ) goto abort_due_to_error;
 93316    p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
 93317    break;
 93318  }
 93319  
 93320  /* Opcode: RowData P1 P2 P3 * *
 93321  ** Synopsis: r[P2]=data
 93322  **
 93323  ** Write into register P2 the complete row content for the row at 
 93324  ** which cursor P1 is currently pointing.
 93325  ** There is no interpretation of the data.  
 93326  ** It is just copied onto the P2 register exactly as 
 93327  ** it is found in the database file.
 93328  **
 93329  ** If cursor P1 is an index, then the content is the key of the row.
 93330  ** If cursor P2 is a table, then the content extracted is the data.
 93331  **
 93332  ** If the P1 cursor must be pointing to a valid row (not a NULL row)
 93333  ** of a real table, not a pseudo-table.
 93334  **
 93335  ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
 93336  ** into the database page.  That means that the content of the output
 93337  ** register will be invalidated as soon as the cursor moves - including
 93338  ** moves caused by other cursors that "save" the current cursors
 93339  ** position in order that they can write to the same table.  If P3==0
 93340  ** then a copy of the data is made into memory.  P3!=0 is faster, but
 93341  ** P3==0 is safer.
 93342  **
 93343  ** If P3!=0 then the content of the P2 register is unsuitable for use
 93344  ** in OP_Result and any OP_Result will invalidate the P2 register content.
 93345  ** The P2 register content is invalidated by opcodes like OP_Function or
 93346  ** by any use of another cursor pointing to the same table.
 93347  */
 93348  case OP_RowData: {
 93349    VdbeCursor *pC;
 93350    BtCursor *pCrsr;
 93351    u32 n;
 93352  
 93353    pOut = out2Prerelease(p, pOp);
 93354  
 93355    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93356    pC = p->apCsr[pOp->p1];
 93357    assert( pC!=0 );
 93358    assert( pC->eCurType==CURTYPE_BTREE );
 93359    assert( isSorter(pC)==0 );
 93360    assert( pC->nullRow==0 );
 93361    assert( pC->uc.pCursor!=0 );
 93362    pCrsr = pC->uc.pCursor;
 93363  
 93364    /* The OP_RowData opcodes always follow OP_NotExists or
 93365    ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
 93366    ** that might invalidate the cursor.
 93367    ** If this where not the case, on of the following assert()s
 93368    ** would fail.  Should this ever change (because of changes in the code
 93369    ** generator) then the fix would be to insert a call to
 93370    ** sqlite3VdbeCursorMoveto().
 93371    */
 93372    assert( pC->deferredMoveto==0 );
 93373    assert( sqlite3BtreeCursorIsValid(pCrsr) );
 93374  #if 0  /* Not required due to the previous to assert() statements */
 93375    rc = sqlite3VdbeCursorMoveto(pC);
 93376    if( rc!=SQLITE_OK ) goto abort_due_to_error;
 93377  #endif
 93378  
 93379    n = sqlite3BtreePayloadSize(pCrsr);
 93380    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
 93381      goto too_big;
 93382    }
 93383    testcase( n==0 );
 93384    rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
 93385    if( rc ) goto abort_due_to_error;
 93386    if( !pOp->p3 ) Deephemeralize(pOut);
 93387    UPDATE_MAX_BLOBSIZE(pOut);
 93388    REGISTER_TRACE(pOp->p2, pOut);
 93389    break;
 93390  }
 93391  
 93392  /* Opcode: Rowid P1 P2 * * *
 93393  ** Synopsis: r[P2]=rowid
 93394  **
 93395  ** Store in register P2 an integer which is the key of the table entry that
 93396  ** P1 is currently point to.
 93397  **
 93398  ** P1 can be either an ordinary table or a virtual table.  There used to
 93399  ** be a separate OP_VRowid opcode for use with virtual tables, but this
 93400  ** one opcode now works for both table types.
 93401  */
 93402  case OP_Rowid: {                 /* out2 */
 93403    VdbeCursor *pC;
 93404    i64 v;
 93405    sqlite3_vtab *pVtab;
 93406    const sqlite3_module *pModule;
 93407  
 93408    pOut = out2Prerelease(p, pOp);
 93409    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93410    pC = p->apCsr[pOp->p1];
 93411    assert( pC!=0 );
 93412    assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
 93413    if( pC->nullRow ){
 93414      pOut->flags = MEM_Null;
 93415      break;
 93416    }else if( pC->deferredMoveto ){
 93417      v = pC->movetoTarget;
 93418  #ifndef SQLITE_OMIT_VIRTUALTABLE
 93419    }else if( pC->eCurType==CURTYPE_VTAB ){
 93420      assert( pC->uc.pVCur!=0 );
 93421      pVtab = pC->uc.pVCur->pVtab;
 93422      pModule = pVtab->pModule;
 93423      assert( pModule->xRowid );
 93424      rc = pModule->xRowid(pC->uc.pVCur, &v);
 93425      sqlite3VtabImportErrmsg(p, pVtab);
 93426      if( rc ) goto abort_due_to_error;
 93427  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 93428    }else{
 93429      assert( pC->eCurType==CURTYPE_BTREE );
 93430      assert( pC->uc.pCursor!=0 );
 93431      rc = sqlite3VdbeCursorRestore(pC);
 93432      if( rc ) goto abort_due_to_error;
 93433      if( pC->nullRow ){
 93434        pOut->flags = MEM_Null;
 93435        break;
 93436      }
 93437      v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
 93438    }
 93439    pOut->u.i = v;
 93440    break;
 93441  }
 93442  
 93443  /* Opcode: NullRow P1 * * * *
 93444  **
 93445  ** Move the cursor P1 to a null row.  Any OP_Column operations
 93446  ** that occur while the cursor is on the null row will always
 93447  ** write a NULL.
 93448  */
 93449  case OP_NullRow: {
 93450    VdbeCursor *pC;
 93451  
 93452    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93453    pC = p->apCsr[pOp->p1];
 93454    assert( pC!=0 );
 93455    pC->nullRow = 1;
 93456    pC->cacheStatus = CACHE_STALE;
 93457    if( pC->eCurType==CURTYPE_BTREE ){
 93458      assert( pC->uc.pCursor!=0 );
 93459      sqlite3BtreeClearCursor(pC->uc.pCursor);
 93460    }
 93461  #ifdef SQLITE_DEBUG
 93462    if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
 93463  #endif
 93464    break;
 93465  }
 93466  
 93467  /* Opcode: SeekEnd P1 * * * *
 93468  **
 93469  ** Position cursor P1 at the end of the btree for the purpose of
 93470  ** appending a new entry onto the btree.
 93471  **
 93472  ** It is assumed that the cursor is used only for appending and so
 93473  ** if the cursor is valid, then the cursor must already be pointing
 93474  ** at the end of the btree and so no changes are made to
 93475  ** the cursor.
 93476  */
 93477  /* Opcode: Last P1 P2 * * *
 93478  **
 93479  ** The next use of the Rowid or Column or Prev instruction for P1 
 93480  ** will refer to the last entry in the database table or index.
 93481  ** If the table or index is empty and P2>0, then jump immediately to P2.
 93482  ** If P2 is 0 or if the table or index is not empty, fall through
 93483  ** to the following instruction.
 93484  **
 93485  ** This opcode leaves the cursor configured to move in reverse order,
 93486  ** from the end toward the beginning.  In other words, the cursor is
 93487  ** configured to use Prev, not Next.
 93488  */
 93489  case OP_SeekEnd:
 93490  case OP_Last: {        /* jump */
 93491    VdbeCursor *pC;
 93492    BtCursor *pCrsr;
 93493    int res;
 93494  
 93495    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93496    pC = p->apCsr[pOp->p1];
 93497    assert( pC!=0 );
 93498    assert( pC->eCurType==CURTYPE_BTREE );
 93499    pCrsr = pC->uc.pCursor;
 93500    res = 0;
 93501    assert( pCrsr!=0 );
 93502  #ifdef SQLITE_DEBUG
 93503    pC->seekOp = pOp->opcode;
 93504  #endif
 93505    if( pOp->opcode==OP_SeekEnd ){
 93506      assert( pOp->p2==0 );
 93507      pC->seekResult = -1;
 93508      if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
 93509        break;
 93510      }
 93511    }
 93512    rc = sqlite3BtreeLast(pCrsr, &res);
 93513    pC->nullRow = (u8)res;
 93514    pC->deferredMoveto = 0;
 93515    pC->cacheStatus = CACHE_STALE;
 93516    if( rc ) goto abort_due_to_error;
 93517    if( pOp->p2>0 ){
 93518      VdbeBranchTaken(res!=0,2);
 93519      if( res ) goto jump_to_p2;
 93520    }
 93521    break;
 93522  }
 93523  
 93524  /* Opcode: IfSmaller P1 P2 P3 * *
 93525  **
 93526  ** Estimate the number of rows in the table P1.  Jump to P2 if that
 93527  ** estimate is less than approximately 2**(0.1*P3).
 93528  */
 93529  case OP_IfSmaller: {        /* jump */
 93530    VdbeCursor *pC;
 93531    BtCursor *pCrsr;
 93532    int res;
 93533    i64 sz;
 93534  
 93535    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93536    pC = p->apCsr[pOp->p1];
 93537    assert( pC!=0 );
 93538    pCrsr = pC->uc.pCursor;
 93539    assert( pCrsr );
 93540    rc = sqlite3BtreeFirst(pCrsr, &res);
 93541    if( rc ) goto abort_due_to_error;
 93542    if( res==0 ){
 93543      sz = sqlite3BtreeRowCountEst(pCrsr);
 93544      if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
 93545    }
 93546    VdbeBranchTaken(res!=0,2);
 93547    if( res ) goto jump_to_p2;
 93548    break;
 93549  }
 93550  
 93551  
 93552  /* Opcode: SorterSort P1 P2 * * *
 93553  **
 93554  ** After all records have been inserted into the Sorter object
 93555  ** identified by P1, invoke this opcode to actually do the sorting.
 93556  ** Jump to P2 if there are no records to be sorted.
 93557  **
 93558  ** This opcode is an alias for OP_Sort and OP_Rewind that is used
 93559  ** for Sorter objects.
 93560  */
 93561  /* Opcode: Sort P1 P2 * * *
 93562  **
 93563  ** This opcode does exactly the same thing as OP_Rewind except that
 93564  ** it increments an undocumented global variable used for testing.
 93565  **
 93566  ** Sorting is accomplished by writing records into a sorting index,
 93567  ** then rewinding that index and playing it back from beginning to
 93568  ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
 93569  ** rewinding so that the global variable will be incremented and
 93570  ** regression tests can determine whether or not the optimizer is
 93571  ** correctly optimizing out sorts.
 93572  */
 93573  case OP_SorterSort:    /* jump */
 93574  case OP_Sort: {        /* jump */
 93575  #ifdef SQLITE_TEST
 93576    sqlite3_sort_count++;
 93577    sqlite3_search_count--;
 93578  #endif
 93579    p->aCounter[SQLITE_STMTSTATUS_SORT]++;
 93580    /* Fall through into OP_Rewind */
 93581  }
 93582  /* Opcode: Rewind P1 P2 * * P5
 93583  **
 93584  ** The next use of the Rowid or Column or Next instruction for P1 
 93585  ** will refer to the first entry in the database table or index.
 93586  ** If the table or index is empty, jump immediately to P2.
 93587  ** If the table or index is not empty, fall through to the following 
 93588  ** instruction.
 93589  **
 93590  ** If P5 is non-zero and the table is not empty, then the "skip-next"
 93591  ** flag is set on the cursor so that the next OP_Next instruction 
 93592  ** executed on it is a no-op.
 93593  **
 93594  ** This opcode leaves the cursor configured to move in forward order,
 93595  ** from the beginning toward the end.  In other words, the cursor is
 93596  ** configured to use Next, not Prev.
 93597  */
 93598  case OP_Rewind: {        /* jump */
 93599    VdbeCursor *pC;
 93600    BtCursor *pCrsr;
 93601    int res;
 93602  
 93603    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93604    pC = p->apCsr[pOp->p1];
 93605    assert( pC!=0 );
 93606    assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
 93607    res = 1;
 93608  #ifdef SQLITE_DEBUG
 93609    pC->seekOp = OP_Rewind;
 93610  #endif
 93611    if( isSorter(pC) ){
 93612      rc = sqlite3VdbeSorterRewind(pC, &res);
 93613    }else{
 93614      assert( pC->eCurType==CURTYPE_BTREE );
 93615      pCrsr = pC->uc.pCursor;
 93616      assert( pCrsr );
 93617      rc = sqlite3BtreeFirst(pCrsr, &res);
 93618  #ifndef SQLITE_OMIT_WINDOWFUNC
 93619      if( pOp->p5 ) sqlite3BtreeSkipNext(pCrsr);
 93620  #endif
 93621      pC->deferredMoveto = 0;
 93622      pC->cacheStatus = CACHE_STALE;
 93623    }
 93624    if( rc ) goto abort_due_to_error;
 93625    pC->nullRow = (u8)res;
 93626    assert( pOp->p2>0 && pOp->p2<p->nOp );
 93627    VdbeBranchTaken(res!=0,2);
 93628    if( res ) goto jump_to_p2;
 93629    break;
 93630  }
 93631  
 93632  /* Opcode: Next P1 P2 P3 P4 P5
 93633  **
 93634  ** Advance cursor P1 so that it points to the next key/data pair in its
 93635  ** table or index.  If there are no more key/value pairs then fall through
 93636  ** to the following instruction.  But if the cursor advance was successful,
 93637  ** jump immediately to P2.
 93638  **
 93639  ** The Next opcode is only valid following an SeekGT, SeekGE, or
 93640  ** OP_Rewind opcode used to position the cursor.  Next is not allowed
 93641  ** to follow SeekLT, SeekLE, or OP_Last.
 93642  **
 93643  ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
 93644  ** been opened prior to this opcode or the program will segfault.
 93645  **
 93646  ** The P3 value is a hint to the btree implementation. If P3==1, that
 93647  ** means P1 is an SQL index and that this instruction could have been
 93648  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
 93649  ** always either 0 or 1.
 93650  **
 93651  ** P4 is always of type P4_ADVANCE. The function pointer points to
 93652  ** sqlite3BtreeNext().
 93653  **
 93654  ** If P5 is positive and the jump is taken, then event counter
 93655  ** number P5-1 in the prepared statement is incremented.
 93656  **
 93657  ** See also: Prev
 93658  */
 93659  /* Opcode: Prev P1 P2 P3 P4 P5
 93660  **
 93661  ** Back up cursor P1 so that it points to the previous key/data pair in its
 93662  ** table or index.  If there is no previous key/value pairs then fall through
 93663  ** to the following instruction.  But if the cursor backup was successful,
 93664  ** jump immediately to P2.
 93665  **
 93666  **
 93667  ** The Prev opcode is only valid following an SeekLT, SeekLE, or
 93668  ** OP_Last opcode used to position the cursor.  Prev is not allowed
 93669  ** to follow SeekGT, SeekGE, or OP_Rewind.
 93670  **
 93671  ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
 93672  ** not open then the behavior is undefined.
 93673  **
 93674  ** The P3 value is a hint to the btree implementation. If P3==1, that
 93675  ** means P1 is an SQL index and that this instruction could have been
 93676  ** omitted if that index had been unique.  P3 is usually 0.  P3 is
 93677  ** always either 0 or 1.
 93678  **
 93679  ** P4 is always of type P4_ADVANCE. The function pointer points to
 93680  ** sqlite3BtreePrevious().
 93681  **
 93682  ** If P5 is positive and the jump is taken, then event counter
 93683  ** number P5-1 in the prepared statement is incremented.
 93684  */
 93685  /* Opcode: SorterNext P1 P2 * * P5
 93686  **
 93687  ** This opcode works just like OP_Next except that P1 must be a
 93688  ** sorter object for which the OP_SorterSort opcode has been
 93689  ** invoked.  This opcode advances the cursor to the next sorted
 93690  ** record, or jumps to P2 if there are no more sorted records.
 93691  */
 93692  case OP_SorterNext: {  /* jump */
 93693    VdbeCursor *pC;
 93694  
 93695    pC = p->apCsr[pOp->p1];
 93696    assert( isSorter(pC) );
 93697    rc = sqlite3VdbeSorterNext(db, pC);
 93698    goto next_tail;
 93699  case OP_Prev:          /* jump */
 93700  case OP_Next:          /* jump */
 93701    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93702    assert( pOp->p5<ArraySize(p->aCounter) );
 93703    pC = p->apCsr[pOp->p1];
 93704    assert( pC!=0 );
 93705    assert( pC->deferredMoveto==0 );
 93706    assert( pC->eCurType==CURTYPE_BTREE );
 93707    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
 93708    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
 93709  
 93710    /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
 93711    ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
 93712    assert( pOp->opcode!=OP_Next
 93713         || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
 93714         || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found 
 93715         || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid);
 93716    assert( pOp->opcode!=OP_Prev
 93717         || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
 93718         || pC->seekOp==OP_Last 
 93719         || pC->seekOp==OP_NullRow);
 93720  
 93721    rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
 93722  next_tail:
 93723    pC->cacheStatus = CACHE_STALE;
 93724    VdbeBranchTaken(rc==SQLITE_OK,2);
 93725    if( rc==SQLITE_OK ){
 93726      pC->nullRow = 0;
 93727      p->aCounter[pOp->p5]++;
 93728  #ifdef SQLITE_TEST
 93729      sqlite3_search_count++;
 93730  #endif
 93731      goto jump_to_p2_and_check_for_interrupt;
 93732    }
 93733    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
 93734    rc = SQLITE_OK;
 93735    pC->nullRow = 1;
 93736    goto check_for_interrupt;
 93737  }
 93738  
 93739  /* Opcode: IdxInsert P1 P2 P3 P4 P5
 93740  ** Synopsis: key=r[P2]
 93741  **
 93742  ** Register P2 holds an SQL index key made using the
 93743  ** MakeRecord instructions.  This opcode writes that key
 93744  ** into the index P1.  Data for the entry is nil.
 93745  **
 93746  ** If P4 is not zero, then it is the number of values in the unpacked
 93747  ** key of reg(P2).  In that case, P3 is the index of the first register
 93748  ** for the unpacked key.  The availability of the unpacked key can sometimes
 93749  ** be an optimization.
 93750  **
 93751  ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
 93752  ** that this insert is likely to be an append.
 93753  **
 93754  ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
 93755  ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
 93756  ** then the change counter is unchanged.
 93757  **
 93758  ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
 93759  ** run faster by avoiding an unnecessary seek on cursor P1.  However,
 93760  ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
 93761  ** seeks on the cursor or if the most recent seek used a key equivalent
 93762  ** to P2. 
 93763  **
 93764  ** This instruction only works for indices.  The equivalent instruction
 93765  ** for tables is OP_Insert.
 93766  */
 93767  /* Opcode: SorterInsert P1 P2 * * *
 93768  ** Synopsis: key=r[P2]
 93769  **
 93770  ** Register P2 holds an SQL index key made using the
 93771  ** MakeRecord instructions.  This opcode writes that key
 93772  ** into the sorter P1.  Data for the entry is nil.
 93773  */
 93774  case OP_SorterInsert:       /* in2 */
 93775  case OP_IdxInsert: {        /* in2 */
 93776    VdbeCursor *pC;
 93777    BtreePayload x;
 93778  
 93779    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93780    pC = p->apCsr[pOp->p1];
 93781    sqlite3VdbeIncrWriteCounter(p, pC);
 93782    assert( pC!=0 );
 93783    assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
 93784    pIn2 = &aMem[pOp->p2];
 93785    assert( pIn2->flags & MEM_Blob );
 93786    if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
 93787    assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
 93788    assert( pC->isTable==0 );
 93789    rc = ExpandBlob(pIn2);
 93790    if( rc ) goto abort_due_to_error;
 93791    if( pOp->opcode==OP_SorterInsert ){
 93792      rc = sqlite3VdbeSorterWrite(pC, pIn2);
 93793    }else{
 93794      x.nKey = pIn2->n;
 93795      x.pKey = pIn2->z;
 93796      x.aMem = aMem + pOp->p3;
 93797      x.nMem = (u16)pOp->p4.i;
 93798      rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
 93799           (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), 
 93800          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
 93801          );
 93802      assert( pC->deferredMoveto==0 );
 93803      pC->cacheStatus = CACHE_STALE;
 93804    }
 93805    if( rc) goto abort_due_to_error;
 93806    break;
 93807  }
 93808  
 93809  /* Opcode: IdxDelete P1 P2 P3 * *
 93810  ** Synopsis: key=r[P2@P3]
 93811  **
 93812  ** The content of P3 registers starting at register P2 form
 93813  ** an unpacked index key. This opcode removes that entry from the 
 93814  ** index opened by cursor P1.
 93815  */
 93816  case OP_IdxDelete: {
 93817    VdbeCursor *pC;
 93818    BtCursor *pCrsr;
 93819    int res;
 93820    UnpackedRecord r;
 93821  
 93822    assert( pOp->p3>0 );
 93823    assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
 93824    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93825    pC = p->apCsr[pOp->p1];
 93826    assert( pC!=0 );
 93827    assert( pC->eCurType==CURTYPE_BTREE );
 93828    sqlite3VdbeIncrWriteCounter(p, pC);
 93829    pCrsr = pC->uc.pCursor;
 93830    assert( pCrsr!=0 );
 93831    assert( pOp->p5==0 );
 93832    r.pKeyInfo = pC->pKeyInfo;
 93833    r.nField = (u16)pOp->p3;
 93834    r.default_rc = 0;
 93835    r.aMem = &aMem[pOp->p2];
 93836    rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
 93837    if( rc ) goto abort_due_to_error;
 93838    if( res==0 ){
 93839      rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
 93840      if( rc ) goto abort_due_to_error;
 93841    }
 93842    assert( pC->deferredMoveto==0 );
 93843    pC->cacheStatus = CACHE_STALE;
 93844    pC->seekResult = 0;
 93845    break;
 93846  }
 93847  
 93848  /* Opcode: DeferredSeek P1 * P3 P4 *
 93849  ** Synopsis: Move P3 to P1.rowid if needed
 93850  **
 93851  ** P1 is an open index cursor and P3 is a cursor on the corresponding
 93852  ** table.  This opcode does a deferred seek of the P3 table cursor
 93853  ** to the row that corresponds to the current row of P1.
 93854  **
 93855  ** This is a deferred seek.  Nothing actually happens until
 93856  ** the cursor is used to read a record.  That way, if no reads
 93857  ** occur, no unnecessary I/O happens.
 93858  **
 93859  ** P4 may be an array of integers (type P4_INTARRAY) containing
 93860  ** one entry for each column in the P3 table.  If array entry a(i)
 93861  ** is non-zero, then reading column a(i)-1 from cursor P3 is 
 93862  ** equivalent to performing the deferred seek and then reading column i 
 93863  ** from P1.  This information is stored in P3 and used to redirect
 93864  ** reads against P3 over to P1, thus possibly avoiding the need to
 93865  ** seek and read cursor P3.
 93866  */
 93867  /* Opcode: IdxRowid P1 P2 * * *
 93868  ** Synopsis: r[P2]=rowid
 93869  **
 93870  ** Write into register P2 an integer which is the last entry in the record at
 93871  ** the end of the index key pointed to by cursor P1.  This integer should be
 93872  ** the rowid of the table entry to which this index entry points.
 93873  **
 93874  ** See also: Rowid, MakeRecord.
 93875  */
 93876  case OP_DeferredSeek:
 93877  case OP_IdxRowid: {           /* out2 */
 93878    VdbeCursor *pC;             /* The P1 index cursor */
 93879    VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
 93880    i64 rowid;                  /* Rowid that P1 current points to */
 93881  
 93882    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93883    pC = p->apCsr[pOp->p1];
 93884    assert( pC!=0 );
 93885    assert( pC->eCurType==CURTYPE_BTREE );
 93886    assert( pC->uc.pCursor!=0 );
 93887    assert( pC->isTable==0 );
 93888    assert( pC->deferredMoveto==0 );
 93889    assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
 93890  
 93891    /* The IdxRowid and Seek opcodes are combined because of the commonality
 93892    ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
 93893    rc = sqlite3VdbeCursorRestore(pC);
 93894  
 93895    /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
 93896    ** out from under the cursor.  That will never happens for an IdxRowid
 93897    ** or Seek opcode */
 93898    if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
 93899  
 93900    if( !pC->nullRow ){
 93901      rowid = 0;  /* Not needed.  Only used to silence a warning. */
 93902      rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
 93903      if( rc!=SQLITE_OK ){
 93904        goto abort_due_to_error;
 93905      }
 93906      if( pOp->opcode==OP_DeferredSeek ){
 93907        assert( pOp->p3>=0 && pOp->p3<p->nCursor );
 93908        pTabCur = p->apCsr[pOp->p3];
 93909        assert( pTabCur!=0 );
 93910        assert( pTabCur->eCurType==CURTYPE_BTREE );
 93911        assert( pTabCur->uc.pCursor!=0 );
 93912        assert( pTabCur->isTable );
 93913        pTabCur->nullRow = 0;
 93914        pTabCur->movetoTarget = rowid;
 93915        pTabCur->deferredMoveto = 1;
 93916        assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
 93917        pTabCur->aAltMap = pOp->p4.ai;
 93918        pTabCur->pAltCursor = pC;
 93919      }else{
 93920        pOut = out2Prerelease(p, pOp);
 93921        pOut->u.i = rowid;
 93922      }
 93923    }else{
 93924      assert( pOp->opcode==OP_IdxRowid );
 93925      sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
 93926    }
 93927    break;
 93928  }
 93929  
 93930  /* Opcode: IdxGE P1 P2 P3 P4 P5
 93931  ** Synopsis: key=r[P3@P4]
 93932  **
 93933  ** The P4 register values beginning with P3 form an unpacked index 
 93934  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
 93935  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 93936  ** fields at the end.
 93937  **
 93938  ** If the P1 index entry is greater than or equal to the key value
 93939  ** then jump to P2.  Otherwise fall through to the next instruction.
 93940  */
 93941  /* Opcode: IdxGT P1 P2 P3 P4 P5
 93942  ** Synopsis: key=r[P3@P4]
 93943  **
 93944  ** The P4 register values beginning with P3 form an unpacked index 
 93945  ** key that omits the PRIMARY KEY.  Compare this key value against the index 
 93946  ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
 93947  ** fields at the end.
 93948  **
 93949  ** If the P1 index entry is greater than the key value
 93950  ** then jump to P2.  Otherwise fall through to the next instruction.
 93951  */
 93952  /* Opcode: IdxLT P1 P2 P3 P4 P5
 93953  ** Synopsis: key=r[P3@P4]
 93954  **
 93955  ** The P4 register values beginning with P3 form an unpacked index 
 93956  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 93957  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 93958  ** ROWID on the P1 index.
 93959  **
 93960  ** If the P1 index entry is less than the key value then jump to P2.
 93961  ** Otherwise fall through to the next instruction.
 93962  */
 93963  /* Opcode: IdxLE P1 P2 P3 P4 P5
 93964  ** Synopsis: key=r[P3@P4]
 93965  **
 93966  ** The P4 register values beginning with P3 form an unpacked index 
 93967  ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 93968  ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 93969  ** ROWID on the P1 index.
 93970  **
 93971  ** If the P1 index entry is less than or equal to the key value then jump
 93972  ** to P2. Otherwise fall through to the next instruction.
 93973  */
 93974  case OP_IdxLE:          /* jump */
 93975  case OP_IdxGT:          /* jump */
 93976  case OP_IdxLT:          /* jump */
 93977  case OP_IdxGE:  {       /* jump */
 93978    VdbeCursor *pC;
 93979    int res;
 93980    UnpackedRecord r;
 93981  
 93982    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 93983    pC = p->apCsr[pOp->p1];
 93984    assert( pC!=0 );
 93985    assert( pC->isOrdered );
 93986    assert( pC->eCurType==CURTYPE_BTREE );
 93987    assert( pC->uc.pCursor!=0);
 93988    assert( pC->deferredMoveto==0 );
 93989    assert( pOp->p5==0 || pOp->p5==1 );
 93990    assert( pOp->p4type==P4_INT32 );
 93991    r.pKeyInfo = pC->pKeyInfo;
 93992    r.nField = (u16)pOp->p4.i;
 93993    if( pOp->opcode<OP_IdxLT ){
 93994      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
 93995      r.default_rc = -1;
 93996    }else{
 93997      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
 93998      r.default_rc = 0;
 93999    }
 94000    r.aMem = &aMem[pOp->p3];
 94001  #ifdef SQLITE_DEBUG
 94002    {
 94003      int i;
 94004      for(i=0; i<r.nField; i++){
 94005        assert( memIsValid(&r.aMem[i]) );
 94006        REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
 94007      }
 94008    }
 94009  #endif
 94010    res = 0;  /* Not needed.  Only used to silence a warning. */
 94011    rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
 94012    assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
 94013    if( (pOp->opcode&1)==(OP_IdxLT&1) ){
 94014      assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
 94015      res = -res;
 94016    }else{
 94017      assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
 94018      res++;
 94019    }
 94020    VdbeBranchTaken(res>0,2);
 94021    if( rc ) goto abort_due_to_error;
 94022    if( res>0 ) goto jump_to_p2;
 94023    break;
 94024  }
 94025  
 94026  /* Opcode: Destroy P1 P2 P3 * *
 94027  **
 94028  ** Delete an entire database table or index whose root page in the database
 94029  ** file is given by P1.
 94030  **
 94031  ** The table being destroyed is in the main database file if P3==0.  If
 94032  ** P3==1 then the table to be clear is in the auxiliary database file
 94033  ** that is used to store tables create using CREATE TEMPORARY TABLE.
 94034  **
 94035  ** If AUTOVACUUM is enabled then it is possible that another root page
 94036  ** might be moved into the newly deleted root page in order to keep all
 94037  ** root pages contiguous at the beginning of the database.  The former
 94038  ** value of the root page that moved - its value before the move occurred -
 94039  ** is stored in register P2. If no page movement was required (because the
 94040  ** table being dropped was already the last one in the database) then a 
 94041  ** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero 
 94042  ** is stored in register P2.
 94043  **
 94044  ** This opcode throws an error if there are any active reader VMs when
 94045  ** it is invoked. This is done to avoid the difficulty associated with 
 94046  ** updating existing cursors when a root page is moved in an AUTOVACUUM 
 94047  ** database. This error is thrown even if the database is not an AUTOVACUUM 
 94048  ** db in order to avoid introducing an incompatibility between autovacuum 
 94049  ** and non-autovacuum modes.
 94050  **
 94051  ** See also: Clear
 94052  */
 94053  case OP_Destroy: {     /* out2 */
 94054    int iMoved;
 94055    int iDb;
 94056  
 94057    sqlite3VdbeIncrWriteCounter(p, 0);
 94058    assert( p->readOnly==0 );
 94059    assert( pOp->p1>1 );
 94060    pOut = out2Prerelease(p, pOp);
 94061    pOut->flags = MEM_Null;
 94062    if( db->nVdbeRead > db->nVDestroy+1 ){
 94063      rc = SQLITE_LOCKED;
 94064      p->errorAction = OE_Abort;
 94065      goto abort_due_to_error;
 94066    }else{
 94067      iDb = pOp->p3;
 94068      assert( DbMaskTest(p->btreeMask, iDb) );
 94069      iMoved = 0;  /* Not needed.  Only to silence a warning. */
 94070      rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
 94071      pOut->flags = MEM_Int;
 94072      pOut->u.i = iMoved;
 94073      if( rc ) goto abort_due_to_error;
 94074  #ifndef SQLITE_OMIT_AUTOVACUUM
 94075      if( iMoved!=0 ){
 94076        sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
 94077        /* All OP_Destroy operations occur on the same btree */
 94078        assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
 94079        resetSchemaOnFault = iDb+1;
 94080      }
 94081  #endif
 94082    }
 94083    break;
 94084  }
 94085  
 94086  /* Opcode: Clear P1 P2 P3
 94087  **
 94088  ** Delete all contents of the database table or index whose root page
 94089  ** in the database file is given by P1.  But, unlike Destroy, do not
 94090  ** remove the table or index from the database file.
 94091  **
 94092  ** The table being clear is in the main database file if P2==0.  If
 94093  ** P2==1 then the table to be clear is in the auxiliary database file
 94094  ** that is used to store tables create using CREATE TEMPORARY TABLE.
 94095  **
 94096  ** If the P3 value is non-zero, then the table referred to must be an
 94097  ** intkey table (an SQL table, not an index). In this case the row change 
 94098  ** count is incremented by the number of rows in the table being cleared. 
 94099  ** If P3 is greater than zero, then the value stored in register P3 is
 94100  ** also incremented by the number of rows in the table being cleared.
 94101  **
 94102  ** See also: Destroy
 94103  */
 94104  case OP_Clear: {
 94105    int nChange;
 94106   
 94107    sqlite3VdbeIncrWriteCounter(p, 0);
 94108    nChange = 0;
 94109    assert( p->readOnly==0 );
 94110    assert( DbMaskTest(p->btreeMask, pOp->p2) );
 94111    rc = sqlite3BtreeClearTable(
 94112        db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
 94113    );
 94114    if( pOp->p3 ){
 94115      p->nChange += nChange;
 94116      if( pOp->p3>0 ){
 94117        assert( memIsValid(&aMem[pOp->p3]) );
 94118        memAboutToChange(p, &aMem[pOp->p3]);
 94119        aMem[pOp->p3].u.i += nChange;
 94120      }
 94121    }
 94122    if( rc ) goto abort_due_to_error;
 94123    break;
 94124  }
 94125  
 94126  /* Opcode: ResetSorter P1 * * * *
 94127  **
 94128  ** Delete all contents from the ephemeral table or sorter
 94129  ** that is open on cursor P1.
 94130  **
 94131  ** This opcode only works for cursors used for sorting and
 94132  ** opened with OP_OpenEphemeral or OP_SorterOpen.
 94133  */
 94134  case OP_ResetSorter: {
 94135    VdbeCursor *pC;
 94136   
 94137    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 94138    pC = p->apCsr[pOp->p1];
 94139    assert( pC!=0 );
 94140    if( isSorter(pC) ){
 94141      sqlite3VdbeSorterReset(db, pC->uc.pSorter);
 94142    }else{
 94143      assert( pC->eCurType==CURTYPE_BTREE );
 94144      assert( pC->isEphemeral );
 94145      rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
 94146      if( rc ) goto abort_due_to_error;
 94147    }
 94148    break;
 94149  }
 94150  
 94151  /* Opcode: CreateBtree P1 P2 P3 * *
 94152  ** Synopsis: r[P2]=root iDb=P1 flags=P3
 94153  **
 94154  ** Allocate a new b-tree in the main database file if P1==0 or in the
 94155  ** TEMP database file if P1==1 or in an attached database if
 94156  ** P1>1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
 94157  ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
 94158  ** The root page number of the new b-tree is stored in register P2.
 94159  */
 94160  case OP_CreateBtree: {          /* out2 */
 94161    int pgno;
 94162    Db *pDb;
 94163  
 94164    sqlite3VdbeIncrWriteCounter(p, 0);
 94165    pOut = out2Prerelease(p, pOp);
 94166    pgno = 0;
 94167    assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
 94168    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 94169    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 94170    assert( p->readOnly==0 );
 94171    pDb = &db->aDb[pOp->p1];
 94172    assert( pDb->pBt!=0 );
 94173    rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
 94174    if( rc ) goto abort_due_to_error;
 94175    pOut->u.i = pgno;
 94176    break;
 94177  }
 94178  
 94179  /* Opcode: SqlExec * * * P4 *
 94180  **
 94181  ** Run the SQL statement or statements specified in the P4 string.
 94182  */
 94183  case OP_SqlExec: {
 94184    sqlite3VdbeIncrWriteCounter(p, 0);
 94185    db->nSqlExec++;
 94186    rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
 94187    db->nSqlExec--;
 94188    if( rc ) goto abort_due_to_error;
 94189    break;
 94190  }
 94191  
 94192  /* Opcode: ParseSchema P1 * * P4 *
 94193  **
 94194  ** Read and parse all entries from the SQLITE_MASTER table of database P1
 94195  ** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
 94196  ** entire schema for P1 is reparsed.
 94197  **
 94198  ** This opcode invokes the parser to create a new virtual machine,
 94199  ** then runs the new virtual machine.  It is thus a re-entrant opcode.
 94200  */
 94201  case OP_ParseSchema: {
 94202    int iDb;
 94203    const char *zMaster;
 94204    char *zSql;
 94205    InitData initData;
 94206  
 94207    /* Any prepared statement that invokes this opcode will hold mutexes
 94208    ** on every btree.  This is a prerequisite for invoking 
 94209    ** sqlite3InitCallback().
 94210    */
 94211  #ifdef SQLITE_DEBUG
 94212    for(iDb=0; iDb<db->nDb; iDb++){
 94213      assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
 94214    }
 94215  #endif
 94216  
 94217    iDb = pOp->p1;
 94218    assert( iDb>=0 && iDb<db->nDb );
 94219    assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
 94220  
 94221  #ifndef SQLITE_OMIT_ALTERTABLE
 94222    if( pOp->p4.z==0 ){
 94223      sqlite3SchemaClear(db->aDb[iDb].pSchema);
 94224      db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
 94225      rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
 94226      db->mDbFlags |= DBFLAG_SchemaChange;
 94227      p->expired = 0;
 94228    }else
 94229  #endif
 94230    {
 94231      zMaster = MASTER_NAME;
 94232      initData.db = db;
 94233      initData.iDb = iDb;
 94234      initData.pzErrMsg = &p->zErrMsg;
 94235      initData.mInitFlags = 0;
 94236      zSql = sqlite3MPrintf(db,
 94237         "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
 94238         db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
 94239      if( zSql==0 ){
 94240        rc = SQLITE_NOMEM_BKPT;
 94241      }else{
 94242        assert( db->init.busy==0 );
 94243        db->init.busy = 1;
 94244        initData.rc = SQLITE_OK;
 94245        initData.nInitRow = 0;
 94246        assert( !db->mallocFailed );
 94247        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
 94248        if( rc==SQLITE_OK ) rc = initData.rc;
 94249        if( rc==SQLITE_OK && initData.nInitRow==0 ){
 94250          /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
 94251          ** at least one SQL statement. Any less than that indicates that
 94252          ** the sqlite_master table is corrupt. */
 94253          rc = SQLITE_CORRUPT_BKPT;
 94254        }
 94255        sqlite3DbFreeNN(db, zSql);
 94256        db->init.busy = 0;
 94257      }
 94258    }
 94259    if( rc ){
 94260      sqlite3ResetAllSchemasOfConnection(db);
 94261      if( rc==SQLITE_NOMEM ){
 94262        goto no_mem;
 94263      }
 94264      goto abort_due_to_error;
 94265    }
 94266    break;  
 94267  }
 94268  
 94269  #if !defined(SQLITE_OMIT_ANALYZE)
 94270  /* Opcode: LoadAnalysis P1 * * * *
 94271  **
 94272  ** Read the sqlite_stat1 table for database P1 and load the content
 94273  ** of that table into the internal index hash table.  This will cause
 94274  ** the analysis to be used when preparing all subsequent queries.
 94275  */
 94276  case OP_LoadAnalysis: {
 94277    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 94278    rc = sqlite3AnalysisLoad(db, pOp->p1);
 94279    if( rc ) goto abort_due_to_error;
 94280    break;  
 94281  }
 94282  #endif /* !defined(SQLITE_OMIT_ANALYZE) */
 94283  
 94284  /* Opcode: DropTable P1 * * P4 *
 94285  **
 94286  ** Remove the internal (in-memory) data structures that describe
 94287  ** the table named P4 in database P1.  This is called after a table
 94288  ** is dropped from disk (using the Destroy opcode) in order to keep 
 94289  ** the internal representation of the
 94290  ** schema consistent with what is on disk.
 94291  */
 94292  case OP_DropTable: {
 94293    sqlite3VdbeIncrWriteCounter(p, 0);
 94294    sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
 94295    break;
 94296  }
 94297  
 94298  /* Opcode: DropIndex P1 * * P4 *
 94299  **
 94300  ** Remove the internal (in-memory) data structures that describe
 94301  ** the index named P4 in database P1.  This is called after an index
 94302  ** is dropped from disk (using the Destroy opcode)
 94303  ** in order to keep the internal representation of the
 94304  ** schema consistent with what is on disk.
 94305  */
 94306  case OP_DropIndex: {
 94307    sqlite3VdbeIncrWriteCounter(p, 0);
 94308    sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
 94309    break;
 94310  }
 94311  
 94312  /* Opcode: DropTrigger P1 * * P4 *
 94313  **
 94314  ** Remove the internal (in-memory) data structures that describe
 94315  ** the trigger named P4 in database P1.  This is called after a trigger
 94316  ** is dropped from disk (using the Destroy opcode) in order to keep 
 94317  ** the internal representation of the
 94318  ** schema consistent with what is on disk.
 94319  */
 94320  case OP_DropTrigger: {
 94321    sqlite3VdbeIncrWriteCounter(p, 0);
 94322    sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
 94323    break;
 94324  }
 94325  
 94326  
 94327  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 94328  /* Opcode: IntegrityCk P1 P2 P3 P4 P5
 94329  **
 94330  ** Do an analysis of the currently open database.  Store in
 94331  ** register P1 the text of an error message describing any problems.
 94332  ** If no problems are found, store a NULL in register P1.
 94333  **
 94334  ** The register P3 contains one less than the maximum number of allowed errors.
 94335  ** At most reg(P3) errors will be reported.
 94336  ** In other words, the analysis stops as soon as reg(P1) errors are 
 94337  ** seen.  Reg(P1) is updated with the number of errors remaining.
 94338  **
 94339  ** The root page numbers of all tables in the database are integers
 94340  ** stored in P4_INTARRAY argument.
 94341  **
 94342  ** If P5 is not zero, the check is done on the auxiliary database
 94343  ** file, not the main database file.
 94344  **
 94345  ** This opcode is used to implement the integrity_check pragma.
 94346  */
 94347  case OP_IntegrityCk: {
 94348    int nRoot;      /* Number of tables to check.  (Number of root pages.) */
 94349    int *aRoot;     /* Array of rootpage numbers for tables to be checked */
 94350    int nErr;       /* Number of errors reported */
 94351    char *z;        /* Text of the error report */
 94352    Mem *pnErr;     /* Register keeping track of errors remaining */
 94353  
 94354    assert( p->bIsReader );
 94355    nRoot = pOp->p2;
 94356    aRoot = pOp->p4.ai;
 94357    assert( nRoot>0 );
 94358    assert( aRoot[0]==nRoot );
 94359    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 94360    pnErr = &aMem[pOp->p3];
 94361    assert( (pnErr->flags & MEM_Int)!=0 );
 94362    assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
 94363    pIn1 = &aMem[pOp->p1];
 94364    assert( pOp->p5<db->nDb );
 94365    assert( DbMaskTest(p->btreeMask, pOp->p5) );
 94366    z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
 94367                                   (int)pnErr->u.i+1, &nErr);
 94368    sqlite3VdbeMemSetNull(pIn1);
 94369    if( nErr==0 ){
 94370      assert( z==0 );
 94371    }else if( z==0 ){
 94372      goto no_mem;
 94373    }else{
 94374      pnErr->u.i -= nErr-1;
 94375      sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
 94376    }
 94377    UPDATE_MAX_BLOBSIZE(pIn1);
 94378    sqlite3VdbeChangeEncoding(pIn1, encoding);
 94379    break;
 94380  }
 94381  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 94382  
 94383  /* Opcode: RowSetAdd P1 P2 * * *
 94384  ** Synopsis: rowset(P1)=r[P2]
 94385  **
 94386  ** Insert the integer value held by register P2 into a RowSet object
 94387  ** held in register P1.
 94388  **
 94389  ** An assertion fails if P2 is not an integer.
 94390  */
 94391  case OP_RowSetAdd: {       /* in1, in2 */
 94392    pIn1 = &aMem[pOp->p1];
 94393    pIn2 = &aMem[pOp->p2];
 94394    assert( (pIn2->flags & MEM_Int)!=0 );
 94395    if( (pIn1->flags & MEM_Blob)==0 ){
 94396      if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
 94397    }
 94398    assert( sqlite3VdbeMemIsRowSet(pIn1) );
 94399    sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
 94400    break;
 94401  }
 94402  
 94403  /* Opcode: RowSetRead P1 P2 P3 * *
 94404  ** Synopsis: r[P3]=rowset(P1)
 94405  **
 94406  ** Extract the smallest value from the RowSet object in P1
 94407  ** and put that value into register P3.
 94408  ** Or, if RowSet object P1 is initially empty, leave P3
 94409  ** unchanged and jump to instruction P2.
 94410  */
 94411  case OP_RowSetRead: {       /* jump, in1, out3 */
 94412    i64 val;
 94413  
 94414    pIn1 = &aMem[pOp->p1];
 94415    assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
 94416    if( (pIn1->flags & MEM_Blob)==0 
 94417     || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
 94418    ){
 94419      /* The boolean index is empty */
 94420      sqlite3VdbeMemSetNull(pIn1);
 94421      VdbeBranchTaken(1,2);
 94422      goto jump_to_p2_and_check_for_interrupt;
 94423    }else{
 94424      /* A value was pulled from the index */
 94425      VdbeBranchTaken(0,2);
 94426      sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
 94427    }
 94428    goto check_for_interrupt;
 94429  }
 94430  
 94431  /* Opcode: RowSetTest P1 P2 P3 P4
 94432  ** Synopsis: if r[P3] in rowset(P1) goto P2
 94433  **
 94434  ** Register P3 is assumed to hold a 64-bit integer value. If register P1
 94435  ** contains a RowSet object and that RowSet object contains
 94436  ** the value held in P3, jump to register P2. Otherwise, insert the
 94437  ** integer in P3 into the RowSet and continue on to the
 94438  ** next opcode.
 94439  **
 94440  ** The RowSet object is optimized for the case where sets of integers
 94441  ** are inserted in distinct phases, which each set contains no duplicates.
 94442  ** Each set is identified by a unique P4 value. The first set
 94443  ** must have P4==0, the final set must have P4==-1, and for all other sets
 94444  ** must have P4>0.
 94445  **
 94446  ** This allows optimizations: (a) when P4==0 there is no need to test
 94447  ** the RowSet object for P3, as it is guaranteed not to contain it,
 94448  ** (b) when P4==-1 there is no need to insert the value, as it will
 94449  ** never be tested for, and (c) when a value that is part of set X is
 94450  ** inserted, there is no need to search to see if the same value was
 94451  ** previously inserted as part of set X (only if it was previously
 94452  ** inserted as part of some other set).
 94453  */
 94454  case OP_RowSetTest: {                     /* jump, in1, in3 */
 94455    int iSet;
 94456    int exists;
 94457  
 94458    pIn1 = &aMem[pOp->p1];
 94459    pIn3 = &aMem[pOp->p3];
 94460    iSet = pOp->p4.i;
 94461    assert( pIn3->flags&MEM_Int );
 94462  
 94463    /* If there is anything other than a rowset object in memory cell P1,
 94464    ** delete it now and initialize P1 with an empty rowset
 94465    */
 94466    if( (pIn1->flags & MEM_Blob)==0 ){
 94467      if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
 94468    }
 94469    assert( sqlite3VdbeMemIsRowSet(pIn1) );
 94470    assert( pOp->p4type==P4_INT32 );
 94471    assert( iSet==-1 || iSet>=0 );
 94472    if( iSet ){
 94473      exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
 94474      VdbeBranchTaken(exists!=0,2);
 94475      if( exists ) goto jump_to_p2;
 94476    }
 94477    if( iSet>=0 ){
 94478      sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
 94479    }
 94480    break;
 94481  }
 94482  
 94483  
 94484  #ifndef SQLITE_OMIT_TRIGGER
 94485  
 94486  /* Opcode: Program P1 P2 P3 P4 P5
 94487  **
 94488  ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
 94489  **
 94490  ** P1 contains the address of the memory cell that contains the first memory 
 94491  ** cell in an array of values used as arguments to the sub-program. P2 
 94492  ** contains the address to jump to if the sub-program throws an IGNORE 
 94493  ** exception using the RAISE() function. Register P3 contains the address 
 94494  ** of a memory cell in this (the parent) VM that is used to allocate the 
 94495  ** memory required by the sub-vdbe at runtime.
 94496  **
 94497  ** P4 is a pointer to the VM containing the trigger program.
 94498  **
 94499  ** If P5 is non-zero, then recursive program invocation is enabled.
 94500  */
 94501  case OP_Program: {        /* jump */
 94502    int nMem;               /* Number of memory registers for sub-program */
 94503    int nByte;              /* Bytes of runtime space required for sub-program */
 94504    Mem *pRt;               /* Register to allocate runtime space */
 94505    Mem *pMem;              /* Used to iterate through memory cells */
 94506    Mem *pEnd;              /* Last memory cell in new array */
 94507    VdbeFrame *pFrame;      /* New vdbe frame to execute in */
 94508    SubProgram *pProgram;   /* Sub-program to execute */
 94509    void *t;                /* Token identifying trigger */
 94510  
 94511    pProgram = pOp->p4.pProgram;
 94512    pRt = &aMem[pOp->p3];
 94513    assert( pProgram->nOp>0 );
 94514    
 94515    /* If the p5 flag is clear, then recursive invocation of triggers is 
 94516    ** disabled for backwards compatibility (p5 is set if this sub-program
 94517    ** is really a trigger, not a foreign key action, and the flag set
 94518    ** and cleared by the "PRAGMA recursive_triggers" command is clear).
 94519    ** 
 94520    ** It is recursive invocation of triggers, at the SQL level, that is 
 94521    ** disabled. In some cases a single trigger may generate more than one 
 94522    ** SubProgram (if the trigger may be executed with more than one different 
 94523    ** ON CONFLICT algorithm). SubProgram structures associated with a
 94524    ** single trigger all have the same value for the SubProgram.token 
 94525    ** variable.  */
 94526    if( pOp->p5 ){
 94527      t = pProgram->token;
 94528      for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
 94529      if( pFrame ) break;
 94530    }
 94531  
 94532    if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
 94533      rc = SQLITE_ERROR;
 94534      sqlite3VdbeError(p, "too many levels of trigger recursion");
 94535      goto abort_due_to_error;
 94536    }
 94537  
 94538    /* Register pRt is used to store the memory required to save the state
 94539    ** of the current program, and the memory required at runtime to execute
 94540    ** the trigger program. If this trigger has been fired before, then pRt 
 94541    ** is already allocated. Otherwise, it must be initialized.  */
 94542    if( (pRt->flags&MEM_Blob)==0 ){
 94543      /* SubProgram.nMem is set to the number of memory cells used by the 
 94544      ** program stored in SubProgram.aOp. As well as these, one memory
 94545      ** cell is required for each cursor used by the program. Set local
 94546      ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
 94547      */
 94548      nMem = pProgram->nMem + pProgram->nCsr;
 94549      assert( nMem>0 );
 94550      if( pProgram->nCsr==0 ) nMem++;
 94551      nByte = ROUND8(sizeof(VdbeFrame))
 94552                + nMem * sizeof(Mem)
 94553                + pProgram->nCsr * sizeof(VdbeCursor*)
 94554                + (pProgram->nOp + 7)/8;
 94555      pFrame = sqlite3DbMallocZero(db, nByte);
 94556      if( !pFrame ){
 94557        goto no_mem;
 94558      }
 94559      sqlite3VdbeMemRelease(pRt);
 94560      pRt->flags = MEM_Blob|MEM_Dyn;
 94561      pRt->z = (char*)pFrame;
 94562      pRt->n = nByte;
 94563      pRt->xDel = sqlite3VdbeFrameMemDel;
 94564  
 94565      pFrame->v = p;
 94566      pFrame->nChildMem = nMem;
 94567      pFrame->nChildCsr = pProgram->nCsr;
 94568      pFrame->pc = (int)(pOp - aOp);
 94569      pFrame->aMem = p->aMem;
 94570      pFrame->nMem = p->nMem;
 94571      pFrame->apCsr = p->apCsr;
 94572      pFrame->nCursor = p->nCursor;
 94573      pFrame->aOp = p->aOp;
 94574      pFrame->nOp = p->nOp;
 94575      pFrame->token = pProgram->token;
 94576  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 94577      pFrame->anExec = p->anExec;
 94578  #endif
 94579  #ifdef SQLITE_DEBUG
 94580      pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
 94581  #endif
 94582  
 94583      pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
 94584      for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
 94585        pMem->flags = MEM_Undefined;
 94586        pMem->db = db;
 94587      }
 94588    }else{
 94589      pFrame = (VdbeFrame*)pRt->z;
 94590      assert( pRt->xDel==sqlite3VdbeFrameMemDel );
 94591      assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
 94592          || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
 94593      assert( pProgram->nCsr==pFrame->nChildCsr );
 94594      assert( (int)(pOp - aOp)==pFrame->pc );
 94595    }
 94596  
 94597    p->nFrame++;
 94598    pFrame->pParent = p->pFrame;
 94599    pFrame->lastRowid = db->lastRowid;
 94600    pFrame->nChange = p->nChange;
 94601    pFrame->nDbChange = p->db->nChange;
 94602    assert( pFrame->pAuxData==0 );
 94603    pFrame->pAuxData = p->pAuxData;
 94604    p->pAuxData = 0;
 94605    p->nChange = 0;
 94606    p->pFrame = pFrame;
 94607    p->aMem = aMem = VdbeFrameMem(pFrame);
 94608    p->nMem = pFrame->nChildMem;
 94609    p->nCursor = (u16)pFrame->nChildCsr;
 94610    p->apCsr = (VdbeCursor **)&aMem[p->nMem];
 94611    pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
 94612    memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
 94613    p->aOp = aOp = pProgram->aOp;
 94614    p->nOp = pProgram->nOp;
 94615  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 94616    p->anExec = 0;
 94617  #endif
 94618  #ifdef SQLITE_DEBUG
 94619    /* Verify that second and subsequent executions of the same trigger do not
 94620    ** try to reuse register values from the first use. */
 94621    {
 94622      int i;
 94623      for(i=0; i<p->nMem; i++){
 94624        aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
 94625        aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */
 94626      }
 94627    }
 94628  #endif
 94629    pOp = &aOp[-1];
 94630  
 94631    break;
 94632  }
 94633  
 94634  /* Opcode: Param P1 P2 * * *
 94635  **
 94636  ** This opcode is only ever present in sub-programs called via the 
 94637  ** OP_Program instruction. Copy a value currently stored in a memory 
 94638  ** cell of the calling (parent) frame to cell P2 in the current frames 
 94639  ** address space. This is used by trigger programs to access the new.* 
 94640  ** and old.* values.
 94641  **
 94642  ** The address of the cell in the parent frame is determined by adding
 94643  ** the value of the P1 argument to the value of the P1 argument to the
 94644  ** calling OP_Program instruction.
 94645  */
 94646  case OP_Param: {           /* out2 */
 94647    VdbeFrame *pFrame;
 94648    Mem *pIn;
 94649    pOut = out2Prerelease(p, pOp);
 94650    pFrame = p->pFrame;
 94651    pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
 94652    sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
 94653    break;
 94654  }
 94655  
 94656  #endif /* #ifndef SQLITE_OMIT_TRIGGER */
 94657  
 94658  #ifndef SQLITE_OMIT_FOREIGN_KEY
 94659  /* Opcode: FkCounter P1 P2 * * *
 94660  ** Synopsis: fkctr[P1]+=P2
 94661  **
 94662  ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
 94663  ** If P1 is non-zero, the database constraint counter is incremented 
 94664  ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
 94665  ** statement counter is incremented (immediate foreign key constraints).
 94666  */
 94667  case OP_FkCounter: {
 94668    if( db->flags & SQLITE_DeferFKs ){
 94669      db->nDeferredImmCons += pOp->p2;
 94670    }else if( pOp->p1 ){
 94671      db->nDeferredCons += pOp->p2;
 94672    }else{
 94673      p->nFkConstraint += pOp->p2;
 94674    }
 94675    break;
 94676  }
 94677  
 94678  /* Opcode: FkIfZero P1 P2 * * *
 94679  ** Synopsis: if fkctr[P1]==0 goto P2
 94680  **
 94681  ** This opcode tests if a foreign key constraint-counter is currently zero.
 94682  ** If so, jump to instruction P2. Otherwise, fall through to the next 
 94683  ** instruction.
 94684  **
 94685  ** If P1 is non-zero, then the jump is taken if the database constraint-counter
 94686  ** is zero (the one that counts deferred constraint violations). If P1 is
 94687  ** zero, the jump is taken if the statement constraint-counter is zero
 94688  ** (immediate foreign key constraint violations).
 94689  */
 94690  case OP_FkIfZero: {         /* jump */
 94691    if( pOp->p1 ){
 94692      VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
 94693      if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
 94694    }else{
 94695      VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
 94696      if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
 94697    }
 94698    break;
 94699  }
 94700  #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
 94701  
 94702  #ifndef SQLITE_OMIT_AUTOINCREMENT
 94703  /* Opcode: MemMax P1 P2 * * *
 94704  ** Synopsis: r[P1]=max(r[P1],r[P2])
 94705  **
 94706  ** P1 is a register in the root frame of this VM (the root frame is
 94707  ** different from the current frame if this instruction is being executed
 94708  ** within a sub-program). Set the value of register P1 to the maximum of 
 94709  ** its current value and the value in register P2.
 94710  **
 94711  ** This instruction throws an error if the memory cell is not initially
 94712  ** an integer.
 94713  */
 94714  case OP_MemMax: {        /* in2 */
 94715    VdbeFrame *pFrame;
 94716    if( p->pFrame ){
 94717      for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
 94718      pIn1 = &pFrame->aMem[pOp->p1];
 94719    }else{
 94720      pIn1 = &aMem[pOp->p1];
 94721    }
 94722    assert( memIsValid(pIn1) );
 94723    sqlite3VdbeMemIntegerify(pIn1);
 94724    pIn2 = &aMem[pOp->p2];
 94725    sqlite3VdbeMemIntegerify(pIn2);
 94726    if( pIn1->u.i<pIn2->u.i){
 94727      pIn1->u.i = pIn2->u.i;
 94728    }
 94729    break;
 94730  }
 94731  #endif /* SQLITE_OMIT_AUTOINCREMENT */
 94732  
 94733  /* Opcode: IfPos P1 P2 P3 * *
 94734  ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
 94735  **
 94736  ** Register P1 must contain an integer.
 94737  ** If the value of register P1 is 1 or greater, subtract P3 from the
 94738  ** value in P1 and jump to P2.
 94739  **
 94740  ** If the initial value of register P1 is less than 1, then the
 94741  ** value is unchanged and control passes through to the next instruction.
 94742  */
 94743  case OP_IfPos: {        /* jump, in1 */
 94744    pIn1 = &aMem[pOp->p1];
 94745    assert( pIn1->flags&MEM_Int );
 94746    VdbeBranchTaken( pIn1->u.i>0, 2);
 94747    if( pIn1->u.i>0 ){
 94748      pIn1->u.i -= pOp->p3;
 94749      goto jump_to_p2;
 94750    }
 94751    break;
 94752  }
 94753  
 94754  /* Opcode: OffsetLimit P1 P2 P3 * *
 94755  ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
 94756  **
 94757  ** This opcode performs a commonly used computation associated with
 94758  ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
 94759  ** holds the offset counter.  The opcode computes the combined value
 94760  ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
 94761  ** value computed is the total number of rows that will need to be
 94762  ** visited in order to complete the query.
 94763  **
 94764  ** If r[P3] is zero or negative, that means there is no OFFSET
 94765  ** and r[P2] is set to be the value of the LIMIT, r[P1].
 94766  **
 94767  ** if r[P1] is zero or negative, that means there is no LIMIT
 94768  ** and r[P2] is set to -1. 
 94769  **
 94770  ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
 94771  */
 94772  case OP_OffsetLimit: {    /* in1, out2, in3 */
 94773    i64 x;
 94774    pIn1 = &aMem[pOp->p1];
 94775    pIn3 = &aMem[pOp->p3];
 94776    pOut = out2Prerelease(p, pOp);
 94777    assert( pIn1->flags & MEM_Int );
 94778    assert( pIn3->flags & MEM_Int );
 94779    x = pIn1->u.i;
 94780    if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
 94781      /* If the LIMIT is less than or equal to zero, loop forever.  This
 94782      ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
 94783      ** also loop forever.  This is undocumented.  In fact, one could argue
 94784      ** that the loop should terminate.  But assuming 1 billion iterations
 94785      ** per second (far exceeding the capabilities of any current hardware)
 94786      ** it would take nearly 300 years to actually reach the limit.  So
 94787      ** looping forever is a reasonable approximation. */
 94788      pOut->u.i = -1;
 94789    }else{
 94790      pOut->u.i = x;
 94791    }
 94792    break;
 94793  }
 94794  
 94795  /* Opcode: IfNotZero P1 P2 * * *
 94796  ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
 94797  **
 94798  ** Register P1 must contain an integer.  If the content of register P1 is
 94799  ** initially greater than zero, then decrement the value in register P1.
 94800  ** If it is non-zero (negative or positive) and then also jump to P2.  
 94801  ** If register P1 is initially zero, leave it unchanged and fall through.
 94802  */
 94803  case OP_IfNotZero: {        /* jump, in1 */
 94804    pIn1 = &aMem[pOp->p1];
 94805    assert( pIn1->flags&MEM_Int );
 94806    VdbeBranchTaken(pIn1->u.i<0, 2);
 94807    if( pIn1->u.i ){
 94808       if( pIn1->u.i>0 ) pIn1->u.i--;
 94809       goto jump_to_p2;
 94810    }
 94811    break;
 94812  }
 94813  
 94814  /* Opcode: DecrJumpZero P1 P2 * * *
 94815  ** Synopsis: if (--r[P1])==0 goto P2
 94816  **
 94817  ** Register P1 must hold an integer.  Decrement the value in P1
 94818  ** and jump to P2 if the new value is exactly zero.
 94819  */
 94820  case OP_DecrJumpZero: {      /* jump, in1 */
 94821    pIn1 = &aMem[pOp->p1];
 94822    assert( pIn1->flags&MEM_Int );
 94823    if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
 94824    VdbeBranchTaken(pIn1->u.i==0, 2);
 94825    if( pIn1->u.i==0 ) goto jump_to_p2;
 94826    break;
 94827  }
 94828  
 94829  
 94830  /* Opcode: AggStep * P2 P3 P4 P5
 94831  ** Synopsis: accum=r[P3] step(r[P2@P5])
 94832  **
 94833  ** Execute the xStep function for an aggregate.
 94834  ** The function has P5 arguments.  P4 is a pointer to the 
 94835  ** FuncDef structure that specifies the function.  Register P3 is the
 94836  ** accumulator.
 94837  **
 94838  ** The P5 arguments are taken from register P2 and its
 94839  ** successors.
 94840  */
 94841  /* Opcode: AggInverse * P2 P3 P4 P5
 94842  ** Synopsis: accum=r[P3] inverse(r[P2@P5])
 94843  **
 94844  ** Execute the xInverse function for an aggregate.
 94845  ** The function has P5 arguments.  P4 is a pointer to the 
 94846  ** FuncDef structure that specifies the function.  Register P3 is the
 94847  ** accumulator.
 94848  **
 94849  ** The P5 arguments are taken from register P2 and its
 94850  ** successors.
 94851  */
 94852  /* Opcode: AggStep1 P1 P2 P3 P4 P5
 94853  ** Synopsis: accum=r[P3] step(r[P2@P5])
 94854  **
 94855  ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
 94856  ** aggregate.  The function has P5 arguments.  P4 is a pointer to the 
 94857  ** FuncDef structure that specifies the function.  Register P3 is the
 94858  ** accumulator.
 94859  **
 94860  ** The P5 arguments are taken from register P2 and its
 94861  ** successors.
 94862  **
 94863  ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
 94864  ** the FuncDef stored in P4 is converted into an sqlite3_context and
 94865  ** the opcode is changed.  In this way, the initialization of the
 94866  ** sqlite3_context only happens once, instead of on each call to the
 94867  ** step function.
 94868  */
 94869  case OP_AggInverse:
 94870  case OP_AggStep: {
 94871    int n;
 94872    sqlite3_context *pCtx;
 94873  
 94874    assert( pOp->p4type==P4_FUNCDEF );
 94875    n = pOp->p5;
 94876    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 94877    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 94878    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 94879    pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
 94880                 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
 94881    if( pCtx==0 ) goto no_mem;
 94882    pCtx->pMem = 0;
 94883    pCtx->pOut = (Mem*)&(pCtx->argv[n]);
 94884    sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
 94885    pCtx->pFunc = pOp->p4.pFunc;
 94886    pCtx->iOp = (int)(pOp - aOp);
 94887    pCtx->pVdbe = p;
 94888    pCtx->skipFlag = 0;
 94889    pCtx->isError = 0;
 94890    pCtx->argc = n;
 94891    pOp->p4type = P4_FUNCCTX;
 94892    pOp->p4.pCtx = pCtx;
 94893  
 94894    /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
 94895    assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
 94896  
 94897    pOp->opcode = OP_AggStep1;
 94898    /* Fall through into OP_AggStep */
 94899  }
 94900  case OP_AggStep1: {
 94901    int i;
 94902    sqlite3_context *pCtx;
 94903    Mem *pMem;
 94904  
 94905    assert( pOp->p4type==P4_FUNCCTX );
 94906    pCtx = pOp->p4.pCtx;
 94907    pMem = &aMem[pOp->p3];
 94908  
 94909  #ifdef SQLITE_DEBUG
 94910    if( pOp->p1 ){
 94911      /* This is an OP_AggInverse call.  Verify that xStep has always
 94912      ** been called at least once prior to any xInverse call. */
 94913      assert( pMem->uTemp==0x1122e0e3 );
 94914    }else{
 94915      /* This is an OP_AggStep call.  Mark it as such. */
 94916      pMem->uTemp = 0x1122e0e3;
 94917    }
 94918  #endif
 94919  
 94920    /* If this function is inside of a trigger, the register array in aMem[]
 94921    ** might change from one evaluation to the next.  The next block of code
 94922    ** checks to see if the register array has changed, and if so it
 94923    ** reinitializes the relavant parts of the sqlite3_context object */
 94924    if( pCtx->pMem != pMem ){
 94925      pCtx->pMem = pMem;
 94926      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
 94927    }
 94928  
 94929  #ifdef SQLITE_DEBUG
 94930    for(i=0; i<pCtx->argc; i++){
 94931      assert( memIsValid(pCtx->argv[i]) );
 94932      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
 94933    }
 94934  #endif
 94935  
 94936    pMem->n++;
 94937    assert( pCtx->pOut->flags==MEM_Null );
 94938    assert( pCtx->isError==0 );
 94939    assert( pCtx->skipFlag==0 );
 94940  #ifndef SQLITE_OMIT_WINDOWFUNC
 94941    if( pOp->p1 ){
 94942      (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
 94943    }else
 94944  #endif
 94945    (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
 94946  
 94947    if( pCtx->isError ){
 94948      if( pCtx->isError>0 ){
 94949        sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
 94950        rc = pCtx->isError;
 94951      }
 94952      if( pCtx->skipFlag ){
 94953        assert( pOp[-1].opcode==OP_CollSeq );
 94954        i = pOp[-1].p1;
 94955        if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
 94956        pCtx->skipFlag = 0;
 94957      }
 94958      sqlite3VdbeMemRelease(pCtx->pOut);
 94959      pCtx->pOut->flags = MEM_Null;
 94960      pCtx->isError = 0;
 94961      if( rc ) goto abort_due_to_error;
 94962    }
 94963    assert( pCtx->pOut->flags==MEM_Null );
 94964    assert( pCtx->skipFlag==0 );
 94965    break;
 94966  }
 94967  
 94968  /* Opcode: AggFinal P1 P2 * P4 *
 94969  ** Synopsis: accum=r[P1] N=P2
 94970  **
 94971  ** P1 is the memory location that is the accumulator for an aggregate
 94972  ** or window function.  Execute the finalizer function 
 94973  ** for an aggregate and store the result in P1.
 94974  **
 94975  ** P2 is the number of arguments that the step function takes and
 94976  ** P4 is a pointer to the FuncDef for this function.  The P2
 94977  ** argument is not used by this opcode.  It is only there to disambiguate
 94978  ** functions that can take varying numbers of arguments.  The
 94979  ** P4 argument is only needed for the case where
 94980  ** the step function was not previously called.
 94981  */
 94982  /* Opcode: AggValue * P2 P3 P4 *
 94983  ** Synopsis: r[P3]=value N=P2
 94984  **
 94985  ** Invoke the xValue() function and store the result in register P3.
 94986  **
 94987  ** P2 is the number of arguments that the step function takes and
 94988  ** P4 is a pointer to the FuncDef for this function.  The P2
 94989  ** argument is not used by this opcode.  It is only there to disambiguate
 94990  ** functions that can take varying numbers of arguments.  The
 94991  ** P4 argument is only needed for the case where
 94992  ** the step function was not previously called.
 94993  */
 94994  case OP_AggValue:
 94995  case OP_AggFinal: {
 94996    Mem *pMem;
 94997    assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
 94998    assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
 94999    pMem = &aMem[pOp->p1];
 95000    assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
 95001  #ifndef SQLITE_OMIT_WINDOWFUNC
 95002    if( pOp->p3 ){
 95003      rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
 95004      pMem = &aMem[pOp->p3];
 95005    }else
 95006  #endif
 95007    {
 95008      rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
 95009    }
 95010    
 95011    if( rc ){
 95012      sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
 95013      goto abort_due_to_error;
 95014    }
 95015    sqlite3VdbeChangeEncoding(pMem, encoding);
 95016    UPDATE_MAX_BLOBSIZE(pMem);
 95017    if( sqlite3VdbeMemTooBig(pMem) ){
 95018      goto too_big;
 95019    }
 95020    break;
 95021  }
 95022  
 95023  #ifndef SQLITE_OMIT_WAL
 95024  /* Opcode: Checkpoint P1 P2 P3 * *
 95025  **
 95026  ** Checkpoint database P1. This is a no-op if P1 is not currently in
 95027  ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
 95028  ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
 95029  ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
 95030  ** WAL after the checkpoint into mem[P3+1] and the number of pages
 95031  ** in the WAL that have been checkpointed after the checkpoint
 95032  ** completes into mem[P3+2].  However on an error, mem[P3+1] and
 95033  ** mem[P3+2] are initialized to -1.
 95034  */
 95035  case OP_Checkpoint: {
 95036    int i;                          /* Loop counter */
 95037    int aRes[3];                    /* Results */
 95038    Mem *pMem;                      /* Write results here */
 95039  
 95040    assert( p->readOnly==0 );
 95041    aRes[0] = 0;
 95042    aRes[1] = aRes[2] = -1;
 95043    assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
 95044         || pOp->p2==SQLITE_CHECKPOINT_FULL
 95045         || pOp->p2==SQLITE_CHECKPOINT_RESTART
 95046         || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
 95047    );
 95048    rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
 95049    if( rc ){
 95050      if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
 95051      rc = SQLITE_OK;
 95052      aRes[0] = 1;
 95053    }
 95054    for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
 95055      sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
 95056    }    
 95057    break;
 95058  };  
 95059  #endif
 95060  
 95061  #ifndef SQLITE_OMIT_PRAGMA
 95062  /* Opcode: JournalMode P1 P2 P3 * *
 95063  **
 95064  ** Change the journal mode of database P1 to P3. P3 must be one of the
 95065  ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
 95066  ** modes (delete, truncate, persist, off and memory), this is a simple
 95067  ** operation. No IO is required.
 95068  **
 95069  ** If changing into or out of WAL mode the procedure is more complicated.
 95070  **
 95071  ** Write a string containing the final journal-mode to register P2.
 95072  */
 95073  case OP_JournalMode: {    /* out2 */
 95074    Btree *pBt;                     /* Btree to change journal mode of */
 95075    Pager *pPager;                  /* Pager associated with pBt */
 95076    int eNew;                       /* New journal mode */
 95077    int eOld;                       /* The old journal mode */
 95078  #ifndef SQLITE_OMIT_WAL
 95079    const char *zFilename;          /* Name of database file for pPager */
 95080  #endif
 95081  
 95082    pOut = out2Prerelease(p, pOp);
 95083    eNew = pOp->p3;
 95084    assert( eNew==PAGER_JOURNALMODE_DELETE 
 95085         || eNew==PAGER_JOURNALMODE_TRUNCATE 
 95086         || eNew==PAGER_JOURNALMODE_PERSIST 
 95087         || eNew==PAGER_JOURNALMODE_OFF
 95088         || eNew==PAGER_JOURNALMODE_MEMORY
 95089         || eNew==PAGER_JOURNALMODE_WAL
 95090         || eNew==PAGER_JOURNALMODE_QUERY
 95091    );
 95092    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 95093    assert( p->readOnly==0 );
 95094  
 95095    pBt = db->aDb[pOp->p1].pBt;
 95096    pPager = sqlite3BtreePager(pBt);
 95097    eOld = sqlite3PagerGetJournalMode(pPager);
 95098    if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
 95099    if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
 95100  
 95101  #ifndef SQLITE_OMIT_WAL
 95102    zFilename = sqlite3PagerFilename(pPager, 1);
 95103  
 95104    /* Do not allow a transition to journal_mode=WAL for a database
 95105    ** in temporary storage or if the VFS does not support shared memory 
 95106    */
 95107    if( eNew==PAGER_JOURNALMODE_WAL
 95108     && (sqlite3Strlen30(zFilename)==0           /* Temp file */
 95109         || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
 95110    ){
 95111      eNew = eOld;
 95112    }
 95113  
 95114    if( (eNew!=eOld)
 95115     && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
 95116    ){
 95117      if( !db->autoCommit || db->nVdbeRead>1 ){
 95118        rc = SQLITE_ERROR;
 95119        sqlite3VdbeError(p,
 95120            "cannot change %s wal mode from within a transaction",
 95121            (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
 95122        );
 95123        goto abort_due_to_error;
 95124      }else{
 95125   
 95126        if( eOld==PAGER_JOURNALMODE_WAL ){
 95127          /* If leaving WAL mode, close the log file. If successful, the call
 95128          ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
 95129          ** file. An EXCLUSIVE lock may still be held on the database file 
 95130          ** after a successful return. 
 95131          */
 95132          rc = sqlite3PagerCloseWal(pPager, db);
 95133          if( rc==SQLITE_OK ){
 95134            sqlite3PagerSetJournalMode(pPager, eNew);
 95135          }
 95136        }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
 95137          /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
 95138          ** as an intermediate */
 95139          sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
 95140        }
 95141    
 95142        /* Open a transaction on the database file. Regardless of the journal
 95143        ** mode, this transaction always uses a rollback journal.
 95144        */
 95145        assert( sqlite3BtreeIsInTrans(pBt)==0 );
 95146        if( rc==SQLITE_OK ){
 95147          rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
 95148        }
 95149      }
 95150    }
 95151  #endif /* ifndef SQLITE_OMIT_WAL */
 95152  
 95153    if( rc ) eNew = eOld;
 95154    eNew = sqlite3PagerSetJournalMode(pPager, eNew);
 95155  
 95156    pOut->flags = MEM_Str|MEM_Static|MEM_Term;
 95157    pOut->z = (char *)sqlite3JournalModename(eNew);
 95158    pOut->n = sqlite3Strlen30(pOut->z);
 95159    pOut->enc = SQLITE_UTF8;
 95160    sqlite3VdbeChangeEncoding(pOut, encoding);
 95161    if( rc ) goto abort_due_to_error;
 95162    break;
 95163  };
 95164  #endif /* SQLITE_OMIT_PRAGMA */
 95165  
 95166  #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
 95167  /* Opcode: Vacuum P1 P2 * * *
 95168  **
 95169  ** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
 95170  ** for an attached database.  The "temp" database may not be vacuumed.
 95171  **
 95172  ** If P2 is not zero, then it is a register holding a string which is
 95173  ** the file into which the result of vacuum should be written.  When
 95174  ** P2 is zero, the vacuum overwrites the original database.
 95175  */
 95176  case OP_Vacuum: {
 95177    assert( p->readOnly==0 );
 95178    rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
 95179                          pOp->p2 ? &aMem[pOp->p2] : 0);
 95180    if( rc ) goto abort_due_to_error;
 95181    break;
 95182  }
 95183  #endif
 95184  
 95185  #if !defined(SQLITE_OMIT_AUTOVACUUM)
 95186  /* Opcode: IncrVacuum P1 P2 * * *
 95187  **
 95188  ** Perform a single step of the incremental vacuum procedure on
 95189  ** the P1 database. If the vacuum has finished, jump to instruction
 95190  ** P2. Otherwise, fall through to the next instruction.
 95191  */
 95192  case OP_IncrVacuum: {        /* jump */
 95193    Btree *pBt;
 95194  
 95195    assert( pOp->p1>=0 && pOp->p1<db->nDb );
 95196    assert( DbMaskTest(p->btreeMask, pOp->p1) );
 95197    assert( p->readOnly==0 );
 95198    pBt = db->aDb[pOp->p1].pBt;
 95199    rc = sqlite3BtreeIncrVacuum(pBt);
 95200    VdbeBranchTaken(rc==SQLITE_DONE,2);
 95201    if( rc ){
 95202      if( rc!=SQLITE_DONE ) goto abort_due_to_error;
 95203      rc = SQLITE_OK;
 95204      goto jump_to_p2;
 95205    }
 95206    break;
 95207  }
 95208  #endif
 95209  
 95210  /* Opcode: Expire P1 P2 * * *
 95211  **
 95212  ** Cause precompiled statements to expire.  When an expired statement
 95213  ** is executed using sqlite3_step() it will either automatically
 95214  ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
 95215  ** or it will fail with SQLITE_SCHEMA.
 95216  ** 
 95217  ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
 95218  ** then only the currently executing statement is expired.
 95219  **
 95220  ** If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
 95221  ** then running SQL statements are allowed to continue to run to completion.
 95222  ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
 95223  ** that might help the statement run faster but which does not affect the
 95224  ** correctness of operation.
 95225  */
 95226  case OP_Expire: {
 95227    assert( pOp->p2==0 || pOp->p2==1 );
 95228    if( !pOp->p1 ){
 95229      sqlite3ExpirePreparedStatements(db, pOp->p2);
 95230    }else{
 95231      p->expired = pOp->p2+1;
 95232    }
 95233    break;
 95234  }
 95235  
 95236  #ifndef SQLITE_OMIT_SHARED_CACHE
 95237  /* Opcode: TableLock P1 P2 P3 P4 *
 95238  ** Synopsis: iDb=P1 root=P2 write=P3
 95239  **
 95240  ** Obtain a lock on a particular table. This instruction is only used when
 95241  ** the shared-cache feature is enabled. 
 95242  **
 95243  ** P1 is the index of the database in sqlite3.aDb[] of the database
 95244  ** on which the lock is acquired.  A readlock is obtained if P3==0 or
 95245  ** a write lock if P3==1.
 95246  **
 95247  ** P2 contains the root-page of the table to lock.
 95248  **
 95249  ** P4 contains a pointer to the name of the table being locked. This is only
 95250  ** used to generate an error message if the lock cannot be obtained.
 95251  */
 95252  case OP_TableLock: {
 95253    u8 isWriteLock = (u8)pOp->p3;
 95254    if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
 95255      int p1 = pOp->p1; 
 95256      assert( p1>=0 && p1<db->nDb );
 95257      assert( DbMaskTest(p->btreeMask, p1) );
 95258      assert( isWriteLock==0 || isWriteLock==1 );
 95259      rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
 95260      if( rc ){
 95261        if( (rc&0xFF)==SQLITE_LOCKED ){
 95262          const char *z = pOp->p4.z;
 95263          sqlite3VdbeError(p, "database table is locked: %s", z);
 95264        }
 95265        goto abort_due_to_error;
 95266      }
 95267    }
 95268    break;
 95269  }
 95270  #endif /* SQLITE_OMIT_SHARED_CACHE */
 95271  
 95272  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95273  /* Opcode: VBegin * * * P4 *
 95274  **
 95275  ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
 95276  ** xBegin method for that table.
 95277  **
 95278  ** Also, whether or not P4 is set, check that this is not being called from
 95279  ** within a callback to a virtual table xSync() method. If it is, the error
 95280  ** code will be set to SQLITE_LOCKED.
 95281  */
 95282  case OP_VBegin: {
 95283    VTable *pVTab;
 95284    pVTab = pOp->p4.pVtab;
 95285    rc = sqlite3VtabBegin(db, pVTab);
 95286    if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
 95287    if( rc ) goto abort_due_to_error;
 95288    break;
 95289  }
 95290  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95291  
 95292  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95293  /* Opcode: VCreate P1 P2 * * *
 95294  **
 95295  ** P2 is a register that holds the name of a virtual table in database 
 95296  ** P1. Call the xCreate method for that table.
 95297  */
 95298  case OP_VCreate: {
 95299    Mem sMem;          /* For storing the record being decoded */
 95300    const char *zTab;  /* Name of the virtual table */
 95301  
 95302    memset(&sMem, 0, sizeof(sMem));
 95303    sMem.db = db;
 95304    /* Because P2 is always a static string, it is impossible for the
 95305    ** sqlite3VdbeMemCopy() to fail */
 95306    assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
 95307    assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
 95308    rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
 95309    assert( rc==SQLITE_OK );
 95310    zTab = (const char*)sqlite3_value_text(&sMem);
 95311    assert( zTab || db->mallocFailed );
 95312    if( zTab ){
 95313      rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
 95314    }
 95315    sqlite3VdbeMemRelease(&sMem);
 95316    if( rc ) goto abort_due_to_error;
 95317    break;
 95318  }
 95319  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95320  
 95321  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95322  /* Opcode: VDestroy P1 * * P4 *
 95323  **
 95324  ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
 95325  ** of that table.
 95326  */
 95327  case OP_VDestroy: {
 95328    db->nVDestroy++;
 95329    rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
 95330    db->nVDestroy--;
 95331    assert( p->errorAction==OE_Abort && p->usesStmtJournal );
 95332    if( rc ) goto abort_due_to_error;
 95333    break;
 95334  }
 95335  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95336  
 95337  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95338  /* Opcode: VOpen P1 * * P4 *
 95339  **
 95340  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 95341  ** P1 is a cursor number.  This opcode opens a cursor to the virtual
 95342  ** table and stores that cursor in P1.
 95343  */
 95344  case OP_VOpen: {
 95345    VdbeCursor *pCur;
 95346    sqlite3_vtab_cursor *pVCur;
 95347    sqlite3_vtab *pVtab;
 95348    const sqlite3_module *pModule;
 95349  
 95350    assert( p->bIsReader );
 95351    pCur = 0;
 95352    pVCur = 0;
 95353    pVtab = pOp->p4.pVtab->pVtab;
 95354    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 95355      rc = SQLITE_LOCKED;
 95356      goto abort_due_to_error;
 95357    }
 95358    pModule = pVtab->pModule;
 95359    rc = pModule->xOpen(pVtab, &pVCur);
 95360    sqlite3VtabImportErrmsg(p, pVtab);
 95361    if( rc ) goto abort_due_to_error;
 95362  
 95363    /* Initialize sqlite3_vtab_cursor base class */
 95364    pVCur->pVtab = pVtab;
 95365  
 95366    /* Initialize vdbe cursor object */
 95367    pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
 95368    if( pCur ){
 95369      pCur->uc.pVCur = pVCur;
 95370      pVtab->nRef++;
 95371    }else{
 95372      assert( db->mallocFailed );
 95373      pModule->xClose(pVCur);
 95374      goto no_mem;
 95375    }
 95376    break;
 95377  }
 95378  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95379  
 95380  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95381  /* Opcode: VFilter P1 P2 P3 P4 *
 95382  ** Synopsis: iplan=r[P3] zplan='P4'
 95383  **
 95384  ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
 95385  ** the filtered result set is empty.
 95386  **
 95387  ** P4 is either NULL or a string that was generated by the xBestIndex
 95388  ** method of the module.  The interpretation of the P4 string is left
 95389  ** to the module implementation.
 95390  **
 95391  ** This opcode invokes the xFilter method on the virtual table specified
 95392  ** by P1.  The integer query plan parameter to xFilter is stored in register
 95393  ** P3. Register P3+1 stores the argc parameter to be passed to the
 95394  ** xFilter method. Registers P3+2..P3+1+argc are the argc
 95395  ** additional parameters which are passed to
 95396  ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
 95397  **
 95398  ** A jump is made to P2 if the result set after filtering would be empty.
 95399  */
 95400  case OP_VFilter: {   /* jump */
 95401    int nArg;
 95402    int iQuery;
 95403    const sqlite3_module *pModule;
 95404    Mem *pQuery;
 95405    Mem *pArgc;
 95406    sqlite3_vtab_cursor *pVCur;
 95407    sqlite3_vtab *pVtab;
 95408    VdbeCursor *pCur;
 95409    int res;
 95410    int i;
 95411    Mem **apArg;
 95412  
 95413    pQuery = &aMem[pOp->p3];
 95414    pArgc = &pQuery[1];
 95415    pCur = p->apCsr[pOp->p1];
 95416    assert( memIsValid(pQuery) );
 95417    REGISTER_TRACE(pOp->p3, pQuery);
 95418    assert( pCur->eCurType==CURTYPE_VTAB );
 95419    pVCur = pCur->uc.pVCur;
 95420    pVtab = pVCur->pVtab;
 95421    pModule = pVtab->pModule;
 95422  
 95423    /* Grab the index number and argc parameters */
 95424    assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
 95425    nArg = (int)pArgc->u.i;
 95426    iQuery = (int)pQuery->u.i;
 95427  
 95428    /* Invoke the xFilter method */
 95429    res = 0;
 95430    apArg = p->apArg;
 95431    for(i = 0; i<nArg; i++){
 95432      apArg[i] = &pArgc[i+1];
 95433    }
 95434    rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
 95435    sqlite3VtabImportErrmsg(p, pVtab);
 95436    if( rc ) goto abort_due_to_error;
 95437    res = pModule->xEof(pVCur);
 95438    pCur->nullRow = 0;
 95439    VdbeBranchTaken(res!=0,2);
 95440    if( res ) goto jump_to_p2;
 95441    break;
 95442  }
 95443  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95444  
 95445  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95446  /* Opcode: VColumn P1 P2 P3 * P5
 95447  ** Synopsis: r[P3]=vcolumn(P2)
 95448  **
 95449  ** Store in register P3 the value of the P2-th column of
 95450  ** the current row of the virtual-table of cursor P1.
 95451  **
 95452  ** If the VColumn opcode is being used to fetch the value of
 95453  ** an unchanging column during an UPDATE operation, then the P5
 95454  ** value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
 95455  ** function to return true inside the xColumn method of the virtual
 95456  ** table implementation.  The P5 column might also contain other
 95457  ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
 95458  ** unused by OP_VColumn.
 95459  */
 95460  case OP_VColumn: {
 95461    sqlite3_vtab *pVtab;
 95462    const sqlite3_module *pModule;
 95463    Mem *pDest;
 95464    sqlite3_context sContext;
 95465  
 95466    VdbeCursor *pCur = p->apCsr[pOp->p1];
 95467    assert( pCur->eCurType==CURTYPE_VTAB );
 95468    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 95469    pDest = &aMem[pOp->p3];
 95470    memAboutToChange(p, pDest);
 95471    if( pCur->nullRow ){
 95472      sqlite3VdbeMemSetNull(pDest);
 95473      break;
 95474    }
 95475    pVtab = pCur->uc.pVCur->pVtab;
 95476    pModule = pVtab->pModule;
 95477    assert( pModule->xColumn );
 95478    memset(&sContext, 0, sizeof(sContext));
 95479    sContext.pOut = pDest;
 95480    testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
 95481    if( pOp->p5 & OPFLAG_NOCHNG ){
 95482      sqlite3VdbeMemSetNull(pDest);
 95483      pDest->flags = MEM_Null|MEM_Zero;
 95484      pDest->u.nZero = 0;
 95485    }else{
 95486      MemSetTypeFlag(pDest, MEM_Null);
 95487    }
 95488    rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
 95489    sqlite3VtabImportErrmsg(p, pVtab);
 95490    if( sContext.isError>0 ){
 95491      sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
 95492      rc = sContext.isError;
 95493    }
 95494    sqlite3VdbeChangeEncoding(pDest, encoding);
 95495    REGISTER_TRACE(pOp->p3, pDest);
 95496    UPDATE_MAX_BLOBSIZE(pDest);
 95497  
 95498    if( sqlite3VdbeMemTooBig(pDest) ){
 95499      goto too_big;
 95500    }
 95501    if( rc ) goto abort_due_to_error;
 95502    break;
 95503  }
 95504  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95505  
 95506  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95507  /* Opcode: VNext P1 P2 * * *
 95508  **
 95509  ** Advance virtual table P1 to the next row in its result set and
 95510  ** jump to instruction P2.  Or, if the virtual table has reached
 95511  ** the end of its result set, then fall through to the next instruction.
 95512  */
 95513  case OP_VNext: {   /* jump */
 95514    sqlite3_vtab *pVtab;
 95515    const sqlite3_module *pModule;
 95516    int res;
 95517    VdbeCursor *pCur;
 95518  
 95519    res = 0;
 95520    pCur = p->apCsr[pOp->p1];
 95521    assert( pCur->eCurType==CURTYPE_VTAB );
 95522    if( pCur->nullRow ){
 95523      break;
 95524    }
 95525    pVtab = pCur->uc.pVCur->pVtab;
 95526    pModule = pVtab->pModule;
 95527    assert( pModule->xNext );
 95528  
 95529    /* Invoke the xNext() method of the module. There is no way for the
 95530    ** underlying implementation to return an error if one occurs during
 95531    ** xNext(). Instead, if an error occurs, true is returned (indicating that 
 95532    ** data is available) and the error code returned when xColumn or
 95533    ** some other method is next invoked on the save virtual table cursor.
 95534    */
 95535    rc = pModule->xNext(pCur->uc.pVCur);
 95536    sqlite3VtabImportErrmsg(p, pVtab);
 95537    if( rc ) goto abort_due_to_error;
 95538    res = pModule->xEof(pCur->uc.pVCur);
 95539    VdbeBranchTaken(!res,2);
 95540    if( !res ){
 95541      /* If there is data, jump to P2 */
 95542      goto jump_to_p2_and_check_for_interrupt;
 95543    }
 95544    goto check_for_interrupt;
 95545  }
 95546  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95547  
 95548  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95549  /* Opcode: VRename P1 * * P4 *
 95550  **
 95551  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 95552  ** This opcode invokes the corresponding xRename method. The value
 95553  ** in register P1 is passed as the zName argument to the xRename method.
 95554  */
 95555  case OP_VRename: {
 95556    sqlite3_vtab *pVtab;
 95557    Mem *pName;
 95558    int isLegacy;
 95559    
 95560    isLegacy = (db->flags & SQLITE_LegacyAlter);
 95561    db->flags |= SQLITE_LegacyAlter;
 95562    pVtab = pOp->p4.pVtab->pVtab;
 95563    pName = &aMem[pOp->p1];
 95564    assert( pVtab->pModule->xRename );
 95565    assert( memIsValid(pName) );
 95566    assert( p->readOnly==0 );
 95567    REGISTER_TRACE(pOp->p1, pName);
 95568    assert( pName->flags & MEM_Str );
 95569    testcase( pName->enc==SQLITE_UTF8 );
 95570    testcase( pName->enc==SQLITE_UTF16BE );
 95571    testcase( pName->enc==SQLITE_UTF16LE );
 95572    rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
 95573    if( rc ) goto abort_due_to_error;
 95574    rc = pVtab->pModule->xRename(pVtab, pName->z);
 95575    if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
 95576    sqlite3VtabImportErrmsg(p, pVtab);
 95577    p->expired = 0;
 95578    if( rc ) goto abort_due_to_error;
 95579    break;
 95580  }
 95581  #endif
 95582  
 95583  #ifndef SQLITE_OMIT_VIRTUALTABLE
 95584  /* Opcode: VUpdate P1 P2 P3 P4 P5
 95585  ** Synopsis: data=r[P3@P2]
 95586  **
 95587  ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 95588  ** This opcode invokes the corresponding xUpdate method. P2 values
 95589  ** are contiguous memory cells starting at P3 to pass to the xUpdate 
 95590  ** invocation. The value in register (P3+P2-1) corresponds to the 
 95591  ** p2th element of the argv array passed to xUpdate.
 95592  **
 95593  ** The xUpdate method will do a DELETE or an INSERT or both.
 95594  ** The argv[0] element (which corresponds to memory cell P3)
 95595  ** is the rowid of a row to delete.  If argv[0] is NULL then no 
 95596  ** deletion occurs.  The argv[1] element is the rowid of the new 
 95597  ** row.  This can be NULL to have the virtual table select the new 
 95598  ** rowid for itself.  The subsequent elements in the array are 
 95599  ** the values of columns in the new row.
 95600  **
 95601  ** If P2==1 then no insert is performed.  argv[0] is the rowid of
 95602  ** a row to delete.
 95603  **
 95604  ** P1 is a boolean flag. If it is set to true and the xUpdate call
 95605  ** is successful, then the value returned by sqlite3_last_insert_rowid() 
 95606  ** is set to the value of the rowid for the row just inserted.
 95607  **
 95608  ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
 95609  ** apply in the case of a constraint failure on an insert or update.
 95610  */
 95611  case OP_VUpdate: {
 95612    sqlite3_vtab *pVtab;
 95613    const sqlite3_module *pModule;
 95614    int nArg;
 95615    int i;
 95616    sqlite_int64 rowid;
 95617    Mem **apArg;
 95618    Mem *pX;
 95619  
 95620    assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
 95621         || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
 95622    );
 95623    assert( p->readOnly==0 );
 95624    if( db->mallocFailed ) goto no_mem;
 95625    sqlite3VdbeIncrWriteCounter(p, 0);
 95626    pVtab = pOp->p4.pVtab->pVtab;
 95627    if( pVtab==0 || NEVER(pVtab->pModule==0) ){
 95628      rc = SQLITE_LOCKED;
 95629      goto abort_due_to_error;
 95630    }
 95631    pModule = pVtab->pModule;
 95632    nArg = pOp->p2;
 95633    assert( pOp->p4type==P4_VTAB );
 95634    if( ALWAYS(pModule->xUpdate) ){
 95635      u8 vtabOnConflict = db->vtabOnConflict;
 95636      apArg = p->apArg;
 95637      pX = &aMem[pOp->p3];
 95638      for(i=0; i<nArg; i++){
 95639        assert( memIsValid(pX) );
 95640        memAboutToChange(p, pX);
 95641        apArg[i] = pX;
 95642        pX++;
 95643      }
 95644      db->vtabOnConflict = pOp->p5;
 95645      rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
 95646      db->vtabOnConflict = vtabOnConflict;
 95647      sqlite3VtabImportErrmsg(p, pVtab);
 95648      if( rc==SQLITE_OK && pOp->p1 ){
 95649        assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
 95650        db->lastRowid = rowid;
 95651      }
 95652      if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
 95653        if( pOp->p5==OE_Ignore ){
 95654          rc = SQLITE_OK;
 95655        }else{
 95656          p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
 95657        }
 95658      }else{
 95659        p->nChange++;
 95660      }
 95661      if( rc ) goto abort_due_to_error;
 95662    }
 95663    break;
 95664  }
 95665  #endif /* SQLITE_OMIT_VIRTUALTABLE */
 95666  
 95667  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 95668  /* Opcode: Pagecount P1 P2 * * *
 95669  **
 95670  ** Write the current number of pages in database P1 to memory cell P2.
 95671  */
 95672  case OP_Pagecount: {            /* out2 */
 95673    pOut = out2Prerelease(p, pOp);
 95674    pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
 95675    break;
 95676  }
 95677  #endif
 95678  
 95679  
 95680  #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
 95681  /* Opcode: MaxPgcnt P1 P2 P3 * *
 95682  **
 95683  ** Try to set the maximum page count for database P1 to the value in P3.
 95684  ** Do not let the maximum page count fall below the current page count and
 95685  ** do not change the maximum page count value if P3==0.
 95686  **
 95687  ** Store the maximum page count after the change in register P2.
 95688  */
 95689  case OP_MaxPgcnt: {            /* out2 */
 95690    unsigned int newMax;
 95691    Btree *pBt;
 95692  
 95693    pOut = out2Prerelease(p, pOp);
 95694    pBt = db->aDb[pOp->p1].pBt;
 95695    newMax = 0;
 95696    if( pOp->p3 ){
 95697      newMax = sqlite3BtreeLastPage(pBt);
 95698      if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
 95699    }
 95700    pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
 95701    break;
 95702  }
 95703  #endif
 95704  
 95705  /* Opcode: Function0 P1 P2 P3 P4 P5
 95706  ** Synopsis: r[P3]=func(r[P2@P5])
 95707  **
 95708  ** Invoke a user function (P4 is a pointer to a FuncDef object that
 95709  ** defines the function) with P5 arguments taken from register P2 and
 95710  ** successors.  The result of the function is stored in register P3.
 95711  ** Register P3 must not be one of the function inputs.
 95712  **
 95713  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
 95714  ** function was determined to be constant at compile time. If the first
 95715  ** argument was constant then bit 0 of P1 is set. This is used to determine
 95716  ** whether meta data associated with a user function argument using the
 95717  ** sqlite3_set_auxdata() API may be safely retained until the next
 95718  ** invocation of this opcode.
 95719  **
 95720  ** See also: Function, AggStep, AggFinal
 95721  */
 95722  /* Opcode: Function P1 P2 P3 P4 P5
 95723  ** Synopsis: r[P3]=func(r[P2@P5])
 95724  **
 95725  ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
 95726  ** contains a pointer to the function to be run) with P5 arguments taken
 95727  ** from register P2 and successors.  The result of the function is stored
 95728  ** in register P3.  Register P3 must not be one of the function inputs.
 95729  **
 95730  ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
 95731  ** function was determined to be constant at compile time. If the first
 95732  ** argument was constant then bit 0 of P1 is set. This is used to determine
 95733  ** whether meta data associated with a user function argument using the
 95734  ** sqlite3_set_auxdata() API may be safely retained until the next
 95735  ** invocation of this opcode.
 95736  **
 95737  ** SQL functions are initially coded as OP_Function0 with P4 pointing
 95738  ** to a FuncDef object.  But on first evaluation, the P4 operand is
 95739  ** automatically converted into an sqlite3_context object and the operation
 95740  ** changed to this OP_Function opcode.  In this way, the initialization of
 95741  ** the sqlite3_context object occurs only once, rather than once for each
 95742  ** evaluation of the function.
 95743  **
 95744  ** See also: Function0, AggStep, AggFinal
 95745  */
 95746  case OP_PureFunc0:              /* group */
 95747  case OP_Function0: {            /* group */
 95748    int n;
 95749    sqlite3_context *pCtx;
 95750  
 95751    assert( pOp->p4type==P4_FUNCDEF );
 95752    n = pOp->p5;
 95753    assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
 95754    assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
 95755    assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
 95756    pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
 95757    if( pCtx==0 ) goto no_mem;
 95758    pCtx->pOut = 0;
 95759    pCtx->pFunc = pOp->p4.pFunc;
 95760    pCtx->iOp = (int)(pOp - aOp);
 95761    pCtx->pVdbe = p;
 95762    pCtx->isError = 0;
 95763    pCtx->argc = n;
 95764    pOp->p4type = P4_FUNCCTX;
 95765    pOp->p4.pCtx = pCtx;
 95766    assert( OP_PureFunc == OP_PureFunc0+2 );
 95767    assert( OP_Function == OP_Function0+2 );
 95768    pOp->opcode += 2;
 95769    /* Fall through into OP_Function */
 95770  }
 95771  case OP_PureFunc:              /* group */
 95772  case OP_Function: {            /* group */
 95773    int i;
 95774    sqlite3_context *pCtx;
 95775  
 95776    assert( pOp->p4type==P4_FUNCCTX );
 95777    pCtx = pOp->p4.pCtx;
 95778  
 95779    /* If this function is inside of a trigger, the register array in aMem[]
 95780    ** might change from one evaluation to the next.  The next block of code
 95781    ** checks to see if the register array has changed, and if so it
 95782    ** reinitializes the relavant parts of the sqlite3_context object */
 95783    pOut = &aMem[pOp->p3];
 95784    if( pCtx->pOut != pOut ){
 95785      pCtx->pOut = pOut;
 95786      for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
 95787    }
 95788  
 95789    memAboutToChange(p, pOut);
 95790  #ifdef SQLITE_DEBUG
 95791    for(i=0; i<pCtx->argc; i++){
 95792      assert( memIsValid(pCtx->argv[i]) );
 95793      REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
 95794    }
 95795  #endif
 95796    MemSetTypeFlag(pOut, MEM_Null);
 95797    assert( pCtx->isError==0 );
 95798    (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
 95799  
 95800    /* If the function returned an error, throw an exception */
 95801    if( pCtx->isError ){
 95802      if( pCtx->isError>0 ){
 95803        sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
 95804        rc = pCtx->isError;
 95805      }
 95806      sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
 95807      pCtx->isError = 0;
 95808      if( rc ) goto abort_due_to_error;
 95809    }
 95810  
 95811    /* Copy the result of the function into register P3 */
 95812    if( pOut->flags & (MEM_Str|MEM_Blob) ){
 95813      sqlite3VdbeChangeEncoding(pOut, encoding);
 95814      if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
 95815    }
 95816  
 95817    REGISTER_TRACE(pOp->p3, pOut);
 95818    UPDATE_MAX_BLOBSIZE(pOut);
 95819    break;
 95820  }
 95821  
 95822  /* Opcode: Trace P1 P2 * P4 *
 95823  **
 95824  ** Write P4 on the statement trace output if statement tracing is
 95825  ** enabled.
 95826  **
 95827  ** Operand P1 must be 0x7fffffff and P2 must positive.
 95828  */
 95829  /* Opcode: Init P1 P2 P3 P4 *
 95830  ** Synopsis: Start at P2
 95831  **
 95832  ** Programs contain a single instance of this opcode as the very first
 95833  ** opcode.
 95834  **
 95835  ** If tracing is enabled (by the sqlite3_trace()) interface, then
 95836  ** the UTF-8 string contained in P4 is emitted on the trace callback.
 95837  ** Or if P4 is blank, use the string returned by sqlite3_sql().
 95838  **
 95839  ** If P2 is not zero, jump to instruction P2.
 95840  **
 95841  ** Increment the value of P1 so that OP_Once opcodes will jump the
 95842  ** first time they are evaluated for this run.
 95843  **
 95844  ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
 95845  ** error is encountered.
 95846  */
 95847  case OP_Trace:
 95848  case OP_Init: {          /* jump */
 95849    int i;
 95850  #ifndef SQLITE_OMIT_TRACE
 95851    char *zTrace;
 95852  #endif
 95853  
 95854    /* If the P4 argument is not NULL, then it must be an SQL comment string.
 95855    ** The "--" string is broken up to prevent false-positives with srcck1.c.
 95856    **
 95857    ** This assert() provides evidence for:
 95858    ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
 95859    ** would have been returned by the legacy sqlite3_trace() interface by
 95860    ** using the X argument when X begins with "--" and invoking
 95861    ** sqlite3_expanded_sql(P) otherwise.
 95862    */
 95863    assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
 95864  
 95865    /* OP_Init is always instruction 0 */
 95866    assert( pOp==p->aOp || pOp->opcode==OP_Trace );
 95867  
 95868  #ifndef SQLITE_OMIT_TRACE
 95869    if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
 95870     && !p->doingRerun
 95871     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 95872    ){
 95873  #ifndef SQLITE_OMIT_DEPRECATED
 95874      if( db->mTrace & SQLITE_TRACE_LEGACY ){
 95875        void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
 95876        char *z = sqlite3VdbeExpandSql(p, zTrace);
 95877        x(db->pTraceArg, z);
 95878        sqlite3_free(z);
 95879      }else
 95880  #endif
 95881      if( db->nVdbeExec>1 ){
 95882        char *z = sqlite3MPrintf(db, "-- %s", zTrace);
 95883        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
 95884        sqlite3DbFree(db, z);
 95885      }else{
 95886        (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
 95887      }
 95888    }
 95889  #ifdef SQLITE_USE_FCNTL_TRACE
 95890    zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
 95891    if( zTrace ){
 95892      int j;
 95893      for(j=0; j<db->nDb; j++){
 95894        if( DbMaskTest(p->btreeMask, j)==0 ) continue;
 95895        sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
 95896      }
 95897    }
 95898  #endif /* SQLITE_USE_FCNTL_TRACE */
 95899  #ifdef SQLITE_DEBUG
 95900    if( (db->flags & SQLITE_SqlTrace)!=0
 95901     && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
 95902    ){
 95903      sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
 95904    }
 95905  #endif /* SQLITE_DEBUG */
 95906  #endif /* SQLITE_OMIT_TRACE */
 95907    assert( pOp->p2>0 );
 95908    if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
 95909      if( pOp->opcode==OP_Trace ) break;
 95910      for(i=1; i<p->nOp; i++){
 95911        if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
 95912      }
 95913      pOp->p1 = 0;
 95914    }
 95915    pOp->p1++;
 95916    p->aCounter[SQLITE_STMTSTATUS_RUN]++;
 95917    goto jump_to_p2;
 95918  }
 95919  
 95920  #ifdef SQLITE_ENABLE_CURSOR_HINTS
 95921  /* Opcode: CursorHint P1 * * P4 *
 95922  **
 95923  ** Provide a hint to cursor P1 that it only needs to return rows that
 95924  ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
 95925  ** to values currently held in registers.  TK_COLUMN terms in the P4
 95926  ** expression refer to columns in the b-tree to which cursor P1 is pointing.
 95927  */
 95928  case OP_CursorHint: {
 95929    VdbeCursor *pC;
 95930  
 95931    assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 95932    assert( pOp->p4type==P4_EXPR );
 95933    pC = p->apCsr[pOp->p1];
 95934    if( pC ){
 95935      assert( pC->eCurType==CURTYPE_BTREE );
 95936      sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
 95937                             pOp->p4.pExpr, aMem);
 95938    }
 95939    break;
 95940  }
 95941  #endif /* SQLITE_ENABLE_CURSOR_HINTS */
 95942  
 95943  #ifdef SQLITE_DEBUG
 95944  /* Opcode:  Abortable   * * * * *
 95945  **
 95946  ** Verify that an Abort can happen.  Assert if an Abort at this point
 95947  ** might cause database corruption.  This opcode only appears in debugging
 95948  ** builds.
 95949  **
 95950  ** An Abort is safe if either there have been no writes, or if there is
 95951  ** an active statement journal.
 95952  */
 95953  case OP_Abortable: {
 95954    sqlite3VdbeAssertAbortable(p);
 95955    break;
 95956  }
 95957  #endif
 95958  
 95959  /* Opcode: Noop * * * * *
 95960  **
 95961  ** Do nothing.  This instruction is often useful as a jump
 95962  ** destination.
 95963  */
 95964  /*
 95965  ** The magic Explain opcode are only inserted when explain==2 (which
 95966  ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
 95967  ** This opcode records information from the optimizer.  It is the
 95968  ** the same as a no-op.  This opcodesnever appears in a real VM program.
 95969  */
 95970  default: {          /* This is really OP_Noop, OP_Explain */
 95971    assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
 95972  
 95973    break;
 95974  }
 95975  
 95976  /*****************************************************************************
 95977  ** The cases of the switch statement above this line should all be indented
 95978  ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
 95979  ** readability.  From this point on down, the normal indentation rules are
 95980  ** restored.
 95981  *****************************************************************************/
 95982      }
 95983  
 95984  #ifdef VDBE_PROFILE
 95985      {
 95986        u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
 95987        if( endTime>start ) pOrigOp->cycles += endTime - start;
 95988        pOrigOp->cnt++;
 95989      }
 95990  #endif
 95991  
 95992      /* The following code adds nothing to the actual functionality
 95993      ** of the program.  It is only here for testing and debugging.
 95994      ** On the other hand, it does burn CPU cycles every time through
 95995      ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
 95996      */
 95997  #ifndef NDEBUG
 95998      assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
 95999  
 96000  #ifdef SQLITE_DEBUG
 96001      if( db->flags & SQLITE_VdbeTrace ){
 96002        u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
 96003        if( rc!=0 ) printf("rc=%d\n",rc);
 96004        if( opProperty & (OPFLG_OUT2) ){
 96005          registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
 96006        }
 96007        if( opProperty & OPFLG_OUT3 ){
 96008          registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
 96009        }
 96010      }
 96011  #endif  /* SQLITE_DEBUG */
 96012  #endif  /* NDEBUG */
 96013    }  /* The end of the for(;;) loop the loops through opcodes */
 96014  
 96015    /* If we reach this point, it means that execution is finished with
 96016    ** an error of some kind.
 96017    */
 96018  abort_due_to_error:
 96019    if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
 96020    assert( rc );
 96021    if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
 96022      sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 96023    }
 96024    p->rc = rc;
 96025    sqlite3SystemError(db, rc);
 96026    testcase( sqlite3GlobalConfig.xLog!=0 );
 96027    sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
 96028                     (int)(pOp - aOp), p->zSql, p->zErrMsg);
 96029    sqlite3VdbeHalt(p);
 96030    if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
 96031    rc = SQLITE_ERROR;
 96032    if( resetSchemaOnFault>0 ){
 96033      sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
 96034    }
 96035  
 96036    /* This is the only way out of this procedure.  We have to
 96037    ** release the mutexes on btrees that were acquired at the
 96038    ** top. */
 96039  vdbe_return:
 96040    testcase( nVmStep>0 );
 96041    p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
 96042    sqlite3VdbeLeave(p);
 96043    assert( rc!=SQLITE_OK || nExtraDelete==0 
 96044         || sqlite3_strlike("DELETE%",p->zSql,0)!=0 
 96045    );
 96046    return rc;
 96047  
 96048    /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
 96049    ** is encountered.
 96050    */
 96051  too_big:
 96052    sqlite3VdbeError(p, "string or blob too big");
 96053    rc = SQLITE_TOOBIG;
 96054    goto abort_due_to_error;
 96055  
 96056    /* Jump to here if a malloc() fails.
 96057    */
 96058  no_mem:
 96059    sqlite3OomFault(db);
 96060    sqlite3VdbeError(p, "out of memory");
 96061    rc = SQLITE_NOMEM_BKPT;
 96062    goto abort_due_to_error;
 96063  
 96064    /* Jump to here if the sqlite3_interrupt() API sets the interrupt
 96065    ** flag.
 96066    */
 96067  abort_due_to_interrupt:
 96068    assert( db->u1.isInterrupted );
 96069    rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
 96070    p->rc = rc;
 96071    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
 96072    goto abort_due_to_error;
 96073  }
 96074  
 96075  
 96076  /************** End of vdbe.c ************************************************/
 96077  /************** Begin file vdbeblob.c ****************************************/
 96078  /*
 96079  ** 2007 May 1
 96080  **
 96081  ** The author disclaims copyright to this source code.  In place of
 96082  ** a legal notice, here is a blessing:
 96083  **
 96084  **    May you do good and not evil.
 96085  **    May you find forgiveness for yourself and forgive others.
 96086  **    May you share freely, never taking more than you give.
 96087  **
 96088  *************************************************************************
 96089  **
 96090  ** This file contains code used to implement incremental BLOB I/O.
 96091  */
 96092  
 96093  /* #include "sqliteInt.h" */
 96094  /* #include "vdbeInt.h" */
 96095  
 96096  #ifndef SQLITE_OMIT_INCRBLOB
 96097  
 96098  /*
 96099  ** Valid sqlite3_blob* handles point to Incrblob structures.
 96100  */
 96101  typedef struct Incrblob Incrblob;
 96102  struct Incrblob {
 96103    int nByte;              /* Size of open blob, in bytes */
 96104    int iOffset;            /* Byte offset of blob in cursor data */
 96105    u16 iCol;               /* Table column this handle is open on */
 96106    BtCursor *pCsr;         /* Cursor pointing at blob row */
 96107    sqlite3_stmt *pStmt;    /* Statement holding cursor open */
 96108    sqlite3 *db;            /* The associated database */
 96109    char *zDb;              /* Database name */
 96110    Table *pTab;            /* Table object */
 96111  };
 96112  
 96113  
 96114  /*
 96115  ** This function is used by both blob_open() and blob_reopen(). It seeks
 96116  ** the b-tree cursor associated with blob handle p to point to row iRow.
 96117  ** If successful, SQLITE_OK is returned and subsequent calls to
 96118  ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
 96119  **
 96120  ** If an error occurs, or if the specified row does not exist or does not
 96121  ** contain a value of type TEXT or BLOB in the column nominated when the
 96122  ** blob handle was opened, then an error code is returned and *pzErr may
 96123  ** be set to point to a buffer containing an error message. It is the
 96124  ** responsibility of the caller to free the error message buffer using
 96125  ** sqlite3DbFree().
 96126  **
 96127  ** If an error does occur, then the b-tree cursor is closed. All subsequent
 96128  ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
 96129  ** immediately return SQLITE_ABORT.
 96130  */
 96131  static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
 96132    int rc;                         /* Error code */
 96133    char *zErr = 0;                 /* Error message */
 96134    Vdbe *v = (Vdbe *)p->pStmt;
 96135  
 96136    /* Set the value of register r[1] in the SQL statement to integer iRow. 
 96137    ** This is done directly as a performance optimization
 96138    */
 96139    v->aMem[1].flags = MEM_Int;
 96140    v->aMem[1].u.i = iRow;
 96141  
 96142    /* If the statement has been run before (and is paused at the OP_ResultRow)
 96143    ** then back it up to the point where it does the OP_NotExists.  This could
 96144    ** have been down with an extra OP_Goto, but simply setting the program
 96145    ** counter is faster. */
 96146    if( v->pc>4 ){
 96147      v->pc = 4;
 96148      assert( v->aOp[v->pc].opcode==OP_NotExists );
 96149      rc = sqlite3VdbeExec(v);
 96150    }else{
 96151      rc = sqlite3_step(p->pStmt);
 96152    }
 96153    if( rc==SQLITE_ROW ){
 96154      VdbeCursor *pC = v->apCsr[0];
 96155      u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
 96156      testcase( pC->nHdrParsed==p->iCol );
 96157      testcase( pC->nHdrParsed==p->iCol+1 );
 96158      if( type<12 ){
 96159        zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
 96160            type==0?"null": type==7?"real": "integer"
 96161        );
 96162        rc = SQLITE_ERROR;
 96163        sqlite3_finalize(p->pStmt);
 96164        p->pStmt = 0;
 96165      }else{
 96166        p->iOffset = pC->aType[p->iCol + pC->nField];
 96167        p->nByte = sqlite3VdbeSerialTypeLen(type);
 96168        p->pCsr =  pC->uc.pCursor;
 96169        sqlite3BtreeIncrblobCursor(p->pCsr);
 96170      }
 96171    }
 96172  
 96173    if( rc==SQLITE_ROW ){
 96174      rc = SQLITE_OK;
 96175    }else if( p->pStmt ){
 96176      rc = sqlite3_finalize(p->pStmt);
 96177      p->pStmt = 0;
 96178      if( rc==SQLITE_OK ){
 96179        zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
 96180        rc = SQLITE_ERROR;
 96181      }else{
 96182        zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
 96183      }
 96184    }
 96185  
 96186    assert( rc!=SQLITE_OK || zErr==0 );
 96187    assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
 96188  
 96189    *pzErr = zErr;
 96190    return rc;
 96191  }
 96192  
 96193  /*
 96194  ** Open a blob handle.
 96195  */
 96196  SQLITE_API int sqlite3_blob_open(
 96197    sqlite3* db,            /* The database connection */
 96198    const char *zDb,        /* The attached database containing the blob */
 96199    const char *zTable,     /* The table containing the blob */
 96200    const char *zColumn,    /* The column containing the blob */
 96201    sqlite_int64 iRow,      /* The row containing the glob */
 96202    int wrFlag,             /* True -> read/write access, false -> read-only */
 96203    sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
 96204  ){
 96205    int nAttempt = 0;
 96206    int iCol;               /* Index of zColumn in row-record */
 96207    int rc = SQLITE_OK;
 96208    char *zErr = 0;
 96209    Table *pTab;
 96210    Incrblob *pBlob = 0;
 96211    Parse sParse;
 96212  
 96213  #ifdef SQLITE_ENABLE_API_ARMOR
 96214    if( ppBlob==0 ){
 96215      return SQLITE_MISUSE_BKPT;
 96216    }
 96217  #endif
 96218    *ppBlob = 0;
 96219  #ifdef SQLITE_ENABLE_API_ARMOR
 96220    if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
 96221      return SQLITE_MISUSE_BKPT;
 96222    }
 96223  #endif
 96224    wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
 96225  
 96226    sqlite3_mutex_enter(db->mutex);
 96227  
 96228    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
 96229    do {
 96230      memset(&sParse, 0, sizeof(Parse));
 96231      if( !pBlob ) goto blob_open_out;
 96232      sParse.db = db;
 96233      sqlite3DbFree(db, zErr);
 96234      zErr = 0;
 96235  
 96236      sqlite3BtreeEnterAll(db);
 96237      pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
 96238      if( pTab && IsVirtual(pTab) ){
 96239        pTab = 0;
 96240        sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
 96241      }
 96242      if( pTab && !HasRowid(pTab) ){
 96243        pTab = 0;
 96244        sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
 96245      }
 96246  #ifndef SQLITE_OMIT_VIEW
 96247      if( pTab && pTab->pSelect ){
 96248        pTab = 0;
 96249        sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
 96250      }
 96251  #endif
 96252      if( !pTab ){
 96253        if( sParse.zErrMsg ){
 96254          sqlite3DbFree(db, zErr);
 96255          zErr = sParse.zErrMsg;
 96256          sParse.zErrMsg = 0;
 96257        }
 96258        rc = SQLITE_ERROR;
 96259        sqlite3BtreeLeaveAll(db);
 96260        goto blob_open_out;
 96261      }
 96262      pBlob->pTab = pTab;
 96263      pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
 96264  
 96265      /* Now search pTab for the exact column. */
 96266      for(iCol=0; iCol<pTab->nCol; iCol++) {
 96267        if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
 96268          break;
 96269        }
 96270      }
 96271      if( iCol==pTab->nCol ){
 96272        sqlite3DbFree(db, zErr);
 96273        zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
 96274        rc = SQLITE_ERROR;
 96275        sqlite3BtreeLeaveAll(db);
 96276        goto blob_open_out;
 96277      }
 96278  
 96279      /* If the value is being opened for writing, check that the
 96280      ** column is not indexed, and that it is not part of a foreign key. 
 96281      */
 96282      if( wrFlag ){
 96283        const char *zFault = 0;
 96284        Index *pIdx;
 96285  #ifndef SQLITE_OMIT_FOREIGN_KEY
 96286        if( db->flags&SQLITE_ForeignKeys ){
 96287          /* Check that the column is not part of an FK child key definition. It
 96288          ** is not necessary to check if it is part of a parent key, as parent
 96289          ** key columns must be indexed. The check below will pick up this 
 96290          ** case.  */
 96291          FKey *pFKey;
 96292          for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
 96293            int j;
 96294            for(j=0; j<pFKey->nCol; j++){
 96295              if( pFKey->aCol[j].iFrom==iCol ){
 96296                zFault = "foreign key";
 96297              }
 96298            }
 96299          }
 96300        }
 96301  #endif
 96302        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 96303          int j;
 96304          for(j=0; j<pIdx->nKeyCol; j++){
 96305            /* FIXME: Be smarter about indexes that use expressions */
 96306            if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
 96307              zFault = "indexed";
 96308            }
 96309          }
 96310        }
 96311        if( zFault ){
 96312          sqlite3DbFree(db, zErr);
 96313          zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
 96314          rc = SQLITE_ERROR;
 96315          sqlite3BtreeLeaveAll(db);
 96316          goto blob_open_out;
 96317        }
 96318      }
 96319  
 96320      pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
 96321      assert( pBlob->pStmt || db->mallocFailed );
 96322      if( pBlob->pStmt ){
 96323        
 96324        /* This VDBE program seeks a btree cursor to the identified 
 96325        ** db/table/row entry. The reason for using a vdbe program instead
 96326        ** of writing code to use the b-tree layer directly is that the
 96327        ** vdbe program will take advantage of the various transaction,
 96328        ** locking and error handling infrastructure built into the vdbe.
 96329        **
 96330        ** After seeking the cursor, the vdbe executes an OP_ResultRow.
 96331        ** Code external to the Vdbe then "borrows" the b-tree cursor and
 96332        ** uses it to implement the blob_read(), blob_write() and 
 96333        ** blob_bytes() functions.
 96334        **
 96335        ** The sqlite3_blob_close() function finalizes the vdbe program,
 96336        ** which closes the b-tree cursor and (possibly) commits the 
 96337        ** transaction.
 96338        */
 96339        static const int iLn = VDBE_OFFSET_LINENO(2);
 96340        static const VdbeOpList openBlob[] = {
 96341          {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
 96342          {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
 96343          /* blobSeekToRow() will initialize r[1] to the desired rowid */
 96344          {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
 96345          {OP_Column,         0, 0, 1},  /* 3  */
 96346          {OP_ResultRow,      1, 0, 0},  /* 4  */
 96347          {OP_Halt,           0, 0, 0},  /* 5  */
 96348        };
 96349        Vdbe *v = (Vdbe *)pBlob->pStmt;
 96350        int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 96351        VdbeOp *aOp;
 96352  
 96353        sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, 
 96354                             pTab->pSchema->schema_cookie,
 96355                             pTab->pSchema->iGeneration);
 96356        sqlite3VdbeChangeP5(v, 1);
 96357        assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
 96358        aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
 96359  
 96360        /* Make sure a mutex is held on the table to be accessed */
 96361        sqlite3VdbeUsesBtree(v, iDb); 
 96362  
 96363        if( db->mallocFailed==0 ){
 96364          assert( aOp!=0 );
 96365          /* Configure the OP_TableLock instruction */
 96366  #ifdef SQLITE_OMIT_SHARED_CACHE
 96367          aOp[0].opcode = OP_Noop;
 96368  #else
 96369          aOp[0].p1 = iDb;
 96370          aOp[0].p2 = pTab->tnum;
 96371          aOp[0].p3 = wrFlag;
 96372          sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
 96373        }
 96374        if( db->mallocFailed==0 ){
 96375  #endif
 96376  
 96377          /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
 96378          ** parameter of the other to pTab->tnum.  */
 96379          if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
 96380          aOp[1].p2 = pTab->tnum;
 96381          aOp[1].p3 = iDb;   
 96382  
 96383          /* Configure the number of columns. Configure the cursor to
 96384          ** think that the table has one more column than it really
 96385          ** does. An OP_Column to retrieve this imaginary column will
 96386          ** always return an SQL NULL. This is useful because it means
 96387          ** we can invoke OP_Column to fill in the vdbe cursors type 
 96388          ** and offset cache without causing any IO.
 96389          */
 96390          aOp[1].p4type = P4_INT32;
 96391          aOp[1].p4.i = pTab->nCol+1;
 96392          aOp[3].p2 = pTab->nCol;
 96393  
 96394          sParse.nVar = 0;
 96395          sParse.nMem = 1;
 96396          sParse.nTab = 1;
 96397          sqlite3VdbeMakeReady(v, &sParse);
 96398        }
 96399      }
 96400     
 96401      pBlob->iCol = iCol;
 96402      pBlob->db = db;
 96403      sqlite3BtreeLeaveAll(db);
 96404      if( db->mallocFailed ){
 96405        goto blob_open_out;
 96406      }
 96407      rc = blobSeekToRow(pBlob, iRow, &zErr);
 96408    } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
 96409  
 96410  blob_open_out:
 96411    if( rc==SQLITE_OK && db->mallocFailed==0 ){
 96412      *ppBlob = (sqlite3_blob *)pBlob;
 96413    }else{
 96414      if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
 96415      sqlite3DbFree(db, pBlob);
 96416    }
 96417    sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
 96418    sqlite3DbFree(db, zErr);
 96419    sqlite3ParserReset(&sParse);
 96420    rc = sqlite3ApiExit(db, rc);
 96421    sqlite3_mutex_leave(db->mutex);
 96422    return rc;
 96423  }
 96424  
 96425  /*
 96426  ** Close a blob handle that was previously created using
 96427  ** sqlite3_blob_open().
 96428  */
 96429  SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
 96430    Incrblob *p = (Incrblob *)pBlob;
 96431    int rc;
 96432    sqlite3 *db;
 96433  
 96434    if( p ){
 96435      db = p->db;
 96436      sqlite3_mutex_enter(db->mutex);
 96437      rc = sqlite3_finalize(p->pStmt);
 96438      sqlite3DbFree(db, p);
 96439      sqlite3_mutex_leave(db->mutex);
 96440    }else{
 96441      rc = SQLITE_OK;
 96442    }
 96443    return rc;
 96444  }
 96445  
 96446  /*
 96447  ** Perform a read or write operation on a blob
 96448  */
 96449  static int blobReadWrite(
 96450    sqlite3_blob *pBlob, 
 96451    void *z, 
 96452    int n, 
 96453    int iOffset, 
 96454    int (*xCall)(BtCursor*, u32, u32, void*)
 96455  ){
 96456    int rc;
 96457    Incrblob *p = (Incrblob *)pBlob;
 96458    Vdbe *v;
 96459    sqlite3 *db;
 96460  
 96461    if( p==0 ) return SQLITE_MISUSE_BKPT;
 96462    db = p->db;
 96463    sqlite3_mutex_enter(db->mutex);
 96464    v = (Vdbe*)p->pStmt;
 96465  
 96466    if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
 96467      /* Request is out of range. Return a transient error. */
 96468      rc = SQLITE_ERROR;
 96469    }else if( v==0 ){
 96470      /* If there is no statement handle, then the blob-handle has
 96471      ** already been invalidated. Return SQLITE_ABORT in this case.
 96472      */
 96473      rc = SQLITE_ABORT;
 96474    }else{
 96475      /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
 96476      ** returned, clean-up the statement handle.
 96477      */
 96478      assert( db == v->db );
 96479      sqlite3BtreeEnterCursor(p->pCsr);
 96480  
 96481  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 96482      if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
 96483        /* If a pre-update hook is registered and this is a write cursor, 
 96484        ** invoke it here. 
 96485        ** 
 96486        ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
 96487        ** operation should really be an SQLITE_UPDATE. This is probably
 96488        ** incorrect, but is convenient because at this point the new.* values 
 96489        ** are not easily obtainable. And for the sessions module, an 
 96490        ** SQLITE_UPDATE where the PK columns do not change is handled in the 
 96491        ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
 96492        ** slightly more efficient). Since you cannot write to a PK column
 96493        ** using the incremental-blob API, this works. For the sessions module
 96494        ** anyhow.
 96495        */
 96496        sqlite3_int64 iKey;
 96497        iKey = sqlite3BtreeIntegerKey(p->pCsr);
 96498        sqlite3VdbePreUpdateHook(
 96499            v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
 96500        );
 96501      }
 96502  #endif
 96503  
 96504      rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
 96505      sqlite3BtreeLeaveCursor(p->pCsr);
 96506      if( rc==SQLITE_ABORT ){
 96507        sqlite3VdbeFinalize(v);
 96508        p->pStmt = 0;
 96509      }else{
 96510        v->rc = rc;
 96511      }
 96512    }
 96513    sqlite3Error(db, rc);
 96514    rc = sqlite3ApiExit(db, rc);
 96515    sqlite3_mutex_leave(db->mutex);
 96516    return rc;
 96517  }
 96518  
 96519  /*
 96520  ** Read data from a blob handle.
 96521  */
 96522  SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
 96523    return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
 96524  }
 96525  
 96526  /*
 96527  ** Write data to a blob handle.
 96528  */
 96529  SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
 96530    return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
 96531  }
 96532  
 96533  /*
 96534  ** Query a blob handle for the size of the data.
 96535  **
 96536  ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
 96537  ** so no mutex is required for access.
 96538  */
 96539  SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
 96540    Incrblob *p = (Incrblob *)pBlob;
 96541    return (p && p->pStmt) ? p->nByte : 0;
 96542  }
 96543  
 96544  /*
 96545  ** Move an existing blob handle to point to a different row of the same
 96546  ** database table.
 96547  **
 96548  ** If an error occurs, or if the specified row does not exist or does not
 96549  ** contain a blob or text value, then an error code is returned and the
 96550  ** database handle error code and message set. If this happens, then all 
 96551  ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
 96552  ** immediately return SQLITE_ABORT.
 96553  */
 96554  SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 96555    int rc;
 96556    Incrblob *p = (Incrblob *)pBlob;
 96557    sqlite3 *db;
 96558  
 96559    if( p==0 ) return SQLITE_MISUSE_BKPT;
 96560    db = p->db;
 96561    sqlite3_mutex_enter(db->mutex);
 96562  
 96563    if( p->pStmt==0 ){
 96564      /* If there is no statement handle, then the blob-handle has
 96565      ** already been invalidated. Return SQLITE_ABORT in this case.
 96566      */
 96567      rc = SQLITE_ABORT;
 96568    }else{
 96569      char *zErr;
 96570      rc = blobSeekToRow(p, iRow, &zErr);
 96571      if( rc!=SQLITE_OK ){
 96572        sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
 96573        sqlite3DbFree(db, zErr);
 96574      }
 96575      assert( rc!=SQLITE_SCHEMA );
 96576    }
 96577  
 96578    rc = sqlite3ApiExit(db, rc);
 96579    assert( rc==SQLITE_OK || p->pStmt==0 );
 96580    sqlite3_mutex_leave(db->mutex);
 96581    return rc;
 96582  }
 96583  
 96584  #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
 96585  
 96586  /************** End of vdbeblob.c ********************************************/
 96587  /************** Begin file vdbesort.c ****************************************/
 96588  /*
 96589  ** 2011-07-09
 96590  **
 96591  ** The author disclaims copyright to this source code.  In place of
 96592  ** a legal notice, here is a blessing:
 96593  **
 96594  **    May you do good and not evil.
 96595  **    May you find forgiveness for yourself and forgive others.
 96596  **    May you share freely, never taking more than you give.
 96597  **
 96598  *************************************************************************
 96599  ** This file contains code for the VdbeSorter object, used in concert with
 96600  ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
 96601  ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
 96602  ** using indexes and without LIMIT clauses.
 96603  **
 96604  ** The VdbeSorter object implements a multi-threaded external merge sort
 96605  ** algorithm that is efficient even if the number of elements being sorted
 96606  ** exceeds the available memory.
 96607  **
 96608  ** Here is the (internal, non-API) interface between this module and the
 96609  ** rest of the SQLite system:
 96610  **
 96611  **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
 96612  **
 96613  **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
 96614  **                                  object.  The row is a binary blob in the
 96615  **                                  OP_MakeRecord format that contains both
 96616  **                                  the ORDER BY key columns and result columns
 96617  **                                  in the case of a SELECT w/ ORDER BY, or
 96618  **                                  the complete record for an index entry
 96619  **                                  in the case of a CREATE INDEX.
 96620  **
 96621  **    sqlite3VdbeSorterRewind()     Sort all content previously added.
 96622  **                                  Position the read cursor on the
 96623  **                                  first sorted element.
 96624  **
 96625  **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
 96626  **                                  element.
 96627  **
 96628  **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
 96629  **                                  row currently under the read cursor.
 96630  **
 96631  **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
 96632  **                                  currently under the read cursor against
 96633  **                                  another binary blob X and report if
 96634  **                                  X is strictly less than the read cursor.
 96635  **                                  Used to enforce uniqueness in a
 96636  **                                  CREATE UNIQUE INDEX statement.
 96637  **
 96638  **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
 96639  **                                  all resources.
 96640  **
 96641  **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
 96642  **                                  is like Close() followed by Init() only
 96643  **                                  much faster.
 96644  **
 96645  ** The interfaces above must be called in a particular order.  Write() can 
 96646  ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
 96647  ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
 96648  **
 96649  **   Init()
 96650  **   for each record: Write()
 96651  **   Rewind()
 96652  **     Rowkey()/Compare()
 96653  **   Next() 
 96654  **   Close()
 96655  **
 96656  ** Algorithm:
 96657  **
 96658  ** Records passed to the sorter via calls to Write() are initially held 
 96659  ** unsorted in main memory. Assuming the amount of memory used never exceeds
 96660  ** a threshold, when Rewind() is called the set of records is sorted using
 96661  ** an in-memory merge sort. In this case, no temporary files are required
 96662  ** and subsequent calls to Rowkey(), Next() and Compare() read records 
 96663  ** directly from main memory.
 96664  **
 96665  ** If the amount of space used to store records in main memory exceeds the
 96666  ** threshold, then the set of records currently in memory are sorted and
 96667  ** written to a temporary file in "Packed Memory Array" (PMA) format.
 96668  ** A PMA created at this point is known as a "level-0 PMA". Higher levels
 96669  ** of PMAs may be created by merging existing PMAs together - for example
 96670  ** merging two or more level-0 PMAs together creates a level-1 PMA.
 96671  **
 96672  ** The threshold for the amount of main memory to use before flushing 
 96673  ** records to a PMA is roughly the same as the limit configured for the
 96674  ** page-cache of the main database. Specifically, the threshold is set to 
 96675  ** the value returned by "PRAGMA main.page_size" multipled by 
 96676  ** that returned by "PRAGMA main.cache_size", in bytes.
 96677  **
 96678  ** If the sorter is running in single-threaded mode, then all PMAs generated
 96679  ** are appended to a single temporary file. Or, if the sorter is running in
 96680  ** multi-threaded mode then up to (N+1) temporary files may be opened, where
 96681  ** N is the configured number of worker threads. In this case, instead of
 96682  ** sorting the records and writing the PMA to a temporary file itself, the
 96683  ** calling thread usually launches a worker thread to do so. Except, if
 96684  ** there are already N worker threads running, the main thread does the work
 96685  ** itself.
 96686  **
 96687  ** The sorter is running in multi-threaded mode if (a) the library was built
 96688  ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
 96689  ** than zero, and (b) worker threads have been enabled at runtime by calling
 96690  ** "PRAGMA threads=N" with some value of N greater than 0.
 96691  **
 96692  ** When Rewind() is called, any data remaining in memory is flushed to a 
 96693  ** final PMA. So at this point the data is stored in some number of sorted
 96694  ** PMAs within temporary files on disk.
 96695  **
 96696  ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
 96697  ** sorter is running in single-threaded mode, then these PMAs are merged
 96698  ** incrementally as keys are retreived from the sorter by the VDBE.  The
 96699  ** MergeEngine object, described in further detail below, performs this
 96700  ** merge.
 96701  **
 96702  ** Or, if running in multi-threaded mode, then a background thread is
 96703  ** launched to merge the existing PMAs. Once the background thread has
 96704  ** merged T bytes of data into a single sorted PMA, the main thread 
 96705  ** begins reading keys from that PMA while the background thread proceeds
 96706  ** with merging the next T bytes of data. And so on.
 96707  **
 96708  ** Parameter T is set to half the value of the memory threshold used 
 96709  ** by Write() above to determine when to create a new PMA.
 96710  **
 96711  ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when 
 96712  ** Rewind() is called, then a hierarchy of incremental-merges is used. 
 96713  ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on 
 96714  ** disk are merged together. Then T bytes of data from the second set, and
 96715  ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
 96716  ** PMAs at a time. This done is to improve locality.
 96717  **
 96718  ** If running in multi-threaded mode and there are more than
 96719  ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
 96720  ** than one background thread may be created. Specifically, there may be
 96721  ** one background thread for each temporary file on disk, and one background
 96722  ** thread to merge the output of each of the others to a single PMA for
 96723  ** the main thread to read from.
 96724  */
 96725  /* #include "sqliteInt.h" */
 96726  /* #include "vdbeInt.h" */
 96727  
 96728  /* 
 96729  ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
 96730  ** messages to stderr that may be helpful in understanding the performance
 96731  ** characteristics of the sorter in multi-threaded mode.
 96732  */
 96733  #if 0
 96734  # define SQLITE_DEBUG_SORTER_THREADS 1
 96735  #endif
 96736  
 96737  /*
 96738  ** Hard-coded maximum amount of data to accumulate in memory before flushing
 96739  ** to a level 0 PMA. The purpose of this limit is to prevent various integer
 96740  ** overflows. 512MiB.
 96741  */
 96742  #define SQLITE_MAX_PMASZ    (1<<29)
 96743  
 96744  /*
 96745  ** Private objects used by the sorter
 96746  */
 96747  typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
 96748  typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
 96749  typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
 96750  typedef struct SorterRecord SorterRecord;   /* A record being sorted */
 96751  typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
 96752  typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
 96753  typedef struct SorterList SorterList;       /* In-memory list of records */
 96754  typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
 96755  
 96756  /*
 96757  ** A container for a temp file handle and the current amount of data 
 96758  ** stored in the file.
 96759  */
 96760  struct SorterFile {
 96761    sqlite3_file *pFd;              /* File handle */
 96762    i64 iEof;                       /* Bytes of data stored in pFd */
 96763  };
 96764  
 96765  /*
 96766  ** An in-memory list of objects to be sorted.
 96767  **
 96768  ** If aMemory==0 then each object is allocated separately and the objects
 96769  ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
 96770  ** are stored in the aMemory[] bulk memory, one right after the other, and
 96771  ** are connected using SorterRecord.u.iNext.
 96772  */
 96773  struct SorterList {
 96774    SorterRecord *pList;            /* Linked list of records */
 96775    u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
 96776    int szPMA;                      /* Size of pList as PMA in bytes */
 96777  };
 96778  
 96779  /*
 96780  ** The MergeEngine object is used to combine two or more smaller PMAs into
 96781  ** one big PMA using a merge operation.  Separate PMAs all need to be
 96782  ** combined into one big PMA in order to be able to step through the sorted
 96783  ** records in order.
 96784  **
 96785  ** The aReadr[] array contains a PmaReader object for each of the PMAs being
 96786  ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
 96787  ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
 96788  ** For the purposes of the paragraphs below, we assume that the array is
 96789  ** actually N elements in size, where N is the smallest power of 2 greater
 96790  ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
 96791  ** are treated as if they are empty (always at EOF).
 96792  **
 96793  ** The aTree[] array is also N elements in size. The value of N is stored in
 96794  ** the MergeEngine.nTree variable.
 96795  **
 96796  ** The final (N/2) elements of aTree[] contain the results of comparing
 96797  ** pairs of PMA keys together. Element i contains the result of 
 96798  ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
 96799  ** aTree element is set to the index of it. 
 96800  **
 96801  ** For the purposes of this comparison, EOF is considered greater than any
 96802  ** other key value. If the keys are equal (only possible with two EOF
 96803  ** values), it doesn't matter which index is stored.
 96804  **
 96805  ** The (N/4) elements of aTree[] that precede the final (N/2) described 
 96806  ** above contains the index of the smallest of each block of 4 PmaReaders
 96807  ** And so on. So that aTree[1] contains the index of the PmaReader that 
 96808  ** currently points to the smallest key value. aTree[0] is unused.
 96809  **
 96810  ** Example:
 96811  **
 96812  **     aReadr[0] -> Banana
 96813  **     aReadr[1] -> Feijoa
 96814  **     aReadr[2] -> Elderberry
 96815  **     aReadr[3] -> Currant
 96816  **     aReadr[4] -> Grapefruit
 96817  **     aReadr[5] -> Apple
 96818  **     aReadr[6] -> Durian
 96819  **     aReadr[7] -> EOF
 96820  **
 96821  **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
 96822  **
 96823  ** The current element is "Apple" (the value of the key indicated by 
 96824  ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
 96825  ** be advanced to the next key in its segment. Say the next key is
 96826  ** "Eggplant":
 96827  **
 96828  **     aReadr[5] -> Eggplant
 96829  **
 96830  ** The contents of aTree[] are updated first by comparing the new PmaReader
 96831  ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
 96832  ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
 96833  ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
 96834  ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
 96835  ** so the value written into element 1 of the array is 0. As follows:
 96836  **
 96837  **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
 96838  **
 96839  ** In other words, each time we advance to the next sorter element, log2(N)
 96840  ** key comparison operations are required, where N is the number of segments
 96841  ** being merged (rounded up to the next power of 2).
 96842  */
 96843  struct MergeEngine {
 96844    int nTree;                 /* Used size of aTree/aReadr (power of 2) */
 96845    SortSubtask *pTask;        /* Used by this thread only */
 96846    int *aTree;                /* Current state of incremental merge */
 96847    PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
 96848  };
 96849  
 96850  /*
 96851  ** This object represents a single thread of control in a sort operation.
 96852  ** Exactly VdbeSorter.nTask instances of this object are allocated
 96853  ** as part of each VdbeSorter object. Instances are never allocated any
 96854  ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
 96855  ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
 96856  ** single-threaded operation, there is exactly one instance of this object
 96857  ** and for multi-threaded operation there are two or more instances.
 96858  **
 96859  ** Essentially, this structure contains all those fields of the VdbeSorter
 96860  ** structure for which each thread requires a separate instance. For example,
 96861  ** each thread requries its own UnpackedRecord object to unpack records in
 96862  ** as part of comparison operations.
 96863  **
 96864  ** Before a background thread is launched, variable bDone is set to 0. Then, 
 96865  ** right before it exits, the thread itself sets bDone to 1. This is used for 
 96866  ** two purposes:
 96867  **
 96868  **   1. When flushing the contents of memory to a level-0 PMA on disk, to
 96869  **      attempt to select a SortSubtask for which there is not already an
 96870  **      active background thread (since doing so causes the main thread
 96871  **      to block until it finishes).
 96872  **
 96873  **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
 96874  **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
 96875  **      block provoke debugging output.
 96876  **
 96877  ** In both cases, the effects of the main thread seeing (bDone==0) even
 96878  ** after the thread has finished are not dire. So we don't worry about
 96879  ** memory barriers and such here.
 96880  */
 96881  typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
 96882  struct SortSubtask {
 96883    SQLiteThread *pThread;          /* Background thread, if any */
 96884    int bDone;                      /* Set if thread is finished but not joined */
 96885    VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
 96886    UnpackedRecord *pUnpacked;      /* Space to unpack a record */
 96887    SorterList list;                /* List for thread to write to a PMA */
 96888    int nPMA;                       /* Number of PMAs currently in file */
 96889    SorterCompare xCompare;         /* Compare function to use */
 96890    SorterFile file;                /* Temp file for level-0 PMAs */
 96891    SorterFile file2;               /* Space for other PMAs */
 96892  };
 96893  
 96894  
 96895  /*
 96896  ** Main sorter structure. A single instance of this is allocated for each 
 96897  ** sorter cursor created by the VDBE.
 96898  **
 96899  ** mxKeysize:
 96900  **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
 96901  **   this variable is updated so as to be set to the size on disk of the
 96902  **   largest record in the sorter.
 96903  */
 96904  struct VdbeSorter {
 96905    int mnPmaSize;                  /* Minimum PMA size, in bytes */
 96906    int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
 96907    int mxKeysize;                  /* Largest serialized key seen so far */
 96908    int pgsz;                       /* Main database page size */
 96909    PmaReader *pReader;             /* Readr data from here after Rewind() */
 96910    MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
 96911    sqlite3 *db;                    /* Database connection */
 96912    KeyInfo *pKeyInfo;              /* How to compare records */
 96913    UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
 96914    SorterList list;                /* List of in-memory records */
 96915    int iMemory;                    /* Offset of free space in list.aMemory */
 96916    int nMemory;                    /* Size of list.aMemory allocation in bytes */
 96917    u8 bUsePMA;                     /* True if one or more PMAs created */
 96918    u8 bUseThreads;                 /* True to use background threads */
 96919    u8 iPrev;                       /* Previous thread used to flush PMA */
 96920    u8 nTask;                       /* Size of aTask[] array */
 96921    u8 typeMask;
 96922    SortSubtask aTask[1];           /* One or more subtasks */
 96923  };
 96924  
 96925  #define SORTER_TYPE_INTEGER 0x01
 96926  #define SORTER_TYPE_TEXT    0x02
 96927  
 96928  /*
 96929  ** An instance of the following object is used to read records out of a
 96930  ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
 96931  ** aKey might point into aMap or into aBuffer.  If neither of those locations
 96932  ** contain a contiguous representation of the key, then aAlloc is allocated
 96933  ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
 96934  **
 96935  ** pFd==0 at EOF.
 96936  */
 96937  struct PmaReader {
 96938    i64 iReadOff;               /* Current read offset */
 96939    i64 iEof;                   /* 1 byte past EOF for this PmaReader */
 96940    int nAlloc;                 /* Bytes of space at aAlloc */
 96941    int nKey;                   /* Number of bytes in key */
 96942    sqlite3_file *pFd;          /* File handle we are reading from */
 96943    u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
 96944    u8 *aKey;                   /* Pointer to current key */
 96945    u8 *aBuffer;                /* Current read buffer */
 96946    int nBuffer;                /* Size of read buffer in bytes */
 96947    u8 *aMap;                   /* Pointer to mapping of entire file */
 96948    IncrMerger *pIncr;          /* Incremental merger */
 96949  };
 96950  
 96951  /*
 96952  ** Normally, a PmaReader object iterates through an existing PMA stored 
 96953  ** within a temp file. However, if the PmaReader.pIncr variable points to
 96954  ** an object of the following type, it may be used to iterate/merge through
 96955  ** multiple PMAs simultaneously.
 96956  **
 96957  ** There are two types of IncrMerger object - single (bUseThread==0) and 
 96958  ** multi-threaded (bUseThread==1). 
 96959  **
 96960  ** A multi-threaded IncrMerger object uses two temporary files - aFile[0] 
 96961  ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in 
 96962  ** size. When the IncrMerger is initialized, it reads enough data from 
 96963  ** pMerger to populate aFile[0]. It then sets variables within the 
 96964  ** corresponding PmaReader object to read from that file and kicks off 
 96965  ** a background thread to populate aFile[1] with the next mxSz bytes of 
 96966  ** sorted record data from pMerger. 
 96967  **
 96968  ** When the PmaReader reaches the end of aFile[0], it blocks until the
 96969  ** background thread has finished populating aFile[1]. It then exchanges
 96970  ** the contents of the aFile[0] and aFile[1] variables within this structure,
 96971  ** sets the PmaReader fields to read from the new aFile[0] and kicks off
 96972  ** another background thread to populate the new aFile[1]. And so on, until
 96973  ** the contents of pMerger are exhausted.
 96974  **
 96975  ** A single-threaded IncrMerger does not open any temporary files of its
 96976  ** own. Instead, it has exclusive access to mxSz bytes of space beginning
 96977  ** at offset iStartOff of file pTask->file2. And instead of using a 
 96978  ** background thread to prepare data for the PmaReader, with a single
 96979  ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
 96980  ** keys from pMerger by the calling thread whenever the PmaReader runs out
 96981  ** of data.
 96982  */
 96983  struct IncrMerger {
 96984    SortSubtask *pTask;             /* Task that owns this merger */
 96985    MergeEngine *pMerger;           /* Merge engine thread reads data from */
 96986    i64 iStartOff;                  /* Offset to start writing file at */
 96987    int mxSz;                       /* Maximum bytes of data to store */
 96988    int bEof;                       /* Set to true when merge is finished */
 96989    int bUseThread;                 /* True to use a bg thread for this object */
 96990    SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
 96991  };
 96992  
 96993  /*
 96994  ** An instance of this object is used for writing a PMA.
 96995  **
 96996  ** The PMA is written one record at a time.  Each record is of an arbitrary
 96997  ** size.  But I/O is more efficient if it occurs in page-sized blocks where
 96998  ** each block is aligned on a page boundary.  This object caches writes to
 96999  ** the PMA so that aligned, page-size blocks are written.
 97000  */
 97001  struct PmaWriter {
 97002    int eFWErr;                     /* Non-zero if in an error state */
 97003    u8 *aBuffer;                    /* Pointer to write buffer */
 97004    int nBuffer;                    /* Size of write buffer in bytes */
 97005    int iBufStart;                  /* First byte of buffer to write */
 97006    int iBufEnd;                    /* Last byte of buffer to write */
 97007    i64 iWriteOff;                  /* Offset of start of buffer in file */
 97008    sqlite3_file *pFd;              /* File handle to write to */
 97009  };
 97010  
 97011  /*
 97012  ** This object is the header on a single record while that record is being
 97013  ** held in memory and prior to being written out as part of a PMA.
 97014  **
 97015  ** How the linked list is connected depends on how memory is being managed
 97016  ** by this module. If using a separate allocation for each in-memory record
 97017  ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
 97018  ** SorterRecord.u.pNext pointers.
 97019  **
 97020  ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
 97021  ** then while records are being accumulated the list is linked using the
 97022  ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
 97023  ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
 97024  ** has finished passing records to the sorter, or when the in-memory buffer
 97025  ** is full, the list is sorted. As part of the sorting process, it is
 97026  ** converted to use the SorterRecord.u.pNext pointers. See function
 97027  ** vdbeSorterSort() for details.
 97028  */
 97029  struct SorterRecord {
 97030    int nVal;                       /* Size of the record in bytes */
 97031    union {
 97032      SorterRecord *pNext;          /* Pointer to next record in list */
 97033      int iNext;                    /* Offset within aMemory of next record */
 97034    } u;
 97035    /* The data for the record immediately follows this header */
 97036  };
 97037  
 97038  /* Return a pointer to the buffer containing the record data for SorterRecord
 97039  ** object p. Should be used as if:
 97040  **
 97041  **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
 97042  */
 97043  #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
 97044  
 97045  
 97046  /* Maximum number of PMAs that a single MergeEngine can merge */
 97047  #define SORTER_MAX_MERGE_COUNT 16
 97048  
 97049  static int vdbeIncrSwap(IncrMerger*);
 97050  static void vdbeIncrFree(IncrMerger *);
 97051  
 97052  /*
 97053  ** Free all memory belonging to the PmaReader object passed as the
 97054  ** argument. All structure fields are set to zero before returning.
 97055  */
 97056  static void vdbePmaReaderClear(PmaReader *pReadr){
 97057    sqlite3_free(pReadr->aAlloc);
 97058    sqlite3_free(pReadr->aBuffer);
 97059    if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
 97060    vdbeIncrFree(pReadr->pIncr);
 97061    memset(pReadr, 0, sizeof(PmaReader));
 97062  }
 97063  
 97064  /*
 97065  ** Read the next nByte bytes of data from the PMA p.
 97066  ** If successful, set *ppOut to point to a buffer containing the data
 97067  ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
 97068  ** error code.
 97069  **
 97070  ** The buffer returned in *ppOut is only valid until the
 97071  ** next call to this function.
 97072  */
 97073  static int vdbePmaReadBlob(
 97074    PmaReader *p,                   /* PmaReader from which to take the blob */
 97075    int nByte,                      /* Bytes of data to read */
 97076    u8 **ppOut                      /* OUT: Pointer to buffer containing data */
 97077  ){
 97078    int iBuf;                       /* Offset within buffer to read from */
 97079    int nAvail;                     /* Bytes of data available in buffer */
 97080  
 97081    if( p->aMap ){
 97082      *ppOut = &p->aMap[p->iReadOff];
 97083      p->iReadOff += nByte;
 97084      return SQLITE_OK;
 97085    }
 97086  
 97087    assert( p->aBuffer );
 97088  
 97089    /* If there is no more data to be read from the buffer, read the next 
 97090    ** p->nBuffer bytes of data from the file into it. Or, if there are less
 97091    ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
 97092    iBuf = p->iReadOff % p->nBuffer;
 97093    if( iBuf==0 ){
 97094      int nRead;                    /* Bytes to read from disk */
 97095      int rc;                       /* sqlite3OsRead() return code */
 97096  
 97097      /* Determine how many bytes of data to read. */
 97098      if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
 97099        nRead = p->nBuffer;
 97100      }else{
 97101        nRead = (int)(p->iEof - p->iReadOff);
 97102      }
 97103      assert( nRead>0 );
 97104  
 97105      /* Readr data from the file. Return early if an error occurs. */
 97106      rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
 97107      assert( rc!=SQLITE_IOERR_SHORT_READ );
 97108      if( rc!=SQLITE_OK ) return rc;
 97109    }
 97110    nAvail = p->nBuffer - iBuf; 
 97111  
 97112    if( nByte<=nAvail ){
 97113      /* The requested data is available in the in-memory buffer. In this
 97114      ** case there is no need to make a copy of the data, just return a 
 97115      ** pointer into the buffer to the caller.  */
 97116      *ppOut = &p->aBuffer[iBuf];
 97117      p->iReadOff += nByte;
 97118    }else{
 97119      /* The requested data is not all available in the in-memory buffer.
 97120      ** In this case, allocate space at p->aAlloc[] to copy the requested
 97121      ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
 97122      int nRem;                     /* Bytes remaining to copy */
 97123  
 97124      /* Extend the p->aAlloc[] allocation if required. */
 97125      if( p->nAlloc<nByte ){
 97126        u8 *aNew;
 97127        int nNew = MAX(128, p->nAlloc*2);
 97128        while( nByte>nNew ) nNew = nNew*2;
 97129        aNew = sqlite3Realloc(p->aAlloc, nNew);
 97130        if( !aNew ) return SQLITE_NOMEM_BKPT;
 97131        p->nAlloc = nNew;
 97132        p->aAlloc = aNew;
 97133      }
 97134  
 97135      /* Copy as much data as is available in the buffer into the start of
 97136      ** p->aAlloc[].  */
 97137      memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
 97138      p->iReadOff += nAvail;
 97139      nRem = nByte - nAvail;
 97140  
 97141      /* The following loop copies up to p->nBuffer bytes per iteration into
 97142      ** the p->aAlloc[] buffer.  */
 97143      while( nRem>0 ){
 97144        int rc;                     /* vdbePmaReadBlob() return code */
 97145        int nCopy;                  /* Number of bytes to copy */
 97146        u8 *aNext;                  /* Pointer to buffer to copy data from */
 97147  
 97148        nCopy = nRem;
 97149        if( nRem>p->nBuffer ) nCopy = p->nBuffer;
 97150        rc = vdbePmaReadBlob(p, nCopy, &aNext);
 97151        if( rc!=SQLITE_OK ) return rc;
 97152        assert( aNext!=p->aAlloc );
 97153        memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
 97154        nRem -= nCopy;
 97155      }
 97156  
 97157      *ppOut = p->aAlloc;
 97158    }
 97159  
 97160    return SQLITE_OK;
 97161  }
 97162  
 97163  /*
 97164  ** Read a varint from the stream of data accessed by p. Set *pnOut to
 97165  ** the value read.
 97166  */
 97167  static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
 97168    int iBuf;
 97169  
 97170    if( p->aMap ){
 97171      p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
 97172    }else{
 97173      iBuf = p->iReadOff % p->nBuffer;
 97174      if( iBuf && (p->nBuffer-iBuf)>=9 ){
 97175        p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
 97176      }else{
 97177        u8 aVarint[16], *a;
 97178        int i = 0, rc;
 97179        do{
 97180          rc = vdbePmaReadBlob(p, 1, &a);
 97181          if( rc ) return rc;
 97182          aVarint[(i++)&0xf] = a[0];
 97183        }while( (a[0]&0x80)!=0 );
 97184        sqlite3GetVarint(aVarint, pnOut);
 97185      }
 97186    }
 97187  
 97188    return SQLITE_OK;
 97189  }
 97190  
 97191  /*
 97192  ** Attempt to memory map file pFile. If successful, set *pp to point to the
 97193  ** new mapping and return SQLITE_OK. If the mapping is not attempted 
 97194  ** (because the file is too large or the VFS layer is configured not to use
 97195  ** mmap), return SQLITE_OK and set *pp to NULL.
 97196  **
 97197  ** Or, if an error occurs, return an SQLite error code. The final value of
 97198  ** *pp is undefined in this case.
 97199  */
 97200  static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
 97201    int rc = SQLITE_OK;
 97202    if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
 97203      sqlite3_file *pFd = pFile->pFd;
 97204      if( pFd->pMethods->iVersion>=3 ){
 97205        rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
 97206        testcase( rc!=SQLITE_OK );
 97207      }
 97208    }
 97209    return rc;
 97210  }
 97211  
 97212  /*
 97213  ** Attach PmaReader pReadr to file pFile (if it is not already attached to
 97214  ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK 
 97215  ** if successful, or an SQLite error code if an error occurs.
 97216  */
 97217  static int vdbePmaReaderSeek(
 97218    SortSubtask *pTask,             /* Task context */
 97219    PmaReader *pReadr,              /* Reader whose cursor is to be moved */
 97220    SorterFile *pFile,              /* Sorter file to read from */
 97221    i64 iOff                        /* Offset in pFile */
 97222  ){
 97223    int rc = SQLITE_OK;
 97224  
 97225    assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
 97226  
 97227    if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
 97228    if( pReadr->aMap ){
 97229      sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
 97230      pReadr->aMap = 0;
 97231    }
 97232    pReadr->iReadOff = iOff;
 97233    pReadr->iEof = pFile->iEof;
 97234    pReadr->pFd = pFile->pFd;
 97235  
 97236    rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
 97237    if( rc==SQLITE_OK && pReadr->aMap==0 ){
 97238      int pgsz = pTask->pSorter->pgsz;
 97239      int iBuf = pReadr->iReadOff % pgsz;
 97240      if( pReadr->aBuffer==0 ){
 97241        pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
 97242        if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
 97243        pReadr->nBuffer = pgsz;
 97244      }
 97245      if( rc==SQLITE_OK && iBuf ){
 97246        int nRead = pgsz - iBuf;
 97247        if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
 97248          nRead = (int)(pReadr->iEof - pReadr->iReadOff);
 97249        }
 97250        rc = sqlite3OsRead(
 97251            pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
 97252        );
 97253        testcase( rc!=SQLITE_OK );
 97254      }
 97255    }
 97256  
 97257    return rc;
 97258  }
 97259  
 97260  /*
 97261  ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
 97262  ** no error occurs, or an SQLite error code if one does.
 97263  */
 97264  static int vdbePmaReaderNext(PmaReader *pReadr){
 97265    int rc = SQLITE_OK;             /* Return Code */
 97266    u64 nRec = 0;                   /* Size of record in bytes */
 97267  
 97268  
 97269    if( pReadr->iReadOff>=pReadr->iEof ){
 97270      IncrMerger *pIncr = pReadr->pIncr;
 97271      int bEof = 1;
 97272      if( pIncr ){
 97273        rc = vdbeIncrSwap(pIncr);
 97274        if( rc==SQLITE_OK && pIncr->bEof==0 ){
 97275          rc = vdbePmaReaderSeek(
 97276              pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
 97277          );
 97278          bEof = 0;
 97279        }
 97280      }
 97281  
 97282      if( bEof ){
 97283        /* This is an EOF condition */
 97284        vdbePmaReaderClear(pReadr);
 97285        testcase( rc!=SQLITE_OK );
 97286        return rc;
 97287      }
 97288    }
 97289  
 97290    if( rc==SQLITE_OK ){
 97291      rc = vdbePmaReadVarint(pReadr, &nRec);
 97292    }
 97293    if( rc==SQLITE_OK ){
 97294      pReadr->nKey = (int)nRec;
 97295      rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
 97296      testcase( rc!=SQLITE_OK );
 97297    }
 97298  
 97299    return rc;
 97300  }
 97301  
 97302  /*
 97303  ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
 97304  ** starting at offset iStart and ending at offset iEof-1. This function 
 97305  ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 
 97306  ** PMA is empty).
 97307  **
 97308  ** If the pnByte parameter is NULL, then it is assumed that the file 
 97309  ** contains a single PMA, and that that PMA omits the initial length varint.
 97310  */
 97311  static int vdbePmaReaderInit(
 97312    SortSubtask *pTask,             /* Task context */
 97313    SorterFile *pFile,              /* Sorter file to read from */
 97314    i64 iStart,                     /* Start offset in pFile */
 97315    PmaReader *pReadr,              /* PmaReader to populate */
 97316    i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
 97317  ){
 97318    int rc;
 97319  
 97320    assert( pFile->iEof>iStart );
 97321    assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
 97322    assert( pReadr->aBuffer==0 );
 97323    assert( pReadr->aMap==0 );
 97324  
 97325    rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
 97326    if( rc==SQLITE_OK ){
 97327      u64 nByte = 0;                 /* Size of PMA in bytes */
 97328      rc = vdbePmaReadVarint(pReadr, &nByte);
 97329      pReadr->iEof = pReadr->iReadOff + nByte;
 97330      *pnByte += nByte;
 97331    }
 97332  
 97333    if( rc==SQLITE_OK ){
 97334      rc = vdbePmaReaderNext(pReadr);
 97335    }
 97336    return rc;
 97337  }
 97338  
 97339  /*
 97340  ** A version of vdbeSorterCompare() that assumes that it has already been
 97341  ** determined that the first field of key1 is equal to the first field of 
 97342  ** key2.
 97343  */
 97344  static int vdbeSorterCompareTail(
 97345    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 97346    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 97347    const void *pKey1, int nKey1,   /* Left side of comparison */
 97348    const void *pKey2, int nKey2    /* Right side of comparison */
 97349  ){
 97350    UnpackedRecord *r2 = pTask->pUnpacked;
 97351    if( *pbKey2Cached==0 ){
 97352      sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
 97353      *pbKey2Cached = 1;
 97354    }
 97355    return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
 97356  }
 97357  
 97358  /*
 97359  ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
 97360  ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
 97361  ** used by the comparison. Return the result of the comparison.
 97362  **
 97363  ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
 97364  ** it is assumed that (pTask->pUnpacked) contains the unpacked version
 97365  ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
 97366  ** version of key2 and *pbKey2Cached set to true before returning.
 97367  **
 97368  ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
 97369  ** to SQLITE_NOMEM.
 97370  */
 97371  static int vdbeSorterCompare(
 97372    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 97373    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 97374    const void *pKey1, int nKey1,   /* Left side of comparison */
 97375    const void *pKey2, int nKey2    /* Right side of comparison */
 97376  ){
 97377    UnpackedRecord *r2 = pTask->pUnpacked;
 97378    if( !*pbKey2Cached ){
 97379      sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
 97380      *pbKey2Cached = 1;
 97381    }
 97382    return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
 97383  }
 97384  
 97385  /*
 97386  ** A specially optimized version of vdbeSorterCompare() that assumes that
 97387  ** the first field of each key is a TEXT value and that the collation
 97388  ** sequence to compare them with is BINARY.
 97389  */
 97390  static int vdbeSorterCompareText(
 97391    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 97392    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 97393    const void *pKey1, int nKey1,   /* Left side of comparison */
 97394    const void *pKey2, int nKey2    /* Right side of comparison */
 97395  ){
 97396    const u8 * const p1 = (const u8 * const)pKey1;
 97397    const u8 * const p2 = (const u8 * const)pKey2;
 97398    const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
 97399    const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
 97400  
 97401    int n1;
 97402    int n2;
 97403    int res;
 97404  
 97405    getVarint32(&p1[1], n1);
 97406    getVarint32(&p2[1], n2);
 97407    res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
 97408    if( res==0 ){
 97409      res = n1 - n2;
 97410    }
 97411  
 97412    if( res==0 ){
 97413      if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
 97414        res = vdbeSorterCompareTail(
 97415            pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
 97416        );
 97417      }
 97418    }else{
 97419      if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
 97420        res = res * -1;
 97421      }
 97422    }
 97423  
 97424    return res;
 97425  }
 97426  
 97427  /*
 97428  ** A specially optimized version of vdbeSorterCompare() that assumes that
 97429  ** the first field of each key is an INTEGER value.
 97430  */
 97431  static int vdbeSorterCompareInt(
 97432    SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
 97433    int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
 97434    const void *pKey1, int nKey1,   /* Left side of comparison */
 97435    const void *pKey2, int nKey2    /* Right side of comparison */
 97436  ){
 97437    const u8 * const p1 = (const u8 * const)pKey1;
 97438    const u8 * const p2 = (const u8 * const)pKey2;
 97439    const int s1 = p1[1];                 /* Left hand serial type */
 97440    const int s2 = p2[1];                 /* Right hand serial type */
 97441    const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
 97442    const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
 97443    int res;                              /* Return value */
 97444  
 97445    assert( (s1>0 && s1<7) || s1==8 || s1==9 );
 97446    assert( (s2>0 && s2<7) || s2==8 || s2==9 );
 97447  
 97448    if( s1==s2 ){
 97449      /* The two values have the same sign. Compare using memcmp(). */
 97450      static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
 97451      const u8 n = aLen[s1];
 97452      int i;
 97453      res = 0;
 97454      for(i=0; i<n; i++){
 97455        if( (res = v1[i] - v2[i])!=0 ){
 97456          if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
 97457            res = v1[0] & 0x80 ? -1 : +1;
 97458          }
 97459          break;
 97460        }
 97461      }
 97462    }else if( s1>7 && s2>7 ){
 97463      res = s1 - s2;
 97464    }else{
 97465      if( s2>7 ){
 97466        res = +1;
 97467      }else if( s1>7 ){
 97468        res = -1;
 97469      }else{
 97470        res = s1 - s2;
 97471      }
 97472      assert( res!=0 );
 97473  
 97474      if( res>0 ){
 97475        if( *v1 & 0x80 ) res = -1;
 97476      }else{
 97477        if( *v2 & 0x80 ) res = +1;
 97478      }
 97479    }
 97480  
 97481    if( res==0 ){
 97482      if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
 97483        res = vdbeSorterCompareTail(
 97484            pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
 97485        );
 97486      }
 97487    }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
 97488      res = res * -1;
 97489    }
 97490  
 97491    return res;
 97492  }
 97493  
 97494  /*
 97495  ** Initialize the temporary index cursor just opened as a sorter cursor.
 97496  **
 97497  ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
 97498  ** to determine the number of fields that should be compared from the
 97499  ** records being sorted. However, if the value passed as argument nField
 97500  ** is non-zero and the sorter is able to guarantee a stable sort, nField
 97501  ** is used instead. This is used when sorting records for a CREATE INDEX
 97502  ** statement. In this case, keys are always delivered to the sorter in
 97503  ** order of the primary key, which happens to be make up the final part 
 97504  ** of the records being sorted. So if the sort is stable, there is never
 97505  ** any reason to compare PK fields and they can be ignored for a small
 97506  ** performance boost.
 97507  **
 97508  ** The sorter can guarantee a stable sort when running in single-threaded
 97509  ** mode, but not in multi-threaded mode.
 97510  **
 97511  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 97512  */
 97513  SQLITE_PRIVATE int sqlite3VdbeSorterInit(
 97514    sqlite3 *db,                    /* Database connection (for malloc()) */
 97515    int nField,                     /* Number of key fields in each record */
 97516    VdbeCursor *pCsr                /* Cursor that holds the new sorter */
 97517  ){
 97518    int pgsz;                       /* Page size of main database */
 97519    int i;                          /* Used to iterate through aTask[] */
 97520    VdbeSorter *pSorter;            /* The new sorter */
 97521    KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
 97522    int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
 97523    int sz;                         /* Size of pSorter in bytes */
 97524    int rc = SQLITE_OK;
 97525  #if SQLITE_MAX_WORKER_THREADS==0
 97526  # define nWorker 0
 97527  #else
 97528    int nWorker;
 97529  #endif
 97530  
 97531    /* Initialize the upper limit on the number of worker threads */
 97532  #if SQLITE_MAX_WORKER_THREADS>0
 97533    if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
 97534      nWorker = 0;
 97535    }else{
 97536      nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
 97537    }
 97538  #endif
 97539  
 97540    /* Do not allow the total number of threads (main thread + all workers)
 97541    ** to exceed the maximum merge count */
 97542  #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
 97543    if( nWorker>=SORTER_MAX_MERGE_COUNT ){
 97544      nWorker = SORTER_MAX_MERGE_COUNT-1;
 97545    }
 97546  #endif
 97547  
 97548    assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
 97549    assert( pCsr->eCurType==CURTYPE_SORTER );
 97550    szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
 97551    sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
 97552  
 97553    pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
 97554    pCsr->uc.pSorter = pSorter;
 97555    if( pSorter==0 ){
 97556      rc = SQLITE_NOMEM_BKPT;
 97557    }else{
 97558      pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
 97559      memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
 97560      pKeyInfo->db = 0;
 97561      if( nField && nWorker==0 ){
 97562        pKeyInfo->nKeyField = nField;
 97563      }
 97564      pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
 97565      pSorter->nTask = nWorker + 1;
 97566      pSorter->iPrev = (u8)(nWorker - 1);
 97567      pSorter->bUseThreads = (pSorter->nTask>1);
 97568      pSorter->db = db;
 97569      for(i=0; i<pSorter->nTask; i++){
 97570        SortSubtask *pTask = &pSorter->aTask[i];
 97571        pTask->pSorter = pSorter;
 97572      }
 97573  
 97574      if( !sqlite3TempInMemory(db) ){
 97575        i64 mxCache;                /* Cache size in bytes*/
 97576        u32 szPma = sqlite3GlobalConfig.szPma;
 97577        pSorter->mnPmaSize = szPma * pgsz;
 97578  
 97579        mxCache = db->aDb[0].pSchema->cache_size;
 97580        if( mxCache<0 ){
 97581          /* A negative cache-size value C indicates that the cache is abs(C)
 97582          ** KiB in size.  */
 97583          mxCache = mxCache * -1024;
 97584        }else{
 97585          mxCache = mxCache * pgsz;
 97586        }
 97587        mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
 97588        pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
 97589  
 97590        /* Avoid large memory allocations if the application has requested
 97591        ** SQLITE_CONFIG_SMALL_MALLOC. */
 97592        if( sqlite3GlobalConfig.bSmallMalloc==0 ){
 97593          assert( pSorter->iMemory==0 );
 97594          pSorter->nMemory = pgsz;
 97595          pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
 97596          if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
 97597        }
 97598      }
 97599  
 97600      if( pKeyInfo->nAllField<13 
 97601       && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
 97602      ){
 97603        pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
 97604      }
 97605    }
 97606  
 97607    return rc;
 97608  }
 97609  #undef nWorker   /* Defined at the top of this function */
 97610  
 97611  /*
 97612  ** Free the list of sorted records starting at pRecord.
 97613  */
 97614  static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
 97615    SorterRecord *p;
 97616    SorterRecord *pNext;
 97617    for(p=pRecord; p; p=pNext){
 97618      pNext = p->u.pNext;
 97619      sqlite3DbFree(db, p);
 97620    }
 97621  }
 97622  
 97623  /*
 97624  ** Free all resources owned by the object indicated by argument pTask. All 
 97625  ** fields of *pTask are zeroed before returning.
 97626  */
 97627  static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
 97628    sqlite3DbFree(db, pTask->pUnpacked);
 97629  #if SQLITE_MAX_WORKER_THREADS>0
 97630    /* pTask->list.aMemory can only be non-zero if it was handed memory
 97631    ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
 97632    if( pTask->list.aMemory ){
 97633      sqlite3_free(pTask->list.aMemory);
 97634    }else
 97635  #endif
 97636    {
 97637      assert( pTask->list.aMemory==0 );
 97638      vdbeSorterRecordFree(0, pTask->list.pList);
 97639    }
 97640    if( pTask->file.pFd ){
 97641      sqlite3OsCloseFree(pTask->file.pFd);
 97642    }
 97643    if( pTask->file2.pFd ){
 97644      sqlite3OsCloseFree(pTask->file2.pFd);
 97645    }
 97646    memset(pTask, 0, sizeof(SortSubtask));
 97647  }
 97648  
 97649  #ifdef SQLITE_DEBUG_SORTER_THREADS
 97650  static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
 97651    i64 t;
 97652    int iTask = (pTask - pTask->pSorter->aTask);
 97653    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 97654    fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
 97655  }
 97656  static void vdbeSorterRewindDebug(const char *zEvent){
 97657    i64 t;
 97658    sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
 97659    fprintf(stderr, "%lld:X %s\n", t, zEvent);
 97660  }
 97661  static void vdbeSorterPopulateDebug(
 97662    SortSubtask *pTask,
 97663    const char *zEvent
 97664  ){
 97665    i64 t;
 97666    int iTask = (pTask - pTask->pSorter->aTask);
 97667    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 97668    fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
 97669  }
 97670  static void vdbeSorterBlockDebug(
 97671    SortSubtask *pTask,
 97672    int bBlocked,
 97673    const char *zEvent
 97674  ){
 97675    if( bBlocked ){
 97676      i64 t;
 97677      sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
 97678      fprintf(stderr, "%lld:main %s\n", t, zEvent);
 97679    }
 97680  }
 97681  #else
 97682  # define vdbeSorterWorkDebug(x,y)
 97683  # define vdbeSorterRewindDebug(y)
 97684  # define vdbeSorterPopulateDebug(x,y)
 97685  # define vdbeSorterBlockDebug(x,y,z)
 97686  #endif
 97687  
 97688  #if SQLITE_MAX_WORKER_THREADS>0
 97689  /*
 97690  ** Join thread pTask->thread.
 97691  */
 97692  static int vdbeSorterJoinThread(SortSubtask *pTask){
 97693    int rc = SQLITE_OK;
 97694    if( pTask->pThread ){
 97695  #ifdef SQLITE_DEBUG_SORTER_THREADS
 97696      int bDone = pTask->bDone;
 97697  #endif
 97698      void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
 97699      vdbeSorterBlockDebug(pTask, !bDone, "enter");
 97700      (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
 97701      vdbeSorterBlockDebug(pTask, !bDone, "exit");
 97702      rc = SQLITE_PTR_TO_INT(pRet);
 97703      assert( pTask->bDone==1 );
 97704      pTask->bDone = 0;
 97705      pTask->pThread = 0;
 97706    }
 97707    return rc;
 97708  }
 97709  
 97710  /*
 97711  ** Launch a background thread to run xTask(pIn).
 97712  */
 97713  static int vdbeSorterCreateThread(
 97714    SortSubtask *pTask,             /* Thread will use this task object */
 97715    void *(*xTask)(void*),          /* Routine to run in a separate thread */
 97716    void *pIn                       /* Argument passed into xTask() */
 97717  ){
 97718    assert( pTask->pThread==0 && pTask->bDone==0 );
 97719    return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
 97720  }
 97721  
 97722  /*
 97723  ** Join all outstanding threads launched by SorterWrite() to create 
 97724  ** level-0 PMAs.
 97725  */
 97726  static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
 97727    int rc = rcin;
 97728    int i;
 97729  
 97730    /* This function is always called by the main user thread.
 97731    **
 97732    ** If this function is being called after SorterRewind() has been called, 
 97733    ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
 97734    ** is currently attempt to join one of the other threads. To avoid a race
 97735    ** condition where this thread also attempts to join the same object, join 
 97736    ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
 97737    for(i=pSorter->nTask-1; i>=0; i--){
 97738      SortSubtask *pTask = &pSorter->aTask[i];
 97739      int rc2 = vdbeSorterJoinThread(pTask);
 97740      if( rc==SQLITE_OK ) rc = rc2;
 97741    }
 97742    return rc;
 97743  }
 97744  #else
 97745  # define vdbeSorterJoinAll(x,rcin) (rcin)
 97746  # define vdbeSorterJoinThread(pTask) SQLITE_OK
 97747  #endif
 97748  
 97749  /*
 97750  ** Allocate a new MergeEngine object capable of handling up to
 97751  ** nReader PmaReader inputs.
 97752  **
 97753  ** nReader is automatically rounded up to the next power of two.
 97754  ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
 97755  */
 97756  static MergeEngine *vdbeMergeEngineNew(int nReader){
 97757    int N = 2;                      /* Smallest power of two >= nReader */
 97758    int nByte;                      /* Total bytes of space to allocate */
 97759    MergeEngine *pNew;              /* Pointer to allocated object to return */
 97760  
 97761    assert( nReader<=SORTER_MAX_MERGE_COUNT );
 97762  
 97763    while( N<nReader ) N += N;
 97764    nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
 97765  
 97766    pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
 97767    if( pNew ){
 97768      pNew->nTree = N;
 97769      pNew->pTask = 0;
 97770      pNew->aReadr = (PmaReader*)&pNew[1];
 97771      pNew->aTree = (int*)&pNew->aReadr[N];
 97772    }
 97773    return pNew;
 97774  }
 97775  
 97776  /*
 97777  ** Free the MergeEngine object passed as the only argument.
 97778  */
 97779  static void vdbeMergeEngineFree(MergeEngine *pMerger){
 97780    int i;
 97781    if( pMerger ){
 97782      for(i=0; i<pMerger->nTree; i++){
 97783        vdbePmaReaderClear(&pMerger->aReadr[i]);
 97784      }
 97785    }
 97786    sqlite3_free(pMerger);
 97787  }
 97788  
 97789  /*
 97790  ** Free all resources associated with the IncrMerger object indicated by
 97791  ** the first argument.
 97792  */
 97793  static void vdbeIncrFree(IncrMerger *pIncr){
 97794    if( pIncr ){
 97795  #if SQLITE_MAX_WORKER_THREADS>0
 97796      if( pIncr->bUseThread ){
 97797        vdbeSorterJoinThread(pIncr->pTask);
 97798        if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
 97799        if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
 97800      }
 97801  #endif
 97802      vdbeMergeEngineFree(pIncr->pMerger);
 97803      sqlite3_free(pIncr);
 97804    }
 97805  }
 97806  
 97807  /*
 97808  ** Reset a sorting cursor back to its original empty state.
 97809  */
 97810  SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
 97811    int i;
 97812    (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
 97813    assert( pSorter->bUseThreads || pSorter->pReader==0 );
 97814  #if SQLITE_MAX_WORKER_THREADS>0
 97815    if( pSorter->pReader ){
 97816      vdbePmaReaderClear(pSorter->pReader);
 97817      sqlite3DbFree(db, pSorter->pReader);
 97818      pSorter->pReader = 0;
 97819    }
 97820  #endif
 97821    vdbeMergeEngineFree(pSorter->pMerger);
 97822    pSorter->pMerger = 0;
 97823    for(i=0; i<pSorter->nTask; i++){
 97824      SortSubtask *pTask = &pSorter->aTask[i];
 97825      vdbeSortSubtaskCleanup(db, pTask);
 97826      pTask->pSorter = pSorter;
 97827    }
 97828    if( pSorter->list.aMemory==0 ){
 97829      vdbeSorterRecordFree(0, pSorter->list.pList);
 97830    }
 97831    pSorter->list.pList = 0;
 97832    pSorter->list.szPMA = 0;
 97833    pSorter->bUsePMA = 0;
 97834    pSorter->iMemory = 0;
 97835    pSorter->mxKeysize = 0;
 97836    sqlite3DbFree(db, pSorter->pUnpacked);
 97837    pSorter->pUnpacked = 0;
 97838  }
 97839  
 97840  /*
 97841  ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
 97842  */
 97843  SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
 97844    VdbeSorter *pSorter;
 97845    assert( pCsr->eCurType==CURTYPE_SORTER );
 97846    pSorter = pCsr->uc.pSorter;
 97847    if( pSorter ){
 97848      sqlite3VdbeSorterReset(db, pSorter);
 97849      sqlite3_free(pSorter->list.aMemory);
 97850      sqlite3DbFree(db, pSorter);
 97851      pCsr->uc.pSorter = 0;
 97852    }
 97853  }
 97854  
 97855  #if SQLITE_MAX_MMAP_SIZE>0
 97856  /*
 97857  ** The first argument is a file-handle open on a temporary file. The file
 97858  ** is guaranteed to be nByte bytes or smaller in size. This function
 97859  ** attempts to extend the file to nByte bytes in size and to ensure that
 97860  ** the VFS has memory mapped it.
 97861  **
 97862  ** Whether or not the file does end up memory mapped of course depends on
 97863  ** the specific VFS implementation.
 97864  */
 97865  static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
 97866    if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
 97867      void *p = 0;
 97868      int chunksize = 4*1024;
 97869      sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
 97870      sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
 97871      sqlite3OsFetch(pFd, 0, (int)nByte, &p);
 97872      sqlite3OsUnfetch(pFd, 0, p);
 97873    }
 97874  }
 97875  #else
 97876  # define vdbeSorterExtendFile(x,y,z)
 97877  #endif
 97878  
 97879  /*
 97880  ** Allocate space for a file-handle and open a temporary file. If successful,
 97881  ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
 97882  ** Otherwise, set *ppFd to 0 and return an SQLite error code.
 97883  */
 97884  static int vdbeSorterOpenTempFile(
 97885    sqlite3 *db,                    /* Database handle doing sort */
 97886    i64 nExtend,                    /* Attempt to extend file to this size */
 97887    sqlite3_file **ppFd
 97888  ){
 97889    int rc;
 97890    if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
 97891    rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
 97892        SQLITE_OPEN_TEMP_JOURNAL |
 97893        SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
 97894        SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
 97895    );
 97896    if( rc==SQLITE_OK ){
 97897      i64 max = SQLITE_MAX_MMAP_SIZE;
 97898      sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
 97899      if( nExtend>0 ){
 97900        vdbeSorterExtendFile(db, *ppFd, nExtend);
 97901      }
 97902    }
 97903    return rc;
 97904  }
 97905  
 97906  /*
 97907  ** If it has not already been allocated, allocate the UnpackedRecord 
 97908  ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 
 97909  ** if no allocation was required), or SQLITE_NOMEM otherwise.
 97910  */
 97911  static int vdbeSortAllocUnpacked(SortSubtask *pTask){
 97912    if( pTask->pUnpacked==0 ){
 97913      pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
 97914      if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
 97915      pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
 97916      pTask->pUnpacked->errCode = 0;
 97917    }
 97918    return SQLITE_OK;
 97919  }
 97920  
 97921  
 97922  /*
 97923  ** Merge the two sorted lists p1 and p2 into a single list.
 97924  */
 97925  static SorterRecord *vdbeSorterMerge(
 97926    SortSubtask *pTask,             /* Calling thread context */
 97927    SorterRecord *p1,               /* First list to merge */
 97928    SorterRecord *p2                /* Second list to merge */
 97929  ){
 97930    SorterRecord *pFinal = 0;
 97931    SorterRecord **pp = &pFinal;
 97932    int bCached = 0;
 97933  
 97934    assert( p1!=0 && p2!=0 );
 97935    for(;;){
 97936      int res;
 97937      res = pTask->xCompare(
 97938          pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
 97939      );
 97940  
 97941      if( res<=0 ){
 97942        *pp = p1;
 97943        pp = &p1->u.pNext;
 97944        p1 = p1->u.pNext;
 97945        if( p1==0 ){
 97946          *pp = p2;
 97947          break;
 97948        }
 97949      }else{
 97950        *pp = p2;
 97951        pp = &p2->u.pNext;
 97952        p2 = p2->u.pNext;
 97953        bCached = 0;
 97954        if( p2==0 ){
 97955          *pp = p1;
 97956          break;
 97957        }
 97958      }
 97959    }
 97960    return pFinal;
 97961  }
 97962  
 97963  /*
 97964  ** Return the SorterCompare function to compare values collected by the
 97965  ** sorter object passed as the only argument.
 97966  */
 97967  static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
 97968    if( p->typeMask==SORTER_TYPE_INTEGER ){
 97969      return vdbeSorterCompareInt;
 97970    }else if( p->typeMask==SORTER_TYPE_TEXT ){
 97971      return vdbeSorterCompareText; 
 97972    }
 97973    return vdbeSorterCompare;
 97974  }
 97975  
 97976  /*
 97977  ** Sort the linked list of records headed at pTask->pList. Return 
 97978  ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 
 97979  ** an error occurs.
 97980  */
 97981  static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
 97982    int i;
 97983    SorterRecord **aSlot;
 97984    SorterRecord *p;
 97985    int rc;
 97986  
 97987    rc = vdbeSortAllocUnpacked(pTask);
 97988    if( rc!=SQLITE_OK ) return rc;
 97989  
 97990    p = pList->pList;
 97991    pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
 97992  
 97993    aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
 97994    if( !aSlot ){
 97995      return SQLITE_NOMEM_BKPT;
 97996    }
 97997  
 97998    while( p ){
 97999      SorterRecord *pNext;
 98000      if( pList->aMemory ){
 98001        if( (u8*)p==pList->aMemory ){
 98002          pNext = 0;
 98003        }else{
 98004          assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
 98005          pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
 98006        }
 98007      }else{
 98008        pNext = p->u.pNext;
 98009      }
 98010  
 98011      p->u.pNext = 0;
 98012      for(i=0; aSlot[i]; i++){
 98013        p = vdbeSorterMerge(pTask, p, aSlot[i]);
 98014        aSlot[i] = 0;
 98015      }
 98016      aSlot[i] = p;
 98017      p = pNext;
 98018    }
 98019  
 98020    p = 0;
 98021    for(i=0; i<64; i++){
 98022      if( aSlot[i]==0 ) continue;
 98023      p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
 98024    }
 98025    pList->pList = p;
 98026  
 98027    sqlite3_free(aSlot);
 98028    assert( pTask->pUnpacked->errCode==SQLITE_OK 
 98029         || pTask->pUnpacked->errCode==SQLITE_NOMEM 
 98030    );
 98031    return pTask->pUnpacked->errCode;
 98032  }
 98033  
 98034  /*
 98035  ** Initialize a PMA-writer object.
 98036  */
 98037  static void vdbePmaWriterInit(
 98038    sqlite3_file *pFd,              /* File handle to write to */
 98039    PmaWriter *p,                   /* Object to populate */
 98040    int nBuf,                       /* Buffer size */
 98041    i64 iStart                      /* Offset of pFd to begin writing at */
 98042  ){
 98043    memset(p, 0, sizeof(PmaWriter));
 98044    p->aBuffer = (u8*)sqlite3Malloc(nBuf);
 98045    if( !p->aBuffer ){
 98046      p->eFWErr = SQLITE_NOMEM_BKPT;
 98047    }else{
 98048      p->iBufEnd = p->iBufStart = (iStart % nBuf);
 98049      p->iWriteOff = iStart - p->iBufStart;
 98050      p->nBuffer = nBuf;
 98051      p->pFd = pFd;
 98052    }
 98053  }
 98054  
 98055  /*
 98056  ** Write nData bytes of data to the PMA. Return SQLITE_OK
 98057  ** if successful, or an SQLite error code if an error occurs.
 98058  */
 98059  static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
 98060    int nRem = nData;
 98061    while( nRem>0 && p->eFWErr==0 ){
 98062      int nCopy = nRem;
 98063      if( nCopy>(p->nBuffer - p->iBufEnd) ){
 98064        nCopy = p->nBuffer - p->iBufEnd;
 98065      }
 98066  
 98067      memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
 98068      p->iBufEnd += nCopy;
 98069      if( p->iBufEnd==p->nBuffer ){
 98070        p->eFWErr = sqlite3OsWrite(p->pFd, 
 98071            &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 98072            p->iWriteOff + p->iBufStart
 98073        );
 98074        p->iBufStart = p->iBufEnd = 0;
 98075        p->iWriteOff += p->nBuffer;
 98076      }
 98077      assert( p->iBufEnd<p->nBuffer );
 98078  
 98079      nRem -= nCopy;
 98080    }
 98081  }
 98082  
 98083  /*
 98084  ** Flush any buffered data to disk and clean up the PMA-writer object.
 98085  ** The results of using the PMA-writer after this call are undefined.
 98086  ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
 98087  ** required. Otherwise, return an SQLite error code.
 98088  **
 98089  ** Before returning, set *piEof to the offset immediately following the
 98090  ** last byte written to the file.
 98091  */
 98092  static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
 98093    int rc;
 98094    if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
 98095      p->eFWErr = sqlite3OsWrite(p->pFd, 
 98096          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
 98097          p->iWriteOff + p->iBufStart
 98098      );
 98099    }
 98100    *piEof = (p->iWriteOff + p->iBufEnd);
 98101    sqlite3_free(p->aBuffer);
 98102    rc = p->eFWErr;
 98103    memset(p, 0, sizeof(PmaWriter));
 98104    return rc;
 98105  }
 98106  
 98107  /*
 98108  ** Write value iVal encoded as a varint to the PMA. Return 
 98109  ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
 98110  */
 98111  static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
 98112    int nByte; 
 98113    u8 aByte[10];
 98114    nByte = sqlite3PutVarint(aByte, iVal);
 98115    vdbePmaWriteBlob(p, aByte, nByte);
 98116  }
 98117  
 98118  /*
 98119  ** Write the current contents of in-memory linked-list pList to a level-0
 98120  ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 
 98121  ** successful, or an SQLite error code otherwise.
 98122  **
 98123  ** The format of a PMA is:
 98124  **
 98125  **     * A varint. This varint contains the total number of bytes of content
 98126  **       in the PMA (not including the varint itself).
 98127  **
 98128  **     * One or more records packed end-to-end in order of ascending keys. 
 98129  **       Each record consists of a varint followed by a blob of data (the 
 98130  **       key). The varint is the number of bytes in the blob of data.
 98131  */
 98132  static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
 98133    sqlite3 *db = pTask->pSorter->db;
 98134    int rc = SQLITE_OK;             /* Return code */
 98135    PmaWriter writer;               /* Object used to write to the file */
 98136  
 98137  #ifdef SQLITE_DEBUG
 98138    /* Set iSz to the expected size of file pTask->file after writing the PMA. 
 98139    ** This is used by an assert() statement at the end of this function.  */
 98140    i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
 98141  #endif
 98142  
 98143    vdbeSorterWorkDebug(pTask, "enter");
 98144    memset(&writer, 0, sizeof(PmaWriter));
 98145    assert( pList->szPMA>0 );
 98146  
 98147    /* If the first temporary PMA file has not been opened, open it now. */
 98148    if( pTask->file.pFd==0 ){
 98149      rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
 98150      assert( rc!=SQLITE_OK || pTask->file.pFd );
 98151      assert( pTask->file.iEof==0 );
 98152      assert( pTask->nPMA==0 );
 98153    }
 98154  
 98155    /* Try to get the file to memory map */
 98156    if( rc==SQLITE_OK ){
 98157      vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
 98158    }
 98159  
 98160    /* Sort the list */
 98161    if( rc==SQLITE_OK ){
 98162      rc = vdbeSorterSort(pTask, pList);
 98163    }
 98164  
 98165    if( rc==SQLITE_OK ){
 98166      SorterRecord *p;
 98167      SorterRecord *pNext = 0;
 98168  
 98169      vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
 98170                        pTask->file.iEof);
 98171      pTask->nPMA++;
 98172      vdbePmaWriteVarint(&writer, pList->szPMA);
 98173      for(p=pList->pList; p; p=pNext){
 98174        pNext = p->u.pNext;
 98175        vdbePmaWriteVarint(&writer, p->nVal);
 98176        vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
 98177        if( pList->aMemory==0 ) sqlite3_free(p);
 98178      }
 98179      pList->pList = p;
 98180      rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
 98181    }
 98182  
 98183    vdbeSorterWorkDebug(pTask, "exit");
 98184    assert( rc!=SQLITE_OK || pList->pList==0 );
 98185    assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
 98186    return rc;
 98187  }
 98188  
 98189  /*
 98190  ** Advance the MergeEngine to its next entry.
 98191  ** Set *pbEof to true there is no next entry because
 98192  ** the MergeEngine has reached the end of all its inputs.
 98193  **
 98194  ** Return SQLITE_OK if successful or an error code if an error occurs.
 98195  */
 98196  static int vdbeMergeEngineStep(
 98197    MergeEngine *pMerger,      /* The merge engine to advance to the next row */
 98198    int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
 98199  ){
 98200    int rc;
 98201    int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
 98202    SortSubtask *pTask = pMerger->pTask;
 98203  
 98204    /* Advance the current PmaReader */
 98205    rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
 98206  
 98207    /* Update contents of aTree[] */
 98208    if( rc==SQLITE_OK ){
 98209      int i;                      /* Index of aTree[] to recalculate */
 98210      PmaReader *pReadr1;         /* First PmaReader to compare */
 98211      PmaReader *pReadr2;         /* Second PmaReader to compare */
 98212      int bCached = 0;
 98213  
 98214      /* Find the first two PmaReaders to compare. The one that was just
 98215      ** advanced (iPrev) and the one next to it in the array.  */
 98216      pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
 98217      pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
 98218  
 98219      for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
 98220        /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
 98221        int iRes;
 98222        if( pReadr1->pFd==0 ){
 98223          iRes = +1;
 98224        }else if( pReadr2->pFd==0 ){
 98225          iRes = -1;
 98226        }else{
 98227          iRes = pTask->xCompare(pTask, &bCached,
 98228              pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
 98229          );
 98230        }
 98231  
 98232        /* If pReadr1 contained the smaller value, set aTree[i] to its index.
 98233        ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
 98234        ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
 98235        ** pKey2 to point to the record belonging to pReadr2.
 98236        **
 98237        ** Alternatively, if pReadr2 contains the smaller of the two values,
 98238        ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
 98239        ** was actually called above, then pTask->pUnpacked now contains
 98240        ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
 98241        ** vdbeSorterCompare() from decoding pReadr2 again.
 98242        **
 98243        ** If the two values were equal, then the value from the oldest
 98244        ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
 98245        ** is sorted from oldest to newest, so pReadr1 contains older values
 98246        ** than pReadr2 iff (pReadr1<pReadr2).  */
 98247        if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
 98248          pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
 98249          pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
 98250          bCached = 0;
 98251        }else{
 98252          if( pReadr1->pFd ) bCached = 0;
 98253          pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
 98254          pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
 98255        }
 98256      }
 98257      *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
 98258    }
 98259  
 98260    return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
 98261  }
 98262  
 98263  #if SQLITE_MAX_WORKER_THREADS>0
 98264  /*
 98265  ** The main routine for background threads that write level-0 PMAs.
 98266  */
 98267  static void *vdbeSorterFlushThread(void *pCtx){
 98268    SortSubtask *pTask = (SortSubtask*)pCtx;
 98269    int rc;                         /* Return code */
 98270    assert( pTask->bDone==0 );
 98271    rc = vdbeSorterListToPMA(pTask, &pTask->list);
 98272    pTask->bDone = 1;
 98273    return SQLITE_INT_TO_PTR(rc);
 98274  }
 98275  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 98276  
 98277  /*
 98278  ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
 98279  ** using a background thread.
 98280  */
 98281  static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
 98282  #if SQLITE_MAX_WORKER_THREADS==0
 98283    pSorter->bUsePMA = 1;
 98284    return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
 98285  #else
 98286    int rc = SQLITE_OK;
 98287    int i;
 98288    SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
 98289    int nWorker = (pSorter->nTask-1);
 98290  
 98291    /* Set the flag to indicate that at least one PMA has been written. 
 98292    ** Or will be, anyhow.  */
 98293    pSorter->bUsePMA = 1;
 98294  
 98295    /* Select a sub-task to sort and flush the current list of in-memory
 98296    ** records to disk. If the sorter is running in multi-threaded mode,
 98297    ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
 98298    ** the background thread from a sub-tasks previous turn is still running,
 98299    ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
 98300    ** fall back to using the final sub-task. The first (pSorter->nTask-1)
 98301    ** sub-tasks are prefered as they use background threads - the final 
 98302    ** sub-task uses the main thread. */
 98303    for(i=0; i<nWorker; i++){
 98304      int iTest = (pSorter->iPrev + i + 1) % nWorker;
 98305      pTask = &pSorter->aTask[iTest];
 98306      if( pTask->bDone ){
 98307        rc = vdbeSorterJoinThread(pTask);
 98308      }
 98309      if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
 98310    }
 98311  
 98312    if( rc==SQLITE_OK ){
 98313      if( i==nWorker ){
 98314        /* Use the foreground thread for this operation */
 98315        rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
 98316      }else{
 98317        /* Launch a background thread for this operation */
 98318        u8 *aMem = pTask->list.aMemory;
 98319        void *pCtx = (void*)pTask;
 98320  
 98321        assert( pTask->pThread==0 && pTask->bDone==0 );
 98322        assert( pTask->list.pList==0 );
 98323        assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
 98324  
 98325        pSorter->iPrev = (u8)(pTask - pSorter->aTask);
 98326        pTask->list = pSorter->list;
 98327        pSorter->list.pList = 0;
 98328        pSorter->list.szPMA = 0;
 98329        if( aMem ){
 98330          pSorter->list.aMemory = aMem;
 98331          pSorter->nMemory = sqlite3MallocSize(aMem);
 98332        }else if( pSorter->list.aMemory ){
 98333          pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
 98334          if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
 98335        }
 98336  
 98337        rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
 98338      }
 98339    }
 98340  
 98341    return rc;
 98342  #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
 98343  }
 98344  
 98345  /*
 98346  ** Add a record to the sorter.
 98347  */
 98348  SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
 98349    const VdbeCursor *pCsr,         /* Sorter cursor */
 98350    Mem *pVal                       /* Memory cell containing record */
 98351  ){
 98352    VdbeSorter *pSorter;
 98353    int rc = SQLITE_OK;             /* Return Code */
 98354    SorterRecord *pNew;             /* New list element */
 98355    int bFlush;                     /* True to flush contents of memory to PMA */
 98356    int nReq;                       /* Bytes of memory required */
 98357    int nPMA;                       /* Bytes of PMA space required */
 98358    int t;                          /* serial type of first record field */
 98359  
 98360    assert( pCsr->eCurType==CURTYPE_SORTER );
 98361    pSorter = pCsr->uc.pSorter;
 98362    getVarint32((const u8*)&pVal->z[1], t);
 98363    if( t>0 && t<10 && t!=7 ){
 98364      pSorter->typeMask &= SORTER_TYPE_INTEGER;
 98365    }else if( t>10 && (t & 0x01) ){
 98366      pSorter->typeMask &= SORTER_TYPE_TEXT;
 98367    }else{
 98368      pSorter->typeMask = 0;
 98369    }
 98370  
 98371    assert( pSorter );
 98372  
 98373    /* Figure out whether or not the current contents of memory should be
 98374    ** flushed to a PMA before continuing. If so, do so.
 98375    **
 98376    ** If using the single large allocation mode (pSorter->aMemory!=0), then
 98377    ** flush the contents of memory to a new PMA if (a) at least one value is
 98378    ** already in memory and (b) the new value will not fit in memory.
 98379    ** 
 98380    ** Or, if using separate allocations for each record, flush the contents
 98381    ** of memory to a PMA if either of the following are true:
 98382    **
 98383    **   * The total memory allocated for the in-memory list is greater 
 98384    **     than (page-size * cache-size), or
 98385    **
 98386    **   * The total memory allocated for the in-memory list is greater 
 98387    **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
 98388    */
 98389    nReq = pVal->n + sizeof(SorterRecord);
 98390    nPMA = pVal->n + sqlite3VarintLen(pVal->n);
 98391    if( pSorter->mxPmaSize ){
 98392      if( pSorter->list.aMemory ){
 98393        bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
 98394      }else{
 98395        bFlush = (
 98396            (pSorter->list.szPMA > pSorter->mxPmaSize)
 98397         || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
 98398        );
 98399      }
 98400      if( bFlush ){
 98401        rc = vdbeSorterFlushPMA(pSorter);
 98402        pSorter->list.szPMA = 0;
 98403        pSorter->iMemory = 0;
 98404        assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
 98405      }
 98406    }
 98407  
 98408    pSorter->list.szPMA += nPMA;
 98409    if( nPMA>pSorter->mxKeysize ){
 98410      pSorter->mxKeysize = nPMA;
 98411    }
 98412  
 98413    if( pSorter->list.aMemory ){
 98414      int nMin = pSorter->iMemory + nReq;
 98415  
 98416      if( nMin>pSorter->nMemory ){
 98417        u8 *aNew;
 98418        int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
 98419        int nNew = pSorter->nMemory * 2;
 98420        while( nNew < nMin ) nNew = nNew*2;
 98421        if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
 98422        if( nNew < nMin ) nNew = nMin;
 98423  
 98424        aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
 98425        if( !aNew ) return SQLITE_NOMEM_BKPT;
 98426        pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
 98427        pSorter->list.aMemory = aNew;
 98428        pSorter->nMemory = nNew;
 98429      }
 98430  
 98431      pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
 98432      pSorter->iMemory += ROUND8(nReq);
 98433      if( pSorter->list.pList ){
 98434        pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
 98435      }
 98436    }else{
 98437      pNew = (SorterRecord *)sqlite3Malloc(nReq);
 98438      if( pNew==0 ){
 98439        return SQLITE_NOMEM_BKPT;
 98440      }
 98441      pNew->u.pNext = pSorter->list.pList;
 98442    }
 98443  
 98444    memcpy(SRVAL(pNew), pVal->z, pVal->n);
 98445    pNew->nVal = pVal->n;
 98446    pSorter->list.pList = pNew;
 98447  
 98448    return rc;
 98449  }
 98450  
 98451  /*
 98452  ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
 98453  ** of the data stored in aFile[1] is the same as that used by regular PMAs,
 98454  ** except that the number-of-bytes varint is omitted from the start.
 98455  */
 98456  static int vdbeIncrPopulate(IncrMerger *pIncr){
 98457    int rc = SQLITE_OK;
 98458    int rc2;
 98459    i64 iStart = pIncr->iStartOff;
 98460    SorterFile *pOut = &pIncr->aFile[1];
 98461    SortSubtask *pTask = pIncr->pTask;
 98462    MergeEngine *pMerger = pIncr->pMerger;
 98463    PmaWriter writer;
 98464    assert( pIncr->bEof==0 );
 98465  
 98466    vdbeSorterPopulateDebug(pTask, "enter");
 98467  
 98468    vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
 98469    while( rc==SQLITE_OK ){
 98470      int dummy;
 98471      PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
 98472      int nKey = pReader->nKey;
 98473      i64 iEof = writer.iWriteOff + writer.iBufEnd;
 98474  
 98475      /* Check if the output file is full or if the input has been exhausted.
 98476      ** In either case exit the loop. */
 98477      if( pReader->pFd==0 ) break;
 98478      if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
 98479  
 98480      /* Write the next key to the output. */
 98481      vdbePmaWriteVarint(&writer, nKey);
 98482      vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
 98483      assert( pIncr->pMerger->pTask==pTask );
 98484      rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
 98485    }
 98486  
 98487    rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
 98488    if( rc==SQLITE_OK ) rc = rc2;
 98489    vdbeSorterPopulateDebug(pTask, "exit");
 98490    return rc;
 98491  }
 98492  
 98493  #if SQLITE_MAX_WORKER_THREADS>0
 98494  /*
 98495  ** The main routine for background threads that populate aFile[1] of
 98496  ** multi-threaded IncrMerger objects.
 98497  */
 98498  static void *vdbeIncrPopulateThread(void *pCtx){
 98499    IncrMerger *pIncr = (IncrMerger*)pCtx;
 98500    void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
 98501    pIncr->pTask->bDone = 1;
 98502    return pRet;
 98503  }
 98504  
 98505  /*
 98506  ** Launch a background thread to populate aFile[1] of pIncr.
 98507  */
 98508  static int vdbeIncrBgPopulate(IncrMerger *pIncr){
 98509    void *p = (void*)pIncr;
 98510    assert( pIncr->bUseThread );
 98511    return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
 98512  }
 98513  #endif
 98514  
 98515  /*
 98516  ** This function is called when the PmaReader corresponding to pIncr has
 98517  ** finished reading the contents of aFile[0]. Its purpose is to "refill"
 98518  ** aFile[0] such that the PmaReader should start rereading it from the
 98519  ** beginning.
 98520  **
 98521  ** For single-threaded objects, this is accomplished by literally reading 
 98522  ** keys from pIncr->pMerger and repopulating aFile[0]. 
 98523  **
 98524  ** For multi-threaded objects, all that is required is to wait until the 
 98525  ** background thread is finished (if it is not already) and then swap 
 98526  ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
 98527  ** been exhausted, this function also launches a new background thread
 98528  ** to populate the new aFile[1].
 98529  **
 98530  ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
 98531  */
 98532  static int vdbeIncrSwap(IncrMerger *pIncr){
 98533    int rc = SQLITE_OK;
 98534  
 98535  #if SQLITE_MAX_WORKER_THREADS>0
 98536    if( pIncr->bUseThread ){
 98537      rc = vdbeSorterJoinThread(pIncr->pTask);
 98538  
 98539      if( rc==SQLITE_OK ){
 98540        SorterFile f0 = pIncr->aFile[0];
 98541        pIncr->aFile[0] = pIncr->aFile[1];
 98542        pIncr->aFile[1] = f0;
 98543      }
 98544  
 98545      if( rc==SQLITE_OK ){
 98546        if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
 98547          pIncr->bEof = 1;
 98548        }else{
 98549          rc = vdbeIncrBgPopulate(pIncr);
 98550        }
 98551      }
 98552    }else
 98553  #endif
 98554    {
 98555      rc = vdbeIncrPopulate(pIncr);
 98556      pIncr->aFile[0] = pIncr->aFile[1];
 98557      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
 98558        pIncr->bEof = 1;
 98559      }
 98560    }
 98561  
 98562    return rc;
 98563  }
 98564  
 98565  /*
 98566  ** Allocate and return a new IncrMerger object to read data from pMerger.
 98567  **
 98568  ** If an OOM condition is encountered, return NULL. In this case free the
 98569  ** pMerger argument before returning.
 98570  */
 98571  static int vdbeIncrMergerNew(
 98572    SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
 98573    MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
 98574    IncrMerger **ppOut      /* Write the new IncrMerger here */
 98575  ){
 98576    int rc = SQLITE_OK;
 98577    IncrMerger *pIncr = *ppOut = (IncrMerger*)
 98578         (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
 98579    if( pIncr ){
 98580      pIncr->pMerger = pMerger;
 98581      pIncr->pTask = pTask;
 98582      pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
 98583      pTask->file2.iEof += pIncr->mxSz;
 98584    }else{
 98585      vdbeMergeEngineFree(pMerger);
 98586      rc = SQLITE_NOMEM_BKPT;
 98587    }
 98588    return rc;
 98589  }
 98590  
 98591  #if SQLITE_MAX_WORKER_THREADS>0
 98592  /*
 98593  ** Set the "use-threads" flag on object pIncr.
 98594  */
 98595  static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
 98596    pIncr->bUseThread = 1;
 98597    pIncr->pTask->file2.iEof -= pIncr->mxSz;
 98598  }
 98599  #endif /* SQLITE_MAX_WORKER_THREADS>0 */
 98600  
 98601  
 98602  
 98603  /*
 98604  ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
 98605  ** two PmaReaders that feed that entry.  Neither of the PmaReaders
 98606  ** are advanced.  This routine merely does the comparison.
 98607  */
 98608  static void vdbeMergeEngineCompare(
 98609    MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
 98610    int iOut               /* Store the result in pMerger->aTree[iOut] */
 98611  ){
 98612    int i1;
 98613    int i2;
 98614    int iRes;
 98615    PmaReader *p1;
 98616    PmaReader *p2;
 98617  
 98618    assert( iOut<pMerger->nTree && iOut>0 );
 98619  
 98620    if( iOut>=(pMerger->nTree/2) ){
 98621      i1 = (iOut - pMerger->nTree/2) * 2;
 98622      i2 = i1 + 1;
 98623    }else{
 98624      i1 = pMerger->aTree[iOut*2];
 98625      i2 = pMerger->aTree[iOut*2+1];
 98626    }
 98627  
 98628    p1 = &pMerger->aReadr[i1];
 98629    p2 = &pMerger->aReadr[i2];
 98630  
 98631    if( p1->pFd==0 ){
 98632      iRes = i2;
 98633    }else if( p2->pFd==0 ){
 98634      iRes = i1;
 98635    }else{
 98636      SortSubtask *pTask = pMerger->pTask;
 98637      int bCached = 0;
 98638      int res;
 98639      assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
 98640      res = pTask->xCompare(
 98641          pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
 98642      );
 98643      if( res<=0 ){
 98644        iRes = i1;
 98645      }else{
 98646        iRes = i2;
 98647      }
 98648    }
 98649  
 98650    pMerger->aTree[iOut] = iRes;
 98651  }
 98652  
 98653  /*
 98654  ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
 98655  ** and vdbePmaReaderIncrMergeInit().
 98656  **
 98657  ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
 98658  ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
 98659  ** when there exists one or more separate worker threads.
 98660  */
 98661  #define INCRINIT_NORMAL 0
 98662  #define INCRINIT_TASK   1
 98663  #define INCRINIT_ROOT   2
 98664  
 98665  /* 
 98666  ** Forward reference required as the vdbeIncrMergeInit() and
 98667  ** vdbePmaReaderIncrInit() routines are called mutually recursively when
 98668  ** building a merge tree.
 98669  */
 98670  static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
 98671  
 98672  /*
 98673  ** Initialize the MergeEngine object passed as the second argument. Once this
 98674  ** function returns, the first key of merged data may be read from the 
 98675  ** MergeEngine object in the usual fashion.
 98676  **
 98677  ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
 98678  ** objects attached to the PmaReader objects that the merger reads from have
 98679  ** already been populated, but that they have not yet populated aFile[0] and
 98680  ** set the PmaReader objects up to read from it. In this case all that is
 98681  ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
 98682  ** its first key.
 98683  **
 98684  ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 
 98685  ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 
 98686  ** to pMerger.
 98687  **
 98688  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 98689  */
 98690  static int vdbeMergeEngineInit(
 98691    SortSubtask *pTask,             /* Thread that will run pMerger */
 98692    MergeEngine *pMerger,           /* MergeEngine to initialize */
 98693    int eMode                       /* One of the INCRINIT_XXX constants */
 98694  ){
 98695    int rc = SQLITE_OK;             /* Return code */
 98696    int i;                          /* For looping over PmaReader objects */
 98697    int nTree;                      /* Number of subtrees to merge */
 98698  
 98699    /* Failure to allocate the merge would have been detected prior to
 98700    ** invoking this routine */
 98701    assert( pMerger!=0 );
 98702  
 98703    /* eMode is always INCRINIT_NORMAL in single-threaded mode */
 98704    assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
 98705  
 98706    /* Verify that the MergeEngine is assigned to a single thread */
 98707    assert( pMerger->pTask==0 );
 98708    pMerger->pTask = pTask;
 98709  
 98710    nTree = pMerger->nTree;
 98711    for(i=0; i<nTree; i++){
 98712      if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
 98713        /* PmaReaders should be normally initialized in order, as if they are
 98714        ** reading from the same temp file this makes for more linear file IO.
 98715        ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
 98716        ** in use it will block the vdbePmaReaderNext() call while it uses
 98717        ** the main thread to fill its buffer. So calling PmaReaderNext()
 98718        ** on this PmaReader before any of the multi-threaded PmaReaders takes
 98719        ** better advantage of multi-processor hardware. */
 98720        rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
 98721      }else{
 98722        rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
 98723      }
 98724      if( rc!=SQLITE_OK ) return rc;
 98725    }
 98726  
 98727    for(i=pMerger->nTree-1; i>0; i--){
 98728      vdbeMergeEngineCompare(pMerger, i);
 98729    }
 98730    return pTask->pUnpacked->errCode;
 98731  }
 98732  
 98733  /*
 98734  ** The PmaReader passed as the first argument is guaranteed to be an
 98735  ** incremental-reader (pReadr->pIncr!=0). This function serves to open
 98736  ** and/or initialize the temp file related fields of the IncrMerge
 98737  ** object at (pReadr->pIncr).
 98738  **
 98739  ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
 98740  ** in the sub-tree headed by pReadr are also initialized. Data is then 
 98741  ** loaded into the buffers belonging to pReadr and it is set to point to 
 98742  ** the first key in its range.
 98743  **
 98744  ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
 98745  ** to be a multi-threaded PmaReader and this function is being called in a
 98746  ** background thread. In this case all PmaReaders in the sub-tree are 
 98747  ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
 98748  ** pReadr is populated. However, pReadr itself is not set up to point
 98749  ** to its first key. A call to vdbePmaReaderNext() is still required to do
 98750  ** that. 
 98751  **
 98752  ** The reason this function does not call vdbePmaReaderNext() immediately 
 98753  ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
 98754  ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
 98755  ** this entire function is being run by thread (pTask->thread), that will
 98756  ** lead to the current background thread attempting to join itself.
 98757  **
 98758  ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
 98759  ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
 98760  ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
 98761  ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
 98762  ** the current PmaReader set to point to the first key in its range.
 98763  **
 98764  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 98765  */
 98766  static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
 98767    int rc = SQLITE_OK;
 98768    IncrMerger *pIncr = pReadr->pIncr;
 98769    SortSubtask *pTask = pIncr->pTask;
 98770    sqlite3 *db = pTask->pSorter->db;
 98771  
 98772    /* eMode is always INCRINIT_NORMAL in single-threaded mode */
 98773    assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
 98774  
 98775    rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
 98776  
 98777    /* Set up the required files for pIncr. A multi-theaded IncrMerge object
 98778    ** requires two temp files to itself, whereas a single-threaded object
 98779    ** only requires a region of pTask->file2. */
 98780    if( rc==SQLITE_OK ){
 98781      int mxSz = pIncr->mxSz;
 98782  #if SQLITE_MAX_WORKER_THREADS>0
 98783      if( pIncr->bUseThread ){
 98784        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
 98785        if( rc==SQLITE_OK ){
 98786          rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
 98787        }
 98788      }else
 98789  #endif
 98790      /*if( !pIncr->bUseThread )*/{
 98791        if( pTask->file2.pFd==0 ){
 98792          assert( pTask->file2.iEof>0 );
 98793          rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
 98794          pTask->file2.iEof = 0;
 98795        }
 98796        if( rc==SQLITE_OK ){
 98797          pIncr->aFile[1].pFd = pTask->file2.pFd;
 98798          pIncr->iStartOff = pTask->file2.iEof;
 98799          pTask->file2.iEof += mxSz;
 98800        }
 98801      }
 98802    }
 98803  
 98804  #if SQLITE_MAX_WORKER_THREADS>0
 98805    if( rc==SQLITE_OK && pIncr->bUseThread ){
 98806      /* Use the current thread to populate aFile[1], even though this
 98807      ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
 98808      ** then this function is already running in background thread 
 98809      ** pIncr->pTask->thread. 
 98810      **
 98811      ** If this is the INCRINIT_ROOT object, then it is running in the 
 98812      ** main VDBE thread. But that is Ok, as that thread cannot return
 98813      ** control to the VDBE or proceed with anything useful until the 
 98814      ** first results are ready from this merger object anyway.
 98815      */
 98816      assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
 98817      rc = vdbeIncrPopulate(pIncr);
 98818    }
 98819  #endif
 98820  
 98821    if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
 98822      rc = vdbePmaReaderNext(pReadr);
 98823    }
 98824  
 98825    return rc;
 98826  }
 98827  
 98828  #if SQLITE_MAX_WORKER_THREADS>0
 98829  /*
 98830  ** The main routine for vdbePmaReaderIncrMergeInit() operations run in 
 98831  ** background threads.
 98832  */
 98833  static void *vdbePmaReaderBgIncrInit(void *pCtx){
 98834    PmaReader *pReader = (PmaReader*)pCtx;
 98835    void *pRet = SQLITE_INT_TO_PTR(
 98836                    vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
 98837                 );
 98838    pReader->pIncr->pTask->bDone = 1;
 98839    return pRet;
 98840  }
 98841  #endif
 98842  
 98843  /*
 98844  ** If the PmaReader passed as the first argument is not an incremental-reader
 98845  ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
 98846  ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
 98847  ** this routine to initialize the incremental merge.
 98848  ** 
 98849  ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), 
 98850  ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
 98851  ** Or, if the IncrMerger is single threaded, the same function is called
 98852  ** using the current thread.
 98853  */
 98854  static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
 98855    IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
 98856    int rc = SQLITE_OK;                  /* Return code */
 98857    if( pIncr ){
 98858  #if SQLITE_MAX_WORKER_THREADS>0
 98859      assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
 98860      if( pIncr->bUseThread ){
 98861        void *pCtx = (void*)pReadr;
 98862        rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
 98863      }else
 98864  #endif
 98865      {
 98866        rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
 98867      }
 98868    }
 98869    return rc;
 98870  }
 98871  
 98872  /*
 98873  ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
 98874  ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
 98875  ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
 98876  ** to NULL and return an SQLite error code.
 98877  **
 98878  ** When this function is called, *piOffset is set to the offset of the
 98879  ** first PMA to read from pTask->file. Assuming no error occurs, it is 
 98880  ** set to the offset immediately following the last byte of the last
 98881  ** PMA before returning. If an error does occur, then the final value of
 98882  ** *piOffset is undefined.
 98883  */
 98884  static int vdbeMergeEngineLevel0(
 98885    SortSubtask *pTask,             /* Sorter task to read from */
 98886    int nPMA,                       /* Number of PMAs to read */
 98887    i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
 98888    MergeEngine **ppOut             /* OUT: New merge-engine */
 98889  ){
 98890    MergeEngine *pNew;              /* Merge engine to return */
 98891    i64 iOff = *piOffset;
 98892    int i;
 98893    int rc = SQLITE_OK;
 98894  
 98895    *ppOut = pNew = vdbeMergeEngineNew(nPMA);
 98896    if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
 98897  
 98898    for(i=0; i<nPMA && rc==SQLITE_OK; i++){
 98899      i64 nDummy = 0;
 98900      PmaReader *pReadr = &pNew->aReadr[i];
 98901      rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
 98902      iOff = pReadr->iEof;
 98903    }
 98904  
 98905    if( rc!=SQLITE_OK ){
 98906      vdbeMergeEngineFree(pNew);
 98907      *ppOut = 0;
 98908    }
 98909    *piOffset = iOff;
 98910    return rc;
 98911  }
 98912  
 98913  /*
 98914  ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
 98915  ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
 98916  **
 98917  ** i.e.
 98918  **
 98919  **   nPMA<=16    -> TreeDepth() == 0
 98920  **   nPMA<=256   -> TreeDepth() == 1
 98921  **   nPMA<=65536 -> TreeDepth() == 2
 98922  */
 98923  static int vdbeSorterTreeDepth(int nPMA){
 98924    int nDepth = 0;
 98925    i64 nDiv = SORTER_MAX_MERGE_COUNT;
 98926    while( nDiv < (i64)nPMA ){
 98927      nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
 98928      nDepth++;
 98929    }
 98930    return nDepth;
 98931  }
 98932  
 98933  /*
 98934  ** pRoot is the root of an incremental merge-tree with depth nDepth (according
 98935  ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
 98936  ** tree, counting from zero. This function adds pLeaf to the tree.
 98937  **
 98938  ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
 98939  ** code is returned and pLeaf is freed.
 98940  */
 98941  static int vdbeSorterAddToTree(
 98942    SortSubtask *pTask,             /* Task context */
 98943    int nDepth,                     /* Depth of tree according to TreeDepth() */
 98944    int iSeq,                       /* Sequence number of leaf within tree */
 98945    MergeEngine *pRoot,             /* Root of tree */
 98946    MergeEngine *pLeaf              /* Leaf to add to tree */
 98947  ){
 98948    int rc = SQLITE_OK;
 98949    int nDiv = 1;
 98950    int i;
 98951    MergeEngine *p = pRoot;
 98952    IncrMerger *pIncr;
 98953  
 98954    rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
 98955  
 98956    for(i=1; i<nDepth; i++){
 98957      nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
 98958    }
 98959  
 98960    for(i=1; i<nDepth && rc==SQLITE_OK; i++){
 98961      int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
 98962      PmaReader *pReadr = &p->aReadr[iIter];
 98963  
 98964      if( pReadr->pIncr==0 ){
 98965        MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 98966        if( pNew==0 ){
 98967          rc = SQLITE_NOMEM_BKPT;
 98968        }else{
 98969          rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
 98970        }
 98971      }
 98972      if( rc==SQLITE_OK ){
 98973        p = pReadr->pIncr->pMerger;
 98974        nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
 98975      }
 98976    }
 98977  
 98978    if( rc==SQLITE_OK ){
 98979      p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
 98980    }else{
 98981      vdbeIncrFree(pIncr);
 98982    }
 98983    return rc;
 98984  }
 98985  
 98986  /*
 98987  ** This function is called as part of a SorterRewind() operation on a sorter
 98988  ** that has already written two or more level-0 PMAs to one or more temp
 98989  ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 
 98990  ** can be used to incrementally merge all PMAs on disk.
 98991  **
 98992  ** If successful, SQLITE_OK is returned and *ppOut set to point to the
 98993  ** MergeEngine object at the root of the tree before returning. Or, if an
 98994  ** error occurs, an SQLite error code is returned and the final value 
 98995  ** of *ppOut is undefined.
 98996  */
 98997  static int vdbeSorterMergeTreeBuild(
 98998    VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
 98999    MergeEngine **ppOut        /* Write the MergeEngine here */
 99000  ){
 99001    MergeEngine *pMain = 0;
 99002    int rc = SQLITE_OK;
 99003    int iTask;
 99004  
 99005  #if SQLITE_MAX_WORKER_THREADS>0
 99006    /* If the sorter uses more than one task, then create the top-level 
 99007    ** MergeEngine here. This MergeEngine will read data from exactly 
 99008    ** one PmaReader per sub-task.  */
 99009    assert( pSorter->bUseThreads || pSorter->nTask==1 );
 99010    if( pSorter->nTask>1 ){
 99011      pMain = vdbeMergeEngineNew(pSorter->nTask);
 99012      if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
 99013    }
 99014  #endif
 99015  
 99016    for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
 99017      SortSubtask *pTask = &pSorter->aTask[iTask];
 99018      assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
 99019      if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
 99020        MergeEngine *pRoot = 0;     /* Root node of tree for this task */
 99021        int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
 99022        i64 iReadOff = 0;
 99023  
 99024        if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
 99025          rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
 99026        }else{
 99027          int i;
 99028          int iSeq = 0;
 99029          pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
 99030          if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
 99031          for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
 99032            MergeEngine *pMerger = 0; /* New level-0 PMA merger */
 99033            int nReader;              /* Number of level-0 PMAs to merge */
 99034  
 99035            nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
 99036            rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
 99037            if( rc==SQLITE_OK ){
 99038              rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
 99039            }
 99040          }
 99041        }
 99042  
 99043        if( rc==SQLITE_OK ){
 99044  #if SQLITE_MAX_WORKER_THREADS>0
 99045          if( pMain!=0 ){
 99046            rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
 99047          }else
 99048  #endif
 99049          {
 99050            assert( pMain==0 );
 99051            pMain = pRoot;
 99052          }
 99053        }else{
 99054          vdbeMergeEngineFree(pRoot);
 99055        }
 99056      }
 99057    }
 99058  
 99059    if( rc!=SQLITE_OK ){
 99060      vdbeMergeEngineFree(pMain);
 99061      pMain = 0;
 99062    }
 99063    *ppOut = pMain;
 99064    return rc;
 99065  }
 99066  
 99067  /*
 99068  ** This function is called as part of an sqlite3VdbeSorterRewind() operation
 99069  ** on a sorter that has written two or more PMAs to temporary files. It sets
 99070  ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
 99071  ** (for multi-threaded sorters) so that it can be used to iterate through
 99072  ** all records stored in the sorter.
 99073  **
 99074  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
 99075  */
 99076  static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
 99077    int rc;                         /* Return code */
 99078    SortSubtask *pTask0 = &pSorter->aTask[0];
 99079    MergeEngine *pMain = 0;
 99080  #if SQLITE_MAX_WORKER_THREADS
 99081    sqlite3 *db = pTask0->pSorter->db;
 99082    int i;
 99083    SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
 99084    for(i=0; i<pSorter->nTask; i++){
 99085      pSorter->aTask[i].xCompare = xCompare;
 99086    }
 99087  #endif
 99088  
 99089    rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
 99090    if( rc==SQLITE_OK ){
 99091  #if SQLITE_MAX_WORKER_THREADS
 99092      assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
 99093      if( pSorter->bUseThreads ){
 99094        int iTask;
 99095        PmaReader *pReadr = 0;
 99096        SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
 99097        rc = vdbeSortAllocUnpacked(pLast);
 99098        if( rc==SQLITE_OK ){
 99099          pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
 99100          pSorter->pReader = pReadr;
 99101          if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
 99102        }
 99103        if( rc==SQLITE_OK ){
 99104          rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
 99105          if( rc==SQLITE_OK ){
 99106            vdbeIncrMergerSetThreads(pReadr->pIncr);
 99107            for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
 99108              IncrMerger *pIncr;
 99109              if( (pIncr = pMain->aReadr[iTask].pIncr) ){
 99110                vdbeIncrMergerSetThreads(pIncr);
 99111                assert( pIncr->pTask!=pLast );
 99112              }
 99113            }
 99114            for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
 99115              /* Check that:
 99116              **   
 99117              **   a) The incremental merge object is configured to use the
 99118              **      right task, and
 99119              **   b) If it is using task (nTask-1), it is configured to run
 99120              **      in single-threaded mode. This is important, as the
 99121              **      root merge (INCRINIT_ROOT) will be using the same task
 99122              **      object.
 99123              */
 99124              PmaReader *p = &pMain->aReadr[iTask];
 99125              assert( p->pIncr==0 || (
 99126                  (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
 99127               && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
 99128              ));
 99129              rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
 99130            }
 99131          }
 99132          pMain = 0;
 99133        }
 99134        if( rc==SQLITE_OK ){
 99135          rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
 99136        }
 99137      }else
 99138  #endif
 99139      {
 99140        rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
 99141        pSorter->pMerger = pMain;
 99142        pMain = 0;
 99143      }
 99144    }
 99145  
 99146    if( rc!=SQLITE_OK ){
 99147      vdbeMergeEngineFree(pMain);
 99148    }
 99149    return rc;
 99150  }
 99151  
 99152  
 99153  /*
 99154  ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
 99155  ** this function is called to prepare for iterating through the records
 99156  ** in sorted order.
 99157  */
 99158  SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
 99159    VdbeSorter *pSorter;
 99160    int rc = SQLITE_OK;             /* Return code */
 99161  
 99162    assert( pCsr->eCurType==CURTYPE_SORTER );
 99163    pSorter = pCsr->uc.pSorter;
 99164    assert( pSorter );
 99165  
 99166    /* If no data has been written to disk, then do not do so now. Instead,
 99167    ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
 99168    ** from the in-memory list.  */
 99169    if( pSorter->bUsePMA==0 ){
 99170      if( pSorter->list.pList ){
 99171        *pbEof = 0;
 99172        rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
 99173      }else{
 99174        *pbEof = 1;
 99175      }
 99176      return rc;
 99177    }
 99178  
 99179    /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 
 99180    ** function flushes the contents of memory to disk, it immediately always
 99181    ** creates a new list consisting of a single key immediately afterwards.
 99182    ** So the list is never empty at this point.  */
 99183    assert( pSorter->list.pList );
 99184    rc = vdbeSorterFlushPMA(pSorter);
 99185  
 99186    /* Join all threads */
 99187    rc = vdbeSorterJoinAll(pSorter, rc);
 99188  
 99189    vdbeSorterRewindDebug("rewind");
 99190  
 99191    /* Assuming no errors have occurred, set up a merger structure to 
 99192    ** incrementally read and merge all remaining PMAs.  */
 99193    assert( pSorter->pReader==0 );
 99194    if( rc==SQLITE_OK ){
 99195      rc = vdbeSorterSetupMerge(pSorter);
 99196      *pbEof = 0;
 99197    }
 99198  
 99199    vdbeSorterRewindDebug("rewinddone");
 99200    return rc;
 99201  }
 99202  
 99203  /*
 99204  ** Advance to the next element in the sorter.  Return value:
 99205  **
 99206  **    SQLITE_OK     success
 99207  **    SQLITE_DONE   end of data
 99208  **    otherwise     some kind of error.
 99209  */
 99210  SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
 99211    VdbeSorter *pSorter;
 99212    int rc;                         /* Return code */
 99213  
 99214    assert( pCsr->eCurType==CURTYPE_SORTER );
 99215    pSorter = pCsr->uc.pSorter;
 99216    assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
 99217    if( pSorter->bUsePMA ){
 99218      assert( pSorter->pReader==0 || pSorter->pMerger==0 );
 99219      assert( pSorter->bUseThreads==0 || pSorter->pReader );
 99220      assert( pSorter->bUseThreads==1 || pSorter->pMerger );
 99221  #if SQLITE_MAX_WORKER_THREADS>0
 99222      if( pSorter->bUseThreads ){
 99223        rc = vdbePmaReaderNext(pSorter->pReader);
 99224        if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
 99225      }else
 99226  #endif
 99227      /*if( !pSorter->bUseThreads )*/ {
 99228        int res = 0;
 99229        assert( pSorter->pMerger!=0 );
 99230        assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
 99231        rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
 99232        if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
 99233      }
 99234    }else{
 99235      SorterRecord *pFree = pSorter->list.pList;
 99236      pSorter->list.pList = pFree->u.pNext;
 99237      pFree->u.pNext = 0;
 99238      if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
 99239      rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
 99240    }
 99241    return rc;
 99242  }
 99243  
 99244  /*
 99245  ** Return a pointer to a buffer owned by the sorter that contains the 
 99246  ** current key.
 99247  */
 99248  static void *vdbeSorterRowkey(
 99249    const VdbeSorter *pSorter,      /* Sorter object */
 99250    int *pnKey                      /* OUT: Size of current key in bytes */
 99251  ){
 99252    void *pKey;
 99253    if( pSorter->bUsePMA ){
 99254      PmaReader *pReader;
 99255  #if SQLITE_MAX_WORKER_THREADS>0
 99256      if( pSorter->bUseThreads ){
 99257        pReader = pSorter->pReader;
 99258      }else
 99259  #endif
 99260      /*if( !pSorter->bUseThreads )*/{
 99261        pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
 99262      }
 99263      *pnKey = pReader->nKey;
 99264      pKey = pReader->aKey;
 99265    }else{
 99266      *pnKey = pSorter->list.pList->nVal;
 99267      pKey = SRVAL(pSorter->list.pList);
 99268    }
 99269    return pKey;
 99270  }
 99271  
 99272  /*
 99273  ** Copy the current sorter key into the memory cell pOut.
 99274  */
 99275  SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
 99276    VdbeSorter *pSorter;
 99277    void *pKey; int nKey;           /* Sorter key to copy into pOut */
 99278  
 99279    assert( pCsr->eCurType==CURTYPE_SORTER );
 99280    pSorter = pCsr->uc.pSorter;
 99281    pKey = vdbeSorterRowkey(pSorter, &nKey);
 99282    if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
 99283      return SQLITE_NOMEM_BKPT;
 99284    }
 99285    pOut->n = nKey;
 99286    MemSetTypeFlag(pOut, MEM_Blob);
 99287    memcpy(pOut->z, pKey, nKey);
 99288  
 99289    return SQLITE_OK;
 99290  }
 99291  
 99292  /*
 99293  ** Compare the key in memory cell pVal with the key that the sorter cursor
 99294  ** passed as the first argument currently points to. For the purposes of
 99295  ** the comparison, ignore the rowid field at the end of each record.
 99296  **
 99297  ** If the sorter cursor key contains any NULL values, consider it to be
 99298  ** less than pVal. Even if pVal also contains NULL values.
 99299  **
 99300  ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
 99301  ** Otherwise, set *pRes to a negative, zero or positive value if the
 99302  ** key in pVal is smaller than, equal to or larger than the current sorter
 99303  ** key.
 99304  **
 99305  ** This routine forms the core of the OP_SorterCompare opcode, which in
 99306  ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
 99307  */
 99308  SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
 99309    const VdbeCursor *pCsr,         /* Sorter cursor */
 99310    Mem *pVal,                      /* Value to compare to current sorter key */
 99311    int nKeyCol,                    /* Compare this many columns */
 99312    int *pRes                       /* OUT: Result of comparison */
 99313  ){
 99314    VdbeSorter *pSorter;
 99315    UnpackedRecord *r2;
 99316    KeyInfo *pKeyInfo;
 99317    int i;
 99318    void *pKey; int nKey;           /* Sorter key to compare pVal with */
 99319  
 99320    assert( pCsr->eCurType==CURTYPE_SORTER );
 99321    pSorter = pCsr->uc.pSorter;
 99322    r2 = pSorter->pUnpacked;
 99323    pKeyInfo = pCsr->pKeyInfo;
 99324    if( r2==0 ){
 99325      r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
 99326      if( r2==0 ) return SQLITE_NOMEM_BKPT;
 99327      r2->nField = nKeyCol;
 99328    }
 99329    assert( r2->nField==nKeyCol );
 99330  
 99331    pKey = vdbeSorterRowkey(pSorter, &nKey);
 99332    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
 99333    for(i=0; i<nKeyCol; i++){
 99334      if( r2->aMem[i].flags & MEM_Null ){
 99335        *pRes = -1;
 99336        return SQLITE_OK;
 99337      }
 99338    }
 99339  
 99340    *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
 99341    return SQLITE_OK;
 99342  }
 99343  
 99344  /************** End of vdbesort.c ********************************************/
 99345  /************** Begin file memjournal.c **************************************/
 99346  /*
 99347  ** 2008 October 7
 99348  **
 99349  ** The author disclaims copyright to this source code.  In place of
 99350  ** a legal notice, here is a blessing:
 99351  **
 99352  **    May you do good and not evil.
 99353  **    May you find forgiveness for yourself and forgive others.
 99354  **    May you share freely, never taking more than you give.
 99355  **
 99356  *************************************************************************
 99357  **
 99358  ** This file contains code use to implement an in-memory rollback journal.
 99359  ** The in-memory rollback journal is used to journal transactions for
 99360  ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
 99361  **
 99362  ** Update:  The in-memory journal is also used to temporarily cache
 99363  ** smaller journals that are not critical for power-loss recovery.
 99364  ** For example, statement journals that are not too big will be held
 99365  ** entirely in memory, thus reducing the number of file I/O calls, and
 99366  ** more importantly, reducing temporary file creation events.  If these
 99367  ** journals become too large for memory, they are spilled to disk.  But
 99368  ** in the common case, they are usually small and no file I/O needs to
 99369  ** occur.
 99370  */
 99371  /* #include "sqliteInt.h" */
 99372  
 99373  /* Forward references to internal structures */
 99374  typedef struct MemJournal MemJournal;
 99375  typedef struct FilePoint FilePoint;
 99376  typedef struct FileChunk FileChunk;
 99377  
 99378  /*
 99379  ** The rollback journal is composed of a linked list of these structures.
 99380  **
 99381  ** The zChunk array is always at least 8 bytes in size - usually much more.
 99382  ** Its actual size is stored in the MemJournal.nChunkSize variable.
 99383  */
 99384  struct FileChunk {
 99385    FileChunk *pNext;               /* Next chunk in the journal */
 99386    u8 zChunk[8];                   /* Content of this chunk */
 99387  };
 99388  
 99389  /*
 99390  ** By default, allocate this many bytes of memory for each FileChunk object.
 99391  */
 99392  #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
 99393  
 99394  /*
 99395  ** For chunk size nChunkSize, return the number of bytes that should
 99396  ** be allocated for each FileChunk structure.
 99397  */
 99398  #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
 99399  
 99400  /*
 99401  ** An instance of this object serves as a cursor into the rollback journal.
 99402  ** The cursor can be either for reading or writing.
 99403  */
 99404  struct FilePoint {
 99405    sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
 99406    FileChunk *pChunk;              /* Specific chunk into which cursor points */
 99407  };
 99408  
 99409  /*
 99410  ** This structure is a subclass of sqlite3_file. Each open memory-journal
 99411  ** is an instance of this class.
 99412  */
 99413  struct MemJournal {
 99414    const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
 99415    int nChunkSize;                 /* In-memory chunk-size */
 99416  
 99417    int nSpill;                     /* Bytes of data before flushing */
 99418    int nSize;                      /* Bytes of data currently in memory */
 99419    FileChunk *pFirst;              /* Head of in-memory chunk-list */
 99420    FilePoint endpoint;             /* Pointer to the end of the file */
 99421    FilePoint readpoint;            /* Pointer to the end of the last xRead() */
 99422  
 99423    int flags;                      /* xOpen flags */
 99424    sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
 99425    const char *zJournal;           /* Name of the journal file */
 99426  };
 99427  
 99428  /*
 99429  ** Read data from the in-memory journal file.  This is the implementation
 99430  ** of the sqlite3_vfs.xRead method.
 99431  */
 99432  static int memjrnlRead(
 99433    sqlite3_file *pJfd,    /* The journal file from which to read */
 99434    void *zBuf,            /* Put the results here */
 99435    int iAmt,              /* Number of bytes to read */
 99436    sqlite_int64 iOfst     /* Begin reading at this offset */
 99437  ){
 99438    MemJournal *p = (MemJournal *)pJfd;
 99439    u8 *zOut = zBuf;
 99440    int nRead = iAmt;
 99441    int iChunkOffset;
 99442    FileChunk *pChunk;
 99443  
 99444  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 99445   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 99446    if( (iAmt+iOfst)>p->endpoint.iOffset ){
 99447      return SQLITE_IOERR_SHORT_READ;
 99448    }
 99449  #endif
 99450  
 99451    assert( (iAmt+iOfst)<=p->endpoint.iOffset );
 99452    assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
 99453    if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
 99454      sqlite3_int64 iOff = 0;
 99455      for(pChunk=p->pFirst; 
 99456          ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
 99457          pChunk=pChunk->pNext
 99458      ){
 99459        iOff += p->nChunkSize;
 99460      }
 99461    }else{
 99462      pChunk = p->readpoint.pChunk;
 99463      assert( pChunk!=0 );
 99464    }
 99465  
 99466    iChunkOffset = (int)(iOfst%p->nChunkSize);
 99467    do {
 99468      int iSpace = p->nChunkSize - iChunkOffset;
 99469      int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
 99470      memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
 99471      zOut += nCopy;
 99472      nRead -= iSpace;
 99473      iChunkOffset = 0;
 99474    } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
 99475    p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
 99476    p->readpoint.pChunk = pChunk;
 99477  
 99478    return SQLITE_OK;
 99479  }
 99480  
 99481  /*
 99482  ** Free the list of FileChunk structures headed at MemJournal.pFirst.
 99483  */
 99484  static void memjrnlFreeChunks(MemJournal *p){
 99485    FileChunk *pIter;
 99486    FileChunk *pNext;
 99487    for(pIter=p->pFirst; pIter; pIter=pNext){
 99488      pNext = pIter->pNext;
 99489      sqlite3_free(pIter);
 99490    } 
 99491    p->pFirst = 0;
 99492  }
 99493  
 99494  /*
 99495  ** Flush the contents of memory to a real file on disk.
 99496  */
 99497  static int memjrnlCreateFile(MemJournal *p){
 99498    int rc;
 99499    sqlite3_file *pReal = (sqlite3_file*)p;
 99500    MemJournal copy = *p;
 99501  
 99502    memset(p, 0, sizeof(MemJournal));
 99503    rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
 99504    if( rc==SQLITE_OK ){
 99505      int nChunk = copy.nChunkSize;
 99506      i64 iOff = 0;
 99507      FileChunk *pIter;
 99508      for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
 99509        if( iOff + nChunk > copy.endpoint.iOffset ){
 99510          nChunk = copy.endpoint.iOffset - iOff;
 99511        }
 99512        rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
 99513        if( rc ) break;
 99514        iOff += nChunk;
 99515      }
 99516      if( rc==SQLITE_OK ){
 99517        /* No error has occurred. Free the in-memory buffers. */
 99518        memjrnlFreeChunks(&copy);
 99519      }
 99520    }
 99521    if( rc!=SQLITE_OK ){
 99522      /* If an error occurred while creating or writing to the file, restore
 99523      ** the original before returning. This way, SQLite uses the in-memory
 99524      ** journal data to roll back changes made to the internal page-cache
 99525      ** before this function was called.  */
 99526      sqlite3OsClose(pReal);
 99527      *p = copy;
 99528    }
 99529    return rc;
 99530  }
 99531  
 99532  
 99533  /*
 99534  ** Write data to the file.
 99535  */
 99536  static int memjrnlWrite(
 99537    sqlite3_file *pJfd,    /* The journal file into which to write */
 99538    const void *zBuf,      /* Take data to be written from here */
 99539    int iAmt,              /* Number of bytes to write */
 99540    sqlite_int64 iOfst     /* Begin writing at this offset into the file */
 99541  ){
 99542    MemJournal *p = (MemJournal *)pJfd;
 99543    int nWrite = iAmt;
 99544    u8 *zWrite = (u8 *)zBuf;
 99545  
 99546    /* If the file should be created now, create it and write the new data
 99547    ** into the file on disk. */
 99548    if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
 99549      int rc = memjrnlCreateFile(p);
 99550      if( rc==SQLITE_OK ){
 99551        rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
 99552      }
 99553      return rc;
 99554    }
 99555  
 99556    /* If the contents of this write should be stored in memory */
 99557    else{
 99558      /* An in-memory journal file should only ever be appended to. Random
 99559      ** access writes are not required. The only exception to this is when
 99560      ** the in-memory journal is being used by a connection using the
 99561      ** atomic-write optimization. In this case the first 28 bytes of the
 99562      ** journal file may be written as part of committing the transaction. */ 
 99563      assert( iOfst==p->endpoint.iOffset || iOfst==0 );
 99564  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 99565   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 99566      if( iOfst==0 && p->pFirst ){
 99567        assert( p->nChunkSize>iAmt );
 99568        memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
 99569      }else
 99570  #else
 99571      assert( iOfst>0 || p->pFirst==0 );
 99572  #endif
 99573      {
 99574        while( nWrite>0 ){
 99575          FileChunk *pChunk = p->endpoint.pChunk;
 99576          int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
 99577          int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
 99578  
 99579          if( iChunkOffset==0 ){
 99580            /* New chunk is required to extend the file. */
 99581            FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
 99582            if( !pNew ){
 99583              return SQLITE_IOERR_NOMEM_BKPT;
 99584            }
 99585            pNew->pNext = 0;
 99586            if( pChunk ){
 99587              assert( p->pFirst );
 99588              pChunk->pNext = pNew;
 99589            }else{
 99590              assert( !p->pFirst );
 99591              p->pFirst = pNew;
 99592            }
 99593            p->endpoint.pChunk = pNew;
 99594          }
 99595  
 99596          memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
 99597          zWrite += iSpace;
 99598          nWrite -= iSpace;
 99599          p->endpoint.iOffset += iSpace;
 99600        }
 99601        p->nSize = iAmt + iOfst;
 99602      }
 99603    }
 99604  
 99605    return SQLITE_OK;
 99606  }
 99607  
 99608  /*
 99609  ** Truncate the file.
 99610  **
 99611  ** If the journal file is already on disk, truncate it there. Or, if it
 99612  ** is still in main memory but is being truncated to zero bytes in size,
 99613  ** ignore 
 99614  */
 99615  static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
 99616    MemJournal *p = (MemJournal *)pJfd;
 99617    if( ALWAYS(size==0) ){
 99618      memjrnlFreeChunks(p);
 99619      p->nSize = 0;
 99620      p->endpoint.pChunk = 0;
 99621      p->endpoint.iOffset = 0;
 99622      p->readpoint.pChunk = 0;
 99623      p->readpoint.iOffset = 0;
 99624    }
 99625    return SQLITE_OK;
 99626  }
 99627  
 99628  /*
 99629  ** Close the file.
 99630  */
 99631  static int memjrnlClose(sqlite3_file *pJfd){
 99632    MemJournal *p = (MemJournal *)pJfd;
 99633    memjrnlFreeChunks(p);
 99634    return SQLITE_OK;
 99635  }
 99636  
 99637  /*
 99638  ** Sync the file.
 99639  **
 99640  ** If the real file has been created, call its xSync method. Otherwise, 
 99641  ** syncing an in-memory journal is a no-op. 
 99642  */
 99643  static int memjrnlSync(sqlite3_file *pJfd, int flags){
 99644    UNUSED_PARAMETER2(pJfd, flags);
 99645    return SQLITE_OK;
 99646  }
 99647  
 99648  /*
 99649  ** Query the size of the file in bytes.
 99650  */
 99651  static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
 99652    MemJournal *p = (MemJournal *)pJfd;
 99653    *pSize = (sqlite_int64) p->endpoint.iOffset;
 99654    return SQLITE_OK;
 99655  }
 99656  
 99657  /*
 99658  ** Table of methods for MemJournal sqlite3_file object.
 99659  */
 99660  static const struct sqlite3_io_methods MemJournalMethods = {
 99661    1,                /* iVersion */
 99662    memjrnlClose,     /* xClose */
 99663    memjrnlRead,      /* xRead */
 99664    memjrnlWrite,     /* xWrite */
 99665    memjrnlTruncate,  /* xTruncate */
 99666    memjrnlSync,      /* xSync */
 99667    memjrnlFileSize,  /* xFileSize */
 99668    0,                /* xLock */
 99669    0,                /* xUnlock */
 99670    0,                /* xCheckReservedLock */
 99671    0,                /* xFileControl */
 99672    0,                /* xSectorSize */
 99673    0,                /* xDeviceCharacteristics */
 99674    0,                /* xShmMap */
 99675    0,                /* xShmLock */
 99676    0,                /* xShmBarrier */
 99677    0,                /* xShmUnmap */
 99678    0,                /* xFetch */
 99679    0                 /* xUnfetch */
 99680  };
 99681  
 99682  /* 
 99683  ** Open a journal file. 
 99684  **
 99685  ** The behaviour of the journal file depends on the value of parameter 
 99686  ** nSpill. If nSpill is 0, then the journal file is always create and 
 99687  ** accessed using the underlying VFS. If nSpill is less than zero, then
 99688  ** all content is always stored in main-memory. Finally, if nSpill is a
 99689  ** positive value, then the journal file is initially created in-memory
 99690  ** but may be flushed to disk later on. In this case the journal file is
 99691  ** flushed to disk either when it grows larger than nSpill bytes in size,
 99692  ** or when sqlite3JournalCreate() is called.
 99693  */
 99694  SQLITE_PRIVATE int sqlite3JournalOpen(
 99695    sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
 99696    const char *zName,         /* Name of the journal file */
 99697    sqlite3_file *pJfd,        /* Preallocated, blank file handle */
 99698    int flags,                 /* Opening flags */
 99699    int nSpill                 /* Bytes buffered before opening the file */
 99700  ){
 99701    MemJournal *p = (MemJournal*)pJfd;
 99702  
 99703    /* Zero the file-handle object. If nSpill was passed zero, initialize
 99704    ** it using the sqlite3OsOpen() function of the underlying VFS. In this
 99705    ** case none of the code in this module is executed as a result of calls
 99706    ** made on the journal file-handle.  */
 99707    memset(p, 0, sizeof(MemJournal));
 99708    if( nSpill==0 ){
 99709      return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
 99710    }
 99711  
 99712    if( nSpill>0 ){
 99713      p->nChunkSize = nSpill;
 99714    }else{
 99715      p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
 99716      assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
 99717    }
 99718  
 99719    p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
 99720    p->nSpill = nSpill;
 99721    p->flags = flags;
 99722    p->zJournal = zName;
 99723    p->pVfs = pVfs;
 99724    return SQLITE_OK;
 99725  }
 99726  
 99727  /*
 99728  ** Open an in-memory journal file.
 99729  */
 99730  SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
 99731    sqlite3JournalOpen(0, 0, pJfd, 0, -1);
 99732  }
 99733  
 99734  #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
 99735   || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 99736  /*
 99737  ** If the argument p points to a MemJournal structure that is not an 
 99738  ** in-memory-only journal file (i.e. is one that was opened with a +ve
 99739  ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying 
 99740  ** file has not yet been created, create it now.
 99741  */
 99742  SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
 99743    int rc = SQLITE_OK;
 99744    MemJournal *p = (MemJournal*)pJfd;
 99745    if( p->pMethod==&MemJournalMethods && (
 99746  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
 99747       p->nSpill>0
 99748  #else
 99749       /* While this appears to not be possible without ATOMIC_WRITE, the
 99750       ** paths are complex, so it seems prudent to leave the test in as
 99751       ** a NEVER(), in case our analysis is subtly flawed. */
 99752       NEVER(p->nSpill>0)
 99753  #endif
 99754  #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
 99755       || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
 99756  #endif
 99757    )){
 99758      rc = memjrnlCreateFile(p);
 99759    }
 99760    return rc;
 99761  }
 99762  #endif
 99763  
 99764  /*
 99765  ** The file-handle passed as the only argument is open on a journal file.
 99766  ** Return true if this "journal file" is currently stored in heap memory,
 99767  ** or false otherwise.
 99768  */
 99769  SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
 99770    return p->pMethods==&MemJournalMethods;
 99771  }
 99772  
 99773  /* 
 99774  ** Return the number of bytes required to store a JournalFile that uses vfs
 99775  ** pVfs to create the underlying on-disk files.
 99776  */
 99777  SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
 99778    return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
 99779  }
 99780  
 99781  /************** End of memjournal.c ******************************************/
 99782  /************** Begin file walker.c ******************************************/
 99783  /*
 99784  ** 2008 August 16
 99785  **
 99786  ** The author disclaims copyright to this source code.  In place of
 99787  ** a legal notice, here is a blessing:
 99788  **
 99789  **    May you do good and not evil.
 99790  **    May you find forgiveness for yourself and forgive others.
 99791  **    May you share freely, never taking more than you give.
 99792  **
 99793  *************************************************************************
 99794  ** This file contains routines used for walking the parser tree for
 99795  ** an SQL statement.
 99796  */
 99797  /* #include "sqliteInt.h" */
 99798  /* #include <stdlib.h> */
 99799  /* #include <string.h> */
 99800  
 99801  
 99802  #if !defined(SQLITE_OMIT_WINDOWFUNC)
 99803  /*
 99804  ** Walk all expressions linked into the list of Window objects passed
 99805  ** as the second argument.
 99806  */
 99807  static int walkWindowList(Walker *pWalker, Window *pList){
 99808    Window *pWin;
 99809    for(pWin=pList; pWin; pWin=pWin->pNextWin){
 99810      if( sqlite3WalkExprList(pWalker, pWin->pOrderBy) ) return WRC_Abort;
 99811      if( sqlite3WalkExprList(pWalker, pWin->pPartition) ) return WRC_Abort;
 99812      if( sqlite3WalkExpr(pWalker, pWin->pFilter) ) return WRC_Abort;
 99813    }
 99814    return WRC_Continue;
 99815  }
 99816  #endif
 99817  
 99818  /*
 99819  ** Walk an expression tree.  Invoke the callback once for each node
 99820  ** of the expression, while descending.  (In other words, the callback
 99821  ** is invoked before visiting children.)
 99822  **
 99823  ** The return value from the callback should be one of the WRC_*
 99824  ** constants to specify how to proceed with the walk.
 99825  **
 99826  **    WRC_Continue      Continue descending down the tree.
 99827  **
 99828  **    WRC_Prune         Do not descend into child nodes, but allow
 99829  **                      the walk to continue with sibling nodes.
 99830  **
 99831  **    WRC_Abort         Do no more callbacks.  Unwind the stack and
 99832  **                      return from the top-level walk call.
 99833  **
 99834  ** The return value from this routine is WRC_Abort to abandon the tree walk
 99835  ** and WRC_Continue to continue.
 99836  */
 99837  static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
 99838    int rc;
 99839    testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
 99840    testcase( ExprHasProperty(pExpr, EP_Reduced) );
 99841    while(1){
 99842      rc = pWalker->xExprCallback(pWalker, pExpr);
 99843      if( rc ) return rc & WRC_Abort;
 99844      if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
 99845        if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
 99846         assert( pExpr->x.pList==0 || pExpr->pRight==0 );
 99847        if( pExpr->pRight ){
 99848          pExpr = pExpr->pRight;
 99849          continue;
 99850        }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 99851          if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
 99852        }else if( pExpr->x.pList ){
 99853          if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
 99854        }
 99855  #ifndef SQLITE_OMIT_WINDOWFUNC
 99856        if( ExprHasProperty(pExpr, EP_WinFunc) ){
 99857          if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
 99858        }
 99859  #endif
 99860      }
 99861      break;
 99862    }
 99863    return WRC_Continue;
 99864  }
 99865  SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
 99866    return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
 99867  }
 99868  
 99869  /*
 99870  ** Call sqlite3WalkExpr() for every expression in list p or until
 99871  ** an abort request is seen.
 99872  */
 99873  SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
 99874    int i;
 99875    struct ExprList_item *pItem;
 99876    if( p ){
 99877      for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
 99878        if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
 99879      }
 99880    }
 99881    return WRC_Continue;
 99882  }
 99883  
 99884  /*
 99885  ** Walk all expressions associated with SELECT statement p.  Do
 99886  ** not invoke the SELECT callback on p, but do (of course) invoke
 99887  ** any expr callbacks and SELECT callbacks that come from subqueries.
 99888  ** Return WRC_Abort or WRC_Continue.
 99889  */
 99890  SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
 99891    if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
 99892    if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
 99893    if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
 99894    if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
 99895    if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
 99896    if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
 99897  #if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
 99898    {
 99899      Parse *pParse = pWalker->pParse;
 99900      if( pParse && IN_RENAME_OBJECT ){
 99901        int rc = walkWindowList(pWalker, p->pWinDefn);
 99902        assert( rc==WRC_Continue );
 99903        return rc;
 99904      }
 99905    }
 99906  #endif
 99907    return WRC_Continue;
 99908  }
 99909  
 99910  /*
 99911  ** Walk the parse trees associated with all subqueries in the
 99912  ** FROM clause of SELECT statement p.  Do not invoke the select
 99913  ** callback on p, but do invoke it on each FROM clause subquery
 99914  ** and on any subqueries further down in the tree.  Return 
 99915  ** WRC_Abort or WRC_Continue;
 99916  */
 99917  SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
 99918    SrcList *pSrc;
 99919    int i;
 99920    struct SrcList_item *pItem;
 99921  
 99922    pSrc = p->pSrc;
 99923    assert( pSrc!=0 );
 99924    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
 99925      if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
 99926        return WRC_Abort;
 99927      }
 99928      if( pItem->fg.isTabFunc
 99929       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
 99930      ){
 99931        return WRC_Abort;
 99932      }
 99933    }
 99934    return WRC_Continue;
 99935  } 
 99936  
 99937  /*
 99938  ** Call sqlite3WalkExpr() for every expression in Select statement p.
 99939  ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
 99940  ** on the compound select chain, p->pPrior. 
 99941  **
 99942  ** If it is not NULL, the xSelectCallback() callback is invoked before
 99943  ** the walk of the expressions and FROM clause. The xSelectCallback2()
 99944  ** method is invoked following the walk of the expressions and FROM clause,
 99945  ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
 99946  ** and if the expressions and FROM clause both return WRC_Continue;
 99947  **
 99948  ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
 99949  ** there is an abort request.
 99950  **
 99951  ** If the Walker does not have an xSelectCallback() then this routine
 99952  ** is a no-op returning WRC_Continue.
 99953  */
 99954  SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
 99955    int rc;
 99956    if( p==0 ) return WRC_Continue;
 99957    if( pWalker->xSelectCallback==0 ) return WRC_Continue;
 99958    do{
 99959      rc = pWalker->xSelectCallback(pWalker, p);
 99960      if( rc ) return rc & WRC_Abort;
 99961      if( sqlite3WalkSelectExpr(pWalker, p)
 99962       || sqlite3WalkSelectFrom(pWalker, p)
 99963      ){
 99964        return WRC_Abort;
 99965      }
 99966      if( pWalker->xSelectCallback2 ){
 99967        pWalker->xSelectCallback2(pWalker, p);
 99968      }
 99969      p = p->pPrior;
 99970    }while( p!=0 );
 99971    return WRC_Continue;
 99972  }
 99973  
 99974  /************** End of walker.c **********************************************/
 99975  /************** Begin file resolve.c *****************************************/
 99976  /*
 99977  ** 2008 August 18
 99978  **
 99979  ** The author disclaims copyright to this source code.  In place of
 99980  ** a legal notice, here is a blessing:
 99981  **
 99982  **    May you do good and not evil.
 99983  **    May you find forgiveness for yourself and forgive others.
 99984  **    May you share freely, never taking more than you give.
 99985  **
 99986  *************************************************************************
 99987  **
 99988  ** This file contains routines used for walking the parser tree and
 99989  ** resolve all identifiers by associating them with a particular
 99990  ** table and column.
 99991  */
 99992  /* #include "sqliteInt.h" */
 99993  
 99994  /*
 99995  ** Walk the expression tree pExpr and increase the aggregate function
 99996  ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
 99997  ** This needs to occur when copying a TK_AGG_FUNCTION node from an
 99998  ** outer query into an inner subquery.
 99999  **
100000  ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
100001  ** is a helper function - a callback for the tree walker.
100002  */
100003  static int incrAggDepth(Walker *pWalker, Expr *pExpr){
100004    if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
100005    return WRC_Continue;
100006  }
100007  static void incrAggFunctionDepth(Expr *pExpr, int N){
100008    if( N>0 ){
100009      Walker w;
100010      memset(&w, 0, sizeof(w));
100011      w.xExprCallback = incrAggDepth;
100012      w.u.n = N;
100013      sqlite3WalkExpr(&w, pExpr);
100014    }
100015  }
100016  
100017  /*
100018  ** Turn the pExpr expression into an alias for the iCol-th column of the
100019  ** result set in pEList.
100020  **
100021  ** If the reference is followed by a COLLATE operator, then make sure
100022  ** the COLLATE operator is preserved.  For example:
100023  **
100024  **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
100025  **
100026  ** Should be transformed into:
100027  **
100028  **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
100029  **
100030  ** The nSubquery parameter specifies how many levels of subquery the
100031  ** alias is removed from the original expression.  The usual value is
100032  ** zero but it might be more if the alias is contained within a subquery
100033  ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
100034  ** structures must be increased by the nSubquery amount.
100035  */
100036  static void resolveAlias(
100037    Parse *pParse,         /* Parsing context */
100038    ExprList *pEList,      /* A result set */
100039    int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
100040    Expr *pExpr,           /* Transform this into an alias to the result set */
100041    const char *zType,     /* "GROUP" or "ORDER" or "" */
100042    int nSubquery          /* Number of subqueries that the label is moving */
100043  ){
100044    Expr *pOrig;           /* The iCol-th column of the result set */
100045    Expr *pDup;            /* Copy of pOrig */
100046    sqlite3 *db;           /* The database connection */
100047  
100048    assert( iCol>=0 && iCol<pEList->nExpr );
100049    pOrig = pEList->a[iCol].pExpr;
100050    assert( pOrig!=0 );
100051    db = pParse->db;
100052    pDup = sqlite3ExprDup(db, pOrig, 0);
100053    if( pDup!=0 ){
100054      if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
100055      if( pExpr->op==TK_COLLATE ){
100056        pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
100057      }
100058  
100059      /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
100060      ** prevents ExprDelete() from deleting the Expr structure itself,
100061      ** allowing it to be repopulated by the memcpy() on the following line.
100062      ** The pExpr->u.zToken might point into memory that will be freed by the
100063      ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
100064      ** make a copy of the token before doing the sqlite3DbFree().
100065      */
100066      ExprSetProperty(pExpr, EP_Static);
100067      sqlite3ExprDelete(db, pExpr);
100068      memcpy(pExpr, pDup, sizeof(*pExpr));
100069      if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
100070        assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
100071        pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
100072        pExpr->flags |= EP_MemToken;
100073      }
100074      sqlite3DbFree(db, pDup);
100075    }
100076    ExprSetProperty(pExpr, EP_Alias);
100077  }
100078  
100079  
100080  /*
100081  ** Return TRUE if the name zCol occurs anywhere in the USING clause.
100082  **
100083  ** Return FALSE if the USING clause is NULL or if it does not contain
100084  ** zCol.
100085  */
100086  static int nameInUsingClause(IdList *pUsing, const char *zCol){
100087    if( pUsing ){
100088      int k;
100089      for(k=0; k<pUsing->nId; k++){
100090        if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
100091      }
100092    }
100093    return 0;
100094  }
100095  
100096  /*
100097  ** Subqueries stores the original database, table and column names for their
100098  ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
100099  ** Check to see if the zSpan given to this routine matches the zDb, zTab,
100100  ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
100101  ** match anything.
100102  */
100103  SQLITE_PRIVATE int sqlite3MatchSpanName(
100104    const char *zSpan,
100105    const char *zCol,
100106    const char *zTab,
100107    const char *zDb
100108  ){
100109    int n;
100110    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
100111    if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
100112      return 0;
100113    }
100114    zSpan += n+1;
100115    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
100116    if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
100117      return 0;
100118    }
100119    zSpan += n+1;
100120    if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
100121      return 0;
100122    }
100123    return 1;
100124  }
100125  
100126  /*
100127  ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
100128  ** that name in the set of source tables in pSrcList and make the pExpr 
100129  ** expression node refer back to that source column.  The following changes
100130  ** are made to pExpr:
100131  **
100132  **    pExpr->iDb           Set the index in db->aDb[] of the database X
100133  **                         (even if X is implied).
100134  **    pExpr->iTable        Set to the cursor number for the table obtained
100135  **                         from pSrcList.
100136  **    pExpr->y.pTab        Points to the Table structure of X.Y (even if
100137  **                         X and/or Y are implied.)
100138  **    pExpr->iColumn       Set to the column number within the table.
100139  **    pExpr->op            Set to TK_COLUMN.
100140  **    pExpr->pLeft         Any expression this points to is deleted
100141  **    pExpr->pRight        Any expression this points to is deleted.
100142  **
100143  ** The zDb variable is the name of the database (the "X").  This value may be
100144  ** NULL meaning that name is of the form Y.Z or Z.  Any available database
100145  ** can be used.  The zTable variable is the name of the table (the "Y").  This
100146  ** value can be NULL if zDb is also NULL.  If zTable is NULL it
100147  ** means that the form of the name is Z and that columns from any table
100148  ** can be used.
100149  **
100150  ** If the name cannot be resolved unambiguously, leave an error message
100151  ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
100152  */
100153  static int lookupName(
100154    Parse *pParse,       /* The parsing context */
100155    const char *zDb,     /* Name of the database containing table, or NULL */
100156    const char *zTab,    /* Name of table containing column, or NULL */
100157    const char *zCol,    /* Name of the column. */
100158    NameContext *pNC,    /* The name context used to resolve the name */
100159    Expr *pExpr          /* Make this EXPR node point to the selected column */
100160  ){
100161    int i, j;                         /* Loop counters */
100162    int cnt = 0;                      /* Number of matching column names */
100163    int cntTab = 0;                   /* Number of matching table names */
100164    int nSubquery = 0;                /* How many levels of subquery */
100165    sqlite3 *db = pParse->db;         /* The database connection */
100166    struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
100167    struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
100168    NameContext *pTopNC = pNC;        /* First namecontext in the list */
100169    Schema *pSchema = 0;              /* Schema of the expression */
100170    int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */
100171    Table *pTab = 0;                  /* Table hold the row */
100172    Column *pCol;                     /* A column of pTab */
100173  
100174    assert( pNC );     /* the name context cannot be NULL. */
100175    assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
100176    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
100177  
100178    /* Initialize the node to no-match */
100179    pExpr->iTable = -1;
100180    ExprSetVVAProperty(pExpr, EP_NoReduce);
100181  
100182    /* Translate the schema name in zDb into a pointer to the corresponding
100183    ** schema.  If not found, pSchema will remain NULL and nothing will match
100184    ** resulting in an appropriate error message toward the end of this routine
100185    */
100186    if( zDb ){
100187      testcase( pNC->ncFlags & NC_PartIdx );
100188      testcase( pNC->ncFlags & NC_IsCheck );
100189      if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
100190        /* Silently ignore database qualifiers inside CHECK constraints and
100191        ** partial indices.  Do not raise errors because that might break
100192        ** legacy and because it does not hurt anything to just ignore the
100193        ** database name. */
100194        zDb = 0;
100195      }else{
100196        for(i=0; i<db->nDb; i++){
100197          assert( db->aDb[i].zDbSName );
100198          if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
100199            pSchema = db->aDb[i].pSchema;
100200            break;
100201          }
100202        }
100203      }
100204    }
100205  
100206    /* Start at the inner-most context and move outward until a match is found */
100207    assert( pNC && cnt==0 );
100208    do{
100209      ExprList *pEList;
100210      SrcList *pSrcList = pNC->pSrcList;
100211  
100212      if( pSrcList ){
100213        for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
100214          pTab = pItem->pTab;
100215          assert( pTab!=0 && pTab->zName!=0 );
100216          assert( pTab->nCol>0 );
100217          if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
100218            int hit = 0;
100219            pEList = pItem->pSelect->pEList;
100220            for(j=0; j<pEList->nExpr; j++){
100221              if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
100222                cnt++;
100223                cntTab = 2;
100224                pMatch = pItem;
100225                pExpr->iColumn = j;
100226                hit = 1;
100227              }
100228            }
100229            if( hit || zTab==0 ) continue;
100230          }
100231          if( zDb && pTab->pSchema!=pSchema ){
100232            continue;
100233          }
100234          if( zTab ){
100235            const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
100236            assert( zTabName!=0 );
100237            if( sqlite3StrICmp(zTabName, zTab)!=0 ){
100238              continue;
100239            }
100240            if( IN_RENAME_OBJECT && pItem->zAlias ){
100241              sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
100242            }
100243          }
100244          if( 0==(cntTab++) ){
100245            pMatch = pItem;
100246          }
100247          for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
100248            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
100249              /* If there has been exactly one prior match and this match
100250              ** is for the right-hand table of a NATURAL JOIN or is in a 
100251              ** USING clause, then skip this match.
100252              */
100253              if( cnt==1 ){
100254                if( pItem->fg.jointype & JT_NATURAL ) continue;
100255                if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
100256              }
100257              cnt++;
100258              pMatch = pItem;
100259              /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
100260              pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
100261              break;
100262            }
100263          }
100264        }
100265        if( pMatch ){
100266          pExpr->iTable = pMatch->iCursor;
100267          pExpr->y.pTab = pMatch->pTab;
100268          /* RIGHT JOIN not (yet) supported */
100269          assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
100270          if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
100271            ExprSetProperty(pExpr, EP_CanBeNull);
100272          }
100273          pSchema = pExpr->y.pTab->pSchema;
100274        }
100275      } /* if( pSrcList ) */
100276  
100277  #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
100278      /* If we have not already resolved the name, then maybe 
100279      ** it is a new.* or old.* trigger argument reference.  Or
100280      ** maybe it is an excluded.* from an upsert.
100281      */
100282      if( zDb==0 && zTab!=0 && cntTab==0 ){
100283        pTab = 0;
100284  #ifndef SQLITE_OMIT_TRIGGER
100285        if( pParse->pTriggerTab!=0 ){
100286          int op = pParse->eTriggerOp;
100287          assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
100288          if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
100289            pExpr->iTable = 1;
100290            pTab = pParse->pTriggerTab;
100291          }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
100292            pExpr->iTable = 0;
100293            pTab = pParse->pTriggerTab;
100294          }
100295        }
100296  #endif /* SQLITE_OMIT_TRIGGER */
100297  #ifndef SQLITE_OMIT_UPSERT
100298        if( (pNC->ncFlags & NC_UUpsert)!=0 ){
100299          Upsert *pUpsert = pNC->uNC.pUpsert;
100300          if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
100301            pTab = pUpsert->pUpsertSrc->a[0].pTab;
100302            pExpr->iTable = 2;
100303          }
100304        }
100305  #endif /* SQLITE_OMIT_UPSERT */
100306  
100307        if( pTab ){ 
100308          int iCol;
100309          pSchema = pTab->pSchema;
100310          cntTab++;
100311          for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
100312            if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
100313              if( iCol==pTab->iPKey ){
100314                iCol = -1;
100315              }
100316              break;
100317            }
100318          }
100319          if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
100320            /* IMP: R-51414-32910 */
100321            iCol = -1;
100322          }
100323          if( iCol<pTab->nCol ){
100324            cnt++;
100325  #ifndef SQLITE_OMIT_UPSERT
100326            if( pExpr->iTable==2 ){
100327              testcase( iCol==(-1) );
100328              if( IN_RENAME_OBJECT ){
100329                pExpr->iColumn = iCol;
100330                pExpr->y.pTab = pTab;
100331                eNewExprOp = TK_COLUMN;
100332              }else{
100333                pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
100334                eNewExprOp = TK_REGISTER;
100335                ExprSetProperty(pExpr, EP_Alias);
100336              }
100337            }else
100338  #endif /* SQLITE_OMIT_UPSERT */
100339            {
100340  #ifndef SQLITE_OMIT_TRIGGER
100341              if( iCol<0 ){
100342                pExpr->affinity = SQLITE_AFF_INTEGER;
100343              }else if( pExpr->iTable==0 ){
100344                testcase( iCol==31 );
100345                testcase( iCol==32 );
100346                pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
100347              }else{
100348                testcase( iCol==31 );
100349                testcase( iCol==32 );
100350                pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
100351              }
100352              pExpr->y.pTab = pTab;
100353              pExpr->iColumn = (i16)iCol;
100354              eNewExprOp = TK_TRIGGER;
100355  #endif /* SQLITE_OMIT_TRIGGER */
100356            }
100357          }
100358        }
100359      }
100360  #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
100361  
100362      /*
100363      ** Perhaps the name is a reference to the ROWID
100364      */
100365      if( cnt==0
100366       && cntTab==1
100367       && pMatch
100368       && (pNC->ncFlags & NC_IdxExpr)==0
100369       && sqlite3IsRowid(zCol)
100370       && VisibleRowid(pMatch->pTab)
100371      ){
100372        cnt = 1;
100373        pExpr->iColumn = -1;
100374        pExpr->affinity = SQLITE_AFF_INTEGER;
100375      }
100376  
100377      /*
100378      ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
100379      ** might refer to an result-set alias.  This happens, for example, when
100380      ** we are resolving names in the WHERE clause of the following command:
100381      **
100382      **     SELECT a+b AS x FROM table WHERE x<10;
100383      **
100384      ** In cases like this, replace pExpr with a copy of the expression that
100385      ** forms the result set entry ("a+b" in the example) and return immediately.
100386      ** Note that the expression in the result set should have already been
100387      ** resolved by the time the WHERE clause is resolved.
100388      **
100389      ** The ability to use an output result-set column in the WHERE, GROUP BY,
100390      ** or HAVING clauses, or as part of a larger expression in the ORDER BY
100391      ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
100392      ** is supported for backwards compatibility only. Hence, we issue a warning
100393      ** on sqlite3_log() whenever the capability is used.
100394      */
100395      if( (pNC->ncFlags & NC_UEList)!=0
100396       && cnt==0
100397       && zTab==0
100398      ){
100399        pEList = pNC->uNC.pEList;
100400        assert( pEList!=0 );
100401        for(j=0; j<pEList->nExpr; j++){
100402          char *zAs = pEList->a[j].zName;
100403          if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
100404            Expr *pOrig;
100405            assert( pExpr->pLeft==0 && pExpr->pRight==0 );
100406            assert( pExpr->x.pList==0 );
100407            assert( pExpr->x.pSelect==0 );
100408            pOrig = pEList->a[j].pExpr;
100409            if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
100410              sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
100411              return WRC_Abort;
100412            }
100413            if( sqlite3ExprVectorSize(pOrig)!=1 ){
100414              sqlite3ErrorMsg(pParse, "row value misused");
100415              return WRC_Abort;
100416            }
100417            resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
100418            cnt = 1;
100419            pMatch = 0;
100420            assert( zTab==0 && zDb==0 );
100421            if( IN_RENAME_OBJECT ){
100422              sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
100423            }
100424            goto lookupname_end;
100425          }
100426        } 
100427      }
100428  
100429      /* Advance to the next name context.  The loop will exit when either
100430      ** we have a match (cnt>0) or when we run out of name contexts.
100431      */
100432      if( cnt ) break;
100433      pNC = pNC->pNext;
100434      nSubquery++;
100435    }while( pNC );
100436  
100437  
100438    /*
100439    ** If X and Y are NULL (in other words if only the column name Z is
100440    ** supplied) and the value of Z is enclosed in double-quotes, then
100441    ** Z is a string literal if it doesn't match any column names.  In that
100442    ** case, we need to return right away and not make any changes to
100443    ** pExpr.
100444    **
100445    ** Because no reference was made to outer contexts, the pNC->nRef
100446    ** fields are not changed in any context.
100447    */
100448    if( cnt==0 && zTab==0 ){
100449      assert( pExpr->op==TK_ID );
100450      if( ExprHasProperty(pExpr,EP_DblQuoted) ){
100451        /* If a double-quoted identifier does not match any known column name,
100452        ** then treat it as a string.
100453        **
100454        ** This hack was added in the early days of SQLite in a misguided attempt
100455        ** to be compatible with MySQL 3.x, which used double-quotes for strings.
100456        ** I now sorely regret putting in this hack. The effect of this hack is
100457        ** that misspelled identifier names are silently converted into strings
100458        ** rather than causing an error, to the frustration of countless
100459        ** programmers. To all those frustrated programmers, my apologies.
100460        **
100461        ** Someday, I hope to get rid of this hack. Unfortunately there is
100462        ** a huge amount of legacy SQL that uses it. So for now, we just
100463        ** issue a warning.
100464        */
100465        sqlite3_log(SQLITE_WARNING,
100466          "double-quoted string literal: \"%w\"", zCol);
100467  #ifdef SQLITE_ENABLE_NORMALIZE
100468        sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
100469  #endif
100470        pExpr->op = TK_STRING;
100471        pExpr->y.pTab = 0;
100472        return WRC_Prune;
100473      }
100474      if( sqlite3ExprIdToTrueFalse(pExpr) ){
100475        return WRC_Prune;
100476      }
100477    }
100478  
100479    /*
100480    ** cnt==0 means there was not match.  cnt>1 means there were two or
100481    ** more matches.  Either way, we have an error.
100482    */
100483    if( cnt!=1 ){
100484      const char *zErr;
100485      zErr = cnt==0 ? "no such column" : "ambiguous column name";
100486      if( zDb ){
100487        sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
100488      }else if( zTab ){
100489        sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
100490      }else{
100491        sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
100492      }
100493      pParse->checkSchema = 1;
100494      pTopNC->nErr++;
100495    }
100496  
100497    /* If a column from a table in pSrcList is referenced, then record
100498    ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
100499    ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
100500    ** column number is greater than the number of bits in the bitmask
100501    ** then set the high-order bit of the bitmask.
100502    */
100503    if( pExpr->iColumn>=0 && pMatch!=0 ){
100504      int n = pExpr->iColumn;
100505      testcase( n==BMS-1 );
100506      if( n>=BMS ){
100507        n = BMS-1;
100508      }
100509      assert( pMatch->iCursor==pExpr->iTable );
100510      pMatch->colUsed |= ((Bitmask)1)<<n;
100511    }
100512  
100513    /* Clean up and return
100514    */
100515    sqlite3ExprDelete(db, pExpr->pLeft);
100516    pExpr->pLeft = 0;
100517    sqlite3ExprDelete(db, pExpr->pRight);
100518    pExpr->pRight = 0;
100519    pExpr->op = eNewExprOp;
100520    ExprSetProperty(pExpr, EP_Leaf);
100521  lookupname_end:
100522    if( cnt==1 ){
100523      assert( pNC!=0 );
100524      if( !ExprHasProperty(pExpr, EP_Alias) ){
100525        sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
100526      }
100527      /* Increment the nRef value on all name contexts from TopNC up to
100528      ** the point where the name matched. */
100529      for(;;){
100530        assert( pTopNC!=0 );
100531        pTopNC->nRef++;
100532        if( pTopNC==pNC ) break;
100533        pTopNC = pTopNC->pNext;
100534      }
100535      return WRC_Prune;
100536    } else {
100537      return WRC_Abort;
100538    }
100539  }
100540  
100541  /*
100542  ** Allocate and return a pointer to an expression to load the column iCol
100543  ** from datasource iSrc in SrcList pSrc.
100544  */
100545  SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
100546    Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
100547    if( p ){
100548      struct SrcList_item *pItem = &pSrc->a[iSrc];
100549      p->y.pTab = pItem->pTab;
100550      p->iTable = pItem->iCursor;
100551      if( p->y.pTab->iPKey==iCol ){
100552        p->iColumn = -1;
100553      }else{
100554        p->iColumn = (ynVar)iCol;
100555        testcase( iCol==BMS );
100556        testcase( iCol==BMS-1 );
100557        pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
100558      }
100559    }
100560    return p;
100561  }
100562  
100563  /*
100564  ** Report an error that an expression is not valid for some set of
100565  ** pNC->ncFlags values determined by validMask.
100566  */
100567  static void notValid(
100568    Parse *pParse,       /* Leave error message here */
100569    NameContext *pNC,    /* The name context */
100570    const char *zMsg,    /* Type of error */
100571    int validMask        /* Set of contexts for which prohibited */
100572  ){
100573    assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
100574    if( (pNC->ncFlags & validMask)!=0 ){
100575      const char *zIn = "partial index WHERE clauses";
100576      if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
100577  #ifndef SQLITE_OMIT_CHECK
100578      else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
100579  #endif
100580      sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
100581    }
100582  }
100583  
100584  /*
100585  ** Expression p should encode a floating point value between 1.0 and 0.0.
100586  ** Return 1024 times this value.  Or return -1 if p is not a floating point
100587  ** value between 1.0 and 0.0.
100588  */
100589  static int exprProbability(Expr *p){
100590    double r = -1.0;
100591    if( p->op!=TK_FLOAT ) return -1;
100592    sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
100593    assert( r>=0.0 );
100594    if( r>1.0 ) return -1;
100595    return (int)(r*134217728.0);
100596  }
100597  
100598  /*
100599  ** This routine is callback for sqlite3WalkExpr().
100600  **
100601  ** Resolve symbolic names into TK_COLUMN operators for the current
100602  ** node in the expression tree.  Return 0 to continue the search down
100603  ** the tree or 2 to abort the tree walk.
100604  **
100605  ** This routine also does error checking and name resolution for
100606  ** function names.  The operator for aggregate functions is changed
100607  ** to TK_AGG_FUNCTION.
100608  */
100609  static int resolveExprStep(Walker *pWalker, Expr *pExpr){
100610    NameContext *pNC;
100611    Parse *pParse;
100612  
100613    pNC = pWalker->u.pNC;
100614    assert( pNC!=0 );
100615    pParse = pNC->pParse;
100616    assert( pParse==pWalker->pParse );
100617  
100618  #ifndef NDEBUG
100619    if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
100620      SrcList *pSrcList = pNC->pSrcList;
100621      int i;
100622      for(i=0; i<pNC->pSrcList->nSrc; i++){
100623        assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
100624      }
100625    }
100626  #endif
100627    switch( pExpr->op ){
100628  
100629  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
100630      /* The special operator TK_ROW means use the rowid for the first
100631      ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
100632      ** clause processing on UPDATE and DELETE statements.
100633      */
100634      case TK_ROW: {
100635        SrcList *pSrcList = pNC->pSrcList;
100636        struct SrcList_item *pItem;
100637        assert( pSrcList && pSrcList->nSrc==1 );
100638        pItem = pSrcList->a;
100639        assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
100640        pExpr->op = TK_COLUMN;
100641        pExpr->y.pTab = pItem->pTab;
100642        pExpr->iTable = pItem->iCursor;
100643        pExpr->iColumn = -1;
100644        pExpr->affinity = SQLITE_AFF_INTEGER;
100645        break;
100646      }
100647  #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
100648            && !defined(SQLITE_OMIT_SUBQUERY) */
100649  
100650      /* A column name:                    ID
100651      ** Or table name and column name:    ID.ID
100652      ** Or a database, table and column:  ID.ID.ID
100653      **
100654      ** The TK_ID and TK_OUT cases are combined so that there will only
100655      ** be one call to lookupName().  Then the compiler will in-line 
100656      ** lookupName() for a size reduction and performance increase.
100657      */
100658      case TK_ID:
100659      case TK_DOT: {
100660        const char *zColumn;
100661        const char *zTable;
100662        const char *zDb;
100663        Expr *pRight;
100664  
100665        if( pExpr->op==TK_ID ){
100666          zDb = 0;
100667          zTable = 0;
100668          zColumn = pExpr->u.zToken;
100669        }else{
100670          Expr *pLeft = pExpr->pLeft;
100671          notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
100672          pRight = pExpr->pRight;
100673          if( pRight->op==TK_ID ){
100674            zDb = 0;
100675          }else{
100676            assert( pRight->op==TK_DOT );
100677            zDb = pLeft->u.zToken;
100678            pLeft = pRight->pLeft;
100679            pRight = pRight->pRight;
100680          }
100681          zTable = pLeft->u.zToken;
100682          zColumn = pRight->u.zToken;
100683          if( IN_RENAME_OBJECT ){
100684            sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
100685            sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
100686          }
100687        }
100688        return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
100689      }
100690  
100691      /* Resolve function names
100692      */
100693      case TK_FUNCTION: {
100694        ExprList *pList = pExpr->x.pList;    /* The argument list */
100695        int n = pList ? pList->nExpr : 0;    /* Number of arguments */
100696        int no_such_func = 0;       /* True if no such function exists */
100697        int wrong_num_args = 0;     /* True if wrong number of arguments */
100698        int is_agg = 0;             /* True if is an aggregate function */
100699        int nId;                    /* Number of characters in function name */
100700        const char *zId;            /* The function name. */
100701        FuncDef *pDef;              /* Information about the function */
100702        u8 enc = ENC(pParse->db);   /* The database encoding */
100703  
100704        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
100705        zId = pExpr->u.zToken;
100706        nId = sqlite3Strlen30(zId);
100707        pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
100708        if( pDef==0 ){
100709          pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
100710          if( pDef==0 ){
100711            no_such_func = 1;
100712          }else{
100713            wrong_num_args = 1;
100714          }
100715        }else{
100716          is_agg = pDef->xFinalize!=0;
100717          if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
100718            ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
100719            if( n==2 ){
100720              pExpr->iTable = exprProbability(pList->a[1].pExpr);
100721              if( pExpr->iTable<0 ){
100722                sqlite3ErrorMsg(pParse,
100723                  "second argument to likelihood() must be a "
100724                  "constant between 0.0 and 1.0");
100725                pNC->nErr++;
100726              }
100727            }else{
100728              /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
100729              ** equivalent to likelihood(X, 0.0625).
100730              ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
100731              ** short-hand for likelihood(X,0.0625).
100732              ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
100733              ** for likelihood(X,0.9375).
100734              ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
100735              ** to likelihood(X,0.9375). */
100736              /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
100737              pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
100738            }             
100739          }
100740  #ifndef SQLITE_OMIT_AUTHORIZATION
100741          {
100742            int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
100743            if( auth!=SQLITE_OK ){
100744              if( auth==SQLITE_DENY ){
100745                sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
100746                                        pDef->zName);
100747                pNC->nErr++;
100748              }
100749              pExpr->op = TK_NULL;
100750              return WRC_Prune;
100751            }
100752          }
100753  #endif
100754          if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
100755            /* For the purposes of the EP_ConstFunc flag, date and time
100756            ** functions and other functions that change slowly are considered
100757            ** constant because they are constant for the duration of one query */
100758            ExprSetProperty(pExpr,EP_ConstFunc);
100759          }
100760          if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
100761            /* Date/time functions that use 'now', and other functions like
100762            ** sqlite_version() that might change over time cannot be used
100763            ** in an index. */
100764            notValid(pParse, pNC, "non-deterministic functions",
100765                     NC_IdxExpr|NC_PartIdx);
100766          }
100767          if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
100768           && pParse->nested==0
100769           && sqlite3Config.bInternalFunctions==0
100770          ){
100771            /* Internal-use-only functions are disallowed unless the
100772            ** SQL is being compiled using sqlite3NestedParse() */
100773            no_such_func = 1;
100774            pDef = 0;
100775          }
100776        }
100777  
100778        if( 0==IN_RENAME_OBJECT ){
100779  #ifndef SQLITE_OMIT_WINDOWFUNC
100780          assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
100781            || (pDef->xValue==0 && pDef->xInverse==0)
100782            || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
100783          );
100784          if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
100785            sqlite3ErrorMsg(pParse, 
100786                "%.*s() may not be used as a window function", nId, zId
100787            );
100788            pNC->nErr++;
100789          }else if( 
100790                (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
100791             || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin)
100792             || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0)
100793          ){
100794            const char *zType;
100795            if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){
100796              zType = "window";
100797            }else{
100798              zType = "aggregate";
100799            }
100800            sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
100801            pNC->nErr++;
100802            is_agg = 0;
100803          }
100804  #else
100805          if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
100806            sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
100807            pNC->nErr++;
100808            is_agg = 0;
100809          }
100810  #endif
100811          else if( no_such_func && pParse->db->init.busy==0
100812  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
100813                    && pParse->explain==0
100814  #endif
100815          ){
100816            sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
100817            pNC->nErr++;
100818          }else if( wrong_num_args ){
100819            sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
100820                 nId, zId);
100821            pNC->nErr++;
100822          }
100823          if( is_agg ){
100824  #ifndef SQLITE_OMIT_WINDOWFUNC
100825            pNC->ncFlags &= ~(pExpr->y.pWin ? NC_AllowWin : NC_AllowAgg);
100826  #else
100827            pNC->ncFlags &= ~NC_AllowAgg;
100828  #endif
100829          }
100830        }
100831        sqlite3WalkExprList(pWalker, pList);
100832        if( is_agg ){
100833  #ifndef SQLITE_OMIT_WINDOWFUNC
100834          if( pExpr->y.pWin ){
100835            Select *pSel = pNC->pWinSelect;
100836            sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef);
100837            sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition);
100838            sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy);
100839            sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
100840            if( 0==pSel->pWin 
100841             || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin) 
100842            ){
100843              pExpr->y.pWin->pNextWin = pSel->pWin;
100844              pSel->pWin = pExpr->y.pWin;
100845            }
100846            pNC->ncFlags |= NC_AllowWin;
100847          }else
100848  #endif /* SQLITE_OMIT_WINDOWFUNC */
100849          {
100850            NameContext *pNC2 = pNC;
100851            pExpr->op = TK_AGG_FUNCTION;
100852            pExpr->op2 = 0;
100853            while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
100854              pExpr->op2++;
100855              pNC2 = pNC2->pNext;
100856            }
100857            assert( pDef!=0 );
100858            if( pNC2 ){
100859              assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
100860              testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
100861              pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
100862  
100863            }
100864            pNC->ncFlags |= NC_AllowAgg;
100865          }
100866        }
100867        /* FIX ME:  Compute pExpr->affinity based on the expected return
100868        ** type of the function 
100869        */
100870        return WRC_Prune;
100871      }
100872  #ifndef SQLITE_OMIT_SUBQUERY
100873      case TK_SELECT:
100874      case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
100875  #endif
100876      case TK_IN: {
100877        testcase( pExpr->op==TK_IN );
100878        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100879          int nRef = pNC->nRef;
100880          notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
100881          sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
100882          assert( pNC->nRef>=nRef );
100883          if( nRef!=pNC->nRef ){
100884            ExprSetProperty(pExpr, EP_VarSelect);
100885            pNC->ncFlags |= NC_VarSelect;
100886          }
100887        }
100888        break;
100889      }
100890      case TK_VARIABLE: {
100891        notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
100892        break;
100893      }
100894      case TK_IS:
100895      case TK_ISNOT: {
100896        Expr *pRight;
100897        assert( !ExprHasProperty(pExpr, EP_Reduced) );
100898        /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
100899        ** and "x IS NOT FALSE". */
100900        if( (pRight = pExpr->pRight)->op==TK_ID ){
100901          int rc = resolveExprStep(pWalker, pRight);
100902          if( rc==WRC_Abort ) return WRC_Abort;
100903          if( pRight->op==TK_TRUEFALSE ){
100904            pExpr->op2 = pExpr->op;
100905            pExpr->op = TK_TRUTH;
100906            return WRC_Continue;
100907          }
100908        }
100909        /* Fall thru */
100910      }
100911      case TK_BETWEEN:
100912      case TK_EQ:
100913      case TK_NE:
100914      case TK_LT:
100915      case TK_LE:
100916      case TK_GT:
100917      case TK_GE: {
100918        int nLeft, nRight;
100919        if( pParse->db->mallocFailed ) break;
100920        assert( pExpr->pLeft!=0 );
100921        nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
100922        if( pExpr->op==TK_BETWEEN ){
100923          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
100924          if( nRight==nLeft ){
100925            nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
100926          }
100927        }else{
100928          assert( pExpr->pRight!=0 );
100929          nRight = sqlite3ExprVectorSize(pExpr->pRight);
100930        }
100931        if( nLeft!=nRight ){
100932          testcase( pExpr->op==TK_EQ );
100933          testcase( pExpr->op==TK_NE );
100934          testcase( pExpr->op==TK_LT );
100935          testcase( pExpr->op==TK_LE );
100936          testcase( pExpr->op==TK_GT );
100937          testcase( pExpr->op==TK_GE );
100938          testcase( pExpr->op==TK_IS );
100939          testcase( pExpr->op==TK_ISNOT );
100940          testcase( pExpr->op==TK_BETWEEN );
100941          sqlite3ErrorMsg(pParse, "row value misused");
100942        }
100943        break; 
100944      }
100945    }
100946    return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
100947  }
100948  
100949  /*
100950  ** pEList is a list of expressions which are really the result set of the
100951  ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
100952  ** This routine checks to see if pE is a simple identifier which corresponds
100953  ** to the AS-name of one of the terms of the expression list.  If it is,
100954  ** this routine return an integer between 1 and N where N is the number of
100955  ** elements in pEList, corresponding to the matching entry.  If there is
100956  ** no match, or if pE is not a simple identifier, then this routine
100957  ** return 0.
100958  **
100959  ** pEList has been resolved.  pE has not.
100960  */
100961  static int resolveAsName(
100962    Parse *pParse,     /* Parsing context for error messages */
100963    ExprList *pEList,  /* List of expressions to scan */
100964    Expr *pE           /* Expression we are trying to match */
100965  ){
100966    int i;             /* Loop counter */
100967  
100968    UNUSED_PARAMETER(pParse);
100969  
100970    if( pE->op==TK_ID ){
100971      char *zCol = pE->u.zToken;
100972      for(i=0; i<pEList->nExpr; i++){
100973        char *zAs = pEList->a[i].zName;
100974        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
100975          return i+1;
100976        }
100977      }
100978    }
100979    return 0;
100980  }
100981  
100982  /*
100983  ** pE is a pointer to an expression which is a single term in the
100984  ** ORDER BY of a compound SELECT.  The expression has not been
100985  ** name resolved.
100986  **
100987  ** At the point this routine is called, we already know that the
100988  ** ORDER BY term is not an integer index into the result set.  That
100989  ** case is handled by the calling routine.
100990  **
100991  ** Attempt to match pE against result set columns in the left-most
100992  ** SELECT statement.  Return the index i of the matching column,
100993  ** as an indication to the caller that it should sort by the i-th column.
100994  ** The left-most column is 1.  In other words, the value returned is the
100995  ** same integer value that would be used in the SQL statement to indicate
100996  ** the column.
100997  **
100998  ** If there is no match, return 0.  Return -1 if an error occurs.
100999  */
101000  static int resolveOrderByTermToExprList(
101001    Parse *pParse,     /* Parsing context for error messages */
101002    Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
101003    Expr *pE           /* The specific ORDER BY term */
101004  ){
101005    int i;             /* Loop counter */
101006    ExprList *pEList;  /* The columns of the result set */
101007    NameContext nc;    /* Name context for resolving pE */
101008    sqlite3 *db;       /* Database connection */
101009    int rc;            /* Return code from subprocedures */
101010    u8 savedSuppErr;   /* Saved value of db->suppressErr */
101011  
101012    assert( sqlite3ExprIsInteger(pE, &i)==0 );
101013    pEList = pSelect->pEList;
101014  
101015    /* Resolve all names in the ORDER BY term expression
101016    */
101017    memset(&nc, 0, sizeof(nc));
101018    nc.pParse = pParse;
101019    nc.pSrcList = pSelect->pSrc;
101020    nc.uNC.pEList = pEList;
101021    nc.ncFlags = NC_AllowAgg|NC_UEList;
101022    nc.nErr = 0;
101023    db = pParse->db;
101024    savedSuppErr = db->suppressErr;
101025    db->suppressErr = 1;
101026    rc = sqlite3ResolveExprNames(&nc, pE);
101027    db->suppressErr = savedSuppErr;
101028    if( rc ) return 0;
101029  
101030    /* Try to match the ORDER BY expression against an expression
101031    ** in the result set.  Return an 1-based index of the matching
101032    ** result-set entry.
101033    */
101034    for(i=0; i<pEList->nExpr; i++){
101035      if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
101036        return i+1;
101037      }
101038    }
101039  
101040    /* If no match, return 0. */
101041    return 0;
101042  }
101043  
101044  /*
101045  ** Generate an ORDER BY or GROUP BY term out-of-range error.
101046  */
101047  static void resolveOutOfRangeError(
101048    Parse *pParse,         /* The error context into which to write the error */
101049    const char *zType,     /* "ORDER" or "GROUP" */
101050    int i,                 /* The index (1-based) of the term out of range */
101051    int mx                 /* Largest permissible value of i */
101052  ){
101053    sqlite3ErrorMsg(pParse, 
101054      "%r %s BY term out of range - should be "
101055      "between 1 and %d", i, zType, mx);
101056  }
101057  
101058  /*
101059  ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
101060  ** each term of the ORDER BY clause is a constant integer between 1
101061  ** and N where N is the number of columns in the compound SELECT.
101062  **
101063  ** ORDER BY terms that are already an integer between 1 and N are
101064  ** unmodified.  ORDER BY terms that are integers outside the range of
101065  ** 1 through N generate an error.  ORDER BY terms that are expressions
101066  ** are matched against result set expressions of compound SELECT
101067  ** beginning with the left-most SELECT and working toward the right.
101068  ** At the first match, the ORDER BY expression is transformed into
101069  ** the integer column number.
101070  **
101071  ** Return the number of errors seen.
101072  */
101073  static int resolveCompoundOrderBy(
101074    Parse *pParse,        /* Parsing context.  Leave error messages here */
101075    Select *pSelect       /* The SELECT statement containing the ORDER BY */
101076  ){
101077    int i;
101078    ExprList *pOrderBy;
101079    ExprList *pEList;
101080    sqlite3 *db;
101081    int moreToDo = 1;
101082  
101083    pOrderBy = pSelect->pOrderBy;
101084    if( pOrderBy==0 ) return 0;
101085    db = pParse->db;
101086    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
101087      sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
101088      return 1;
101089    }
101090    for(i=0; i<pOrderBy->nExpr; i++){
101091      pOrderBy->a[i].done = 0;
101092    }
101093    pSelect->pNext = 0;
101094    while( pSelect->pPrior ){
101095      pSelect->pPrior->pNext = pSelect;
101096      pSelect = pSelect->pPrior;
101097    }
101098    while( pSelect && moreToDo ){
101099      struct ExprList_item *pItem;
101100      moreToDo = 0;
101101      pEList = pSelect->pEList;
101102      assert( pEList!=0 );
101103      for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
101104        int iCol = -1;
101105        Expr *pE, *pDup;
101106        if( pItem->done ) continue;
101107        pE = sqlite3ExprSkipCollate(pItem->pExpr);
101108        if( sqlite3ExprIsInteger(pE, &iCol) ){
101109          if( iCol<=0 || iCol>pEList->nExpr ){
101110            resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
101111            return 1;
101112          }
101113        }else{
101114          iCol = resolveAsName(pParse, pEList, pE);
101115          if( iCol==0 ){
101116            /* Now test if expression pE matches one of the values returned
101117            ** by pSelect. In the usual case this is done by duplicating the 
101118            ** expression, resolving any symbols in it, and then comparing
101119            ** it against each expression returned by the SELECT statement.
101120            ** Once the comparisons are finished, the duplicate expression
101121            ** is deleted.
101122            **
101123            ** Or, if this is running as part of an ALTER TABLE operation,
101124            ** resolve the symbols in the actual expression, not a duplicate.
101125            ** And, if one of the comparisons is successful, leave the expression
101126            ** as is instead of transforming it to an integer as in the usual
101127            ** case. This allows the code in alter.c to modify column
101128            ** refererences within the ORDER BY expression as required.  */
101129            if( IN_RENAME_OBJECT ){
101130              pDup = pE;
101131            }else{
101132              pDup = sqlite3ExprDup(db, pE, 0);
101133            }
101134            if( !db->mallocFailed ){
101135              assert(pDup);
101136              iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
101137            }
101138            if( !IN_RENAME_OBJECT ){
101139              sqlite3ExprDelete(db, pDup);
101140            }
101141          }
101142        }
101143        if( iCol>0 ){
101144          /* Convert the ORDER BY term into an integer column number iCol,
101145          ** taking care to preserve the COLLATE clause if it exists */
101146          if( !IN_RENAME_OBJECT ){
101147            Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
101148            if( pNew==0 ) return 1;
101149            pNew->flags |= EP_IntValue;
101150            pNew->u.iValue = iCol;
101151            if( pItem->pExpr==pE ){
101152              pItem->pExpr = pNew;
101153            }else{
101154              Expr *pParent = pItem->pExpr;
101155              assert( pParent->op==TK_COLLATE );
101156              while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
101157              assert( pParent->pLeft==pE );
101158              pParent->pLeft = pNew;
101159            }
101160            sqlite3ExprDelete(db, pE);
101161            pItem->u.x.iOrderByCol = (u16)iCol;
101162          }
101163          pItem->done = 1;
101164        }else{
101165          moreToDo = 1;
101166        }
101167      }
101168      pSelect = pSelect->pNext;
101169    }
101170    for(i=0; i<pOrderBy->nExpr; i++){
101171      if( pOrderBy->a[i].done==0 ){
101172        sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
101173              "column in the result set", i+1);
101174        return 1;
101175      }
101176    }
101177    return 0;
101178  }
101179  
101180  /*
101181  ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
101182  ** the SELECT statement pSelect.  If any term is reference to a
101183  ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
101184  ** field) then convert that term into a copy of the corresponding result set
101185  ** column.
101186  **
101187  ** If any errors are detected, add an error message to pParse and
101188  ** return non-zero.  Return zero if no errors are seen.
101189  */
101190  SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
101191    Parse *pParse,        /* Parsing context.  Leave error messages here */
101192    Select *pSelect,      /* The SELECT statement containing the clause */
101193    ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
101194    const char *zType     /* "ORDER" or "GROUP" */
101195  ){
101196    int i;
101197    sqlite3 *db = pParse->db;
101198    ExprList *pEList;
101199    struct ExprList_item *pItem;
101200  
101201    if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
101202    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
101203      sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
101204      return 1;
101205    }
101206    pEList = pSelect->pEList;
101207    assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
101208    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
101209      if( pItem->u.x.iOrderByCol ){
101210        if( pItem->u.x.iOrderByCol>pEList->nExpr ){
101211          resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
101212          return 1;
101213        }
101214        resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
101215                     zType,0);
101216      }
101217    }
101218    return 0;
101219  }
101220  
101221  #ifndef SQLITE_OMIT_WINDOWFUNC
101222  /*
101223  ** Walker callback for resolveRemoveWindows().
101224  */
101225  static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
101226    if( ExprHasProperty(pExpr, EP_WinFunc) ){
101227      Window **pp;
101228      for(pp=&pWalker->u.pSelect->pWin; *pp; pp=&(*pp)->pNextWin){
101229        if( *pp==pExpr->y.pWin ){
101230          *pp = (*pp)->pNextWin;
101231          break;
101232        }    
101233      }
101234    }
101235    return WRC_Continue;
101236  }
101237  
101238  /*
101239  ** Remove any Window objects owned by the expression pExpr from the
101240  ** Select.pWin list of Select object pSelect.
101241  */
101242  static void resolveRemoveWindows(Select *pSelect, Expr *pExpr){
101243    Walker sWalker;
101244    memset(&sWalker, 0, sizeof(Walker));
101245    sWalker.xExprCallback = resolveRemoveWindowsCb;
101246    sWalker.u.pSelect = pSelect;
101247    sqlite3WalkExpr(&sWalker, pExpr);
101248  }
101249  #else
101250  # define resolveRemoveWindows(x,y)
101251  #endif
101252  
101253  /*
101254  ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
101255  ** The Name context of the SELECT statement is pNC.  zType is either
101256  ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
101257  **
101258  ** This routine resolves each term of the clause into an expression.
101259  ** If the order-by term is an integer I between 1 and N (where N is the
101260  ** number of columns in the result set of the SELECT) then the expression
101261  ** in the resolution is a copy of the I-th result-set expression.  If
101262  ** the order-by term is an identifier that corresponds to the AS-name of
101263  ** a result-set expression, then the term resolves to a copy of the
101264  ** result-set expression.  Otherwise, the expression is resolved in
101265  ** the usual way - using sqlite3ResolveExprNames().
101266  **
101267  ** This routine returns the number of errors.  If errors occur, then
101268  ** an appropriate error message might be left in pParse.  (OOM errors
101269  ** excepted.)
101270  */
101271  static int resolveOrderGroupBy(
101272    NameContext *pNC,     /* The name context of the SELECT statement */
101273    Select *pSelect,      /* The SELECT statement holding pOrderBy */
101274    ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
101275    const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
101276  ){
101277    int i, j;                      /* Loop counters */
101278    int iCol;                      /* Column number */
101279    struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
101280    Parse *pParse;                 /* Parsing context */
101281    int nResult;                   /* Number of terms in the result set */
101282  
101283    if( pOrderBy==0 ) return 0;
101284    nResult = pSelect->pEList->nExpr;
101285    pParse = pNC->pParse;
101286    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
101287      Expr *pE = pItem->pExpr;
101288      Expr *pE2 = sqlite3ExprSkipCollate(pE);
101289      if( zType[0]!='G' ){
101290        iCol = resolveAsName(pParse, pSelect->pEList, pE2);
101291        if( iCol>0 ){
101292          /* If an AS-name match is found, mark this ORDER BY column as being
101293          ** a copy of the iCol-th result-set column.  The subsequent call to
101294          ** sqlite3ResolveOrderGroupBy() will convert the expression to a
101295          ** copy of the iCol-th result-set expression. */
101296          pItem->u.x.iOrderByCol = (u16)iCol;
101297          continue;
101298        }
101299      }
101300      if( sqlite3ExprIsInteger(pE2, &iCol) ){
101301        /* The ORDER BY term is an integer constant.  Again, set the column
101302        ** number so that sqlite3ResolveOrderGroupBy() will convert the
101303        ** order-by term to a copy of the result-set expression */
101304        if( iCol<1 || iCol>0xffff ){
101305          resolveOutOfRangeError(pParse, zType, i+1, nResult);
101306          return 1;
101307        }
101308        pItem->u.x.iOrderByCol = (u16)iCol;
101309        continue;
101310      }
101311  
101312      /* Otherwise, treat the ORDER BY term as an ordinary expression */
101313      pItem->u.x.iOrderByCol = 0;
101314      if( sqlite3ResolveExprNames(pNC, pE) ){
101315        return 1;
101316      }
101317      for(j=0; j<pSelect->pEList->nExpr; j++){
101318        if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
101319          /* Since this expresion is being changed into a reference
101320          ** to an identical expression in the result set, remove all Window
101321          ** objects belonging to the expression from the Select.pWin list. */
101322          resolveRemoveWindows(pSelect, pE);
101323          pItem->u.x.iOrderByCol = j+1;
101324        }
101325      }
101326    }
101327    return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
101328  }
101329  
101330  /*
101331  ** Resolve names in the SELECT statement p and all of its descendants.
101332  */
101333  static int resolveSelectStep(Walker *pWalker, Select *p){
101334    NameContext *pOuterNC;  /* Context that contains this SELECT */
101335    NameContext sNC;        /* Name context of this SELECT */
101336    int isCompound;         /* True if p is a compound select */
101337    int nCompound;          /* Number of compound terms processed so far */
101338    Parse *pParse;          /* Parsing context */
101339    int i;                  /* Loop counter */
101340    ExprList *pGroupBy;     /* The GROUP BY clause */
101341    Select *pLeftmost;      /* Left-most of SELECT of a compound */
101342    sqlite3 *db;            /* Database connection */
101343    
101344  
101345    assert( p!=0 );
101346    if( p->selFlags & SF_Resolved ){
101347      return WRC_Prune;
101348    }
101349    pOuterNC = pWalker->u.pNC;
101350    pParse = pWalker->pParse;
101351    db = pParse->db;
101352  
101353    /* Normally sqlite3SelectExpand() will be called first and will have
101354    ** already expanded this SELECT.  However, if this is a subquery within
101355    ** an expression, sqlite3ResolveExprNames() will be called without a
101356    ** prior call to sqlite3SelectExpand().  When that happens, let
101357    ** sqlite3SelectPrep() do all of the processing for this SELECT.
101358    ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
101359    ** this routine in the correct order.
101360    */
101361    if( (p->selFlags & SF_Expanded)==0 ){
101362      sqlite3SelectPrep(pParse, p, pOuterNC);
101363      return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
101364    }
101365  
101366    isCompound = p->pPrior!=0;
101367    nCompound = 0;
101368    pLeftmost = p;
101369    while( p ){
101370      assert( (p->selFlags & SF_Expanded)!=0 );
101371      assert( (p->selFlags & SF_Resolved)==0 );
101372      p->selFlags |= SF_Resolved;
101373  
101374      /* Resolve the expressions in the LIMIT and OFFSET clauses. These
101375      ** are not allowed to refer to any names, so pass an empty NameContext.
101376      */
101377      memset(&sNC, 0, sizeof(sNC));
101378      sNC.pParse = pParse;
101379      sNC.pWinSelect = p;
101380      if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
101381        return WRC_Abort;
101382      }
101383  
101384      /* If the SF_Converted flags is set, then this Select object was
101385      ** was created by the convertCompoundSelectToSubquery() function.
101386      ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
101387      ** as if it were part of the sub-query, not the parent. This block
101388      ** moves the pOrderBy down to the sub-query. It will be moved back
101389      ** after the names have been resolved.  */
101390      if( p->selFlags & SF_Converted ){
101391        Select *pSub = p->pSrc->a[0].pSelect;
101392        assert( p->pSrc->nSrc==1 && p->pOrderBy );
101393        assert( pSub->pPrior && pSub->pOrderBy==0 );
101394        pSub->pOrderBy = p->pOrderBy;
101395        p->pOrderBy = 0;
101396      }
101397    
101398      /* Recursively resolve names in all subqueries
101399      */
101400      for(i=0; i<p->pSrc->nSrc; i++){
101401        struct SrcList_item *pItem = &p->pSrc->a[i];
101402        if( pItem->pSelect ){
101403          NameContext *pNC;         /* Used to iterate name contexts */
101404          int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
101405          const char *zSavedContext = pParse->zAuthContext;
101406  
101407          /* Count the total number of references to pOuterNC and all of its
101408          ** parent contexts. After resolving references to expressions in
101409          ** pItem->pSelect, check if this value has changed. If so, then
101410          ** SELECT statement pItem->pSelect must be correlated. Set the
101411          ** pItem->fg.isCorrelated flag if this is the case. */
101412          for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
101413  
101414          if( pItem->zName ) pParse->zAuthContext = pItem->zName;
101415          sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
101416          pParse->zAuthContext = zSavedContext;
101417          if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
101418  
101419          for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
101420          assert( pItem->fg.isCorrelated==0 && nRef<=0 );
101421          pItem->fg.isCorrelated = (nRef!=0);
101422        }
101423      }
101424    
101425      /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
101426      ** resolve the result-set expression list.
101427      */
101428      sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
101429      sNC.pSrcList = p->pSrc;
101430      sNC.pNext = pOuterNC;
101431    
101432      /* Resolve names in the result set. */
101433      if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
101434      sNC.ncFlags &= ~NC_AllowWin;
101435    
101436      /* If there are no aggregate functions in the result-set, and no GROUP BY 
101437      ** expression, do not allow aggregates in any of the other expressions.
101438      */
101439      assert( (p->selFlags & SF_Aggregate)==0 );
101440      pGroupBy = p->pGroupBy;
101441      if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
101442        assert( NC_MinMaxAgg==SF_MinMaxAgg );
101443        p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
101444      }else{
101445        sNC.ncFlags &= ~NC_AllowAgg;
101446      }
101447    
101448      /* If a HAVING clause is present, then there must be a GROUP BY clause.
101449      */
101450      if( p->pHaving && !pGroupBy ){
101451        sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
101452        return WRC_Abort;
101453      }
101454    
101455      /* Add the output column list to the name-context before parsing the
101456      ** other expressions in the SELECT statement. This is so that
101457      ** expressions in the WHERE clause (etc.) can refer to expressions by
101458      ** aliases in the result set.
101459      **
101460      ** Minor point: If this is the case, then the expression will be
101461      ** re-evaluated for each reference to it.
101462      */
101463      assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
101464      sNC.uNC.pEList = p->pEList;
101465      sNC.ncFlags |= NC_UEList;
101466      if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
101467      if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
101468  
101469      /* Resolve names in table-valued-function arguments */
101470      for(i=0; i<p->pSrc->nSrc; i++){
101471        struct SrcList_item *pItem = &p->pSrc->a[i];
101472        if( pItem->fg.isTabFunc
101473         && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 
101474        ){
101475          return WRC_Abort;
101476        }
101477      }
101478  
101479      /* The ORDER BY and GROUP BY clauses may not refer to terms in
101480      ** outer queries 
101481      */
101482      sNC.pNext = 0;
101483      sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
101484  
101485      /* If this is a converted compound query, move the ORDER BY clause from 
101486      ** the sub-query back to the parent query. At this point each term
101487      ** within the ORDER BY clause has been transformed to an integer value.
101488      ** These integers will be replaced by copies of the corresponding result
101489      ** set expressions by the call to resolveOrderGroupBy() below.  */
101490      if( p->selFlags & SF_Converted ){
101491        Select *pSub = p->pSrc->a[0].pSelect;
101492        p->pOrderBy = pSub->pOrderBy;
101493        pSub->pOrderBy = 0;
101494      }
101495  
101496      /* Process the ORDER BY clause for singleton SELECT statements.
101497      ** The ORDER BY clause for compounds SELECT statements is handled
101498      ** below, after all of the result-sets for all of the elements of
101499      ** the compound have been resolved.
101500      **
101501      ** If there is an ORDER BY clause on a term of a compound-select other
101502      ** than the right-most term, then that is a syntax error.  But the error
101503      ** is not detected until much later, and so we need to go ahead and
101504      ** resolve those symbols on the incorrect ORDER BY for consistency.
101505      */
101506      if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
101507       && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
101508      ){
101509        return WRC_Abort;
101510      }
101511      if( db->mallocFailed ){
101512        return WRC_Abort;
101513      }
101514      sNC.ncFlags &= ~NC_AllowWin;
101515    
101516      /* Resolve the GROUP BY clause.  At the same time, make sure 
101517      ** the GROUP BY clause does not contain aggregate functions.
101518      */
101519      if( pGroupBy ){
101520        struct ExprList_item *pItem;
101521      
101522        if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
101523          return WRC_Abort;
101524        }
101525        for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
101526          if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
101527            sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
101528                "the GROUP BY clause");
101529            return WRC_Abort;
101530          }
101531        }
101532      }
101533  
101534      if( IN_RENAME_OBJECT ){
101535        Window *pWin;
101536        for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
101537          if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
101538           || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
101539          ){
101540            return WRC_Abort;
101541          }
101542        }
101543      }
101544  
101545      /* If this is part of a compound SELECT, check that it has the right
101546      ** number of expressions in the select list. */
101547      if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
101548        sqlite3SelectWrongNumTermsError(pParse, p->pNext);
101549        return WRC_Abort;
101550      }
101551  
101552      /* Advance to the next term of the compound
101553      */
101554      p = p->pPrior;
101555      nCompound++;
101556    }
101557  
101558    /* Resolve the ORDER BY on a compound SELECT after all terms of
101559    ** the compound have been resolved.
101560    */
101561    if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
101562      return WRC_Abort;
101563    }
101564  
101565    return WRC_Prune;
101566  }
101567  
101568  /*
101569  ** This routine walks an expression tree and resolves references to
101570  ** table columns and result-set columns.  At the same time, do error
101571  ** checking on function usage and set a flag if any aggregate functions
101572  ** are seen.
101573  **
101574  ** To resolve table columns references we look for nodes (or subtrees) of the 
101575  ** form X.Y.Z or Y.Z or just Z where
101576  **
101577  **      X:   The name of a database.  Ex:  "main" or "temp" or
101578  **           the symbolic name assigned to an ATTACH-ed database.
101579  **
101580  **      Y:   The name of a table in a FROM clause.  Or in a trigger
101581  **           one of the special names "old" or "new".
101582  **
101583  **      Z:   The name of a column in table Y.
101584  **
101585  ** The node at the root of the subtree is modified as follows:
101586  **
101587  **    Expr.op        Changed to TK_COLUMN
101588  **    Expr.pTab      Points to the Table object for X.Y
101589  **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
101590  **    Expr.iTable    The VDBE cursor number for X.Y
101591  **
101592  **
101593  ** To resolve result-set references, look for expression nodes of the
101594  ** form Z (with no X and Y prefix) where the Z matches the right-hand
101595  ** size of an AS clause in the result-set of a SELECT.  The Z expression
101596  ** is replaced by a copy of the left-hand side of the result-set expression.
101597  ** Table-name and function resolution occurs on the substituted expression
101598  ** tree.  For example, in:
101599  **
101600  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
101601  **
101602  ** The "x" term of the order by is replaced by "a+b" to render:
101603  **
101604  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
101605  **
101606  ** Function calls are checked to make sure that the function is 
101607  ** defined and that the correct number of arguments are specified.
101608  ** If the function is an aggregate function, then the NC_HasAgg flag is
101609  ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
101610  ** If an expression contains aggregate functions then the EP_Agg
101611  ** property on the expression is set.
101612  **
101613  ** An error message is left in pParse if anything is amiss.  The number
101614  ** if errors is returned.
101615  */
101616  SQLITE_PRIVATE int sqlite3ResolveExprNames( 
101617    NameContext *pNC,       /* Namespace to resolve expressions in. */
101618    Expr *pExpr             /* The expression to be analyzed. */
101619  ){
101620    u16 savedHasAgg;
101621    Walker w;
101622  
101623    if( pExpr==0 ) return SQLITE_OK;
101624    savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
101625    pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
101626    w.pParse = pNC->pParse;
101627    w.xExprCallback = resolveExprStep;
101628    w.xSelectCallback = resolveSelectStep;
101629    w.xSelectCallback2 = 0;
101630    w.u.pNC = pNC;
101631  #if SQLITE_MAX_EXPR_DEPTH>0
101632    w.pParse->nHeight += pExpr->nHeight;
101633    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
101634      return SQLITE_ERROR;
101635    }
101636  #endif
101637    sqlite3WalkExpr(&w, pExpr);
101638  #if SQLITE_MAX_EXPR_DEPTH>0
101639    w.pParse->nHeight -= pExpr->nHeight;
101640  #endif
101641    if( pNC->ncFlags & NC_HasAgg ){
101642      ExprSetProperty(pExpr, EP_Agg);
101643    }
101644    pNC->ncFlags |= savedHasAgg;
101645    return pNC->nErr>0 || w.pParse->nErr>0;
101646  }
101647  
101648  /*
101649  ** Resolve all names for all expression in an expression list.  This is
101650  ** just like sqlite3ResolveExprNames() except that it works for an expression
101651  ** list rather than a single expression.
101652  */
101653  SQLITE_PRIVATE int sqlite3ResolveExprListNames( 
101654    NameContext *pNC,       /* Namespace to resolve expressions in. */
101655    ExprList *pList         /* The expression list to be analyzed. */
101656  ){
101657    int i;
101658    if( pList ){
101659      for(i=0; i<pList->nExpr; i++){
101660        if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
101661      }
101662    }
101663    return WRC_Continue;
101664  }
101665  
101666  /*
101667  ** Resolve all names in all expressions of a SELECT and in all
101668  ** decendents of the SELECT, including compounds off of p->pPrior,
101669  ** subqueries in expressions, and subqueries used as FROM clause
101670  ** terms.
101671  **
101672  ** See sqlite3ResolveExprNames() for a description of the kinds of
101673  ** transformations that occur.
101674  **
101675  ** All SELECT statements should have been expanded using
101676  ** sqlite3SelectExpand() prior to invoking this routine.
101677  */
101678  SQLITE_PRIVATE void sqlite3ResolveSelectNames(
101679    Parse *pParse,         /* The parser context */
101680    Select *p,             /* The SELECT statement being coded. */
101681    NameContext *pOuterNC  /* Name context for parent SELECT statement */
101682  ){
101683    Walker w;
101684  
101685    assert( p!=0 );
101686    w.xExprCallback = resolveExprStep;
101687    w.xSelectCallback = resolveSelectStep;
101688    w.xSelectCallback2 = 0;
101689    w.pParse = pParse;
101690    w.u.pNC = pOuterNC;
101691    sqlite3WalkSelect(&w, p);
101692  }
101693  
101694  /*
101695  ** Resolve names in expressions that can only reference a single table
101696  ** or which cannot reference any tables at all.  Examples:
101697  **
101698  **    (1)   CHECK constraints
101699  **    (2)   WHERE clauses on partial indices
101700  **    (3)   Expressions in indexes on expressions
101701  **    (4)   Expression arguments to VACUUM INTO.
101702  **
101703  ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
101704  ** nodes of the expression is set to -1 and the Expr.iColumn value is
101705  ** set to the column number.  In case (4), TK_COLUMN nodes cause an error.
101706  **
101707  ** Any errors cause an error message to be set in pParse.
101708  */
101709  SQLITE_PRIVATE int sqlite3ResolveSelfReference(
101710    Parse *pParse,      /* Parsing context */
101711    Table *pTab,        /* The table being referenced, or NULL */
101712    int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr, or 0 */
101713    Expr *pExpr,        /* Expression to resolve.  May be NULL. */
101714    ExprList *pList     /* Expression list to resolve.  May be NULL. */
101715  ){
101716    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
101717    NameContext sNC;                /* Name context for pParse->pNewTable */
101718    int rc;
101719  
101720    assert( type==0 || pTab!=0 );
101721    assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || pTab==0 );
101722    memset(&sNC, 0, sizeof(sNC));
101723    memset(&sSrc, 0, sizeof(sSrc));
101724    if( pTab ){
101725      sSrc.nSrc = 1;
101726      sSrc.a[0].zName = pTab->zName;
101727      sSrc.a[0].pTab = pTab;
101728      sSrc.a[0].iCursor = -1;
101729    }
101730    sNC.pParse = pParse;
101731    sNC.pSrcList = &sSrc;
101732    sNC.ncFlags = type;
101733    if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
101734    if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
101735    return rc;
101736  }
101737  
101738  /************** End of resolve.c *********************************************/
101739  /************** Begin file expr.c ********************************************/
101740  /*
101741  ** 2001 September 15
101742  **
101743  ** The author disclaims copyright to this source code.  In place of
101744  ** a legal notice, here is a blessing:
101745  **
101746  **    May you do good and not evil.
101747  **    May you find forgiveness for yourself and forgive others.
101748  **    May you share freely, never taking more than you give.
101749  **
101750  *************************************************************************
101751  ** This file contains routines used for analyzing expressions and
101752  ** for generating VDBE code that evaluates expressions in SQLite.
101753  */
101754  /* #include "sqliteInt.h" */
101755  
101756  /* Forward declarations */
101757  static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
101758  static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
101759  
101760  /*
101761  ** Return the affinity character for a single column of a table.
101762  */
101763  SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
101764    assert( iCol<pTab->nCol );
101765    return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
101766  }
101767  
101768  /*
101769  ** Return the 'affinity' of the expression pExpr if any.
101770  **
101771  ** If pExpr is a column, a reference to a column via an 'AS' alias,
101772  ** or a sub-select with a column as the return value, then the 
101773  ** affinity of that column is returned. Otherwise, 0x00 is returned,
101774  ** indicating no affinity for the expression.
101775  **
101776  ** i.e. the WHERE clause expressions in the following statements all
101777  ** have an affinity:
101778  **
101779  ** CREATE TABLE t1(a);
101780  ** SELECT * FROM t1 WHERE a;
101781  ** SELECT a AS b FROM t1 WHERE b;
101782  ** SELECT * FROM t1 WHERE (select a from t1);
101783  */
101784  SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
101785    int op;
101786    pExpr = sqlite3ExprSkipCollate(pExpr);
101787    if( pExpr->flags & EP_Generic ) return 0;
101788    op = pExpr->op;
101789    if( op==TK_SELECT ){
101790      assert( pExpr->flags&EP_xIsSelect );
101791      return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
101792    }
101793    if( op==TK_REGISTER ) op = pExpr->op2;
101794  #ifndef SQLITE_OMIT_CAST
101795    if( op==TK_CAST ){
101796      assert( !ExprHasProperty(pExpr, EP_IntValue) );
101797      return sqlite3AffinityType(pExpr->u.zToken, 0);
101798    }
101799  #endif
101800    if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
101801      return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
101802    }
101803    if( op==TK_SELECT_COLUMN ){
101804      assert( pExpr->pLeft->flags&EP_xIsSelect );
101805      return sqlite3ExprAffinity(
101806          pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
101807      );
101808    }
101809    return pExpr->affinity;
101810  }
101811  
101812  /*
101813  ** Set the collating sequence for expression pExpr to be the collating
101814  ** sequence named by pToken.   Return a pointer to a new Expr node that
101815  ** implements the COLLATE operator.
101816  **
101817  ** If a memory allocation error occurs, that fact is recorded in pParse->db
101818  ** and the pExpr parameter is returned unchanged.
101819  */
101820  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
101821    Parse *pParse,           /* Parsing context */
101822    Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
101823    const Token *pCollName,  /* Name of collating sequence */
101824    int dequote              /* True to dequote pCollName */
101825  ){
101826    if( pCollName->n>0 ){
101827      Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
101828      if( pNew ){
101829        pNew->pLeft = pExpr;
101830        pNew->flags |= EP_Collate|EP_Skip;
101831        pExpr = pNew;
101832      }
101833    }
101834    return pExpr;
101835  }
101836  SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
101837    Token s;
101838    assert( zC!=0 );
101839    sqlite3TokenInit(&s, (char*)zC);
101840    return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
101841  }
101842  
101843  /*
101844  ** Skip over any TK_COLLATE operators and any unlikely()
101845  ** or likelihood() function at the root of an expression.
101846  */
101847  SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
101848    while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
101849      if( ExprHasProperty(pExpr, EP_Unlikely) ){
101850        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
101851        assert( pExpr->x.pList->nExpr>0 );
101852        assert( pExpr->op==TK_FUNCTION );
101853        pExpr = pExpr->x.pList->a[0].pExpr;
101854      }else{
101855        assert( pExpr->op==TK_COLLATE );
101856        pExpr = pExpr->pLeft;
101857      }
101858    }   
101859    return pExpr;
101860  }
101861  
101862  /*
101863  ** Return the collation sequence for the expression pExpr. If
101864  ** there is no defined collating sequence, return NULL.
101865  **
101866  ** See also: sqlite3ExprNNCollSeq()
101867  **
101868  ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
101869  ** default collation if pExpr has no defined collation.
101870  **
101871  ** The collating sequence might be determined by a COLLATE operator
101872  ** or by the presence of a column with a defined collating sequence.
101873  ** COLLATE operators take first precedence.  Left operands take
101874  ** precedence over right operands.
101875  */
101876  SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
101877    sqlite3 *db = pParse->db;
101878    CollSeq *pColl = 0;
101879    Expr *p = pExpr;
101880    while( p ){
101881      int op = p->op;
101882      if( p->flags & EP_Generic ) break;
101883      if( op==TK_REGISTER ) op = p->op2;
101884      if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
101885       && p->y.pTab!=0
101886      ){
101887        /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
101888        ** a TK_COLUMN but was previously evaluated and cached in a register */
101889        int j = p->iColumn;
101890        if( j>=0 ){
101891          const char *zColl = p->y.pTab->aCol[j].zColl;
101892          pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
101893        }
101894        break;
101895      }
101896      if( op==TK_CAST || op==TK_UPLUS ){
101897        p = p->pLeft;
101898        continue;
101899      }
101900      if( op==TK_COLLATE ){
101901        pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
101902        break;
101903      }
101904      if( p->flags & EP_Collate ){
101905        if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
101906          p = p->pLeft;
101907        }else{
101908          Expr *pNext  = p->pRight;
101909          /* The Expr.x union is never used at the same time as Expr.pRight */
101910          assert( p->x.pList==0 || p->pRight==0 );
101911          /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
101912          ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
101913          ** least one EP_Collate. Thus the following two ALWAYS. */
101914          if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
101915            int i;
101916            for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
101917              if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
101918                pNext = p->x.pList->a[i].pExpr;
101919                break;
101920              }
101921            }
101922          }
101923          p = pNext;
101924        }
101925      }else{
101926        break;
101927      }
101928    }
101929    if( sqlite3CheckCollSeq(pParse, pColl) ){ 
101930      pColl = 0;
101931    }
101932    return pColl;
101933  }
101934  
101935  /*
101936  ** Return the collation sequence for the expression pExpr. If
101937  ** there is no defined collating sequence, return a pointer to the
101938  ** defautl collation sequence.
101939  **
101940  ** See also: sqlite3ExprCollSeq()
101941  **
101942  ** The sqlite3ExprCollSeq() routine works the same except that it
101943  ** returns NULL if there is no defined collation.
101944  */
101945  SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
101946    CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
101947    if( p==0 ) p = pParse->db->pDfltColl;
101948    assert( p!=0 );
101949    return p;
101950  }
101951  
101952  /*
101953  ** Return TRUE if the two expressions have equivalent collating sequences.
101954  */
101955  SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
101956    CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
101957    CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
101958    return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
101959  }
101960  
101961  /*
101962  ** pExpr is an operand of a comparison operator.  aff2 is the
101963  ** type affinity of the other operand.  This routine returns the
101964  ** type affinity that should be used for the comparison operator.
101965  */
101966  SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
101967    char aff1 = sqlite3ExprAffinity(pExpr);
101968    if( aff1 && aff2 ){
101969      /* Both sides of the comparison are columns. If one has numeric
101970      ** affinity, use that. Otherwise use no affinity.
101971      */
101972      if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
101973        return SQLITE_AFF_NUMERIC;
101974      }else{
101975        return SQLITE_AFF_BLOB;
101976      }
101977    }else if( !aff1 && !aff2 ){
101978      /* Neither side of the comparison is a column.  Compare the
101979      ** results directly.
101980      */
101981      return SQLITE_AFF_BLOB;
101982    }else{
101983      /* One side is a column, the other is not. Use the columns affinity. */
101984      assert( aff1==0 || aff2==0 );
101985      return (aff1 + aff2);
101986    }
101987  }
101988  
101989  /*
101990  ** pExpr is a comparison operator.  Return the type affinity that should
101991  ** be applied to both operands prior to doing the comparison.
101992  */
101993  static char comparisonAffinity(Expr *pExpr){
101994    char aff;
101995    assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
101996            pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
101997            pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
101998    assert( pExpr->pLeft );
101999    aff = sqlite3ExprAffinity(pExpr->pLeft);
102000    if( pExpr->pRight ){
102001      aff = sqlite3CompareAffinity(pExpr->pRight, aff);
102002    }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
102003      aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
102004    }else if( aff==0 ){
102005      aff = SQLITE_AFF_BLOB;
102006    }
102007    return aff;
102008  }
102009  
102010  /*
102011  ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
102012  ** idx_affinity is the affinity of an indexed column. Return true
102013  ** if the index with affinity idx_affinity may be used to implement
102014  ** the comparison in pExpr.
102015  */
102016  SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
102017    char aff = comparisonAffinity(pExpr);
102018    switch( aff ){
102019      case SQLITE_AFF_BLOB:
102020        return 1;
102021      case SQLITE_AFF_TEXT:
102022        return idx_affinity==SQLITE_AFF_TEXT;
102023      default:
102024        return sqlite3IsNumericAffinity(idx_affinity);
102025    }
102026  }
102027  
102028  /*
102029  ** Return the P5 value that should be used for a binary comparison
102030  ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
102031  */
102032  static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
102033    u8 aff = (char)sqlite3ExprAffinity(pExpr2);
102034    aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
102035    return aff;
102036  }
102037  
102038  /*
102039  ** Return a pointer to the collation sequence that should be used by
102040  ** a binary comparison operator comparing pLeft and pRight.
102041  **
102042  ** If the left hand expression has a collating sequence type, then it is
102043  ** used. Otherwise the collation sequence for the right hand expression
102044  ** is used, or the default (BINARY) if neither expression has a collating
102045  ** type.
102046  **
102047  ** Argument pRight (but not pLeft) may be a null pointer. In this case,
102048  ** it is not considered.
102049  */
102050  SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
102051    Parse *pParse, 
102052    Expr *pLeft, 
102053    Expr *pRight
102054  ){
102055    CollSeq *pColl;
102056    assert( pLeft );
102057    if( pLeft->flags & EP_Collate ){
102058      pColl = sqlite3ExprCollSeq(pParse, pLeft);
102059    }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
102060      pColl = sqlite3ExprCollSeq(pParse, pRight);
102061    }else{
102062      pColl = sqlite3ExprCollSeq(pParse, pLeft);
102063      if( !pColl ){
102064        pColl = sqlite3ExprCollSeq(pParse, pRight);
102065      }
102066    }
102067    return pColl;
102068  }
102069  
102070  /*
102071  ** Generate code for a comparison operator.
102072  */
102073  static int codeCompare(
102074    Parse *pParse,    /* The parsing (and code generating) context */
102075    Expr *pLeft,      /* The left operand */
102076    Expr *pRight,     /* The right operand */
102077    int opcode,       /* The comparison opcode */
102078    int in1, int in2, /* Register holding operands */
102079    int dest,         /* Jump here if true.  */
102080    int jumpIfNull    /* If true, jump if either operand is NULL */
102081  ){
102082    int p5;
102083    int addr;
102084    CollSeq *p4;
102085  
102086    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
102087    p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
102088    addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
102089                             (void*)p4, P4_COLLSEQ);
102090    sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
102091    return addr;
102092  }
102093  
102094  /*
102095  ** Return true if expression pExpr is a vector, or false otherwise.
102096  **
102097  ** A vector is defined as any expression that results in two or more
102098  ** columns of result.  Every TK_VECTOR node is an vector because the
102099  ** parser will not generate a TK_VECTOR with fewer than two entries.
102100  ** But a TK_SELECT might be either a vector or a scalar. It is only
102101  ** considered a vector if it has two or more result columns.
102102  */
102103  SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
102104    return sqlite3ExprVectorSize(pExpr)>1;
102105  }
102106  
102107  /*
102108  ** If the expression passed as the only argument is of type TK_VECTOR 
102109  ** return the number of expressions in the vector. Or, if the expression
102110  ** is a sub-select, return the number of columns in the sub-select. For
102111  ** any other type of expression, return 1.
102112  */
102113  SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
102114    u8 op = pExpr->op;
102115    if( op==TK_REGISTER ) op = pExpr->op2;
102116    if( op==TK_VECTOR ){
102117      return pExpr->x.pList->nExpr;
102118    }else if( op==TK_SELECT ){
102119      return pExpr->x.pSelect->pEList->nExpr;
102120    }else{
102121      return 1;
102122    }
102123  }
102124  
102125  /*
102126  ** Return a pointer to a subexpression of pVector that is the i-th
102127  ** column of the vector (numbered starting with 0).  The caller must
102128  ** ensure that i is within range.
102129  **
102130  ** If pVector is really a scalar (and "scalar" here includes subqueries
102131  ** that return a single column!) then return pVector unmodified.
102132  **
102133  ** pVector retains ownership of the returned subexpression.
102134  **
102135  ** If the vector is a (SELECT ...) then the expression returned is
102136  ** just the expression for the i-th term of the result set, and may
102137  ** not be ready for evaluation because the table cursor has not yet
102138  ** been positioned.
102139  */
102140  SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
102141    assert( i<sqlite3ExprVectorSize(pVector) );
102142    if( sqlite3ExprIsVector(pVector) ){
102143      assert( pVector->op2==0 || pVector->op==TK_REGISTER );
102144      if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
102145        return pVector->x.pSelect->pEList->a[i].pExpr;
102146      }else{
102147        return pVector->x.pList->a[i].pExpr;
102148      }
102149    }
102150    return pVector;
102151  }
102152  
102153  /*
102154  ** Compute and return a new Expr object which when passed to
102155  ** sqlite3ExprCode() will generate all necessary code to compute
102156  ** the iField-th column of the vector expression pVector.
102157  **
102158  ** It is ok for pVector to be a scalar (as long as iField==0).  
102159  ** In that case, this routine works like sqlite3ExprDup().
102160  **
102161  ** The caller owns the returned Expr object and is responsible for
102162  ** ensuring that the returned value eventually gets freed.
102163  **
102164  ** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
102165  ** then the returned object will reference pVector and so pVector must remain
102166  ** valid for the life of the returned object.  If pVector is a TK_VECTOR
102167  ** or a scalar expression, then it can be deleted as soon as this routine
102168  ** returns.
102169  **
102170  ** A trick to cause a TK_SELECT pVector to be deleted together with
102171  ** the returned Expr object is to attach the pVector to the pRight field
102172  ** of the returned TK_SELECT_COLUMN Expr object.
102173  */
102174  SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
102175    Parse *pParse,       /* Parsing context */
102176    Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
102177    int iField           /* Which column of the vector to return */
102178  ){
102179    Expr *pRet;
102180    if( pVector->op==TK_SELECT ){
102181      assert( pVector->flags & EP_xIsSelect );
102182      /* The TK_SELECT_COLUMN Expr node:
102183      **
102184      ** pLeft:           pVector containing TK_SELECT.  Not deleted.
102185      ** pRight:          not used.  But recursively deleted.
102186      ** iColumn:         Index of a column in pVector
102187      ** iTable:          0 or the number of columns on the LHS of an assignment
102188      ** pLeft->iTable:   First in an array of register holding result, or 0
102189      **                  if the result is not yet computed.
102190      **
102191      ** sqlite3ExprDelete() specifically skips the recursive delete of
102192      ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
102193      ** can be attached to pRight to cause this node to take ownership of
102194      ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
102195      ** with the same pLeft pointer to the pVector, but only one of them
102196      ** will own the pVector.
102197      */
102198      pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
102199      if( pRet ){
102200        pRet->iColumn = iField;
102201        pRet->pLeft = pVector;
102202      }
102203      assert( pRet==0 || pRet->iTable==0 );
102204    }else{
102205      if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
102206      pRet = sqlite3ExprDup(pParse->db, pVector, 0);
102207      sqlite3RenameTokenRemap(pParse, pRet, pVector);
102208    }
102209    return pRet;
102210  }
102211  
102212  /*
102213  ** If expression pExpr is of type TK_SELECT, generate code to evaluate
102214  ** it. Return the register in which the result is stored (or, if the 
102215  ** sub-select returns more than one column, the first in an array
102216  ** of registers in which the result is stored).
102217  **
102218  ** If pExpr is not a TK_SELECT expression, return 0.
102219  */
102220  static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
102221    int reg = 0;
102222  #ifndef SQLITE_OMIT_SUBQUERY
102223    if( pExpr->op==TK_SELECT ){
102224      reg = sqlite3CodeSubselect(pParse, pExpr);
102225    }
102226  #endif
102227    return reg;
102228  }
102229  
102230  /*
102231  ** Argument pVector points to a vector expression - either a TK_VECTOR
102232  ** or TK_SELECT that returns more than one column. This function returns
102233  ** the register number of a register that contains the value of
102234  ** element iField of the vector.
102235  **
102236  ** If pVector is a TK_SELECT expression, then code for it must have 
102237  ** already been generated using the exprCodeSubselect() routine. In this
102238  ** case parameter regSelect should be the first in an array of registers
102239  ** containing the results of the sub-select. 
102240  **
102241  ** If pVector is of type TK_VECTOR, then code for the requested field
102242  ** is generated. In this case (*pRegFree) may be set to the number of
102243  ** a temporary register to be freed by the caller before returning.
102244  **
102245  ** Before returning, output parameter (*ppExpr) is set to point to the
102246  ** Expr object corresponding to element iElem of the vector.
102247  */
102248  static int exprVectorRegister(
102249    Parse *pParse,                  /* Parse context */
102250    Expr *pVector,                  /* Vector to extract element from */
102251    int iField,                     /* Field to extract from pVector */
102252    int regSelect,                  /* First in array of registers */
102253    Expr **ppExpr,                  /* OUT: Expression element */
102254    int *pRegFree                   /* OUT: Temp register to free */
102255  ){
102256    u8 op = pVector->op;
102257    assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
102258    if( op==TK_REGISTER ){
102259      *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
102260      return pVector->iTable+iField;
102261    }
102262    if( op==TK_SELECT ){
102263      *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
102264       return regSelect+iField;
102265    }
102266    *ppExpr = pVector->x.pList->a[iField].pExpr;
102267    return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
102268  }
102269  
102270  /*
102271  ** Expression pExpr is a comparison between two vector values. Compute
102272  ** the result of the comparison (1, 0, or NULL) and write that
102273  ** result into register dest.
102274  **
102275  ** The caller must satisfy the following preconditions:
102276  **
102277  **    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
102278  **    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
102279  **    otherwise:                op==pExpr->op and p5==0
102280  */
102281  static void codeVectorCompare(
102282    Parse *pParse,        /* Code generator context */
102283    Expr *pExpr,          /* The comparison operation */
102284    int dest,             /* Write results into this register */
102285    u8 op,                /* Comparison operator */
102286    u8 p5                 /* SQLITE_NULLEQ or zero */
102287  ){
102288    Vdbe *v = pParse->pVdbe;
102289    Expr *pLeft = pExpr->pLeft;
102290    Expr *pRight = pExpr->pRight;
102291    int nLeft = sqlite3ExprVectorSize(pLeft);
102292    int i;
102293    int regLeft = 0;
102294    int regRight = 0;
102295    u8 opx = op;
102296    int addrDone = sqlite3VdbeMakeLabel(pParse);
102297  
102298    if( nLeft!=sqlite3ExprVectorSize(pRight) ){
102299      sqlite3ErrorMsg(pParse, "row value misused");
102300      return;
102301    }
102302    assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 
102303         || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 
102304         || pExpr->op==TK_LT || pExpr->op==TK_GT 
102305         || pExpr->op==TK_LE || pExpr->op==TK_GE 
102306    );
102307    assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
102308              || (pExpr->op==TK_ISNOT && op==TK_NE) );
102309    assert( p5==0 || pExpr->op!=op );
102310    assert( p5==SQLITE_NULLEQ || pExpr->op==op );
102311  
102312    p5 |= SQLITE_STOREP2;
102313    if( opx==TK_LE ) opx = TK_LT;
102314    if( opx==TK_GE ) opx = TK_GT;
102315  
102316    regLeft = exprCodeSubselect(pParse, pLeft);
102317    regRight = exprCodeSubselect(pParse, pRight);
102318  
102319    for(i=0; 1 /*Loop exits by "break"*/; i++){
102320      int regFree1 = 0, regFree2 = 0;
102321      Expr *pL, *pR; 
102322      int r1, r2;
102323      assert( i>=0 && i<nLeft );
102324      r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
102325      r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
102326      codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
102327      testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
102328      testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
102329      testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
102330      testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
102331      testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
102332      testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
102333      sqlite3ReleaseTempReg(pParse, regFree1);
102334      sqlite3ReleaseTempReg(pParse, regFree2);
102335      if( i==nLeft-1 ){
102336        break;
102337      }
102338      if( opx==TK_EQ ){
102339        sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
102340        p5 |= SQLITE_KEEPNULL;
102341      }else if( opx==TK_NE ){
102342        sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
102343        p5 |= SQLITE_KEEPNULL;
102344      }else{
102345        assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
102346        sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
102347        VdbeCoverageIf(v, op==TK_LT);
102348        VdbeCoverageIf(v, op==TK_GT);
102349        VdbeCoverageIf(v, op==TK_LE);
102350        VdbeCoverageIf(v, op==TK_GE);
102351        if( i==nLeft-2 ) opx = op;
102352      }
102353    }
102354    sqlite3VdbeResolveLabel(v, addrDone);
102355  }
102356  
102357  #if SQLITE_MAX_EXPR_DEPTH>0
102358  /*
102359  ** Check that argument nHeight is less than or equal to the maximum
102360  ** expression depth allowed. If it is not, leave an error message in
102361  ** pParse.
102362  */
102363  SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
102364    int rc = SQLITE_OK;
102365    int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
102366    if( nHeight>mxHeight ){
102367      sqlite3ErrorMsg(pParse, 
102368         "Expression tree is too large (maximum depth %d)", mxHeight
102369      );
102370      rc = SQLITE_ERROR;
102371    }
102372    return rc;
102373  }
102374  
102375  /* The following three functions, heightOfExpr(), heightOfExprList()
102376  ** and heightOfSelect(), are used to determine the maximum height
102377  ** of any expression tree referenced by the structure passed as the
102378  ** first argument.
102379  **
102380  ** If this maximum height is greater than the current value pointed
102381  ** to by pnHeight, the second parameter, then set *pnHeight to that
102382  ** value.
102383  */
102384  static void heightOfExpr(Expr *p, int *pnHeight){
102385    if( p ){
102386      if( p->nHeight>*pnHeight ){
102387        *pnHeight = p->nHeight;
102388      }
102389    }
102390  }
102391  static void heightOfExprList(ExprList *p, int *pnHeight){
102392    if( p ){
102393      int i;
102394      for(i=0; i<p->nExpr; i++){
102395        heightOfExpr(p->a[i].pExpr, pnHeight);
102396      }
102397    }
102398  }
102399  static void heightOfSelect(Select *pSelect, int *pnHeight){
102400    Select *p;
102401    for(p=pSelect; p; p=p->pPrior){
102402      heightOfExpr(p->pWhere, pnHeight);
102403      heightOfExpr(p->pHaving, pnHeight);
102404      heightOfExpr(p->pLimit, pnHeight);
102405      heightOfExprList(p->pEList, pnHeight);
102406      heightOfExprList(p->pGroupBy, pnHeight);
102407      heightOfExprList(p->pOrderBy, pnHeight);
102408    }
102409  }
102410  
102411  /*
102412  ** Set the Expr.nHeight variable in the structure passed as an 
102413  ** argument. An expression with no children, Expr.pList or 
102414  ** Expr.pSelect member has a height of 1. Any other expression
102415  ** has a height equal to the maximum height of any other 
102416  ** referenced Expr plus one.
102417  **
102418  ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
102419  ** if appropriate.
102420  */
102421  static void exprSetHeight(Expr *p){
102422    int nHeight = 0;
102423    heightOfExpr(p->pLeft, &nHeight);
102424    heightOfExpr(p->pRight, &nHeight);
102425    if( ExprHasProperty(p, EP_xIsSelect) ){
102426      heightOfSelect(p->x.pSelect, &nHeight);
102427    }else if( p->x.pList ){
102428      heightOfExprList(p->x.pList, &nHeight);
102429      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
102430    }
102431    p->nHeight = nHeight + 1;
102432  }
102433  
102434  /*
102435  ** Set the Expr.nHeight variable using the exprSetHeight() function. If
102436  ** the height is greater than the maximum allowed expression depth,
102437  ** leave an error in pParse.
102438  **
102439  ** Also propagate all EP_Propagate flags from the Expr.x.pList into
102440  ** Expr.flags. 
102441  */
102442  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
102443    if( pParse->nErr ) return;
102444    exprSetHeight(p);
102445    sqlite3ExprCheckHeight(pParse, p->nHeight);
102446  }
102447  
102448  /*
102449  ** Return the maximum height of any expression tree referenced
102450  ** by the select statement passed as an argument.
102451  */
102452  SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
102453    int nHeight = 0;
102454    heightOfSelect(p, &nHeight);
102455    return nHeight;
102456  }
102457  #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
102458  /*
102459  ** Propagate all EP_Propagate flags from the Expr.x.pList into
102460  ** Expr.flags. 
102461  */
102462  SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
102463    if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
102464      p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
102465    }
102466  }
102467  #define exprSetHeight(y)
102468  #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
102469  
102470  /*
102471  ** This routine is the core allocator for Expr nodes.
102472  **
102473  ** Construct a new expression node and return a pointer to it.  Memory
102474  ** for this node and for the pToken argument is a single allocation
102475  ** obtained from sqlite3DbMalloc().  The calling function
102476  ** is responsible for making sure the node eventually gets freed.
102477  **
102478  ** If dequote is true, then the token (if it exists) is dequoted.
102479  ** If dequote is false, no dequoting is performed.  The deQuote
102480  ** parameter is ignored if pToken is NULL or if the token does not
102481  ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
102482  ** then the EP_DblQuoted flag is set on the expression node.
102483  **
102484  ** Special case:  If op==TK_INTEGER and pToken points to a string that
102485  ** can be translated into a 32-bit integer, then the token is not
102486  ** stored in u.zToken.  Instead, the integer values is written
102487  ** into u.iValue and the EP_IntValue flag is set.  No extra storage
102488  ** is allocated to hold the integer text and the dequote flag is ignored.
102489  */
102490  SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
102491    sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
102492    int op,                 /* Expression opcode */
102493    const Token *pToken,    /* Token argument.  Might be NULL */
102494    int dequote             /* True to dequote */
102495  ){
102496    Expr *pNew;
102497    int nExtra = 0;
102498    int iValue = 0;
102499  
102500    assert( db!=0 );
102501    if( pToken ){
102502      if( op!=TK_INTEGER || pToken->z==0
102503            || sqlite3GetInt32(pToken->z, &iValue)==0 ){
102504        nExtra = pToken->n+1;
102505        assert( iValue>=0 );
102506      }
102507    }
102508    pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
102509    if( pNew ){
102510      memset(pNew, 0, sizeof(Expr));
102511      pNew->op = (u8)op;
102512      pNew->iAgg = -1;
102513      if( pToken ){
102514        if( nExtra==0 ){
102515          pNew->flags |= EP_IntValue|EP_Leaf;
102516          pNew->u.iValue = iValue;
102517        }else{
102518          pNew->u.zToken = (char*)&pNew[1];
102519          assert( pToken->z!=0 || pToken->n==0 );
102520          if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
102521          pNew->u.zToken[pToken->n] = 0;
102522          if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
102523            sqlite3DequoteExpr(pNew);
102524          }
102525        }
102526      }
102527  #if SQLITE_MAX_EXPR_DEPTH>0
102528      pNew->nHeight = 1;
102529  #endif  
102530    }
102531    return pNew;
102532  }
102533  
102534  /*
102535  ** Allocate a new expression node from a zero-terminated token that has
102536  ** already been dequoted.
102537  */
102538  SQLITE_PRIVATE Expr *sqlite3Expr(
102539    sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
102540    int op,                 /* Expression opcode */
102541    const char *zToken      /* Token argument.  Might be NULL */
102542  ){
102543    Token x;
102544    x.z = zToken;
102545    x.n = sqlite3Strlen30(zToken);
102546    return sqlite3ExprAlloc(db, op, &x, 0);
102547  }
102548  
102549  /*
102550  ** Attach subtrees pLeft and pRight to the Expr node pRoot.
102551  **
102552  ** If pRoot==NULL that means that a memory allocation error has occurred.
102553  ** In that case, delete the subtrees pLeft and pRight.
102554  */
102555  SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
102556    sqlite3 *db,
102557    Expr *pRoot,
102558    Expr *pLeft,
102559    Expr *pRight
102560  ){
102561    if( pRoot==0 ){
102562      assert( db->mallocFailed );
102563      sqlite3ExprDelete(db, pLeft);
102564      sqlite3ExprDelete(db, pRight);
102565    }else{
102566      if( pRight ){
102567        pRoot->pRight = pRight;
102568        pRoot->flags |= EP_Propagate & pRight->flags;
102569      }
102570      if( pLeft ){
102571        pRoot->pLeft = pLeft;
102572        pRoot->flags |= EP_Propagate & pLeft->flags;
102573      }
102574      exprSetHeight(pRoot);
102575    }
102576  }
102577  
102578  /*
102579  ** Allocate an Expr node which joins as many as two subtrees.
102580  **
102581  ** One or both of the subtrees can be NULL.  Return a pointer to the new
102582  ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
102583  ** free the subtrees and return NULL.
102584  */
102585  SQLITE_PRIVATE Expr *sqlite3PExpr(
102586    Parse *pParse,          /* Parsing context */
102587    int op,                 /* Expression opcode */
102588    Expr *pLeft,            /* Left operand */
102589    Expr *pRight            /* Right operand */
102590  ){
102591    Expr *p;
102592    if( op==TK_AND && pParse->nErr==0 && !IN_RENAME_OBJECT ){
102593      /* Take advantage of short-circuit false optimization for AND */
102594      p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
102595    }else{
102596      p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
102597      if( p ){
102598        memset(p, 0, sizeof(Expr));
102599        p->op = op & TKFLG_MASK;
102600        p->iAgg = -1;
102601      }
102602      sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
102603    }
102604    if( p ) {
102605      sqlite3ExprCheckHeight(pParse, p->nHeight);
102606    }
102607    return p;
102608  }
102609  
102610  /*
102611  ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
102612  ** do a memory allocation failure) then delete the pSelect object.
102613  */
102614  SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
102615    if( pExpr ){
102616      pExpr->x.pSelect = pSelect;
102617      ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
102618      sqlite3ExprSetHeightAndFlags(pParse, pExpr);
102619    }else{
102620      assert( pParse->db->mallocFailed );
102621      sqlite3SelectDelete(pParse->db, pSelect);
102622    }
102623  }
102624  
102625  
102626  /*
102627  ** If the expression is always either TRUE or FALSE (respectively),
102628  ** then return 1.  If one cannot determine the truth value of the
102629  ** expression at compile-time return 0.
102630  **
102631  ** This is an optimization.  If is OK to return 0 here even if
102632  ** the expression really is always false or false (a false negative).
102633  ** But it is a bug to return 1 if the expression might have different
102634  ** boolean values in different circumstances (a false positive.)
102635  **
102636  ** Note that if the expression is part of conditional for a
102637  ** LEFT JOIN, then we cannot determine at compile-time whether or not
102638  ** is it true or false, so always return 0.
102639  */
102640  static int exprAlwaysTrue(Expr *p){
102641    int v = 0;
102642    if( ExprHasProperty(p, EP_FromJoin) ) return 0;
102643    if( !sqlite3ExprIsInteger(p, &v) ) return 0;
102644    return v!=0;
102645  }
102646  static int exprAlwaysFalse(Expr *p){
102647    int v = 0;
102648    if( ExprHasProperty(p, EP_FromJoin) ) return 0;
102649    if( !sqlite3ExprIsInteger(p, &v) ) return 0;
102650    return v==0;
102651  }
102652  
102653  /*
102654  ** Join two expressions using an AND operator.  If either expression is
102655  ** NULL, then just return the other expression.
102656  **
102657  ** If one side or the other of the AND is known to be false, then instead
102658  ** of returning an AND expression, just return a constant expression with
102659  ** a value of false.
102660  */
102661  SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
102662    if( pLeft==0 ){
102663      return pRight;
102664    }else if( pRight==0 ){
102665      return pLeft;
102666    }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
102667      sqlite3ExprDelete(db, pLeft);
102668      sqlite3ExprDelete(db, pRight);
102669      return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
102670    }else{
102671      Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
102672      sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
102673      return pNew;
102674    }
102675  }
102676  
102677  /*
102678  ** Construct a new expression node for a function with multiple
102679  ** arguments.
102680  */
102681  SQLITE_PRIVATE Expr *sqlite3ExprFunction(
102682    Parse *pParse,        /* Parsing context */
102683    ExprList *pList,      /* Argument list */
102684    Token *pToken,        /* Name of the function */
102685    int eDistinct         /* SF_Distinct or SF_ALL or 0 */
102686  ){
102687    Expr *pNew;
102688    sqlite3 *db = pParse->db;
102689    assert( pToken );
102690    pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
102691    if( pNew==0 ){
102692      sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
102693      return 0;
102694    }
102695    if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
102696      sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
102697    }
102698    pNew->x.pList = pList;
102699    ExprSetProperty(pNew, EP_HasFunc);
102700    assert( !ExprHasProperty(pNew, EP_xIsSelect) );
102701    sqlite3ExprSetHeightAndFlags(pParse, pNew);
102702    if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
102703    return pNew;
102704  }
102705  
102706  /*
102707  ** Assign a variable number to an expression that encodes a wildcard
102708  ** in the original SQL statement.  
102709  **
102710  ** Wildcards consisting of a single "?" are assigned the next sequential
102711  ** variable number.
102712  **
102713  ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
102714  ** sure "nnn" is not too big to avoid a denial of service attack when
102715  ** the SQL statement comes from an external source.
102716  **
102717  ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
102718  ** as the previous instance of the same wildcard.  Or if this is the first
102719  ** instance of the wildcard, the next sequential variable number is
102720  ** assigned.
102721  */
102722  SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
102723    sqlite3 *db = pParse->db;
102724    const char *z;
102725    ynVar x;
102726  
102727    if( pExpr==0 ) return;
102728    assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
102729    z = pExpr->u.zToken;
102730    assert( z!=0 );
102731    assert( z[0]!=0 );
102732    assert( n==(u32)sqlite3Strlen30(z) );
102733    if( z[1]==0 ){
102734      /* Wildcard of the form "?".  Assign the next variable number */
102735      assert( z[0]=='?' );
102736      x = (ynVar)(++pParse->nVar);
102737    }else{
102738      int doAdd = 0;
102739      if( z[0]=='?' ){
102740        /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
102741        ** use it as the variable number */
102742        i64 i;
102743        int bOk;
102744        if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
102745          i = z[1]-'0';  /* The common case of ?N for a single digit N */
102746          bOk = 1;
102747        }else{
102748          bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
102749        }
102750        testcase( i==0 );
102751        testcase( i==1 );
102752        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
102753        testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
102754        if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
102755          sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
102756              db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
102757          return;
102758        }
102759        x = (ynVar)i;
102760        if( x>pParse->nVar ){
102761          pParse->nVar = (int)x;
102762          doAdd = 1;
102763        }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
102764          doAdd = 1;
102765        }
102766      }else{
102767        /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
102768        ** number as the prior appearance of the same name, or if the name
102769        ** has never appeared before, reuse the same variable number
102770        */
102771        x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
102772        if( x==0 ){
102773          x = (ynVar)(++pParse->nVar);
102774          doAdd = 1;
102775        }
102776      }
102777      if( doAdd ){
102778        pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
102779      }
102780    }
102781    pExpr->iColumn = x;
102782    if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
102783      sqlite3ErrorMsg(pParse, "too many SQL variables");
102784    }
102785  }
102786  
102787  /*
102788  ** Recursively delete an expression tree.
102789  */
102790  static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
102791    assert( p!=0 );
102792    /* Sanity check: Assert that the IntValue is non-negative if it exists */
102793    assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
102794  
102795    assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
102796    assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
102797            || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
102798  #ifdef SQLITE_DEBUG
102799    if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
102800      assert( p->pLeft==0 );
102801      assert( p->pRight==0 );
102802      assert( p->x.pSelect==0 );
102803    }
102804  #endif
102805    if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
102806      /* The Expr.x union is never used at the same time as Expr.pRight */
102807      assert( p->x.pList==0 || p->pRight==0 );
102808      if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
102809      if( p->pRight ){
102810        sqlite3ExprDeleteNN(db, p->pRight);
102811      }else if( ExprHasProperty(p, EP_xIsSelect) ){
102812        sqlite3SelectDelete(db, p->x.pSelect);
102813      }else{
102814        sqlite3ExprListDelete(db, p->x.pList);
102815      }
102816      if( ExprHasProperty(p, EP_WinFunc) ){
102817        assert( p->op==TK_FUNCTION );
102818        sqlite3WindowDelete(db, p->y.pWin);
102819      }
102820    }
102821    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
102822    if( !ExprHasProperty(p, EP_Static) ){
102823      sqlite3DbFreeNN(db, p);
102824    }
102825  }
102826  SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
102827    if( p ) sqlite3ExprDeleteNN(db, p);
102828  }
102829  
102830  /*
102831  ** Return the number of bytes allocated for the expression structure 
102832  ** passed as the first argument. This is always one of EXPR_FULLSIZE,
102833  ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
102834  */
102835  static int exprStructSize(Expr *p){
102836    if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
102837    if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
102838    return EXPR_FULLSIZE;
102839  }
102840  
102841  /*
102842  ** Copy the complete content of an Expr node, taking care not to read
102843  ** past the end of the structure for a reduced-size version of the source
102844  ** Expr.
102845  */
102846  static void exprNodeCopy(Expr *pDest, Expr *pSrc){
102847    memset(pDest, 0, sizeof(Expr));
102848    memcpy(pDest, pSrc, exprStructSize(pSrc));
102849  }
102850  
102851  /*
102852  ** The dupedExpr*Size() routines each return the number of bytes required
102853  ** to store a copy of an expression or expression tree.  They differ in
102854  ** how much of the tree is measured.
102855  **
102856  **     dupedExprStructSize()     Size of only the Expr structure 
102857  **     dupedExprNodeSize()       Size of Expr + space for token
102858  **     dupedExprSize()           Expr + token + subtree components
102859  **
102860  ***************************************************************************
102861  **
102862  ** The dupedExprStructSize() function returns two values OR-ed together:  
102863  ** (1) the space required for a copy of the Expr structure only and 
102864  ** (2) the EP_xxx flags that indicate what the structure size should be.
102865  ** The return values is always one of:
102866  **
102867  **      EXPR_FULLSIZE
102868  **      EXPR_REDUCEDSIZE   | EP_Reduced
102869  **      EXPR_TOKENONLYSIZE | EP_TokenOnly
102870  **
102871  ** The size of the structure can be found by masking the return value
102872  ** of this routine with 0xfff.  The flags can be found by masking the
102873  ** return value with EP_Reduced|EP_TokenOnly.
102874  **
102875  ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
102876  ** (unreduced) Expr objects as they or originally constructed by the parser.
102877  ** During expression analysis, extra information is computed and moved into
102878  ** later parts of the Expr object and that extra information might get chopped
102879  ** off if the expression is reduced.  Note also that it does not work to
102880  ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
102881  ** to reduce a pristine expression tree from the parser.  The implementation
102882  ** of dupedExprStructSize() contain multiple assert() statements that attempt
102883  ** to enforce this constraint.
102884  */
102885  static int dupedExprStructSize(Expr *p, int flags){
102886    int nSize;
102887    assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
102888    assert( EXPR_FULLSIZE<=0xfff );
102889    assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
102890    if( 0==flags || p->op==TK_SELECT_COLUMN 
102891  #ifndef SQLITE_OMIT_WINDOWFUNC
102892     || ExprHasProperty(p, EP_WinFunc)
102893  #endif
102894    ){
102895      nSize = EXPR_FULLSIZE;
102896    }else{
102897      assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
102898      assert( !ExprHasProperty(p, EP_FromJoin) ); 
102899      assert( !ExprHasProperty(p, EP_MemToken) );
102900      assert( !ExprHasProperty(p, EP_NoReduce) );
102901      if( p->pLeft || p->x.pList ){
102902        nSize = EXPR_REDUCEDSIZE | EP_Reduced;
102903      }else{
102904        assert( p->pRight==0 );
102905        nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
102906      }
102907    }
102908    return nSize;
102909  }
102910  
102911  /*
102912  ** This function returns the space in bytes required to store the copy 
102913  ** of the Expr structure and a copy of the Expr.u.zToken string (if that
102914  ** string is defined.)
102915  */
102916  static int dupedExprNodeSize(Expr *p, int flags){
102917    int nByte = dupedExprStructSize(p, flags) & 0xfff;
102918    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
102919      nByte += sqlite3Strlen30NN(p->u.zToken)+1;
102920    }
102921    return ROUND8(nByte);
102922  }
102923  
102924  /*
102925  ** Return the number of bytes required to create a duplicate of the 
102926  ** expression passed as the first argument. The second argument is a
102927  ** mask containing EXPRDUP_XXX flags.
102928  **
102929  ** The value returned includes space to create a copy of the Expr struct
102930  ** itself and the buffer referred to by Expr.u.zToken, if any.
102931  **
102932  ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
102933  ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
102934  ** and Expr.pRight variables (but not for any structures pointed to or 
102935  ** descended from the Expr.x.pList or Expr.x.pSelect variables).
102936  */
102937  static int dupedExprSize(Expr *p, int flags){
102938    int nByte = 0;
102939    if( p ){
102940      nByte = dupedExprNodeSize(p, flags);
102941      if( flags&EXPRDUP_REDUCE ){
102942        nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
102943      }
102944    }
102945    return nByte;
102946  }
102947  
102948  /*
102949  ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
102950  ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
102951  ** to store the copy of expression p, the copies of p->u.zToken
102952  ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
102953  ** if any. Before returning, *pzBuffer is set to the first byte past the
102954  ** portion of the buffer copied into by this function.
102955  */
102956  static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
102957    Expr *pNew;           /* Value to return */
102958    u8 *zAlloc;           /* Memory space from which to build Expr object */
102959    u32 staticFlag;       /* EP_Static if space not obtained from malloc */
102960  
102961    assert( db!=0 );
102962    assert( p );
102963    assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
102964    assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
102965  
102966    /* Figure out where to write the new Expr structure. */
102967    if( pzBuffer ){
102968      zAlloc = *pzBuffer;
102969      staticFlag = EP_Static;
102970    }else{
102971      zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
102972      staticFlag = 0;
102973    }
102974    pNew = (Expr *)zAlloc;
102975  
102976    if( pNew ){
102977      /* Set nNewSize to the size allocated for the structure pointed to
102978      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
102979      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
102980      ** by the copy of the p->u.zToken string (if any).
102981      */
102982      const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
102983      const int nNewSize = nStructSize & 0xfff;
102984      int nToken;
102985      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
102986        nToken = sqlite3Strlen30(p->u.zToken) + 1;
102987      }else{
102988        nToken = 0;
102989      }
102990      if( dupFlags ){
102991        assert( ExprHasProperty(p, EP_Reduced)==0 );
102992        memcpy(zAlloc, p, nNewSize);
102993      }else{
102994        u32 nSize = (u32)exprStructSize(p);
102995        memcpy(zAlloc, p, nSize);
102996        if( nSize<EXPR_FULLSIZE ){ 
102997          memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
102998        }
102999      }
103000  
103001      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
103002      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
103003      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
103004      pNew->flags |= staticFlag;
103005  
103006      /* Copy the p->u.zToken string, if any. */
103007      if( nToken ){
103008        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
103009        memcpy(zToken, p->u.zToken, nToken);
103010      }
103011  
103012      if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
103013        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
103014        if( ExprHasProperty(p, EP_xIsSelect) ){
103015          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
103016        }else{
103017          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
103018        }
103019      }
103020  
103021      /* Fill in pNew->pLeft and pNew->pRight. */
103022      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
103023        zAlloc += dupedExprNodeSize(p, dupFlags);
103024        if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
103025          pNew->pLeft = p->pLeft ?
103026                        exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
103027          pNew->pRight = p->pRight ?
103028                         exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
103029        }
103030  #ifndef SQLITE_OMIT_WINDOWFUNC
103031        if( ExprHasProperty(p, EP_WinFunc) ){
103032          pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
103033          assert( ExprHasProperty(pNew, EP_WinFunc) );
103034        }
103035  #endif /* SQLITE_OMIT_WINDOWFUNC */
103036        if( pzBuffer ){
103037          *pzBuffer = zAlloc;
103038        }
103039      }else{
103040        if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
103041          if( pNew->op==TK_SELECT_COLUMN ){
103042            pNew->pLeft = p->pLeft;
103043            assert( p->iColumn==0 || p->pRight==0 );
103044            assert( p->pRight==0  || p->pRight==p->pLeft );
103045          }else{
103046            pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
103047          }
103048          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
103049        }
103050      }
103051    }
103052    return pNew;
103053  }
103054  
103055  /*
103056  ** Create and return a deep copy of the object passed as the second 
103057  ** argument. If an OOM condition is encountered, NULL is returned
103058  ** and the db->mallocFailed flag set.
103059  */
103060  #ifndef SQLITE_OMIT_CTE
103061  static With *withDup(sqlite3 *db, With *p){
103062    With *pRet = 0;
103063    if( p ){
103064      int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
103065      pRet = sqlite3DbMallocZero(db, nByte);
103066      if( pRet ){
103067        int i;
103068        pRet->nCte = p->nCte;
103069        for(i=0; i<p->nCte; i++){
103070          pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
103071          pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
103072          pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
103073        }
103074      }
103075    }
103076    return pRet;
103077  }
103078  #else
103079  # define withDup(x,y) 0
103080  #endif
103081  
103082  #ifndef SQLITE_OMIT_WINDOWFUNC
103083  /*
103084  ** The gatherSelectWindows() procedure and its helper routine
103085  ** gatherSelectWindowsCallback() are used to scan all the expressions
103086  ** an a newly duplicated SELECT statement and gather all of the Window
103087  ** objects found there, assembling them onto the linked list at Select->pWin.
103088  */
103089  static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
103090    if( pExpr->op==TK_FUNCTION && pExpr->y.pWin!=0 ){
103091      assert( ExprHasProperty(pExpr, EP_WinFunc) );
103092      pExpr->y.pWin->pNextWin = pWalker->u.pSelect->pWin;
103093      pWalker->u.pSelect->pWin = pExpr->y.pWin;
103094    }
103095    return WRC_Continue;
103096  }
103097  static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
103098    return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
103099  }
103100  static void gatherSelectWindows(Select *p){
103101    Walker w;
103102    w.xExprCallback = gatherSelectWindowsCallback;
103103    w.xSelectCallback = gatherSelectWindowsSelectCallback;
103104    w.xSelectCallback2 = 0;
103105    w.pParse = 0;
103106    w.u.pSelect = p;
103107    sqlite3WalkSelect(&w, p);
103108  }
103109  #endif
103110  
103111  
103112  /*
103113  ** The following group of routines make deep copies of expressions,
103114  ** expression lists, ID lists, and select statements.  The copies can
103115  ** be deleted (by being passed to their respective ...Delete() routines)
103116  ** without effecting the originals.
103117  **
103118  ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
103119  ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
103120  ** by subsequent calls to sqlite*ListAppend() routines.
103121  **
103122  ** Any tables that the SrcList might point to are not duplicated.
103123  **
103124  ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
103125  ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
103126  ** truncated version of the usual Expr structure that will be stored as
103127  ** part of the in-memory representation of the database schema.
103128  */
103129  SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
103130    assert( flags==0 || flags==EXPRDUP_REDUCE );
103131    return p ? exprDup(db, p, flags, 0) : 0;
103132  }
103133  SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
103134    ExprList *pNew;
103135    struct ExprList_item *pItem, *pOldItem;
103136    int i;
103137    Expr *pPriorSelectCol = 0;
103138    assert( db!=0 );
103139    if( p==0 ) return 0;
103140    pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
103141    if( pNew==0 ) return 0;
103142    pNew->nExpr = p->nExpr;
103143    pItem = pNew->a;
103144    pOldItem = p->a;
103145    for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
103146      Expr *pOldExpr = pOldItem->pExpr;
103147      Expr *pNewExpr;
103148      pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
103149      if( pOldExpr 
103150       && pOldExpr->op==TK_SELECT_COLUMN
103151       && (pNewExpr = pItem->pExpr)!=0 
103152      ){
103153        assert( pNewExpr->iColumn==0 || i>0 );
103154        if( pNewExpr->iColumn==0 ){
103155          assert( pOldExpr->pLeft==pOldExpr->pRight );
103156          pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
103157        }else{
103158          assert( i>0 );
103159          assert( pItem[-1].pExpr!=0 );
103160          assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
103161          assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
103162          pNewExpr->pLeft = pPriorSelectCol;
103163        }
103164      }
103165      pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
103166      pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
103167      pItem->sortOrder = pOldItem->sortOrder;
103168      pItem->done = 0;
103169      pItem->bSpanIsTab = pOldItem->bSpanIsTab;
103170      pItem->bSorterRef = pOldItem->bSorterRef;
103171      pItem->u = pOldItem->u;
103172    }
103173    return pNew;
103174  }
103175  
103176  /*
103177  ** If cursors, triggers, views and subqueries are all omitted from
103178  ** the build, then none of the following routines, except for 
103179  ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
103180  ** called with a NULL argument.
103181  */
103182  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
103183   || !defined(SQLITE_OMIT_SUBQUERY)
103184  SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
103185    SrcList *pNew;
103186    int i;
103187    int nByte;
103188    assert( db!=0 );
103189    if( p==0 ) return 0;
103190    nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
103191    pNew = sqlite3DbMallocRawNN(db, nByte );
103192    if( pNew==0 ) return 0;
103193    pNew->nSrc = pNew->nAlloc = p->nSrc;
103194    for(i=0; i<p->nSrc; i++){
103195      struct SrcList_item *pNewItem = &pNew->a[i];
103196      struct SrcList_item *pOldItem = &p->a[i];
103197      Table *pTab;
103198      pNewItem->pSchema = pOldItem->pSchema;
103199      pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
103200      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
103201      pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
103202      pNewItem->fg = pOldItem->fg;
103203      pNewItem->iCursor = pOldItem->iCursor;
103204      pNewItem->addrFillSub = pOldItem->addrFillSub;
103205      pNewItem->regReturn = pOldItem->regReturn;
103206      if( pNewItem->fg.isIndexedBy ){
103207        pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
103208      }
103209      pNewItem->pIBIndex = pOldItem->pIBIndex;
103210      if( pNewItem->fg.isTabFunc ){
103211        pNewItem->u1.pFuncArg = 
103212            sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
103213      }
103214      pTab = pNewItem->pTab = pOldItem->pTab;
103215      if( pTab ){
103216        pTab->nTabRef++;
103217      }
103218      pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
103219      pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
103220      pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
103221      pNewItem->colUsed = pOldItem->colUsed;
103222    }
103223    return pNew;
103224  }
103225  SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
103226    IdList *pNew;
103227    int i;
103228    assert( db!=0 );
103229    if( p==0 ) return 0;
103230    pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
103231    if( pNew==0 ) return 0;
103232    pNew->nId = p->nId;
103233    pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
103234    if( pNew->a==0 ){
103235      sqlite3DbFreeNN(db, pNew);
103236      return 0;
103237    }
103238    /* Note that because the size of the allocation for p->a[] is not
103239    ** necessarily a power of two, sqlite3IdListAppend() may not be called
103240    ** on the duplicate created by this function. */
103241    for(i=0; i<p->nId; i++){
103242      struct IdList_item *pNewItem = &pNew->a[i];
103243      struct IdList_item *pOldItem = &p->a[i];
103244      pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
103245      pNewItem->idx = pOldItem->idx;
103246    }
103247    return pNew;
103248  }
103249  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
103250    Select *pRet = 0;
103251    Select *pNext = 0;
103252    Select **pp = &pRet;
103253    Select *p;
103254  
103255    assert( db!=0 );
103256    for(p=pDup; p; p=p->pPrior){
103257      Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
103258      if( pNew==0 ) break;
103259      pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
103260      pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
103261      pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
103262      pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
103263      pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
103264      pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
103265      pNew->op = p->op;
103266      pNew->pNext = pNext;
103267      pNew->pPrior = 0;
103268      pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
103269      pNew->iLimit = 0;
103270      pNew->iOffset = 0;
103271      pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
103272      pNew->addrOpenEphm[0] = -1;
103273      pNew->addrOpenEphm[1] = -1;
103274      pNew->nSelectRow = p->nSelectRow;
103275      pNew->pWith = withDup(db, p->pWith);
103276  #ifndef SQLITE_OMIT_WINDOWFUNC
103277      pNew->pWin = 0;
103278      pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
103279      if( p->pWin ) gatherSelectWindows(pNew);
103280  #endif
103281      pNew->selId = p->selId;
103282      *pp = pNew;
103283      pp = &pNew->pPrior;
103284      pNext = pNew;
103285    }
103286  
103287    return pRet;
103288  }
103289  #else
103290  SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
103291    assert( p==0 );
103292    return 0;
103293  }
103294  #endif
103295  
103296  
103297  /*
103298  ** Add a new element to the end of an expression list.  If pList is
103299  ** initially NULL, then create a new expression list.
103300  **
103301  ** The pList argument must be either NULL or a pointer to an ExprList
103302  ** obtained from a prior call to sqlite3ExprListAppend().  This routine
103303  ** may not be used with an ExprList obtained from sqlite3ExprListDup().
103304  ** Reason:  This routine assumes that the number of slots in pList->a[]
103305  ** is a power of two.  That is true for sqlite3ExprListAppend() returns
103306  ** but is not necessarily true from the return value of sqlite3ExprListDup().
103307  **
103308  ** If a memory allocation error occurs, the entire list is freed and
103309  ** NULL is returned.  If non-NULL is returned, then it is guaranteed
103310  ** that the new entry was successfully appended.
103311  */
103312  SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
103313    Parse *pParse,          /* Parsing context */
103314    ExprList *pList,        /* List to which to append. Might be NULL */
103315    Expr *pExpr             /* Expression to be appended. Might be NULL */
103316  ){
103317    struct ExprList_item *pItem;
103318    sqlite3 *db = pParse->db;
103319    assert( db!=0 );
103320    if( pList==0 ){
103321      pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
103322      if( pList==0 ){
103323        goto no_mem;
103324      }
103325      pList->nExpr = 0;
103326    }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
103327      ExprList *pNew;
103328      pNew = sqlite3DbRealloc(db, pList, 
103329               sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
103330      if( pNew==0 ){
103331        goto no_mem;
103332      }
103333      pList = pNew;
103334    }
103335    pItem = &pList->a[pList->nExpr++];
103336    assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
103337    assert( offsetof(struct ExprList_item,pExpr)==0 );
103338    memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
103339    pItem->pExpr = pExpr;
103340    return pList;
103341  
103342  no_mem:     
103343    /* Avoid leaking memory if malloc has failed. */
103344    sqlite3ExprDelete(db, pExpr);
103345    sqlite3ExprListDelete(db, pList);
103346    return 0;
103347  }
103348  
103349  /*
103350  ** pColumns and pExpr form a vector assignment which is part of the SET
103351  ** clause of an UPDATE statement.  Like this:
103352  **
103353  **        (a,b,c) = (expr1,expr2,expr3)
103354  ** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
103355  **
103356  ** For each term of the vector assignment, append new entries to the
103357  ** expression list pList.  In the case of a subquery on the RHS, append
103358  ** TK_SELECT_COLUMN expressions.
103359  */
103360  SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
103361    Parse *pParse,         /* Parsing context */
103362    ExprList *pList,       /* List to which to append. Might be NULL */
103363    IdList *pColumns,      /* List of names of LHS of the assignment */
103364    Expr *pExpr            /* Vector expression to be appended. Might be NULL */
103365  ){
103366    sqlite3 *db = pParse->db;
103367    int n;
103368    int i;
103369    int iFirst = pList ? pList->nExpr : 0;
103370    /* pColumns can only be NULL due to an OOM but an OOM will cause an
103371    ** exit prior to this routine being invoked */
103372    if( NEVER(pColumns==0) ) goto vector_append_error;
103373    if( pExpr==0 ) goto vector_append_error;
103374  
103375    /* If the RHS is a vector, then we can immediately check to see that 
103376    ** the size of the RHS and LHS match.  But if the RHS is a SELECT, 
103377    ** wildcards ("*") in the result set of the SELECT must be expanded before
103378    ** we can do the size check, so defer the size check until code generation.
103379    */
103380    if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
103381      sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
103382                      pColumns->nId, n);
103383      goto vector_append_error;
103384    }
103385  
103386    for(i=0; i<pColumns->nId; i++){
103387      Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
103388      pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
103389      if( pList ){
103390        assert( pList->nExpr==iFirst+i+1 );
103391        pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
103392        pColumns->a[i].zName = 0;
103393      }
103394    }
103395  
103396    if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
103397      Expr *pFirst = pList->a[iFirst].pExpr;
103398      assert( pFirst!=0 );
103399      assert( pFirst->op==TK_SELECT_COLUMN );
103400       
103401      /* Store the SELECT statement in pRight so it will be deleted when
103402      ** sqlite3ExprListDelete() is called */
103403      pFirst->pRight = pExpr;
103404      pExpr = 0;
103405  
103406      /* Remember the size of the LHS in iTable so that we can check that
103407      ** the RHS and LHS sizes match during code generation. */
103408      pFirst->iTable = pColumns->nId;
103409    }
103410  
103411  vector_append_error:
103412    if( IN_RENAME_OBJECT ){
103413      sqlite3RenameExprUnmap(pParse, pExpr);
103414    }
103415    sqlite3ExprDelete(db, pExpr);
103416    sqlite3IdListDelete(db, pColumns);
103417    return pList;
103418  }
103419  
103420  /*
103421  ** Set the sort order for the last element on the given ExprList.
103422  */
103423  SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
103424    if( p==0 ) return;
103425    assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
103426    assert( p->nExpr>0 );
103427    if( iSortOrder<0 ){
103428      assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
103429      return;
103430    }
103431    p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
103432  }
103433  
103434  /*
103435  ** Set the ExprList.a[].zName element of the most recently added item
103436  ** on the expression list.
103437  **
103438  ** pList might be NULL following an OOM error.  But pName should never be
103439  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
103440  ** is set.
103441  */
103442  SQLITE_PRIVATE void sqlite3ExprListSetName(
103443    Parse *pParse,          /* Parsing context */
103444    ExprList *pList,        /* List to which to add the span. */
103445    Token *pName,           /* Name to be added */
103446    int dequote             /* True to cause the name to be dequoted */
103447  ){
103448    assert( pList!=0 || pParse->db->mallocFailed!=0 );
103449    if( pList ){
103450      struct ExprList_item *pItem;
103451      assert( pList->nExpr>0 );
103452      pItem = &pList->a[pList->nExpr-1];
103453      assert( pItem->zName==0 );
103454      pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
103455      if( dequote ) sqlite3Dequote(pItem->zName);
103456      if( IN_RENAME_OBJECT ){
103457        sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
103458      }
103459    }
103460  }
103461  
103462  /*
103463  ** Set the ExprList.a[].zSpan element of the most recently added item
103464  ** on the expression list.
103465  **
103466  ** pList might be NULL following an OOM error.  But pSpan should never be
103467  ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
103468  ** is set.
103469  */
103470  SQLITE_PRIVATE void sqlite3ExprListSetSpan(
103471    Parse *pParse,          /* Parsing context */
103472    ExprList *pList,        /* List to which to add the span. */
103473    const char *zStart,     /* Start of the span */
103474    const char *zEnd        /* End of the span */
103475  ){
103476    sqlite3 *db = pParse->db;
103477    assert( pList!=0 || db->mallocFailed!=0 );
103478    if( pList ){
103479      struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
103480      assert( pList->nExpr>0 );
103481      sqlite3DbFree(db, pItem->zSpan);
103482      pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
103483    }
103484  }
103485  
103486  /*
103487  ** If the expression list pEList contains more than iLimit elements,
103488  ** leave an error message in pParse.
103489  */
103490  SQLITE_PRIVATE void sqlite3ExprListCheckLength(
103491    Parse *pParse,
103492    ExprList *pEList,
103493    const char *zObject
103494  ){
103495    int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
103496    testcase( pEList && pEList->nExpr==mx );
103497    testcase( pEList && pEList->nExpr==mx+1 );
103498    if( pEList && pEList->nExpr>mx ){
103499      sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
103500    }
103501  }
103502  
103503  /*
103504  ** Delete an entire expression list.
103505  */
103506  static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
103507    int i = pList->nExpr;
103508    struct ExprList_item *pItem =  pList->a;
103509    assert( pList->nExpr>0 );
103510    do{
103511      sqlite3ExprDelete(db, pItem->pExpr);
103512      sqlite3DbFree(db, pItem->zName);
103513      sqlite3DbFree(db, pItem->zSpan);
103514      pItem++;
103515    }while( --i>0 );
103516    sqlite3DbFreeNN(db, pList);
103517  }
103518  SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
103519    if( pList ) exprListDeleteNN(db, pList);
103520  }
103521  
103522  /*
103523  ** Return the bitwise-OR of all Expr.flags fields in the given
103524  ** ExprList.
103525  */
103526  SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
103527    int i;
103528    u32 m = 0;
103529    assert( pList!=0 );
103530    for(i=0; i<pList->nExpr; i++){
103531       Expr *pExpr = pList->a[i].pExpr;
103532       assert( pExpr!=0 );
103533       m |= pExpr->flags;
103534    }
103535    return m;
103536  }
103537  
103538  /*
103539  ** This is a SELECT-node callback for the expression walker that
103540  ** always "fails".  By "fail" in this case, we mean set
103541  ** pWalker->eCode to zero and abort.
103542  **
103543  ** This callback is used by multiple expression walkers.
103544  */
103545  SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
103546    UNUSED_PARAMETER(NotUsed);
103547    pWalker->eCode = 0;
103548    return WRC_Abort;
103549  }
103550  
103551  /*
103552  ** If the input expression is an ID with the name "true" or "false"
103553  ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
103554  ** the conversion happened, and zero if the expression is unaltered.
103555  */
103556  SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
103557    assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
103558    if( !ExprHasProperty(pExpr, EP_Quoted)
103559     && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
103560         || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
103561    ){
103562      pExpr->op = TK_TRUEFALSE;
103563      return 1;
103564    }
103565    return 0;
103566  }
103567  
103568  /*
103569  ** The argument must be a TK_TRUEFALSE Expr node.  Return 1 if it is TRUE
103570  ** and 0 if it is FALSE.
103571  */
103572  SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
103573    assert( pExpr->op==TK_TRUEFALSE );
103574    assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
103575         || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
103576    return pExpr->u.zToken[4]==0;
103577  }
103578  
103579  
103580  /*
103581  ** These routines are Walker callbacks used to check expressions to
103582  ** see if they are "constant" for some definition of constant.  The
103583  ** Walker.eCode value determines the type of "constant" we are looking
103584  ** for.
103585  **
103586  ** These callback routines are used to implement the following:
103587  **
103588  **     sqlite3ExprIsConstant()                  pWalker->eCode==1
103589  **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
103590  **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
103591  **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
103592  **
103593  ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
103594  ** is found to not be a constant.
103595  **
103596  ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
103597  ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
103598  ** an existing schema and 4 when processing a new statement.  A bound
103599  ** parameter raises an error for new statements, but is silently converted
103600  ** to NULL for existing schemas.  This allows sqlite_master tables that 
103601  ** contain a bound parameter because they were generated by older versions
103602  ** of SQLite to be parsed by newer versions of SQLite without raising a
103603  ** malformed schema error.
103604  */
103605  static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
103606  
103607    /* If pWalker->eCode is 2 then any term of the expression that comes from
103608    ** the ON or USING clauses of a left join disqualifies the expression
103609    ** from being considered constant. */
103610    if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
103611      pWalker->eCode = 0;
103612      return WRC_Abort;
103613    }
103614  
103615    switch( pExpr->op ){
103616      /* Consider functions to be constant if all their arguments are constant
103617      ** and either pWalker->eCode==4 or 5 or the function has the
103618      ** SQLITE_FUNC_CONST flag. */
103619      case TK_FUNCTION:
103620        if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
103621          return WRC_Continue;
103622        }else{
103623          pWalker->eCode = 0;
103624          return WRC_Abort;
103625        }
103626      case TK_ID:
103627        /* Convert "true" or "false" in a DEFAULT clause into the
103628        ** appropriate TK_TRUEFALSE operator */
103629        if( sqlite3ExprIdToTrueFalse(pExpr) ){
103630          return WRC_Prune;
103631        }
103632        /* Fall thru */
103633      case TK_COLUMN:
103634      case TK_AGG_FUNCTION:
103635      case TK_AGG_COLUMN:
103636        testcase( pExpr->op==TK_ID );
103637        testcase( pExpr->op==TK_COLUMN );
103638        testcase( pExpr->op==TK_AGG_FUNCTION );
103639        testcase( pExpr->op==TK_AGG_COLUMN );
103640        if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
103641          return WRC_Continue;
103642        }
103643        if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
103644          return WRC_Continue;
103645        }
103646        /* Fall through */
103647      case TK_IF_NULL_ROW:
103648      case TK_REGISTER:
103649        testcase( pExpr->op==TK_REGISTER );
103650        testcase( pExpr->op==TK_IF_NULL_ROW );
103651        pWalker->eCode = 0;
103652        return WRC_Abort;
103653      case TK_VARIABLE:
103654        if( pWalker->eCode==5 ){
103655          /* Silently convert bound parameters that appear inside of CREATE
103656          ** statements into a NULL when parsing the CREATE statement text out
103657          ** of the sqlite_master table */
103658          pExpr->op = TK_NULL;
103659        }else if( pWalker->eCode==4 ){
103660          /* A bound parameter in a CREATE statement that originates from
103661          ** sqlite3_prepare() causes an error */
103662          pWalker->eCode = 0;
103663          return WRC_Abort;
103664        }
103665        /* Fall through */
103666      default:
103667        testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
103668        testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
103669        return WRC_Continue;
103670    }
103671  }
103672  static int exprIsConst(Expr *p, int initFlag, int iCur){
103673    Walker w;
103674    w.eCode = initFlag;
103675    w.xExprCallback = exprNodeIsConstant;
103676    w.xSelectCallback = sqlite3SelectWalkFail;
103677  #ifdef SQLITE_DEBUG
103678    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
103679  #endif
103680    w.u.iCur = iCur;
103681    sqlite3WalkExpr(&w, p);
103682    return w.eCode;
103683  }
103684  
103685  /*
103686  ** Walk an expression tree.  Return non-zero if the expression is constant
103687  ** and 0 if it involves variables or function calls.
103688  **
103689  ** For the purposes of this function, a double-quoted string (ex: "abc")
103690  ** is considered a variable but a single-quoted string (ex: 'abc') is
103691  ** a constant.
103692  */
103693  SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
103694    return exprIsConst(p, 1, 0);
103695  }
103696  
103697  /*
103698  ** Walk an expression tree.  Return non-zero if
103699  **
103700  **   (1) the expression is constant, and
103701  **   (2) the expression does originate in the ON or USING clause
103702  **       of a LEFT JOIN, and
103703  **   (3) the expression does not contain any EP_FixedCol TK_COLUMN
103704  **       operands created by the constant propagation optimization.
103705  **
103706  ** When this routine returns true, it indicates that the expression
103707  ** can be added to the pParse->pConstExpr list and evaluated once when
103708  ** the prepared statement starts up.  See sqlite3ExprCodeAtInit().
103709  */
103710  SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
103711    return exprIsConst(p, 2, 0);
103712  }
103713  
103714  /*
103715  ** Walk an expression tree.  Return non-zero if the expression is constant
103716  ** for any single row of the table with cursor iCur.  In other words, the
103717  ** expression must not refer to any non-deterministic function nor any
103718  ** table other than iCur.
103719  */
103720  SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
103721    return exprIsConst(p, 3, iCur);
103722  }
103723  
103724  
103725  /*
103726  ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
103727  */
103728  static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
103729    ExprList *pGroupBy = pWalker->u.pGroupBy;
103730    int i;
103731  
103732    /* Check if pExpr is identical to any GROUP BY term. If so, consider
103733    ** it constant.  */
103734    for(i=0; i<pGroupBy->nExpr; i++){
103735      Expr *p = pGroupBy->a[i].pExpr;
103736      if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
103737        CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
103738        if( sqlite3IsBinary(pColl) ){
103739          return WRC_Prune;
103740        }
103741      }
103742    }
103743  
103744    /* Check if pExpr is a sub-select. If so, consider it variable. */
103745    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103746      pWalker->eCode = 0;
103747      return WRC_Abort;
103748    }
103749  
103750    return exprNodeIsConstant(pWalker, pExpr);
103751  }
103752  
103753  /*
103754  ** Walk the expression tree passed as the first argument. Return non-zero
103755  ** if the expression consists entirely of constants or copies of terms 
103756  ** in pGroupBy that sort with the BINARY collation sequence.
103757  **
103758  ** This routine is used to determine if a term of the HAVING clause can
103759  ** be promoted into the WHERE clause.  In order for such a promotion to work,
103760  ** the value of the HAVING clause term must be the same for all members of
103761  ** a "group".  The requirement that the GROUP BY term must be BINARY
103762  ** assumes that no other collating sequence will have a finer-grained
103763  ** grouping than binary.  In other words (A=B COLLATE binary) implies
103764  ** A=B in every other collating sequence.  The requirement that the
103765  ** GROUP BY be BINARY is stricter than necessary.  It would also work
103766  ** to promote HAVING clauses that use the same alternative collating
103767  ** sequence as the GROUP BY term, but that is much harder to check,
103768  ** alternative collating sequences are uncommon, and this is only an
103769  ** optimization, so we take the easy way out and simply require the
103770  ** GROUP BY to use the BINARY collating sequence.
103771  */
103772  SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
103773    Walker w;
103774    w.eCode = 1;
103775    w.xExprCallback = exprNodeIsConstantOrGroupBy;
103776    w.xSelectCallback = 0;
103777    w.u.pGroupBy = pGroupBy;
103778    w.pParse = pParse;
103779    sqlite3WalkExpr(&w, p);
103780    return w.eCode;
103781  }
103782  
103783  /*
103784  ** Walk an expression tree.  Return non-zero if the expression is constant
103785  ** or a function call with constant arguments.  Return and 0 if there
103786  ** are any variables.
103787  **
103788  ** For the purposes of this function, a double-quoted string (ex: "abc")
103789  ** is considered a variable but a single-quoted string (ex: 'abc') is
103790  ** a constant.
103791  */
103792  SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
103793    assert( isInit==0 || isInit==1 );
103794    return exprIsConst(p, 4+isInit, 0);
103795  }
103796  
103797  #ifdef SQLITE_ENABLE_CURSOR_HINTS
103798  /*
103799  ** Walk an expression tree.  Return 1 if the expression contains a
103800  ** subquery of some kind.  Return 0 if there are no subqueries.
103801  */
103802  SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
103803    Walker w;
103804    w.eCode = 1;
103805    w.xExprCallback = sqlite3ExprWalkNoop;
103806    w.xSelectCallback = sqlite3SelectWalkFail;
103807  #ifdef SQLITE_DEBUG
103808    w.xSelectCallback2 = sqlite3SelectWalkAssert2;
103809  #endif
103810    sqlite3WalkExpr(&w, p);
103811    return w.eCode==0;
103812  }
103813  #endif
103814  
103815  /*
103816  ** If the expression p codes a constant integer that is small enough
103817  ** to fit in a 32-bit integer, return 1 and put the value of the integer
103818  ** in *pValue.  If the expression is not an integer or if it is too big
103819  ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
103820  */
103821  SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
103822    int rc = 0;
103823    if( p==0 ) return 0;  /* Can only happen following on OOM */
103824  
103825    /* If an expression is an integer literal that fits in a signed 32-bit
103826    ** integer, then the EP_IntValue flag will have already been set */
103827    assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
103828             || sqlite3GetInt32(p->u.zToken, &rc)==0 );
103829  
103830    if( p->flags & EP_IntValue ){
103831      *pValue = p->u.iValue;
103832      return 1;
103833    }
103834    switch( p->op ){
103835      case TK_UPLUS: {
103836        rc = sqlite3ExprIsInteger(p->pLeft, pValue);
103837        break;
103838      }
103839      case TK_UMINUS: {
103840        int v;
103841        if( sqlite3ExprIsInteger(p->pLeft, &v) ){
103842          assert( v!=(-2147483647-1) );
103843          *pValue = -v;
103844          rc = 1;
103845        }
103846        break;
103847      }
103848      default: break;
103849    }
103850    return rc;
103851  }
103852  
103853  /*
103854  ** Return FALSE if there is no chance that the expression can be NULL.
103855  **
103856  ** If the expression might be NULL or if the expression is too complex
103857  ** to tell return TRUE.  
103858  **
103859  ** This routine is used as an optimization, to skip OP_IsNull opcodes
103860  ** when we know that a value cannot be NULL.  Hence, a false positive
103861  ** (returning TRUE when in fact the expression can never be NULL) might
103862  ** be a small performance hit but is otherwise harmless.  On the other
103863  ** hand, a false negative (returning FALSE when the result could be NULL)
103864  ** will likely result in an incorrect answer.  So when in doubt, return
103865  ** TRUE.
103866  */
103867  SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
103868    u8 op;
103869    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
103870      p = p->pLeft;
103871    }
103872    op = p->op;
103873    if( op==TK_REGISTER ) op = p->op2;
103874    switch( op ){
103875      case TK_INTEGER:
103876      case TK_STRING:
103877      case TK_FLOAT:
103878      case TK_BLOB:
103879        return 0;
103880      case TK_COLUMN:
103881        return ExprHasProperty(p, EP_CanBeNull) ||
103882               p->y.pTab==0 ||  /* Reference to column of index on expression */
103883               (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
103884      default:
103885        return 1;
103886    }
103887  }
103888  
103889  /*
103890  ** Return TRUE if the given expression is a constant which would be
103891  ** unchanged by OP_Affinity with the affinity given in the second
103892  ** argument.
103893  **
103894  ** This routine is used to determine if the OP_Affinity operation
103895  ** can be omitted.  When in doubt return FALSE.  A false negative
103896  ** is harmless.  A false positive, however, can result in the wrong
103897  ** answer.
103898  */
103899  SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
103900    u8 op;
103901    if( aff==SQLITE_AFF_BLOB ) return 1;
103902    while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
103903    op = p->op;
103904    if( op==TK_REGISTER ) op = p->op2;
103905    switch( op ){
103906      case TK_INTEGER: {
103907        return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
103908      }
103909      case TK_FLOAT: {
103910        return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
103911      }
103912      case TK_STRING: {
103913        return aff==SQLITE_AFF_TEXT;
103914      }
103915      case TK_BLOB: {
103916        return 1;
103917      }
103918      case TK_COLUMN: {
103919        assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
103920        return p->iColumn<0
103921            && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
103922      }
103923      default: {
103924        return 0;
103925      }
103926    }
103927  }
103928  
103929  /*
103930  ** Return TRUE if the given string is a row-id column name.
103931  */
103932  SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
103933    if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
103934    if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
103935    if( sqlite3StrICmp(z, "OID")==0 ) return 1;
103936    return 0;
103937  }
103938  
103939  /*
103940  ** pX is the RHS of an IN operator.  If pX is a SELECT statement 
103941  ** that can be simplified to a direct table access, then return
103942  ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
103943  ** or if the SELECT statement needs to be manifested into a transient
103944  ** table, then return NULL.
103945  */
103946  #ifndef SQLITE_OMIT_SUBQUERY
103947  static Select *isCandidateForInOpt(Expr *pX){
103948    Select *p;
103949    SrcList *pSrc;
103950    ExprList *pEList;
103951    Table *pTab;
103952    int i;
103953    if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
103954    if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
103955    p = pX->x.pSelect;
103956    if( p->pPrior ) return 0;              /* Not a compound SELECT */
103957    if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
103958      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
103959      testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
103960      return 0; /* No DISTINCT keyword and no aggregate functions */
103961    }
103962    assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
103963    if( p->pLimit ) return 0;              /* Has no LIMIT clause */
103964    if( p->pWhere ) return 0;              /* Has no WHERE clause */
103965    pSrc = p->pSrc;
103966    assert( pSrc!=0 );
103967    if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
103968    if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
103969    pTab = pSrc->a[0].pTab;
103970    assert( pTab!=0 );
103971    assert( pTab->pSelect==0 );            /* FROM clause is not a view */
103972    if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
103973    pEList = p->pEList;
103974    assert( pEList!=0 );
103975    /* All SELECT results must be columns. */
103976    for(i=0; i<pEList->nExpr; i++){
103977      Expr *pRes = pEList->a[i].pExpr;
103978      if( pRes->op!=TK_COLUMN ) return 0;
103979      assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
103980    }
103981    return p;
103982  }
103983  #endif /* SQLITE_OMIT_SUBQUERY */
103984  
103985  #ifndef SQLITE_OMIT_SUBQUERY
103986  /*
103987  ** Generate code that checks the left-most column of index table iCur to see if
103988  ** it contains any NULL entries.  Cause the register at regHasNull to be set
103989  ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
103990  ** to be set to NULL if iCur contains one or more NULL values.
103991  */
103992  static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
103993    int addr1;
103994    sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
103995    addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
103996    sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
103997    sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
103998    VdbeComment((v, "first_entry_in(%d)", iCur));
103999    sqlite3VdbeJumpHere(v, addr1);
104000  }
104001  #endif
104002  
104003  
104004  #ifndef SQLITE_OMIT_SUBQUERY
104005  /*
104006  ** The argument is an IN operator with a list (not a subquery) on the 
104007  ** right-hand side.  Return TRUE if that list is constant.
104008  */
104009  static int sqlite3InRhsIsConstant(Expr *pIn){
104010    Expr *pLHS;
104011    int res;
104012    assert( !ExprHasProperty(pIn, EP_xIsSelect) );
104013    pLHS = pIn->pLeft;
104014    pIn->pLeft = 0;
104015    res = sqlite3ExprIsConstant(pIn);
104016    pIn->pLeft = pLHS;
104017    return res;
104018  }
104019  #endif
104020  
104021  /*
104022  ** This function is used by the implementation of the IN (...) operator.
104023  ** The pX parameter is the expression on the RHS of the IN operator, which
104024  ** might be either a list of expressions or a subquery.
104025  **
104026  ** The job of this routine is to find or create a b-tree object that can
104027  ** be used either to test for membership in the RHS set or to iterate through
104028  ** all members of the RHS set, skipping duplicates.
104029  **
104030  ** A cursor is opened on the b-tree object that is the RHS of the IN operator
104031  ** and pX->iTable is set to the index of that cursor.
104032  **
104033  ** The returned value of this function indicates the b-tree type, as follows:
104034  **
104035  **   IN_INDEX_ROWID      - The cursor was opened on a database table.
104036  **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
104037  **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
104038  **   IN_INDEX_EPH        - The cursor was opened on a specially created and
104039  **                         populated epheremal table.
104040  **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
104041  **                         implemented as a sequence of comparisons.
104042  **
104043  ** An existing b-tree might be used if the RHS expression pX is a simple
104044  ** subquery such as:
104045  **
104046  **     SELECT <column1>, <column2>... FROM <table>
104047  **
104048  ** If the RHS of the IN operator is a list or a more complex subquery, then
104049  ** an ephemeral table might need to be generated from the RHS and then
104050  ** pX->iTable made to point to the ephemeral table instead of an
104051  ** existing table.
104052  **
104053  ** The inFlags parameter must contain, at a minimum, one of the bits
104054  ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both.  If inFlags contains
104055  ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
104056  ** membership test.  When the IN_INDEX_LOOP bit is set, the IN index will
104057  ** be used to loop over all values of the RHS of the IN operator.
104058  **
104059  ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
104060  ** through the set members) then the b-tree must not contain duplicates.
104061  ** An epheremal table will be created unless the selected columns are guaranteed
104062  ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
104063  ** a UNIQUE constraint or index.
104064  **
104065  ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
104066  ** for fast set membership tests) then an epheremal table must 
104067  ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 
104068  ** index can be found with the specified <columns> as its left-most.
104069  **
104070  ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
104071  ** if the RHS of the IN operator is a list (not a subquery) then this
104072  ** routine might decide that creating an ephemeral b-tree for membership
104073  ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
104074  ** calling routine should implement the IN operator using a sequence
104075  ** of Eq or Ne comparison operations.
104076  **
104077  ** When the b-tree is being used for membership tests, the calling function
104078  ** might need to know whether or not the RHS side of the IN operator
104079  ** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
104080  ** if there is any chance that the (...) might contain a NULL value at
104081  ** runtime, then a register is allocated and the register number written
104082  ** to *prRhsHasNull. If there is no chance that the (...) contains a
104083  ** NULL value, then *prRhsHasNull is left unchanged.
104084  **
104085  ** If a register is allocated and its location stored in *prRhsHasNull, then
104086  ** the value in that register will be NULL if the b-tree contains one or more
104087  ** NULL values, and it will be some non-NULL value if the b-tree contains no
104088  ** NULL values.
104089  **
104090  ** If the aiMap parameter is not NULL, it must point to an array containing
104091  ** one element for each column returned by the SELECT statement on the RHS
104092  ** of the IN(...) operator. The i'th entry of the array is populated with the
104093  ** offset of the index column that matches the i'th column returned by the
104094  ** SELECT. For example, if the expression and selected index are:
104095  **
104096  **   (?,?,?) IN (SELECT a, b, c FROM t1)
104097  **   CREATE INDEX i1 ON t1(b, c, a);
104098  **
104099  ** then aiMap[] is populated with {2, 0, 1}.
104100  */
104101  #ifndef SQLITE_OMIT_SUBQUERY
104102  SQLITE_PRIVATE int sqlite3FindInIndex(
104103    Parse *pParse,             /* Parsing context */
104104    Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
104105    u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
104106    int *prRhsHasNull,         /* Register holding NULL status.  See notes */
104107    int *aiMap,                /* Mapping from Index fields to RHS fields */
104108    int *piTab                 /* OUT: index to use */
104109  ){
104110    Select *p;                            /* SELECT to the right of IN operator */
104111    int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
104112    int iTab = pParse->nTab++;            /* Cursor of the RHS table */
104113    int mustBeUnique;                     /* True if RHS must be unique */
104114    Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
104115  
104116    assert( pX->op==TK_IN );
104117    mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
104118  
104119    /* If the RHS of this IN(...) operator is a SELECT, and if it matters 
104120    ** whether or not the SELECT result contains NULL values, check whether
104121    ** or not NULL is actually possible (it may not be, for example, due 
104122    ** to NOT NULL constraints in the schema). If no NULL values are possible,
104123    ** set prRhsHasNull to 0 before continuing.  */
104124    if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
104125      int i;
104126      ExprList *pEList = pX->x.pSelect->pEList;
104127      for(i=0; i<pEList->nExpr; i++){
104128        if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
104129      }
104130      if( i==pEList->nExpr ){
104131        prRhsHasNull = 0;
104132      }
104133    }
104134  
104135    /* Check to see if an existing table or index can be used to
104136    ** satisfy the query.  This is preferable to generating a new 
104137    ** ephemeral table.  */
104138    if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
104139      sqlite3 *db = pParse->db;              /* Database connection */
104140      Table *pTab;                           /* Table <table>. */
104141      i16 iDb;                               /* Database idx for pTab */
104142      ExprList *pEList = p->pEList;
104143      int nExpr = pEList->nExpr;
104144  
104145      assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
104146      assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
104147      assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
104148      pTab = p->pSrc->a[0].pTab;
104149  
104150      /* Code an OP_Transaction and OP_TableLock for <table>. */
104151      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
104152      sqlite3CodeVerifySchema(pParse, iDb);
104153      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
104154  
104155      assert(v);  /* sqlite3GetVdbe() has always been previously called */
104156      if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
104157        /* The "x IN (SELECT rowid FROM table)" case */
104158        int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
104159        VdbeCoverage(v);
104160  
104161        sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
104162        eType = IN_INDEX_ROWID;
104163        ExplainQueryPlan((pParse, 0,
104164              "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
104165        sqlite3VdbeJumpHere(v, iAddr);
104166      }else{
104167        Index *pIdx;                         /* Iterator variable */
104168        int affinity_ok = 1;
104169        int i;
104170  
104171        /* Check that the affinity that will be used to perform each 
104172        ** comparison is the same as the affinity of each column in table
104173        ** on the RHS of the IN operator.  If it not, it is not possible to
104174        ** use any index of the RHS table.  */
104175        for(i=0; i<nExpr && affinity_ok; i++){
104176          Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
104177          int iCol = pEList->a[i].pExpr->iColumn;
104178          char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
104179          char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
104180          testcase( cmpaff==SQLITE_AFF_BLOB );
104181          testcase( cmpaff==SQLITE_AFF_TEXT );
104182          switch( cmpaff ){
104183            case SQLITE_AFF_BLOB:
104184              break;
104185            case SQLITE_AFF_TEXT:
104186              /* sqlite3CompareAffinity() only returns TEXT if one side or the
104187              ** other has no affinity and the other side is TEXT.  Hence,
104188              ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
104189              ** and for the term on the LHS of the IN to have no affinity. */
104190              assert( idxaff==SQLITE_AFF_TEXT );
104191              break;
104192            default:
104193              affinity_ok = sqlite3IsNumericAffinity(idxaff);
104194          }
104195        }
104196  
104197        if( affinity_ok ){
104198          /* Search for an existing index that will work for this IN operator */
104199          for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
104200            Bitmask colUsed;      /* Columns of the index used */
104201            Bitmask mCol;         /* Mask for the current column */
104202            if( pIdx->nColumn<nExpr ) continue;
104203            if( pIdx->pPartIdxWhere!=0 ) continue;
104204            /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
104205            ** BITMASK(nExpr) without overflowing */
104206            testcase( pIdx->nColumn==BMS-2 );
104207            testcase( pIdx->nColumn==BMS-1 );
104208            if( pIdx->nColumn>=BMS-1 ) continue;
104209            if( mustBeUnique ){
104210              if( pIdx->nKeyCol>nExpr
104211               ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
104212              ){
104213                continue;  /* This index is not unique over the IN RHS columns */
104214              }
104215            }
104216    
104217            colUsed = 0;   /* Columns of index used so far */
104218            for(i=0; i<nExpr; i++){
104219              Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
104220              Expr *pRhs = pEList->a[i].pExpr;
104221              CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
104222              int j;
104223    
104224              assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
104225              for(j=0; j<nExpr; j++){
104226                if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
104227                assert( pIdx->azColl[j] );
104228                if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
104229                  continue;
104230                }
104231                break;
104232              }
104233              if( j==nExpr ) break;
104234              mCol = MASKBIT(j);
104235              if( mCol & colUsed ) break; /* Each column used only once */
104236              colUsed |= mCol;
104237              if( aiMap ) aiMap[i] = j;
104238            }
104239    
104240            assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
104241            if( colUsed==(MASKBIT(nExpr)-1) ){
104242              /* If we reach this point, that means the index pIdx is usable */
104243              int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
104244              ExplainQueryPlan((pParse, 0,
104245                                "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
104246              sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
104247              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
104248              VdbeComment((v, "%s", pIdx->zName));
104249              assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
104250              eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
104251    
104252              if( prRhsHasNull ){
104253  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
104254                i64 mask = (1<<nExpr)-1;
104255                sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 
104256                    iTab, 0, 0, (u8*)&mask, P4_INT64);
104257  #endif
104258                *prRhsHasNull = ++pParse->nMem;
104259                if( nExpr==1 ){
104260                  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
104261                }
104262              }
104263              sqlite3VdbeJumpHere(v, iAddr);
104264            }
104265          } /* End loop over indexes */
104266        } /* End if( affinity_ok ) */
104267      } /* End if not an rowid index */
104268    } /* End attempt to optimize using an index */
104269  
104270    /* If no preexisting index is available for the IN clause
104271    ** and IN_INDEX_NOOP is an allowed reply
104272    ** and the RHS of the IN operator is a list, not a subquery
104273    ** and the RHS is not constant or has two or fewer terms,
104274    ** then it is not worth creating an ephemeral table to evaluate
104275    ** the IN operator so return IN_INDEX_NOOP.
104276    */
104277    if( eType==0
104278     && (inFlags & IN_INDEX_NOOP_OK)
104279     && !ExprHasProperty(pX, EP_xIsSelect)
104280     && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
104281    ){
104282      eType = IN_INDEX_NOOP;
104283    }
104284  
104285    if( eType==0 ){
104286      /* Could not find an existing table or index to use as the RHS b-tree.
104287      ** We will have to generate an ephemeral table to do the job.
104288      */
104289      u32 savedNQueryLoop = pParse->nQueryLoop;
104290      int rMayHaveNull = 0;
104291      eType = IN_INDEX_EPH;
104292      if( inFlags & IN_INDEX_LOOP ){
104293        pParse->nQueryLoop = 0;
104294      }else if( prRhsHasNull ){
104295        *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
104296      }
104297      assert( pX->op==TK_IN );
104298      sqlite3CodeRhsOfIN(pParse, pX, iTab);
104299      if( rMayHaveNull ){
104300        sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
104301      }
104302      pParse->nQueryLoop = savedNQueryLoop;
104303    }
104304  
104305    if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
104306      int i, n;
104307      n = sqlite3ExprVectorSize(pX->pLeft);
104308      for(i=0; i<n; i++) aiMap[i] = i;
104309    }
104310    *piTab = iTab;
104311    return eType;
104312  }
104313  #endif
104314  
104315  #ifndef SQLITE_OMIT_SUBQUERY
104316  /*
104317  ** Argument pExpr is an (?, ?...) IN(...) expression. This 
104318  ** function allocates and returns a nul-terminated string containing 
104319  ** the affinities to be used for each column of the comparison.
104320  **
104321  ** It is the responsibility of the caller to ensure that the returned
104322  ** string is eventually freed using sqlite3DbFree().
104323  */
104324  static char *exprINAffinity(Parse *pParse, Expr *pExpr){
104325    Expr *pLeft = pExpr->pLeft;
104326    int nVal = sqlite3ExprVectorSize(pLeft);
104327    Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
104328    char *zRet;
104329  
104330    assert( pExpr->op==TK_IN );
104331    zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
104332    if( zRet ){
104333      int i;
104334      for(i=0; i<nVal; i++){
104335        Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
104336        char a = sqlite3ExprAffinity(pA);
104337        if( pSelect ){
104338          zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
104339        }else{
104340          zRet[i] = a;
104341        }
104342      }
104343      zRet[nVal] = '\0';
104344    }
104345    return zRet;
104346  }
104347  #endif
104348  
104349  #ifndef SQLITE_OMIT_SUBQUERY
104350  /*
104351  ** Load the Parse object passed as the first argument with an error 
104352  ** message of the form:
104353  **
104354  **   "sub-select returns N columns - expected M"
104355  */   
104356  SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
104357    const char *zFmt = "sub-select returns %d columns - expected %d";
104358    sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
104359  }
104360  #endif
104361  
104362  /*
104363  ** Expression pExpr is a vector that has been used in a context where
104364  ** it is not permitted. If pExpr is a sub-select vector, this routine 
104365  ** loads the Parse object with a message of the form:
104366  **
104367  **   "sub-select returns N columns - expected 1"
104368  **
104369  ** Or, if it is a regular scalar vector:
104370  **
104371  **   "row value misused"
104372  */   
104373  SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
104374  #ifndef SQLITE_OMIT_SUBQUERY
104375    if( pExpr->flags & EP_xIsSelect ){
104376      sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
104377    }else
104378  #endif
104379    {
104380      sqlite3ErrorMsg(pParse, "row value misused");
104381    }
104382  }
104383  
104384  #ifndef SQLITE_OMIT_SUBQUERY
104385  /*
104386  ** Generate code that will construct an ephemeral table containing all terms
104387  ** in the RHS of an IN operator.  The IN operator can be in either of two
104388  ** forms:
104389  **
104390  **     x IN (4,5,11)              -- IN operator with list on right-hand side
104391  **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
104392  **
104393  ** The pExpr parameter is the IN operator.  The cursor number for the
104394  ** constructed ephermeral table is returned.  The first time the ephemeral
104395  ** table is computed, the cursor number is also stored in pExpr->iTable,
104396  ** however the cursor number returned might not be the same, as it might
104397  ** have been duplicated using OP_OpenDup.
104398  **
104399  ** If the LHS expression ("x" in the examples) is a column value, or
104400  ** the SELECT statement returns a column value, then the affinity of that
104401  ** column is used to build the index keys. If both 'x' and the
104402  ** SELECT... statement are columns, then numeric affinity is used
104403  ** if either column has NUMERIC or INTEGER affinity. If neither
104404  ** 'x' nor the SELECT... statement are columns, then numeric affinity
104405  ** is used.
104406  */
104407  SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
104408    Parse *pParse,          /* Parsing context */
104409    Expr *pExpr,            /* The IN operator */
104410    int iTab                /* Use this cursor number */
104411  ){
104412    int addrOnce = 0;           /* Address of the OP_Once instruction at top */
104413    int addr;                   /* Address of OP_OpenEphemeral instruction */
104414    Expr *pLeft;                /* the LHS of the IN operator */
104415    KeyInfo *pKeyInfo = 0;      /* Key information */
104416    int nVal;                   /* Size of vector pLeft */
104417    Vdbe *v;                    /* The prepared statement under construction */
104418  
104419    v = pParse->pVdbe;
104420    assert( v!=0 );
104421  
104422    /* The evaluation of the IN must be repeated every time it
104423    ** is encountered if any of the following is true:
104424    **
104425    **    *  The right-hand side is a correlated subquery
104426    **    *  The right-hand side is an expression list containing variables
104427    **    *  We are inside a trigger
104428    **
104429    ** If all of the above are false, then we can compute the RHS just once
104430    ** and reuse it many names.
104431    */
104432    if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
104433      /* Reuse of the RHS is allowed */
104434      /* If this routine has already been coded, but the previous code
104435      ** might not have been invoked yet, so invoke it now as a subroutine. 
104436      */
104437      if( ExprHasProperty(pExpr, EP_Subrtn) ){
104438        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
104439        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104440          ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
104441                pExpr->x.pSelect->selId));
104442        }
104443        sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
104444                          pExpr->y.sub.iAddr);
104445        sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
104446        sqlite3VdbeJumpHere(v, addrOnce);
104447        return;
104448      }
104449  
104450      /* Begin coding the subroutine */
104451      ExprSetProperty(pExpr, EP_Subrtn);
104452      pExpr->y.sub.regReturn = ++pParse->nMem;
104453      pExpr->y.sub.iAddr =
104454        sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
104455      VdbeComment((v, "return address"));
104456  
104457      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
104458    }
104459  
104460    /* Check to see if this is a vector IN operator */
104461    pLeft = pExpr->pLeft;
104462    nVal = sqlite3ExprVectorSize(pLeft);
104463  
104464    /* Construct the ephemeral table that will contain the content of
104465    ** RHS of the IN operator.
104466    */
104467    pExpr->iTable = iTab;
104468    addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
104469  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
104470    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104471      VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
104472    }else{
104473      VdbeComment((v, "RHS of IN operator"));
104474    }
104475  #endif
104476    pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
104477  
104478    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
104479      /* Case 1:     expr IN (SELECT ...)
104480      **
104481      ** Generate code to write the results of the select into the temporary
104482      ** table allocated and opened above.
104483      */
104484      Select *pSelect = pExpr->x.pSelect;
104485      ExprList *pEList = pSelect->pEList;
104486  
104487      ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
104488          addrOnce?"":"CORRELATED ", pSelect->selId
104489      ));
104490      /* If the LHS and RHS of the IN operator do not match, that
104491      ** error will have been caught long before we reach this point. */
104492      if( ALWAYS(pEList->nExpr==nVal) ){
104493        SelectDest dest;
104494        int i;
104495        sqlite3SelectDestInit(&dest, SRT_Set, iTab);
104496        dest.zAffSdst = exprINAffinity(pParse, pExpr);
104497        pSelect->iLimit = 0;
104498        testcase( pSelect->selFlags & SF_Distinct );
104499        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
104500        if( sqlite3Select(pParse, pSelect, &dest) ){
104501          sqlite3DbFree(pParse->db, dest.zAffSdst);
104502          sqlite3KeyInfoUnref(pKeyInfo);
104503          return;
104504        }
104505        sqlite3DbFree(pParse->db, dest.zAffSdst);
104506        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
104507        assert( pEList!=0 );
104508        assert( pEList->nExpr>0 );
104509        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
104510        for(i=0; i<nVal; i++){
104511          Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
104512          pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
104513              pParse, p, pEList->a[i].pExpr
104514          );
104515        }
104516      }
104517    }else if( ALWAYS(pExpr->x.pList!=0) ){
104518      /* Case 2:     expr IN (exprlist)
104519      **
104520      ** For each expression, build an index key from the evaluation and
104521      ** store it in the temporary table. If <expr> is a column, then use
104522      ** that columns affinity when building index keys. If <expr> is not
104523      ** a column, use numeric affinity.
104524      */
104525      char affinity;            /* Affinity of the LHS of the IN */
104526      int i;
104527      ExprList *pList = pExpr->x.pList;
104528      struct ExprList_item *pItem;
104529      int r1, r2, r3;
104530      affinity = sqlite3ExprAffinity(pLeft);
104531      if( !affinity ){
104532        affinity = SQLITE_AFF_BLOB;
104533      }
104534      if( pKeyInfo ){
104535        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
104536        pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
104537      }
104538  
104539      /* Loop through each expression in <exprlist>. */
104540      r1 = sqlite3GetTempReg(pParse);
104541      r2 = sqlite3GetTempReg(pParse);
104542      for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
104543        Expr *pE2 = pItem->pExpr;
104544  
104545        /* If the expression is not constant then we will need to
104546        ** disable the test that was generated above that makes sure
104547        ** this code only executes once.  Because for a non-constant
104548        ** expression we need to rerun this code each time.
104549        */
104550        if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
104551          sqlite3VdbeChangeToNoop(v, addrOnce);
104552          addrOnce = 0;
104553        }
104554  
104555        /* Evaluate the expression and insert it into the temp table */
104556        r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
104557        sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
104558        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r3, 1);
104559      }
104560      sqlite3ReleaseTempReg(pParse, r1);
104561      sqlite3ReleaseTempReg(pParse, r2);
104562    }
104563    if( pKeyInfo ){
104564      sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
104565    }
104566    if( addrOnce ){
104567      sqlite3VdbeJumpHere(v, addrOnce);
104568      /* Subroutine return */
104569      sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
104570      sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
104571    }
104572  }
104573  #endif /* SQLITE_OMIT_SUBQUERY */
104574  
104575  /*
104576  ** Generate code for scalar subqueries used as a subquery expression
104577  ** or EXISTS operator:
104578  **
104579  **     (SELECT a FROM b)          -- subquery
104580  **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
104581  **
104582  ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
104583  **
104584  ** The register that holds the result.  For a multi-column SELECT, 
104585  ** the result is stored in a contiguous array of registers and the
104586  ** return value is the register of the left-most result column.
104587  ** Return 0 if an error occurs.
104588  */
104589  #ifndef SQLITE_OMIT_SUBQUERY
104590  SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
104591    int addrOnce = 0;           /* Address of OP_Once at top of subroutine */
104592    int rReg = 0;               /* Register storing resulting */
104593    Select *pSel;               /* SELECT statement to encode */
104594    SelectDest dest;            /* How to deal with SELECT result */
104595    int nReg;                   /* Registers to allocate */
104596    Expr *pLimit;               /* New limit expression */
104597  
104598    Vdbe *v = pParse->pVdbe;
104599    assert( v!=0 );
104600    testcase( pExpr->op==TK_EXISTS );
104601    testcase( pExpr->op==TK_SELECT );
104602    assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
104603    assert( ExprHasProperty(pExpr, EP_xIsSelect) );
104604    pSel = pExpr->x.pSelect;
104605  
104606    /* The evaluation of the EXISTS/SELECT must be repeated every time it
104607    ** is encountered if any of the following is true:
104608    **
104609    **    *  The right-hand side is a correlated subquery
104610    **    *  The right-hand side is an expression list containing variables
104611    **    *  We are inside a trigger
104612    **
104613    ** If all of the above are false, then we can run this code just once
104614    ** save the results, and reuse the same result on subsequent invocations.
104615    */
104616    if( !ExprHasProperty(pExpr, EP_VarSelect) ){
104617      /* If this routine has already been coded, then invoke it as a
104618      ** subroutine. */
104619      if( ExprHasProperty(pExpr, EP_Subrtn) ){
104620        ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
104621        sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
104622                          pExpr->y.sub.iAddr);
104623        return pExpr->iTable;
104624      }
104625  
104626      /* Begin coding the subroutine */
104627      ExprSetProperty(pExpr, EP_Subrtn);
104628      pExpr->y.sub.regReturn = ++pParse->nMem;
104629      pExpr->y.sub.iAddr =
104630        sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
104631      VdbeComment((v, "return address"));
104632  
104633      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
104634    }
104635    
104636    /* For a SELECT, generate code to put the values for all columns of
104637    ** the first row into an array of registers and return the index of
104638    ** the first register.
104639    **
104640    ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
104641    ** into a register and return that register number.
104642    **
104643    ** In both cases, the query is augmented with "LIMIT 1".  Any 
104644    ** preexisting limit is discarded in place of the new LIMIT 1.
104645    */
104646    ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
104647          addrOnce?"":"CORRELATED ", pSel->selId));
104648    nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
104649    sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
104650    pParse->nMem += nReg;
104651    if( pExpr->op==TK_SELECT ){
104652      dest.eDest = SRT_Mem;
104653      dest.iSdst = dest.iSDParm;
104654      dest.nSdst = nReg;
104655      sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
104656      VdbeComment((v, "Init subquery result"));
104657    }else{
104658      dest.eDest = SRT_Exists;
104659      sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
104660      VdbeComment((v, "Init EXISTS result"));
104661    }
104662    pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
104663    if( pSel->pLimit ){
104664      sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
104665      pSel->pLimit->pLeft = pLimit;
104666    }else{
104667      pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
104668    }
104669    pSel->iLimit = 0;
104670    if( sqlite3Select(pParse, pSel, &dest) ){
104671      return 0;
104672    }
104673    pExpr->iTable = rReg = dest.iSDParm;
104674    ExprSetVVAProperty(pExpr, EP_NoReduce);
104675    if( addrOnce ){
104676      sqlite3VdbeJumpHere(v, addrOnce);
104677  
104678      /* Subroutine return */
104679      sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
104680      sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
104681    }
104682  
104683    return rReg;
104684  }
104685  #endif /* SQLITE_OMIT_SUBQUERY */
104686  
104687  #ifndef SQLITE_OMIT_SUBQUERY
104688  /*
104689  ** Expr pIn is an IN(...) expression. This function checks that the 
104690  ** sub-select on the RHS of the IN() operator has the same number of 
104691  ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 
104692  ** a sub-query, that the LHS is a vector of size 1.
104693  */
104694  SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
104695    int nVector = sqlite3ExprVectorSize(pIn->pLeft);
104696    if( (pIn->flags & EP_xIsSelect) ){
104697      if( nVector!=pIn->x.pSelect->pEList->nExpr ){
104698        sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
104699        return 1;
104700      }
104701    }else if( nVector!=1 ){
104702      sqlite3VectorErrorMsg(pParse, pIn->pLeft);
104703      return 1;
104704    }
104705    return 0;
104706  }
104707  #endif
104708  
104709  #ifndef SQLITE_OMIT_SUBQUERY
104710  /*
104711  ** Generate code for an IN expression.
104712  **
104713  **      x IN (SELECT ...)
104714  **      x IN (value, value, ...)
104715  **
104716  ** The left-hand side (LHS) is a scalar or vector expression.  The 
104717  ** right-hand side (RHS) is an array of zero or more scalar values, or a
104718  ** subquery.  If the RHS is a subquery, the number of result columns must
104719  ** match the number of columns in the vector on the LHS.  If the RHS is
104720  ** a list of values, the LHS must be a scalar. 
104721  **
104722  ** The IN operator is true if the LHS value is contained within the RHS.
104723  ** The result is false if the LHS is definitely not in the RHS.  The 
104724  ** result is NULL if the presence of the LHS in the RHS cannot be 
104725  ** determined due to NULLs.
104726  **
104727  ** This routine generates code that jumps to destIfFalse if the LHS is not 
104728  ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
104729  ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
104730  ** within the RHS then fall through.
104731  **
104732  ** See the separate in-operator.md documentation file in the canonical
104733  ** SQLite source tree for additional information.
104734  */
104735  static void sqlite3ExprCodeIN(
104736    Parse *pParse,        /* Parsing and code generating context */
104737    Expr *pExpr,          /* The IN expression */
104738    int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
104739    int destIfNull        /* Jump here if the results are unknown due to NULLs */
104740  ){
104741    int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
104742    int eType;            /* Type of the RHS */
104743    int rLhs;             /* Register(s) holding the LHS values */
104744    int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
104745    Vdbe *v;              /* Statement under construction */
104746    int *aiMap = 0;       /* Map from vector field to index column */
104747    char *zAff = 0;       /* Affinity string for comparisons */
104748    int nVector;          /* Size of vectors for this IN operator */
104749    int iDummy;           /* Dummy parameter to exprCodeVector() */
104750    Expr *pLeft;          /* The LHS of the IN operator */
104751    int i;                /* loop counter */
104752    int destStep2;        /* Where to jump when NULLs seen in step 2 */
104753    int destStep6 = 0;    /* Start of code for Step 6 */
104754    int addrTruthOp;      /* Address of opcode that determines the IN is true */
104755    int destNotNull;      /* Jump here if a comparison is not true in step 6 */
104756    int addrTop;          /* Top of the step-6 loop */ 
104757    int iTab = 0;         /* Index to use */
104758  
104759    pLeft = pExpr->pLeft;
104760    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
104761    zAff = exprINAffinity(pParse, pExpr);
104762    nVector = sqlite3ExprVectorSize(pExpr->pLeft);
104763    aiMap = (int*)sqlite3DbMallocZero(
104764        pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
104765    );
104766    if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
104767  
104768    /* Attempt to compute the RHS. After this step, if anything other than
104769    ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
104770    ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
104771    ** the RHS has not yet been coded.  */
104772    v = pParse->pVdbe;
104773    assert( v!=0 );       /* OOM detected prior to this routine */
104774    VdbeNoopComment((v, "begin IN expr"));
104775    eType = sqlite3FindInIndex(pParse, pExpr,
104776                               IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
104777                               destIfFalse==destIfNull ? 0 : &rRhsHasNull,
104778                               aiMap, &iTab);
104779  
104780    assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
104781         || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 
104782    );
104783  #ifdef SQLITE_DEBUG
104784    /* Confirm that aiMap[] contains nVector integer values between 0 and
104785    ** nVector-1. */
104786    for(i=0; i<nVector; i++){
104787      int j, cnt;
104788      for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
104789      assert( cnt==1 );
104790    }
104791  #endif
104792  
104793    /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 
104794    ** vector, then it is stored in an array of nVector registers starting 
104795    ** at r1.
104796    **
104797    ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
104798    ** so that the fields are in the same order as an existing index.   The
104799    ** aiMap[] array contains a mapping from the original LHS field order to
104800    ** the field order that matches the RHS index.
104801    */
104802    rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
104803    for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
104804    if( i==nVector ){
104805      /* LHS fields are not reordered */
104806      rLhs = rLhsOrig;
104807    }else{
104808      /* Need to reorder the LHS fields according to aiMap */
104809      rLhs = sqlite3GetTempRange(pParse, nVector);
104810      for(i=0; i<nVector; i++){
104811        sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
104812      }
104813    }
104814  
104815    /* If sqlite3FindInIndex() did not find or create an index that is
104816    ** suitable for evaluating the IN operator, then evaluate using a
104817    ** sequence of comparisons.
104818    **
104819    ** This is step (1) in the in-operator.md optimized algorithm.
104820    */
104821    if( eType==IN_INDEX_NOOP ){
104822      ExprList *pList = pExpr->x.pList;
104823      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
104824      int labelOk = sqlite3VdbeMakeLabel(pParse);
104825      int r2, regToFree;
104826      int regCkNull = 0;
104827      int ii;
104828      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
104829      if( destIfNull!=destIfFalse ){
104830        regCkNull = sqlite3GetTempReg(pParse);
104831        sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
104832      }
104833      for(ii=0; ii<pList->nExpr; ii++){
104834        r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
104835        if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
104836          sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
104837        }
104838        if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
104839          sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
104840                            (void*)pColl, P4_COLLSEQ);
104841          VdbeCoverageIf(v, ii<pList->nExpr-1);
104842          VdbeCoverageIf(v, ii==pList->nExpr-1);
104843          sqlite3VdbeChangeP5(v, zAff[0]);
104844        }else{
104845          assert( destIfNull==destIfFalse );
104846          sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
104847                            (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
104848          sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
104849        }
104850        sqlite3ReleaseTempReg(pParse, regToFree);
104851      }
104852      if( regCkNull ){
104853        sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
104854        sqlite3VdbeGoto(v, destIfFalse);
104855      }
104856      sqlite3VdbeResolveLabel(v, labelOk);
104857      sqlite3ReleaseTempReg(pParse, regCkNull);
104858      goto sqlite3ExprCodeIN_finished;
104859    }
104860  
104861    /* Step 2: Check to see if the LHS contains any NULL columns.  If the
104862    ** LHS does contain NULLs then the result must be either FALSE or NULL.
104863    ** We will then skip the binary search of the RHS.
104864    */
104865    if( destIfNull==destIfFalse ){
104866      destStep2 = destIfFalse;
104867    }else{
104868      destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
104869    }
104870    for(i=0; i<nVector; i++){
104871      Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
104872      if( sqlite3ExprCanBeNull(p) ){
104873        sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
104874        VdbeCoverage(v);
104875      }
104876    }
104877  
104878    /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
104879    ** of the RHS using the LHS as a probe.  If found, the result is
104880    ** true.
104881    */
104882    if( eType==IN_INDEX_ROWID ){
104883      /* In this case, the RHS is the ROWID of table b-tree and so we also
104884      ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
104885      ** into a single opcode. */
104886      sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
104887      VdbeCoverage(v);
104888      addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
104889    }else{
104890      sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
104891      if( destIfFalse==destIfNull ){
104892        /* Combine Step 3 and Step 5 into a single opcode */
104893        sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
104894                             rLhs, nVector); VdbeCoverage(v);
104895        goto sqlite3ExprCodeIN_finished;
104896      }
104897      /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
104898      addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
104899                                        rLhs, nVector); VdbeCoverage(v);
104900    }
104901  
104902    /* Step 4.  If the RHS is known to be non-NULL and we did not find
104903    ** an match on the search above, then the result must be FALSE.
104904    */
104905    if( rRhsHasNull && nVector==1 ){
104906      sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
104907      VdbeCoverage(v);
104908    }
104909  
104910    /* Step 5.  If we do not care about the difference between NULL and
104911    ** FALSE, then just return false. 
104912    */
104913    if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
104914  
104915    /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
104916    ** If any comparison is NULL, then the result is NULL.  If all
104917    ** comparisons are FALSE then the final result is FALSE.
104918    **
104919    ** For a scalar LHS, it is sufficient to check just the first row
104920    ** of the RHS.
104921    */
104922    if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
104923    addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
104924    VdbeCoverage(v);
104925    if( nVector>1 ){
104926      destNotNull = sqlite3VdbeMakeLabel(pParse);
104927    }else{
104928      /* For nVector==1, combine steps 6 and 7 by immediately returning
104929      ** FALSE if the first comparison is not NULL */
104930      destNotNull = destIfFalse;
104931    }
104932    for(i=0; i<nVector; i++){
104933      Expr *p;
104934      CollSeq *pColl;
104935      int r3 = sqlite3GetTempReg(pParse);
104936      p = sqlite3VectorFieldSubexpr(pLeft, i);
104937      pColl = sqlite3ExprCollSeq(pParse, p);
104938      sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
104939      sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
104940                        (void*)pColl, P4_COLLSEQ);
104941      VdbeCoverage(v);
104942      sqlite3ReleaseTempReg(pParse, r3);
104943    }
104944    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
104945    if( nVector>1 ){
104946      sqlite3VdbeResolveLabel(v, destNotNull);
104947      sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
104948      VdbeCoverage(v);
104949  
104950      /* Step 7:  If we reach this point, we know that the result must
104951      ** be false. */
104952      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
104953    }
104954  
104955    /* Jumps here in order to return true. */
104956    sqlite3VdbeJumpHere(v, addrTruthOp);
104957  
104958  sqlite3ExprCodeIN_finished:
104959    if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
104960    VdbeComment((v, "end IN expr"));
104961  sqlite3ExprCodeIN_oom_error:
104962    sqlite3DbFree(pParse->db, aiMap);
104963    sqlite3DbFree(pParse->db, zAff);
104964  }
104965  #endif /* SQLITE_OMIT_SUBQUERY */
104966  
104967  #ifndef SQLITE_OMIT_FLOATING_POINT
104968  /*
104969  ** Generate an instruction that will put the floating point
104970  ** value described by z[0..n-1] into register iMem.
104971  **
104972  ** The z[] string will probably not be zero-terminated.  But the 
104973  ** z[n] character is guaranteed to be something that does not look
104974  ** like the continuation of the number.
104975  */
104976  static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
104977    if( ALWAYS(z!=0) ){
104978      double value;
104979      sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
104980      assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
104981      if( negateFlag ) value = -value;
104982      sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
104983    }
104984  }
104985  #endif
104986  
104987  
104988  /*
104989  ** Generate an instruction that will put the integer describe by
104990  ** text z[0..n-1] into register iMem.
104991  **
104992  ** Expr.u.zToken is always UTF8 and zero-terminated.
104993  */
104994  static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
104995    Vdbe *v = pParse->pVdbe;
104996    if( pExpr->flags & EP_IntValue ){
104997      int i = pExpr->u.iValue;
104998      assert( i>=0 );
104999      if( negFlag ) i = -i;
105000      sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
105001    }else{
105002      int c;
105003      i64 value;
105004      const char *z = pExpr->u.zToken;
105005      assert( z!=0 );
105006      c = sqlite3DecOrHexToI64(z, &value);
105007      if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
105008  #ifdef SQLITE_OMIT_FLOATING_POINT
105009        sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
105010  #else
105011  #ifndef SQLITE_OMIT_HEX_INTEGER
105012        if( sqlite3_strnicmp(z,"0x",2)==0 ){
105013          sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
105014        }else
105015  #endif
105016        {
105017          codeReal(v, z, negFlag, iMem);
105018        }
105019  #endif
105020      }else{
105021        if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
105022        sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
105023      }
105024    }
105025  }
105026  
105027  
105028  /* Generate code that will load into register regOut a value that is
105029  ** appropriate for the iIdxCol-th column of index pIdx.
105030  */
105031  SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
105032    Parse *pParse,  /* The parsing context */
105033    Index *pIdx,    /* The index whose column is to be loaded */
105034    int iTabCur,    /* Cursor pointing to a table row */
105035    int iIdxCol,    /* The column of the index to be loaded */
105036    int regOut      /* Store the index column value in this register */
105037  ){
105038    i16 iTabCol = pIdx->aiColumn[iIdxCol];
105039    if( iTabCol==XN_EXPR ){
105040      assert( pIdx->aColExpr );
105041      assert( pIdx->aColExpr->nExpr>iIdxCol );
105042      pParse->iSelfTab = iTabCur + 1;
105043      sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
105044      pParse->iSelfTab = 0;
105045    }else{
105046      sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
105047                                      iTabCol, regOut);
105048    }
105049  }
105050  
105051  /*
105052  ** Generate code to extract the value of the iCol-th column of a table.
105053  */
105054  SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
105055    Vdbe *v,        /* The VDBE under construction */
105056    Table *pTab,    /* The table containing the value */
105057    int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
105058    int iCol,       /* Index of the column to extract */
105059    int regOut      /* Extract the value into this register */
105060  ){
105061    if( pTab==0 ){
105062      sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
105063      return;
105064    }
105065    if( iCol<0 || iCol==pTab->iPKey ){
105066      sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
105067    }else{
105068      int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
105069      int x = iCol;
105070      if( !HasRowid(pTab) && !IsVirtual(pTab) ){
105071        x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
105072      }
105073      sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
105074    }
105075    if( iCol>=0 ){
105076      sqlite3ColumnDefault(v, pTab, iCol, regOut);
105077    }
105078  }
105079  
105080  /*
105081  ** Generate code that will extract the iColumn-th column from
105082  ** table pTab and store the column value in register iReg. 
105083  **
105084  ** There must be an open cursor to pTab in iTable when this routine
105085  ** is called.  If iColumn<0 then code is generated that extracts the rowid.
105086  */
105087  SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
105088    Parse *pParse,   /* Parsing and code generating context */
105089    Table *pTab,     /* Description of the table we are reading from */
105090    int iColumn,     /* Index of the table column */
105091    int iTable,      /* The cursor pointing to the table */
105092    int iReg,        /* Store results here */
105093    u8 p5            /* P5 value for OP_Column + FLAGS */
105094  ){
105095    Vdbe *v = pParse->pVdbe;
105096    assert( v!=0 );
105097    sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
105098    if( p5 ){
105099      sqlite3VdbeChangeP5(v, p5);
105100    }
105101    return iReg;
105102  }
105103  
105104  /*
105105  ** Generate code to move content from registers iFrom...iFrom+nReg-1
105106  ** over to iTo..iTo+nReg-1.
105107  */
105108  SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
105109    assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
105110    sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
105111  }
105112  
105113  /*
105114  ** Convert a scalar expression node to a TK_REGISTER referencing
105115  ** register iReg.  The caller must ensure that iReg already contains
105116  ** the correct value for the expression.
105117  */
105118  static void exprToRegister(Expr *p, int iReg){
105119    p->op2 = p->op;
105120    p->op = TK_REGISTER;
105121    p->iTable = iReg;
105122    ExprClearProperty(p, EP_Skip);
105123  }
105124  
105125  /*
105126  ** Evaluate an expression (either a vector or a scalar expression) and store
105127  ** the result in continguous temporary registers.  Return the index of
105128  ** the first register used to store the result.
105129  **
105130  ** If the returned result register is a temporary scalar, then also write
105131  ** that register number into *piFreeable.  If the returned result register
105132  ** is not a temporary or if the expression is a vector set *piFreeable
105133  ** to 0.
105134  */
105135  static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
105136    int iResult;
105137    int nResult = sqlite3ExprVectorSize(p);
105138    if( nResult==1 ){
105139      iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
105140    }else{
105141      *piFreeable = 0;
105142      if( p->op==TK_SELECT ){
105143  #if SQLITE_OMIT_SUBQUERY
105144        iResult = 0;
105145  #else
105146        iResult = sqlite3CodeSubselect(pParse, p);
105147  #endif
105148      }else{
105149        int i;
105150        iResult = pParse->nMem+1;
105151        pParse->nMem += nResult;
105152        for(i=0; i<nResult; i++){
105153          sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
105154        }
105155      }
105156    }
105157    return iResult;
105158  }
105159  
105160  
105161  /*
105162  ** Generate code into the current Vdbe to evaluate the given
105163  ** expression.  Attempt to store the results in register "target".
105164  ** Return the register where results are stored.
105165  **
105166  ** With this routine, there is no guarantee that results will
105167  ** be stored in target.  The result might be stored in some other
105168  ** register if it is convenient to do so.  The calling function
105169  ** must check the return code and move the results to the desired
105170  ** register.
105171  */
105172  SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
105173    Vdbe *v = pParse->pVdbe;  /* The VM under construction */
105174    int op;                   /* The opcode being coded */
105175    int inReg = target;       /* Results stored in register inReg */
105176    int regFree1 = 0;         /* If non-zero free this temporary register */
105177    int regFree2 = 0;         /* If non-zero free this temporary register */
105178    int r1, r2;               /* Various register numbers */
105179    Expr tempX;               /* Temporary expression node */
105180    int p5 = 0;
105181  
105182    assert( target>0 && target<=pParse->nMem );
105183    if( v==0 ){
105184      assert( pParse->db->mallocFailed );
105185      return 0;
105186    }
105187  
105188  expr_code_doover:
105189    if( pExpr==0 ){
105190      op = TK_NULL;
105191    }else{
105192      op = pExpr->op;
105193    }
105194    switch( op ){
105195      case TK_AGG_COLUMN: {
105196        AggInfo *pAggInfo = pExpr->pAggInfo;
105197        struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
105198        if( !pAggInfo->directMode ){
105199          assert( pCol->iMem>0 );
105200          return pCol->iMem;
105201        }else if( pAggInfo->useSortingIdx ){
105202          sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
105203                                pCol->iSorterColumn, target);
105204          return target;
105205        }
105206        /* Otherwise, fall thru into the TK_COLUMN case */
105207      }
105208      case TK_COLUMN: {
105209        int iTab = pExpr->iTable;
105210        if( ExprHasProperty(pExpr, EP_FixedCol) ){
105211          /* This COLUMN expression is really a constant due to WHERE clause
105212          ** constraints, and that constant is coded by the pExpr->pLeft
105213          ** expresssion.  However, make sure the constant has the correct
105214          ** datatype by applying the Affinity of the table column to the
105215          ** constant.
105216          */
105217          int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
105218          int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
105219          if( aff!=SQLITE_AFF_BLOB ){
105220            static const char zAff[] = "B\000C\000D\000E";
105221            assert( SQLITE_AFF_BLOB=='A' );
105222            assert( SQLITE_AFF_TEXT=='B' );
105223            if( iReg!=target ){
105224              sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
105225              iReg = target;
105226            }
105227            sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
105228                              &zAff[(aff-'B')*2], P4_STATIC);
105229          }
105230          return iReg;
105231        }
105232        if( iTab<0 ){
105233          if( pParse->iSelfTab<0 ){
105234            /* Generating CHECK constraints or inserting into partial index */
105235            return pExpr->iColumn - pParse->iSelfTab;
105236          }else{
105237            /* Coding an expression that is part of an index where column names
105238            ** in the index refer to the table to which the index belongs */
105239            iTab = pParse->iSelfTab - 1;
105240          }
105241        }
105242        return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
105243                                 pExpr->iColumn, iTab, target,
105244                                 pExpr->op2);
105245      }
105246      case TK_INTEGER: {
105247        codeInteger(pParse, pExpr, 0, target);
105248        return target;
105249      }
105250      case TK_TRUEFALSE: {
105251        sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
105252        return target;
105253      }
105254  #ifndef SQLITE_OMIT_FLOATING_POINT
105255      case TK_FLOAT: {
105256        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105257        codeReal(v, pExpr->u.zToken, 0, target);
105258        return target;
105259      }
105260  #endif
105261      case TK_STRING: {
105262        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105263        sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
105264        return target;
105265      }
105266      case TK_NULL: {
105267        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
105268        return target;
105269      }
105270  #ifndef SQLITE_OMIT_BLOB_LITERAL
105271      case TK_BLOB: {
105272        int n;
105273        const char *z;
105274        char *zBlob;
105275        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105276        assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
105277        assert( pExpr->u.zToken[1]=='\'' );
105278        z = &pExpr->u.zToken[2];
105279        n = sqlite3Strlen30(z) - 1;
105280        assert( z[n]=='\'' );
105281        zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
105282        sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
105283        return target;
105284      }
105285  #endif
105286      case TK_VARIABLE: {
105287        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105288        assert( pExpr->u.zToken!=0 );
105289        assert( pExpr->u.zToken[0]!=0 );
105290        sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
105291        if( pExpr->u.zToken[1]!=0 ){
105292          const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
105293          assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
105294          pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
105295          sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
105296        }
105297        return target;
105298      }
105299      case TK_REGISTER: {
105300        return pExpr->iTable;
105301      }
105302  #ifndef SQLITE_OMIT_CAST
105303      case TK_CAST: {
105304        /* Expressions of the form:   CAST(pLeft AS token) */
105305        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
105306        if( inReg!=target ){
105307          sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
105308          inReg = target;
105309        }
105310        sqlite3VdbeAddOp2(v, OP_Cast, target,
105311                          sqlite3AffinityType(pExpr->u.zToken, 0));
105312        return inReg;
105313      }
105314  #endif /* SQLITE_OMIT_CAST */
105315      case TK_IS:
105316      case TK_ISNOT:
105317        op = (op==TK_IS) ? TK_EQ : TK_NE;
105318        p5 = SQLITE_NULLEQ;
105319        /* fall-through */
105320      case TK_LT:
105321      case TK_LE:
105322      case TK_GT:
105323      case TK_GE:
105324      case TK_NE:
105325      case TK_EQ: {
105326        Expr *pLeft = pExpr->pLeft;
105327        if( sqlite3ExprIsVector(pLeft) ){
105328          codeVectorCompare(pParse, pExpr, target, op, p5);
105329        }else{
105330          r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
105331          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
105332          codeCompare(pParse, pLeft, pExpr->pRight, op,
105333              r1, r2, inReg, SQLITE_STOREP2 | p5);
105334          assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
105335          assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
105336          assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
105337          assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
105338          assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
105339          assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
105340          testcase( regFree1==0 );
105341          testcase( regFree2==0 );
105342        }
105343        break;
105344      }
105345      case TK_AND:
105346      case TK_OR:
105347      case TK_PLUS:
105348      case TK_STAR:
105349      case TK_MINUS:
105350      case TK_REM:
105351      case TK_BITAND:
105352      case TK_BITOR:
105353      case TK_SLASH:
105354      case TK_LSHIFT:
105355      case TK_RSHIFT: 
105356      case TK_CONCAT: {
105357        assert( TK_AND==OP_And );            testcase( op==TK_AND );
105358        assert( TK_OR==OP_Or );              testcase( op==TK_OR );
105359        assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
105360        assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
105361        assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
105362        assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
105363        assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
105364        assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
105365        assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
105366        assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
105367        assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
105368        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
105369        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
105370        sqlite3VdbeAddOp3(v, op, r2, r1, target);
105371        testcase( regFree1==0 );
105372        testcase( regFree2==0 );
105373        break;
105374      }
105375      case TK_UMINUS: {
105376        Expr *pLeft = pExpr->pLeft;
105377        assert( pLeft );
105378        if( pLeft->op==TK_INTEGER ){
105379          codeInteger(pParse, pLeft, 1, target);
105380          return target;
105381  #ifndef SQLITE_OMIT_FLOATING_POINT
105382        }else if( pLeft->op==TK_FLOAT ){
105383          assert( !ExprHasProperty(pExpr, EP_IntValue) );
105384          codeReal(v, pLeft->u.zToken, 1, target);
105385          return target;
105386  #endif
105387        }else{
105388          tempX.op = TK_INTEGER;
105389          tempX.flags = EP_IntValue|EP_TokenOnly;
105390          tempX.u.iValue = 0;
105391          r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
105392          r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
105393          sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
105394          testcase( regFree2==0 );
105395        }
105396        break;
105397      }
105398      case TK_BITNOT:
105399      case TK_NOT: {
105400        assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
105401        assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
105402        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
105403        testcase( regFree1==0 );
105404        sqlite3VdbeAddOp2(v, op, r1, inReg);
105405        break;
105406      }
105407      case TK_TRUTH: {
105408        int isTrue;    /* IS TRUE or IS NOT TRUE */
105409        int bNormal;   /* IS TRUE or IS FALSE */
105410        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
105411        testcase( regFree1==0 );
105412        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
105413        bNormal = pExpr->op2==TK_IS;
105414        testcase( isTrue && bNormal);
105415        testcase( !isTrue && bNormal);
105416        sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
105417        break;
105418      }
105419      case TK_ISNULL:
105420      case TK_NOTNULL: {
105421        int addr;
105422        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
105423        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
105424        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
105425        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
105426        testcase( regFree1==0 );
105427        addr = sqlite3VdbeAddOp1(v, op, r1);
105428        VdbeCoverageIf(v, op==TK_ISNULL);
105429        VdbeCoverageIf(v, op==TK_NOTNULL);
105430        sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
105431        sqlite3VdbeJumpHere(v, addr);
105432        break;
105433      }
105434      case TK_AGG_FUNCTION: {
105435        AggInfo *pInfo = pExpr->pAggInfo;
105436        if( pInfo==0 ){
105437          assert( !ExprHasProperty(pExpr, EP_IntValue) );
105438          sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
105439        }else{
105440          return pInfo->aFunc[pExpr->iAgg].iMem;
105441        }
105442        break;
105443      }
105444      case TK_FUNCTION: {
105445        ExprList *pFarg;       /* List of function arguments */
105446        int nFarg;             /* Number of function arguments */
105447        FuncDef *pDef;         /* The function definition object */
105448        const char *zId;       /* The function name */
105449        u32 constMask = 0;     /* Mask of function arguments that are constant */
105450        int i;                 /* Loop counter */
105451        sqlite3 *db = pParse->db;  /* The database connection */
105452        u8 enc = ENC(db);      /* The text encoding used by this database */
105453        CollSeq *pColl = 0;    /* A collating sequence */
105454  
105455  #ifndef SQLITE_OMIT_WINDOWFUNC
105456        if( ExprHasProperty(pExpr, EP_WinFunc) ){
105457          return pExpr->y.pWin->regResult;
105458        }
105459  #endif
105460  
105461        if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
105462          /* SQL functions can be expensive. So try to move constant functions
105463          ** out of the inner loop, even if that means an extra OP_Copy. */
105464          return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
105465        }
105466        assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
105467        if( ExprHasProperty(pExpr, EP_TokenOnly) ){
105468          pFarg = 0;
105469        }else{
105470          pFarg = pExpr->x.pList;
105471        }
105472        nFarg = pFarg ? pFarg->nExpr : 0;
105473        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105474        zId = pExpr->u.zToken;
105475        pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
105476  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105477        if( pDef==0 && pParse->explain ){
105478          pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
105479        }
105480  #endif
105481        if( pDef==0 || pDef->xFinalize!=0 ){
105482          sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
105483          break;
105484        }
105485  
105486        /* Attempt a direct implementation of the built-in COALESCE() and
105487        ** IFNULL() functions.  This avoids unnecessary evaluation of
105488        ** arguments past the first non-NULL argument.
105489        */
105490        if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
105491          int endCoalesce = sqlite3VdbeMakeLabel(pParse);
105492          assert( nFarg>=2 );
105493          sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
105494          for(i=1; i<nFarg; i++){
105495            sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
105496            VdbeCoverage(v);
105497            sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
105498          }
105499          sqlite3VdbeResolveLabel(v, endCoalesce);
105500          break;
105501        }
105502  
105503        /* The UNLIKELY() function is a no-op.  The result is the value
105504        ** of the first argument.
105505        */
105506        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
105507          assert( nFarg>=1 );
105508          return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
105509        }
105510  
105511  #ifdef SQLITE_DEBUG
105512        /* The AFFINITY() function evaluates to a string that describes
105513        ** the type affinity of the argument.  This is used for testing of
105514        ** the SQLite type logic.
105515        */
105516        if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
105517          const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
105518          char aff;
105519          assert( nFarg==1 );
105520          aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
105521          sqlite3VdbeLoadString(v, target, 
105522                                aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
105523          return target;
105524        }
105525  #endif
105526  
105527        for(i=0; i<nFarg; i++){
105528          if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
105529            testcase( i==31 );
105530            constMask |= MASKBIT32(i);
105531          }
105532          if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
105533            pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
105534          }
105535        }
105536        if( pFarg ){
105537          if( constMask ){
105538            r1 = pParse->nMem+1;
105539            pParse->nMem += nFarg;
105540          }else{
105541            r1 = sqlite3GetTempRange(pParse, nFarg);
105542          }
105543  
105544          /* For length() and typeof() functions with a column argument,
105545          ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
105546          ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
105547          ** loading.
105548          */
105549          if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
105550            u8 exprOp;
105551            assert( nFarg==1 );
105552            assert( pFarg->a[0].pExpr!=0 );
105553            exprOp = pFarg->a[0].pExpr->op;
105554            if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
105555              assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
105556              assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
105557              testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
105558              pFarg->a[0].pExpr->op2 = 
105559                    pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
105560            }
105561          }
105562  
105563          sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
105564                                  SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
105565        }else{
105566          r1 = 0;
105567        }
105568  #ifndef SQLITE_OMIT_VIRTUALTABLE
105569        /* Possibly overload the function if the first argument is
105570        ** a virtual table column.
105571        **
105572        ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
105573        ** second argument, not the first, as the argument to test to
105574        ** see if it is a column in a virtual table.  This is done because
105575        ** the left operand of infix functions (the operand we want to
105576        ** control overloading) ends up as the second argument to the
105577        ** function.  The expression "A glob B" is equivalent to 
105578        ** "glob(B,A).  We want to use the A in "A glob B" to test
105579        ** for function overloading.  But we use the B term in "glob(B,A)".
105580        */
105581        if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
105582          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
105583        }else if( nFarg>0 ){
105584          pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
105585        }
105586  #endif
105587        if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
105588          if( !pColl ) pColl = db->pDfltColl; 
105589          sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
105590        }
105591  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
105592        if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
105593          Expr *pArg = pFarg->a[0].pExpr;
105594          if( pArg->op==TK_COLUMN ){
105595            sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
105596          }else{
105597            sqlite3VdbeAddOp2(v, OP_Null, 0, target);
105598          }
105599        }else
105600  #endif
105601        {
105602          sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
105603                            constMask, r1, target, (char*)pDef, P4_FUNCDEF);
105604          sqlite3VdbeChangeP5(v, (u8)nFarg);
105605        }
105606        if( nFarg && constMask==0 ){
105607          sqlite3ReleaseTempRange(pParse, r1, nFarg);
105608        }
105609        return target;
105610      }
105611  #ifndef SQLITE_OMIT_SUBQUERY
105612      case TK_EXISTS:
105613      case TK_SELECT: {
105614        int nCol;
105615        testcase( op==TK_EXISTS );
105616        testcase( op==TK_SELECT );
105617        if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
105618          sqlite3SubselectError(pParse, nCol, 1);
105619        }else{
105620          return sqlite3CodeSubselect(pParse, pExpr);
105621        }
105622        break;
105623      }
105624      case TK_SELECT_COLUMN: {
105625        int n;
105626        if( pExpr->pLeft->iTable==0 ){
105627          pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
105628        }
105629        assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
105630        if( pExpr->iTable
105631         && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft)) 
105632        ){
105633          sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
105634                                  pExpr->iTable, n);
105635        }
105636        return pExpr->pLeft->iTable + pExpr->iColumn;
105637      }
105638      case TK_IN: {
105639        int destIfFalse = sqlite3VdbeMakeLabel(pParse);
105640        int destIfNull = sqlite3VdbeMakeLabel(pParse);
105641        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
105642        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
105643        sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
105644        sqlite3VdbeResolveLabel(v, destIfFalse);
105645        sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
105646        sqlite3VdbeResolveLabel(v, destIfNull);
105647        return target;
105648      }
105649  #endif /* SQLITE_OMIT_SUBQUERY */
105650  
105651  
105652      /*
105653      **    x BETWEEN y AND z
105654      **
105655      ** This is equivalent to
105656      **
105657      **    x>=y AND x<=z
105658      **
105659      ** X is stored in pExpr->pLeft.
105660      ** Y is stored in pExpr->pList->a[0].pExpr.
105661      ** Z is stored in pExpr->pList->a[1].pExpr.
105662      */
105663      case TK_BETWEEN: {
105664        exprCodeBetween(pParse, pExpr, target, 0, 0);
105665        return target;
105666      }
105667      case TK_SPAN:
105668      case TK_COLLATE: 
105669      case TK_UPLUS: {
105670        pExpr = pExpr->pLeft;
105671        goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
105672      }
105673  
105674      case TK_TRIGGER: {
105675        /* If the opcode is TK_TRIGGER, then the expression is a reference
105676        ** to a column in the new.* or old.* pseudo-tables available to
105677        ** trigger programs. In this case Expr.iTable is set to 1 for the
105678        ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
105679        ** is set to the column of the pseudo-table to read, or to -1 to
105680        ** read the rowid field.
105681        **
105682        ** The expression is implemented using an OP_Param opcode. The p1
105683        ** parameter is set to 0 for an old.rowid reference, or to (i+1)
105684        ** to reference another column of the old.* pseudo-table, where 
105685        ** i is the index of the column. For a new.rowid reference, p1 is
105686        ** set to (n+1), where n is the number of columns in each pseudo-table.
105687        ** For a reference to any other column in the new.* pseudo-table, p1
105688        ** is set to (n+2+i), where n and i are as defined previously. For
105689        ** example, if the table on which triggers are being fired is
105690        ** declared as:
105691        **
105692        **   CREATE TABLE t1(a, b);
105693        **
105694        ** Then p1 is interpreted as follows:
105695        **
105696        **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
105697        **   p1==1   ->    old.a         p1==4   ->    new.a
105698        **   p1==2   ->    old.b         p1==5   ->    new.b       
105699        */
105700        Table *pTab = pExpr->y.pTab;
105701        int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
105702  
105703        assert( pExpr->iTable==0 || pExpr->iTable==1 );
105704        assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
105705        assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
105706        assert( p1>=0 && p1<(pTab->nCol*2+2) );
105707  
105708        sqlite3VdbeAddOp2(v, OP_Param, p1, target);
105709        VdbeComment((v, "r[%d]=%s.%s", target,
105710          (pExpr->iTable ? "new" : "old"),
105711          (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
105712        ));
105713  
105714  #ifndef SQLITE_OMIT_FLOATING_POINT
105715        /* If the column has REAL affinity, it may currently be stored as an
105716        ** integer. Use OP_RealAffinity to make sure it is really real.
105717        **
105718        ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
105719        ** floating point when extracting it from the record.  */
105720        if( pExpr->iColumn>=0 
105721         && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
105722        ){
105723          sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
105724        }
105725  #endif
105726        break;
105727      }
105728  
105729      case TK_VECTOR: {
105730        sqlite3ErrorMsg(pParse, "row value misused");
105731        break;
105732      }
105733  
105734      case TK_IF_NULL_ROW: {
105735        int addrINR;
105736        addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
105737        inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
105738        sqlite3VdbeJumpHere(v, addrINR);
105739        sqlite3VdbeChangeP3(v, addrINR, inReg);
105740        break;
105741      }
105742  
105743      /*
105744      ** Form A:
105745      **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
105746      **
105747      ** Form B:
105748      **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
105749      **
105750      ** Form A is can be transformed into the equivalent form B as follows:
105751      **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
105752      **        WHEN x=eN THEN rN ELSE y END
105753      **
105754      ** X (if it exists) is in pExpr->pLeft.
105755      ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
105756      ** odd.  The Y is also optional.  If the number of elements in x.pList
105757      ** is even, then Y is omitted and the "otherwise" result is NULL.
105758      ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
105759      **
105760      ** The result of the expression is the Ri for the first matching Ei,
105761      ** or if there is no matching Ei, the ELSE term Y, or if there is
105762      ** no ELSE term, NULL.
105763      */
105764      default: assert( op==TK_CASE ); {
105765        int endLabel;                     /* GOTO label for end of CASE stmt */
105766        int nextCase;                     /* GOTO label for next WHEN clause */
105767        int nExpr;                        /* 2x number of WHEN terms */
105768        int i;                            /* Loop counter */
105769        ExprList *pEList;                 /* List of WHEN terms */
105770        struct ExprList_item *aListelem;  /* Array of WHEN terms */
105771        Expr opCompare;                   /* The X==Ei expression */
105772        Expr *pX;                         /* The X expression */
105773        Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
105774  
105775        assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
105776        assert(pExpr->x.pList->nExpr > 0);
105777        pEList = pExpr->x.pList;
105778        aListelem = pEList->a;
105779        nExpr = pEList->nExpr;
105780        endLabel = sqlite3VdbeMakeLabel(pParse);
105781        if( (pX = pExpr->pLeft)!=0 ){
105782          exprNodeCopy(&tempX, pX);
105783          testcase( pX->op==TK_COLUMN );
105784          exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
105785          testcase( regFree1==0 );
105786          memset(&opCompare, 0, sizeof(opCompare));
105787          opCompare.op = TK_EQ;
105788          opCompare.pLeft = &tempX;
105789          pTest = &opCompare;
105790          /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
105791          ** The value in regFree1 might get SCopy-ed into the file result.
105792          ** So make sure that the regFree1 register is not reused for other
105793          ** purposes and possibly overwritten.  */
105794          regFree1 = 0;
105795        }
105796        for(i=0; i<nExpr-1; i=i+2){
105797          if( pX ){
105798            assert( pTest!=0 );
105799            opCompare.pRight = aListelem[i].pExpr;
105800          }else{
105801            pTest = aListelem[i].pExpr;
105802          }
105803          nextCase = sqlite3VdbeMakeLabel(pParse);
105804          testcase( pTest->op==TK_COLUMN );
105805          sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
105806          testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
105807          sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
105808          sqlite3VdbeGoto(v, endLabel);
105809          sqlite3VdbeResolveLabel(v, nextCase);
105810        }
105811        if( (nExpr&1)!=0 ){
105812          sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
105813        }else{
105814          sqlite3VdbeAddOp2(v, OP_Null, 0, target);
105815        }
105816        sqlite3VdbeResolveLabel(v, endLabel);
105817        break;
105818      }
105819  #ifndef SQLITE_OMIT_TRIGGER
105820      case TK_RAISE: {
105821        assert( pExpr->affinity==OE_Rollback 
105822             || pExpr->affinity==OE_Abort
105823             || pExpr->affinity==OE_Fail
105824             || pExpr->affinity==OE_Ignore
105825        );
105826        if( !pParse->pTriggerTab ){
105827          sqlite3ErrorMsg(pParse,
105828                         "RAISE() may only be used within a trigger-program");
105829          return 0;
105830        }
105831        if( pExpr->affinity==OE_Abort ){
105832          sqlite3MayAbort(pParse);
105833        }
105834        assert( !ExprHasProperty(pExpr, EP_IntValue) );
105835        if( pExpr->affinity==OE_Ignore ){
105836          sqlite3VdbeAddOp4(
105837              v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
105838          VdbeCoverage(v);
105839        }else{
105840          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
105841                                pExpr->affinity, pExpr->u.zToken, 0, 0);
105842        }
105843  
105844        break;
105845      }
105846  #endif
105847    }
105848    sqlite3ReleaseTempReg(pParse, regFree1);
105849    sqlite3ReleaseTempReg(pParse, regFree2);
105850    return inReg;
105851  }
105852  
105853  /*
105854  ** Factor out the code of the given expression to initialization time.
105855  **
105856  ** If regDest>=0 then the result is always stored in that register and the
105857  ** result is not reusable.  If regDest<0 then this routine is free to 
105858  ** store the value whereever it wants.  The register where the expression 
105859  ** is stored is returned.  When regDest<0, two identical expressions will
105860  ** code to the same register.
105861  */
105862  SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
105863    Parse *pParse,    /* Parsing context */
105864    Expr *pExpr,      /* The expression to code when the VDBE initializes */
105865    int regDest       /* Store the value in this register */
105866  ){
105867    ExprList *p;
105868    assert( ConstFactorOk(pParse) );
105869    p = pParse->pConstExpr;
105870    if( regDest<0 && p ){
105871      struct ExprList_item *pItem;
105872      int i;
105873      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
105874        if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
105875          return pItem->u.iConstExprReg;
105876        }
105877      }
105878    }
105879    pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
105880    p = sqlite3ExprListAppend(pParse, p, pExpr);
105881    if( p ){
105882       struct ExprList_item *pItem = &p->a[p->nExpr-1];
105883       pItem->reusable = regDest<0;
105884       if( regDest<0 ) regDest = ++pParse->nMem;
105885       pItem->u.iConstExprReg = regDest;
105886    }
105887    pParse->pConstExpr = p;
105888    return regDest;
105889  }
105890  
105891  /*
105892  ** Generate code to evaluate an expression and store the results
105893  ** into a register.  Return the register number where the results
105894  ** are stored.
105895  **
105896  ** If the register is a temporary register that can be deallocated,
105897  ** then write its number into *pReg.  If the result register is not
105898  ** a temporary, then set *pReg to zero.
105899  **
105900  ** If pExpr is a constant, then this routine might generate this
105901  ** code to fill the register in the initialization section of the
105902  ** VDBE program, in order to factor it out of the evaluation loop.
105903  */
105904  SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
105905    int r2;
105906    pExpr = sqlite3ExprSkipCollate(pExpr);
105907    if( ConstFactorOk(pParse)
105908     && pExpr->op!=TK_REGISTER
105909     && sqlite3ExprIsConstantNotJoin(pExpr)
105910    ){
105911      *pReg  = 0;
105912      r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
105913    }else{
105914      int r1 = sqlite3GetTempReg(pParse);
105915      r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
105916      if( r2==r1 ){
105917        *pReg = r1;
105918      }else{
105919        sqlite3ReleaseTempReg(pParse, r1);
105920        *pReg = 0;
105921      }
105922    }
105923    return r2;
105924  }
105925  
105926  /*
105927  ** Generate code that will evaluate expression pExpr and store the
105928  ** results in register target.  The results are guaranteed to appear
105929  ** in register target.
105930  */
105931  SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
105932    int inReg;
105933  
105934    assert( target>0 && target<=pParse->nMem );
105935    if( pExpr && pExpr->op==TK_REGISTER ){
105936      sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
105937    }else{
105938      inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
105939      assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
105940      if( inReg!=target && pParse->pVdbe ){
105941        sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
105942      }
105943    }
105944  }
105945  
105946  /*
105947  ** Make a transient copy of expression pExpr and then code it using
105948  ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
105949  ** except that the input expression is guaranteed to be unchanged.
105950  */
105951  SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
105952    sqlite3 *db = pParse->db;
105953    pExpr = sqlite3ExprDup(db, pExpr, 0);
105954    if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
105955    sqlite3ExprDelete(db, pExpr);
105956  }
105957  
105958  /*
105959  ** Generate code that will evaluate expression pExpr and store the
105960  ** results in register target.  The results are guaranteed to appear
105961  ** in register target.  If the expression is constant, then this routine
105962  ** might choose to code the expression at initialization time.
105963  */
105964  SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
105965    if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
105966      sqlite3ExprCodeAtInit(pParse, pExpr, target);
105967    }else{
105968      sqlite3ExprCode(pParse, pExpr, target);
105969    }
105970  }
105971  
105972  /*
105973  ** Generate code that evaluates the given expression and puts the result
105974  ** in register target.
105975  **
105976  ** Also make a copy of the expression results into another "cache" register
105977  ** and modify the expression so that the next time it is evaluated,
105978  ** the result is a copy of the cache register.
105979  **
105980  ** This routine is used for expressions that are used multiple 
105981  ** times.  They are evaluated once and the results of the expression
105982  ** are reused.
105983  */
105984  SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
105985    Vdbe *v = pParse->pVdbe;
105986    int iMem;
105987  
105988    assert( target>0 );
105989    assert( pExpr->op!=TK_REGISTER );
105990    sqlite3ExprCode(pParse, pExpr, target);
105991    iMem = ++pParse->nMem;
105992    sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
105993    exprToRegister(pExpr, iMem);
105994  }
105995  
105996  /*
105997  ** Generate code that pushes the value of every element of the given
105998  ** expression list into a sequence of registers beginning at target.
105999  **
106000  ** Return the number of elements evaluated.  The number returned will
106001  ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
106002  ** is defined.
106003  **
106004  ** The SQLITE_ECEL_DUP flag prevents the arguments from being
106005  ** filled using OP_SCopy.  OP_Copy must be used instead.
106006  **
106007  ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
106008  ** factored out into initialization code.
106009  **
106010  ** The SQLITE_ECEL_REF flag means that expressions in the list with
106011  ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
106012  ** in registers at srcReg, and so the value can be copied from there.
106013  ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
106014  ** are simply omitted rather than being copied from srcReg.
106015  */
106016  SQLITE_PRIVATE int sqlite3ExprCodeExprList(
106017    Parse *pParse,     /* Parsing context */
106018    ExprList *pList,   /* The expression list to be coded */
106019    int target,        /* Where to write results */
106020    int srcReg,        /* Source registers if SQLITE_ECEL_REF */
106021    u8 flags           /* SQLITE_ECEL_* flags */
106022  ){
106023    struct ExprList_item *pItem;
106024    int i, j, n;
106025    u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
106026    Vdbe *v = pParse->pVdbe;
106027    assert( pList!=0 );
106028    assert( target>0 );
106029    assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
106030    n = pList->nExpr;
106031    if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
106032    for(pItem=pList->a, i=0; i<n; i++, pItem++){
106033      Expr *pExpr = pItem->pExpr;
106034  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
106035      if( pItem->bSorterRef ){
106036        i--;
106037        n--;
106038      }else
106039  #endif
106040      if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
106041        if( flags & SQLITE_ECEL_OMITREF ){
106042          i--;
106043          n--;
106044        }else{
106045          sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
106046        }
106047      }else if( (flags & SQLITE_ECEL_FACTOR)!=0
106048             && sqlite3ExprIsConstantNotJoin(pExpr)
106049      ){
106050        sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
106051      }else{
106052        int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
106053        if( inReg!=target+i ){
106054          VdbeOp *pOp;
106055          if( copyOp==OP_Copy
106056           && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
106057           && pOp->p1+pOp->p3+1==inReg
106058           && pOp->p2+pOp->p3+1==target+i
106059          ){
106060            pOp->p3++;
106061          }else{
106062            sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
106063          }
106064        }
106065      }
106066    }
106067    return n;
106068  }
106069  
106070  /*
106071  ** Generate code for a BETWEEN operator.
106072  **
106073  **    x BETWEEN y AND z
106074  **
106075  ** The above is equivalent to 
106076  **
106077  **    x>=y AND x<=z
106078  **
106079  ** Code it as such, taking care to do the common subexpression
106080  ** elimination of x.
106081  **
106082  ** The xJumpIf parameter determines details:
106083  **
106084  **    NULL:                   Store the boolean result in reg[dest]
106085  **    sqlite3ExprIfTrue:      Jump to dest if true
106086  **    sqlite3ExprIfFalse:     Jump to dest if false
106087  **
106088  ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
106089  */
106090  static void exprCodeBetween(
106091    Parse *pParse,    /* Parsing and code generating context */
106092    Expr *pExpr,      /* The BETWEEN expression */
106093    int dest,         /* Jump destination or storage location */
106094    void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
106095    int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
106096  ){
106097   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
106098    Expr compLeft;    /* The  x>=y  term */
106099    Expr compRight;   /* The  x<=z  term */
106100    Expr exprX;       /* The  x  subexpression */
106101    int regFree1 = 0; /* Temporary use register */
106102  
106103    memset(&compLeft, 0, sizeof(Expr));
106104    memset(&compRight, 0, sizeof(Expr));
106105    memset(&exprAnd, 0, sizeof(Expr));
106106  
106107    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
106108    exprNodeCopy(&exprX, pExpr->pLeft);
106109    exprAnd.op = TK_AND;
106110    exprAnd.pLeft = &compLeft;
106111    exprAnd.pRight = &compRight;
106112    compLeft.op = TK_GE;
106113    compLeft.pLeft = &exprX;
106114    compLeft.pRight = pExpr->x.pList->a[0].pExpr;
106115    compRight.op = TK_LE;
106116    compRight.pLeft = &exprX;
106117    compRight.pRight = pExpr->x.pList->a[1].pExpr;
106118    exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
106119    if( xJump ){
106120      xJump(pParse, &exprAnd, dest, jumpIfNull);
106121    }else{
106122      /* Mark the expression is being from the ON or USING clause of a join
106123      ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
106124      ** it into the Parse.pConstExpr list.  We should use a new bit for this,
106125      ** for clarity, but we are out of bits in the Expr.flags field so we
106126      ** have to reuse the EP_FromJoin bit.  Bummer. */
106127      exprX.flags |= EP_FromJoin;
106128      sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
106129    }
106130    sqlite3ReleaseTempReg(pParse, regFree1);
106131  
106132    /* Ensure adequate test coverage */
106133    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
106134    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
106135    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
106136    testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
106137    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
106138    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
106139    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
106140    testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
106141    testcase( xJump==0 );
106142  }
106143  
106144  /*
106145  ** Generate code for a boolean expression such that a jump is made
106146  ** to the label "dest" if the expression is true but execution
106147  ** continues straight thru if the expression is false.
106148  **
106149  ** If the expression evaluates to NULL (neither true nor false), then
106150  ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
106151  **
106152  ** This code depends on the fact that certain token values (ex: TK_EQ)
106153  ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
106154  ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
106155  ** the make process cause these values to align.  Assert()s in the code
106156  ** below verify that the numbers are aligned correctly.
106157  */
106158  SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
106159    Vdbe *v = pParse->pVdbe;
106160    int op = 0;
106161    int regFree1 = 0;
106162    int regFree2 = 0;
106163    int r1, r2;
106164  
106165    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
106166    if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
106167    if( NEVER(pExpr==0) ) return;  /* No way this can happen */
106168    op = pExpr->op;
106169    switch( op ){
106170      case TK_AND: {
106171        int d2 = sqlite3VdbeMakeLabel(pParse);
106172        testcase( jumpIfNull==0 );
106173        sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
106174        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
106175        sqlite3VdbeResolveLabel(v, d2);
106176        break;
106177      }
106178      case TK_OR: {
106179        testcase( jumpIfNull==0 );
106180        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
106181        sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
106182        break;
106183      }
106184      case TK_NOT: {
106185        testcase( jumpIfNull==0 );
106186        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
106187        break;
106188      }
106189      case TK_TRUTH: {
106190        int isNot;      /* IS NOT TRUE or IS NOT FALSE */
106191        int isTrue;     /* IS TRUE or IS NOT TRUE */
106192        testcase( jumpIfNull==0 );
106193        isNot = pExpr->op2==TK_ISNOT;
106194        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
106195        testcase( isTrue && isNot );
106196        testcase( !isTrue && isNot );
106197        if( isTrue ^ isNot ){
106198          sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
106199                            isNot ? SQLITE_JUMPIFNULL : 0);
106200        }else{
106201          sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
106202                             isNot ? SQLITE_JUMPIFNULL : 0);
106203        }
106204        break;
106205      }
106206      case TK_IS:
106207      case TK_ISNOT:
106208        testcase( op==TK_IS );
106209        testcase( op==TK_ISNOT );
106210        op = (op==TK_IS) ? TK_EQ : TK_NE;
106211        jumpIfNull = SQLITE_NULLEQ;
106212        /* Fall thru */
106213      case TK_LT:
106214      case TK_LE:
106215      case TK_GT:
106216      case TK_GE:
106217      case TK_NE:
106218      case TK_EQ: {
106219        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
106220        testcase( jumpIfNull==0 );
106221        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
106222        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
106223        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
106224                    r1, r2, dest, jumpIfNull);
106225        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
106226        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
106227        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
106228        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
106229        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
106230        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
106231        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
106232        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
106233        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
106234        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
106235        testcase( regFree1==0 );
106236        testcase( regFree2==0 );
106237        break;
106238      }
106239      case TK_ISNULL:
106240      case TK_NOTNULL: {
106241        assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
106242        assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
106243        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
106244        sqlite3VdbeAddOp2(v, op, r1, dest);
106245        VdbeCoverageIf(v, op==TK_ISNULL);
106246        VdbeCoverageIf(v, op==TK_NOTNULL);
106247        testcase( regFree1==0 );
106248        break;
106249      }
106250      case TK_BETWEEN: {
106251        testcase( jumpIfNull==0 );
106252        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
106253        break;
106254      }
106255  #ifndef SQLITE_OMIT_SUBQUERY
106256      case TK_IN: {
106257        int destIfFalse = sqlite3VdbeMakeLabel(pParse);
106258        int destIfNull = jumpIfNull ? dest : destIfFalse;
106259        sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
106260        sqlite3VdbeGoto(v, dest);
106261        sqlite3VdbeResolveLabel(v, destIfFalse);
106262        break;
106263      }
106264  #endif
106265      default: {
106266      default_expr:
106267        if( exprAlwaysTrue(pExpr) ){
106268          sqlite3VdbeGoto(v, dest);
106269        }else if( exprAlwaysFalse(pExpr) ){
106270          /* No-op */
106271        }else{
106272          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
106273          sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
106274          VdbeCoverage(v);
106275          testcase( regFree1==0 );
106276          testcase( jumpIfNull==0 );
106277        }
106278        break;
106279      }
106280    }
106281    sqlite3ReleaseTempReg(pParse, regFree1);
106282    sqlite3ReleaseTempReg(pParse, regFree2);  
106283  }
106284  
106285  /*
106286  ** Generate code for a boolean expression such that a jump is made
106287  ** to the label "dest" if the expression is false but execution
106288  ** continues straight thru if the expression is true.
106289  **
106290  ** If the expression evaluates to NULL (neither true nor false) then
106291  ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
106292  ** is 0.
106293  */
106294  SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
106295    Vdbe *v = pParse->pVdbe;
106296    int op = 0;
106297    int regFree1 = 0;
106298    int regFree2 = 0;
106299    int r1, r2;
106300  
106301    assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
106302    if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
106303    if( pExpr==0 )    return;
106304  
106305    /* The value of pExpr->op and op are related as follows:
106306    **
106307    **       pExpr->op            op
106308    **       ---------          ----------
106309    **       TK_ISNULL          OP_NotNull
106310    **       TK_NOTNULL         OP_IsNull
106311    **       TK_NE              OP_Eq
106312    **       TK_EQ              OP_Ne
106313    **       TK_GT              OP_Le
106314    **       TK_LE              OP_Gt
106315    **       TK_GE              OP_Lt
106316    **       TK_LT              OP_Ge
106317    **
106318    ** For other values of pExpr->op, op is undefined and unused.
106319    ** The value of TK_ and OP_ constants are arranged such that we
106320    ** can compute the mapping above using the following expression.
106321    ** Assert()s verify that the computation is correct.
106322    */
106323    op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
106324  
106325    /* Verify correct alignment of TK_ and OP_ constants
106326    */
106327    assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
106328    assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
106329    assert( pExpr->op!=TK_NE || op==OP_Eq );
106330    assert( pExpr->op!=TK_EQ || op==OP_Ne );
106331    assert( pExpr->op!=TK_LT || op==OP_Ge );
106332    assert( pExpr->op!=TK_LE || op==OP_Gt );
106333    assert( pExpr->op!=TK_GT || op==OP_Le );
106334    assert( pExpr->op!=TK_GE || op==OP_Lt );
106335  
106336    switch( pExpr->op ){
106337      case TK_AND: {
106338        testcase( jumpIfNull==0 );
106339        sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
106340        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
106341        break;
106342      }
106343      case TK_OR: {
106344        int d2 = sqlite3VdbeMakeLabel(pParse);
106345        testcase( jumpIfNull==0 );
106346        sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
106347        sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
106348        sqlite3VdbeResolveLabel(v, d2);
106349        break;
106350      }
106351      case TK_NOT: {
106352        testcase( jumpIfNull==0 );
106353        sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
106354        break;
106355      }
106356      case TK_TRUTH: {
106357        int isNot;   /* IS NOT TRUE or IS NOT FALSE */
106358        int isTrue;  /* IS TRUE or IS NOT TRUE */
106359        testcase( jumpIfNull==0 );
106360        isNot = pExpr->op2==TK_ISNOT;
106361        isTrue = sqlite3ExprTruthValue(pExpr->pRight);
106362        testcase( isTrue && isNot );
106363        testcase( !isTrue && isNot );
106364        if( isTrue ^ isNot ){
106365          /* IS TRUE and IS NOT FALSE */
106366          sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
106367                             isNot ? 0 : SQLITE_JUMPIFNULL);
106368  
106369        }else{
106370          /* IS FALSE and IS NOT TRUE */
106371          sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
106372                            isNot ? 0 : SQLITE_JUMPIFNULL);
106373        }
106374        break;
106375      }
106376      case TK_IS:
106377      case TK_ISNOT:
106378        testcase( pExpr->op==TK_IS );
106379        testcase( pExpr->op==TK_ISNOT );
106380        op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
106381        jumpIfNull = SQLITE_NULLEQ;
106382        /* Fall thru */
106383      case TK_LT:
106384      case TK_LE:
106385      case TK_GT:
106386      case TK_GE:
106387      case TK_NE:
106388      case TK_EQ: {
106389        if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
106390        testcase( jumpIfNull==0 );
106391        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
106392        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
106393        codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
106394                    r1, r2, dest, jumpIfNull);
106395        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
106396        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
106397        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
106398        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
106399        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
106400        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
106401        VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
106402        assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
106403        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
106404        VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
106405        testcase( regFree1==0 );
106406        testcase( regFree2==0 );
106407        break;
106408      }
106409      case TK_ISNULL:
106410      case TK_NOTNULL: {
106411        r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
106412        sqlite3VdbeAddOp2(v, op, r1, dest);
106413        testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
106414        testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
106415        testcase( regFree1==0 );
106416        break;
106417      }
106418      case TK_BETWEEN: {
106419        testcase( jumpIfNull==0 );
106420        exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
106421        break;
106422      }
106423  #ifndef SQLITE_OMIT_SUBQUERY
106424      case TK_IN: {
106425        if( jumpIfNull ){
106426          sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
106427        }else{
106428          int destIfNull = sqlite3VdbeMakeLabel(pParse);
106429          sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
106430          sqlite3VdbeResolveLabel(v, destIfNull);
106431        }
106432        break;
106433      }
106434  #endif
106435      default: {
106436      default_expr: 
106437        if( exprAlwaysFalse(pExpr) ){
106438          sqlite3VdbeGoto(v, dest);
106439        }else if( exprAlwaysTrue(pExpr) ){
106440          /* no-op */
106441        }else{
106442          r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
106443          sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
106444          VdbeCoverage(v);
106445          testcase( regFree1==0 );
106446          testcase( jumpIfNull==0 );
106447        }
106448        break;
106449      }
106450    }
106451    sqlite3ReleaseTempReg(pParse, regFree1);
106452    sqlite3ReleaseTempReg(pParse, regFree2);
106453  }
106454  
106455  /*
106456  ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
106457  ** code generation, and that copy is deleted after code generation. This
106458  ** ensures that the original pExpr is unchanged.
106459  */
106460  SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
106461    sqlite3 *db = pParse->db;
106462    Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
106463    if( db->mallocFailed==0 ){
106464      sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
106465    }
106466    sqlite3ExprDelete(db, pCopy);
106467  }
106468  
106469  /*
106470  ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
106471  ** type of expression.
106472  **
106473  ** If pExpr is a simple SQL value - an integer, real, string, blob
106474  ** or NULL value - then the VDBE currently being prepared is configured
106475  ** to re-prepare each time a new value is bound to variable pVar.
106476  **
106477  ** Additionally, if pExpr is a simple SQL value and the value is the
106478  ** same as that currently bound to variable pVar, non-zero is returned.
106479  ** Otherwise, if the values are not the same or if pExpr is not a simple
106480  ** SQL value, zero is returned.
106481  */
106482  static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
106483    int res = 0;
106484    int iVar;
106485    sqlite3_value *pL, *pR = 0;
106486    
106487    sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
106488    if( pR ){
106489      iVar = pVar->iColumn;
106490      sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
106491      pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
106492      if( pL ){
106493        if( sqlite3_value_type(pL)==SQLITE_TEXT ){
106494          sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
106495        }
106496        res =  0==sqlite3MemCompare(pL, pR, 0);
106497      }
106498      sqlite3ValueFree(pR);
106499      sqlite3ValueFree(pL);
106500    }
106501  
106502    return res;
106503  }
106504  
106505  /*
106506  ** Do a deep comparison of two expression trees.  Return 0 if the two
106507  ** expressions are completely identical.  Return 1 if they differ only
106508  ** by a COLLATE operator at the top level.  Return 2 if there are differences
106509  ** other than the top-level COLLATE operator.
106510  **
106511  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
106512  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
106513  **
106514  ** The pA side might be using TK_REGISTER.  If that is the case and pB is
106515  ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
106516  **
106517  ** Sometimes this routine will return 2 even if the two expressions
106518  ** really are equivalent.  If we cannot prove that the expressions are
106519  ** identical, we return 2 just to be safe.  So if this routine
106520  ** returns 2, then you do not really know for certain if the two
106521  ** expressions are the same.  But if you get a 0 or 1 return, then you
106522  ** can be sure the expressions are the same.  In the places where
106523  ** this routine is used, it does not hurt to get an extra 2 - that
106524  ** just might result in some slightly slower code.  But returning
106525  ** an incorrect 0 or 1 could lead to a malfunction.
106526  **
106527  ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
106528  ** pParse->pReprepare can be matched against literals in pB.  The 
106529  ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
106530  ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 
106531  ** Argument pParse should normally be NULL. If it is not NULL and pA or
106532  ** pB causes a return value of 2.
106533  */
106534  SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
106535    u32 combinedFlags;
106536    if( pA==0 || pB==0 ){
106537      return pB==pA ? 0 : 2;
106538    }
106539    if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
106540      return 0;
106541    }
106542    combinedFlags = pA->flags | pB->flags;
106543    if( combinedFlags & EP_IntValue ){
106544      if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
106545        return 0;
106546      }
106547      return 2;
106548    }
106549    if( pA->op!=pB->op || pA->op==TK_RAISE ){
106550      if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
106551        return 1;
106552      }
106553      if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
106554        return 1;
106555      }
106556      return 2;
106557    }
106558    if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
106559      if( pA->op==TK_FUNCTION ){
106560        if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
106561  #ifndef SQLITE_OMIT_WINDOWFUNC
106562        /* Justification for the assert():
106563        ** window functions have p->op==TK_FUNCTION but aggregate functions
106564        ** have p->op==TK_AGG_FUNCTION.  So any comparison between an aggregate
106565        ** function and a window function should have failed before reaching
106566        ** this point.  And, it is not possible to have a window function and
106567        ** a scalar function with the same name and number of arguments.  So
106568        ** if we reach this point, either A and B both window functions or
106569        ** neither are a window functions. */
106570        assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
106571        if( ExprHasProperty(pA,EP_WinFunc) ){
106572          if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
106573        }
106574  #endif
106575      }else if( pA->op==TK_NULL ){
106576        return 0;
106577      }else if( pA->op==TK_COLLATE ){
106578        if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
106579      }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
106580        return 2;
106581      }
106582    }
106583    if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
106584    if( (combinedFlags & EP_TokenOnly)==0 ){
106585      if( combinedFlags & EP_xIsSelect ) return 2;
106586      if( (combinedFlags & EP_FixedCol)==0
106587       && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
106588      if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
106589      if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
106590      if( pA->op!=TK_STRING
106591       && pA->op!=TK_TRUEFALSE
106592       && (combinedFlags & EP_Reduced)==0
106593      ){
106594        if( pA->iColumn!=pB->iColumn ) return 2;
106595        if( pA->iTable!=pB->iTable 
106596         && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
106597      }
106598    }
106599    return 0;
106600  }
106601  
106602  /*
106603  ** Compare two ExprList objects.  Return 0 if they are identical and 
106604  ** non-zero if they differ in any way.
106605  **
106606  ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
106607  ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
106608  **
106609  ** This routine might return non-zero for equivalent ExprLists.  The
106610  ** only consequence will be disabled optimizations.  But this routine
106611  ** must never return 0 if the two ExprList objects are different, or
106612  ** a malfunction will result.
106613  **
106614  ** Two NULL pointers are considered to be the same.  But a NULL pointer
106615  ** always differs from a non-NULL pointer.
106616  */
106617  SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
106618    int i;
106619    if( pA==0 && pB==0 ) return 0;
106620    if( pA==0 || pB==0 ) return 1;
106621    if( pA->nExpr!=pB->nExpr ) return 1;
106622    for(i=0; i<pA->nExpr; i++){
106623      Expr *pExprA = pA->a[i].pExpr;
106624      Expr *pExprB = pB->a[i].pExpr;
106625      if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
106626      if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
106627    }
106628    return 0;
106629  }
106630  
106631  /*
106632  ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
106633  ** are ignored.
106634  */
106635  SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
106636    return sqlite3ExprCompare(0,
106637               sqlite3ExprSkipCollate(pA),
106638               sqlite3ExprSkipCollate(pB),
106639               iTab);
106640  }
106641  
106642  /*
106643  ** Return true if we can prove the pE2 will always be true if pE1 is
106644  ** true.  Return false if we cannot complete the proof or if pE2 might
106645  ** be false.  Examples:
106646  **
106647  **     pE1: x==5       pE2: x==5             Result: true
106648  **     pE1: x>0        pE2: x==5             Result: false
106649  **     pE1: x=21       pE2: x=21 OR y=43     Result: true
106650  **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
106651  **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
106652  **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
106653  **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
106654  **
106655  ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
106656  ** Expr.iTable<0 then assume a table number given by iTab.
106657  **
106658  ** If pParse is not NULL, then the values of bound variables in pE1 are 
106659  ** compared against literal values in pE2 and pParse->pVdbe->expmask is
106660  ** modified to record which bound variables are referenced.  If pParse 
106661  ** is NULL, then false will be returned if pE1 contains any bound variables.
106662  **
106663  ** When in doubt, return false.  Returning true might give a performance
106664  ** improvement.  Returning false might cause a performance reduction, but
106665  ** it will always give the correct answer and is hence always safe.
106666  */
106667  SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
106668    if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
106669      return 1;
106670    }
106671    if( pE2->op==TK_OR
106672     && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
106673               || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
106674    ){
106675      return 1;
106676    }
106677    if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
106678      Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
106679      testcase( pX!=pE1->pLeft );
106680      if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
106681    }
106682    return 0;
106683  }
106684  
106685  /*
106686  ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
106687  ** If the expression node requires that the table at pWalker->iCur
106688  ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
106689  **
106690  ** This routine controls an optimization.  False positives (setting
106691  ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
106692  ** (never setting pWalker->eCode) is a harmless missed optimization.
106693  */
106694  static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
106695    testcase( pExpr->op==TK_AGG_COLUMN );
106696    testcase( pExpr->op==TK_AGG_FUNCTION );
106697    if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
106698    switch( pExpr->op ){
106699      case TK_ISNOT:
106700      case TK_NOT:
106701      case TK_ISNULL:
106702      case TK_NOTNULL:
106703      case TK_IS:
106704      case TK_OR:
106705      case TK_CASE:
106706      case TK_IN:
106707      case TK_FUNCTION:
106708        testcase( pExpr->op==TK_ISNOT );
106709        testcase( pExpr->op==TK_NOT );
106710        testcase( pExpr->op==TK_ISNULL );
106711        testcase( pExpr->op==TK_NOTNULL );
106712        testcase( pExpr->op==TK_IS );
106713        testcase( pExpr->op==TK_OR );
106714        testcase( pExpr->op==TK_CASE );
106715        testcase( pExpr->op==TK_IN );
106716        testcase( pExpr->op==TK_FUNCTION );
106717        return WRC_Prune;
106718      case TK_COLUMN:
106719        if( pWalker->u.iCur==pExpr->iTable ){
106720          pWalker->eCode = 1;
106721          return WRC_Abort;
106722        }
106723        return WRC_Prune;
106724  
106725      /* Virtual tables are allowed to use constraints like x=NULL.  So
106726      ** a term of the form x=y does not prove that y is not null if x
106727      ** is the column of a virtual table */
106728      case TK_EQ:
106729      case TK_NE:
106730      case TK_LT:
106731      case TK_LE:
106732      case TK_GT:
106733      case TK_GE:
106734        testcase( pExpr->op==TK_EQ );
106735        testcase( pExpr->op==TK_NE );
106736        testcase( pExpr->op==TK_LT );
106737        testcase( pExpr->op==TK_LE );
106738        testcase( pExpr->op==TK_GT );
106739        testcase( pExpr->op==TK_GE );
106740        if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
106741         || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
106742        ){
106743         return WRC_Prune;
106744        }
106745      default:
106746        return WRC_Continue;
106747    }
106748  }
106749  
106750  /*
106751  ** Return true (non-zero) if expression p can only be true if at least
106752  ** one column of table iTab is non-null.  In other words, return true
106753  ** if expression p will always be NULL or false if every column of iTab
106754  ** is NULL.
106755  **
106756  ** False negatives are acceptable.  In other words, it is ok to return
106757  ** zero even if expression p will never be true of every column of iTab
106758  ** is NULL.  A false negative is merely a missed optimization opportunity.
106759  **
106760  ** False positives are not allowed, however.  A false positive may result
106761  ** in an incorrect answer.
106762  **
106763  ** Terms of p that are marked with EP_FromJoin (and hence that come from
106764  ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
106765  **
106766  ** This routine is used to check if a LEFT JOIN can be converted into
106767  ** an ordinary JOIN.  The p argument is the WHERE clause.  If the WHERE
106768  ** clause requires that some column of the right table of the LEFT JOIN
106769  ** be non-NULL, then the LEFT JOIN can be safely converted into an
106770  ** ordinary join.
106771  */
106772  SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
106773    Walker w;
106774    w.xExprCallback = impliesNotNullRow;
106775    w.xSelectCallback = 0;
106776    w.xSelectCallback2 = 0;
106777    w.eCode = 0;
106778    w.u.iCur = iTab;
106779    sqlite3WalkExpr(&w, p);
106780    return w.eCode;
106781  }
106782  
106783  /*
106784  ** An instance of the following structure is used by the tree walker
106785  ** to determine if an expression can be evaluated by reference to the
106786  ** index only, without having to do a search for the corresponding
106787  ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
106788  ** is the cursor for the table.
106789  */
106790  struct IdxCover {
106791    Index *pIdx;     /* The index to be tested for coverage */
106792    int iCur;        /* Cursor number for the table corresponding to the index */
106793  };
106794  
106795  /*
106796  ** Check to see if there are references to columns in table 
106797  ** pWalker->u.pIdxCover->iCur can be satisfied using the index
106798  ** pWalker->u.pIdxCover->pIdx.
106799  */
106800  static int exprIdxCover(Walker *pWalker, Expr *pExpr){
106801    if( pExpr->op==TK_COLUMN
106802     && pExpr->iTable==pWalker->u.pIdxCover->iCur
106803     && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
106804    ){
106805      pWalker->eCode = 1;
106806      return WRC_Abort;
106807    }
106808    return WRC_Continue;
106809  }
106810  
106811  /*
106812  ** Determine if an index pIdx on table with cursor iCur contains will
106813  ** the expression pExpr.  Return true if the index does cover the
106814  ** expression and false if the pExpr expression references table columns
106815  ** that are not found in the index pIdx.
106816  **
106817  ** An index covering an expression means that the expression can be
106818  ** evaluated using only the index and without having to lookup the
106819  ** corresponding table entry.
106820  */
106821  SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
106822    Expr *pExpr,        /* The index to be tested */
106823    int iCur,           /* The cursor number for the corresponding table */
106824    Index *pIdx         /* The index that might be used for coverage */
106825  ){
106826    Walker w;
106827    struct IdxCover xcov;
106828    memset(&w, 0, sizeof(w));
106829    xcov.iCur = iCur;
106830    xcov.pIdx = pIdx;
106831    w.xExprCallback = exprIdxCover;
106832    w.u.pIdxCover = &xcov;
106833    sqlite3WalkExpr(&w, pExpr);
106834    return !w.eCode;
106835  }
106836  
106837  
106838  /*
106839  ** An instance of the following structure is used by the tree walker
106840  ** to count references to table columns in the arguments of an 
106841  ** aggregate function, in order to implement the
106842  ** sqlite3FunctionThisSrc() routine.
106843  */
106844  struct SrcCount {
106845    SrcList *pSrc;   /* One particular FROM clause in a nested query */
106846    int nThis;       /* Number of references to columns in pSrcList */
106847    int nOther;      /* Number of references to columns in other FROM clauses */
106848  };
106849  
106850  /*
106851  ** Count the number of references to columns.
106852  */
106853  static int exprSrcCount(Walker *pWalker, Expr *pExpr){
106854    /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
106855    ** is always called before sqlite3ExprAnalyzeAggregates() and so the
106856    ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
106857    ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
106858    ** NEVER() will need to be removed. */
106859    if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
106860      int i;
106861      struct SrcCount *p = pWalker->u.pSrcCount;
106862      SrcList *pSrc = p->pSrc;
106863      int nSrc = pSrc ? pSrc->nSrc : 0;
106864      for(i=0; i<nSrc; i++){
106865        if( pExpr->iTable==pSrc->a[i].iCursor ) break;
106866      }
106867      if( i<nSrc ){
106868        p->nThis++;
106869      }else{
106870        p->nOther++;
106871      }
106872    }
106873    return WRC_Continue;
106874  }
106875  
106876  /*
106877  ** Determine if any of the arguments to the pExpr Function reference
106878  ** pSrcList.  Return true if they do.  Also return true if the function
106879  ** has no arguments or has only constant arguments.  Return false if pExpr
106880  ** references columns but not columns of tables found in pSrcList.
106881  */
106882  SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
106883    Walker w;
106884    struct SrcCount cnt;
106885    assert( pExpr->op==TK_AGG_FUNCTION );
106886    w.xExprCallback = exprSrcCount;
106887    w.xSelectCallback = 0;
106888    w.u.pSrcCount = &cnt;
106889    cnt.pSrc = pSrcList;
106890    cnt.nThis = 0;
106891    cnt.nOther = 0;
106892    sqlite3WalkExprList(&w, pExpr->x.pList);
106893    return cnt.nThis>0 || cnt.nOther==0;
106894  }
106895  
106896  /*
106897  ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
106898  ** the new element.  Return a negative number if malloc fails.
106899  */
106900  static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
106901    int i;
106902    pInfo->aCol = sqlite3ArrayAllocate(
106903         db,
106904         pInfo->aCol,
106905         sizeof(pInfo->aCol[0]),
106906         &pInfo->nColumn,
106907         &i
106908    );
106909    return i;
106910  }    
106911  
106912  /*
106913  ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
106914  ** the new element.  Return a negative number if malloc fails.
106915  */
106916  static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
106917    int i;
106918    pInfo->aFunc = sqlite3ArrayAllocate(
106919         db, 
106920         pInfo->aFunc,
106921         sizeof(pInfo->aFunc[0]),
106922         &pInfo->nFunc,
106923         &i
106924    );
106925    return i;
106926  }    
106927  
106928  /*
106929  ** This is the xExprCallback for a tree walker.  It is used to
106930  ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
106931  ** for additional information.
106932  */
106933  static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
106934    int i;
106935    NameContext *pNC = pWalker->u.pNC;
106936    Parse *pParse = pNC->pParse;
106937    SrcList *pSrcList = pNC->pSrcList;
106938    AggInfo *pAggInfo = pNC->uNC.pAggInfo;
106939  
106940    assert( pNC->ncFlags & NC_UAggInfo );
106941    switch( pExpr->op ){
106942      case TK_AGG_COLUMN:
106943      case TK_COLUMN: {
106944        testcase( pExpr->op==TK_AGG_COLUMN );
106945        testcase( pExpr->op==TK_COLUMN );
106946        /* Check to see if the column is in one of the tables in the FROM
106947        ** clause of the aggregate query */
106948        if( ALWAYS(pSrcList!=0) ){
106949          struct SrcList_item *pItem = pSrcList->a;
106950          for(i=0; i<pSrcList->nSrc; i++, pItem++){
106951            struct AggInfo_col *pCol;
106952            assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
106953            if( pExpr->iTable==pItem->iCursor ){
106954              /* If we reach this point, it means that pExpr refers to a table
106955              ** that is in the FROM clause of the aggregate query.  
106956              **
106957              ** Make an entry for the column in pAggInfo->aCol[] if there
106958              ** is not an entry there already.
106959              */
106960              int k;
106961              pCol = pAggInfo->aCol;
106962              for(k=0; k<pAggInfo->nColumn; k++, pCol++){
106963                if( pCol->iTable==pExpr->iTable &&
106964                    pCol->iColumn==pExpr->iColumn ){
106965                  break;
106966                }
106967              }
106968              if( (k>=pAggInfo->nColumn)
106969               && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
106970              ){
106971                pCol = &pAggInfo->aCol[k];
106972                pCol->pTab = pExpr->y.pTab;
106973                pCol->iTable = pExpr->iTable;
106974                pCol->iColumn = pExpr->iColumn;
106975                pCol->iMem = ++pParse->nMem;
106976                pCol->iSorterColumn = -1;
106977                pCol->pExpr = pExpr;
106978                if( pAggInfo->pGroupBy ){
106979                  int j, n;
106980                  ExprList *pGB = pAggInfo->pGroupBy;
106981                  struct ExprList_item *pTerm = pGB->a;
106982                  n = pGB->nExpr;
106983                  for(j=0; j<n; j++, pTerm++){
106984                    Expr *pE = pTerm->pExpr;
106985                    if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
106986                        pE->iColumn==pExpr->iColumn ){
106987                      pCol->iSorterColumn = j;
106988                      break;
106989                    }
106990                  }
106991                }
106992                if( pCol->iSorterColumn<0 ){
106993                  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
106994                }
106995              }
106996              /* There is now an entry for pExpr in pAggInfo->aCol[] (either
106997              ** because it was there before or because we just created it).
106998              ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
106999              ** pAggInfo->aCol[] entry.
107000              */
107001              ExprSetVVAProperty(pExpr, EP_NoReduce);
107002              pExpr->pAggInfo = pAggInfo;
107003              pExpr->op = TK_AGG_COLUMN;
107004              pExpr->iAgg = (i16)k;
107005              break;
107006            } /* endif pExpr->iTable==pItem->iCursor */
107007          } /* end loop over pSrcList */
107008        }
107009        return WRC_Prune;
107010      }
107011      case TK_AGG_FUNCTION: {
107012        if( (pNC->ncFlags & NC_InAggFunc)==0
107013         && pWalker->walkerDepth==pExpr->op2
107014        ){
107015          /* Check to see if pExpr is a duplicate of another aggregate 
107016          ** function that is already in the pAggInfo structure
107017          */
107018          struct AggInfo_func *pItem = pAggInfo->aFunc;
107019          for(i=0; i<pAggInfo->nFunc; i++, pItem++){
107020            if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
107021              break;
107022            }
107023          }
107024          if( i>=pAggInfo->nFunc ){
107025            /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
107026            */
107027            u8 enc = ENC(pParse->db);
107028            i = addAggInfoFunc(pParse->db, pAggInfo);
107029            if( i>=0 ){
107030              assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
107031              pItem = &pAggInfo->aFunc[i];
107032              pItem->pExpr = pExpr;
107033              pItem->iMem = ++pParse->nMem;
107034              assert( !ExprHasProperty(pExpr, EP_IntValue) );
107035              pItem->pFunc = sqlite3FindFunction(pParse->db,
107036                     pExpr->u.zToken, 
107037                     pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
107038              if( pExpr->flags & EP_Distinct ){
107039                pItem->iDistinct = pParse->nTab++;
107040              }else{
107041                pItem->iDistinct = -1;
107042              }
107043            }
107044          }
107045          /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
107046          */
107047          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
107048          ExprSetVVAProperty(pExpr, EP_NoReduce);
107049          pExpr->iAgg = (i16)i;
107050          pExpr->pAggInfo = pAggInfo;
107051          return WRC_Prune;
107052        }else{
107053          return WRC_Continue;
107054        }
107055      }
107056    }
107057    return WRC_Continue;
107058  }
107059  static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
107060    UNUSED_PARAMETER(pSelect);
107061    pWalker->walkerDepth++;
107062    return WRC_Continue;
107063  }
107064  static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
107065    UNUSED_PARAMETER(pSelect);
107066    pWalker->walkerDepth--;
107067  }
107068  
107069  /*
107070  ** Analyze the pExpr expression looking for aggregate functions and
107071  ** for variables that need to be added to AggInfo object that pNC->pAggInfo
107072  ** points to.  Additional entries are made on the AggInfo object as
107073  ** necessary.
107074  **
107075  ** This routine should only be called after the expression has been
107076  ** analyzed by sqlite3ResolveExprNames().
107077  */
107078  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
107079    Walker w;
107080    w.xExprCallback = analyzeAggregate;
107081    w.xSelectCallback = analyzeAggregatesInSelect;
107082    w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
107083    w.walkerDepth = 0;
107084    w.u.pNC = pNC;
107085    w.pParse = 0;
107086    assert( pNC->pSrcList!=0 );
107087    sqlite3WalkExpr(&w, pExpr);
107088  }
107089  
107090  /*
107091  ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
107092  ** expression list.  Return the number of errors.
107093  **
107094  ** If an error is found, the analysis is cut short.
107095  */
107096  SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
107097    struct ExprList_item *pItem;
107098    int i;
107099    if( pList ){
107100      for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
107101        sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
107102      }
107103    }
107104  }
107105  
107106  /*
107107  ** Allocate a single new register for use to hold some intermediate result.
107108  */
107109  SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
107110    if( pParse->nTempReg==0 ){
107111      return ++pParse->nMem;
107112    }
107113    return pParse->aTempReg[--pParse->nTempReg];
107114  }
107115  
107116  /*
107117  ** Deallocate a register, making available for reuse for some other
107118  ** purpose.
107119  */
107120  SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
107121    if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
107122      pParse->aTempReg[pParse->nTempReg++] = iReg;
107123    }
107124  }
107125  
107126  /*
107127  ** Allocate or deallocate a block of nReg consecutive registers.
107128  */
107129  SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
107130    int i, n;
107131    if( nReg==1 ) return sqlite3GetTempReg(pParse);
107132    i = pParse->iRangeReg;
107133    n = pParse->nRangeReg;
107134    if( nReg<=n ){
107135      pParse->iRangeReg += nReg;
107136      pParse->nRangeReg -= nReg;
107137    }else{
107138      i = pParse->nMem+1;
107139      pParse->nMem += nReg;
107140    }
107141    return i;
107142  }
107143  SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
107144    if( nReg==1 ){
107145      sqlite3ReleaseTempReg(pParse, iReg);
107146      return;
107147    }
107148    if( nReg>pParse->nRangeReg ){
107149      pParse->nRangeReg = nReg;
107150      pParse->iRangeReg = iReg;
107151    }
107152  }
107153  
107154  /*
107155  ** Mark all temporary registers as being unavailable for reuse.
107156  */
107157  SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
107158    pParse->nTempReg = 0;
107159    pParse->nRangeReg = 0;
107160  }
107161  
107162  /*
107163  ** Validate that no temporary register falls within the range of
107164  ** iFirst..iLast, inclusive.  This routine is only call from within assert()
107165  ** statements.
107166  */
107167  #ifdef SQLITE_DEBUG
107168  SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
107169    int i;
107170    if( pParse->nRangeReg>0
107171     && pParse->iRangeReg+pParse->nRangeReg > iFirst
107172     && pParse->iRangeReg <= iLast
107173    ){
107174       return 0;
107175    }
107176    for(i=0; i<pParse->nTempReg; i++){
107177      if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
107178        return 0;
107179      }
107180    }
107181    return 1;
107182  }
107183  #endif /* SQLITE_DEBUG */
107184  
107185  /************** End of expr.c ************************************************/
107186  /************** Begin file alter.c *******************************************/
107187  /*
107188  ** 2005 February 15
107189  **
107190  ** The author disclaims copyright to this source code.  In place of
107191  ** a legal notice, here is a blessing:
107192  **
107193  **    May you do good and not evil.
107194  **    May you find forgiveness for yourself and forgive others.
107195  **    May you share freely, never taking more than you give.
107196  **
107197  *************************************************************************
107198  ** This file contains C code routines that used to generate VDBE code
107199  ** that implements the ALTER TABLE command.
107200  */
107201  /* #include "sqliteInt.h" */
107202  
107203  /*
107204  ** The code in this file only exists if we are not omitting the
107205  ** ALTER TABLE logic from the build.
107206  */
107207  #ifndef SQLITE_OMIT_ALTERTABLE
107208  
107209  /*
107210  ** Parameter zName is the name of a table that is about to be altered
107211  ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
107212  ** If the table is a system table, this function leaves an error message
107213  ** in pParse->zErr (system tables may not be altered) and returns non-zero.
107214  **
107215  ** Or, if zName is not a system table, zero is returned.
107216  */
107217  static int isAlterableTable(Parse *pParse, Table *pTab){
107218    if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) 
107219  #ifndef SQLITE_OMIT_VIRTUALTABLE
107220     || ( (pTab->tabFlags & TF_Shadow) 
107221       && (pParse->db->flags & SQLITE_Defensive)
107222       && pParse->db->nVdbeExec==0
107223     )
107224  #endif
107225    ){
107226      sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
107227      return 1;
107228    }
107229    return 0;
107230  }
107231  
107232  /*
107233  ** Generate code to verify that the schemas of database zDb and, if
107234  ** bTemp is not true, database "temp", can still be parsed. This is
107235  ** called at the end of the generation of an ALTER TABLE ... RENAME ...
107236  ** statement to ensure that the operation has not rendered any schema
107237  ** objects unusable.
107238  */
107239  static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
107240    sqlite3NestedParse(pParse, 
107241        "SELECT 1 "
107242        "FROM \"%w\".%s "
107243        "WHERE name NOT LIKE 'sqlite_%%'"
107244        " AND sql NOT LIKE 'create virtual%%'"
107245        " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
107246        zDb, MASTER_NAME, 
107247        zDb, bTemp
107248    );
107249  
107250    if( bTemp==0 ){
107251      sqlite3NestedParse(pParse, 
107252          "SELECT 1 "
107253          "FROM temp.%s "
107254          "WHERE name NOT LIKE 'sqlite_%%'"
107255          " AND sql NOT LIKE 'create virtual%%'"
107256          " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
107257          MASTER_NAME, zDb 
107258      );
107259    }
107260  }
107261  
107262  /*
107263  ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
107264  ** the temp database as well.
107265  */
107266  static void renameReloadSchema(Parse *pParse, int iDb){
107267    Vdbe *v = pParse->pVdbe;
107268    if( v ){
107269      sqlite3ChangeCookie(pParse, iDb);
107270      sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
107271      if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
107272    }
107273  }
107274  
107275  /*
107276  ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
107277  ** command. 
107278  */
107279  SQLITE_PRIVATE void sqlite3AlterRenameTable(
107280    Parse *pParse,            /* Parser context. */
107281    SrcList *pSrc,            /* The table to rename. */
107282    Token *pName              /* The new table name. */
107283  ){
107284    int iDb;                  /* Database that contains the table */
107285    char *zDb;                /* Name of database iDb */
107286    Table *pTab;              /* Table being renamed */
107287    char *zName = 0;          /* NULL-terminated version of pName */ 
107288    sqlite3 *db = pParse->db; /* Database connection */
107289    int nTabName;             /* Number of UTF-8 characters in zTabName */
107290    const char *zTabName;     /* Original name of the table */
107291    Vdbe *v;
107292    VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
107293    u32 savedDbFlags;         /* Saved value of db->mDbFlags */
107294  
107295    savedDbFlags = db->mDbFlags;  
107296    if( NEVER(db->mallocFailed) ) goto exit_rename_table;
107297    assert( pSrc->nSrc==1 );
107298    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
107299  
107300    pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
107301    if( !pTab ) goto exit_rename_table;
107302    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
107303    zDb = db->aDb[iDb].zDbSName;
107304    db->mDbFlags |= DBFLAG_PreferBuiltin;
107305  
107306    /* Get a NULL terminated version of the new table name. */
107307    zName = sqlite3NameFromToken(db, pName);
107308    if( !zName ) goto exit_rename_table;
107309  
107310    /* Check that a table or index named 'zName' does not already exist
107311    ** in database iDb. If so, this is an error.
107312    */
107313    if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
107314      sqlite3ErrorMsg(pParse, 
107315          "there is already another table or index with this name: %s", zName);
107316      goto exit_rename_table;
107317    }
107318  
107319    /* Make sure it is not a system table being altered, or a reserved name
107320    ** that the table is being renamed to.
107321    */
107322    if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
107323      goto exit_rename_table;
107324    }
107325    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
107326      exit_rename_table;
107327    }
107328  
107329  #ifndef SQLITE_OMIT_VIEW
107330    if( pTab->pSelect ){
107331      sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
107332      goto exit_rename_table;
107333    }
107334  #endif
107335  
107336  #ifndef SQLITE_OMIT_AUTHORIZATION
107337    /* Invoke the authorization callback. */
107338    if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
107339      goto exit_rename_table;
107340    }
107341  #endif
107342  
107343  #ifndef SQLITE_OMIT_VIRTUALTABLE
107344    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107345      goto exit_rename_table;
107346    }
107347    if( IsVirtual(pTab) ){
107348      pVTab = sqlite3GetVTable(db, pTab);
107349      if( pVTab->pVtab->pModule->xRename==0 ){
107350        pVTab = 0;
107351      }
107352    }
107353  #endif
107354  
107355    /* Begin a transaction for database iDb. 
107356    ** Then modify the schema cookie (since the ALTER TABLE modifies the
107357    ** schema). Open a statement transaction if the table is a virtual
107358    ** table.
107359    */
107360    v = sqlite3GetVdbe(pParse);
107361    if( v==0 ){
107362      goto exit_rename_table;
107363    }
107364  
107365    /* figure out how many UTF-8 characters are in zName */
107366    zTabName = pTab->zName;
107367    nTabName = sqlite3Utf8CharLen(zTabName, -1);
107368  
107369    /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
107370    ** the schema to use the new table name.  */
107371    sqlite3NestedParse(pParse, 
107372        "UPDATE \"%w\".%s SET "
107373        "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
107374        "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
107375        "AND   name NOT LIKE 'sqlite_%%'"
107376        , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
107377    );
107378  
107379    /* Update the tbl_name and name columns of the sqlite_master table
107380    ** as required.  */
107381    sqlite3NestedParse(pParse,
107382        "UPDATE %Q.%s SET "
107383            "tbl_name = %Q, "
107384            "name = CASE "
107385              "WHEN type='table' THEN %Q "
107386              "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
107387               "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
107388              "ELSE name END "
107389        "WHERE tbl_name=%Q COLLATE nocase AND "
107390            "(type='table' OR type='index' OR type='trigger');", 
107391        zDb, MASTER_NAME, 
107392        zName, zName, zName, 
107393        nTabName, zTabName
107394    );
107395  
107396  #ifndef SQLITE_OMIT_AUTOINCREMENT
107397    /* If the sqlite_sequence table exists in this database, then update 
107398    ** it with the new table name.
107399    */
107400    if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
107401      sqlite3NestedParse(pParse,
107402          "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
107403          zDb, zName, pTab->zName);
107404    }
107405  #endif
107406  
107407    /* If the table being renamed is not itself part of the temp database,
107408    ** edit view and trigger definitions within the temp database 
107409    ** as required.  */
107410    if( iDb!=1 ){
107411      sqlite3NestedParse(pParse, 
107412          "UPDATE sqlite_temp_master SET "
107413              "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
107414              "tbl_name = "
107415                "CASE WHEN tbl_name=%Q COLLATE nocase AND "
107416                "          sqlite_rename_test(%Q, sql, type, name, 1) "
107417                "THEN %Q ELSE tbl_name END "
107418              "WHERE type IN ('view', 'trigger')"
107419          , zDb, zTabName, zName, zTabName, zDb, zName);
107420    }
107421  
107422    /* If this is a virtual table, invoke the xRename() function if
107423    ** one is defined. The xRename() callback will modify the names
107424    ** of any resources used by the v-table implementation (including other
107425    ** SQLite tables) that are identified by the name of the virtual table.
107426    */
107427  #ifndef SQLITE_OMIT_VIRTUALTABLE
107428    if( pVTab ){
107429      int i = ++pParse->nMem;
107430      sqlite3VdbeLoadString(v, i, zName);
107431      sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
107432      sqlite3MayAbort(pParse);
107433    }
107434  #endif
107435  
107436    renameReloadSchema(pParse, iDb);
107437    renameTestSchema(pParse, zDb, iDb==1);
107438  
107439  exit_rename_table:
107440    sqlite3SrcListDelete(db, pSrc);
107441    sqlite3DbFree(db, zName);
107442    db->mDbFlags = savedDbFlags;
107443  }
107444  
107445  /*
107446  ** This function is called after an "ALTER TABLE ... ADD" statement
107447  ** has been parsed. Argument pColDef contains the text of the new
107448  ** column definition.
107449  **
107450  ** The Table structure pParse->pNewTable was extended to include
107451  ** the new column during parsing.
107452  */
107453  SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
107454    Table *pNew;              /* Copy of pParse->pNewTable */
107455    Table *pTab;              /* Table being altered */
107456    int iDb;                  /* Database number */
107457    const char *zDb;          /* Database name */
107458    const char *zTab;         /* Table name */
107459    char *zCol;               /* Null-terminated column definition */
107460    Column *pCol;             /* The new column */
107461    Expr *pDflt;              /* Default value for the new column */
107462    sqlite3 *db;              /* The database connection; */
107463    Vdbe *v;                  /* The prepared statement under construction */
107464    int r1;                   /* Temporary registers */
107465  
107466    db = pParse->db;
107467    if( pParse->nErr || db->mallocFailed ) return;
107468    pNew = pParse->pNewTable;
107469    assert( pNew );
107470  
107471    assert( sqlite3BtreeHoldsAllMutexes(db) );
107472    iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
107473    zDb = db->aDb[iDb].zDbSName;
107474    zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
107475    pCol = &pNew->aCol[pNew->nCol-1];
107476    pDflt = pCol->pDflt;
107477    pTab = sqlite3FindTable(db, zTab, zDb);
107478    assert( pTab );
107479  
107480  #ifndef SQLITE_OMIT_AUTHORIZATION
107481    /* Invoke the authorization callback. */
107482    if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
107483      return;
107484    }
107485  #endif
107486  
107487    /* If the default value for the new column was specified with a 
107488    ** literal NULL, then set pDflt to 0. This simplifies checking
107489    ** for an SQL NULL default below.
107490    */
107491    assert( pDflt==0 || pDflt->op==TK_SPAN );
107492    if( pDflt && pDflt->pLeft->op==TK_NULL ){
107493      pDflt = 0;
107494    }
107495  
107496    /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
107497    ** If there is a NOT NULL constraint, then the default value for the
107498    ** column must not be NULL.
107499    */
107500    if( pCol->colFlags & COLFLAG_PRIMKEY ){
107501      sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
107502      return;
107503    }
107504    if( pNew->pIndex ){
107505      sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
107506      return;
107507    }
107508    if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
107509      sqlite3ErrorMsg(pParse, 
107510          "Cannot add a REFERENCES column with non-NULL default value");
107511      return;
107512    }
107513    if( pCol->notNull && !pDflt ){
107514      sqlite3ErrorMsg(pParse, 
107515          "Cannot add a NOT NULL column with default value NULL");
107516      return;
107517    }
107518  
107519    /* Ensure the default expression is something that sqlite3ValueFromExpr()
107520    ** can handle (i.e. not CURRENT_TIME etc.)
107521    */
107522    if( pDflt ){
107523      sqlite3_value *pVal = 0;
107524      int rc;
107525      rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
107526      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
107527      if( rc!=SQLITE_OK ){
107528        assert( db->mallocFailed == 1 );
107529        return;
107530      }
107531      if( !pVal ){
107532        sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
107533        return;
107534      }
107535      sqlite3ValueFree(pVal);
107536    }
107537  
107538    /* Modify the CREATE TABLE statement. */
107539    zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
107540    if( zCol ){
107541      char *zEnd = &zCol[pColDef->n-1];
107542      u32 savedDbFlags = db->mDbFlags;
107543      while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
107544        *zEnd-- = '\0';
107545      }
107546      db->mDbFlags |= DBFLAG_PreferBuiltin;
107547      sqlite3NestedParse(pParse, 
107548          "UPDATE \"%w\".%s SET "
107549            "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
107550          "WHERE type = 'table' AND name = %Q", 
107551        zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
107552        zTab
107553      );
107554      sqlite3DbFree(db, zCol);
107555      db->mDbFlags = savedDbFlags;
107556    }
107557  
107558    /* Make sure the schema version is at least 3.  But do not upgrade
107559    ** from less than 3 to 4, as that will corrupt any preexisting DESC
107560    ** index.
107561    */
107562    v = sqlite3GetVdbe(pParse);
107563    if( v ){
107564      r1 = sqlite3GetTempReg(pParse);
107565      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
107566      sqlite3VdbeUsesBtree(v, iDb);
107567      sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
107568      sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
107569      VdbeCoverage(v);
107570      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
107571      sqlite3ReleaseTempReg(pParse, r1);
107572    }
107573  
107574    /* Reload the table definition */
107575    renameReloadSchema(pParse, iDb);
107576  }
107577  
107578  /*
107579  ** This function is called by the parser after the table-name in
107580  ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
107581  ** pSrc is the full-name of the table being altered.
107582  **
107583  ** This routine makes a (partial) copy of the Table structure
107584  ** for the table being altered and sets Parse.pNewTable to point
107585  ** to it. Routines called by the parser as the column definition
107586  ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
107587  ** the copy. The copy of the Table structure is deleted by tokenize.c 
107588  ** after parsing is finished.
107589  **
107590  ** Routine sqlite3AlterFinishAddColumn() will be called to complete
107591  ** coding the "ALTER TABLE ... ADD" statement.
107592  */
107593  SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
107594    Table *pNew;
107595    Table *pTab;
107596    int iDb;
107597    int i;
107598    int nAlloc;
107599    sqlite3 *db = pParse->db;
107600  
107601    /* Look up the table being altered. */
107602    assert( pParse->pNewTable==0 );
107603    assert( sqlite3BtreeHoldsAllMutexes(db) );
107604    if( db->mallocFailed ) goto exit_begin_add_column;
107605    pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
107606    if( !pTab ) goto exit_begin_add_column;
107607  
107608  #ifndef SQLITE_OMIT_VIRTUALTABLE
107609    if( IsVirtual(pTab) ){
107610      sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
107611      goto exit_begin_add_column;
107612    }
107613  #endif
107614  
107615    /* Make sure this is not an attempt to ALTER a view. */
107616    if( pTab->pSelect ){
107617      sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
107618      goto exit_begin_add_column;
107619    }
107620    if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
107621      goto exit_begin_add_column;
107622    }
107623  
107624    assert( pTab->addColOffset>0 );
107625    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107626  
107627    /* Put a copy of the Table struct in Parse.pNewTable for the
107628    ** sqlite3AddColumn() function and friends to modify.  But modify
107629    ** the name by adding an "sqlite_altertab_" prefix.  By adding this
107630    ** prefix, we insure that the name will not collide with an existing
107631    ** table because user table are not allowed to have the "sqlite_"
107632    ** prefix on their name.
107633    */
107634    pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
107635    if( !pNew ) goto exit_begin_add_column;
107636    pParse->pNewTable = pNew;
107637    pNew->nTabRef = 1;
107638    pNew->nCol = pTab->nCol;
107639    assert( pNew->nCol>0 );
107640    nAlloc = (((pNew->nCol-1)/8)*8)+8;
107641    assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
107642    pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
107643    pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
107644    if( !pNew->aCol || !pNew->zName ){
107645      assert( db->mallocFailed );
107646      goto exit_begin_add_column;
107647    }
107648    memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
107649    for(i=0; i<pNew->nCol; i++){
107650      Column *pCol = &pNew->aCol[i];
107651      pCol->zName = sqlite3DbStrDup(db, pCol->zName);
107652      pCol->zColl = 0;
107653      pCol->pDflt = 0;
107654    }
107655    pNew->pSchema = db->aDb[iDb].pSchema;
107656    pNew->addColOffset = pTab->addColOffset;
107657    pNew->nTabRef = 1;
107658  
107659  exit_begin_add_column:
107660    sqlite3SrcListDelete(db, pSrc);
107661    return;
107662  }
107663  
107664  /*
107665  ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
107666  ** command. This function checks if the table is a view or virtual
107667  ** table (columns of views or virtual tables may not be renamed). If so,
107668  ** it loads an error message into pParse and returns non-zero.
107669  **
107670  ** Or, if pTab is not a view or virtual table, zero is returned.
107671  */
107672  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
107673  static int isRealTable(Parse *pParse, Table *pTab){
107674    const char *zType = 0;
107675  #ifndef SQLITE_OMIT_VIEW
107676    if( pTab->pSelect ){
107677      zType = "view";
107678    }
107679  #endif
107680  #ifndef SQLITE_OMIT_VIRTUALTABLE
107681    if( IsVirtual(pTab) ){
107682      zType = "virtual table";
107683    }
107684  #endif
107685    if( zType ){
107686      sqlite3ErrorMsg(
107687          pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
107688      );
107689      return 1;
107690    }
107691    return 0;
107692  }
107693  #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
107694  # define isRealTable(x,y) (0)
107695  #endif
107696  
107697  /*
107698  ** Handles the following parser reduction:
107699  **
107700  **  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
107701  */
107702  SQLITE_PRIVATE void sqlite3AlterRenameColumn(
107703    Parse *pParse,                  /* Parsing context */
107704    SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */
107705    Token *pOld,                    /* Name of column being changed */
107706    Token *pNew                     /* New column name */
107707  ){
107708    sqlite3 *db = pParse->db;       /* Database connection */
107709    Table *pTab;                    /* Table being updated */
107710    int iCol;                       /* Index of column being renamed */
107711    char *zOld = 0;                 /* Old column name */
107712    char *zNew = 0;                 /* New column name */
107713    const char *zDb;                /* Name of schema containing the table */
107714    int iSchema;                    /* Index of the schema */
107715    int bQuote;                     /* True to quote the new name */
107716  
107717    /* Locate the table to be altered */
107718    pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
107719    if( !pTab ) goto exit_rename_column;
107720  
107721    /* Cannot alter a system table */
107722    if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
107723    if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
107724  
107725    /* Which schema holds the table to be altered */  
107726    iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
107727    assert( iSchema>=0 );
107728    zDb = db->aDb[iSchema].zDbSName;
107729  
107730  #ifndef SQLITE_OMIT_AUTHORIZATION
107731    /* Invoke the authorization callback. */
107732    if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
107733      goto exit_rename_column;
107734    }
107735  #endif
107736  
107737    /* Make sure the old name really is a column name in the table to be
107738    ** altered.  Set iCol to be the index of the column being renamed */
107739    zOld = sqlite3NameFromToken(db, pOld);
107740    if( !zOld ) goto exit_rename_column;
107741    for(iCol=0; iCol<pTab->nCol; iCol++){
107742      if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
107743    }
107744    if( iCol==pTab->nCol ){
107745      sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
107746      goto exit_rename_column;
107747    }
107748  
107749    /* Do the rename operation using a recursive UPDATE statement that
107750    ** uses the sqlite_rename_column() SQL function to compute the new
107751    ** CREATE statement text for the sqlite_master table.
107752    */
107753    zNew = sqlite3NameFromToken(db, pNew);
107754    if( !zNew ) goto exit_rename_column;
107755    assert( pNew->n>0 );
107756    bQuote = sqlite3Isquote(pNew->z[0]);
107757    sqlite3NestedParse(pParse, 
107758        "UPDATE \"%w\".%s SET "
107759        "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
107760        "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
107761        " AND sql NOT LIKE 'create virtual%%'",
107762        zDb, MASTER_NAME, 
107763        zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
107764        pTab->zName
107765    );
107766  
107767    sqlite3NestedParse(pParse, 
107768        "UPDATE temp.%s SET "
107769        "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
107770        "WHERE type IN ('trigger', 'view')",
107771        MASTER_NAME, 
107772        zDb, pTab->zName, iCol, zNew, bQuote
107773    );
107774  
107775    /* Drop and reload the database schema. */
107776    renameReloadSchema(pParse, iSchema);
107777    renameTestSchema(pParse, zDb, iSchema==1);
107778  
107779   exit_rename_column:
107780    sqlite3SrcListDelete(db, pSrc);
107781    sqlite3DbFree(db, zOld);
107782    sqlite3DbFree(db, zNew);
107783    return;
107784  }
107785  
107786  /*
107787  ** Each RenameToken object maps an element of the parse tree into
107788  ** the token that generated that element.  The parse tree element
107789  ** might be one of:
107790  **
107791  **     *  A pointer to an Expr that represents an ID
107792  **     *  The name of a table column in Column.zName
107793  **
107794  ** A list of RenameToken objects can be constructed during parsing.
107795  ** Each new object is created by sqlite3RenameTokenMap().
107796  ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
107797  ** routine is used to keep the mapping current.
107798  **
107799  ** After the parse finishes, renameTokenFind() routine can be used
107800  ** to look up the actual token value that created some element in
107801  ** the parse tree.
107802  */
107803  struct RenameToken {
107804    void *p;               /* Parse tree element created by token t */
107805    Token t;               /* The token that created parse tree element p */
107806    RenameToken *pNext;    /* Next is a list of all RenameToken objects */
107807  };
107808  
107809  /*
107810  ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
107811  ** down into the Walker.
107812  */
107813  typedef struct RenameCtx RenameCtx;
107814  struct RenameCtx {
107815    RenameToken *pList;             /* List of tokens to overwrite */
107816    int nList;                      /* Number of tokens in pList */
107817    int iCol;                       /* Index of column being renamed */
107818    Table *pTab;                    /* Table being ALTERed */ 
107819    const char *zOld;               /* Old column name */
107820  };
107821  
107822  #ifdef SQLITE_DEBUG
107823  /*
107824  ** This function is only for debugging. It performs two tasks:
107825  **
107826  **   1. Checks that pointer pPtr does not already appear in the 
107827  **      rename-token list.
107828  **
107829  **   2. Dereferences each pointer in the rename-token list.
107830  **
107831  ** The second is most effective when debugging under valgrind or
107832  ** address-sanitizer or similar. If any of these pointers no longer 
107833  ** point to valid objects, an exception is raised by the memory-checking 
107834  ** tool.
107835  **
107836  ** The point of this is to prevent comparisons of invalid pointer values.
107837  ** Even though this always seems to work, it is undefined according to the
107838  ** C standard. Example of undefined comparison:
107839  **
107840  **     sqlite3_free(x);
107841  **     if( x==y ) ...
107842  **
107843  ** Technically, as x no longer points into a valid object or to the byte
107844  ** following a valid object, it may not be used in comparison operations.
107845  */
107846  static void renameTokenCheckAll(Parse *pParse, void *pPtr){
107847    if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
107848      RenameToken *p;
107849      u8 i = 0;
107850      for(p=pParse->pRename; p; p=p->pNext){
107851        if( p->p ){
107852          assert( p->p!=pPtr );
107853          i += *(u8*)(p->p);
107854        }
107855      }
107856    }
107857  }
107858  #else
107859  # define renameTokenCheckAll(x,y)
107860  #endif
107861  
107862  /*
107863  ** Remember that the parser tree element pPtr was created using
107864  ** the token pToken.
107865  **
107866  ** In other words, construct a new RenameToken object and add it
107867  ** to the list of RenameToken objects currently being built up
107868  ** in pParse->pRename.
107869  **
107870  ** The pPtr argument is returned so that this routine can be used
107871  ** with tail recursion in tokenExpr() routine, for a small performance
107872  ** improvement.
107873  */
107874  SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
107875    RenameToken *pNew;
107876    assert( pPtr || pParse->db->mallocFailed );
107877    renameTokenCheckAll(pParse, pPtr);
107878    pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
107879    if( pNew ){
107880      pNew->p = pPtr;
107881      pNew->t = *pToken;
107882      pNew->pNext = pParse->pRename;
107883      pParse->pRename = pNew;
107884    }
107885  
107886    return pPtr;
107887  }
107888  
107889  /*
107890  ** It is assumed that there is already a RenameToken object associated
107891  ** with parse tree element pFrom. This function remaps the associated token
107892  ** to parse tree element pTo.
107893  */
107894  SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
107895    RenameToken *p;
107896    renameTokenCheckAll(pParse, pTo);
107897    for(p=pParse->pRename; p; p=p->pNext){
107898      if( p->p==pFrom ){
107899        p->p = pTo;
107900        break;
107901      }
107902    }
107903  }
107904  
107905  /*
107906  ** Walker callback used by sqlite3RenameExprUnmap().
107907  */
107908  static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
107909    Parse *pParse = pWalker->pParse;
107910    sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
107911    return WRC_Continue;
107912  }
107913  
107914  /*
107915  ** Remove all nodes that are part of expression pExpr from the rename list.
107916  */
107917  SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
107918    Walker sWalker;
107919    memset(&sWalker, 0, sizeof(Walker));
107920    sWalker.pParse = pParse;
107921    sWalker.xExprCallback = renameUnmapExprCb;
107922    sqlite3WalkExpr(&sWalker, pExpr);
107923  }
107924  
107925  /*
107926  ** Remove all nodes that are part of expression-list pEList from the 
107927  ** rename list.
107928  */
107929  SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
107930    if( pEList ){
107931      int i;
107932      Walker sWalker;
107933      memset(&sWalker, 0, sizeof(Walker));
107934      sWalker.pParse = pParse;
107935      sWalker.xExprCallback = renameUnmapExprCb;
107936      sqlite3WalkExprList(&sWalker, pEList);
107937      for(i=0; i<pEList->nExpr; i++){
107938        sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
107939      }
107940    }
107941  }
107942  
107943  /*
107944  ** Free the list of RenameToken objects given in the second argument
107945  */
107946  static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
107947    RenameToken *pNext;
107948    RenameToken *p;
107949    for(p=pToken; p; p=pNext){
107950      pNext = p->pNext;
107951      sqlite3DbFree(db, p);
107952    }
107953  }
107954  
107955  /*
107956  ** Search the Parse object passed as the first argument for a RenameToken
107957  ** object associated with parse tree element pPtr. If found, remove it
107958  ** from the Parse object and add it to the list maintained by the
107959  ** RenameCtx object passed as the second argument.
107960  */
107961  static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
107962    RenameToken **pp;
107963    assert( pPtr!=0 );
107964    for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
107965      if( (*pp)->p==pPtr ){
107966        RenameToken *pToken = *pp;
107967        *pp = pToken->pNext;
107968        pToken->pNext = pCtx->pList;
107969        pCtx->pList = pToken;
107970        pCtx->nList++;
107971        break;
107972      }
107973    }
107974  }
107975  
107976  /*
107977  ** Iterate through the Select objects that are part of WITH clauses attached
107978  ** to select statement pSelect.
107979  */
107980  static void renameWalkWith(Walker *pWalker, Select *pSelect){
107981    if( pSelect->pWith ){
107982      int i;
107983      for(i=0; i<pSelect->pWith->nCte; i++){
107984        Select *p = pSelect->pWith->a[i].pSelect;
107985        NameContext sNC;
107986        memset(&sNC, 0, sizeof(sNC));
107987        sNC.pParse = pWalker->pParse;
107988        sqlite3SelectPrep(sNC.pParse, p, &sNC);
107989        sqlite3WalkSelect(pWalker, p);
107990      }
107991    }
107992  }
107993  
107994  /*
107995  ** This is a Walker select callback. It does nothing. It is only required
107996  ** because without a dummy callback, sqlite3WalkExpr() and similar do not
107997  ** descend into sub-select statements.
107998  */
107999  static int renameColumnSelectCb(Walker *pWalker, Select *p){
108000    renameWalkWith(pWalker, p);
108001    return WRC_Continue;
108002  }
108003  
108004  /*
108005  ** This is a Walker expression callback.
108006  **
108007  ** For every TK_COLUMN node in the expression tree, search to see
108008  ** if the column being references is the column being renamed by an
108009  ** ALTER TABLE statement.  If it is, then attach its associated
108010  ** RenameToken object to the list of RenameToken objects being
108011  ** constructed in RenameCtx object at pWalker->u.pRename.
108012  */
108013  static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
108014    RenameCtx *p = pWalker->u.pRename;
108015    if( pExpr->op==TK_TRIGGER 
108016     && pExpr->iColumn==p->iCol 
108017     && pWalker->pParse->pTriggerTab==p->pTab
108018    ){
108019      renameTokenFind(pWalker->pParse, p, (void*)pExpr);
108020    }else if( pExpr->op==TK_COLUMN 
108021     && pExpr->iColumn==p->iCol 
108022     && p->pTab==pExpr->y.pTab
108023    ){
108024      renameTokenFind(pWalker->pParse, p, (void*)pExpr);
108025    }
108026    return WRC_Continue;
108027  }
108028  
108029  /*
108030  ** The RenameCtx contains a list of tokens that reference a column that
108031  ** is being renamed by an ALTER TABLE statement.  Return the "last"
108032  ** RenameToken in the RenameCtx and remove that RenameToken from the
108033  ** RenameContext.  "Last" means the last RenameToken encountered when
108034  ** the input SQL is parsed from left to right.  Repeated calls to this routine
108035  ** return all column name tokens in the order that they are encountered
108036  ** in the SQL statement.
108037  */
108038  static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
108039    RenameToken *pBest = pCtx->pList;
108040    RenameToken *pToken;
108041    RenameToken **pp;
108042  
108043    for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
108044      if( pToken->t.z>pBest->t.z ) pBest = pToken;
108045    }
108046    for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
108047    *pp = pBest->pNext;
108048  
108049    return pBest;
108050  }
108051  
108052  /*
108053  ** An error occured while parsing or otherwise processing a database
108054  ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
108055  ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
108056  ** sub-routine is currently stored in pParse->zErrMsg. This function
108057  ** adds context to the error message and then stores it in pCtx.
108058  */
108059  static void renameColumnParseError(
108060    sqlite3_context *pCtx, 
108061    int bPost,
108062    sqlite3_value *pType,
108063    sqlite3_value *pObject,
108064    Parse *pParse
108065  ){
108066    const char *zT = (const char*)sqlite3_value_text(pType);
108067    const char *zN = (const char*)sqlite3_value_text(pObject);
108068    char *zErr;
108069  
108070    zErr = sqlite3_mprintf("error in %s %s%s: %s", 
108071        zT, zN, (bPost ? " after rename" : ""),
108072        pParse->zErrMsg
108073    );
108074    sqlite3_result_error(pCtx, zErr, -1);
108075    sqlite3_free(zErr);
108076  }
108077  
108078  /*
108079  ** For each name in the the expression-list pEList (i.e. each
108080  ** pEList->a[i].zName) that matches the string in zOld, extract the 
108081  ** corresponding rename-token from Parse object pParse and add it
108082  ** to the RenameCtx pCtx.
108083  */
108084  static void renameColumnElistNames(
108085    Parse *pParse, 
108086    RenameCtx *pCtx, 
108087    ExprList *pEList, 
108088    const char *zOld
108089  ){
108090    if( pEList ){
108091      int i;
108092      for(i=0; i<pEList->nExpr; i++){
108093        char *zName = pEList->a[i].zName;
108094        if( 0==sqlite3_stricmp(zName, zOld) ){
108095          renameTokenFind(pParse, pCtx, (void*)zName);
108096        }
108097      }
108098    }
108099  }
108100  
108101  /*
108102  ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) 
108103  ** that matches the string in zOld, extract the corresponding rename-token 
108104  ** from Parse object pParse and add it to the RenameCtx pCtx.
108105  */
108106  static void renameColumnIdlistNames(
108107    Parse *pParse, 
108108    RenameCtx *pCtx, 
108109    IdList *pIdList, 
108110    const char *zOld
108111  ){
108112    if( pIdList ){
108113      int i;
108114      for(i=0; i<pIdList->nId; i++){
108115        char *zName = pIdList->a[i].zName;
108116        if( 0==sqlite3_stricmp(zName, zOld) ){
108117          renameTokenFind(pParse, pCtx, (void*)zName);
108118        }
108119      }
108120    }
108121  }
108122  
108123  /*
108124  ** Parse the SQL statement zSql using Parse object (*p). The Parse object
108125  ** is initialized by this function before it is used.
108126  */
108127  static int renameParseSql(
108128    Parse *p,                       /* Memory to use for Parse object */
108129    const char *zDb,                /* Name of schema SQL belongs to */
108130    int bTable,                     /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
108131    sqlite3 *db,                    /* Database handle */
108132    const char *zSql,               /* SQL to parse */
108133    int bTemp                       /* True if SQL is from temp schema */
108134  ){
108135    int rc;
108136    char *zErr = 0;
108137  
108138    db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
108139  
108140    /* Parse the SQL statement passed as the first argument. If no error
108141    ** occurs and the parse does not result in a new table, index or
108142    ** trigger object, the database must be corrupt. */
108143    memset(p, 0, sizeof(Parse));
108144    p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
108145    p->db = db;
108146    p->nQueryLoop = 1;
108147    rc = sqlite3RunParser(p, zSql, &zErr);
108148    assert( p->zErrMsg==0 );
108149    assert( rc!=SQLITE_OK || zErr==0 );
108150    p->zErrMsg = zErr;
108151    if( db->mallocFailed ) rc = SQLITE_NOMEM;
108152    if( rc==SQLITE_OK 
108153     && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 
108154    ){
108155      rc = SQLITE_CORRUPT_BKPT;
108156    }
108157  
108158  #ifdef SQLITE_DEBUG
108159    /* Ensure that all mappings in the Parse.pRename list really do map to
108160    ** a part of the input string.  */
108161    if( rc==SQLITE_OK ){
108162      int nSql = sqlite3Strlen30(zSql);
108163      RenameToken *pToken;
108164      for(pToken=p->pRename; pToken; pToken=pToken->pNext){
108165        assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
108166      }
108167    }
108168  #endif
108169  
108170    db->init.iDb = 0;
108171    return rc;
108172  }
108173  
108174  /*
108175  ** This function edits SQL statement zSql, replacing each token identified
108176  ** by the linked list pRename with the text of zNew. If argument bQuote is
108177  ** true, then zNew is always quoted first. If no error occurs, the result
108178  ** is loaded into context object pCtx as the result.
108179  **
108180  ** Or, if an error occurs (i.e. an OOM condition), an error is left in
108181  ** pCtx and an SQLite error code returned.
108182  */
108183  static int renameEditSql(
108184    sqlite3_context *pCtx,          /* Return result here */
108185    RenameCtx *pRename,             /* Rename context */
108186    const char *zSql,               /* SQL statement to edit */
108187    const char *zNew,               /* New token text */
108188    int bQuote                      /* True to always quote token */
108189  ){
108190    int nNew = sqlite3Strlen30(zNew);
108191    int nSql = sqlite3Strlen30(zSql);
108192    sqlite3 *db = sqlite3_context_db_handle(pCtx);
108193    int rc = SQLITE_OK;
108194    char *zQuot;
108195    char *zOut;
108196    int nQuot;
108197  
108198    /* Set zQuot to point to a buffer containing a quoted copy of the 
108199    ** identifier zNew. If the corresponding identifier in the original 
108200    ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
108201    ** point to zQuot so that all substitutions are made using the
108202    ** quoted version of the new column name.  */
108203    zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
108204    if( zQuot==0 ){
108205      return SQLITE_NOMEM;
108206    }else{
108207      nQuot = sqlite3Strlen30(zQuot);
108208    }
108209    if( bQuote ){
108210      zNew = zQuot;
108211      nNew = nQuot;
108212    }
108213  
108214    /* At this point pRename->pList contains a list of RenameToken objects
108215    ** corresponding to all tokens in the input SQL that must be replaced
108216    ** with the new column name. All that remains is to construct and
108217    ** return the edited SQL string. */
108218    assert( nQuot>=nNew );
108219    zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
108220    if( zOut ){
108221      int nOut = nSql;
108222      memcpy(zOut, zSql, nSql);
108223      while( pRename->pList ){
108224        int iOff;                   /* Offset of token to replace in zOut */
108225        RenameToken *pBest = renameColumnTokenNext(pRename);
108226  
108227        u32 nReplace;
108228        const char *zReplace;
108229        if( sqlite3IsIdChar(*pBest->t.z) ){
108230          nReplace = nNew;
108231          zReplace = zNew;
108232        }else{
108233          nReplace = nQuot;
108234          zReplace = zQuot;
108235        }
108236  
108237        iOff = pBest->t.z - zSql;
108238        if( pBest->t.n!=nReplace ){
108239          memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], 
108240              nOut - (iOff + pBest->t.n)
108241          );
108242          nOut += nReplace - pBest->t.n;
108243          zOut[nOut] = '\0';
108244        }
108245        memcpy(&zOut[iOff], zReplace, nReplace);
108246        sqlite3DbFree(db, pBest);
108247      }
108248  
108249      sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
108250      sqlite3DbFree(db, zOut);
108251    }else{
108252      rc = SQLITE_NOMEM;
108253    }
108254  
108255    sqlite3_free(zQuot);
108256    return rc;
108257  }
108258  
108259  /*
108260  ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
108261  ** it was read from the schema of database zDb. Return SQLITE_OK if 
108262  ** successful. Otherwise, return an SQLite error code and leave an error
108263  ** message in the Parse object.
108264  */
108265  static int renameResolveTrigger(Parse *pParse, const char *zDb){
108266    sqlite3 *db = pParse->db;
108267    Trigger *pNew = pParse->pNewTrigger;
108268    TriggerStep *pStep;
108269    NameContext sNC;
108270    int rc = SQLITE_OK;
108271  
108272    memset(&sNC, 0, sizeof(sNC));
108273    sNC.pParse = pParse;
108274    assert( pNew->pTabSchema );
108275    pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, 
108276        db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
108277    );
108278    pParse->eTriggerOp = pNew->op;
108279    /* ALWAYS() because if the table of the trigger does not exist, the
108280    ** error would have been hit before this point */
108281    if( ALWAYS(pParse->pTriggerTab) ){
108282      rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
108283    }
108284  
108285    /* Resolve symbols in WHEN clause */
108286    if( rc==SQLITE_OK && pNew->pWhen ){
108287      rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
108288    }
108289  
108290    for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
108291      if( pStep->pSelect ){
108292        sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
108293        if( pParse->nErr ) rc = pParse->rc;
108294      }
108295      if( rc==SQLITE_OK && pStep->zTarget ){
108296        Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
108297        if( pTarget==0 ){
108298          rc = SQLITE_ERROR;
108299        }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
108300          SrcList sSrc;
108301          memset(&sSrc, 0, sizeof(sSrc));
108302          sSrc.nSrc = 1;
108303          sSrc.a[0].zName = pStep->zTarget;
108304          sSrc.a[0].pTab = pTarget;
108305          sNC.pSrcList = &sSrc;
108306          if( pStep->pWhere ){
108307            rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
108308          }
108309          if( rc==SQLITE_OK ){
108310            rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
108311          }
108312          assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
108313          if( pStep->pUpsert ){
108314            Upsert *pUpsert = pStep->pUpsert;
108315            assert( rc==SQLITE_OK );
108316            pUpsert->pUpsertSrc = &sSrc;
108317            sNC.uNC.pUpsert = pUpsert;
108318            sNC.ncFlags = NC_UUpsert;
108319            rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
108320            if( rc==SQLITE_OK ){
108321              ExprList *pUpsertSet = pUpsert->pUpsertSet;
108322              rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
108323            }
108324            if( rc==SQLITE_OK ){
108325              rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
108326            }
108327            if( rc==SQLITE_OK ){
108328              rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
108329            }
108330            sNC.ncFlags = 0;
108331          }
108332          sNC.pSrcList = 0;
108333        }
108334      }
108335    }
108336    return rc;
108337  }
108338  
108339  /*
108340  ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
108341  ** objects that are part of the trigger passed as the second argument.
108342  */
108343  static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
108344    TriggerStep *pStep;
108345  
108346    /* Find tokens to edit in WHEN clause */
108347    sqlite3WalkExpr(pWalker, pTrigger->pWhen);
108348  
108349    /* Find tokens to edit in trigger steps */
108350    for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
108351      sqlite3WalkSelect(pWalker, pStep->pSelect);
108352      sqlite3WalkExpr(pWalker, pStep->pWhere);
108353      sqlite3WalkExprList(pWalker, pStep->pExprList);
108354      if( pStep->pUpsert ){
108355        Upsert *pUpsert = pStep->pUpsert;
108356        sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
108357        sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
108358        sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
108359        sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
108360      }
108361    }
108362  }
108363  
108364  /*
108365  ** Free the contents of Parse object (*pParse). Do not free the memory
108366  ** occupied by the Parse object itself.
108367  */
108368  static void renameParseCleanup(Parse *pParse){
108369    sqlite3 *db = pParse->db;
108370    Index *pIdx;
108371    if( pParse->pVdbe ){
108372      sqlite3VdbeFinalize(pParse->pVdbe);
108373    }
108374    sqlite3DeleteTable(db, pParse->pNewTable);
108375    while( (pIdx = pParse->pNewIndex)!=0 ){
108376      pParse->pNewIndex = pIdx->pNext;
108377      sqlite3FreeIndex(db, pIdx);
108378    }
108379    sqlite3DeleteTrigger(db, pParse->pNewTrigger);
108380    sqlite3DbFree(db, pParse->zErrMsg);
108381    renameTokenFree(db, pParse->pRename);
108382    sqlite3ParserReset(pParse);
108383  }
108384  
108385  /*
108386  ** SQL function:
108387  **
108388  **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
108389  **
108390  **   0. zSql:     SQL statement to rewrite
108391  **   1. type:     Type of object ("table", "view" etc.)
108392  **   2. object:   Name of object
108393  **   3. Database: Database name (e.g. "main")
108394  **   4. Table:    Table name
108395  **   5. iCol:     Index of column to rename
108396  **   6. zNew:     New column name
108397  **   7. bQuote:   Non-zero if the new column name should be quoted.
108398  **   8. bTemp:    True if zSql comes from temp schema
108399  **
108400  ** Do a column rename operation on the CREATE statement given in zSql.
108401  ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
108402  ** into zNew.  The name should be quoted if bQuote is true.
108403  **
108404  ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
108405  ** It is only accessible to SQL created using sqlite3NestedParse().  It is
108406  ** not reachable from ordinary SQL passed into sqlite3_prepare().
108407  */
108408  static void renameColumnFunc(
108409    sqlite3_context *context,
108410    int NotUsed,
108411    sqlite3_value **argv
108412  ){
108413    sqlite3 *db = sqlite3_context_db_handle(context);
108414    RenameCtx sCtx;
108415    const char *zSql = (const char*)sqlite3_value_text(argv[0]);
108416    const char *zDb = (const char*)sqlite3_value_text(argv[3]);
108417    const char *zTable = (const char*)sqlite3_value_text(argv[4]);
108418    int iCol = sqlite3_value_int(argv[5]);
108419    const char *zNew = (const char*)sqlite3_value_text(argv[6]);
108420    int bQuote = sqlite3_value_int(argv[7]);
108421    int bTemp = sqlite3_value_int(argv[8]);
108422    const char *zOld;
108423    int rc;
108424    Parse sParse;
108425    Walker sWalker;
108426    Index *pIdx;
108427    int i;
108428    Table *pTab;
108429  #ifndef SQLITE_OMIT_AUTHORIZATION
108430    sqlite3_xauth xAuth = db->xAuth;
108431  #endif
108432  
108433    UNUSED_PARAMETER(NotUsed);
108434    if( zSql==0 ) return;
108435    if( zTable==0 ) return;
108436    if( zNew==0 ) return;
108437    if( iCol<0 ) return;
108438    sqlite3BtreeEnterAll(db);
108439    pTab = sqlite3FindTable(db, zTable, zDb);
108440    if( pTab==0 || iCol>=pTab->nCol ){
108441      sqlite3BtreeLeaveAll(db);
108442      return;
108443    }
108444    zOld = pTab->aCol[iCol].zName;
108445    memset(&sCtx, 0, sizeof(sCtx));
108446    sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
108447  
108448  #ifndef SQLITE_OMIT_AUTHORIZATION
108449    db->xAuth = 0;
108450  #endif
108451    rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
108452  
108453    /* Find tokens that need to be replaced. */
108454    memset(&sWalker, 0, sizeof(Walker));
108455    sWalker.pParse = &sParse;
108456    sWalker.xExprCallback = renameColumnExprCb;
108457    sWalker.xSelectCallback = renameColumnSelectCb;
108458    sWalker.u.pRename = &sCtx;
108459  
108460    sCtx.pTab = pTab;
108461    if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
108462    if( sParse.pNewTable ){
108463      Select *pSelect = sParse.pNewTable->pSelect;
108464      if( pSelect ){
108465        sParse.rc = SQLITE_OK;
108466        sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
108467        rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
108468        if( rc==SQLITE_OK ){
108469          sqlite3WalkSelect(&sWalker, pSelect);
108470        }
108471        if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
108472      }else{
108473        /* A regular table */
108474        int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
108475        FKey *pFKey;
108476        assert( sParse.pNewTable->pSelect==0 );
108477        sCtx.pTab = sParse.pNewTable;
108478        if( bFKOnly==0 ){
108479          renameTokenFind(
108480              &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
108481          );
108482          if( sCtx.iCol<0 ){
108483            renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
108484          }
108485          sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
108486          for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
108487            sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
108488          }
108489          for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
108490            sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
108491          }
108492        }
108493  
108494        for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
108495          for(i=0; i<pFKey->nCol; i++){
108496            if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
108497              renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
108498            }
108499            if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
108500             && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
108501            ){
108502              renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
108503            }
108504          }
108505        }
108506      }
108507    }else if( sParse.pNewIndex ){
108508      sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
108509      sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
108510    }else{
108511      /* A trigger */
108512      TriggerStep *pStep;
108513      rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
108514      if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
108515  
108516      for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
108517        if( pStep->zTarget ){ 
108518          Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
108519          if( pTarget==pTab ){
108520            if( pStep->pUpsert ){
108521              ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
108522              renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
108523            }
108524            renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
108525            renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
108526          }
108527        }
108528      }
108529  
108530  
108531      /* Find tokens to edit in UPDATE OF clause */
108532      if( sParse.pTriggerTab==pTab ){
108533        renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
108534      }
108535  
108536      /* Find tokens to edit in various expressions and selects */
108537      renameWalkTrigger(&sWalker, sParse.pNewTrigger);
108538    }
108539  
108540    assert( rc==SQLITE_OK );
108541    rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
108542  
108543  renameColumnFunc_done:
108544    if( rc!=SQLITE_OK ){
108545      if( sParse.zErrMsg ){
108546        renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
108547      }else{
108548        sqlite3_result_error_code(context, rc);
108549      }
108550    }
108551  
108552    renameParseCleanup(&sParse);
108553    renameTokenFree(db, sCtx.pList);
108554  #ifndef SQLITE_OMIT_AUTHORIZATION
108555    db->xAuth = xAuth;
108556  #endif
108557    sqlite3BtreeLeaveAll(db);
108558  }
108559  
108560  /*
108561  ** Walker expression callback used by "RENAME TABLE". 
108562  */
108563  static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
108564    RenameCtx *p = pWalker->u.pRename;
108565    if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
108566      renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
108567    }
108568    return WRC_Continue;
108569  }
108570  
108571  /*
108572  ** Walker select callback used by "RENAME TABLE". 
108573  */
108574  static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
108575    int i;
108576    RenameCtx *p = pWalker->u.pRename;
108577    SrcList *pSrc = pSelect->pSrc;
108578    if( pSrc==0 ){
108579      assert( pWalker->pParse->db->mallocFailed );
108580      return WRC_Abort;
108581    }
108582    for(i=0; i<pSrc->nSrc; i++){
108583      struct SrcList_item *pItem = &pSrc->a[i];
108584      if( pItem->pTab==p->pTab ){
108585        renameTokenFind(pWalker->pParse, p, pItem->zName);
108586      }
108587    }
108588    renameWalkWith(pWalker, pSelect);
108589  
108590    return WRC_Continue;
108591  }
108592  
108593  
108594  /*
108595  ** This C function implements an SQL user function that is used by SQL code
108596  ** generated by the ALTER TABLE ... RENAME command to modify the definition
108597  ** of any foreign key constraints that use the table being renamed as the 
108598  ** parent table. It is passed three arguments:
108599  **
108600  **   0: The database containing the table being renamed.
108601  **   1. type:     Type of object ("table", "view" etc.)
108602  **   2. object:   Name of object
108603  **   3: The complete text of the schema statement being modified,
108604  **   4: The old name of the table being renamed, and
108605  **   5: The new name of the table being renamed.
108606  **   6: True if the schema statement comes from the temp db.
108607  **
108608  ** It returns the new schema statement. For example:
108609  **
108610  ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
108611  **       -> 'CREATE TABLE t1(a REFERENCES t3)'
108612  */
108613  static void renameTableFunc(
108614    sqlite3_context *context,
108615    int NotUsed,
108616    sqlite3_value **argv
108617  ){
108618    sqlite3 *db = sqlite3_context_db_handle(context);
108619    const char *zDb = (const char*)sqlite3_value_text(argv[0]);
108620    const char *zInput = (const char*)sqlite3_value_text(argv[3]);
108621    const char *zOld = (const char*)sqlite3_value_text(argv[4]);
108622    const char *zNew = (const char*)sqlite3_value_text(argv[5]);
108623    int bTemp = sqlite3_value_int(argv[6]);
108624    UNUSED_PARAMETER(NotUsed);
108625  
108626    if( zInput && zOld && zNew ){
108627      Parse sParse;
108628      int rc;
108629      int bQuote = 1;
108630      RenameCtx sCtx;
108631      Walker sWalker;
108632  
108633  #ifndef SQLITE_OMIT_AUTHORIZATION
108634      sqlite3_xauth xAuth = db->xAuth;
108635      db->xAuth = 0;
108636  #endif
108637  
108638      sqlite3BtreeEnterAll(db);
108639  
108640      memset(&sCtx, 0, sizeof(RenameCtx));
108641      sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
108642      memset(&sWalker, 0, sizeof(Walker));
108643      sWalker.pParse = &sParse;
108644      sWalker.xExprCallback = renameTableExprCb;
108645      sWalker.xSelectCallback = renameTableSelectCb;
108646      sWalker.u.pRename = &sCtx;
108647  
108648      rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
108649  
108650      if( rc==SQLITE_OK ){
108651        int isLegacy = (db->flags & SQLITE_LegacyAlter);
108652        if( sParse.pNewTable ){
108653          Table *pTab = sParse.pNewTable;
108654  
108655          if( pTab->pSelect ){
108656            if( isLegacy==0 ){
108657              NameContext sNC;
108658              memset(&sNC, 0, sizeof(sNC));
108659              sNC.pParse = &sParse;
108660  
108661              sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
108662              if( sParse.nErr ) rc = sParse.rc;
108663              sqlite3WalkSelect(&sWalker, pTab->pSelect);
108664            }
108665          }else{
108666            /* Modify any FK definitions to point to the new table. */
108667  #ifndef SQLITE_OMIT_FOREIGN_KEY
108668            if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
108669              FKey *pFKey;
108670              for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
108671                if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
108672                  renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
108673                }
108674              }
108675            }
108676  #endif
108677  
108678            /* If this is the table being altered, fix any table refs in CHECK
108679            ** expressions. Also update the name that appears right after the
108680            ** "CREATE [VIRTUAL] TABLE" bit. */
108681            if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
108682              sCtx.pTab = pTab;
108683              if( isLegacy==0 ){
108684                sqlite3WalkExprList(&sWalker, pTab->pCheck);
108685              }
108686              renameTokenFind(&sParse, &sCtx, pTab->zName);
108687            }
108688          }
108689        }
108690  
108691        else if( sParse.pNewIndex ){
108692          renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
108693          if( isLegacy==0 ){
108694            sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
108695          }
108696        }
108697  
108698  #ifndef SQLITE_OMIT_TRIGGER
108699        else{
108700          Trigger *pTrigger = sParse.pNewTrigger;
108701          TriggerStep *pStep;
108702          if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) 
108703              && sCtx.pTab->pSchema==pTrigger->pTabSchema
108704            ){
108705            renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
108706          }
108707  
108708          if( isLegacy==0 ){
108709            rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
108710            if( rc==SQLITE_OK ){
108711              renameWalkTrigger(&sWalker, pTrigger);
108712              for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
108713                if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
108714                  renameTokenFind(&sParse, &sCtx, pStep->zTarget);
108715                }
108716              }
108717            }
108718          }
108719        }
108720  #endif
108721      }
108722  
108723      if( rc==SQLITE_OK ){
108724        rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
108725      }
108726      if( rc!=SQLITE_OK ){
108727        if( sParse.zErrMsg ){
108728          renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
108729        }else{
108730          sqlite3_result_error_code(context, rc);
108731        }
108732      }
108733  
108734      renameParseCleanup(&sParse);
108735      renameTokenFree(db, sCtx.pList);
108736      sqlite3BtreeLeaveAll(db);
108737  #ifndef SQLITE_OMIT_AUTHORIZATION
108738      db->xAuth = xAuth;
108739  #endif
108740    }
108741  
108742    return;
108743  }
108744  
108745  /*
108746  ** An SQL user function that checks that there are no parse or symbol
108747  ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
108748  ** After an ALTER TABLE .. RENAME operation is performed and the schema
108749  ** reloaded, this function is called on each SQL statement in the schema
108750  ** to ensure that it is still usable.
108751  **
108752  **   0: Database name ("main", "temp" etc.).
108753  **   1: SQL statement.
108754  **   2: Object type ("view", "table", "trigger" or "index").
108755  **   3: Object name.
108756  **   4: True if object is from temp schema.
108757  **
108758  ** Unless it finds an error, this function normally returns NULL. However, it
108759  ** returns integer value 1 if:
108760  **
108761  **   * the SQL argument creates a trigger, and
108762  **   * the table that the trigger is attached to is in database zDb.
108763  */
108764  static void renameTableTest(
108765    sqlite3_context *context,
108766    int NotUsed,
108767    sqlite3_value **argv
108768  ){
108769    sqlite3 *db = sqlite3_context_db_handle(context);
108770    char const *zDb = (const char*)sqlite3_value_text(argv[0]);
108771    char const *zInput = (const char*)sqlite3_value_text(argv[1]);
108772    int bTemp = sqlite3_value_int(argv[4]);
108773    int isLegacy = (db->flags & SQLITE_LegacyAlter);
108774  
108775  #ifndef SQLITE_OMIT_AUTHORIZATION
108776    sqlite3_xauth xAuth = db->xAuth;
108777    db->xAuth = 0;
108778  #endif
108779  
108780    UNUSED_PARAMETER(NotUsed);
108781    if( zDb && zInput ){
108782      int rc;
108783      Parse sParse;
108784      rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
108785      if( rc==SQLITE_OK ){
108786        if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
108787          NameContext sNC;
108788          memset(&sNC, 0, sizeof(sNC));
108789          sNC.pParse = &sParse;
108790          sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
108791          if( sParse.nErr ) rc = sParse.rc;
108792        }
108793  
108794        else if( sParse.pNewTrigger ){
108795          if( isLegacy==0 ){
108796            rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
108797          }
108798          if( rc==SQLITE_OK ){
108799            int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
108800            int i2 = sqlite3FindDbName(db, zDb);
108801            if( i1==i2 ) sqlite3_result_int(context, 1);
108802          }
108803        }
108804      }
108805  
108806      if( rc!=SQLITE_OK ){
108807        renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
108808      }
108809      renameParseCleanup(&sParse);
108810    }
108811  
108812  #ifndef SQLITE_OMIT_AUTHORIZATION
108813    db->xAuth = xAuth;
108814  #endif
108815  }
108816  
108817  /*
108818  ** Register built-in functions used to help implement ALTER TABLE
108819  */
108820  SQLITE_PRIVATE void sqlite3AlterFunctions(void){
108821    static FuncDef aAlterTableFuncs[] = {
108822      INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
108823      INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
108824      INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
108825    };
108826    sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
108827  }
108828  #endif  /* SQLITE_ALTER_TABLE */
108829  
108830  /************** End of alter.c ***********************************************/
108831  /************** Begin file analyze.c *****************************************/
108832  /*
108833  ** 2005-07-08
108834  **
108835  ** The author disclaims copyright to this source code.  In place of
108836  ** a legal notice, here is a blessing:
108837  **
108838  **    May you do good and not evil.
108839  **    May you find forgiveness for yourself and forgive others.
108840  **    May you share freely, never taking more than you give.
108841  **
108842  *************************************************************************
108843  ** This file contains code associated with the ANALYZE command.
108844  **
108845  ** The ANALYZE command gather statistics about the content of tables
108846  ** and indices.  These statistics are made available to the query planner
108847  ** to help it make better decisions about how to perform queries.
108848  **
108849  ** The following system tables are or have been supported:
108850  **
108851  **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
108852  **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
108853  **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
108854  **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
108855  **
108856  ** Additional tables might be added in future releases of SQLite.
108857  ** The sqlite_stat2 table is not created or used unless the SQLite version
108858  ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
108859  ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
108860  ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
108861  ** created and used by SQLite versions 3.7.9 and later and with
108862  ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
108863  ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
108864  ** version of sqlite_stat3 and is only available when compiled with
108865  ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
108866  ** not possible to enable both STAT3 and STAT4 at the same time.  If they
108867  ** are both enabled, then STAT4 takes precedence.
108868  **
108869  ** For most applications, sqlite_stat1 provides all the statistics required
108870  ** for the query planner to make good choices.
108871  **
108872  ** Format of sqlite_stat1:
108873  **
108874  ** There is normally one row per index, with the index identified by the
108875  ** name in the idx column.  The tbl column is the name of the table to
108876  ** which the index belongs.  In each such row, the stat column will be
108877  ** a string consisting of a list of integers.  The first integer in this
108878  ** list is the number of rows in the index.  (This is the same as the
108879  ** number of rows in the table, except for partial indices.)  The second
108880  ** integer is the average number of rows in the index that have the same
108881  ** value in the first column of the index.  The third integer is the average
108882  ** number of rows in the index that have the same value for the first two
108883  ** columns.  The N-th integer (for N>1) is the average number of rows in 
108884  ** the index which have the same value for the first N-1 columns.  For
108885  ** a K-column index, there will be K+1 integers in the stat column.  If
108886  ** the index is unique, then the last integer will be 1.
108887  **
108888  ** The list of integers in the stat column can optionally be followed
108889  ** by the keyword "unordered".  The "unordered" keyword, if it is present,
108890  ** must be separated from the last integer by a single space.  If the
108891  ** "unordered" keyword is present, then the query planner assumes that
108892  ** the index is unordered and will not use the index for a range query.
108893  ** 
108894  ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
108895  ** column contains a single integer which is the (estimated) number of
108896  ** rows in the table identified by sqlite_stat1.tbl.
108897  **
108898  ** Format of sqlite_stat2:
108899  **
108900  ** The sqlite_stat2 is only created and is only used if SQLite is compiled
108901  ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
108902  ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
108903  ** about the distribution of keys within an index.  The index is identified by
108904  ** the "idx" column and the "tbl" column is the name of the table to which
108905  ** the index belongs.  There are usually 10 rows in the sqlite_stat2
108906  ** table for each index.
108907  **
108908  ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
108909  ** inclusive are samples of the left-most key value in the index taken at
108910  ** evenly spaced points along the index.  Let the number of samples be S
108911  ** (10 in the standard build) and let C be the number of rows in the index.
108912  ** Then the sampled rows are given by:
108913  **
108914  **     rownumber = (i*C*2 + C)/(S*2)
108915  **
108916  ** For i between 0 and S-1.  Conceptually, the index space is divided into
108917  ** S uniform buckets and the samples are the middle row from each bucket.
108918  **
108919  ** The format for sqlite_stat2 is recorded here for legacy reference.  This
108920  ** version of SQLite does not support sqlite_stat2.  It neither reads nor
108921  ** writes the sqlite_stat2 table.  This version of SQLite only supports
108922  ** sqlite_stat3.
108923  **
108924  ** Format for sqlite_stat3:
108925  **
108926  ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
108927  ** sqlite_stat4 format will be described first.  Further information
108928  ** about sqlite_stat3 follows the sqlite_stat4 description.
108929  **
108930  ** Format for sqlite_stat4:
108931  **
108932  ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
108933  ** to aid the query planner in choosing good indices based on the values
108934  ** that indexed columns are compared against in the WHERE clauses of
108935  ** queries.
108936  **
108937  ** The sqlite_stat4 table contains multiple entries for each index.
108938  ** The idx column names the index and the tbl column is the table of the
108939  ** index.  If the idx and tbl columns are the same, then the sample is
108940  ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
108941  ** binary encoding of a key from the index.  The nEq column is a
108942  ** list of integers.  The first integer is the approximate number
108943  ** of entries in the index whose left-most column exactly matches
108944  ** the left-most column of the sample.  The second integer in nEq
108945  ** is the approximate number of entries in the index where the
108946  ** first two columns match the first two columns of the sample.
108947  ** And so forth.  nLt is another list of integers that show the approximate
108948  ** number of entries that are strictly less than the sample.  The first
108949  ** integer in nLt contains the number of entries in the index where the
108950  ** left-most column is less than the left-most column of the sample.
108951  ** The K-th integer in the nLt entry is the number of index entries 
108952  ** where the first K columns are less than the first K columns of the
108953  ** sample.  The nDLt column is like nLt except that it contains the 
108954  ** number of distinct entries in the index that are less than the
108955  ** sample.
108956  **
108957  ** There can be an arbitrary number of sqlite_stat4 entries per index.
108958  ** The ANALYZE command will typically generate sqlite_stat4 tables
108959  ** that contain between 10 and 40 samples which are distributed across
108960  ** the key space, though not uniformly, and which include samples with
108961  ** large nEq values.
108962  **
108963  ** Format for sqlite_stat3 redux:
108964  **
108965  ** The sqlite_stat3 table is like sqlite_stat4 except that it only
108966  ** looks at the left-most column of the index.  The sqlite_stat3.sample
108967  ** column contains the actual value of the left-most column instead
108968  ** of a blob encoding of the complete index key as is found in
108969  ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
108970  ** all contain just a single integer which is the same as the first
108971  ** integer in the equivalent columns in sqlite_stat4.
108972  */
108973  #ifndef SQLITE_OMIT_ANALYZE
108974  /* #include "sqliteInt.h" */
108975  
108976  #if defined(SQLITE_ENABLE_STAT4)
108977  # define IsStat4     1
108978  # define IsStat3     0
108979  #elif defined(SQLITE_ENABLE_STAT3)
108980  # define IsStat4     0
108981  # define IsStat3     1
108982  #else
108983  # define IsStat4     0
108984  # define IsStat3     0
108985  # undef SQLITE_STAT4_SAMPLES
108986  # define SQLITE_STAT4_SAMPLES 1
108987  #endif
108988  #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
108989  
108990  /*
108991  ** This routine generates code that opens the sqlite_statN tables.
108992  ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
108993  ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
108994  ** appropriate compile-time options are provided.
108995  **
108996  ** If the sqlite_statN tables do not previously exist, it is created.
108997  **
108998  ** Argument zWhere may be a pointer to a buffer containing a table name,
108999  ** or it may be a NULL pointer. If it is not NULL, then all entries in
109000  ** the sqlite_statN tables associated with the named table are deleted.
109001  ** If zWhere==0, then code is generated to delete all stat table entries.
109002  */
109003  static void openStatTable(
109004    Parse *pParse,          /* Parsing context */
109005    int iDb,                /* The database we are looking in */
109006    int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
109007    const char *zWhere,     /* Delete entries for this table or index */
109008    const char *zWhereType  /* Either "tbl" or "idx" */
109009  ){
109010    static const struct {
109011      const char *zName;
109012      const char *zCols;
109013    } aTable[] = {
109014      { "sqlite_stat1", "tbl,idx,stat" },
109015  #if defined(SQLITE_ENABLE_STAT4)
109016      { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
109017      { "sqlite_stat3", 0 },
109018  #elif defined(SQLITE_ENABLE_STAT3)
109019      { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
109020      { "sqlite_stat4", 0 },
109021  #else
109022      { "sqlite_stat3", 0 },
109023      { "sqlite_stat4", 0 },
109024  #endif
109025    };
109026    int i;
109027    sqlite3 *db = pParse->db;
109028    Db *pDb;
109029    Vdbe *v = sqlite3GetVdbe(pParse);
109030    int aRoot[ArraySize(aTable)];
109031    u8 aCreateTbl[ArraySize(aTable)];
109032  
109033    if( v==0 ) return;
109034    assert( sqlite3BtreeHoldsAllMutexes(db) );
109035    assert( sqlite3VdbeDb(v)==db );
109036    pDb = &db->aDb[iDb];
109037  
109038    /* Create new statistic tables if they do not exist, or clear them
109039    ** if they do already exist.
109040    */
109041    for(i=0; i<ArraySize(aTable); i++){
109042      const char *zTab = aTable[i].zName;
109043      Table *pStat;
109044      if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
109045        if( aTable[i].zCols ){
109046          /* The sqlite_statN table does not exist. Create it. Note that a 
109047          ** side-effect of the CREATE TABLE statement is to leave the rootpage 
109048          ** of the new table in register pParse->regRoot. This is important 
109049          ** because the OpenWrite opcode below will be needing it. */
109050          sqlite3NestedParse(pParse,
109051              "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
109052          );
109053          aRoot[i] = pParse->regRoot;
109054          aCreateTbl[i] = OPFLAG_P2ISREG;
109055        }
109056      }else{
109057        /* The table already exists. If zWhere is not NULL, delete all entries 
109058        ** associated with the table zWhere. If zWhere is NULL, delete the
109059        ** entire contents of the table. */
109060        aRoot[i] = pStat->tnum;
109061        aCreateTbl[i] = 0;
109062        sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
109063        if( zWhere ){
109064          sqlite3NestedParse(pParse,
109065             "DELETE FROM %Q.%s WHERE %s=%Q",
109066             pDb->zDbSName, zTab, zWhereType, zWhere
109067          );
109068  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
109069        }else if( db->xPreUpdateCallback ){
109070          sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
109071  #endif
109072        }else{
109073          /* The sqlite_stat[134] table already exists.  Delete all rows. */
109074          sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
109075        }
109076      }
109077    }
109078  
109079    /* Open the sqlite_stat[134] tables for writing. */
109080    for(i=0; aTable[i].zCols; i++){
109081      assert( i<ArraySize(aTable) );
109082      sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
109083      sqlite3VdbeChangeP5(v, aCreateTbl[i]);
109084      VdbeComment((v, aTable[i].zName));
109085    }
109086  }
109087  
109088  /*
109089  ** Recommended number of samples for sqlite_stat4
109090  */
109091  #ifndef SQLITE_STAT4_SAMPLES
109092  # define SQLITE_STAT4_SAMPLES 24
109093  #endif
109094  
109095  /*
109096  ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
109097  ** share an instance of the following structure to hold their state
109098  ** information.
109099  */
109100  typedef struct Stat4Accum Stat4Accum;
109101  typedef struct Stat4Sample Stat4Sample;
109102  struct Stat4Sample {
109103    tRowcnt *anEq;                  /* sqlite_stat4.nEq */
109104    tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
109105  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109106    tRowcnt *anLt;                  /* sqlite_stat4.nLt */
109107    union {
109108      i64 iRowid;                     /* Rowid in main table of the key */
109109      u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
109110    } u;
109111    u32 nRowid;                     /* Sizeof aRowid[] */
109112    u8 isPSample;                   /* True if a periodic sample */
109113    int iCol;                       /* If !isPSample, the reason for inclusion */
109114    u32 iHash;                      /* Tiebreaker hash */
109115  #endif
109116  };                                                    
109117  struct Stat4Accum {
109118    tRowcnt nRow;             /* Number of rows in the entire table */
109119    tRowcnt nPSample;         /* How often to do a periodic sample */
109120    int nCol;                 /* Number of columns in index + pk/rowid */
109121    int nKeyCol;              /* Number of index columns w/o the pk/rowid */
109122    int mxSample;             /* Maximum number of samples to accumulate */
109123    Stat4Sample current;      /* Current row as a Stat4Sample */
109124    u32 iPrn;                 /* Pseudo-random number used for sampling */
109125    Stat4Sample *aBest;       /* Array of nCol best samples */
109126    int iMin;                 /* Index in a[] of entry with minimum score */
109127    int nSample;              /* Current number of samples */
109128    int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
109129    int iGet;                 /* Index of current sample accessed by stat_get() */
109130    Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
109131    sqlite3 *db;              /* Database connection, for malloc() */
109132  };
109133  
109134  /* Reclaim memory used by a Stat4Sample
109135  */
109136  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109137  static void sampleClear(sqlite3 *db, Stat4Sample *p){
109138    assert( db!=0 );
109139    if( p->nRowid ){
109140      sqlite3DbFree(db, p->u.aRowid);
109141      p->nRowid = 0;
109142    }
109143  }
109144  #endif
109145  
109146  /* Initialize the BLOB value of a ROWID
109147  */
109148  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109149  static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
109150    assert( db!=0 );
109151    if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
109152    p->u.aRowid = sqlite3DbMallocRawNN(db, n);
109153    if( p->u.aRowid ){
109154      p->nRowid = n;
109155      memcpy(p->u.aRowid, pData, n);
109156    }else{
109157      p->nRowid = 0;
109158    }
109159  }
109160  #endif
109161  
109162  /* Initialize the INTEGER value of a ROWID.
109163  */
109164  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109165  static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
109166    assert( db!=0 );
109167    if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
109168    p->nRowid = 0;
109169    p->u.iRowid = iRowid;
109170  }
109171  #endif
109172  
109173  
109174  /*
109175  ** Copy the contents of object (*pFrom) into (*pTo).
109176  */
109177  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109178  static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
109179    pTo->isPSample = pFrom->isPSample;
109180    pTo->iCol = pFrom->iCol;
109181    pTo->iHash = pFrom->iHash;
109182    memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
109183    memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
109184    memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
109185    if( pFrom->nRowid ){
109186      sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
109187    }else{
109188      sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
109189    }
109190  }
109191  #endif
109192  
109193  /*
109194  ** Reclaim all memory of a Stat4Accum structure.
109195  */
109196  static void stat4Destructor(void *pOld){
109197    Stat4Accum *p = (Stat4Accum*)pOld;
109198  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109199    int i;
109200    for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
109201    for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
109202    sampleClear(p->db, &p->current);
109203  #endif
109204    sqlite3DbFree(p->db, p);
109205  }
109206  
109207  /*
109208  ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
109209  ** are:
109210  **     N:    The number of columns in the index including the rowid/pk (note 1)
109211  **     K:    The number of columns in the index excluding the rowid/pk.
109212  **     C:    The number of rows in the index (note 2)
109213  **
109214  ** Note 1:  In the special case of the covering index that implements a
109215  ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
109216  ** total number of columns in the table.
109217  **
109218  ** Note 2:  C is only used for STAT3 and STAT4.
109219  **
109220  ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
109221  ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
109222  ** PRIMARY KEY of the table.  The covering index that implements the
109223  ** original WITHOUT ROWID table as N==K as a special case.
109224  **
109225  ** This routine allocates the Stat4Accum object in heap memory. The return 
109226  ** value is a pointer to the Stat4Accum object.  The datatype of the
109227  ** return value is BLOB, but it is really just a pointer to the Stat4Accum
109228  ** object.
109229  */
109230  static void statInit(
109231    sqlite3_context *context,
109232    int argc,
109233    sqlite3_value **argv
109234  ){
109235    Stat4Accum *p;
109236    int nCol;                       /* Number of columns in index being sampled */
109237    int nKeyCol;                    /* Number of key columns */
109238    int nColUp;                     /* nCol rounded up for alignment */
109239    int n;                          /* Bytes of space to allocate */
109240    sqlite3 *db;                    /* Database connection */
109241  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109242    int mxSample = SQLITE_STAT4_SAMPLES;
109243  #endif
109244  
109245    /* Decode the three function arguments */
109246    UNUSED_PARAMETER(argc);
109247    nCol = sqlite3_value_int(argv[0]);
109248    assert( nCol>0 );
109249    nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
109250    nKeyCol = sqlite3_value_int(argv[1]);
109251    assert( nKeyCol<=nCol );
109252    assert( nKeyCol>0 );
109253  
109254    /* Allocate the space required for the Stat4Accum object */
109255    n = sizeof(*p) 
109256      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
109257      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
109258  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109259      + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
109260      + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
109261      + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
109262  #endif
109263    ;
109264    db = sqlite3_context_db_handle(context);
109265    p = sqlite3DbMallocZero(db, n);
109266    if( p==0 ){
109267      sqlite3_result_error_nomem(context);
109268      return;
109269    }
109270  
109271    p->db = db;
109272    p->nRow = 0;
109273    p->nCol = nCol;
109274    p->nKeyCol = nKeyCol;
109275    p->current.anDLt = (tRowcnt*)&p[1];
109276    p->current.anEq = &p->current.anDLt[nColUp];
109277  
109278  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109279    {
109280      u8 *pSpace;                     /* Allocated space not yet assigned */
109281      int i;                          /* Used to iterate through p->aSample[] */
109282  
109283      p->iGet = -1;
109284      p->mxSample = mxSample;
109285      p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
109286      p->current.anLt = &p->current.anEq[nColUp];
109287      p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
109288    
109289      /* Set up the Stat4Accum.a[] and aBest[] arrays */
109290      p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
109291      p->aBest = &p->a[mxSample];
109292      pSpace = (u8*)(&p->a[mxSample+nCol]);
109293      for(i=0; i<(mxSample+nCol); i++){
109294        p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
109295        p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
109296        p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
109297      }
109298      assert( (pSpace - (u8*)p)==n );
109299    
109300      for(i=0; i<nCol; i++){
109301        p->aBest[i].iCol = i;
109302      }
109303    }
109304  #endif
109305  
109306    /* Return a pointer to the allocated object to the caller.  Note that
109307    ** only the pointer (the 2nd parameter) matters.  The size of the object
109308    ** (given by the 3rd parameter) is never used and can be any positive
109309    ** value. */
109310    sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
109311  }
109312  static const FuncDef statInitFuncdef = {
109313    2+IsStat34,      /* nArg */
109314    SQLITE_UTF8,     /* funcFlags */
109315    0,               /* pUserData */
109316    0,               /* pNext */
109317    statInit,        /* xSFunc */
109318    0,               /* xFinalize */
109319    0, 0,            /* xValue, xInverse */
109320    "stat_init",     /* zName */
109321    {0}
109322  };
109323  
109324  #ifdef SQLITE_ENABLE_STAT4
109325  /*
109326  ** pNew and pOld are both candidate non-periodic samples selected for 
109327  ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
109328  ** considering only any trailing columns and the sample hash value, this
109329  ** function returns true if sample pNew is to be preferred over pOld.
109330  ** In other words, if we assume that the cardinalities of the selected
109331  ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
109332  **
109333  ** This function assumes that for each argument sample, the contents of
109334  ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
109335  */
109336  static int sampleIsBetterPost(
109337    Stat4Accum *pAccum, 
109338    Stat4Sample *pNew, 
109339    Stat4Sample *pOld
109340  ){
109341    int nCol = pAccum->nCol;
109342    int i;
109343    assert( pNew->iCol==pOld->iCol );
109344    for(i=pNew->iCol+1; i<nCol; i++){
109345      if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
109346      if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
109347    }
109348    if( pNew->iHash>pOld->iHash ) return 1;
109349    return 0;
109350  }
109351  #endif
109352  
109353  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109354  /*
109355  ** Return true if pNew is to be preferred over pOld.
109356  **
109357  ** This function assumes that for each argument sample, the contents of
109358  ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
109359  */
109360  static int sampleIsBetter(
109361    Stat4Accum *pAccum, 
109362    Stat4Sample *pNew, 
109363    Stat4Sample *pOld
109364  ){
109365    tRowcnt nEqNew = pNew->anEq[pNew->iCol];
109366    tRowcnt nEqOld = pOld->anEq[pOld->iCol];
109367  
109368    assert( pOld->isPSample==0 && pNew->isPSample==0 );
109369    assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
109370  
109371    if( (nEqNew>nEqOld) ) return 1;
109372  #ifdef SQLITE_ENABLE_STAT4
109373    if( nEqNew==nEqOld ){
109374      if( pNew->iCol<pOld->iCol ) return 1;
109375      return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
109376    }
109377    return 0;
109378  #else
109379    return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
109380  #endif
109381  }
109382  
109383  /*
109384  ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
109385  ** remove the least desirable sample from p->a[] to make room.
109386  */
109387  static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
109388    Stat4Sample *pSample = 0;
109389    int i;
109390  
109391    assert( IsStat4 || nEqZero==0 );
109392  
109393  #ifdef SQLITE_ENABLE_STAT4
109394    /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
109395    ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
109396    ** other words, if nMaxEqZero is n, then it is guaranteed that there
109397    ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
109398    if( nEqZero>p->nMaxEqZero ){
109399      p->nMaxEqZero = nEqZero;
109400    }
109401    if( pNew->isPSample==0 ){
109402      Stat4Sample *pUpgrade = 0;
109403      assert( pNew->anEq[pNew->iCol]>0 );
109404  
109405      /* This sample is being added because the prefix that ends in column 
109406      ** iCol occurs many times in the table. However, if we have already
109407      ** added a sample that shares this prefix, there is no need to add
109408      ** this one. Instead, upgrade the priority of the highest priority
109409      ** existing sample that shares this prefix.  */
109410      for(i=p->nSample-1; i>=0; i--){
109411        Stat4Sample *pOld = &p->a[i];
109412        if( pOld->anEq[pNew->iCol]==0 ){
109413          if( pOld->isPSample ) return;
109414          assert( pOld->iCol>pNew->iCol );
109415          assert( sampleIsBetter(p, pNew, pOld) );
109416          if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
109417            pUpgrade = pOld;
109418          }
109419        }
109420      }
109421      if( pUpgrade ){
109422        pUpgrade->iCol = pNew->iCol;
109423        pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
109424        goto find_new_min;
109425      }
109426    }
109427  #endif
109428  
109429    /* If necessary, remove sample iMin to make room for the new sample. */
109430    if( p->nSample>=p->mxSample ){
109431      Stat4Sample *pMin = &p->a[p->iMin];
109432      tRowcnt *anEq = pMin->anEq;
109433      tRowcnt *anLt = pMin->anLt;
109434      tRowcnt *anDLt = pMin->anDLt;
109435      sampleClear(p->db, pMin);
109436      memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
109437      pSample = &p->a[p->nSample-1];
109438      pSample->nRowid = 0;
109439      pSample->anEq = anEq;
109440      pSample->anDLt = anDLt;
109441      pSample->anLt = anLt;
109442      p->nSample = p->mxSample-1;
109443    }
109444  
109445    /* The "rows less-than" for the rowid column must be greater than that
109446    ** for the last sample in the p->a[] array. Otherwise, the samples would
109447    ** be out of order. */
109448  #ifdef SQLITE_ENABLE_STAT4
109449    assert( p->nSample==0 
109450         || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
109451  #endif
109452  
109453    /* Insert the new sample */
109454    pSample = &p->a[p->nSample];
109455    sampleCopy(p, pSample, pNew);
109456    p->nSample++;
109457  
109458    /* Zero the first nEqZero entries in the anEq[] array. */
109459    memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
109460  
109461  #ifdef SQLITE_ENABLE_STAT4
109462   find_new_min:
109463  #endif
109464    if( p->nSample>=p->mxSample ){
109465      int iMin = -1;
109466      for(i=0; i<p->mxSample; i++){
109467        if( p->a[i].isPSample ) continue;
109468        if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
109469          iMin = i;
109470        }
109471      }
109472      assert( iMin>=0 );
109473      p->iMin = iMin;
109474    }
109475  }
109476  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
109477  
109478  /*
109479  ** Field iChng of the index being scanned has changed. So at this point
109480  ** p->current contains a sample that reflects the previous row of the
109481  ** index. The value of anEq[iChng] and subsequent anEq[] elements are
109482  ** correct at this point.
109483  */
109484  static void samplePushPrevious(Stat4Accum *p, int iChng){
109485  #ifdef SQLITE_ENABLE_STAT4
109486    int i;
109487  
109488    /* Check if any samples from the aBest[] array should be pushed
109489    ** into IndexSample.a[] at this point.  */
109490    for(i=(p->nCol-2); i>=iChng; i--){
109491      Stat4Sample *pBest = &p->aBest[i];
109492      pBest->anEq[i] = p->current.anEq[i];
109493      if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
109494        sampleInsert(p, pBest, i);
109495      }
109496    }
109497  
109498    /* Check that no sample contains an anEq[] entry with an index of
109499    ** p->nMaxEqZero or greater set to zero. */
109500    for(i=p->nSample-1; i>=0; i--){
109501      int j;
109502      for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
109503    }
109504  
109505    /* Update the anEq[] fields of any samples already collected. */
109506    if( iChng<p->nMaxEqZero ){
109507      for(i=p->nSample-1; i>=0; i--){
109508        int j;
109509        for(j=iChng; j<p->nCol; j++){
109510          if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
109511        }
109512      }
109513      p->nMaxEqZero = iChng;
109514    }
109515  #endif
109516  
109517  #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
109518    if( iChng==0 ){
109519      tRowcnt nLt = p->current.anLt[0];
109520      tRowcnt nEq = p->current.anEq[0];
109521  
109522      /* Check if this is to be a periodic sample. If so, add it. */
109523      if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
109524        p->current.isPSample = 1;
109525        sampleInsert(p, &p->current, 0);
109526        p->current.isPSample = 0;
109527      }else 
109528  
109529      /* Or if it is a non-periodic sample. Add it in this case too. */
109530      if( p->nSample<p->mxSample 
109531       || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
109532      ){
109533        sampleInsert(p, &p->current, 0);
109534      }
109535    }
109536  #endif
109537  
109538  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
109539    UNUSED_PARAMETER( p );
109540    UNUSED_PARAMETER( iChng );
109541  #endif
109542  }
109543  
109544  /*
109545  ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
109546  ** Arguments:
109547  **
109548  **    P     Pointer to the Stat4Accum object created by stat_init()
109549  **    C     Index of left-most column to differ from previous row
109550  **    R     Rowid for the current row.  Might be a key record for
109551  **          WITHOUT ROWID tables.
109552  **
109553  ** This SQL function always returns NULL.  It's purpose it to accumulate
109554  ** statistical data and/or samples in the Stat4Accum object about the
109555  ** index being analyzed.  The stat_get() SQL function will later be used to
109556  ** extract relevant information for constructing the sqlite_statN tables.
109557  **
109558  ** The R parameter is only used for STAT3 and STAT4
109559  */
109560  static void statPush(
109561    sqlite3_context *context,
109562    int argc,
109563    sqlite3_value **argv
109564  ){
109565    int i;
109566  
109567    /* The three function arguments */
109568    Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
109569    int iChng = sqlite3_value_int(argv[1]);
109570  
109571    UNUSED_PARAMETER( argc );
109572    UNUSED_PARAMETER( context );
109573    assert( p->nCol>0 );
109574    assert( iChng<p->nCol );
109575  
109576    if( p->nRow==0 ){
109577      /* This is the first call to this function. Do initialization. */
109578      for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
109579    }else{
109580      /* Second and subsequent calls get processed here */
109581      samplePushPrevious(p, iChng);
109582  
109583      /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
109584      ** to the current row of the index. */
109585      for(i=0; i<iChng; i++){
109586        p->current.anEq[i]++;
109587      }
109588      for(i=iChng; i<p->nCol; i++){
109589        p->current.anDLt[i]++;
109590  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109591        p->current.anLt[i] += p->current.anEq[i];
109592  #endif
109593        p->current.anEq[i] = 1;
109594      }
109595    }
109596    p->nRow++;
109597  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109598    if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
109599      sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
109600    }else{
109601      sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
109602                                         sqlite3_value_blob(argv[2]));
109603    }
109604    p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
109605  #endif
109606  
109607  #ifdef SQLITE_ENABLE_STAT4
109608    {
109609      tRowcnt nLt = p->current.anLt[p->nCol-1];
109610  
109611      /* Check if this is to be a periodic sample. If so, add it. */
109612      if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
109613        p->current.isPSample = 1;
109614        p->current.iCol = 0;
109615        sampleInsert(p, &p->current, p->nCol-1);
109616        p->current.isPSample = 0;
109617      }
109618  
109619      /* Update the aBest[] array. */
109620      for(i=0; i<(p->nCol-1); i++){
109621        p->current.iCol = i;
109622        if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
109623          sampleCopy(p, &p->aBest[i], &p->current);
109624        }
109625      }
109626    }
109627  #endif
109628  }
109629  static const FuncDef statPushFuncdef = {
109630    2+IsStat34,      /* nArg */
109631    SQLITE_UTF8,     /* funcFlags */
109632    0,               /* pUserData */
109633    0,               /* pNext */
109634    statPush,        /* xSFunc */
109635    0,               /* xFinalize */
109636    0, 0,            /* xValue, xInverse */
109637    "stat_push",     /* zName */
109638    {0}
109639  };
109640  
109641  #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
109642  #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
109643  #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
109644  #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
109645  #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
109646  
109647  /*
109648  ** Implementation of the stat_get(P,J) SQL function.  This routine is
109649  ** used to query statistical information that has been gathered into
109650  ** the Stat4Accum object by prior calls to stat_push().  The P parameter
109651  ** has type BLOB but it is really just a pointer to the Stat4Accum object.
109652  ** The content to returned is determined by the parameter J
109653  ** which is one of the STAT_GET_xxxx values defined above.
109654  **
109655  ** The stat_get(P,J) function is not available to generic SQL.  It is
109656  ** inserted as part of a manually constructed bytecode program.  (See
109657  ** the callStatGet() routine below.)  It is guaranteed that the P
109658  ** parameter will always be a poiner to a Stat4Accum object, never a
109659  ** NULL.
109660  **
109661  ** If neither STAT3 nor STAT4 are enabled, then J is always
109662  ** STAT_GET_STAT1 and is hence omitted and this routine becomes
109663  ** a one-parameter function, stat_get(P), that always returns the
109664  ** stat1 table entry information.
109665  */
109666  static void statGet(
109667    sqlite3_context *context,
109668    int argc,
109669    sqlite3_value **argv
109670  ){
109671    Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
109672  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109673    /* STAT3 and STAT4 have a parameter on this routine. */
109674    int eCall = sqlite3_value_int(argv[1]);
109675    assert( argc==2 );
109676    assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
109677         || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
109678         || eCall==STAT_GET_NDLT 
109679    );
109680    if( eCall==STAT_GET_STAT1 )
109681  #else
109682    assert( argc==1 );
109683  #endif
109684    {
109685      /* Return the value to store in the "stat" column of the sqlite_stat1
109686      ** table for this index.
109687      **
109688      ** The value is a string composed of a list of integers describing 
109689      ** the index. The first integer in the list is the total number of 
109690      ** entries in the index. There is one additional integer in the list 
109691      ** for each indexed column. This additional integer is an estimate of
109692      ** the number of rows matched by a stabbing query on the index using
109693      ** a key with the corresponding number of fields. In other words,
109694      ** if the index is on columns (a,b) and the sqlite_stat1 value is 
109695      ** "100 10 2", then SQLite estimates that:
109696      **
109697      **   * the index contains 100 rows,
109698      **   * "WHERE a=?" matches 10 rows, and
109699      **   * "WHERE a=? AND b=?" matches 2 rows.
109700      **
109701      ** If D is the count of distinct values and K is the total number of 
109702      ** rows, then each estimate is computed as:
109703      **
109704      **        I = (K+D-1)/D
109705      */
109706      char *z;
109707      int i;
109708  
109709      char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
109710      if( zRet==0 ){
109711        sqlite3_result_error_nomem(context);
109712        return;
109713      }
109714  
109715      sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
109716      z = zRet + sqlite3Strlen30(zRet);
109717      for(i=0; i<p->nKeyCol; i++){
109718        u64 nDistinct = p->current.anDLt[i] + 1;
109719        u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
109720        sqlite3_snprintf(24, z, " %llu", iVal);
109721        z += sqlite3Strlen30(z);
109722        assert( p->current.anEq[i] );
109723      }
109724      assert( z[0]=='\0' && z>zRet );
109725  
109726      sqlite3_result_text(context, zRet, -1, sqlite3_free);
109727    }
109728  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109729    else if( eCall==STAT_GET_ROWID ){
109730      if( p->iGet<0 ){
109731        samplePushPrevious(p, 0);
109732        p->iGet = 0;
109733      }
109734      if( p->iGet<p->nSample ){
109735        Stat4Sample *pS = p->a + p->iGet;
109736        if( pS->nRowid==0 ){
109737          sqlite3_result_int64(context, pS->u.iRowid);
109738        }else{
109739          sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
109740                              SQLITE_TRANSIENT);
109741        }
109742      }
109743    }else{
109744      tRowcnt *aCnt = 0;
109745  
109746      assert( p->iGet<p->nSample );
109747      switch( eCall ){
109748        case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
109749        case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
109750        default: {
109751          aCnt = p->a[p->iGet].anDLt; 
109752          p->iGet++;
109753          break;
109754        }
109755      }
109756  
109757      if( IsStat3 ){
109758        sqlite3_result_int64(context, (i64)aCnt[0]);
109759      }else{
109760        char *zRet = sqlite3MallocZero(p->nCol * 25);
109761        if( zRet==0 ){
109762          sqlite3_result_error_nomem(context);
109763        }else{
109764          int i;
109765          char *z = zRet;
109766          for(i=0; i<p->nCol; i++){
109767            sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
109768            z += sqlite3Strlen30(z);
109769          }
109770          assert( z[0]=='\0' && z>zRet );
109771          z[-1] = '\0';
109772          sqlite3_result_text(context, zRet, -1, sqlite3_free);
109773        }
109774      }
109775    }
109776  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
109777  #ifndef SQLITE_DEBUG
109778    UNUSED_PARAMETER( argc );
109779  #endif
109780  }
109781  static const FuncDef statGetFuncdef = {
109782    1+IsStat34,      /* nArg */
109783    SQLITE_UTF8,     /* funcFlags */
109784    0,               /* pUserData */
109785    0,               /* pNext */
109786    statGet,         /* xSFunc */
109787    0,               /* xFinalize */
109788    0, 0,            /* xValue, xInverse */
109789    "stat_get",      /* zName */
109790    {0}
109791  };
109792  
109793  static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
109794    assert( regOut!=regStat4 && regOut!=regStat4+1 );
109795  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109796    sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
109797  #elif SQLITE_DEBUG
109798    assert( iParam==STAT_GET_STAT1 );
109799  #else
109800    UNUSED_PARAMETER( iParam );
109801  #endif
109802    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
109803                      (char*)&statGetFuncdef, P4_FUNCDEF);
109804    sqlite3VdbeChangeP5(v, 1 + IsStat34);
109805  }
109806  
109807  /*
109808  ** Generate code to do an analysis of all indices associated with
109809  ** a single table.
109810  */
109811  static void analyzeOneTable(
109812    Parse *pParse,   /* Parser context */
109813    Table *pTab,     /* Table whose indices are to be analyzed */
109814    Index *pOnlyIdx, /* If not NULL, only analyze this one index */
109815    int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
109816    int iMem,        /* Available memory locations begin here */
109817    int iTab         /* Next available cursor */
109818  ){
109819    sqlite3 *db = pParse->db;    /* Database handle */
109820    Index *pIdx;                 /* An index to being analyzed */
109821    int iIdxCur;                 /* Cursor open on index being analyzed */
109822    int iTabCur;                 /* Table cursor */
109823    Vdbe *v;                     /* The virtual machine being built up */
109824    int i;                       /* Loop counter */
109825    int jZeroRows = -1;          /* Jump from here if number of rows is zero */
109826    int iDb;                     /* Index of database containing pTab */
109827    u8 needTableCnt = 1;         /* True to count the table */
109828    int regNewRowid = iMem++;    /* Rowid for the inserted record */
109829    int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
109830    int regChng = iMem++;        /* Index of changed index field */
109831  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109832    int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
109833  #endif
109834    int regTemp = iMem++;        /* Temporary use register */
109835    int regTabname = iMem++;     /* Register containing table name */
109836    int regIdxname = iMem++;     /* Register containing index name */
109837    int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
109838    int regPrev = iMem;          /* MUST BE LAST (see below) */
109839  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
109840    Table *pStat1 = 0; 
109841  #endif
109842  
109843    pParse->nMem = MAX(pParse->nMem, iMem);
109844    v = sqlite3GetVdbe(pParse);
109845    if( v==0 || NEVER(pTab==0) ){
109846      return;
109847    }
109848    if( pTab->tnum==0 ){
109849      /* Do not gather statistics on views or virtual tables */
109850      return;
109851    }
109852    if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
109853      /* Do not gather statistics on system tables */
109854      return;
109855    }
109856    assert( sqlite3BtreeHoldsAllMutexes(db) );
109857    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109858    assert( iDb>=0 );
109859    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
109860  #ifndef SQLITE_OMIT_AUTHORIZATION
109861    if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
109862        db->aDb[iDb].zDbSName ) ){
109863      return;
109864    }
109865  #endif
109866  
109867  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
109868    if( db->xPreUpdateCallback ){
109869      pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
109870      if( pStat1==0 ) return;
109871      pStat1->zName = (char*)&pStat1[1];
109872      memcpy(pStat1->zName, "sqlite_stat1", 13);
109873      pStat1->nCol = 3;
109874      pStat1->iPKey = -1;
109875      sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
109876    }
109877  #endif
109878  
109879    /* Establish a read-lock on the table at the shared-cache level. 
109880    ** Open a read-only cursor on the table. Also allocate a cursor number
109881    ** to use for scanning indexes (iIdxCur). No index cursor is opened at
109882    ** this time though.  */
109883    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109884    iTabCur = iTab++;
109885    iIdxCur = iTab++;
109886    pParse->nTab = MAX(pParse->nTab, iTab);
109887    sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
109888    sqlite3VdbeLoadString(v, regTabname, pTab->zName);
109889  
109890    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109891      int nCol;                     /* Number of columns in pIdx. "N" */
109892      int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
109893      int addrNextRow;              /* Address of "next_row:" */
109894      const char *zIdxName;         /* Name of the index */
109895      int nColTest;                 /* Number of columns to test for changes */
109896  
109897      if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
109898      if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
109899      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
109900        nCol = pIdx->nKeyCol;
109901        zIdxName = pTab->zName;
109902        nColTest = nCol - 1;
109903      }else{
109904        nCol = pIdx->nColumn;
109905        zIdxName = pIdx->zName;
109906        nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
109907      }
109908  
109909      /* Populate the register containing the index name. */
109910      sqlite3VdbeLoadString(v, regIdxname, zIdxName);
109911      VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
109912  
109913      /*
109914      ** Pseudo-code for loop that calls stat_push():
109915      **
109916      **   Rewind csr
109917      **   if eof(csr) goto end_of_scan;
109918      **   regChng = 0
109919      **   goto chng_addr_0;
109920      **
109921      **  next_row:
109922      **   regChng = 0
109923      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
109924      **   regChng = 1
109925      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
109926      **   ...
109927      **   regChng = N
109928      **   goto chng_addr_N
109929      **
109930      **  chng_addr_0:
109931      **   regPrev(0) = idx(0)
109932      **  chng_addr_1:
109933      **   regPrev(1) = idx(1)
109934      **  ...
109935      **
109936      **  endDistinctTest:
109937      **   regRowid = idx(rowid)
109938      **   stat_push(P, regChng, regRowid)
109939      **   Next csr
109940      **   if !eof(csr) goto next_row;
109941      **
109942      **  end_of_scan:
109943      */
109944  
109945      /* Make sure there are enough memory cells allocated to accommodate 
109946      ** the regPrev array and a trailing rowid (the rowid slot is required
109947      ** when building a record to insert into the sample column of 
109948      ** the sqlite_stat4 table.  */
109949      pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
109950  
109951      /* Open a read-only cursor on the index being analyzed. */
109952      assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
109953      sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
109954      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
109955      VdbeComment((v, "%s", pIdx->zName));
109956  
109957      /* Invoke the stat_init() function. The arguments are:
109958      ** 
109959      **    (1) the number of columns in the index including the rowid
109960      **        (or for a WITHOUT ROWID table, the number of PK columns),
109961      **    (2) the number of columns in the key without the rowid/pk
109962      **    (3) the number of rows in the index,
109963      **
109964      **
109965      ** The third argument is only used for STAT3 and STAT4
109966      */
109967  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109968      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
109969  #endif
109970      sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
109971      sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
109972      sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
109973                       (char*)&statInitFuncdef, P4_FUNCDEF);
109974      sqlite3VdbeChangeP5(v, 2+IsStat34);
109975  
109976      /* Implementation of the following:
109977      **
109978      **   Rewind csr
109979      **   if eof(csr) goto end_of_scan;
109980      **   regChng = 0
109981      **   goto next_push_0;
109982      **
109983      */
109984      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
109985      VdbeCoverage(v);
109986      sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
109987      addrNextRow = sqlite3VdbeCurrentAddr(v);
109988  
109989      if( nColTest>0 ){
109990        int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
109991        int *aGotoChng;               /* Array of jump instruction addresses */
109992        aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
109993        if( aGotoChng==0 ) continue;
109994  
109995        /*
109996        **  next_row:
109997        **   regChng = 0
109998        **   if( idx(0) != regPrev(0) ) goto chng_addr_0
109999        **   regChng = 1
110000        **   if( idx(1) != regPrev(1) ) goto chng_addr_1
110001        **   ...
110002        **   regChng = N
110003        **   goto endDistinctTest
110004        */
110005        sqlite3VdbeAddOp0(v, OP_Goto);
110006        addrNextRow = sqlite3VdbeCurrentAddr(v);
110007        if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
110008          /* For a single-column UNIQUE index, once we have found a non-NULL
110009          ** row, we know that all the rest will be distinct, so skip 
110010          ** subsequent distinctness tests. */
110011          sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
110012          VdbeCoverage(v);
110013        }
110014        for(i=0; i<nColTest; i++){
110015          char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
110016          sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
110017          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
110018          aGotoChng[i] = 
110019          sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
110020          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
110021          VdbeCoverage(v);
110022        }
110023        sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
110024        sqlite3VdbeGoto(v, endDistinctTest);
110025    
110026    
110027        /*
110028        **  chng_addr_0:
110029        **   regPrev(0) = idx(0)
110030        **  chng_addr_1:
110031        **   regPrev(1) = idx(1)
110032        **  ...
110033        */
110034        sqlite3VdbeJumpHere(v, addrNextRow-1);
110035        for(i=0; i<nColTest; i++){
110036          sqlite3VdbeJumpHere(v, aGotoChng[i]);
110037          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
110038        }
110039        sqlite3VdbeResolveLabel(v, endDistinctTest);
110040        sqlite3DbFree(db, aGotoChng);
110041      }
110042    
110043      /*
110044      **  chng_addr_N:
110045      **   regRowid = idx(rowid)            // STAT34 only
110046      **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
110047      **   Next csr
110048      **   if !eof(csr) goto next_row;
110049      */
110050  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110051      assert( regRowid==(regStat4+2) );
110052      if( HasRowid(pTab) ){
110053        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
110054      }else{
110055        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
110056        int j, k, regKey;
110057        regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
110058        for(j=0; j<pPk->nKeyCol; j++){
110059          k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
110060          assert( k>=0 && k<pIdx->nColumn );
110061          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
110062          VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
110063        }
110064        sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
110065        sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
110066      }
110067  #endif
110068      assert( regChng==(regStat4+1) );
110069      sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
110070                       (char*)&statPushFuncdef, P4_FUNCDEF);
110071      sqlite3VdbeChangeP5(v, 2+IsStat34);
110072      sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
110073  
110074      /* Add the entry to the stat1 table. */
110075      callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
110076      assert( "BBB"[0]==SQLITE_AFF_TEXT );
110077      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
110078      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
110079      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
110080  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
110081      sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
110082  #endif
110083      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
110084  
110085      /* Add the entries to the stat3 or stat4 table. */
110086  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110087      {
110088        int regEq = regStat1;
110089        int regLt = regStat1+1;
110090        int regDLt = regStat1+2;
110091        int regSample = regStat1+3;
110092        int regCol = regStat1+4;
110093        int regSampleRowid = regCol + nCol;
110094        int addrNext;
110095        int addrIsNull;
110096        u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
110097  
110098        pParse->nMem = MAX(pParse->nMem, regCol+nCol);
110099  
110100        addrNext = sqlite3VdbeCurrentAddr(v);
110101        callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
110102        addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
110103        VdbeCoverage(v);
110104        callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
110105        callStatGet(v, regStat4, STAT_GET_NLT, regLt);
110106        callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
110107        sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
110108        VdbeCoverage(v);
110109  #ifdef SQLITE_ENABLE_STAT3
110110        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
110111  #else
110112        for(i=0; i<nCol; i++){
110113          sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
110114        }
110115        sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
110116  #endif
110117        sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
110118        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
110119        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
110120        sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
110121        sqlite3VdbeJumpHere(v, addrIsNull);
110122      }
110123  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
110124  
110125      /* End of analysis */
110126      sqlite3VdbeJumpHere(v, addrRewind);
110127    }
110128  
110129  
110130    /* Create a single sqlite_stat1 entry containing NULL as the index
110131    ** name and the row count as the content.
110132    */
110133    if( pOnlyIdx==0 && needTableCnt ){
110134      VdbeComment((v, "%s", pTab->zName));
110135      sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
110136      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
110137      sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
110138      assert( "BBB"[0]==SQLITE_AFF_TEXT );
110139      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
110140      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
110141      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
110142      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
110143  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
110144      sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
110145  #endif
110146      sqlite3VdbeJumpHere(v, jZeroRows);
110147    }
110148  }
110149  
110150  
110151  /*
110152  ** Generate code that will cause the most recent index analysis to
110153  ** be loaded into internal hash tables where is can be used.
110154  */
110155  static void loadAnalysis(Parse *pParse, int iDb){
110156    Vdbe *v = sqlite3GetVdbe(pParse);
110157    if( v ){
110158      sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
110159    }
110160  }
110161  
110162  /*
110163  ** Generate code that will do an analysis of an entire database
110164  */
110165  static void analyzeDatabase(Parse *pParse, int iDb){
110166    sqlite3 *db = pParse->db;
110167    Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
110168    HashElem *k;
110169    int iStatCur;
110170    int iMem;
110171    int iTab;
110172  
110173    sqlite3BeginWriteOperation(pParse, 0, iDb);
110174    iStatCur = pParse->nTab;
110175    pParse->nTab += 3;
110176    openStatTable(pParse, iDb, iStatCur, 0, 0);
110177    iMem = pParse->nMem+1;
110178    iTab = pParse->nTab;
110179    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110180    for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
110181      Table *pTab = (Table*)sqliteHashData(k);
110182      analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
110183    }
110184    loadAnalysis(pParse, iDb);
110185  }
110186  
110187  /*
110188  ** Generate code that will do an analysis of a single table in
110189  ** a database.  If pOnlyIdx is not NULL then it is a single index
110190  ** in pTab that should be analyzed.
110191  */
110192  static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
110193    int iDb;
110194    int iStatCur;
110195  
110196    assert( pTab!=0 );
110197    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
110198    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
110199    sqlite3BeginWriteOperation(pParse, 0, iDb);
110200    iStatCur = pParse->nTab;
110201    pParse->nTab += 3;
110202    if( pOnlyIdx ){
110203      openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
110204    }else{
110205      openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
110206    }
110207    analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
110208    loadAnalysis(pParse, iDb);
110209  }
110210  
110211  /*
110212  ** Generate code for the ANALYZE command.  The parser calls this routine
110213  ** when it recognizes an ANALYZE command.
110214  **
110215  **        ANALYZE                            -- 1
110216  **        ANALYZE  <database>                -- 2
110217  **        ANALYZE  ?<database>.?<tablename>  -- 3
110218  **
110219  ** Form 1 causes all indices in all attached databases to be analyzed.
110220  ** Form 2 analyzes all indices the single database named.
110221  ** Form 3 analyzes all indices associated with the named table.
110222  */
110223  SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
110224    sqlite3 *db = pParse->db;
110225    int iDb;
110226    int i;
110227    char *z, *zDb;
110228    Table *pTab;
110229    Index *pIdx;
110230    Token *pTableName;
110231    Vdbe *v;
110232  
110233    /* Read the database schema. If an error occurs, leave an error message
110234    ** and code in pParse and return NULL. */
110235    assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
110236    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
110237      return;
110238    }
110239  
110240    assert( pName2!=0 || pName1==0 );
110241    if( pName1==0 ){
110242      /* Form 1:  Analyze everything */
110243      for(i=0; i<db->nDb; i++){
110244        if( i==1 ) continue;  /* Do not analyze the TEMP database */
110245        analyzeDatabase(pParse, i);
110246      }
110247    }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
110248      /* Analyze the schema named as the argument */
110249      analyzeDatabase(pParse, iDb);
110250    }else{
110251      /* Form 3: Analyze the table or index named as an argument */
110252      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
110253      if( iDb>=0 ){
110254        zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
110255        z = sqlite3NameFromToken(db, pTableName);
110256        if( z ){
110257          if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
110258            analyzeTable(pParse, pIdx->pTable, pIdx);
110259          }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
110260            analyzeTable(pParse, pTab, 0);
110261          }
110262          sqlite3DbFree(db, z);
110263        }
110264      }
110265    }
110266    if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
110267      sqlite3VdbeAddOp0(v, OP_Expire);
110268    }
110269  }
110270  
110271  /*
110272  ** Used to pass information from the analyzer reader through to the
110273  ** callback routine.
110274  */
110275  typedef struct analysisInfo analysisInfo;
110276  struct analysisInfo {
110277    sqlite3 *db;
110278    const char *zDatabase;
110279  };
110280  
110281  /*
110282  ** The first argument points to a nul-terminated string containing a
110283  ** list of space separated integers. Read the first nOut of these into
110284  ** the array aOut[].
110285  */
110286  static void decodeIntArray(
110287    char *zIntArray,       /* String containing int array to decode */
110288    int nOut,              /* Number of slots in aOut[] */
110289    tRowcnt *aOut,         /* Store integers here */
110290    LogEst *aLog,          /* Or, if aOut==0, here */
110291    Index *pIndex          /* Handle extra flags for this index, if not NULL */
110292  ){
110293    char *z = zIntArray;
110294    int c;
110295    int i;
110296    tRowcnt v;
110297  
110298  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110299    if( z==0 ) z = "";
110300  #else
110301    assert( z!=0 );
110302  #endif
110303    for(i=0; *z && i<nOut; i++){
110304      v = 0;
110305      while( (c=z[0])>='0' && c<='9' ){
110306        v = v*10 + c - '0';
110307        z++;
110308      }
110309  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110310      if( aOut ) aOut[i] = v;
110311      if( aLog ) aLog[i] = sqlite3LogEst(v);
110312  #else
110313      assert( aOut==0 );
110314      UNUSED_PARAMETER(aOut);
110315      assert( aLog!=0 );
110316      aLog[i] = sqlite3LogEst(v);
110317  #endif
110318      if( *z==' ' ) z++;
110319    }
110320  #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
110321    assert( pIndex!=0 ); {
110322  #else
110323    if( pIndex ){
110324  #endif
110325      pIndex->bUnordered = 0;
110326      pIndex->noSkipScan = 0;
110327      while( z[0] ){
110328        if( sqlite3_strglob("unordered*", z)==0 ){
110329          pIndex->bUnordered = 1;
110330        }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
110331          pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
110332        }else if( sqlite3_strglob("noskipscan*", z)==0 ){
110333          pIndex->noSkipScan = 1;
110334        }
110335  #ifdef SQLITE_ENABLE_COSTMULT
110336        else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
110337          pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
110338        }
110339  #endif
110340        while( z[0]!=0 && z[0]!=' ' ) z++;
110341        while( z[0]==' ' ) z++;
110342      }
110343    }
110344  }
110345  
110346  /*
110347  ** This callback is invoked once for each index when reading the
110348  ** sqlite_stat1 table.  
110349  **
110350  **     argv[0] = name of the table
110351  **     argv[1] = name of the index (might be NULL)
110352  **     argv[2] = results of analysis - on integer for each column
110353  **
110354  ** Entries for which argv[1]==NULL simply record the number of rows in
110355  ** the table.
110356  */
110357  static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
110358    analysisInfo *pInfo = (analysisInfo*)pData;
110359    Index *pIndex;
110360    Table *pTable;
110361    const char *z;
110362  
110363    assert( argc==3 );
110364    UNUSED_PARAMETER2(NotUsed, argc);
110365  
110366    if( argv==0 || argv[0]==0 || argv[2]==0 ){
110367      return 0;
110368    }
110369    pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
110370    if( pTable==0 ){
110371      return 0;
110372    }
110373    if( argv[1]==0 ){
110374      pIndex = 0;
110375    }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
110376      pIndex = sqlite3PrimaryKeyIndex(pTable);
110377    }else{
110378      pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
110379    }
110380    z = argv[2];
110381  
110382    if( pIndex ){
110383      tRowcnt *aiRowEst = 0;
110384      int nCol = pIndex->nKeyCol+1;
110385  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110386      /* Index.aiRowEst may already be set here if there are duplicate 
110387      ** sqlite_stat1 entries for this index. In that case just clobber
110388      ** the old data with the new instead of allocating a new array.  */
110389      if( pIndex->aiRowEst==0 ){
110390        pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
110391        if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
110392      }
110393      aiRowEst = pIndex->aiRowEst;
110394  #endif
110395      pIndex->bUnordered = 0;
110396      decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
110397      pIndex->hasStat1 = 1;
110398      if( pIndex->pPartIdxWhere==0 ){
110399        pTable->nRowLogEst = pIndex->aiRowLogEst[0];
110400        pTable->tabFlags |= TF_HasStat1;
110401      }
110402    }else{
110403      Index fakeIdx;
110404      fakeIdx.szIdxRow = pTable->szTabRow;
110405  #ifdef SQLITE_ENABLE_COSTMULT
110406      fakeIdx.pTable = pTable;
110407  #endif
110408      decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
110409      pTable->szTabRow = fakeIdx.szIdxRow;
110410      pTable->tabFlags |= TF_HasStat1;
110411    }
110412  
110413    return 0;
110414  }
110415  
110416  /*
110417  ** If the Index.aSample variable is not NULL, delete the aSample[] array
110418  ** and its contents.
110419  */
110420  SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
110421  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110422    if( pIdx->aSample ){
110423      int j;
110424      for(j=0; j<pIdx->nSample; j++){
110425        IndexSample *p = &pIdx->aSample[j];
110426        sqlite3DbFree(db, p->p);
110427      }
110428      sqlite3DbFree(db, pIdx->aSample);
110429    }
110430    if( db && db->pnBytesFreed==0 ){
110431      pIdx->nSample = 0;
110432      pIdx->aSample = 0;
110433    }
110434  #else
110435    UNUSED_PARAMETER(db);
110436    UNUSED_PARAMETER(pIdx);
110437  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
110438  }
110439  
110440  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110441  /*
110442  ** Populate the pIdx->aAvgEq[] array based on the samples currently
110443  ** stored in pIdx->aSample[]. 
110444  */
110445  static void initAvgEq(Index *pIdx){
110446    if( pIdx ){
110447      IndexSample *aSample = pIdx->aSample;
110448      IndexSample *pFinal = &aSample[pIdx->nSample-1];
110449      int iCol;
110450      int nCol = 1;
110451      if( pIdx->nSampleCol>1 ){
110452        /* If this is stat4 data, then calculate aAvgEq[] values for all
110453        ** sample columns except the last. The last is always set to 1, as
110454        ** once the trailing PK fields are considered all index keys are
110455        ** unique.  */
110456        nCol = pIdx->nSampleCol-1;
110457        pIdx->aAvgEq[nCol] = 1;
110458      }
110459      for(iCol=0; iCol<nCol; iCol++){
110460        int nSample = pIdx->nSample;
110461        int i;                    /* Used to iterate through samples */
110462        tRowcnt sumEq = 0;        /* Sum of the nEq values */
110463        tRowcnt avgEq = 0;
110464        tRowcnt nRow;             /* Number of rows in index */
110465        i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
110466        i64 nDist100;             /* Number of distinct values in index */
110467  
110468        if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
110469          nRow = pFinal->anLt[iCol];
110470          nDist100 = (i64)100 * pFinal->anDLt[iCol];
110471          nSample--;
110472        }else{
110473          nRow = pIdx->aiRowEst[0];
110474          nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
110475        }
110476        pIdx->nRowEst0 = nRow;
110477  
110478        /* Set nSum to the number of distinct (iCol+1) field prefixes that
110479        ** occur in the stat4 table for this index. Set sumEq to the sum of 
110480        ** the nEq values for column iCol for the same set (adding the value 
110481        ** only once where there exist duplicate prefixes).  */
110482        for(i=0; i<nSample; i++){
110483          if( i==(pIdx->nSample-1)
110484           || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
110485          ){
110486            sumEq += aSample[i].anEq[iCol];
110487            nSum100 += 100;
110488          }
110489        }
110490  
110491        if( nDist100>nSum100 && sumEq<nRow ){
110492          avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
110493        }
110494        if( avgEq==0 ) avgEq = 1;
110495        pIdx->aAvgEq[iCol] = avgEq;
110496      }
110497    }
110498  }
110499  
110500  /*
110501  ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
110502  ** is supplied instead, find the PRIMARY KEY index for that table.
110503  */
110504  static Index *findIndexOrPrimaryKey(
110505    sqlite3 *db,
110506    const char *zName,
110507    const char *zDb
110508  ){
110509    Index *pIdx = sqlite3FindIndex(db, zName, zDb);
110510    if( pIdx==0 ){
110511      Table *pTab = sqlite3FindTable(db, zName, zDb);
110512      if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
110513    }
110514    return pIdx;
110515  }
110516  
110517  /*
110518  ** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
110519  ** into the relevant Index.aSample[] arrays.
110520  **
110521  ** Arguments zSql1 and zSql2 must point to SQL statements that return
110522  ** data equivalent to the following (statements are different for stat3,
110523  ** see the caller of this function for details):
110524  **
110525  **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
110526  **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
110527  **
110528  ** where %Q is replaced with the database name before the SQL is executed.
110529  */
110530  static int loadStatTbl(
110531    sqlite3 *db,                  /* Database handle */
110532    int bStat3,                   /* Assume single column records only */
110533    const char *zSql1,            /* SQL statement 1 (see above) */
110534    const char *zSql2,            /* SQL statement 2 (see above) */
110535    const char *zDb               /* Database name (e.g. "main") */
110536  ){
110537    int rc;                       /* Result codes from subroutines */
110538    sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
110539    char *zSql;                   /* Text of the SQL statement */
110540    Index *pPrevIdx = 0;          /* Previous index in the loop */
110541    IndexSample *pSample;         /* A slot in pIdx->aSample[] */
110542  
110543    assert( db->lookaside.bDisable );
110544    zSql = sqlite3MPrintf(db, zSql1, zDb);
110545    if( !zSql ){
110546      return SQLITE_NOMEM_BKPT;
110547    }
110548    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
110549    sqlite3DbFree(db, zSql);
110550    if( rc ) return rc;
110551  
110552    while( sqlite3_step(pStmt)==SQLITE_ROW ){
110553      int nIdxCol = 1;              /* Number of columns in stat4 records */
110554  
110555      char *zIndex;   /* Index name */
110556      Index *pIdx;    /* Pointer to the index object */
110557      int nSample;    /* Number of samples */
110558      int nByte;      /* Bytes of space required */
110559      int i;          /* Bytes of space required */
110560      tRowcnt *pSpace;
110561  
110562      zIndex = (char *)sqlite3_column_text(pStmt, 0);
110563      if( zIndex==0 ) continue;
110564      nSample = sqlite3_column_int(pStmt, 1);
110565      pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
110566      assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
110567      /* Index.nSample is non-zero at this point if data has already been
110568      ** loaded from the stat4 table. In this case ignore stat3 data.  */
110569      if( pIdx==0 || pIdx->nSample ) continue;
110570      if( bStat3==0 ){
110571        assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
110572        if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
110573          nIdxCol = pIdx->nKeyCol;
110574        }else{
110575          nIdxCol = pIdx->nColumn;
110576        }
110577      }
110578      pIdx->nSampleCol = nIdxCol;
110579      nByte = sizeof(IndexSample) * nSample;
110580      nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
110581      nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
110582  
110583      pIdx->aSample = sqlite3DbMallocZero(db, nByte);
110584      if( pIdx->aSample==0 ){
110585        sqlite3_finalize(pStmt);
110586        return SQLITE_NOMEM_BKPT;
110587      }
110588      pSpace = (tRowcnt*)&pIdx->aSample[nSample];
110589      pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
110590      for(i=0; i<nSample; i++){
110591        pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
110592        pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
110593        pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
110594      }
110595      assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
110596    }
110597    rc = sqlite3_finalize(pStmt);
110598    if( rc ) return rc;
110599  
110600    zSql = sqlite3MPrintf(db, zSql2, zDb);
110601    if( !zSql ){
110602      return SQLITE_NOMEM_BKPT;
110603    }
110604    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
110605    sqlite3DbFree(db, zSql);
110606    if( rc ) return rc;
110607  
110608    while( sqlite3_step(pStmt)==SQLITE_ROW ){
110609      char *zIndex;                 /* Index name */
110610      Index *pIdx;                  /* Pointer to the index object */
110611      int nCol = 1;                 /* Number of columns in index */
110612  
110613      zIndex = (char *)sqlite3_column_text(pStmt, 0);
110614      if( zIndex==0 ) continue;
110615      pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
110616      if( pIdx==0 ) continue;
110617      /* This next condition is true if data has already been loaded from 
110618      ** the sqlite_stat4 table. In this case ignore stat3 data.  */
110619      nCol = pIdx->nSampleCol;
110620      if( bStat3 && nCol>1 ) continue;
110621      if( pIdx!=pPrevIdx ){
110622        initAvgEq(pPrevIdx);
110623        pPrevIdx = pIdx;
110624      }
110625      pSample = &pIdx->aSample[pIdx->nSample];
110626      decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
110627      decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
110628      decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
110629  
110630      /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
110631      ** This is in case the sample record is corrupted. In that case, the
110632      ** sqlite3VdbeRecordCompare() may read up to two varints past the
110633      ** end of the allocated buffer before it realizes it is dealing with
110634      ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
110635      ** a buffer overread.  */
110636      pSample->n = sqlite3_column_bytes(pStmt, 4);
110637      pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
110638      if( pSample->p==0 ){
110639        sqlite3_finalize(pStmt);
110640        return SQLITE_NOMEM_BKPT;
110641      }
110642      if( pSample->n ){
110643        memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
110644      }
110645      pIdx->nSample++;
110646    }
110647    rc = sqlite3_finalize(pStmt);
110648    if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
110649    return rc;
110650  }
110651  
110652  /*
110653  ** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
110654  ** the Index.aSample[] arrays of all indices.
110655  */
110656  static int loadStat4(sqlite3 *db, const char *zDb){
110657    int rc = SQLITE_OK;             /* Result codes from subroutines */
110658  
110659    assert( db->lookaside.bDisable );
110660    if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
110661      rc = loadStatTbl(db, 0,
110662        "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
110663        "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
110664        zDb
110665      );
110666    }
110667  
110668    if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
110669      rc = loadStatTbl(db, 1,
110670        "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
110671        "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
110672        zDb
110673      );
110674    }
110675  
110676    return rc;
110677  }
110678  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
110679  
110680  /*
110681  ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
110682  ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
110683  ** arrays. The contents of sqlite_stat3/4 are used to populate the
110684  ** Index.aSample[] arrays.
110685  **
110686  ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
110687  ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
110688  ** during compilation and the sqlite_stat3/4 table is present, no data is 
110689  ** read from it.
110690  **
110691  ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
110692  ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
110693  ** returned. However, in this case, data is read from the sqlite_stat1
110694  ** table (if it is present) before returning.
110695  **
110696  ** If an OOM error occurs, this function always sets db->mallocFailed.
110697  ** This means if the caller does not care about other errors, the return
110698  ** code may be ignored.
110699  */
110700  SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
110701    analysisInfo sInfo;
110702    HashElem *i;
110703    char *zSql;
110704    int rc = SQLITE_OK;
110705    Schema *pSchema = db->aDb[iDb].pSchema;
110706  
110707    assert( iDb>=0 && iDb<db->nDb );
110708    assert( db->aDb[iDb].pBt!=0 );
110709  
110710    /* Clear any prior statistics */
110711    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110712    for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
110713      Table *pTab = sqliteHashData(i);
110714      pTab->tabFlags &= ~TF_HasStat1;
110715    }
110716    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
110717      Index *pIdx = sqliteHashData(i);
110718      pIdx->hasStat1 = 0;
110719  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110720      sqlite3DeleteIndexSamples(db, pIdx);
110721      pIdx->aSample = 0;
110722  #endif
110723    }
110724  
110725    /* Load new statistics out of the sqlite_stat1 table */
110726    sInfo.db = db;
110727    sInfo.zDatabase = db->aDb[iDb].zDbSName;
110728    if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
110729      zSql = sqlite3MPrintf(db, 
110730          "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
110731      if( zSql==0 ){
110732        rc = SQLITE_NOMEM_BKPT;
110733      }else{
110734        rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
110735        sqlite3DbFree(db, zSql);
110736      }
110737    }
110738  
110739    /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
110740    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110741    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
110742      Index *pIdx = sqliteHashData(i);
110743      if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
110744    }
110745  
110746    /* Load the statistics from the sqlite_stat4 table. */
110747  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110748    if( rc==SQLITE_OK ){
110749      db->lookaside.bDisable++;
110750      rc = loadStat4(db, sInfo.zDatabase);
110751      db->lookaside.bDisable--;
110752    }
110753    for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
110754      Index *pIdx = sqliteHashData(i);
110755      sqlite3_free(pIdx->aiRowEst);
110756      pIdx->aiRowEst = 0;
110757    }
110758  #endif
110759  
110760    if( rc==SQLITE_NOMEM ){
110761      sqlite3OomFault(db);
110762    }
110763    return rc;
110764  }
110765  
110766  
110767  #endif /* SQLITE_OMIT_ANALYZE */
110768  
110769  /************** End of analyze.c *********************************************/
110770  /************** Begin file attach.c ******************************************/
110771  /*
110772  ** 2003 April 6
110773  **
110774  ** The author disclaims copyright to this source code.  In place of
110775  ** a legal notice, here is a blessing:
110776  **
110777  **    May you do good and not evil.
110778  **    May you find forgiveness for yourself and forgive others.
110779  **    May you share freely, never taking more than you give.
110780  **
110781  *************************************************************************
110782  ** This file contains code used to implement the ATTACH and DETACH commands.
110783  */
110784  /* #include "sqliteInt.h" */
110785  
110786  #ifndef SQLITE_OMIT_ATTACH
110787  /*
110788  ** Resolve an expression that was part of an ATTACH or DETACH statement. This
110789  ** is slightly different from resolving a normal SQL expression, because simple
110790  ** identifiers are treated as strings, not possible column names or aliases.
110791  **
110792  ** i.e. if the parser sees:
110793  **
110794  **     ATTACH DATABASE abc AS def
110795  **
110796  ** it treats the two expressions as literal strings 'abc' and 'def' instead of
110797  ** looking for columns of the same name.
110798  **
110799  ** This only applies to the root node of pExpr, so the statement:
110800  **
110801  **     ATTACH DATABASE abc||def AS 'db2'
110802  **
110803  ** will fail because neither abc or def can be resolved.
110804  */
110805  static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
110806  {
110807    int rc = SQLITE_OK;
110808    if( pExpr ){
110809      if( pExpr->op!=TK_ID ){
110810        rc = sqlite3ResolveExprNames(pName, pExpr);
110811      }else{
110812        pExpr->op = TK_STRING;
110813      }
110814    }
110815    return rc;
110816  }
110817  
110818  /*
110819  ** An SQL user-function registered to do the work of an ATTACH statement. The
110820  ** three arguments to the function come directly from an attach statement:
110821  **
110822  **     ATTACH DATABASE x AS y KEY z
110823  **
110824  **     SELECT sqlite_attach(x, y, z)
110825  **
110826  ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
110827  ** third argument.
110828  **
110829  ** If the db->init.reopenMemdb flags is set, then instead of attaching a
110830  ** new database, close the database on db->init.iDb and reopen it as an
110831  ** empty MemDB.
110832  */
110833  static void attachFunc(
110834    sqlite3_context *context,
110835    int NotUsed,
110836    sqlite3_value **argv
110837  ){
110838    int i;
110839    int rc = 0;
110840    sqlite3 *db = sqlite3_context_db_handle(context);
110841    const char *zName;
110842    const char *zFile;
110843    char *zPath = 0;
110844    char *zErr = 0;
110845    unsigned int flags;
110846    Db *aNew;                 /* New array of Db pointers */
110847    Db *pNew;                 /* Db object for the newly attached database */
110848    char *zErrDyn = 0;
110849    sqlite3_vfs *pVfs;
110850  
110851    UNUSED_PARAMETER(NotUsed);
110852    zFile = (const char *)sqlite3_value_text(argv[0]);
110853    zName = (const char *)sqlite3_value_text(argv[1]);
110854    if( zFile==0 ) zFile = "";
110855    if( zName==0 ) zName = "";
110856  
110857  #ifdef SQLITE_ENABLE_DESERIALIZE
110858  # define REOPEN_AS_MEMDB(db)  (db->init.reopenMemdb)
110859  #else
110860  # define REOPEN_AS_MEMDB(db)  (0)
110861  #endif
110862  
110863    if( REOPEN_AS_MEMDB(db) ){
110864      /* This is not a real ATTACH.  Instead, this routine is being called
110865      ** from sqlite3_deserialize() to close database db->init.iDb and
110866      ** reopen it as a MemDB */
110867      pVfs = sqlite3_vfs_find("memdb");
110868      if( pVfs==0 ) return;
110869      pNew = &db->aDb[db->init.iDb];
110870      if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
110871      pNew->pBt = 0;
110872      pNew->pSchema = 0;
110873      rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
110874    }else{
110875      /* This is a real ATTACH
110876      **
110877      ** Check for the following errors:
110878      **
110879      **     * Too many attached databases,
110880      **     * Transaction currently open
110881      **     * Specified database name already being used.
110882      */
110883      if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
110884        zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
110885          db->aLimit[SQLITE_LIMIT_ATTACHED]
110886        );
110887        goto attach_error;
110888      }
110889      for(i=0; i<db->nDb; i++){
110890        char *z = db->aDb[i].zDbSName;
110891        assert( z && zName );
110892        if( sqlite3StrICmp(z, zName)==0 ){
110893          zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
110894          goto attach_error;
110895        }
110896      }
110897    
110898      /* Allocate the new entry in the db->aDb[] array and initialize the schema
110899      ** hash tables.
110900      */
110901      if( db->aDb==db->aDbStatic ){
110902        aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
110903        if( aNew==0 ) return;
110904        memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
110905      }else{
110906        aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
110907        if( aNew==0 ) return;
110908      }
110909      db->aDb = aNew;
110910      pNew = &db->aDb[db->nDb];
110911      memset(pNew, 0, sizeof(*pNew));
110912    
110913      /* Open the database file. If the btree is successfully opened, use
110914      ** it to obtain the database schema. At this point the schema may
110915      ** or may not be initialized.
110916      */
110917      flags = db->openFlags;
110918      if( strcmp(db->pVfs->zName,"null")==0 ){
110919        pVfs = sqlite3_vfs_find(NULL); /* returns the default VFS */
110920      } else {
110921        pVfs = db->pVfs;
110922      }
110923      rc = sqlite3ParseUri(pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
110924      if( rc!=SQLITE_OK ){
110925        if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
110926        sqlite3_result_error(context, zErr, -1);
110927        sqlite3_free(zErr);
110928        return;
110929      }
110930      assert( pVfs );
110931      flags |= SQLITE_OPEN_MAIN_DB;
110932      rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
110933      db->nDb++;
110934      pNew->zDbSName = sqlite3DbStrDup(db, zName);
110935    }
110936    db->noSharedCache = 0;
110937    if( rc==SQLITE_CONSTRAINT ){
110938      rc = SQLITE_ERROR;
110939      zErrDyn = sqlite3MPrintf(db, "database is already attached");
110940    }else if( rc==SQLITE_OK ){
110941      Pager *pPager;
110942      pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
110943      if( !pNew->pSchema ){
110944        rc = SQLITE_NOMEM_BKPT;
110945      }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
110946        zErrDyn = sqlite3MPrintf(db, 
110947          "attached databases must use the same text encoding as main database");
110948        rc = SQLITE_ERROR;
110949      }
110950      sqlite3BtreeEnter(pNew->pBt);
110951      pPager = sqlite3BtreePager(pNew->pBt);
110952      sqlite3PagerLockingMode(pPager, db->dfltLockMode);
110953      sqlite3BtreeSecureDelete(pNew->pBt,
110954                               sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
110955  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110956      sqlite3BtreeSetPagerFlags(pNew->pBt,
110957                        PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
110958  #endif
110959      sqlite3BtreeLeave(pNew->pBt);
110960    }
110961    pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
110962    if( rc==SQLITE_OK && pNew->zDbSName==0 ){
110963      rc = SQLITE_NOMEM_BKPT;
110964    }
110965  
110966  
110967  #ifdef SQLITE_HAS_CODEC
110968    if( rc==SQLITE_OK ){
110969      extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
110970      extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
110971      int nKey;
110972      char *zKey;
110973      int t = sqlite3_value_type(argv[2]);
110974      switch( t ){
110975        case SQLITE_INTEGER:
110976        case SQLITE_FLOAT:
110977          zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
110978          rc = SQLITE_ERROR;
110979          break;
110980          
110981        case SQLITE_TEXT:
110982        case SQLITE_BLOB:
110983          nKey = sqlite3_value_bytes(argv[2]);
110984          zKey = (char *)sqlite3_value_blob(argv[2]);
110985          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
110986          break;
110987  
110988        case SQLITE_NULL:
110989          /* No key specified.  Use the key from URI filename, or if none,
110990          ** use the key from the main database. */
110991          if( sqlite3CodecQueryParameters(db, zName, zPath)==0 ){
110992            sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
110993            if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
110994              rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
110995            }
110996          }
110997          break;
110998      }
110999    }
111000  #endif
111001  
111002    /* If the file was opened successfully, read the schema for the new database.
111003    ** If this fails, or if opening the file failed, then close the file and 
111004    ** remove the entry from the db->aDb[] array. i.e. put everything back the
111005    ** way we found it.
111006    */
111007    if( rc==SQLITE_OK ){
111008      sqlite3BtreeEnterAll(db);
111009      db->init.iDb = 0;
111010      db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
111011      rc = sqlite3Init(db, &zErrDyn);
111012      sqlite3BtreeLeaveAll(db);
111013      assert( zErrDyn==0 || rc!=SQLITE_OK );
111014    }
111015  #ifdef SQLITE_USER_AUTHENTICATION
111016    if( rc==SQLITE_OK ){
111017      u8 newAuth = 0;
111018      rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
111019      if( newAuth<db->auth.authLevel ){
111020        rc = SQLITE_AUTH_USER;
111021      }
111022    }
111023  #endif
111024  
111025    /* enable the database branching, if requested */
111026    if( rc==SQLITE_OK ){
111027      rc = process_branch_uri(db, zName, zPath);
111028    }
111029    sqlite3_free( zPath );
111030  
111031    if( rc ){
111032      if( !REOPEN_AS_MEMDB(db) ){
111033        int iDb = db->nDb - 1;
111034        assert( iDb>=2 );
111035        if( db->aDb[iDb].pBt ){
111036          sqlite3BtreeClose(db->aDb[iDb].pBt);
111037          db->aDb[iDb].pBt = 0;
111038          db->aDb[iDb].pSchema = 0;
111039        }
111040        sqlite3ResetAllSchemasOfConnection(db);
111041        db->nDb = iDb;
111042        if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
111043          sqlite3OomFault(db);
111044          sqlite3DbFree(db, zErrDyn);
111045          zErrDyn = sqlite3MPrintf(db, "out of memory");
111046        }else if( zErrDyn==0 ){
111047          zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
111048        }
111049      }
111050      goto attach_error;
111051    }
111052    
111053    return;
111054  
111055  attach_error:
111056    /* Return an error if we get here */
111057    if( zErrDyn ){
111058      sqlite3_result_error(context, zErrDyn, -1);
111059      sqlite3DbFree(db, zErrDyn);
111060    }
111061    if( rc ) sqlite3_result_error_code(context, rc);
111062  }
111063  
111064  /*
111065  ** An SQL user-function registered to do the work of an DETACH statement. The
111066  ** three arguments to the function come directly from a detach statement:
111067  **
111068  **     DETACH DATABASE x
111069  **
111070  **     SELECT sqlite_detach(x)
111071  */
111072  static void detachFunc(
111073    sqlite3_context *context,
111074    int NotUsed,
111075    sqlite3_value **argv
111076  ){
111077    const char *zName = (const char *)sqlite3_value_text(argv[0]);
111078    sqlite3 *db = sqlite3_context_db_handle(context);
111079    int i;
111080    Db *pDb = 0;
111081    char zErr[128];
111082  
111083    UNUSED_PARAMETER(NotUsed);
111084  
111085    if( zName==0 ) zName = "";
111086    for(i=0; i<db->nDb; i++){
111087      pDb = &db->aDb[i];
111088      if( pDb->pBt==0 ) continue;
111089      if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
111090    }
111091  
111092    if( i>=db->nDb ){
111093      sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
111094      goto detach_error;
111095    }
111096    if( i<2 ){
111097      sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
111098      goto detach_error;
111099    }
111100    if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
111101      sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
111102      goto detach_error;
111103    }
111104  
111105    sqlite3BtreeClose(pDb->pBt);
111106    pDb->pBt = 0;
111107    pDb->pSchema = 0;
111108    sqlite3CollapseDatabaseArray(db);
111109    return;
111110  
111111  detach_error:
111112    sqlite3_result_error(context, zErr, -1);
111113  }
111114  
111115  /*
111116  ** This procedure generates VDBE code for a single invocation of either the
111117  ** sqlite_detach() or sqlite_attach() SQL user functions.
111118  */
111119  static void codeAttach(
111120    Parse *pParse,       /* The parser context */
111121    int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
111122    FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
111123    Expr *pAuthArg,      /* Expression to pass to authorization callback */
111124    Expr *pFilename,     /* Name of database file */
111125    Expr *pDbname,       /* Name of the database to use internally */
111126    Expr *pKey           /* Database key for encryption extension */
111127  ){
111128    int rc;
111129    NameContext sName;
111130    Vdbe *v;
111131    sqlite3* db = pParse->db;
111132    int regArgs;
111133  
111134    if( pParse->nErr ) goto attach_end;
111135    memset(&sName, 0, sizeof(NameContext));
111136    sName.pParse = pParse;
111137  
111138    if( 
111139        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
111140        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
111141        SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
111142    ){
111143      goto attach_end;
111144    }
111145  
111146  #ifndef SQLITE_OMIT_AUTHORIZATION
111147    if( pAuthArg ){
111148      char *zAuthArg;
111149      if( pAuthArg->op==TK_STRING ){
111150        zAuthArg = pAuthArg->u.zToken;
111151      }else{
111152        zAuthArg = 0;
111153      }
111154      rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
111155      if(rc!=SQLITE_OK ){
111156        goto attach_end;
111157      }
111158    }
111159  #endif /* SQLITE_OMIT_AUTHORIZATION */
111160  
111161  
111162    v = sqlite3GetVdbe(pParse);
111163    regArgs = sqlite3GetTempRange(pParse, 4);
111164    sqlite3ExprCode(pParse, pFilename, regArgs);
111165    sqlite3ExprCode(pParse, pDbname, regArgs+1);
111166    sqlite3ExprCode(pParse, pKey, regArgs+2);
111167  
111168    assert( v || db->mallocFailed );
111169    if( v ){
111170      sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
111171                        (char *)pFunc, P4_FUNCDEF);
111172      assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
111173      sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
111174   
111175      /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
111176      ** statement only). For DETACH, set it to false (expire all existing
111177      ** statements).
111178      */
111179      sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
111180    }
111181    
111182  attach_end:
111183    sqlite3ExprDelete(db, pFilename);
111184    sqlite3ExprDelete(db, pDbname);
111185    sqlite3ExprDelete(db, pKey);
111186  }
111187  
111188  /*
111189  ** Called by the parser to compile a DETACH statement.
111190  **
111191  **     DETACH pDbname
111192  */
111193  SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
111194    static const FuncDef detach_func = {
111195      1,                /* nArg */
111196      SQLITE_UTF8,      /* funcFlags */
111197      0,                /* pUserData */
111198      0,                /* pNext */
111199      detachFunc,       /* xSFunc */
111200      0,                /* xFinalize */
111201      0, 0,             /* xValue, xInverse */
111202      "sqlite_detach",  /* zName */
111203      {0}
111204    };
111205    codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
111206  }
111207  
111208  /*
111209  ** Called by the parser to compile an ATTACH statement.
111210  **
111211  **     ATTACH p AS pDbname KEY pKey
111212  */
111213  SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
111214    static const FuncDef attach_func = {
111215      3,                /* nArg */
111216      SQLITE_UTF8,      /* funcFlags */
111217      0,                /* pUserData */
111218      0,                /* pNext */
111219      attachFunc,       /* xSFunc */
111220      0,                /* xFinalize */
111221      0, 0,             /* xValue, xInverse */
111222      "sqlite_attach",  /* zName */
111223      {0}
111224    };
111225    codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
111226  }
111227  #endif /* SQLITE_OMIT_ATTACH */
111228  
111229  /*
111230  ** Initialize a DbFixer structure.  This routine must be called prior
111231  ** to passing the structure to one of the sqliteFixAAAA() routines below.
111232  */
111233  SQLITE_PRIVATE void sqlite3FixInit(
111234    DbFixer *pFix,      /* The fixer to be initialized */
111235    Parse *pParse,      /* Error messages will be written here */
111236    int iDb,            /* This is the database that must be used */
111237    const char *zType,  /* "view", "trigger", or "index" */
111238    const Token *pName  /* Name of the view, trigger, or index */
111239  ){
111240    sqlite3 *db;
111241  
111242    db = pParse->db;
111243    assert( db->nDb>iDb );
111244    pFix->pParse = pParse;
111245    pFix->zDb = db->aDb[iDb].zDbSName;
111246    pFix->pSchema = db->aDb[iDb].pSchema;
111247    pFix->zType = zType;
111248    pFix->pName = pName;
111249    pFix->bVarOnly = (iDb==1);
111250  }
111251  
111252  /*
111253  ** The following set of routines walk through the parse tree and assign
111254  ** a specific database to all table references where the database name
111255  ** was left unspecified in the original SQL statement.  The pFix structure
111256  ** must have been initialized by a prior call to sqlite3FixInit().
111257  **
111258  ** These routines are used to make sure that an index, trigger, or
111259  ** view in one database does not refer to objects in a different database.
111260  ** (Exception: indices, triggers, and views in the TEMP database are
111261  ** allowed to refer to anything.)  If a reference is explicitly made
111262  ** to an object in a different database, an error message is added to
111263  ** pParse->zErrMsg and these routines return non-zero.  If everything
111264  ** checks out, these routines return 0.
111265  */
111266  SQLITE_PRIVATE int sqlite3FixSrcList(
111267    DbFixer *pFix,       /* Context of the fixation */
111268    SrcList *pList       /* The Source list to check and modify */
111269  ){
111270    int i;
111271    const char *zDb;
111272    struct SrcList_item *pItem;
111273  
111274    if( NEVER(pList==0) ) return 0;
111275    zDb = pFix->zDb;
111276    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
111277      if( pFix->bVarOnly==0 ){
111278        if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
111279          sqlite3ErrorMsg(pFix->pParse,
111280              "%s %T cannot reference objects in database %s",
111281              pFix->zType, pFix->pName, pItem->zDatabase);
111282          return 1;
111283        }
111284        sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
111285        pItem->zDatabase = 0;
111286        pItem->pSchema = pFix->pSchema;
111287      }
111288  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
111289      if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
111290      if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
111291  #endif
111292      if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
111293        return 1;
111294      }
111295    }
111296    return 0;
111297  }
111298  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
111299  SQLITE_PRIVATE int sqlite3FixSelect(
111300    DbFixer *pFix,       /* Context of the fixation */
111301    Select *pSelect      /* The SELECT statement to be fixed to one database */
111302  ){
111303    while( pSelect ){
111304      if( sqlite3FixExprList(pFix, pSelect->pEList) ){
111305        return 1;
111306      }
111307      if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
111308        return 1;
111309      }
111310      if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
111311        return 1;
111312      }
111313      if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
111314        return 1;
111315      }
111316      if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
111317        return 1;
111318      }
111319      if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
111320        return 1;
111321      }
111322      if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
111323        return 1;
111324      }
111325      if( pSelect->pWith ){
111326        int i;
111327        for(i=0; i<pSelect->pWith->nCte; i++){
111328          if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
111329            return 1;
111330          }
111331        }
111332      }
111333      pSelect = pSelect->pPrior;
111334    }
111335    return 0;
111336  }
111337  SQLITE_PRIVATE int sqlite3FixExpr(
111338    DbFixer *pFix,     /* Context of the fixation */
111339    Expr *pExpr        /* The expression to be fixed to one database */
111340  ){
111341    while( pExpr ){
111342      if( pExpr->op==TK_VARIABLE ){
111343        if( pFix->pParse->db->init.busy ){
111344          pExpr->op = TK_NULL;
111345        }else{
111346          sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
111347          return 1;
111348        }
111349      }
111350      if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
111351      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
111352        if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
111353      }else{
111354        if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
111355      }
111356      if( sqlite3FixExpr(pFix, pExpr->pRight) ){
111357        return 1;
111358      }
111359      pExpr = pExpr->pLeft;
111360    }
111361    return 0;
111362  }
111363  SQLITE_PRIVATE int sqlite3FixExprList(
111364    DbFixer *pFix,     /* Context of the fixation */
111365    ExprList *pList    /* The expression to be fixed to one database */
111366  ){
111367    int i;
111368    struct ExprList_item *pItem;
111369    if( pList==0 ) return 0;
111370    for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
111371      if( sqlite3FixExpr(pFix, pItem->pExpr) ){
111372        return 1;
111373      }
111374    }
111375    return 0;
111376  }
111377  #endif
111378  
111379  #ifndef SQLITE_OMIT_TRIGGER
111380  SQLITE_PRIVATE int sqlite3FixTriggerStep(
111381    DbFixer *pFix,     /* Context of the fixation */
111382    TriggerStep *pStep /* The trigger step be fixed to one database */
111383  ){
111384    while( pStep ){
111385      if( sqlite3FixSelect(pFix, pStep->pSelect) ){
111386        return 1;
111387      }
111388      if( sqlite3FixExpr(pFix, pStep->pWhere) ){
111389        return 1;
111390      }
111391      if( sqlite3FixExprList(pFix, pStep->pExprList) ){
111392        return 1;
111393      }
111394  #ifndef SQLITE_OMIT_UPSERT
111395      if( pStep->pUpsert ){
111396        Upsert *pUp = pStep->pUpsert;
111397        if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
111398         || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
111399         || sqlite3FixExprList(pFix, pUp->pUpsertSet)
111400         || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
111401        ){
111402          return 1;
111403        }
111404      }
111405  #endif
111406      pStep = pStep->pNext;
111407    }
111408    return 0;
111409  }
111410  #endif
111411  
111412  /************** End of attach.c **********************************************/
111413  /************** Begin file auth.c ********************************************/
111414  /*
111415  ** 2003 January 11
111416  **
111417  ** The author disclaims copyright to this source code.  In place of
111418  ** a legal notice, here is a blessing:
111419  **
111420  **    May you do good and not evil.
111421  **    May you find forgiveness for yourself and forgive others.
111422  **    May you share freely, never taking more than you give.
111423  **
111424  *************************************************************************
111425  ** This file contains code used to implement the sqlite3_set_authorizer()
111426  ** API.  This facility is an optional feature of the library.  Embedded
111427  ** systems that do not need this facility may omit it by recompiling
111428  ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
111429  */
111430  /* #include "sqliteInt.h" */
111431  
111432  /*
111433  ** All of the code in this file may be omitted by defining a single
111434  ** macro.
111435  */
111436  #ifndef SQLITE_OMIT_AUTHORIZATION
111437  
111438  /*
111439  ** Set or clear the access authorization function.
111440  **
111441  ** The access authorization function is be called during the compilation
111442  ** phase to verify that the user has read and/or write access permission on
111443  ** various fields of the database.  The first argument to the auth function
111444  ** is a copy of the 3rd argument to this routine.  The second argument
111445  ** to the auth function is one of these constants:
111446  **
111447  **       SQLITE_CREATE_INDEX
111448  **       SQLITE_CREATE_TABLE
111449  **       SQLITE_CREATE_TEMP_INDEX
111450  **       SQLITE_CREATE_TEMP_TABLE
111451  **       SQLITE_CREATE_TEMP_TRIGGER
111452  **       SQLITE_CREATE_TEMP_VIEW
111453  **       SQLITE_CREATE_TRIGGER
111454  **       SQLITE_CREATE_VIEW
111455  **       SQLITE_DELETE
111456  **       SQLITE_DROP_INDEX
111457  **       SQLITE_DROP_TABLE
111458  **       SQLITE_DROP_TEMP_INDEX
111459  **       SQLITE_DROP_TEMP_TABLE
111460  **       SQLITE_DROP_TEMP_TRIGGER
111461  **       SQLITE_DROP_TEMP_VIEW
111462  **       SQLITE_DROP_TRIGGER
111463  **       SQLITE_DROP_VIEW
111464  **       SQLITE_INSERT
111465  **       SQLITE_PRAGMA
111466  **       SQLITE_READ
111467  **       SQLITE_SELECT
111468  **       SQLITE_TRANSACTION
111469  **       SQLITE_UPDATE
111470  **
111471  ** The third and fourth arguments to the auth function are the name of
111472  ** the table and the column that are being accessed.  The auth function
111473  ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
111474  ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
111475  ** means that the SQL statement will never-run - the sqlite3_exec() call
111476  ** will return with an error.  SQLITE_IGNORE means that the SQL statement
111477  ** should run but attempts to read the specified column will return NULL
111478  ** and attempts to write the column will be ignored.
111479  **
111480  ** Setting the auth function to NULL disables this hook.  The default
111481  ** setting of the auth function is NULL.
111482  */
111483  SQLITE_API int sqlite3_set_authorizer(
111484    sqlite3 *db,
111485    int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
111486    void *pArg
111487  ){
111488  #ifdef SQLITE_ENABLE_API_ARMOR
111489    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
111490  #endif
111491    sqlite3_mutex_enter(db->mutex);
111492    db->xAuth = (sqlite3_xauth)xAuth;
111493    db->pAuthArg = pArg;
111494    sqlite3ExpirePreparedStatements(db, 0);
111495    sqlite3_mutex_leave(db->mutex);
111496    return SQLITE_OK;
111497  }
111498  
111499  /*
111500  ** Write an error message into pParse->zErrMsg that explains that the
111501  ** user-supplied authorization function returned an illegal value.
111502  */
111503  static void sqliteAuthBadReturnCode(Parse *pParse){
111504    sqlite3ErrorMsg(pParse, "authorizer malfunction");
111505    pParse->rc = SQLITE_ERROR;
111506  }
111507  
111508  /*
111509  ** Invoke the authorization callback for permission to read column zCol from
111510  ** table zTab in database zDb. This function assumes that an authorization
111511  ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
111512  **
111513  ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
111514  ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
111515  ** is treated as SQLITE_DENY. In this case an error is left in pParse.
111516  */
111517  SQLITE_PRIVATE int sqlite3AuthReadCol(
111518    Parse *pParse,                  /* The parser context */
111519    const char *zTab,               /* Table name */
111520    const char *zCol,               /* Column name */
111521    int iDb                         /* Index of containing database. */
111522  ){
111523    sqlite3 *db = pParse->db;          /* Database handle */
111524    char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
111525    int rc;                            /* Auth callback return code */
111526  
111527    if( db->init.busy ) return SQLITE_OK;
111528    rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
111529  #ifdef SQLITE_USER_AUTHENTICATION
111530                   ,db->auth.zAuthUser
111531  #endif
111532                  );
111533    if( rc==SQLITE_DENY ){
111534      char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
111535      if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
111536      sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
111537      pParse->rc = SQLITE_AUTH;
111538    }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
111539      sqliteAuthBadReturnCode(pParse);
111540    }
111541    return rc;
111542  }
111543  
111544  /*
111545  ** The pExpr should be a TK_COLUMN expression.  The table referred to
111546  ** is in pTabList or else it is the NEW or OLD table of a trigger.  
111547  ** Check to see if it is OK to read this particular column.
111548  **
111549  ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
111550  ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
111551  ** then generate an error.
111552  */
111553  SQLITE_PRIVATE void sqlite3AuthRead(
111554    Parse *pParse,        /* The parser context */
111555    Expr *pExpr,          /* The expression to check authorization on */
111556    Schema *pSchema,      /* The schema of the expression */
111557    SrcList *pTabList     /* All table that pExpr might refer to */
111558  ){
111559    sqlite3 *db = pParse->db;
111560    Table *pTab = 0;      /* The table being read */
111561    const char *zCol;     /* Name of the column of the table */
111562    int iSrc;             /* Index in pTabList->a[] of table being read */
111563    int iDb;              /* The index of the database the expression refers to */
111564    int iCol;             /* Index of column in table */
111565  
111566    assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
111567    assert( !IN_RENAME_OBJECT || db->xAuth==0 );
111568    if( db->xAuth==0 ) return;
111569    iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
111570    if( iDb<0 ){
111571      /* An attempt to read a column out of a subquery or other
111572      ** temporary table. */
111573      return;
111574    }
111575  
111576    if( pExpr->op==TK_TRIGGER ){
111577      pTab = pParse->pTriggerTab;
111578    }else{
111579      assert( pTabList );
111580      for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
111581        if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
111582          pTab = pTabList->a[iSrc].pTab;
111583          break;
111584        }
111585      }
111586    }
111587    iCol = pExpr->iColumn;
111588    if( NEVER(pTab==0) ) return;
111589  
111590    if( iCol>=0 ){
111591      assert( iCol<pTab->nCol );
111592      zCol = pTab->aCol[iCol].zName;
111593    }else if( pTab->iPKey>=0 ){
111594      assert( pTab->iPKey<pTab->nCol );
111595      zCol = pTab->aCol[pTab->iPKey].zName;
111596    }else{
111597      zCol = "ROWID";
111598    }
111599    assert( iDb>=0 && iDb<db->nDb );
111600    if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
111601      pExpr->op = TK_NULL;
111602    }
111603  }
111604  
111605  /*
111606  ** Do an authorization check using the code and arguments given.  Return
111607  ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
111608  ** is returned, then the error count and error message in pParse are
111609  ** modified appropriately.
111610  */
111611  SQLITE_PRIVATE int sqlite3AuthCheck(
111612    Parse *pParse,
111613    int code,
111614    const char *zArg1,
111615    const char *zArg2,
111616    const char *zArg3
111617  ){
111618    sqlite3 *db = pParse->db;
111619    int rc;
111620  
111621    /* Don't do any authorization checks if the database is initialising
111622    ** or if the parser is being invoked from within sqlite3_declare_vtab.
111623    */
111624    assert( !IN_RENAME_OBJECT || db->xAuth==0 );
111625    if( db->init.busy || IN_SPECIAL_PARSE ){
111626      return SQLITE_OK;
111627    }
111628  
111629    if( db->xAuth==0 ){
111630      return SQLITE_OK;
111631    }
111632  
111633    /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
111634    ** callback are either NULL pointers or zero-terminated strings that
111635    ** contain additional details about the action to be authorized.
111636    **
111637    ** The following testcase() macros show that any of the 3rd through 6th
111638    ** parameters can be either NULL or a string. */
111639    testcase( zArg1==0 );
111640    testcase( zArg2==0 );
111641    testcase( zArg3==0 );
111642    testcase( pParse->zAuthContext==0 );
111643  
111644    rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
111645  #ifdef SQLITE_USER_AUTHENTICATION
111646                   ,db->auth.zAuthUser
111647  #endif
111648                  );
111649    if( rc==SQLITE_DENY ){
111650      sqlite3ErrorMsg(pParse, "not authorized");
111651      pParse->rc = SQLITE_AUTH;
111652    }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
111653      rc = SQLITE_DENY;
111654      sqliteAuthBadReturnCode(pParse);
111655    }
111656    return rc;
111657  }
111658  
111659  /*
111660  ** Push an authorization context.  After this routine is called, the
111661  ** zArg3 argument to authorization callbacks will be zContext until
111662  ** popped.  Or if pParse==0, this routine is a no-op.
111663  */
111664  SQLITE_PRIVATE void sqlite3AuthContextPush(
111665    Parse *pParse,
111666    AuthContext *pContext, 
111667    const char *zContext
111668  ){
111669    assert( pParse );
111670    pContext->pParse = pParse;
111671    pContext->zAuthContext = pParse->zAuthContext;
111672    pParse->zAuthContext = zContext;
111673  }
111674  
111675  /*
111676  ** Pop an authorization context that was previously pushed
111677  ** by sqlite3AuthContextPush
111678  */
111679  SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
111680    if( pContext->pParse ){
111681      pContext->pParse->zAuthContext = pContext->zAuthContext;
111682      pContext->pParse = 0;
111683    }
111684  }
111685  
111686  #endif /* SQLITE_OMIT_AUTHORIZATION */
111687  
111688  /************** End of auth.c ************************************************/
111689  /************** Begin file build.c *******************************************/
111690  /*
111691  ** 2001 September 15
111692  **
111693  ** The author disclaims copyright to this source code.  In place of
111694  ** a legal notice, here is a blessing:
111695  **
111696  **    May you do good and not evil.
111697  **    May you find forgiveness for yourself and forgive others.
111698  **    May you share freely, never taking more than you give.
111699  **
111700  *************************************************************************
111701  ** This file contains C code routines that are called by the SQLite parser
111702  ** when syntax rules are reduced.  The routines in this file handle the
111703  ** following kinds of SQL syntax:
111704  **
111705  **     CREATE TABLE
111706  **     DROP TABLE
111707  **     CREATE INDEX
111708  **     DROP INDEX
111709  **     creating ID lists
111710  **     BEGIN TRANSACTION
111711  **     COMMIT
111712  **     ROLLBACK
111713  */
111714  /* #include "sqliteInt.h" */
111715  
111716  #ifndef SQLITE_OMIT_SHARED_CACHE
111717  /*
111718  ** The TableLock structure is only used by the sqlite3TableLock() and
111719  ** codeTableLocks() functions.
111720  */
111721  struct TableLock {
111722    int iDb;               /* The database containing the table to be locked */
111723    int iTab;              /* The root page of the table to be locked */
111724    u8 isWriteLock;        /* True for write lock.  False for a read lock */
111725    const char *zLockName; /* Name of the table */
111726  };
111727  
111728  /*
111729  ** Record the fact that we want to lock a table at run-time.  
111730  **
111731  ** The table to be locked has root page iTab and is found in database iDb.
111732  ** A read or a write lock can be taken depending on isWritelock.
111733  **
111734  ** This routine just records the fact that the lock is desired.  The
111735  ** code to make the lock occur is generated by a later call to
111736  ** codeTableLocks() which occurs during sqlite3FinishCoding().
111737  */
111738  SQLITE_PRIVATE void sqlite3TableLock(
111739    Parse *pParse,     /* Parsing context */
111740    int iDb,           /* Index of the database containing the table to lock */
111741    int iTab,          /* Root page number of the table to be locked */
111742    u8 isWriteLock,    /* True for a write lock */
111743    const char *zName  /* Name of the table to be locked */
111744  ){
111745    Parse *pToplevel = sqlite3ParseToplevel(pParse);
111746    int i;
111747    int nBytes;
111748    TableLock *p;
111749    assert( iDb>=0 );
111750  
111751    if( iDb==1 ) return;
111752    if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
111753    for(i=0; i<pToplevel->nTableLock; i++){
111754      p = &pToplevel->aTableLock[i];
111755      if( p->iDb==iDb && p->iTab==iTab ){
111756        p->isWriteLock = (p->isWriteLock || isWriteLock);
111757        return;
111758      }
111759    }
111760  
111761    nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
111762    pToplevel->aTableLock =
111763        sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
111764    if( pToplevel->aTableLock ){
111765      p = &pToplevel->aTableLock[pToplevel->nTableLock++];
111766      p->iDb = iDb;
111767      p->iTab = iTab;
111768      p->isWriteLock = isWriteLock;
111769      p->zLockName = zName;
111770    }else{
111771      pToplevel->nTableLock = 0;
111772      sqlite3OomFault(pToplevel->db);
111773    }
111774  }
111775  
111776  /*
111777  ** Code an OP_TableLock instruction for each table locked by the
111778  ** statement (configured by calls to sqlite3TableLock()).
111779  */
111780  static void codeTableLocks(Parse *pParse){
111781    int i;
111782    Vdbe *pVdbe; 
111783  
111784    pVdbe = sqlite3GetVdbe(pParse);
111785    assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
111786  
111787    for(i=0; i<pParse->nTableLock; i++){
111788      TableLock *p = &pParse->aTableLock[i];
111789      int p1 = p->iDb;
111790      sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
111791                        p->zLockName, P4_STATIC);
111792    }
111793  }
111794  #else
111795    #define codeTableLocks(x)
111796  #endif
111797  
111798  /*
111799  ** Return TRUE if the given yDbMask object is empty - if it contains no
111800  ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
111801  ** macros when SQLITE_MAX_ATTACHED is greater than 30.
111802  */
111803  #if SQLITE_MAX_ATTACHED>30
111804  SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
111805    int i;
111806    for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
111807    return 1;
111808  }
111809  #endif
111810  
111811  /*
111812  ** This routine is called after a single SQL statement has been
111813  ** parsed and a VDBE program to execute that statement has been
111814  ** prepared.  This routine puts the finishing touches on the
111815  ** VDBE program and resets the pParse structure for the next
111816  ** parse.
111817  **
111818  ** Note that if an error occurred, it might be the case that
111819  ** no VDBE code was generated.
111820  */
111821  SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
111822    sqlite3 *db;
111823    Vdbe *v;
111824  
111825    assert( pParse->pToplevel==0 );
111826    db = pParse->db;
111827    if( pParse->nested ) return;
111828    if( db->mallocFailed || pParse->nErr ){
111829      if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
111830      return;
111831    }
111832  
111833    /* Begin by generating some termination code at the end of the
111834    ** vdbe program
111835    */
111836    v = sqlite3GetVdbe(pParse);
111837    assert( !pParse->isMultiWrite 
111838         || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
111839    if( v ){
111840      sqlite3VdbeAddOp0(v, OP_Halt);
111841  
111842  #if SQLITE_USER_AUTHENTICATION
111843      if( pParse->nTableLock>0 && db->init.busy==0 ){
111844        sqlite3UserAuthInit(db);
111845        if( db->auth.authLevel<UAUTH_User ){
111846          sqlite3ErrorMsg(pParse, "user not authenticated");
111847          pParse->rc = SQLITE_AUTH_USER;
111848          return;
111849        }
111850      }
111851  #endif
111852  
111853      /* The cookie mask contains one bit for each database file open.
111854      ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
111855      ** set for each database that is used.  Generate code to start a
111856      ** transaction on each used database and to verify the schema cookie
111857      ** on each used database.
111858      */
111859      if( db->mallocFailed==0 
111860       && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
111861      ){
111862        int iDb, i;
111863        assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
111864        sqlite3VdbeJumpHere(v, 0);
111865        for(iDb=0; iDb<db->nDb; iDb++){
111866          Schema *pSchema;
111867          if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
111868          sqlite3VdbeUsesBtree(v, iDb);
111869          pSchema = db->aDb[iDb].pSchema;
111870          sqlite3VdbeAddOp4Int(v,
111871            OP_Transaction,                    /* Opcode */
111872            iDb,                               /* P1 */
111873            DbMaskTest(pParse->writeMask,iDb), /* P2 */
111874            pSchema->schema_cookie,            /* P3 */
111875            pSchema->iGeneration               /* P4 */
111876          );
111877          if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
111878          VdbeComment((v,
111879                "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
111880        }
111881  #ifndef SQLITE_OMIT_VIRTUALTABLE
111882        for(i=0; i<pParse->nVtabLock; i++){
111883          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
111884          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
111885        }
111886        pParse->nVtabLock = 0;
111887  #endif
111888  
111889        /* Once all the cookies have been verified and transactions opened, 
111890        ** obtain the required table-locks. This is a no-op unless the 
111891        ** shared-cache feature is enabled.
111892        */
111893        codeTableLocks(pParse);
111894  
111895        /* Initialize any AUTOINCREMENT data structures required.
111896        */
111897        sqlite3AutoincrementBegin(pParse);
111898  
111899        /* Code constant expressions that where factored out of inner loops */
111900        if( pParse->pConstExpr ){
111901          ExprList *pEL = pParse->pConstExpr;
111902          pParse->okConstFactor = 0;
111903          for(i=0; i<pEL->nExpr; i++){
111904            sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
111905          }
111906        }
111907  
111908        /* Finally, jump back to the beginning of the executable code. */
111909        sqlite3VdbeGoto(v, 1);
111910      }
111911    }
111912  
111913  
111914    /* Get the VDBE program ready for execution
111915    */
111916    if( v && pParse->nErr==0 && !db->mallocFailed ){
111917      /* A minimum of one cursor is required if autoincrement is used
111918      *  See ticket [a696379c1f08866] */
111919      assert( pParse->pAinc==0 || pParse->nTab>0 );
111920      sqlite3VdbeMakeReady(v, pParse);
111921      pParse->rc = SQLITE_DONE;
111922    }else{
111923      pParse->rc = SQLITE_ERROR;
111924    }
111925  }
111926  
111927  /*
111928  ** Run the parser and code generator recursively in order to generate
111929  ** code for the SQL statement given onto the end of the pParse context
111930  ** currently under construction.  When the parser is run recursively
111931  ** this way, the final OP_Halt is not appended and other initialization
111932  ** and finalization steps are omitted because those are handling by the
111933  ** outermost parser.
111934  **
111935  ** Not everything is nestable.  This facility is designed to permit
111936  ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
111937  ** care if you decide to try to use this routine for some other purposes.
111938  */
111939  SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
111940    va_list ap;
111941    char *zSql;
111942    char *zErrMsg = 0;
111943    sqlite3 *db = pParse->db;
111944    char saveBuf[PARSE_TAIL_SZ];
111945  
111946    if( pParse->nErr ) return;
111947    assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
111948    va_start(ap, zFormat);
111949    zSql = sqlite3VMPrintf(db, zFormat, ap);
111950    va_end(ap);
111951    if( zSql==0 ){
111952      return;   /* A malloc must have failed */
111953    }
111954    pParse->nested++;
111955    memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
111956    memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
111957    sqlite3RunParser(pParse, zSql, &zErrMsg);
111958    sqlite3DbFree(db, zErrMsg);
111959    sqlite3DbFree(db, zSql);
111960    memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
111961    pParse->nested--;
111962  }
111963  
111964  #if SQLITE_USER_AUTHENTICATION
111965  /*
111966  ** Return TRUE if zTable is the name of the system table that stores the
111967  ** list of users and their access credentials.
111968  */
111969  SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
111970    return sqlite3_stricmp(zTable, "sqlite_user")==0;
111971  }
111972  #endif
111973  
111974  /*
111975  ** Locate the in-memory structure that describes a particular database
111976  ** table given the name of that table and (optionally) the name of the
111977  ** database containing the table.  Return NULL if not found.
111978  **
111979  ** If zDatabase is 0, all databases are searched for the table and the
111980  ** first matching table is returned.  (No checking for duplicate table
111981  ** names is done.)  The search order is TEMP first, then MAIN, then any
111982  ** auxiliary databases added using the ATTACH command.
111983  **
111984  ** See also sqlite3LocateTable().
111985  */
111986  SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
111987    Table *p = 0;
111988    int i;
111989  
111990    /* All mutexes are required for schema access.  Make sure we hold them. */
111991    assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
111992  #if SQLITE_USER_AUTHENTICATION
111993    /* Only the admin user is allowed to know that the sqlite_user table
111994    ** exists */
111995    if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
111996      return 0;
111997    }
111998  #endif
111999    while(1){
112000      for(i=OMIT_TEMPDB; i<db->nDb; i++){
112001        int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
112002        if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
112003          assert( sqlite3SchemaMutexHeld(db, j, 0) );
112004          p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
112005          if( p ) return p;
112006        }
112007      }
112008      /* Not found.  If the name we were looking for was temp.sqlite_master
112009      ** then change the name to sqlite_temp_master and try again. */
112010      if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
112011      if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
112012      zName = TEMP_MASTER_NAME;
112013    }
112014    return 0;
112015  }
112016  
112017  /*
112018  ** Locate the in-memory structure that describes a particular database
112019  ** table given the name of that table and (optionally) the name of the
112020  ** database containing the table.  Return NULL if not found.  Also leave an
112021  ** error message in pParse->zErrMsg.
112022  **
112023  ** The difference between this routine and sqlite3FindTable() is that this
112024  ** routine leaves an error message in pParse->zErrMsg where
112025  ** sqlite3FindTable() does not.
112026  */
112027  SQLITE_PRIVATE Table *sqlite3LocateTable(
112028    Parse *pParse,         /* context in which to report errors */
112029    u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
112030    const char *zName,     /* Name of the table we are looking for */
112031    const char *zDbase     /* Name of the database.  Might be NULL */
112032  ){
112033    Table *p;
112034    sqlite3 *db = pParse->db;
112035  
112036    /* Read the database schema. If an error occurs, leave an error message
112037    ** and code in pParse and return NULL. */
112038    if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 
112039     && SQLITE_OK!=sqlite3ReadSchema(pParse)
112040    ){
112041      return 0;
112042    }
112043  
112044    p = sqlite3FindTable(db, zName, zDbase);
112045    if( p==0 ){
112046  #ifndef SQLITE_OMIT_VIRTUALTABLE
112047      /* If zName is the not the name of a table in the schema created using
112048      ** CREATE, then check to see if it is the name of an virtual table that
112049      ** can be an eponymous virtual table. */
112050      if( pParse->disableVtab==0 ){
112051        Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
112052        if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
112053          pMod = sqlite3PragmaVtabRegister(db, zName);
112054        }
112055        if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
112056          return pMod->pEpoTab;
112057        }
112058      }
112059  #endif
112060      if( flags & LOCATE_NOERR ) return 0;
112061      pParse->checkSchema = 1;
112062    }else if( IsVirtual(p) && pParse->disableVtab ){
112063      p = 0;
112064    }
112065  
112066    if( p==0 ){
112067      const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
112068      if( zDbase ){
112069        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
112070      }else{
112071        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
112072      }
112073    }
112074  
112075    return p;
112076  }
112077  
112078  /*
112079  ** Locate the table identified by *p.
112080  **
112081  ** This is a wrapper around sqlite3LocateTable(). The difference between
112082  ** sqlite3LocateTable() and this function is that this function restricts
112083  ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
112084  ** non-NULL if it is part of a view or trigger program definition. See
112085  ** sqlite3FixSrcList() for details.
112086  */
112087  SQLITE_PRIVATE Table *sqlite3LocateTableItem(
112088    Parse *pParse, 
112089    u32 flags,
112090    struct SrcList_item *p
112091  ){
112092    const char *zDb;
112093    assert( p->pSchema==0 || p->zDatabase==0 );
112094    if( p->pSchema ){
112095      int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
112096      zDb = pParse->db->aDb[iDb].zDbSName;
112097    }else{
112098      zDb = p->zDatabase;
112099    }
112100    return sqlite3LocateTable(pParse, flags, p->zName, zDb);
112101  }
112102  
112103  /*
112104  ** Locate the in-memory structure that describes 
112105  ** a particular index given the name of that index
112106  ** and the name of the database that contains the index.
112107  ** Return NULL if not found.
112108  **
112109  ** If zDatabase is 0, all databases are searched for the
112110  ** table and the first matching index is returned.  (No checking
112111  ** for duplicate index names is done.)  The search order is
112112  ** TEMP first, then MAIN, then any auxiliary databases added
112113  ** using the ATTACH command.
112114  */
112115  SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
112116    Index *p = 0;
112117    int i;
112118    /* All mutexes are required for schema access.  Make sure we hold them. */
112119    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
112120    for(i=OMIT_TEMPDB; i<db->nDb; i++){
112121      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
112122      Schema *pSchema = db->aDb[j].pSchema;
112123      assert( pSchema );
112124      if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
112125      assert( sqlite3SchemaMutexHeld(db, j, 0) );
112126      p = sqlite3HashFind(&pSchema->idxHash, zName);
112127      if( p ) break;
112128    }
112129    return p;
112130  }
112131  
112132  /*
112133  ** Reclaim the memory used by an index
112134  */
112135  SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
112136  #ifndef SQLITE_OMIT_ANALYZE
112137    sqlite3DeleteIndexSamples(db, p);
112138  #endif
112139    sqlite3ExprDelete(db, p->pPartIdxWhere);
112140    sqlite3ExprListDelete(db, p->aColExpr);
112141    sqlite3DbFree(db, p->zColAff);
112142    if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
112143  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112144    sqlite3_free(p->aiRowEst);
112145  #endif
112146    sqlite3DbFree(db, p);
112147  }
112148  
112149  /*
112150  ** For the index called zIdxName which is found in the database iDb,
112151  ** unlike that index from its Table then remove the index from
112152  ** the index hash table and free all memory structures associated
112153  ** with the index.
112154  */
112155  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
112156    Index *pIndex;
112157    Hash *pHash;
112158  
112159    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112160    pHash = &db->aDb[iDb].pSchema->idxHash;
112161    pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
112162    if( ALWAYS(pIndex) ){
112163      if( pIndex->pTable->pIndex==pIndex ){
112164        pIndex->pTable->pIndex = pIndex->pNext;
112165      }else{
112166        Index *p;
112167        /* Justification of ALWAYS();  The index must be on the list of
112168        ** indices. */
112169        p = pIndex->pTable->pIndex;
112170        while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
112171        if( ALWAYS(p && p->pNext==pIndex) ){
112172          p->pNext = pIndex->pNext;
112173        }
112174      }
112175      sqlite3FreeIndex(db, pIndex);
112176    }
112177    db->mDbFlags |= DBFLAG_SchemaChange;
112178  }
112179  
112180  /*
112181  ** Look through the list of open database files in db->aDb[] and if
112182  ** any have been closed, remove them from the list.  Reallocate the
112183  ** db->aDb[] structure to a smaller size, if possible.
112184  **
112185  ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
112186  ** are never candidates for being collapsed.
112187  */
112188  SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
112189    int i, j;
112190    for(i=j=2; i<db->nDb; i++){
112191      struct Db *pDb = &db->aDb[i];
112192      if( pDb->pBt==0 ){
112193        sqlite3DbFree(db, pDb->zDbSName);
112194        pDb->zDbSName = 0;
112195        continue;
112196      }
112197      if( j<i ){
112198        db->aDb[j] = db->aDb[i];
112199      }
112200      j++;
112201    }
112202    db->nDb = j;
112203    if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
112204      memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
112205      sqlite3DbFree(db, db->aDb);
112206      db->aDb = db->aDbStatic;
112207    }
112208  }
112209  
112210  /*
112211  ** Reset the schema for the database at index iDb.  Also reset the
112212  ** TEMP schema.  The reset is deferred if db->nSchemaLock is not zero.
112213  ** Deferred resets may be run by calling with iDb<0.
112214  */
112215  SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
112216    int i;
112217    assert( iDb<db->nDb );
112218  
112219    if( iDb>=0 ){
112220      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112221      DbSetProperty(db, iDb, DB_ResetWanted);
112222      DbSetProperty(db, 1, DB_ResetWanted);
112223      db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
112224    }
112225  
112226    if( db->nSchemaLock==0 ){
112227      for(i=0; i<db->nDb; i++){
112228        if( DbHasProperty(db, i, DB_ResetWanted) ){
112229          sqlite3SchemaClear(db->aDb[i].pSchema);
112230        }
112231      }
112232    }
112233  }
112234  
112235  /*
112236  ** Erase all schema information from all attached databases (including
112237  ** "main" and "temp") for a single database connection.
112238  */
112239  SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
112240    int i;
112241    sqlite3BtreeEnterAll(db);
112242    for(i=0; i<db->nDb; i++){
112243      Db *pDb = &db->aDb[i];
112244      if( pDb->pSchema ){
112245        if( db->nSchemaLock==0 ){
112246          sqlite3SchemaClear(pDb->pSchema);
112247        }else{
112248          DbSetProperty(db, i, DB_ResetWanted);
112249        }
112250      }
112251    }
112252    db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
112253    sqlite3VtabUnlockList(db);
112254    sqlite3BtreeLeaveAll(db);
112255    if( db->nSchemaLock==0 ){
112256      sqlite3CollapseDatabaseArray(db);
112257    }
112258  }
112259  
112260  /*
112261  ** This routine is called when a commit occurs.
112262  */
112263  SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
112264    db->mDbFlags &= ~DBFLAG_SchemaChange;
112265  }
112266  
112267  /*
112268  ** Delete memory allocated for the column names of a table or view (the
112269  ** Table.aCol[] array).
112270  */
112271  SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
112272    int i;
112273    Column *pCol;
112274    assert( pTable!=0 );
112275    if( (pCol = pTable->aCol)!=0 ){
112276      for(i=0; i<pTable->nCol; i++, pCol++){
112277        sqlite3DbFree(db, pCol->zName);
112278        sqlite3ExprDelete(db, pCol->pDflt);
112279        sqlite3DbFree(db, pCol->zColl);
112280      }
112281      sqlite3DbFree(db, pTable->aCol);
112282    }
112283  }
112284  
112285  /*
112286  ** Remove the memory data structures associated with the given
112287  ** Table.  No changes are made to disk by this routine.
112288  **
112289  ** This routine just deletes the data structure.  It does not unlink
112290  ** the table data structure from the hash table.  But it does destroy
112291  ** memory structures of the indices and foreign keys associated with 
112292  ** the table.
112293  **
112294  ** The db parameter is optional.  It is needed if the Table object 
112295  ** contains lookaside memory.  (Table objects in the schema do not use
112296  ** lookaside memory, but some ephemeral Table objects do.)  Or the
112297  ** db parameter can be used with db->pnBytesFreed to measure the memory
112298  ** used by the Table object.
112299  */
112300  static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
112301    Index *pIndex, *pNext;
112302  
112303  #ifdef SQLITE_DEBUG
112304    /* Record the number of outstanding lookaside allocations in schema Tables
112305    ** prior to doing any free() operations.  Since schema Tables do not use
112306    ** lookaside, this number should not change. */
112307    int nLookaside = 0;
112308    if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
112309      nLookaside = sqlite3LookasideUsed(db, 0);
112310    }
112311  #endif
112312  
112313    /* Delete all indices associated with this table. */
112314    for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
112315      pNext = pIndex->pNext;
112316      assert( pIndex->pSchema==pTable->pSchema
112317           || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
112318      if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
112319        char *zName = pIndex->zName; 
112320        TESTONLY ( Index *pOld = ) sqlite3HashInsert(
112321           &pIndex->pSchema->idxHash, zName, 0
112322        );
112323        assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
112324        assert( pOld==pIndex || pOld==0 );
112325      }
112326      sqlite3FreeIndex(db, pIndex);
112327    }
112328  
112329    /* Delete any foreign keys attached to this table. */
112330    sqlite3FkDelete(db, pTable);
112331  
112332    /* Delete the Table structure itself.
112333    */
112334    sqlite3DeleteColumnNames(db, pTable);
112335    sqlite3DbFree(db, pTable->zName);
112336    sqlite3DbFree(db, pTable->zColAff);
112337    sqlite3SelectDelete(db, pTable->pSelect);
112338    sqlite3ExprListDelete(db, pTable->pCheck);
112339  #ifndef SQLITE_OMIT_VIRTUALTABLE
112340    sqlite3VtabClear(db, pTable);
112341  #endif
112342    sqlite3DbFree(db, pTable);
112343  
112344    /* Verify that no lookaside memory was used by schema tables */
112345    assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
112346  }
112347  SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
112348    /* Do not delete the table until the reference count reaches zero. */
112349    if( !pTable ) return;
112350    if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
112351    deleteTable(db, pTable);
112352  }
112353  
112354  
112355  /*
112356  ** Unlink the given table from the hash tables and the delete the
112357  ** table structure with all its indices and foreign keys.
112358  */
112359  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
112360    Table *p;
112361    Db *pDb;
112362  
112363    assert( db!=0 );
112364    assert( iDb>=0 && iDb<db->nDb );
112365    assert( zTabName );
112366    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112367    testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
112368    pDb = &db->aDb[iDb];
112369    p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
112370    sqlite3DeleteTable(db, p);
112371    db->mDbFlags |= DBFLAG_SchemaChange;
112372  }
112373  
112374  /*
112375  ** Given a token, return a string that consists of the text of that
112376  ** token.  Space to hold the returned string
112377  ** is obtained from sqliteMalloc() and must be freed by the calling
112378  ** function.
112379  **
112380  ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
112381  ** surround the body of the token are removed.
112382  **
112383  ** Tokens are often just pointers into the original SQL text and so
112384  ** are not \000 terminated and are not persistent.  The returned string
112385  ** is \000 terminated and is persistent.
112386  */
112387  SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
112388    char *zName;
112389    if( pName ){
112390      zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
112391      sqlite3Dequote(zName);
112392    }else{
112393      zName = 0;
112394    }
112395    return zName;
112396  }
112397  
112398  /*
112399  ** Open the sqlite_master table stored in database number iDb for
112400  ** writing. The table is opened using cursor 0.
112401  */
112402  SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
112403    Vdbe *v = sqlite3GetVdbe(p);
112404    sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
112405    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
112406    if( p->nTab==0 ){
112407      p->nTab = 1;
112408    }
112409  }
112410  
112411  /*
112412  ** Parameter zName points to a nul-terminated buffer containing the name
112413  ** of a database ("main", "temp" or the name of an attached db). This
112414  ** function returns the index of the named database in db->aDb[], or
112415  ** -1 if the named db cannot be found.
112416  */
112417  SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
112418    int i = -1;         /* Database number */
112419    if( zName ){
112420      Db *pDb;
112421      for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
112422        if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
112423        /* "main" is always an acceptable alias for the primary database
112424        ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
112425        if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
112426      }
112427    }
112428    return i;
112429  }
112430  
112431  /*
112432  ** The token *pName contains the name of a database (either "main" or
112433  ** "temp" or the name of an attached db). This routine returns the
112434  ** index of the named database in db->aDb[], or -1 if the named db 
112435  ** does not exist.
112436  */
112437  SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
112438    int i;                               /* Database number */
112439    char *zName;                         /* Name we are searching for */
112440    zName = sqlite3NameFromToken(db, pName);
112441    i = sqlite3FindDbName(db, zName);
112442    sqlite3DbFree(db, zName);
112443    return i;
112444  }
112445  
112446  /* The table or view or trigger name is passed to this routine via tokens
112447  ** pName1 and pName2. If the table name was fully qualified, for example:
112448  **
112449  ** CREATE TABLE xxx.yyy (...);
112450  ** 
112451  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
112452  ** the table name is not fully qualified, i.e.:
112453  **
112454  ** CREATE TABLE yyy(...);
112455  **
112456  ** Then pName1 is set to "yyy" and pName2 is "".
112457  **
112458  ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
112459  ** pName2) that stores the unqualified table name.  The index of the
112460  ** database "xxx" is returned.
112461  */
112462  SQLITE_PRIVATE int sqlite3TwoPartName(
112463    Parse *pParse,      /* Parsing and code generating context */
112464    Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
112465    Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
112466    Token **pUnqual     /* Write the unqualified object name here */
112467  ){
112468    int iDb;                    /* Database holding the object */
112469    sqlite3 *db = pParse->db;
112470  
112471    assert( pName2!=0 );
112472    if( pName2->n>0 ){
112473      if( db->init.busy ) {
112474        sqlite3ErrorMsg(pParse, "corrupt database");
112475        return -1;
112476      }
112477      *pUnqual = pName2;
112478      iDb = sqlite3FindDb(db, pName1);
112479      if( iDb<0 ){
112480        sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
112481        return -1;
112482      }
112483    }else{
112484      assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
112485               || (db->mDbFlags & DBFLAG_Vacuum)!=0);
112486      iDb = db->init.iDb;
112487      *pUnqual = pName1;
112488    }
112489    return iDb;
112490  }
112491  
112492  /*
112493  ** True if PRAGMA writable_schema is ON
112494  */
112495  SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
112496    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
112497    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
112498                 SQLITE_WriteSchema );
112499    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
112500                 SQLITE_Defensive );
112501    testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
112502                 (SQLITE_WriteSchema|SQLITE_Defensive) );
112503    return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
112504  }
112505  
112506  /*
112507  ** This routine is used to check if the UTF-8 string zName is a legal
112508  ** unqualified name for a new schema object (table, index, view or
112509  ** trigger). All names are legal except those that begin with the string
112510  ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
112511  ** is reserved for internal use.
112512  */
112513  SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
112514    if( !pParse->db->init.busy && pParse->nested==0 
112515            && sqlite3WritableSchema(pParse->db)==0
112516            && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
112517      sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
112518      return SQLITE_ERROR;
112519    }
112520    return SQLITE_OK;
112521  }
112522  
112523  /*
112524  ** Return the PRIMARY KEY index of a table
112525  */
112526  SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
112527    Index *p;
112528    for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
112529    return p;
112530  }
112531  
112532  /*
112533  ** Return the column of index pIdx that corresponds to table
112534  ** column iCol.  Return -1 if not found.
112535  */
112536  SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
112537    int i;
112538    for(i=0; i<pIdx->nColumn; i++){
112539      if( iCol==pIdx->aiColumn[i] ) return i;
112540    }
112541    return -1;
112542  }
112543  
112544  /*
112545  ** Begin constructing a new table representation in memory.  This is
112546  ** the first of several action routines that get called in response
112547  ** to a CREATE TABLE statement.  In particular, this routine is called
112548  ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
112549  ** flag is true if the table should be stored in the auxiliary database
112550  ** file instead of in the main database file.  This is normally the case
112551  ** when the "TEMP" or "TEMPORARY" keyword occurs in between
112552  ** CREATE and TABLE.
112553  **
112554  ** The new table record is initialized and put in pParse->pNewTable.
112555  ** As more of the CREATE TABLE statement is parsed, additional action
112556  ** routines will be called to add more information to this record.
112557  ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
112558  ** is called to complete the construction of the new table record.
112559  */
112560  SQLITE_PRIVATE void sqlite3StartTable(
112561    Parse *pParse,   /* Parser context */
112562    Token *pName1,   /* First part of the name of the table or view */
112563    Token *pName2,   /* Second part of the name of the table or view */
112564    int isTemp,      /* True if this is a TEMP table */
112565    int isView,      /* True if this is a VIEW */
112566    int isVirtual,   /* True if this is a VIRTUAL table */
112567    int noErr        /* Do nothing if table already exists */
112568  ){
112569    Table *pTable;
112570    char *zName = 0; /* The name of the new table */
112571    sqlite3 *db = pParse->db;
112572    Vdbe *v;
112573    int iDb;         /* Database number to create the table in */
112574    Token *pName;    /* Unqualified name of the table to create */
112575  
112576    if( db->init.busy && db->init.newTnum==1 ){
112577      /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
112578      iDb = db->init.iDb;
112579      zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
112580      pName = pName1;
112581    }else{
112582      /* The common case */
112583      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
112584      if( iDb<0 ) return;
112585      if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
112586        /* If creating a temp table, the name may not be qualified. Unless 
112587        ** the database name is "temp" anyway.  */
112588        sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
112589        return;
112590      }
112591      if( !OMIT_TEMPDB && isTemp ) iDb = 1;
112592      zName = sqlite3NameFromToken(db, pName);
112593      if( IN_RENAME_OBJECT ){
112594        sqlite3RenameTokenMap(pParse, (void*)zName, pName);
112595      }
112596    }
112597    pParse->sNameToken = *pName;
112598    if( zName==0 ) return;
112599    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
112600      goto begin_table_error;
112601    }
112602    if( db->init.iDb==1 ) isTemp = 1;
112603  #ifndef SQLITE_OMIT_AUTHORIZATION
112604    assert( isTemp==0 || isTemp==1 );
112605    assert( isView==0 || isView==1 );
112606    {
112607      static const u8 aCode[] = {
112608         SQLITE_CREATE_TABLE,
112609         SQLITE_CREATE_TEMP_TABLE,
112610         SQLITE_CREATE_VIEW,
112611         SQLITE_CREATE_TEMP_VIEW
112612      };
112613      char *zDb = db->aDb[iDb].zDbSName;
112614      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
112615        goto begin_table_error;
112616      }
112617      if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
112618                                         zName, 0, zDb) ){
112619        goto begin_table_error;
112620      }
112621    }
112622  #endif
112623  
112624    /* Make sure the new table name does not collide with an existing
112625    ** index or table name in the same database.  Issue an error message if
112626    ** it does. The exception is if the statement being parsed was passed
112627    ** to an sqlite3_declare_vtab() call. In that case only the column names
112628    ** and types will be used, so there is no need to test for namespace
112629    ** collisions.
112630    */
112631    if( !IN_SPECIAL_PARSE ){
112632      char *zDb = db->aDb[iDb].zDbSName;
112633      if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
112634        goto begin_table_error;
112635      }
112636      pTable = sqlite3FindTable(db, zName, zDb);
112637      if( pTable ){
112638        if( !noErr ){
112639          sqlite3ErrorMsg(pParse, "table %T already exists", pName);
112640        }else{
112641          assert( !db->init.busy || CORRUPT_DB );
112642          sqlite3CodeVerifySchema(pParse, iDb);
112643        }
112644        goto begin_table_error;
112645      }
112646      if( sqlite3FindIndex(db, zName, zDb)!=0 ){
112647        sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
112648        goto begin_table_error;
112649      }
112650    }
112651  
112652    pTable = sqlite3DbMallocZero(db, sizeof(Table));
112653    if( pTable==0 ){
112654      assert( db->mallocFailed );
112655      pParse->rc = SQLITE_NOMEM_BKPT;
112656      pParse->nErr++;
112657      goto begin_table_error;
112658    }
112659    pTable->zName = zName;
112660    pTable->iPKey = -1;
112661    pTable->pSchema = db->aDb[iDb].pSchema;
112662    pTable->nTabRef = 1;
112663  #ifdef SQLITE_DEFAULT_ROWEST
112664    pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
112665  #else
112666    pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
112667  #endif
112668    assert( pParse->pNewTable==0 );
112669    pParse->pNewTable = pTable;
112670  
112671    /* If this is the magic sqlite_sequence table used by autoincrement,
112672    ** then record a pointer to this table in the main database structure
112673    ** so that INSERT can find the table easily.
112674    */
112675  #ifndef SQLITE_OMIT_AUTOINCREMENT
112676    if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
112677      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112678      pTable->pSchema->pSeqTab = pTable;
112679    }
112680  #endif
112681  
112682    /* Begin generating the code that will insert the table record into
112683    ** the SQLITE_MASTER table.  Note in particular that we must go ahead
112684    ** and allocate the record number for the table entry now.  Before any
112685    ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
112686    ** indices to be created and the table record must come before the 
112687    ** indices.  Hence, the record number for the table must be allocated
112688    ** now.
112689    */
112690    if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
112691      int addr1;
112692      int fileFormat;
112693      int reg1, reg2, reg3;
112694      /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
112695      static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
112696      sqlite3BeginWriteOperation(pParse, 1, iDb);
112697  
112698  #ifndef SQLITE_OMIT_VIRTUALTABLE
112699      if( isVirtual ){
112700        sqlite3VdbeAddOp0(v, OP_VBegin);
112701      }
112702  #endif
112703  
112704      /* If the file format and encoding in the database have not been set, 
112705      ** set them now.
112706      */
112707      reg1 = pParse->regRowid = ++pParse->nMem;
112708      reg2 = pParse->regRoot = ++pParse->nMem;
112709      reg3 = ++pParse->nMem;
112710      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
112711      sqlite3VdbeUsesBtree(v, iDb);
112712      addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
112713      fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
112714                    1 : SQLITE_MAX_FILE_FORMAT;
112715      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
112716      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
112717      sqlite3VdbeJumpHere(v, addr1);
112718  
112719      /* This just creates a place-holder record in the sqlite_master table.
112720      ** The record created does not contain anything yet.  It will be replaced
112721      ** by the real entry in code generated at sqlite3EndTable().
112722      **
112723      ** The rowid for the new entry is left in register pParse->regRowid.
112724      ** The root page number of the new table is left in reg pParse->regRoot.
112725      ** The rowid and root page number values are needed by the code that
112726      ** sqlite3EndTable will generate.
112727      */
112728  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
112729      if( isView || isVirtual ){
112730        sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
112731      }else
112732  #endif
112733      {
112734        pParse->addrCrTab =
112735           sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
112736      }
112737      sqlite3OpenMasterTable(pParse, iDb);
112738      sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
112739      sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
112740      sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
112741      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
112742      sqlite3VdbeAddOp0(v, OP_Close);
112743    }
112744  
112745    /* Normal (non-error) return. */
112746    return;
112747  
112748    /* If an error occurs, we jump here */
112749  begin_table_error:
112750    sqlite3DbFree(db, zName);
112751    return;
112752  }
112753  
112754  /* Set properties of a table column based on the (magical)
112755  ** name of the column.
112756  */
112757  #if SQLITE_ENABLE_HIDDEN_COLUMNS
112758  SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
112759    if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
112760      pCol->colFlags |= COLFLAG_HIDDEN;
112761    }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
112762      pTab->tabFlags |= TF_OOOHidden;
112763    }
112764  }
112765  #endif
112766  
112767  
112768  /*
112769  ** Add a new column to the table currently being constructed.
112770  **
112771  ** The parser calls this routine once for each column declaration
112772  ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
112773  ** first to get things going.  Then this routine is called for each
112774  ** column.
112775  */
112776  SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
112777    Table *p;
112778    int i;
112779    char *z;
112780    char *zType;
112781    Column *pCol;
112782    sqlite3 *db = pParse->db;
112783    if( (p = pParse->pNewTable)==0 ) return;
112784    if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
112785      sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
112786      return;
112787    }
112788    z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
112789    if( z==0 ) return;
112790    if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
112791    memcpy(z, pName->z, pName->n);
112792    z[pName->n] = 0;
112793    sqlite3Dequote(z);
112794    for(i=0; i<p->nCol; i++){
112795      if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
112796        sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
112797        sqlite3DbFree(db, z);
112798        return;
112799      }
112800    }
112801    if( (p->nCol & 0x7)==0 ){
112802      Column *aNew;
112803      aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
112804      if( aNew==0 ){
112805        sqlite3DbFree(db, z);
112806        return;
112807      }
112808      p->aCol = aNew;
112809    }
112810    pCol = &p->aCol[p->nCol];
112811    memset(pCol, 0, sizeof(p->aCol[0]));
112812    pCol->zName = z;
112813    sqlite3ColumnPropertiesFromName(p, pCol);
112814   
112815    if( pType->n==0 ){
112816      /* If there is no type specified, columns have the default affinity
112817      ** 'BLOB' with a default size of 4 bytes. */
112818      pCol->affinity = SQLITE_AFF_BLOB;
112819      pCol->szEst = 1;
112820  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
112821      if( 4>=sqlite3GlobalConfig.szSorterRef ){
112822        pCol->colFlags |= COLFLAG_SORTERREF;
112823      }
112824  #endif
112825    }else{
112826      zType = z + sqlite3Strlen30(z) + 1;
112827      memcpy(zType, pType->z, pType->n);
112828      zType[pType->n] = 0;
112829      sqlite3Dequote(zType);
112830      pCol->affinity = sqlite3AffinityType(zType, pCol);
112831      pCol->colFlags |= COLFLAG_HASTYPE;
112832    }
112833    p->nCol++;
112834    pParse->constraintName.n = 0;
112835  }
112836  
112837  /*
112838  ** This routine is called by the parser while in the middle of
112839  ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
112840  ** been seen on a column.  This routine sets the notNull flag on
112841  ** the column currently under construction.
112842  */
112843  SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
112844    Table *p;
112845    Column *pCol;
112846    p = pParse->pNewTable;
112847    if( p==0 || NEVER(p->nCol<1) ) return;
112848    pCol = &p->aCol[p->nCol-1];
112849    pCol->notNull = (u8)onError;
112850    p->tabFlags |= TF_HasNotNull;
112851  
112852    /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
112853    ** on this column.  */
112854    if( pCol->colFlags & COLFLAG_UNIQUE ){
112855      Index *pIdx;
112856      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
112857        assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
112858        if( pIdx->aiColumn[0]==p->nCol-1 ){
112859          pIdx->uniqNotNull = 1;
112860        }
112861      }
112862    }
112863  }
112864  
112865  /*
112866  ** Scan the column type name zType (length nType) and return the
112867  ** associated affinity type.
112868  **
112869  ** This routine does a case-independent search of zType for the 
112870  ** substrings in the following table. If one of the substrings is
112871  ** found, the corresponding affinity is returned. If zType contains
112872  ** more than one of the substrings, entries toward the top of 
112873  ** the table take priority. For example, if zType is 'BLOBINT', 
112874  ** SQLITE_AFF_INTEGER is returned.
112875  **
112876  ** Substring     | Affinity
112877  ** --------------------------------
112878  ** 'INT'         | SQLITE_AFF_INTEGER
112879  ** 'CHAR'        | SQLITE_AFF_TEXT
112880  ** 'CLOB'        | SQLITE_AFF_TEXT
112881  ** 'TEXT'        | SQLITE_AFF_TEXT
112882  ** 'BLOB'        | SQLITE_AFF_BLOB
112883  ** 'REAL'        | SQLITE_AFF_REAL
112884  ** 'FLOA'        | SQLITE_AFF_REAL
112885  ** 'DOUB'        | SQLITE_AFF_REAL
112886  **
112887  ** If none of the substrings in the above table are found,
112888  ** SQLITE_AFF_NUMERIC is returned.
112889  */
112890  SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
112891    u32 h = 0;
112892    char aff = SQLITE_AFF_NUMERIC;
112893    const char *zChar = 0;
112894  
112895    assert( zIn!=0 );
112896    while( zIn[0] ){
112897      h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
112898      zIn++;
112899      if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
112900        aff = SQLITE_AFF_TEXT;
112901        zChar = zIn;
112902      }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
112903        aff = SQLITE_AFF_TEXT;
112904      }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
112905        aff = SQLITE_AFF_TEXT;
112906      }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
112907          && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
112908        aff = SQLITE_AFF_BLOB;
112909        if( zIn[0]=='(' ) zChar = zIn;
112910  #ifndef SQLITE_OMIT_FLOATING_POINT
112911      }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
112912          && aff==SQLITE_AFF_NUMERIC ){
112913        aff = SQLITE_AFF_REAL;
112914      }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
112915          && aff==SQLITE_AFF_NUMERIC ){
112916        aff = SQLITE_AFF_REAL;
112917      }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
112918          && aff==SQLITE_AFF_NUMERIC ){
112919        aff = SQLITE_AFF_REAL;
112920  #endif
112921      }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
112922        aff = SQLITE_AFF_INTEGER;
112923        break;
112924      }
112925    }
112926  
112927    /* If pCol is not NULL, store an estimate of the field size.  The
112928    ** estimate is scaled so that the size of an integer is 1.  */
112929    if( pCol ){
112930      int v = 0;   /* default size is approx 4 bytes */
112931      if( aff<SQLITE_AFF_NUMERIC ){
112932        if( zChar ){
112933          while( zChar[0] ){
112934            if( sqlite3Isdigit(zChar[0]) ){
112935              /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
112936              sqlite3GetInt32(zChar, &v);
112937              break;
112938            }
112939            zChar++;
112940          }
112941        }else{
112942          v = 16;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
112943        }
112944      }
112945  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
112946      if( v>=sqlite3GlobalConfig.szSorterRef ){
112947        pCol->colFlags |= COLFLAG_SORTERREF;
112948      }
112949  #endif
112950      v = v/4 + 1;
112951      if( v>255 ) v = 255;
112952      pCol->szEst = v;
112953    }
112954    return aff;
112955  }
112956  
112957  /*
112958  ** The expression is the default value for the most recently added column
112959  ** of the table currently under construction.
112960  **
112961  ** Default value expressions must be constant.  Raise an exception if this
112962  ** is not the case.
112963  **
112964  ** This routine is called by the parser while in the middle of
112965  ** parsing a CREATE TABLE statement.
112966  */
112967  SQLITE_PRIVATE void sqlite3AddDefaultValue(
112968    Parse *pParse,           /* Parsing context */
112969    Expr *pExpr,             /* The parsed expression of the default value */
112970    const char *zStart,      /* Start of the default value text */
112971    const char *zEnd         /* First character past end of defaut value text */
112972  ){
112973    Table *p;
112974    Column *pCol;
112975    sqlite3 *db = pParse->db;
112976    p = pParse->pNewTable;
112977    if( p!=0 ){
112978      pCol = &(p->aCol[p->nCol-1]);
112979      if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
112980        sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
112981            pCol->zName);
112982      }else{
112983        /* A copy of pExpr is used instead of the original, as pExpr contains
112984        ** tokens that point to volatile memory.
112985        */
112986        Expr x;
112987        sqlite3ExprDelete(db, pCol->pDflt);
112988        memset(&x, 0, sizeof(x));
112989        x.op = TK_SPAN;
112990        x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
112991        x.pLeft = pExpr;
112992        x.flags = EP_Skip;
112993        pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
112994        sqlite3DbFree(db, x.u.zToken);
112995      }
112996    }
112997    if( IN_RENAME_OBJECT ){
112998      sqlite3RenameExprUnmap(pParse, pExpr);
112999    }
113000    sqlite3ExprDelete(db, pExpr);
113001  }
113002  
113003  /*
113004  ** Backwards Compatibility Hack:
113005  ** 
113006  ** Historical versions of SQLite accepted strings as column names in
113007  ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
113008  **
113009  **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
113010  **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
113011  **
113012  ** This is goofy.  But to preserve backwards compatibility we continue to
113013  ** accept it.  This routine does the necessary conversion.  It converts
113014  ** the expression given in its argument from a TK_STRING into a TK_ID
113015  ** if the expression is just a TK_STRING with an optional COLLATE clause.
113016  ** If the epxression is anything other than TK_STRING, the expression is
113017  ** unchanged.
113018  */
113019  static void sqlite3StringToId(Expr *p){
113020    if( p->op==TK_STRING ){
113021      p->op = TK_ID;
113022    }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
113023      p->pLeft->op = TK_ID;
113024    }
113025  }
113026  
113027  /*
113028  ** Designate the PRIMARY KEY for the table.  pList is a list of names 
113029  ** of columns that form the primary key.  If pList is NULL, then the
113030  ** most recently added column of the table is the primary key.
113031  **
113032  ** A table can have at most one primary key.  If the table already has
113033  ** a primary key (and this is the second primary key) then create an
113034  ** error.
113035  **
113036  ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
113037  ** then we will try to use that column as the rowid.  Set the Table.iPKey
113038  ** field of the table under construction to be the index of the
113039  ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
113040  ** no INTEGER PRIMARY KEY.
113041  **
113042  ** If the key is not an INTEGER PRIMARY KEY, then create a unique
113043  ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
113044  */
113045  SQLITE_PRIVATE void sqlite3AddPrimaryKey(
113046    Parse *pParse,    /* Parsing context */
113047    ExprList *pList,  /* List of field names to be indexed */
113048    int onError,      /* What to do with a uniqueness conflict */
113049    int autoInc,      /* True if the AUTOINCREMENT keyword is present */
113050    int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
113051  ){
113052    Table *pTab = pParse->pNewTable;
113053    Column *pCol = 0;
113054    int iCol = -1, i;
113055    int nTerm;
113056    if( pTab==0 ) goto primary_key_exit;
113057    if( pTab->tabFlags & TF_HasPrimaryKey ){
113058      sqlite3ErrorMsg(pParse, 
113059        "table \"%s\" has more than one primary key", pTab->zName);
113060      goto primary_key_exit;
113061    }
113062    pTab->tabFlags |= TF_HasPrimaryKey;
113063    if( pList==0 ){
113064      iCol = pTab->nCol - 1;
113065      pCol = &pTab->aCol[iCol];
113066      pCol->colFlags |= COLFLAG_PRIMKEY;
113067      nTerm = 1;
113068    }else{
113069      nTerm = pList->nExpr;
113070      for(i=0; i<nTerm; i++){
113071        Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
113072        assert( pCExpr!=0 );
113073        sqlite3StringToId(pCExpr);
113074        if( pCExpr->op==TK_ID ){
113075          const char *zCName = pCExpr->u.zToken;
113076          for(iCol=0; iCol<pTab->nCol; iCol++){
113077            if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
113078              pCol = &pTab->aCol[iCol];
113079              pCol->colFlags |= COLFLAG_PRIMKEY;
113080              break;
113081            }
113082          }
113083        }
113084      }
113085    }
113086    if( nTerm==1
113087     && pCol
113088     && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
113089     && sortOrder!=SQLITE_SO_DESC
113090    ){
113091      if( IN_RENAME_OBJECT && pList ){
113092        sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pList->a[0].pExpr);
113093      }
113094      pTab->iPKey = iCol;
113095      pTab->keyConf = (u8)onError;
113096      assert( autoInc==0 || autoInc==1 );
113097      pTab->tabFlags |= autoInc*TF_Autoincrement;
113098      if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
113099    }else if( autoInc ){
113100  #ifndef SQLITE_OMIT_AUTOINCREMENT
113101      sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
113102         "INTEGER PRIMARY KEY");
113103  #endif
113104    }else{
113105      sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
113106                             0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
113107      pList = 0;
113108    }
113109  
113110  primary_key_exit:
113111    sqlite3ExprListDelete(pParse->db, pList);
113112    return;
113113  }
113114  
113115  /*
113116  ** Add a new CHECK constraint to the table currently under construction.
113117  */
113118  SQLITE_PRIVATE void sqlite3AddCheckConstraint(
113119    Parse *pParse,    /* Parsing context */
113120    Expr *pCheckExpr  /* The check expression */
113121  ){
113122  #ifndef SQLITE_OMIT_CHECK
113123    Table *pTab = pParse->pNewTable;
113124    sqlite3 *db = pParse->db;
113125    if( pTab && !IN_DECLARE_VTAB
113126     && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
113127    ){
113128      pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
113129      if( pParse->constraintName.n ){
113130        sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
113131      }
113132    }else
113133  #endif
113134    {
113135      sqlite3ExprDelete(pParse->db, pCheckExpr);
113136    }
113137  }
113138  
113139  /*
113140  ** Set the collation function of the most recently parsed table column
113141  ** to the CollSeq given.
113142  */
113143  SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
113144    Table *p;
113145    int i;
113146    char *zColl;              /* Dequoted name of collation sequence */
113147    sqlite3 *db;
113148  
113149    if( (p = pParse->pNewTable)==0 ) return;
113150    i = p->nCol-1;
113151    db = pParse->db;
113152    zColl = sqlite3NameFromToken(db, pToken);
113153    if( !zColl ) return;
113154  
113155    if( sqlite3LocateCollSeq(pParse, zColl) ){
113156      Index *pIdx;
113157      sqlite3DbFree(db, p->aCol[i].zColl);
113158      p->aCol[i].zColl = zColl;
113159    
113160      /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
113161      ** then an index may have been created on this column before the
113162      ** collation type was added. Correct this if it is the case.
113163      */
113164      for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
113165        assert( pIdx->nKeyCol==1 );
113166        if( pIdx->aiColumn[0]==i ){
113167          pIdx->azColl[0] = p->aCol[i].zColl;
113168        }
113169      }
113170    }else{
113171      sqlite3DbFree(db, zColl);
113172    }
113173  }
113174  
113175  /*
113176  ** This function returns the collation sequence for database native text
113177  ** encoding identified by the string zName, length nName.
113178  **
113179  ** If the requested collation sequence is not available, or not available
113180  ** in the database native encoding, the collation factory is invoked to
113181  ** request it. If the collation factory does not supply such a sequence,
113182  ** and the sequence is available in another text encoding, then that is
113183  ** returned instead.
113184  **
113185  ** If no versions of the requested collations sequence are available, or
113186  ** another error occurs, NULL is returned and an error message written into
113187  ** pParse.
113188  **
113189  ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
113190  ** invokes the collation factory if the named collation cannot be found
113191  ** and generates an error message.
113192  **
113193  ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
113194  */
113195  SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
113196    sqlite3 *db = pParse->db;
113197    u8 enc = ENC(db);
113198    u8 initbusy = db->init.busy;
113199    CollSeq *pColl;
113200  
113201    pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
113202    if( !initbusy && (!pColl || !pColl->xCmp) ){
113203      pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
113204    }
113205  
113206    return pColl;
113207  }
113208  
113209  
113210  /*
113211  ** Generate code that will increment the schema cookie.
113212  **
113213  ** The schema cookie is used to determine when the schema for the
113214  ** database changes.  After each schema change, the cookie value
113215  ** changes.  When a process first reads the schema it records the
113216  ** cookie.  Thereafter, whenever it goes to access the database,
113217  ** it checks the cookie to make sure the schema has not changed
113218  ** since it was last read.
113219  **
113220  ** This plan is not completely bullet-proof.  It is possible for
113221  ** the schema to change multiple times and for the cookie to be
113222  ** set back to prior value.  But schema changes are infrequent
113223  ** and the probability of hitting the same cookie value is only
113224  ** 1 chance in 2^32.  So we're safe enough.
113225  **
113226  ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
113227  ** the schema-version whenever the schema changes.
113228  */
113229  SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
113230    sqlite3 *db = pParse->db;
113231    Vdbe *v = pParse->pVdbe;
113232    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113233    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 
113234                     (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
113235  }
113236  
113237  /*
113238  ** Measure the number of characters needed to output the given
113239  ** identifier.  The number returned includes any quotes used
113240  ** but does not include the null terminator.
113241  **
113242  ** The estimate is conservative.  It might be larger that what is
113243  ** really needed.
113244  */
113245  static int identLength(const char *z){
113246    int n;
113247    for(n=0; *z; n++, z++){
113248      if( *z=='"' ){ n++; }
113249    }
113250    return n + 2;
113251  }
113252  
113253  /*
113254  ** The first parameter is a pointer to an output buffer. The second 
113255  ** parameter is a pointer to an integer that contains the offset at
113256  ** which to write into the output buffer. This function copies the
113257  ** nul-terminated string pointed to by the third parameter, zSignedIdent,
113258  ** to the specified offset in the buffer and updates *pIdx to refer
113259  ** to the first byte after the last byte written before returning.
113260  ** 
113261  ** If the string zSignedIdent consists entirely of alpha-numeric
113262  ** characters, does not begin with a digit and is not an SQL keyword,
113263  ** then it is copied to the output buffer exactly as it is. Otherwise,
113264  ** it is quoted using double-quotes.
113265  */
113266  static void identPut(char *z, int *pIdx, char *zSignedIdent){
113267    unsigned char *zIdent = (unsigned char*)zSignedIdent;
113268    int i, j, needQuote;
113269    i = *pIdx;
113270  
113271    for(j=0; zIdent[j]; j++){
113272      if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
113273    }
113274    needQuote = sqlite3Isdigit(zIdent[0])
113275              || sqlite3KeywordCode(zIdent, j)!=TK_ID
113276              || zIdent[j]!=0
113277              || j==0;
113278  
113279    if( needQuote ) z[i++] = '"';
113280    for(j=0; zIdent[j]; j++){
113281      z[i++] = zIdent[j];
113282      if( zIdent[j]=='"' ) z[i++] = '"';
113283    }
113284    if( needQuote ) z[i++] = '"';
113285    z[i] = 0;
113286    *pIdx = i;
113287  }
113288  
113289  /*
113290  ** Generate a CREATE TABLE statement appropriate for the given
113291  ** table.  Memory to hold the text of the statement is obtained
113292  ** from sqliteMalloc() and must be freed by the calling function.
113293  */
113294  static char *createTableStmt(sqlite3 *db, Table *p){
113295    int i, k, n;
113296    char *zStmt;
113297    char *zSep, *zSep2, *zEnd;
113298    Column *pCol;
113299    n = 0;
113300    for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
113301      n += identLength(pCol->zName) + 5;
113302    }
113303    n += identLength(p->zName);
113304    if( n<50 ){ 
113305      zSep = "";
113306      zSep2 = ",";
113307      zEnd = ")";
113308    }else{
113309      zSep = "\n  ";
113310      zSep2 = ",\n  ";
113311      zEnd = "\n)";
113312    }
113313    n += 35 + 6*p->nCol;
113314    zStmt = sqlite3DbMallocRaw(0, n);
113315    if( zStmt==0 ){
113316      sqlite3OomFault(db);
113317      return 0;
113318    }
113319    sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
113320    k = sqlite3Strlen30(zStmt);
113321    identPut(zStmt, &k, p->zName);
113322    zStmt[k++] = '(';
113323    for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
113324      static const char * const azType[] = {
113325          /* SQLITE_AFF_BLOB    */ "",
113326          /* SQLITE_AFF_TEXT    */ " TEXT",
113327          /* SQLITE_AFF_NUMERIC */ " NUM",
113328          /* SQLITE_AFF_INTEGER */ " INT",
113329          /* SQLITE_AFF_REAL    */ " REAL"
113330      };
113331      int len;
113332      const char *zType;
113333  
113334      sqlite3_snprintf(n-k, &zStmt[k], zSep);
113335      k += sqlite3Strlen30(&zStmt[k]);
113336      zSep = zSep2;
113337      identPut(zStmt, &k, pCol->zName);
113338      assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
113339      assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
113340      testcase( pCol->affinity==SQLITE_AFF_BLOB );
113341      testcase( pCol->affinity==SQLITE_AFF_TEXT );
113342      testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
113343      testcase( pCol->affinity==SQLITE_AFF_INTEGER );
113344      testcase( pCol->affinity==SQLITE_AFF_REAL );
113345      
113346      zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
113347      len = sqlite3Strlen30(zType);
113348      assert( pCol->affinity==SQLITE_AFF_BLOB 
113349              || pCol->affinity==sqlite3AffinityType(zType, 0) );
113350      memcpy(&zStmt[k], zType, len);
113351      k += len;
113352      assert( k<=n );
113353    }
113354    sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
113355    return zStmt;
113356  }
113357  
113358  /*
113359  ** Resize an Index object to hold N columns total.  Return SQLITE_OK
113360  ** on success and SQLITE_NOMEM on an OOM error.
113361  */
113362  static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
113363    char *zExtra;
113364    int nByte;
113365    if( pIdx->nColumn>=N ) return SQLITE_OK;
113366    assert( pIdx->isResized==0 );
113367    nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
113368    zExtra = sqlite3DbMallocZero(db, nByte);
113369    if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
113370    memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
113371    pIdx->azColl = (const char**)zExtra;
113372    zExtra += sizeof(char*)*N;
113373    memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
113374    pIdx->aiColumn = (i16*)zExtra;
113375    zExtra += sizeof(i16)*N;
113376    memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
113377    pIdx->aSortOrder = (u8*)zExtra;
113378    pIdx->nColumn = N;
113379    pIdx->isResized = 1;
113380    return SQLITE_OK;
113381  }
113382  
113383  /*
113384  ** Estimate the total row width for a table.
113385  */
113386  static void estimateTableWidth(Table *pTab){
113387    unsigned wTable = 0;
113388    const Column *pTabCol;
113389    int i;
113390    for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
113391      wTable += pTabCol->szEst;
113392    }
113393    if( pTab->iPKey<0 ) wTable++;
113394    pTab->szTabRow = sqlite3LogEst(wTable*4);
113395  }
113396  
113397  /*
113398  ** Estimate the average size of a row for an index.
113399  */
113400  static void estimateIndexWidth(Index *pIdx){
113401    unsigned wIndex = 0;
113402    int i;
113403    const Column *aCol = pIdx->pTable->aCol;
113404    for(i=0; i<pIdx->nColumn; i++){
113405      i16 x = pIdx->aiColumn[i];
113406      assert( x<pIdx->pTable->nCol );
113407      wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
113408    }
113409    pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
113410  }
113411  
113412  /* Return true if value x is found any of the first nCol entries of aiCol[]
113413  */
113414  static int hasColumn(const i16 *aiCol, int nCol, int x){
113415    while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
113416    return 0;
113417  }
113418  
113419  /* Recompute the colNotIdxed field of the Index.
113420  **
113421  ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
113422  ** columns that are within the first 63 columns of the table.  The
113423  ** high-order bit of colNotIdxed is always 1.  All unindexed columns
113424  ** of the table have a 1.
113425  **
113426  ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
113427  ** to determine if the index is covering index.
113428  */
113429  static void recomputeColumnsNotIndexed(Index *pIdx){
113430    Bitmask m = 0;
113431    int j;
113432    for(j=pIdx->nColumn-1; j>=0; j--){
113433      int x = pIdx->aiColumn[j];
113434      if( x>=0 ){
113435        testcase( x==BMS-1 );
113436        testcase( x==BMS-2 );
113437        if( x<BMS-1 ) m |= MASKBIT(x);
113438      }
113439    }
113440    pIdx->colNotIdxed = ~m;
113441    assert( (pIdx->colNotIdxed>>63)==1 );
113442  }
113443  
113444  /*
113445  ** This routine runs at the end of parsing a CREATE TABLE statement that
113446  ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
113447  ** internal schema data structures and the generated VDBE code so that they
113448  ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
113449  ** Changes include:
113450  **
113451  **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
113452  **     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 
113453  **          into BTREE_BLOBKEY.
113454  **     (3)  Bypass the creation of the sqlite_master table entry
113455  **          for the PRIMARY KEY as the primary key index is now
113456  **          identified by the sqlite_master table entry of the table itself.
113457  **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
113458  **          schema to the rootpage from the main table.
113459  **     (5)  Add all table columns to the PRIMARY KEY Index object
113460  **          so that the PRIMARY KEY is a covering index.  The surplus
113461  **          columns are part of KeyInfo.nAllField and are not used for
113462  **          sorting or lookup or uniqueness checks.
113463  **     (6)  Replace the rowid tail on all automatically generated UNIQUE
113464  **          indices with the PRIMARY KEY columns.
113465  **
113466  ** For virtual tables, only (1) is performed.
113467  */
113468  static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
113469    Index *pIdx;
113470    Index *pPk;
113471    int nPk;
113472    int i, j;
113473    sqlite3 *db = pParse->db;
113474    Vdbe *v = pParse->pVdbe;
113475  
113476    /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
113477    */
113478    if( !db->init.imposterTable ){
113479      for(i=0; i<pTab->nCol; i++){
113480        if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
113481          pTab->aCol[i].notNull = OE_Abort;
113482        }
113483      }
113484    }
113485  
113486    /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
113487    ** into BTREE_BLOBKEY.
113488    */
113489    if( pParse->addrCrTab ){
113490      assert( v );
113491      sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
113492    }
113493  
113494    /* Locate the PRIMARY KEY index.  Or, if this table was originally
113495    ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
113496    */
113497    if( pTab->iPKey>=0 ){
113498      ExprList *pList;
113499      Token ipkToken;
113500      sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
113501      pList = sqlite3ExprListAppend(pParse, 0, 
113502                    sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
113503      if( pList==0 ) return;
113504      pList->a[0].sortOrder = pParse->iPkSortOrder;
113505      assert( pParse->pNewTable==pTab );
113506      sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
113507                         SQLITE_IDXTYPE_PRIMARYKEY);
113508      if( db->mallocFailed || pParse->nErr ) return;
113509      pPk = sqlite3PrimaryKeyIndex(pTab);
113510      pTab->iPKey = -1;
113511    }else{
113512      pPk = sqlite3PrimaryKeyIndex(pTab);
113513  
113514      /*
113515      ** Remove all redundant columns from the PRIMARY KEY.  For example, change
113516      ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
113517      ** code assumes the PRIMARY KEY contains no repeated columns.
113518      */
113519      for(i=j=1; i<pPk->nKeyCol; i++){
113520        if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
113521          pPk->nColumn--;
113522        }else{
113523          pPk->aiColumn[j++] = pPk->aiColumn[i];
113524        }
113525      }
113526      pPk->nKeyCol = j;
113527    }
113528    assert( pPk!=0 );
113529    pPk->isCovering = 1;
113530    if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
113531    nPk = pPk->nKeyCol;
113532  
113533    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
113534    ** table entry. This is only required if currently generating VDBE
113535    ** code for a CREATE TABLE (not when parsing one as part of reading
113536    ** a database schema).  */
113537    if( v && pPk->tnum>0 ){
113538      assert( db->init.busy==0 );
113539      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
113540    }
113541  
113542    /* The root page of the PRIMARY KEY is the table root page */
113543    pPk->tnum = pTab->tnum;
113544  
113545    /* Update the in-memory representation of all UNIQUE indices by converting
113546    ** the final rowid column into one or more columns of the PRIMARY KEY.
113547    */
113548    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
113549      int n;
113550      if( IsPrimaryKeyIndex(pIdx) ) continue;
113551      for(i=n=0; i<nPk; i++){
113552        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
113553      }
113554      if( n==0 ){
113555        /* This index is a superset of the primary key */
113556        pIdx->nColumn = pIdx->nKeyCol;
113557        continue;
113558      }
113559      if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
113560      for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
113561        if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
113562          pIdx->aiColumn[j] = pPk->aiColumn[i];
113563          pIdx->azColl[j] = pPk->azColl[i];
113564          j++;
113565        }
113566      }
113567      assert( pIdx->nColumn>=pIdx->nKeyCol+n );
113568      assert( pIdx->nColumn>=j );
113569    }
113570  
113571    /* Add all table columns to the PRIMARY KEY index
113572    */
113573    if( nPk<pTab->nCol ){
113574      if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
113575      for(i=0, j=nPk; i<pTab->nCol; i++){
113576        if( !hasColumn(pPk->aiColumn, j, i) ){
113577          assert( j<pPk->nColumn );
113578          pPk->aiColumn[j] = i;
113579          pPk->azColl[j] = sqlite3StrBINARY;
113580          j++;
113581        }
113582      }
113583      assert( pPk->nColumn==j );
113584      assert( pTab->nCol==j );
113585    }else{
113586      pPk->nColumn = pTab->nCol;
113587    }
113588    recomputeColumnsNotIndexed(pPk);
113589  }
113590  
113591  #ifndef SQLITE_OMIT_VIRTUALTABLE
113592  /*
113593  ** Return true if zName is a shadow table name in the current database
113594  ** connection.
113595  **
113596  ** zName is temporarily modified while this routine is running, but is
113597  ** restored to its original value prior to this routine returning.
113598  */
113599  static int isShadowTableName(sqlite3 *db, char *zName){
113600    char *zTail;                  /* Pointer to the last "_" in zName */
113601    Table *pTab;                  /* Table that zName is a shadow of */
113602    Module *pMod;                 /* Module for the virtual table */
113603  
113604    zTail = strrchr(zName, '_');
113605    if( zTail==0 ) return 0;
113606    *zTail = 0;
113607    pTab = sqlite3FindTable(db, zName, 0);
113608    *zTail = '_';
113609    if( pTab==0 ) return 0;
113610    if( !IsVirtual(pTab) ) return 0;
113611    pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
113612    if( pMod==0 ) return 0;
113613    if( pMod->pModule->iVersion<3 ) return 0;
113614    if( pMod->pModule->xShadowName==0 ) return 0;
113615    return pMod->pModule->xShadowName(zTail+1);
113616  }
113617  #else
113618  # define isShadowTableName(x,y) 0
113619  #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
113620  
113621  /*
113622  ** This routine is called to report the final ")" that terminates
113623  ** a CREATE TABLE statement.
113624  **
113625  ** The table structure that other action routines have been building
113626  ** is added to the internal hash tables, assuming no errors have
113627  ** occurred.
113628  **
113629  ** An entry for the table is made in the master table on disk, unless
113630  ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
113631  ** it means we are reading the sqlite_master table because we just
113632  ** connected to the database or because the sqlite_master table has
113633  ** recently changed, so the entry for this table already exists in
113634  ** the sqlite_master table.  We do not want to create it again.
113635  **
113636  ** If the pSelect argument is not NULL, it means that this routine
113637  ** was called to create a table generated from a 
113638  ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
113639  ** the new table will match the result set of the SELECT.
113640  */
113641  SQLITE_PRIVATE void sqlite3EndTable(
113642    Parse *pParse,          /* Parse context */
113643    Token *pCons,           /* The ',' token after the last column defn. */
113644    Token *pEnd,            /* The ')' before options in the CREATE TABLE */
113645    u8 tabOpts,             /* Extra table options. Usually 0. */
113646    Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
113647  ){
113648    Table *p;                 /* The new table */
113649    sqlite3 *db = pParse->db; /* The database connection */
113650    int iDb;                  /* Database in which the table lives */
113651    Index *pIdx;              /* An implied index of the table */
113652  
113653    if( pEnd==0 && pSelect==0 ){
113654      return;
113655    }
113656    assert( !db->mallocFailed );
113657    p = pParse->pNewTable;
113658    if( p==0 ) return;
113659  
113660    if( pSelect==0 && isShadowTableName(db, p->zName) ){
113661      p->tabFlags |= TF_Shadow;
113662    }
113663  
113664    /* If the db->init.busy is 1 it means we are reading the SQL off the
113665    ** "sqlite_master" or "sqlite_temp_master" table on the disk.
113666    ** So do not write to the disk again.  Extract the root page number
113667    ** for the table from the db->init.newTnum field.  (The page number
113668    ** should have been put there by the sqliteOpenCb routine.)
113669    **
113670    ** If the root page number is 1, that means this is the sqlite_master
113671    ** table itself.  So mark it read-only.
113672    */
113673    if( db->init.busy ){
113674      if( pSelect ){
113675        sqlite3ErrorMsg(pParse, "");
113676        return;
113677      }
113678      p->tnum = db->init.newTnum;
113679      if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
113680    }
113681  
113682    /* Special processing for WITHOUT ROWID Tables */
113683    if( tabOpts & TF_WithoutRowid ){
113684      if( (p->tabFlags & TF_Autoincrement) ){
113685        sqlite3ErrorMsg(pParse,
113686            "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
113687        return;
113688      }
113689      if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
113690        sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
113691      }else{
113692        p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
113693        convertToWithoutRowidTable(pParse, p);
113694      }
113695    }
113696  
113697    iDb = sqlite3SchemaToIndex(db, p->pSchema);
113698  
113699  #ifndef SQLITE_OMIT_CHECK
113700    /* Resolve names in all CHECK constraint expressions.
113701    */
113702    if( p->pCheck ){
113703      sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
113704    }
113705  #endif /* !defined(SQLITE_OMIT_CHECK) */
113706  
113707    /* Estimate the average row size for the table and for all implied indices */
113708    estimateTableWidth(p);
113709    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
113710      estimateIndexWidth(pIdx);
113711    }
113712  
113713    /* If not initializing, then create a record for the new table
113714    ** in the SQLITE_MASTER table of the database.
113715    **
113716    ** If this is a TEMPORARY table, write the entry into the auxiliary
113717    ** file instead of into the main database file.
113718    */
113719    if( !db->init.busy ){
113720      int n;
113721      Vdbe *v;
113722      char *zType;    /* "view" or "table" */
113723      char *zType2;   /* "VIEW" or "TABLE" */
113724      char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
113725  
113726      v = sqlite3GetVdbe(pParse);
113727      if( NEVER(v==0) ) return;
113728  
113729      sqlite3VdbeAddOp1(v, OP_Close, 0);
113730  
113731      /* 
113732      ** Initialize zType for the new view or table.
113733      */
113734      if( p->pSelect==0 ){
113735        /* A regular table */
113736        zType = "table";
113737        zType2 = "TABLE";
113738  #ifndef SQLITE_OMIT_VIEW
113739      }else{
113740        /* A view */
113741        zType = "view";
113742        zType2 = "VIEW";
113743  #endif
113744      }
113745  
113746      /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
113747      ** statement to populate the new table. The root-page number for the
113748      ** new table is in register pParse->regRoot.
113749      **
113750      ** Once the SELECT has been coded by sqlite3Select(), it is in a
113751      ** suitable state to query for the column names and types to be used
113752      ** by the new table.
113753      **
113754      ** A shared-cache write-lock is not required to write to the new table,
113755      ** as a schema-lock must have already been obtained to create it. Since
113756      ** a schema-lock excludes all other database users, the write-lock would
113757      ** be redundant.
113758      */
113759      if( pSelect ){
113760        SelectDest dest;    /* Where the SELECT should store results */
113761        int regYield;       /* Register holding co-routine entry-point */
113762        int addrTop;        /* Top of the co-routine */
113763        int regRec;         /* A record to be insert into the new table */
113764        int regRowid;       /* Rowid of the next row to insert */
113765        int addrInsLoop;    /* Top of the loop for inserting rows */
113766        Table *pSelTab;     /* A table that describes the SELECT results */
113767  
113768        regYield = ++pParse->nMem;
113769        regRec = ++pParse->nMem;
113770        regRowid = ++pParse->nMem;
113771        assert(pParse->nTab==1);
113772        sqlite3MayAbort(pParse);
113773        sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
113774        sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
113775        pParse->nTab = 2;
113776        addrTop = sqlite3VdbeCurrentAddr(v) + 1;
113777        sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
113778        if( pParse->nErr ) return;
113779        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
113780        if( pSelTab==0 ) return;
113781        assert( p->aCol==0 );
113782        p->nCol = pSelTab->nCol;
113783        p->aCol = pSelTab->aCol;
113784        pSelTab->nCol = 0;
113785        pSelTab->aCol = 0;
113786        sqlite3DeleteTable(db, pSelTab);
113787        sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
113788        sqlite3Select(pParse, pSelect, &dest);
113789        if( pParse->nErr ) return;
113790        sqlite3VdbeEndCoroutine(v, regYield);
113791        sqlite3VdbeJumpHere(v, addrTop - 1);
113792        addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
113793        VdbeCoverage(v);
113794        sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
113795        sqlite3TableAffinity(v, p, 0);
113796        sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
113797        sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
113798        sqlite3VdbeGoto(v, addrInsLoop);
113799        sqlite3VdbeJumpHere(v, addrInsLoop);
113800        sqlite3VdbeAddOp1(v, OP_Close, 1);
113801      }
113802  
113803      /* Compute the complete text of the CREATE statement */
113804      if( pSelect ){
113805        zStmt = createTableStmt(db, p);
113806      }else{
113807        Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
113808        n = (int)(pEnd2->z - pParse->sNameToken.z);
113809        if( pEnd2->z[0]!=';' ) n += pEnd2->n;
113810        zStmt = sqlite3MPrintf(db, 
113811            "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
113812        );
113813      }
113814  
113815      /* A slot for the record has already been allocated in the 
113816      ** SQLITE_MASTER table.  We just need to update that slot with all
113817      ** the information we've collected.
113818      */
113819      sqlite3NestedParse(pParse,
113820        "UPDATE %Q.%s "
113821           "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
113822         "WHERE rowid=#%d",
113823        db->aDb[iDb].zDbSName, MASTER_NAME,
113824        zType,
113825        p->zName,
113826        p->zName,
113827        pParse->regRoot,
113828        zStmt,
113829        pParse->regRowid
113830      );
113831      sqlite3DbFree(db, zStmt);
113832      sqlite3ChangeCookie(pParse, iDb);
113833  
113834  #ifndef SQLITE_OMIT_AUTOINCREMENT
113835      /* Check to see if we need to create an sqlite_sequence table for
113836      ** keeping track of autoincrement keys.
113837      */
113838      if( (p->tabFlags & TF_Autoincrement)!=0 ){
113839        Db *pDb = &db->aDb[iDb];
113840        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113841        if( pDb->pSchema->pSeqTab==0 ){
113842          sqlite3NestedParse(pParse,
113843            "CREATE TABLE %Q.sqlite_sequence(name,seq)",
113844            pDb->zDbSName
113845          );
113846        }
113847      }
113848  #endif
113849  
113850      /* Reparse everything to update our internal data structures */
113851      sqlite3VdbeAddParseSchemaOp(v, iDb,
113852             sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
113853    }
113854  
113855  
113856    /* Add the table to the in-memory representation of the database.
113857    */
113858    if( db->init.busy ){
113859      Table *pOld;
113860      Schema *pSchema = p->pSchema;
113861      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113862      pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
113863      if( pOld ){
113864        assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
113865        sqlite3OomFault(db);
113866        return;
113867      }
113868      pParse->pNewTable = 0;
113869      db->mDbFlags |= DBFLAG_SchemaChange;
113870  
113871  #ifndef SQLITE_OMIT_ALTERTABLE
113872      if( !p->pSelect ){
113873        const char *zName = (const char *)pParse->sNameToken.z;
113874        int nName;
113875        assert( !pSelect && pCons && pEnd );
113876        if( pCons->z==0 ){
113877          pCons = pEnd;
113878        }
113879        nName = (int)((const char *)pCons->z - zName);
113880        p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
113881      }
113882  #endif
113883    }
113884  }
113885  
113886  #ifndef SQLITE_OMIT_VIEW
113887  /*
113888  ** The parser calls this routine in order to create a new VIEW
113889  */
113890  SQLITE_PRIVATE void sqlite3CreateView(
113891    Parse *pParse,     /* The parsing context */
113892    Token *pBegin,     /* The CREATE token that begins the statement */
113893    Token *pName1,     /* The token that holds the name of the view */
113894    Token *pName2,     /* The token that holds the name of the view */
113895    ExprList *pCNames, /* Optional list of view column names */
113896    Select *pSelect,   /* A SELECT statement that will become the new view */
113897    int isTemp,        /* TRUE for a TEMPORARY view */
113898    int noErr          /* Suppress error messages if VIEW already exists */
113899  ){
113900    Table *p;
113901    int n;
113902    const char *z;
113903    Token sEnd;
113904    DbFixer sFix;
113905    Token *pName = 0;
113906    int iDb;
113907    sqlite3 *db = pParse->db;
113908  
113909    if( pParse->nVar>0 ){
113910      sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
113911      goto create_view_fail;
113912    }
113913    sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
113914    p = pParse->pNewTable;
113915    if( p==0 || pParse->nErr ) goto create_view_fail;
113916    sqlite3TwoPartName(pParse, pName1, pName2, &pName);
113917    iDb = sqlite3SchemaToIndex(db, p->pSchema);
113918    sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
113919    if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
113920  
113921    /* Make a copy of the entire SELECT statement that defines the view.
113922    ** This will force all the Expr.token.z values to be dynamically
113923    ** allocated rather than point to the input string - which means that
113924    ** they will persist after the current sqlite3_exec() call returns.
113925    */
113926    if( IN_RENAME_OBJECT ){
113927      p->pSelect = pSelect;
113928      pSelect = 0;
113929    }else{
113930      p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
113931    }
113932    p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
113933    if( db->mallocFailed ) goto create_view_fail;
113934  
113935    /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
113936    ** the end.
113937    */
113938    sEnd = pParse->sLastToken;
113939    assert( sEnd.z[0]!=0 || sEnd.n==0 );
113940    if( sEnd.z[0]!=';' ){
113941      sEnd.z += sEnd.n;
113942    }
113943    sEnd.n = 0;
113944    n = (int)(sEnd.z - pBegin->z);
113945    assert( n>0 );
113946    z = pBegin->z;
113947    while( sqlite3Isspace(z[n-1]) ){ n--; }
113948    sEnd.z = &z[n-1];
113949    sEnd.n = 1;
113950  
113951    /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
113952    sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
113953  
113954  create_view_fail:
113955    sqlite3SelectDelete(db, pSelect);
113956    if( IN_RENAME_OBJECT ){
113957      sqlite3RenameExprlistUnmap(pParse, pCNames);
113958    }
113959    sqlite3ExprListDelete(db, pCNames);
113960    return;
113961  }
113962  #endif /* SQLITE_OMIT_VIEW */
113963  
113964  #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
113965  /*
113966  ** The Table structure pTable is really a VIEW.  Fill in the names of
113967  ** the columns of the view in the pTable structure.  Return the number
113968  ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
113969  */
113970  SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
113971    Table *pSelTab;   /* A fake table from which we get the result set */
113972    Select *pSel;     /* Copy of the SELECT that implements the view */
113973    int nErr = 0;     /* Number of errors encountered */
113974    int n;            /* Temporarily holds the number of cursors assigned */
113975    sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
113976  #ifndef SQLITE_OMIT_VIRTUALTABLE
113977    int rc;
113978  #endif
113979  #ifndef SQLITE_OMIT_AUTHORIZATION
113980    sqlite3_xauth xAuth;       /* Saved xAuth pointer */
113981  #endif
113982  
113983    assert( pTable );
113984  
113985  #ifndef SQLITE_OMIT_VIRTUALTABLE
113986    db->nSchemaLock++;
113987    rc = sqlite3VtabCallConnect(pParse, pTable);
113988    db->nSchemaLock--;
113989    if( rc ){
113990      return 1;
113991    }
113992    if( IsVirtual(pTable) ) return 0;
113993  #endif
113994  
113995  #ifndef SQLITE_OMIT_VIEW
113996    /* A positive nCol means the columns names for this view are
113997    ** already known.
113998    */
113999    if( pTable->nCol>0 ) return 0;
114000  
114001    /* A negative nCol is a special marker meaning that we are currently
114002    ** trying to compute the column names.  If we enter this routine with
114003    ** a negative nCol, it means two or more views form a loop, like this:
114004    **
114005    **     CREATE VIEW one AS SELECT * FROM two;
114006    **     CREATE VIEW two AS SELECT * FROM one;
114007    **
114008    ** Actually, the error above is now caught prior to reaching this point.
114009    ** But the following test is still important as it does come up
114010    ** in the following:
114011    ** 
114012    **     CREATE TABLE main.ex1(a);
114013    **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
114014    **     SELECT * FROM temp.ex1;
114015    */
114016    if( pTable->nCol<0 ){
114017      sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
114018      return 1;
114019    }
114020    assert( pTable->nCol>=0 );
114021  
114022    /* If we get this far, it means we need to compute the table names.
114023    ** Note that the call to sqlite3ResultSetOfSelect() will expand any
114024    ** "*" elements in the results set of the view and will assign cursors
114025    ** to the elements of the FROM clause.  But we do not want these changes
114026    ** to be permanent.  So the computation is done on a copy of the SELECT
114027    ** statement that defines the view.
114028    */
114029    assert( pTable->pSelect );
114030    pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
114031    if( pSel ){
114032  #ifndef SQLITE_OMIT_ALTERTABLE
114033      u8 eParseMode = pParse->eParseMode;
114034      pParse->eParseMode = PARSE_MODE_NORMAL;
114035  #endif
114036      n = pParse->nTab;
114037      sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
114038      pTable->nCol = -1;
114039      db->lookaside.bDisable++;
114040  #ifndef SQLITE_OMIT_AUTHORIZATION
114041      xAuth = db->xAuth;
114042      db->xAuth = 0;
114043      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
114044      db->xAuth = xAuth;
114045  #else
114046      pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
114047  #endif
114048      pParse->nTab = n;
114049      if( pTable->pCheck ){
114050        /* CREATE VIEW name(arglist) AS ...
114051        ** The names of the columns in the table are taken from
114052        ** arglist which is stored in pTable->pCheck.  The pCheck field
114053        ** normally holds CHECK constraints on an ordinary table, but for
114054        ** a VIEW it holds the list of column names.
114055        */
114056        sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
114057                                   &pTable->nCol, &pTable->aCol);
114058        if( db->mallocFailed==0 
114059         && pParse->nErr==0
114060         && pTable->nCol==pSel->pEList->nExpr
114061        ){
114062          sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
114063        }
114064      }else if( pSelTab ){
114065        /* CREATE VIEW name AS...  without an argument list.  Construct
114066        ** the column names from the SELECT statement that defines the view.
114067        */
114068        assert( pTable->aCol==0 );
114069        pTable->nCol = pSelTab->nCol;
114070        pTable->aCol = pSelTab->aCol;
114071        pSelTab->nCol = 0;
114072        pSelTab->aCol = 0;
114073        assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
114074      }else{
114075        pTable->nCol = 0;
114076        nErr++;
114077      }
114078      sqlite3DeleteTable(db, pSelTab);
114079      sqlite3SelectDelete(db, pSel);
114080      db->lookaside.bDisable--;
114081  #ifndef SQLITE_OMIT_ALTERTABLE
114082      pParse->eParseMode = eParseMode;
114083  #endif
114084    } else {
114085      nErr++;
114086    }
114087    pTable->pSchema->schemaFlags |= DB_UnresetViews;
114088    if( db->mallocFailed ){
114089      sqlite3DeleteColumnNames(db, pTable);
114090      pTable->aCol = 0;
114091      pTable->nCol = 0;
114092    }
114093  #endif /* SQLITE_OMIT_VIEW */
114094    return nErr;  
114095  }
114096  #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
114097  
114098  #ifndef SQLITE_OMIT_VIEW
114099  /*
114100  ** Clear the column names from every VIEW in database idx.
114101  */
114102  static void sqliteViewResetAll(sqlite3 *db, int idx){
114103    HashElem *i;
114104    assert( sqlite3SchemaMutexHeld(db, idx, 0) );
114105    if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
114106    for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
114107      Table *pTab = sqliteHashData(i);
114108      if( pTab->pSelect ){
114109        sqlite3DeleteColumnNames(db, pTab);
114110        pTab->aCol = 0;
114111        pTab->nCol = 0;
114112      }
114113    }
114114    DbClearProperty(db, idx, DB_UnresetViews);
114115  }
114116  #else
114117  # define sqliteViewResetAll(A,B)
114118  #endif /* SQLITE_OMIT_VIEW */
114119  
114120  /*
114121  ** This function is called by the VDBE to adjust the internal schema
114122  ** used by SQLite when the btree layer moves a table root page. The
114123  ** root-page of a table or index in database iDb has changed from iFrom
114124  ** to iTo.
114125  **
114126  ** Ticket #1728:  The symbol table might still contain information
114127  ** on tables and/or indices that are the process of being deleted.
114128  ** If you are unlucky, one of those deleted indices or tables might
114129  ** have the same rootpage number as the real table or index that is
114130  ** being moved.  So we cannot stop searching after the first match 
114131  ** because the first match might be for one of the deleted indices
114132  ** or tables and not the table/index that is actually being moved.
114133  ** We must continue looping until all tables and indices with
114134  ** rootpage==iFrom have been converted to have a rootpage of iTo
114135  ** in order to be certain that we got the right one.
114136  */
114137  #ifndef SQLITE_OMIT_AUTOVACUUM
114138  SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
114139    HashElem *pElem;
114140    Hash *pHash;
114141    Db *pDb;
114142  
114143    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114144    pDb = &db->aDb[iDb];
114145    pHash = &pDb->pSchema->tblHash;
114146    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
114147      Table *pTab = sqliteHashData(pElem);
114148      if( pTab->tnum==iFrom ){
114149        pTab->tnum = iTo;
114150      }
114151    }
114152    pHash = &pDb->pSchema->idxHash;
114153    for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
114154      Index *pIdx = sqliteHashData(pElem);
114155      if( pIdx->tnum==iFrom ){
114156        pIdx->tnum = iTo;
114157      }
114158    }
114159  }
114160  #endif
114161  
114162  /*
114163  ** Write code to erase the table with root-page iTable from database iDb.
114164  ** Also write code to modify the sqlite_master table and internal schema
114165  ** if a root-page of another table is moved by the btree-layer whilst
114166  ** erasing iTable (this can happen with an auto-vacuum database).
114167  */ 
114168  static void destroyRootPage(Parse *pParse, int iTable, int iDb){
114169    Vdbe *v = sqlite3GetVdbe(pParse);
114170    int r1 = sqlite3GetTempReg(pParse);
114171    if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
114172    sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
114173    sqlite3MayAbort(pParse);
114174  #ifndef SQLITE_OMIT_AUTOVACUUM
114175    /* OP_Destroy stores an in integer r1. If this integer
114176    ** is non-zero, then it is the root page number of a table moved to
114177    ** location iTable. The following code modifies the sqlite_master table to
114178    ** reflect this.
114179    **
114180    ** The "#NNN" in the SQL is a special constant that means whatever value
114181    ** is in register NNN.  See grammar rules associated with the TK_REGISTER
114182    ** token for additional information.
114183    */
114184    sqlite3NestedParse(pParse, 
114185       "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
114186       pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
114187  #endif
114188    sqlite3ReleaseTempReg(pParse, r1);
114189  }
114190  
114191  /*
114192  ** Write VDBE code to erase table pTab and all associated indices on disk.
114193  ** Code to update the sqlite_master tables and internal schema definitions
114194  ** in case a root-page belonging to another table is moved by the btree layer
114195  ** is also added (this can happen with an auto-vacuum database).
114196  */
114197  static void destroyTable(Parse *pParse, Table *pTab){
114198    /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
114199    ** is not defined), then it is important to call OP_Destroy on the
114200    ** table and index root-pages in order, starting with the numerically 
114201    ** largest root-page number. This guarantees that none of the root-pages
114202    ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
114203    ** following were coded:
114204    **
114205    ** OP_Destroy 4 0
114206    ** ...
114207    ** OP_Destroy 5 0
114208    **
114209    ** and root page 5 happened to be the largest root-page number in the
114210    ** database, then root page 5 would be moved to page 4 by the 
114211    ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
114212    ** a free-list page.
114213    */
114214    int iTab = pTab->tnum;
114215    int iDestroyed = 0;
114216  
114217    while( 1 ){
114218      Index *pIdx;
114219      int iLargest = 0;
114220  
114221      if( iDestroyed==0 || iTab<iDestroyed ){
114222        iLargest = iTab;
114223      }
114224      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114225        int iIdx = pIdx->tnum;
114226        assert( pIdx->pSchema==pTab->pSchema );
114227        if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
114228          iLargest = iIdx;
114229        }
114230      }
114231      if( iLargest==0 ){
114232        return;
114233      }else{
114234        int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
114235        assert( iDb>=0 && iDb<pParse->db->nDb );
114236        destroyRootPage(pParse, iLargest, iDb);
114237        iDestroyed = iLargest;
114238      }
114239    }
114240  }
114241  
114242  /*
114243  ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
114244  ** after a DROP INDEX or DROP TABLE command.
114245  */
114246  static void sqlite3ClearStatTables(
114247    Parse *pParse,         /* The parsing context */
114248    int iDb,               /* The database number */
114249    const char *zType,     /* "idx" or "tbl" */
114250    const char *zName      /* Name of index or table */
114251  ){
114252    int i;
114253    const char *zDbName = pParse->db->aDb[iDb].zDbSName;
114254    for(i=1; i<=4; i++){
114255      char zTab[24];
114256      sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
114257      if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
114258        sqlite3NestedParse(pParse,
114259          "DELETE FROM %Q.%s WHERE %s=%Q",
114260          zDbName, zTab, zType, zName
114261        );
114262      }
114263    }
114264  }
114265  
114266  /*
114267  ** Generate code to drop a table.
114268  */
114269  SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
114270    Vdbe *v;
114271    sqlite3 *db = pParse->db;
114272    Trigger *pTrigger;
114273    Db *pDb = &db->aDb[iDb];
114274  
114275    v = sqlite3GetVdbe(pParse);
114276    assert( v!=0 );
114277    sqlite3BeginWriteOperation(pParse, 1, iDb);
114278  
114279  #ifndef SQLITE_OMIT_VIRTUALTABLE
114280    if( IsVirtual(pTab) ){
114281      sqlite3VdbeAddOp0(v, OP_VBegin);
114282    }
114283  #endif
114284  
114285    /* Drop all triggers associated with the table being dropped. Code
114286    ** is generated to remove entries from sqlite_master and/or
114287    ** sqlite_temp_master if required.
114288    */
114289    pTrigger = sqlite3TriggerList(pParse, pTab);
114290    while( pTrigger ){
114291      assert( pTrigger->pSchema==pTab->pSchema || 
114292          pTrigger->pSchema==db->aDb[1].pSchema );
114293      sqlite3DropTriggerPtr(pParse, pTrigger);
114294      pTrigger = pTrigger->pNext;
114295    }
114296  
114297  #ifndef SQLITE_OMIT_AUTOINCREMENT
114298    /* Remove any entries of the sqlite_sequence table associated with
114299    ** the table being dropped. This is done before the table is dropped
114300    ** at the btree level, in case the sqlite_sequence table needs to
114301    ** move as a result of the drop (can happen in auto-vacuum mode).
114302    */
114303    if( pTab->tabFlags & TF_Autoincrement ){
114304      sqlite3NestedParse(pParse,
114305        "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
114306        pDb->zDbSName, pTab->zName
114307      );
114308    }
114309  #endif
114310  
114311    /* Drop all SQLITE_MASTER table and index entries that refer to the
114312    ** table. The program name loops through the master table and deletes
114313    ** every row that refers to a table of the same name as the one being
114314    ** dropped. Triggers are handled separately because a trigger can be
114315    ** created in the temp database that refers to a table in another
114316    ** database.
114317    */
114318    sqlite3NestedParse(pParse, 
114319        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
114320        pDb->zDbSName, MASTER_NAME, pTab->zName);
114321    if( !isView && !IsVirtual(pTab) ){
114322      destroyTable(pParse, pTab);
114323    }
114324  
114325    /* Remove the table entry from SQLite's internal schema and modify
114326    ** the schema cookie.
114327    */
114328    if( IsVirtual(pTab) ){
114329      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
114330      sqlite3MayAbort(pParse);
114331    }
114332    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
114333    sqlite3ChangeCookie(pParse, iDb);
114334    sqliteViewResetAll(db, iDb);
114335  }
114336  
114337  /*
114338  ** This routine is called to do the work of a DROP TABLE statement.
114339  ** pName is the name of the table to be dropped.
114340  */
114341  SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
114342    Table *pTab;
114343    Vdbe *v;
114344    sqlite3 *db = pParse->db;
114345    int iDb;
114346  
114347    if( db->mallocFailed ){
114348      goto exit_drop_table;
114349    }
114350    assert( pParse->nErr==0 );
114351    assert( pName->nSrc==1 );
114352    if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
114353    if( noErr ) db->suppressErr++;
114354    assert( isView==0 || isView==LOCATE_VIEW );
114355    pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
114356    if( noErr ) db->suppressErr--;
114357  
114358    if( pTab==0 ){
114359      if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
114360      goto exit_drop_table;
114361    }
114362    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114363    assert( iDb>=0 && iDb<db->nDb );
114364  
114365    /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
114366    ** it is initialized.
114367    */
114368    if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
114369      goto exit_drop_table;
114370    }
114371  #ifndef SQLITE_OMIT_AUTHORIZATION
114372    {
114373      int code;
114374      const char *zTab = SCHEMA_TABLE(iDb);
114375      const char *zDb = db->aDb[iDb].zDbSName;
114376      const char *zArg2 = 0;
114377      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
114378        goto exit_drop_table;
114379      }
114380      if( isView ){
114381        if( !OMIT_TEMPDB && iDb==1 ){
114382          code = SQLITE_DROP_TEMP_VIEW;
114383        }else{
114384          code = SQLITE_DROP_VIEW;
114385        }
114386  #ifndef SQLITE_OMIT_VIRTUALTABLE
114387      }else if( IsVirtual(pTab) ){
114388        code = SQLITE_DROP_VTABLE;
114389        zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
114390  #endif
114391      }else{
114392        if( !OMIT_TEMPDB && iDb==1 ){
114393          code = SQLITE_DROP_TEMP_TABLE;
114394        }else{
114395          code = SQLITE_DROP_TABLE;
114396        }
114397      }
114398      if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
114399        goto exit_drop_table;
114400      }
114401      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
114402        goto exit_drop_table;
114403      }
114404    }
114405  #endif
114406    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
114407      && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
114408      sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
114409      goto exit_drop_table;
114410    }
114411  
114412  #ifndef SQLITE_OMIT_VIEW
114413    /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
114414    ** on a table.
114415    */
114416    if( isView && pTab->pSelect==0 ){
114417      sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
114418      goto exit_drop_table;
114419    }
114420    if( !isView && pTab->pSelect ){
114421      sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
114422      goto exit_drop_table;
114423    }
114424  #endif
114425  
114426    /* Generate code to remove the table from the master table
114427    ** on disk.
114428    */
114429    v = sqlite3GetVdbe(pParse);
114430    if( v ){
114431      sqlite3BeginWriteOperation(pParse, 1, iDb);
114432      if( !isView ){
114433        sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
114434        sqlite3FkDropTable(pParse, pName, pTab);
114435      }
114436      sqlite3CodeDropTable(pParse, pTab, iDb, isView);
114437    }
114438  
114439  exit_drop_table:
114440    sqlite3SrcListDelete(db, pName);
114441  }
114442  
114443  /*
114444  ** This routine is called to create a new foreign key on the table
114445  ** currently under construction.  pFromCol determines which columns
114446  ** in the current table point to the foreign key.  If pFromCol==0 then
114447  ** connect the key to the last column inserted.  pTo is the name of
114448  ** the table referred to (a.k.a the "parent" table).  pToCol is a list
114449  ** of tables in the parent pTo table.  flags contains all
114450  ** information about the conflict resolution algorithms specified
114451  ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
114452  **
114453  ** An FKey structure is created and added to the table currently
114454  ** under construction in the pParse->pNewTable field.
114455  **
114456  ** The foreign key is set for IMMEDIATE processing.  A subsequent call
114457  ** to sqlite3DeferForeignKey() might change this to DEFERRED.
114458  */
114459  SQLITE_PRIVATE void sqlite3CreateForeignKey(
114460    Parse *pParse,       /* Parsing context */
114461    ExprList *pFromCol,  /* Columns in this table that point to other table */
114462    Token *pTo,          /* Name of the other table */
114463    ExprList *pToCol,    /* Columns in the other table */
114464    int flags            /* Conflict resolution algorithms. */
114465  ){
114466    sqlite3 *db = pParse->db;
114467  #ifndef SQLITE_OMIT_FOREIGN_KEY
114468    FKey *pFKey = 0;
114469    FKey *pNextTo;
114470    Table *p = pParse->pNewTable;
114471    int nByte;
114472    int i;
114473    int nCol;
114474    char *z;
114475  
114476    assert( pTo!=0 );
114477    if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
114478    if( pFromCol==0 ){
114479      int iCol = p->nCol-1;
114480      if( NEVER(iCol<0) ) goto fk_end;
114481      if( pToCol && pToCol->nExpr!=1 ){
114482        sqlite3ErrorMsg(pParse, "foreign key on %s"
114483           " should reference only one column of table %T",
114484           p->aCol[iCol].zName, pTo);
114485        goto fk_end;
114486      }
114487      nCol = 1;
114488    }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
114489      sqlite3ErrorMsg(pParse,
114490          "number of columns in foreign key does not match the number of "
114491          "columns in the referenced table");
114492      goto fk_end;
114493    }else{
114494      nCol = pFromCol->nExpr;
114495    }
114496    nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
114497    if( pToCol ){
114498      for(i=0; i<pToCol->nExpr; i++){
114499        nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
114500      }
114501    }
114502    pFKey = sqlite3DbMallocZero(db, nByte );
114503    if( pFKey==0 ){
114504      goto fk_end;
114505    }
114506    pFKey->pFrom = p;
114507    pFKey->pNextFrom = p->pFKey;
114508    z = (char*)&pFKey->aCol[nCol];
114509    pFKey->zTo = z;
114510    if( IN_RENAME_OBJECT ){
114511      sqlite3RenameTokenMap(pParse, (void*)z, pTo);
114512    }
114513    memcpy(z, pTo->z, pTo->n);
114514    z[pTo->n] = 0;
114515    sqlite3Dequote(z);
114516    z += pTo->n+1;
114517    pFKey->nCol = nCol;
114518    if( pFromCol==0 ){
114519      pFKey->aCol[0].iFrom = p->nCol-1;
114520    }else{
114521      for(i=0; i<nCol; i++){
114522        int j;
114523        for(j=0; j<p->nCol; j++){
114524          if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
114525            pFKey->aCol[i].iFrom = j;
114526            break;
114527          }
114528        }
114529        if( j>=p->nCol ){
114530          sqlite3ErrorMsg(pParse, 
114531            "unknown column \"%s\" in foreign key definition", 
114532            pFromCol->a[i].zName);
114533          goto fk_end;
114534        }
114535        if( IN_RENAME_OBJECT ){
114536          sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
114537        }
114538      }
114539    }
114540    if( pToCol ){
114541      for(i=0; i<nCol; i++){
114542        int n = sqlite3Strlen30(pToCol->a[i].zName);
114543        pFKey->aCol[i].zCol = z;
114544        if( IN_RENAME_OBJECT ){
114545          sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
114546        }
114547        memcpy(z, pToCol->a[i].zName, n);
114548        z[n] = 0;
114549        z += n+1;
114550      }
114551    }
114552    pFKey->isDeferred = 0;
114553    pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
114554    pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
114555  
114556    assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
114557    pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
114558        pFKey->zTo, (void *)pFKey
114559    );
114560    if( pNextTo==pFKey ){
114561      sqlite3OomFault(db);
114562      goto fk_end;
114563    }
114564    if( pNextTo ){
114565      assert( pNextTo->pPrevTo==0 );
114566      pFKey->pNextTo = pNextTo;
114567      pNextTo->pPrevTo = pFKey;
114568    }
114569  
114570    /* Link the foreign key to the table as the last step.
114571    */
114572    p->pFKey = pFKey;
114573    pFKey = 0;
114574  
114575  fk_end:
114576    sqlite3DbFree(db, pFKey);
114577  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
114578    sqlite3ExprListDelete(db, pFromCol);
114579    sqlite3ExprListDelete(db, pToCol);
114580  }
114581  
114582  /*
114583  ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
114584  ** clause is seen as part of a foreign key definition.  The isDeferred
114585  ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
114586  ** The behavior of the most recently created foreign key is adjusted
114587  ** accordingly.
114588  */
114589  SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
114590  #ifndef SQLITE_OMIT_FOREIGN_KEY
114591    Table *pTab;
114592    FKey *pFKey;
114593    if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
114594    assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
114595    pFKey->isDeferred = (u8)isDeferred;
114596  #endif
114597  }
114598  
114599  /*
114600  ** Generate code that will erase and refill index *pIdx.  This is
114601  ** used to initialize a newly created index or to recompute the
114602  ** content of an index in response to a REINDEX command.
114603  **
114604  ** if memRootPage is not negative, it means that the index is newly
114605  ** created.  The register specified by memRootPage contains the
114606  ** root page number of the index.  If memRootPage is negative, then
114607  ** the index already exists and must be cleared before being refilled and
114608  ** the root page number of the index is taken from pIndex->tnum.
114609  */
114610  static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
114611    Table *pTab = pIndex->pTable;  /* The table that is indexed */
114612    int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
114613    int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
114614    int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
114615    int addr1;                     /* Address of top of loop */
114616    int addr2;                     /* Address to jump to for next iteration */
114617    int tnum;                      /* Root page of index */
114618    int iPartIdxLabel;             /* Jump to this label to skip a row */
114619    Vdbe *v;                       /* Generate code into this virtual machine */
114620    KeyInfo *pKey;                 /* KeyInfo for index */
114621    int regRecord;                 /* Register holding assembled index record */
114622    sqlite3 *db = pParse->db;      /* The database connection */
114623    int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
114624  
114625  #ifndef SQLITE_OMIT_AUTHORIZATION
114626    if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
114627        db->aDb[iDb].zDbSName ) ){
114628      return;
114629    }
114630  #endif
114631  
114632    /* Require a write-lock on the table to perform this operation */
114633    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
114634  
114635    v = sqlite3GetVdbe(pParse);
114636    if( v==0 ) return;
114637    if( memRootPage>=0 ){
114638      tnum = memRootPage;
114639    }else{
114640      tnum = pIndex->tnum;
114641    }
114642    pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
114643    assert( pKey!=0 || db->mallocFailed || pParse->nErr );
114644  
114645    /* Open the sorter cursor if we are to use one. */
114646    iSorter = pParse->nTab++;
114647    sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
114648                      sqlite3KeyInfoRef(pKey), P4_KEYINFO);
114649  
114650    /* Open the table. Loop through all rows of the table, inserting index
114651    ** records into the sorter. */
114652    sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
114653    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
114654    regRecord = sqlite3GetTempReg(pParse);
114655    sqlite3MultiWrite(pParse);
114656  
114657    sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
114658    sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
114659    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
114660    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
114661    sqlite3VdbeJumpHere(v, addr1);
114662    if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
114663    sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
114664                      (char *)pKey, P4_KEYINFO);
114665    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
114666  
114667    addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
114668    if( IsUniqueIndex(pIndex) ){
114669      int j2 = sqlite3VdbeGoto(v, 1);
114670      addr2 = sqlite3VdbeCurrentAddr(v);
114671      sqlite3VdbeVerifyAbortable(v, OE_Abort);
114672      sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
114673                           pIndex->nKeyCol); VdbeCoverage(v);
114674      sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
114675      sqlite3VdbeJumpHere(v, j2);
114676    }else{
114677      addr2 = sqlite3VdbeCurrentAddr(v);
114678    }
114679    sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
114680    sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
114681    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
114682    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
114683    sqlite3ReleaseTempReg(pParse, regRecord);
114684    sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
114685    sqlite3VdbeJumpHere(v, addr1);
114686  
114687    sqlite3VdbeAddOp1(v, OP_Close, iTab);
114688    sqlite3VdbeAddOp1(v, OP_Close, iIdx);
114689    sqlite3VdbeAddOp1(v, OP_Close, iSorter);
114690  }
114691  
114692  /*
114693  ** Allocate heap space to hold an Index object with nCol columns.
114694  **
114695  ** Increase the allocation size to provide an extra nExtra bytes
114696  ** of 8-byte aligned space after the Index object and return a
114697  ** pointer to this extra space in *ppExtra.
114698  */
114699  SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
114700    sqlite3 *db,         /* Database connection */
114701    i16 nCol,            /* Total number of columns in the index */
114702    int nExtra,          /* Number of bytes of extra space to alloc */
114703    char **ppExtra       /* Pointer to the "extra" space */
114704  ){
114705    Index *p;            /* Allocated index object */
114706    int nByte;           /* Bytes of space for Index object + arrays */
114707  
114708    nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
114709            ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
114710            ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
114711                   sizeof(i16)*nCol +            /* Index.aiColumn   */
114712                   sizeof(u8)*nCol);             /* Index.aSortOrder */
114713    p = sqlite3DbMallocZero(db, nByte + nExtra);
114714    if( p ){
114715      char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
114716      p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
114717      p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
114718      p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
114719      p->aSortOrder = (u8*)pExtra;
114720      p->nColumn = nCol;
114721      p->nKeyCol = nCol - 1;
114722      *ppExtra = ((char*)p) + nByte;
114723    }
114724    return p;
114725  }
114726  
114727  /*
114728  ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
114729  ** and pTblList is the name of the table that is to be indexed.  Both will 
114730  ** be NULL for a primary key or an index that is created to satisfy a
114731  ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
114732  ** as the table to be indexed.  pParse->pNewTable is a table that is
114733  ** currently being constructed by a CREATE TABLE statement.
114734  **
114735  ** pList is a list of columns to be indexed.  pList will be NULL if this
114736  ** is a primary key or unique-constraint on the most recent column added
114737  ** to the table currently under construction.  
114738  */
114739  SQLITE_PRIVATE void sqlite3CreateIndex(
114740    Parse *pParse,     /* All information about this parse */
114741    Token *pName1,     /* First part of index name. May be NULL */
114742    Token *pName2,     /* Second part of index name. May be NULL */
114743    SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
114744    ExprList *pList,   /* A list of columns to be indexed */
114745    int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
114746    Token *pStart,     /* The CREATE token that begins this statement */
114747    Expr *pPIWhere,    /* WHERE clause for partial indices */
114748    int sortOrder,     /* Sort order of primary key when pList==NULL */
114749    int ifNotExist,    /* Omit error if index already exists */
114750    u8 idxType         /* The index type */
114751  ){
114752    Table *pTab = 0;     /* Table to be indexed */
114753    Index *pIndex = 0;   /* The index to be created */
114754    char *zName = 0;     /* Name of the index */
114755    int nName;           /* Number of characters in zName */
114756    int i, j;
114757    DbFixer sFix;        /* For assigning database names to pTable */
114758    int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
114759    sqlite3 *db = pParse->db;
114760    Db *pDb;             /* The specific table containing the indexed database */
114761    int iDb;             /* Index of the database that is being written */
114762    Token *pName = 0;    /* Unqualified name of the index to create */
114763    struct ExprList_item *pListItem; /* For looping over pList */
114764    int nExtra = 0;                  /* Space allocated for zExtra[] */
114765    int nExtraCol;                   /* Number of extra columns needed */
114766    char *zExtra = 0;                /* Extra space after the Index object */
114767    Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
114768  
114769    if( db->mallocFailed || pParse->nErr>0 ){
114770      goto exit_create_index;
114771    }
114772    if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
114773      goto exit_create_index;
114774    }
114775    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
114776      goto exit_create_index;
114777    }
114778  
114779    /*
114780    ** Find the table that is to be indexed.  Return early if not found.
114781    */
114782    if( pTblName!=0 ){
114783  
114784      /* Use the two-part index name to determine the database 
114785      ** to search for the table. 'Fix' the table name to this db
114786      ** before looking up the table.
114787      */
114788      assert( pName1 && pName2 );
114789      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
114790      if( iDb<0 ) goto exit_create_index;
114791      assert( pName && pName->z );
114792  
114793  #ifndef SQLITE_OMIT_TEMPDB
114794      /* If the index name was unqualified, check if the table
114795      ** is a temp table. If so, set the database to 1. Do not do this
114796      ** if initialising a database schema.
114797      */
114798      if( !db->init.busy ){
114799        pTab = sqlite3SrcListLookup(pParse, pTblName);
114800        if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
114801          iDb = 1;
114802        }
114803      }
114804  #endif
114805  
114806      sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
114807      if( sqlite3FixSrcList(&sFix, pTblName) ){
114808        /* Because the parser constructs pTblName from a single identifier,
114809        ** sqlite3FixSrcList can never fail. */
114810        assert(0);
114811      }
114812      pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
114813      assert( db->mallocFailed==0 || pTab==0 );
114814      if( pTab==0 ) goto exit_create_index;
114815      if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
114816        sqlite3ErrorMsg(pParse, 
114817             "cannot create a TEMP index on non-TEMP table \"%s\"",
114818             pTab->zName);
114819        goto exit_create_index;
114820      }
114821      if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
114822    }else{
114823      assert( pName==0 );
114824      assert( pStart==0 );
114825      pTab = pParse->pNewTable;
114826      if( !pTab ) goto exit_create_index;
114827      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114828    }
114829    pDb = &db->aDb[iDb];
114830  
114831    assert( pTab!=0 );
114832    assert( pParse->nErr==0 );
114833    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
114834         && db->init.busy==0
114835  #if SQLITE_USER_AUTHENTICATION
114836         && sqlite3UserAuthTable(pTab->zName)==0
114837  #endif
114838  #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
114839         && sqlite3StrICmp(&pTab->zName[7],"master")!=0
114840  #endif
114841         && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0
114842   ){
114843      sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
114844      goto exit_create_index;
114845    }
114846  #ifndef SQLITE_OMIT_VIEW
114847    if( pTab->pSelect ){
114848      sqlite3ErrorMsg(pParse, "views may not be indexed");
114849      goto exit_create_index;
114850    }
114851  #endif
114852  #ifndef SQLITE_OMIT_VIRTUALTABLE
114853    if( IsVirtual(pTab) ){
114854      sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
114855      goto exit_create_index;
114856    }
114857  #endif
114858  
114859    /*
114860    ** Find the name of the index.  Make sure there is not already another
114861    ** index or table with the same name.  
114862    **
114863    ** Exception:  If we are reading the names of permanent indices from the
114864    ** sqlite_master table (because some other process changed the schema) and
114865    ** one of the index names collides with the name of a temporary table or
114866    ** index, then we will continue to process this index.
114867    **
114868    ** If pName==0 it means that we are
114869    ** dealing with a primary key or UNIQUE constraint.  We have to invent our
114870    ** own name.
114871    */
114872    if( pName ){
114873      zName = sqlite3NameFromToken(db, pName);
114874      if( zName==0 ) goto exit_create_index;
114875      assert( pName->z!=0 );
114876      if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
114877        goto exit_create_index;
114878      }
114879      if( !IN_RENAME_OBJECT ){
114880        if( !db->init.busy ){
114881          if( sqlite3FindTable(db, zName, 0)!=0 ){
114882            sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
114883            goto exit_create_index;
114884          }
114885        }
114886        if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
114887          if( !ifNotExist ){
114888            sqlite3ErrorMsg(pParse, "index %s already exists", zName);
114889          }else{
114890            assert( !db->init.busy );
114891            sqlite3CodeVerifySchema(pParse, iDb);
114892          }
114893          goto exit_create_index;
114894        }
114895      }
114896    }else{
114897      int n;
114898      Index *pLoop;
114899      for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
114900      zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
114901      if( zName==0 ){
114902        goto exit_create_index;
114903      }
114904  
114905      /* Automatic index names generated from within sqlite3_declare_vtab()
114906      ** must have names that are distinct from normal automatic index names.
114907      ** The following statement converts "sqlite3_autoindex..." into
114908      ** "sqlite3_butoindex..." in order to make the names distinct.
114909      ** The "vtab_err.test" test demonstrates the need of this statement. */
114910      if( IN_SPECIAL_PARSE ) zName[7]++;
114911    }
114912  
114913    /* Check for authorization to create an index.
114914    */
114915  #ifndef SQLITE_OMIT_AUTHORIZATION
114916    if( !IN_RENAME_OBJECT ){
114917      const char *zDb = pDb->zDbSName;
114918      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
114919        goto exit_create_index;
114920      }
114921      i = SQLITE_CREATE_INDEX;
114922      if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
114923      if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
114924        goto exit_create_index;
114925      }
114926    }
114927  #endif
114928  
114929    /* If pList==0, it means this routine was called to make a primary
114930    ** key out of the last column added to the table under construction.
114931    ** So create a fake list to simulate this.
114932    */
114933    if( pList==0 ){
114934      Token prevCol;
114935      Column *pCol = &pTab->aCol[pTab->nCol-1];
114936      pCol->colFlags |= COLFLAG_UNIQUE;
114937      sqlite3TokenInit(&prevCol, pCol->zName);
114938      pList = sqlite3ExprListAppend(pParse, 0,
114939                sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
114940      if( pList==0 ) goto exit_create_index;
114941      assert( pList->nExpr==1 );
114942      sqlite3ExprListSetSortOrder(pList, sortOrder);
114943    }else{
114944      sqlite3ExprListCheckLength(pParse, pList, "index");
114945    }
114946  
114947    /* Figure out how many bytes of space are required to store explicitly
114948    ** specified collation sequence names.
114949    */
114950    for(i=0; i<pList->nExpr; i++){
114951      Expr *pExpr = pList->a[i].pExpr;
114952      assert( pExpr!=0 );
114953      if( pExpr->op==TK_COLLATE ){
114954        nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
114955      }
114956    }
114957  
114958    /* 
114959    ** Allocate the index structure. 
114960    */
114961    nName = sqlite3Strlen30(zName);
114962    nExtraCol = pPk ? pPk->nKeyCol : 1;
114963    pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
114964                                        nName + nExtra + 1, &zExtra);
114965    if( db->mallocFailed ){
114966      goto exit_create_index;
114967    }
114968    assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
114969    assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
114970    pIndex->zName = zExtra;
114971    zExtra += nName + 1;
114972    memcpy(pIndex->zName, zName, nName+1);
114973    pIndex->pTable = pTab;
114974    pIndex->onError = (u8)onError;
114975    pIndex->uniqNotNull = onError!=OE_None;
114976    pIndex->idxType = idxType;
114977    pIndex->pSchema = db->aDb[iDb].pSchema;
114978    pIndex->nKeyCol = pList->nExpr;
114979    if( pPIWhere ){
114980      sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
114981      pIndex->pPartIdxWhere = pPIWhere;
114982      pPIWhere = 0;
114983    }
114984    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114985  
114986    /* Check to see if we should honor DESC requests on index columns
114987    */
114988    if( pDb->pSchema->file_format>=4 ){
114989      sortOrderMask = -1;   /* Honor DESC */
114990    }else{
114991      sortOrderMask = 0;    /* Ignore DESC */
114992    }
114993  
114994    /* Analyze the list of expressions that form the terms of the index and
114995    ** report any errors.  In the common case where the expression is exactly
114996    ** a table column, store that column in aiColumn[].  For general expressions,
114997    ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
114998    **
114999    ** TODO: Issue a warning if two or more columns of the index are identical.
115000    ** TODO: Issue a warning if the table primary key is used as part of the
115001    ** index key.
115002    */
115003    pListItem = pList->a;
115004    if( IN_RENAME_OBJECT ){
115005      pIndex->aColExpr = pList;
115006      pList = 0;
115007    }
115008    for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
115009      Expr *pCExpr;                  /* The i-th index expression */
115010      int requestedSortOrder;        /* ASC or DESC on the i-th expression */
115011      const char *zColl;             /* Collation sequence name */
115012  
115013      sqlite3StringToId(pListItem->pExpr);
115014      sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
115015      if( pParse->nErr ) goto exit_create_index;
115016      pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
115017      if( pCExpr->op!=TK_COLUMN ){
115018        if( pTab==pParse->pNewTable ){
115019          sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
115020                                  "UNIQUE constraints");
115021          goto exit_create_index;
115022        }
115023        if( pIndex->aColExpr==0 ){
115024          pIndex->aColExpr = pList;
115025          pList = 0;
115026        }
115027        j = XN_EXPR;
115028        pIndex->aiColumn[i] = XN_EXPR;
115029        pIndex->uniqNotNull = 0;
115030      }else{
115031        j = pCExpr->iColumn;
115032        assert( j<=0x7fff );
115033        if( j<0 ){
115034          j = pTab->iPKey;
115035        }else if( pTab->aCol[j].notNull==0 ){
115036          pIndex->uniqNotNull = 0;
115037        }
115038        pIndex->aiColumn[i] = (i16)j;
115039      }
115040      zColl = 0;
115041      if( pListItem->pExpr->op==TK_COLLATE ){
115042        int nColl;
115043        zColl = pListItem->pExpr->u.zToken;
115044        nColl = sqlite3Strlen30(zColl) + 1;
115045        assert( nExtra>=nColl );
115046        memcpy(zExtra, zColl, nColl);
115047        zColl = zExtra;
115048        zExtra += nColl;
115049        nExtra -= nColl;
115050      }else if( j>=0 ){
115051        zColl = pTab->aCol[j].zColl;
115052      }
115053      if( !zColl ) zColl = sqlite3StrBINARY;
115054      if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
115055        goto exit_create_index;
115056      }
115057      pIndex->azColl[i] = zColl;
115058      requestedSortOrder = pListItem->sortOrder & sortOrderMask;
115059      pIndex->aSortOrder[i] = (u8)requestedSortOrder;
115060    }
115061  
115062    /* Append the table key to the end of the index.  For WITHOUT ROWID
115063    ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
115064    ** normal tables (when pPk==0) this will be the rowid.
115065    */
115066    if( pPk ){
115067      for(j=0; j<pPk->nKeyCol; j++){
115068        int x = pPk->aiColumn[j];
115069        assert( x>=0 );
115070        if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
115071          pIndex->nColumn--; 
115072        }else{
115073          pIndex->aiColumn[i] = x;
115074          pIndex->azColl[i] = pPk->azColl[j];
115075          pIndex->aSortOrder[i] = pPk->aSortOrder[j];
115076          i++;
115077        }
115078      }
115079      assert( i==pIndex->nColumn );
115080    }else{
115081      pIndex->aiColumn[i] = XN_ROWID;
115082      pIndex->azColl[i] = sqlite3StrBINARY;
115083    }
115084    sqlite3DefaultRowEst(pIndex);
115085    if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
115086  
115087    /* If this index contains every column of its table, then mark
115088    ** it as a covering index */
115089    assert( HasRowid(pTab) 
115090        || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
115091    recomputeColumnsNotIndexed(pIndex);
115092    if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
115093      pIndex->isCovering = 1;
115094      for(j=0; j<pTab->nCol; j++){
115095        if( j==pTab->iPKey ) continue;
115096        if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
115097        pIndex->isCovering = 0;
115098        break;
115099      }
115100    }
115101  
115102    if( pTab==pParse->pNewTable ){
115103      /* This routine has been called to create an automatic index as a
115104      ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
115105      ** a PRIMARY KEY or UNIQUE clause following the column definitions.
115106      ** i.e. one of:
115107      **
115108      ** CREATE TABLE t(x PRIMARY KEY, y);
115109      ** CREATE TABLE t(x, y, UNIQUE(x, y));
115110      **
115111      ** Either way, check to see if the table already has such an index. If
115112      ** so, don't bother creating this one. This only applies to
115113      ** automatically created indices. Users can do as they wish with
115114      ** explicit indices.
115115      **
115116      ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
115117      ** (and thus suppressing the second one) even if they have different
115118      ** sort orders.
115119      **
115120      ** If there are different collating sequences or if the columns of
115121      ** the constraint occur in different orders, then the constraints are
115122      ** considered distinct and both result in separate indices.
115123      */
115124      Index *pIdx;
115125      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115126        int k;
115127        assert( IsUniqueIndex(pIdx) );
115128        assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
115129        assert( IsUniqueIndex(pIndex) );
115130  
115131        if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
115132        for(k=0; k<pIdx->nKeyCol; k++){
115133          const char *z1;
115134          const char *z2;
115135          assert( pIdx->aiColumn[k]>=0 );
115136          if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
115137          z1 = pIdx->azColl[k];
115138          z2 = pIndex->azColl[k];
115139          if( sqlite3StrICmp(z1, z2) ) break;
115140        }
115141        if( k==pIdx->nKeyCol ){
115142          if( pIdx->onError!=pIndex->onError ){
115143            /* This constraint creates the same index as a previous
115144            ** constraint specified somewhere in the CREATE TABLE statement.
115145            ** However the ON CONFLICT clauses are different. If both this 
115146            ** constraint and the previous equivalent constraint have explicit
115147            ** ON CONFLICT clauses this is an error. Otherwise, use the
115148            ** explicitly specified behavior for the index.
115149            */
115150            if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
115151              sqlite3ErrorMsg(pParse, 
115152                  "conflicting ON CONFLICT clauses specified", 0);
115153            }
115154            if( pIdx->onError==OE_Default ){
115155              pIdx->onError = pIndex->onError;
115156            }
115157          }
115158          if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
115159          if( IN_RENAME_OBJECT ){
115160            pIndex->pNext = pParse->pNewIndex;
115161            pParse->pNewIndex = pIndex;
115162            pIndex = 0;
115163          }
115164          goto exit_create_index;
115165        }
115166      }
115167    }
115168  
115169    if( !IN_RENAME_OBJECT ){
115170  
115171      /* Link the new Index structure to its table and to the other
115172      ** in-memory database structures. 
115173      */
115174      assert( pParse->nErr==0 );
115175      if( db->init.busy ){
115176        Index *p;
115177        assert( !IN_SPECIAL_PARSE );
115178        assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
115179        if( pTblName!=0 ){
115180          pIndex->tnum = db->init.newTnum;
115181          if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
115182            sqlite3ErrorMsg(pParse, "invalid rootpage");
115183            pParse->rc = SQLITE_CORRUPT_BKPT;
115184            goto exit_create_index;
115185          }
115186        }
115187        p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
115188            pIndex->zName, pIndex);
115189        if( p ){
115190          assert( p==pIndex );  /* Malloc must have failed */
115191          sqlite3OomFault(db);
115192          goto exit_create_index;
115193        }
115194        db->mDbFlags |= DBFLAG_SchemaChange;
115195      }
115196  
115197      /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
115198      ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
115199      ** emit code to allocate the index rootpage on disk and make an entry for
115200      ** the index in the sqlite_master table and populate the index with
115201      ** content.  But, do not do this if we are simply reading the sqlite_master
115202      ** table to parse the schema, or if this index is the PRIMARY KEY index
115203      ** of a WITHOUT ROWID table.
115204      **
115205      ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
115206      ** or UNIQUE index in a CREATE TABLE statement.  Since the table
115207      ** has just been created, it contains no data and the index initialization
115208      ** step can be skipped.
115209      */
115210      else if( HasRowid(pTab) || pTblName!=0 ){
115211        Vdbe *v;
115212        char *zStmt;
115213        int iMem = ++pParse->nMem;
115214  
115215        v = sqlite3GetVdbe(pParse);
115216        if( v==0 ) goto exit_create_index;
115217  
115218        sqlite3BeginWriteOperation(pParse, 1, iDb);
115219  
115220        /* Create the rootpage for the index using CreateIndex. But before
115221        ** doing so, code a Noop instruction and store its address in 
115222        ** Index.tnum. This is required in case this index is actually a 
115223        ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 
115224        ** that case the convertToWithoutRowidTable() routine will replace
115225        ** the Noop with a Goto to jump over the VDBE code generated below. */
115226        pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
115227        sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
115228  
115229        /* Gather the complete text of the CREATE INDEX statement into
115230        ** the zStmt variable
115231        */
115232        if( pStart ){
115233          int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
115234          if( pName->z[n-1]==';' ) n--;
115235          /* A named index with an explicit CREATE INDEX statement */
115236          zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
115237              onError==OE_None ? "" : " UNIQUE", n, pName->z);
115238        }else{
115239          /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
115240          /* zStmt = sqlite3MPrintf(""); */
115241          zStmt = 0;
115242        }
115243  
115244        /* Add an entry in sqlite_master for this index
115245        */
115246        sqlite3NestedParse(pParse, 
115247            "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
115248            db->aDb[iDb].zDbSName, MASTER_NAME,
115249            pIndex->zName,
115250            pTab->zName,
115251            iMem,
115252            zStmt
115253            );
115254        sqlite3DbFree(db, zStmt);
115255  
115256        /* Fill the index with data and reparse the schema. Code an OP_Expire
115257        ** to invalidate all pre-compiled statements.
115258        */
115259        if( pTblName ){
115260          sqlite3RefillIndex(pParse, pIndex, iMem);
115261          sqlite3ChangeCookie(pParse, iDb);
115262          sqlite3VdbeAddParseSchemaOp(v, iDb,
115263              sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
115264          sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
115265        }
115266  
115267        sqlite3VdbeJumpHere(v, pIndex->tnum);
115268      }
115269    }
115270  
115271    /* When adding an index to the list of indices for a table, make
115272    ** sure all indices labeled OE_Replace come after all those labeled
115273    ** OE_Ignore.  This is necessary for the correct constraint check
115274    ** processing (in sqlite3GenerateConstraintChecks()) as part of
115275    ** UPDATE and INSERT statements.  
115276    */
115277    if( db->init.busy || pTblName==0 ){
115278      if( onError!=OE_Replace || pTab->pIndex==0
115279           || pTab->pIndex->onError==OE_Replace){
115280        pIndex->pNext = pTab->pIndex;
115281        pTab->pIndex = pIndex;
115282      }else{
115283        Index *pOther = pTab->pIndex;
115284        while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
115285          pOther = pOther->pNext;
115286        }
115287        pIndex->pNext = pOther->pNext;
115288        pOther->pNext = pIndex;
115289      }
115290      pIndex = 0;
115291    }
115292    else if( IN_RENAME_OBJECT ){
115293      assert( pParse->pNewIndex==0 );
115294      pParse->pNewIndex = pIndex;
115295      pIndex = 0;
115296    }
115297  
115298    /* Clean up before exiting */
115299  exit_create_index:
115300    if( pIndex ) sqlite3FreeIndex(db, pIndex);
115301    sqlite3ExprDelete(db, pPIWhere);
115302    sqlite3ExprListDelete(db, pList);
115303    sqlite3SrcListDelete(db, pTblName);
115304    sqlite3DbFree(db, zName);
115305  }
115306  
115307  /*
115308  ** Fill the Index.aiRowEst[] array with default information - information
115309  ** to be used when we have not run the ANALYZE command.
115310  **
115311  ** aiRowEst[0] is supposed to contain the number of elements in the index.
115312  ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
115313  ** number of rows in the table that match any particular value of the
115314  ** first column of the index.  aiRowEst[2] is an estimate of the number
115315  ** of rows that match any particular combination of the first 2 columns
115316  ** of the index.  And so forth.  It must always be the case that
115317  *
115318  **           aiRowEst[N]<=aiRowEst[N-1]
115319  **           aiRowEst[N]>=1
115320  **
115321  ** Apart from that, we have little to go on besides intuition as to
115322  ** how aiRowEst[] should be initialized.  The numbers generated here
115323  ** are based on typical values found in actual indices.
115324  */
115325  SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
115326    /*                10,  9,  8,  7,  6 */
115327    LogEst aVal[] = { 33, 32, 30, 28, 26 };
115328    LogEst *a = pIdx->aiRowLogEst;
115329    int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
115330    int i;
115331  
115332    /* Indexes with default row estimates should not have stat1 data */
115333    assert( !pIdx->hasStat1 );
115334  
115335    /* Set the first entry (number of rows in the index) to the estimated 
115336    ** number of rows in the table, or half the number of rows in the table
115337    ** for a partial index.   But do not let the estimate drop below 10. */
115338    a[0] = pIdx->pTable->nRowLogEst;
115339    if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
115340    if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
115341  
115342    /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
115343    ** 6 and each subsequent value (if any) is 5.  */
115344    memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
115345    for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
115346      a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
115347    }
115348  
115349    assert( 0==sqlite3LogEst(1) );
115350    if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
115351  }
115352  
115353  /*
115354  ** This routine will drop an existing named index.  This routine
115355  ** implements the DROP INDEX statement.
115356  */
115357  SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
115358    Index *pIndex;
115359    Vdbe *v;
115360    sqlite3 *db = pParse->db;
115361    int iDb;
115362  
115363    assert( pParse->nErr==0 );   /* Never called with prior errors */
115364    if( db->mallocFailed ){
115365      goto exit_drop_index;
115366    }
115367    assert( pName->nSrc==1 );
115368    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
115369      goto exit_drop_index;
115370    }
115371    pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
115372    if( pIndex==0 ){
115373      if( !ifExists ){
115374        sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
115375      }else{
115376        sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
115377      }
115378      pParse->checkSchema = 1;
115379      goto exit_drop_index;
115380    }
115381    if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
115382      sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
115383        "or PRIMARY KEY constraint cannot be dropped", 0);
115384      goto exit_drop_index;
115385    }
115386    iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
115387  #ifndef SQLITE_OMIT_AUTHORIZATION
115388    {
115389      int code = SQLITE_DROP_INDEX;
115390      Table *pTab = pIndex->pTable;
115391      const char *zDb = db->aDb[iDb].zDbSName;
115392      const char *zTab = SCHEMA_TABLE(iDb);
115393      if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
115394        goto exit_drop_index;
115395      }
115396      if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
115397      if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
115398        goto exit_drop_index;
115399      }
115400    }
115401  #endif
115402  
115403    /* Generate code to remove the index and from the master table */
115404    v = sqlite3GetVdbe(pParse);
115405    if( v ){
115406      sqlite3BeginWriteOperation(pParse, 1, iDb);
115407      sqlite3NestedParse(pParse,
115408         "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
115409         db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
115410      );
115411      sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
115412      sqlite3ChangeCookie(pParse, iDb);
115413      destroyRootPage(pParse, pIndex->tnum, iDb);
115414      sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
115415    }
115416  
115417  exit_drop_index:
115418    sqlite3SrcListDelete(db, pName);
115419  }
115420  
115421  /*
115422  ** pArray is a pointer to an array of objects. Each object in the
115423  ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
115424  ** to extend the array so that there is space for a new object at the end.
115425  **
115426  ** When this function is called, *pnEntry contains the current size of
115427  ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
115428  ** in total).
115429  **
115430  ** If the realloc() is successful (i.e. if no OOM condition occurs), the
115431  ** space allocated for the new object is zeroed, *pnEntry updated to
115432  ** reflect the new size of the array and a pointer to the new allocation
115433  ** returned. *pIdx is set to the index of the new array entry in this case.
115434  **
115435  ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
115436  ** unchanged and a copy of pArray returned.
115437  */
115438  SQLITE_PRIVATE void *sqlite3ArrayAllocate(
115439    sqlite3 *db,      /* Connection to notify of malloc failures */
115440    void *pArray,     /* Array of objects.  Might be reallocated */
115441    int szEntry,      /* Size of each object in the array */
115442    int *pnEntry,     /* Number of objects currently in use */
115443    int *pIdx         /* Write the index of a new slot here */
115444  ){
115445    char *z;
115446    int n = *pnEntry;
115447    if( (n & (n-1))==0 ){
115448      int sz = (n==0) ? 1 : 2*n;
115449      void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
115450      if( pNew==0 ){
115451        *pIdx = -1;
115452        return pArray;
115453      }
115454      pArray = pNew;
115455    }
115456    z = (char*)pArray;
115457    memset(&z[n * szEntry], 0, szEntry);
115458    *pIdx = n;
115459    ++*pnEntry;
115460    return pArray;
115461  }
115462  
115463  /*
115464  ** Append a new element to the given IdList.  Create a new IdList if
115465  ** need be.
115466  **
115467  ** A new IdList is returned, or NULL if malloc() fails.
115468  */
115469  SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
115470    sqlite3 *db = pParse->db;
115471    int i;
115472    if( pList==0 ){
115473      pList = sqlite3DbMallocZero(db, sizeof(IdList) );
115474      if( pList==0 ) return 0;
115475    }
115476    pList->a = sqlite3ArrayAllocate(
115477        db,
115478        pList->a,
115479        sizeof(pList->a[0]),
115480        &pList->nId,
115481        &i
115482    );
115483    if( i<0 ){
115484      sqlite3IdListDelete(db, pList);
115485      return 0;
115486    }
115487    pList->a[i].zName = sqlite3NameFromToken(db, pToken);
115488    if( IN_RENAME_OBJECT && pList->a[i].zName ){
115489      sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
115490    }
115491    return pList;
115492  }
115493  
115494  /*
115495  ** Delete an IdList.
115496  */
115497  SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
115498    int i;
115499    if( pList==0 ) return;
115500    for(i=0; i<pList->nId; i++){
115501      sqlite3DbFree(db, pList->a[i].zName);
115502    }
115503    sqlite3DbFree(db, pList->a);
115504    sqlite3DbFreeNN(db, pList);
115505  }
115506  
115507  /*
115508  ** Return the index in pList of the identifier named zId.  Return -1
115509  ** if not found.
115510  */
115511  SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
115512    int i;
115513    if( pList==0 ) return -1;
115514    for(i=0; i<pList->nId; i++){
115515      if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
115516    }
115517    return -1;
115518  }
115519  
115520  /*
115521  ** Maximum size of a SrcList object.
115522  ** The SrcList object is used to represent the FROM clause of a
115523  ** SELECT statement, and the query planner cannot deal with more
115524  ** than 64 tables in a join.  So any value larger than 64 here
115525  ** is sufficient for most uses.  Smaller values, like say 10, are
115526  ** appropriate for small and memory-limited applications.
115527  */
115528  #ifndef SQLITE_MAX_SRCLIST
115529  # define SQLITE_MAX_SRCLIST 200
115530  #endif
115531  
115532  /*
115533  ** Expand the space allocated for the given SrcList object by
115534  ** creating nExtra new slots beginning at iStart.  iStart is zero based.
115535  ** New slots are zeroed.
115536  **
115537  ** For example, suppose a SrcList initially contains two entries: A,B.
115538  ** To append 3 new entries onto the end, do this:
115539  **
115540  **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
115541  **
115542  ** After the call above it would contain:  A, B, nil, nil, nil.
115543  ** If the iStart argument had been 1 instead of 2, then the result
115544  ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
115545  ** the iStart value would be 0.  The result then would
115546  ** be: nil, nil, nil, A, B.
115547  **
115548  ** If a memory allocation fails or the SrcList becomes too large, leave
115549  ** the original SrcList unchanged, return NULL, and leave an error message
115550  ** in pParse.
115551  */
115552  SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
115553    Parse *pParse,     /* Parsing context into which errors are reported */
115554    SrcList *pSrc,     /* The SrcList to be enlarged */
115555    int nExtra,        /* Number of new slots to add to pSrc->a[] */
115556    int iStart         /* Index in pSrc->a[] of first new slot */
115557  ){
115558    int i;
115559  
115560    /* Sanity checking on calling parameters */
115561    assert( iStart>=0 );
115562    assert( nExtra>=1 );
115563    assert( pSrc!=0 );
115564    assert( iStart<=pSrc->nSrc );
115565  
115566    /* Allocate additional space if needed */
115567    if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
115568      SrcList *pNew;
115569      int nAlloc = pSrc->nSrc*2+nExtra;
115570      sqlite3 *db = pParse->db;
115571  
115572      if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
115573        sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
115574                        SQLITE_MAX_SRCLIST);
115575        return 0;
115576      }
115577      if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
115578      pNew = sqlite3DbRealloc(db, pSrc,
115579                 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
115580      if( pNew==0 ){
115581        assert( db->mallocFailed );
115582        return 0;
115583      }
115584      pSrc = pNew;
115585      pSrc->nAlloc = nAlloc;
115586    }
115587  
115588    /* Move existing slots that come after the newly inserted slots
115589    ** out of the way */
115590    for(i=pSrc->nSrc-1; i>=iStart; i--){
115591      pSrc->a[i+nExtra] = pSrc->a[i];
115592    }
115593    pSrc->nSrc += nExtra;
115594  
115595    /* Zero the newly allocated slots */
115596    memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
115597    for(i=iStart; i<iStart+nExtra; i++){
115598      pSrc->a[i].iCursor = -1;
115599    }
115600  
115601    /* Return a pointer to the enlarged SrcList */
115602    return pSrc;
115603  }
115604  
115605  
115606  /*
115607  ** Append a new table name to the given SrcList.  Create a new SrcList if
115608  ** need be.  A new entry is created in the SrcList even if pTable is NULL.
115609  **
115610  ** A SrcList is returned, or NULL if there is an OOM error or if the
115611  ** SrcList grows to large.  The returned
115612  ** SrcList might be the same as the SrcList that was input or it might be
115613  ** a new one.  If an OOM error does occurs, then the prior value of pList
115614  ** that is input to this routine is automatically freed.
115615  **
115616  ** If pDatabase is not null, it means that the table has an optional
115617  ** database name prefix.  Like this:  "database.table".  The pDatabase
115618  ** points to the table name and the pTable points to the database name.
115619  ** The SrcList.a[].zName field is filled with the table name which might
115620  ** come from pTable (if pDatabase is NULL) or from pDatabase.  
115621  ** SrcList.a[].zDatabase is filled with the database name from pTable,
115622  ** or with NULL if no database is specified.
115623  **
115624  ** In other words, if call like this:
115625  **
115626  **         sqlite3SrcListAppend(D,A,B,0);
115627  **
115628  ** Then B is a table name and the database name is unspecified.  If called
115629  ** like this:
115630  **
115631  **         sqlite3SrcListAppend(D,A,B,C);
115632  **
115633  ** Then C is the table name and B is the database name.  If C is defined
115634  ** then so is B.  In other words, we never have a case where:
115635  **
115636  **         sqlite3SrcListAppend(D,A,0,C);
115637  **
115638  ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
115639  ** before being added to the SrcList.
115640  */
115641  SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
115642    Parse *pParse,      /* Parsing context, in which errors are reported */
115643    SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
115644    Token *pTable,      /* Table to append */
115645    Token *pDatabase    /* Database of the table */
115646  ){
115647    struct SrcList_item *pItem;
115648    sqlite3 *db;
115649    assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
115650    assert( pParse!=0 );
115651    assert( pParse->db!=0 );
115652    db = pParse->db;
115653    if( pList==0 ){
115654      pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
115655      if( pList==0 ) return 0;
115656      pList->nAlloc = 1;
115657      pList->nSrc = 1;
115658      memset(&pList->a[0], 0, sizeof(pList->a[0]));
115659      pList->a[0].iCursor = -1;
115660    }else{
115661      SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
115662      if( pNew==0 ){
115663        sqlite3SrcListDelete(db, pList);
115664        return 0;
115665      }else{
115666        pList = pNew;
115667      }
115668    }
115669    pItem = &pList->a[pList->nSrc-1];
115670    if( pDatabase && pDatabase->z==0 ){
115671      pDatabase = 0;
115672    }
115673    if( pDatabase ){
115674      pItem->zName = sqlite3NameFromToken(db, pDatabase);
115675      pItem->zDatabase = sqlite3NameFromToken(db, pTable);
115676    }else{
115677      pItem->zName = sqlite3NameFromToken(db, pTable);
115678      pItem->zDatabase = 0;
115679    }
115680    return pList;
115681  }
115682  
115683  /*
115684  ** Assign VdbeCursor index numbers to all tables in a SrcList
115685  */
115686  SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
115687    int i;
115688    struct SrcList_item *pItem;
115689    assert(pList || pParse->db->mallocFailed );
115690    if( pList ){
115691      for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
115692        if( pItem->iCursor>=0 ) break;
115693        pItem->iCursor = pParse->nTab++;
115694        if( pItem->pSelect ){
115695          sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
115696        }
115697      }
115698    }
115699  }
115700  
115701  /*
115702  ** Delete an entire SrcList including all its substructure.
115703  */
115704  SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
115705    int i;
115706    struct SrcList_item *pItem;
115707    if( pList==0 ) return;
115708    for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
115709      sqlite3DbFree(db, pItem->zDatabase);
115710      sqlite3DbFree(db, pItem->zName);
115711      sqlite3DbFree(db, pItem->zAlias);
115712      if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
115713      if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
115714      sqlite3DeleteTable(db, pItem->pTab);
115715      sqlite3SelectDelete(db, pItem->pSelect);
115716      sqlite3ExprDelete(db, pItem->pOn);
115717      sqlite3IdListDelete(db, pItem->pUsing);
115718    }
115719    sqlite3DbFreeNN(db, pList);
115720  }
115721  
115722  /*
115723  ** This routine is called by the parser to add a new term to the
115724  ** end of a growing FROM clause.  The "p" parameter is the part of
115725  ** the FROM clause that has already been constructed.  "p" is NULL
115726  ** if this is the first term of the FROM clause.  pTable and pDatabase
115727  ** are the name of the table and database named in the FROM clause term.
115728  ** pDatabase is NULL if the database name qualifier is missing - the
115729  ** usual case.  If the term has an alias, then pAlias points to the
115730  ** alias token.  If the term is a subquery, then pSubquery is the
115731  ** SELECT statement that the subquery encodes.  The pTable and
115732  ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
115733  ** parameters are the content of the ON and USING clauses.
115734  **
115735  ** Return a new SrcList which encodes is the FROM with the new
115736  ** term added.
115737  */
115738  SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
115739    Parse *pParse,          /* Parsing context */
115740    SrcList *p,             /* The left part of the FROM clause already seen */
115741    Token *pTable,          /* Name of the table to add to the FROM clause */
115742    Token *pDatabase,       /* Name of the database containing pTable */
115743    Token *pAlias,          /* The right-hand side of the AS subexpression */
115744    Select *pSubquery,      /* A subquery used in place of a table name */
115745    Expr *pOn,              /* The ON clause of a join */
115746    IdList *pUsing          /* The USING clause of a join */
115747  ){
115748    struct SrcList_item *pItem;
115749    sqlite3 *db = pParse->db;
115750    if( !p && (pOn || pUsing) ){
115751      sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
115752        (pOn ? "ON" : "USING")
115753      );
115754      goto append_from_error;
115755    }
115756    p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
115757    if( p==0 ){
115758      goto append_from_error;
115759    }
115760    assert( p->nSrc>0 );
115761    pItem = &p->a[p->nSrc-1];
115762    assert( (pTable==0)==(pDatabase==0) );
115763    assert( pItem->zName==0 || pDatabase!=0 );
115764    if( IN_RENAME_OBJECT && pItem->zName ){
115765      Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
115766      sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
115767    }
115768    assert( pAlias!=0 );
115769    if( pAlias->n ){
115770      pItem->zAlias = sqlite3NameFromToken(db, pAlias);
115771    }
115772    pItem->pSelect = pSubquery;
115773    pItem->pOn = pOn;
115774    pItem->pUsing = pUsing;
115775    return p;
115776  
115777   append_from_error:
115778    assert( p==0 );
115779    sqlite3ExprDelete(db, pOn);
115780    sqlite3IdListDelete(db, pUsing);
115781    sqlite3SelectDelete(db, pSubquery);
115782    return 0;
115783  }
115784  
115785  /*
115786  ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
115787  ** element of the source-list passed as the second argument.
115788  */
115789  SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
115790    assert( pIndexedBy!=0 );
115791    if( p && pIndexedBy->n>0 ){
115792      struct SrcList_item *pItem;
115793      assert( p->nSrc>0 );
115794      pItem = &p->a[p->nSrc-1];
115795      assert( pItem->fg.notIndexed==0 );
115796      assert( pItem->fg.isIndexedBy==0 );
115797      assert( pItem->fg.isTabFunc==0 );
115798      if( pIndexedBy->n==1 && !pIndexedBy->z ){
115799        /* A "NOT INDEXED" clause was supplied. See parse.y 
115800        ** construct "indexed_opt" for details. */
115801        pItem->fg.notIndexed = 1;
115802      }else{
115803        pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
115804        pItem->fg.isIndexedBy = 1;
115805      }
115806    }
115807  }
115808  
115809  /*
115810  ** Add the list of function arguments to the SrcList entry for a
115811  ** table-valued-function.
115812  */
115813  SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
115814    if( p ){
115815      struct SrcList_item *pItem = &p->a[p->nSrc-1];
115816      assert( pItem->fg.notIndexed==0 );
115817      assert( pItem->fg.isIndexedBy==0 );
115818      assert( pItem->fg.isTabFunc==0 );
115819      pItem->u1.pFuncArg = pList;
115820      pItem->fg.isTabFunc = 1;
115821    }else{
115822      sqlite3ExprListDelete(pParse->db, pList);
115823    }
115824  }
115825  
115826  /*
115827  ** When building up a FROM clause in the parser, the join operator
115828  ** is initially attached to the left operand.  But the code generator
115829  ** expects the join operator to be on the right operand.  This routine
115830  ** Shifts all join operators from left to right for an entire FROM
115831  ** clause.
115832  **
115833  ** Example: Suppose the join is like this:
115834  **
115835  **           A natural cross join B
115836  **
115837  ** The operator is "natural cross join".  The A and B operands are stored
115838  ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
115839  ** operator with A.  This routine shifts that operator over to B.
115840  */
115841  SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
115842    if( p ){
115843      int i;
115844      for(i=p->nSrc-1; i>0; i--){
115845        p->a[i].fg.jointype = p->a[i-1].fg.jointype;
115846      }
115847      p->a[0].fg.jointype = 0;
115848    }
115849  }
115850  
115851  /*
115852  ** Generate VDBE code for a BEGIN statement.
115853  */
115854  SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
115855    sqlite3 *db;
115856    Vdbe *v;
115857    int i;
115858  
115859    assert( pParse!=0 );
115860    db = pParse->db;
115861    assert( db!=0 );
115862    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
115863      return;
115864    }
115865    v = sqlite3GetVdbe(pParse);
115866    if( !v ) return;
115867    if( type!=TK_DEFERRED ){
115868      for(i=0; i<db->nDb; i++){
115869        sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
115870        sqlite3VdbeUsesBtree(v, i);
115871      }
115872    }
115873    sqlite3VdbeAddOp0(v, OP_AutoCommit);
115874  }
115875  
115876  /*
115877  ** Generate VDBE code for a COMMIT or ROLLBACK statement.
115878  ** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
115879  ** code is generated for a COMMIT.
115880  */
115881  SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
115882    Vdbe *v;
115883    int isRollback;
115884  
115885    assert( pParse!=0 );
115886    assert( pParse->db!=0 );
115887    assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
115888    isRollback = eType==TK_ROLLBACK;
115889    if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 
115890         isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
115891      return;
115892    }
115893    v = sqlite3GetVdbe(pParse);
115894    if( v ){
115895      sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
115896    }
115897  }
115898  
115899  /*
115900  ** This function is called by the parser when it parses a command to create,
115901  ** release or rollback an SQL savepoint. 
115902  */
115903  SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
115904    char *zName = sqlite3NameFromToken(pParse->db, pName);
115905    if( zName ){
115906      Vdbe *v = sqlite3GetVdbe(pParse);
115907  #ifndef SQLITE_OMIT_AUTHORIZATION
115908      static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
115909      assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
115910  #endif
115911      if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
115912        sqlite3DbFree(pParse->db, zName);
115913        return;
115914      }
115915      sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
115916    }
115917  }
115918  
115919  /*
115920  ** Make sure the TEMP database is open and available for use.  Return
115921  ** the number of errors.  Leave any error messages in the pParse structure.
115922  */
115923  SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
115924    sqlite3 *db = pParse->db;
115925    if( db->aDb[1].pBt==0 && !pParse->explain ){
115926      int rc;
115927      Btree *pBt;
115928      sqlite3_vfs *pVfs;
115929      static const int flags = 
115930            SQLITE_OPEN_READWRITE |
115931            SQLITE_OPEN_CREATE |
115932            SQLITE_OPEN_EXCLUSIVE |
115933            SQLITE_OPEN_DELETEONCLOSE |
115934            SQLITE_OPEN_TEMP_DB;
115935  
115936      if( strcmp(db->pVfs->zName,"null")==0 ){
115937        pVfs = sqlite3_vfs_find(NULL); /* returns the default VFS */
115938      } else {
115939        pVfs = db->pVfs;
115940      }
115941      rc = sqlite3BtreeOpen(pVfs, 0, db, &pBt, 0, flags);
115942      if( rc!=SQLITE_OK ){
115943        sqlite3ErrorMsg(pParse, "unable to open a temporary database "
115944          "file for storing temporary tables");
115945        pParse->rc = rc;
115946        return 1;
115947      }
115948      db->aDb[1].pBt = pBt;
115949      assert( db->aDb[1].pSchema );
115950      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
115951        sqlite3OomFault(db);
115952        return 1;
115953      }
115954    }
115955    return 0;
115956  }
115957  
115958  /*
115959  ** Record the fact that the schema cookie will need to be verified
115960  ** for database iDb.  The code to actually verify the schema cookie
115961  ** will occur at the end of the top-level VDBE and will be generated
115962  ** later, by sqlite3FinishCoding().
115963  */
115964  SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
115965    Parse *pToplevel = sqlite3ParseToplevel(pParse);
115966  
115967    assert( iDb>=0 && iDb<pParse->db->nDb );
115968    assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
115969    assert( iDb<SQLITE_MAX_ATTACHED+2 );
115970    assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
115971    if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
115972      DbMaskSet(pToplevel->cookieMask, iDb);
115973      if( !OMIT_TEMPDB && iDb==1 ){
115974        sqlite3OpenTempDatabase(pToplevel);
115975      }
115976    }
115977  }
115978  
115979  /*
115980  ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
115981  ** attached database. Otherwise, invoke it for the database named zDb only.
115982  */
115983  SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
115984    sqlite3 *db = pParse->db;
115985    int i;
115986    for(i=0; i<db->nDb; i++){
115987      Db *pDb = &db->aDb[i];
115988      if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
115989        sqlite3CodeVerifySchema(pParse, i);
115990      }
115991    }
115992  }
115993  
115994  /*
115995  ** Generate VDBE code that prepares for doing an operation that
115996  ** might change the database.
115997  **
115998  ** This routine starts a new transaction if we are not already within
115999  ** a transaction.  If we are already within a transaction, then a checkpoint
116000  ** is set if the setStatement parameter is true.  A checkpoint should
116001  ** be set for operations that might fail (due to a constraint) part of
116002  ** the way through and which will need to undo some writes without having to
116003  ** rollback the whole transaction.  For operations where all constraints
116004  ** can be checked before any changes are made to the database, it is never
116005  ** necessary to undo a write and the checkpoint should not be set.
116006  */
116007  SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
116008    Parse *pToplevel = sqlite3ParseToplevel(pParse);
116009    sqlite3CodeVerifySchema(pParse, iDb);
116010    DbMaskSet(pToplevel->writeMask, iDb);
116011    pToplevel->isMultiWrite |= setStatement;
116012  }
116013  
116014  /*
116015  ** Indicate that the statement currently under construction might write
116016  ** more than one entry (example: deleting one row then inserting another,
116017  ** inserting multiple rows in a table, or inserting a row and index entries.)
116018  ** If an abort occurs after some of these writes have completed, then it will
116019  ** be necessary to undo the completed writes.
116020  */
116021  SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
116022    Parse *pToplevel = sqlite3ParseToplevel(pParse);
116023    pToplevel->isMultiWrite = 1;
116024  }
116025  
116026  /* 
116027  ** The code generator calls this routine if is discovers that it is
116028  ** possible to abort a statement prior to completion.  In order to 
116029  ** perform this abort without corrupting the database, we need to make
116030  ** sure that the statement is protected by a statement transaction.
116031  **
116032  ** Technically, we only need to set the mayAbort flag if the
116033  ** isMultiWrite flag was previously set.  There is a time dependency
116034  ** such that the abort must occur after the multiwrite.  This makes
116035  ** some statements involving the REPLACE conflict resolution algorithm
116036  ** go a little faster.  But taking advantage of this time dependency
116037  ** makes it more difficult to prove that the code is correct (in 
116038  ** particular, it prevents us from writing an effective
116039  ** implementation of sqlite3AssertMayAbort()) and so we have chosen
116040  ** to take the safe route and skip the optimization.
116041  */
116042  SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
116043    Parse *pToplevel = sqlite3ParseToplevel(pParse);
116044    pToplevel->mayAbort = 1;
116045  }
116046  
116047  /*
116048  ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
116049  ** error. The onError parameter determines which (if any) of the statement
116050  ** and/or current transaction is rolled back.
116051  */
116052  SQLITE_PRIVATE void sqlite3HaltConstraint(
116053    Parse *pParse,    /* Parsing context */
116054    int errCode,      /* extended error code */
116055    int onError,      /* Constraint type */
116056    char *p4,         /* Error message */
116057    i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
116058    u8 p5Errmsg       /* P5_ErrMsg type */
116059  ){
116060    Vdbe *v = sqlite3GetVdbe(pParse);
116061    assert( (errCode&0xff)==SQLITE_CONSTRAINT );
116062    if( onError==OE_Abort ){
116063      sqlite3MayAbort(pParse);
116064    }
116065    sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
116066    sqlite3VdbeChangeP5(v, p5Errmsg);
116067  }
116068  
116069  /*
116070  ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
116071  */
116072  SQLITE_PRIVATE void sqlite3UniqueConstraint(
116073    Parse *pParse,    /* Parsing context */
116074    int onError,      /* Constraint type */
116075    Index *pIdx       /* The index that triggers the constraint */
116076  ){
116077    char *zErr;
116078    int j;
116079    StrAccum errMsg;
116080    Table *pTab = pIdx->pTable;
116081  
116082    sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
116083    if( pIdx->aColExpr ){
116084      sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
116085    }else{
116086      for(j=0; j<pIdx->nKeyCol; j++){
116087        char *zCol;
116088        assert( pIdx->aiColumn[j]>=0 );
116089        zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
116090        if( j ) sqlite3_str_append(&errMsg, ", ", 2);
116091        sqlite3_str_appendall(&errMsg, pTab->zName);
116092        sqlite3_str_append(&errMsg, ".", 1);
116093        sqlite3_str_appendall(&errMsg, zCol);
116094      }
116095    }
116096    zErr = sqlite3StrAccumFinish(&errMsg);
116097    sqlite3HaltConstraint(pParse, 
116098      IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
116099                              : SQLITE_CONSTRAINT_UNIQUE,
116100      onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
116101  }
116102  
116103  
116104  /*
116105  ** Code an OP_Halt due to non-unique rowid.
116106  */
116107  SQLITE_PRIVATE void sqlite3RowidConstraint(
116108    Parse *pParse,    /* Parsing context */
116109    int onError,      /* Conflict resolution algorithm */
116110    Table *pTab       /* The table with the non-unique rowid */ 
116111  ){
116112    char *zMsg;
116113    int rc;
116114    if( pTab->iPKey>=0 ){
116115      zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
116116                            pTab->aCol[pTab->iPKey].zName);
116117      rc = SQLITE_CONSTRAINT_PRIMARYKEY;
116118    }else{
116119      zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
116120      rc = SQLITE_CONSTRAINT_ROWID;
116121    }
116122    sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
116123                          P5_ConstraintUnique);
116124  }
116125  
116126  /*
116127  ** Check to see if pIndex uses the collating sequence pColl.  Return
116128  ** true if it does and false if it does not.
116129  */
116130  #ifndef SQLITE_OMIT_REINDEX
116131  static int collationMatch(const char *zColl, Index *pIndex){
116132    int i;
116133    assert( zColl!=0 );
116134    for(i=0; i<pIndex->nColumn; i++){
116135      const char *z = pIndex->azColl[i];
116136      assert( z!=0 || pIndex->aiColumn[i]<0 );
116137      if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
116138        return 1;
116139      }
116140    }
116141    return 0;
116142  }
116143  #endif
116144  
116145  /*
116146  ** Recompute all indices of pTab that use the collating sequence pColl.
116147  ** If pColl==0 then recompute all indices of pTab.
116148  */
116149  #ifndef SQLITE_OMIT_REINDEX
116150  static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
116151    if( !IsVirtual(pTab) ){
116152      Index *pIndex;              /* An index associated with pTab */
116153  
116154      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
116155        if( zColl==0 || collationMatch(zColl, pIndex) ){
116156          int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
116157          sqlite3BeginWriteOperation(pParse, 0, iDb);
116158          sqlite3RefillIndex(pParse, pIndex, -1);
116159        }
116160      }
116161    }
116162  }
116163  #endif
116164  
116165  /*
116166  ** Recompute all indices of all tables in all databases where the
116167  ** indices use the collating sequence pColl.  If pColl==0 then recompute
116168  ** all indices everywhere.
116169  */
116170  #ifndef SQLITE_OMIT_REINDEX
116171  static void reindexDatabases(Parse *pParse, char const *zColl){
116172    Db *pDb;                    /* A single database */
116173    int iDb;                    /* The database index number */
116174    sqlite3 *db = pParse->db;   /* The database connection */
116175    HashElem *k;                /* For looping over tables in pDb */
116176    Table *pTab;                /* A table in the database */
116177  
116178    assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
116179    for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
116180      assert( pDb!=0 );
116181      for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
116182        pTab = (Table*)sqliteHashData(k);
116183        reindexTable(pParse, pTab, zColl);
116184      }
116185    }
116186  }
116187  #endif
116188  
116189  /*
116190  ** Generate code for the REINDEX command.
116191  **
116192  **        REINDEX                            -- 1
116193  **        REINDEX  <collation>               -- 2
116194  **        REINDEX  ?<database>.?<tablename>  -- 3
116195  **        REINDEX  ?<database>.?<indexname>  -- 4
116196  **
116197  ** Form 1 causes all indices in all attached databases to be rebuilt.
116198  ** Form 2 rebuilds all indices in all databases that use the named
116199  ** collating function.  Forms 3 and 4 rebuild the named index or all
116200  ** indices associated with the named table.
116201  */
116202  #ifndef SQLITE_OMIT_REINDEX
116203  SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
116204    CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
116205    char *z;                    /* Name of a table or index */
116206    const char *zDb;            /* Name of the database */
116207    Table *pTab;                /* A table in the database */
116208    Index *pIndex;              /* An index associated with pTab */
116209    int iDb;                    /* The database index number */
116210    sqlite3 *db = pParse->db;   /* The database connection */
116211    Token *pObjName;            /* Name of the table or index to be reindexed */
116212  
116213    /* Read the database schema. If an error occurs, leave an error message
116214    ** and code in pParse and return NULL. */
116215    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
116216      return;
116217    }
116218  
116219    if( pName1==0 ){
116220      reindexDatabases(pParse, 0);
116221      return;
116222    }else if( NEVER(pName2==0) || pName2->z==0 ){
116223      char *zColl;
116224      assert( pName1->z );
116225      zColl = sqlite3NameFromToken(pParse->db, pName1);
116226      if( !zColl ) return;
116227      pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
116228      if( pColl ){
116229        reindexDatabases(pParse, zColl);
116230        sqlite3DbFree(db, zColl);
116231        return;
116232      }
116233      sqlite3DbFree(db, zColl);
116234    }
116235    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
116236    if( iDb<0 ) return;
116237    z = sqlite3NameFromToken(db, pObjName);
116238    if( z==0 ) return;
116239    zDb = db->aDb[iDb].zDbSName;
116240    pTab = sqlite3FindTable(db, z, zDb);
116241    if( pTab ){
116242      reindexTable(pParse, pTab, 0);
116243      sqlite3DbFree(db, z);
116244      return;
116245    }
116246    pIndex = sqlite3FindIndex(db, z, zDb);
116247    sqlite3DbFree(db, z);
116248    if( pIndex ){
116249      sqlite3BeginWriteOperation(pParse, 0, iDb);
116250      sqlite3RefillIndex(pParse, pIndex, -1);
116251      return;
116252    }
116253    sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
116254  }
116255  #endif
116256  
116257  /*
116258  ** Return a KeyInfo structure that is appropriate for the given Index.
116259  **
116260  ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
116261  ** when it has finished using it.
116262  */
116263  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
116264    int i;
116265    int nCol = pIdx->nColumn;
116266    int nKey = pIdx->nKeyCol;
116267    KeyInfo *pKey;
116268    if( pParse->nErr ) return 0;
116269    if( pIdx->uniqNotNull ){
116270      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
116271    }else{
116272      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
116273    }
116274    if( pKey ){
116275      assert( sqlite3KeyInfoIsWriteable(pKey) );
116276      for(i=0; i<nCol; i++){
116277        const char *zColl = pIdx->azColl[i];
116278        pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
116279                          sqlite3LocateCollSeq(pParse, zColl);
116280        pKey->aSortOrder[i] = pIdx->aSortOrder[i];
116281      }
116282      if( pParse->nErr ){
116283        assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
116284        if( pIdx->bNoQuery==0 ){
116285          /* Deactivate the index because it contains an unknown collating
116286          ** sequence.  The only way to reactive the index is to reload the
116287          ** schema.  Adding the missing collating sequence later does not
116288          ** reactive the index.  The application had the chance to register
116289          ** the missing index using the collation-needed callback.  For
116290          ** simplicity, SQLite will not give the application a second chance.
116291          */
116292          pIdx->bNoQuery = 1;
116293          pParse->rc = SQLITE_ERROR_RETRY;
116294        }
116295        sqlite3KeyInfoUnref(pKey);
116296        pKey = 0;
116297      }
116298    }
116299    return pKey;
116300  }
116301  
116302  #ifndef SQLITE_OMIT_CTE
116303  /* 
116304  ** This routine is invoked once per CTE by the parser while parsing a 
116305  ** WITH clause. 
116306  */
116307  SQLITE_PRIVATE With *sqlite3WithAdd(
116308    Parse *pParse,          /* Parsing context */
116309    With *pWith,            /* Existing WITH clause, or NULL */
116310    Token *pName,           /* Name of the common-table */
116311    ExprList *pArglist,     /* Optional column name list for the table */
116312    Select *pQuery          /* Query used to initialize the table */
116313  ){
116314    sqlite3 *db = pParse->db;
116315    With *pNew;
116316    char *zName;
116317  
116318    /* Check that the CTE name is unique within this WITH clause. If
116319    ** not, store an error in the Parse structure. */
116320    zName = sqlite3NameFromToken(pParse->db, pName);
116321    if( zName && pWith ){
116322      int i;
116323      for(i=0; i<pWith->nCte; i++){
116324        if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
116325          sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
116326        }
116327      }
116328    }
116329  
116330    if( pWith ){
116331      int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
116332      pNew = sqlite3DbRealloc(db, pWith, nByte);
116333    }else{
116334      pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
116335    }
116336    assert( (pNew!=0 && zName!=0) || db->mallocFailed );
116337  
116338    if( db->mallocFailed ){
116339      sqlite3ExprListDelete(db, pArglist);
116340      sqlite3SelectDelete(db, pQuery);
116341      sqlite3DbFree(db, zName);
116342      pNew = pWith;
116343    }else{
116344      pNew->a[pNew->nCte].pSelect = pQuery;
116345      pNew->a[pNew->nCte].pCols = pArglist;
116346      pNew->a[pNew->nCte].zName = zName;
116347      pNew->a[pNew->nCte].zCteErr = 0;
116348      pNew->nCte++;
116349    }
116350  
116351    return pNew;
116352  }
116353  
116354  /*
116355  ** Free the contents of the With object passed as the second argument.
116356  */
116357  SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
116358    if( pWith ){
116359      int i;
116360      for(i=0; i<pWith->nCte; i++){
116361        struct Cte *pCte = &pWith->a[i];
116362        sqlite3ExprListDelete(db, pCte->pCols);
116363        sqlite3SelectDelete(db, pCte->pSelect);
116364        sqlite3DbFree(db, pCte->zName);
116365      }
116366      sqlite3DbFree(db, pWith);
116367    }
116368  }
116369  #endif /* !defined(SQLITE_OMIT_CTE) */
116370  
116371  /************** End of build.c ***********************************************/
116372  /************** Begin file callback.c ****************************************/
116373  /*
116374  ** 2005 May 23 
116375  **
116376  ** The author disclaims copyright to this source code.  In place of
116377  ** a legal notice, here is a blessing:
116378  **
116379  **    May you do good and not evil.
116380  **    May you find forgiveness for yourself and forgive others.
116381  **    May you share freely, never taking more than you give.
116382  **
116383  *************************************************************************
116384  **
116385  ** This file contains functions used to access the internal hash tables
116386  ** of user defined functions and collation sequences.
116387  */
116388  
116389  /* #include "sqliteInt.h" */
116390  
116391  /*
116392  ** Invoke the 'collation needed' callback to request a collation sequence
116393  ** in the encoding enc of name zName, length nName.
116394  */
116395  static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
116396    assert( !db->xCollNeeded || !db->xCollNeeded16 );
116397    if( db->xCollNeeded ){
116398      char *zExternal = sqlite3DbStrDup(db, zName);
116399      if( !zExternal ) return;
116400      db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
116401      sqlite3DbFree(db, zExternal);
116402    }
116403  #ifndef SQLITE_OMIT_UTF16
116404    if( db->xCollNeeded16 ){
116405      char const *zExternal;
116406      sqlite3_value *pTmp = sqlite3ValueNew(db);
116407      sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
116408      zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
116409      if( zExternal ){
116410        db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
116411      }
116412      sqlite3ValueFree(pTmp);
116413    }
116414  #endif
116415  }
116416  
116417  /*
116418  ** This routine is called if the collation factory fails to deliver a
116419  ** collation function in the best encoding but there may be other versions
116420  ** of this collation function (for other text encodings) available. Use one
116421  ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
116422  ** possible.
116423  */
116424  static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
116425    CollSeq *pColl2;
116426    char *z = pColl->zName;
116427    int i;
116428    static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
116429    for(i=0; i<3; i++){
116430      pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
116431      if( pColl2->xCmp!=0 ){
116432        memcpy(pColl, pColl2, sizeof(CollSeq));
116433        pColl->xDel = 0;         /* Do not copy the destructor */
116434        return SQLITE_OK;
116435      }
116436    }
116437    return SQLITE_ERROR;
116438  }
116439  
116440  /*
116441  ** This function is responsible for invoking the collation factory callback
116442  ** or substituting a collation sequence of a different encoding when the
116443  ** requested collation sequence is not available in the desired encoding.
116444  ** 
116445  ** If it is not NULL, then pColl must point to the database native encoding 
116446  ** collation sequence with name zName, length nName.
116447  **
116448  ** The return value is either the collation sequence to be used in database
116449  ** db for collation type name zName, length nName, or NULL, if no collation
116450  ** sequence can be found.  If no collation is found, leave an error message.
116451  **
116452  ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
116453  */
116454  SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
116455    Parse *pParse,        /* Parsing context */
116456    u8 enc,               /* The desired encoding for the collating sequence */
116457    CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
116458    const char *zName     /* Collating sequence name */
116459  ){
116460    CollSeq *p;
116461    sqlite3 *db = pParse->db;
116462  
116463    p = pColl;
116464    if( !p ){
116465      p = sqlite3FindCollSeq(db, enc, zName, 0);
116466    }
116467    if( !p || !p->xCmp ){
116468      /* No collation sequence of this type for this encoding is registered.
116469      ** Call the collation factory to see if it can supply us with one.
116470      */
116471      callCollNeeded(db, enc, zName);
116472      p = sqlite3FindCollSeq(db, enc, zName, 0);
116473    }
116474    if( p && !p->xCmp && synthCollSeq(db, p) ){
116475      p = 0;
116476    }
116477    assert( !p || p->xCmp );
116478    if( p==0 ){
116479      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
116480      pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
116481    }
116482    return p;
116483  }
116484  
116485  /*
116486  ** This routine is called on a collation sequence before it is used to
116487  ** check that it is defined. An undefined collation sequence exists when
116488  ** a database is loaded that contains references to collation sequences
116489  ** that have not been defined by sqlite3_create_collation() etc.
116490  **
116491  ** If required, this routine calls the 'collation needed' callback to
116492  ** request a definition of the collating sequence. If this doesn't work, 
116493  ** an equivalent collating sequence that uses a text encoding different
116494  ** from the main database is substituted, if one is available.
116495  */
116496  SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
116497    if( pColl && pColl->xCmp==0 ){
116498      const char *zName = pColl->zName;
116499      sqlite3 *db = pParse->db;
116500      CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
116501      if( !p ){
116502        return SQLITE_ERROR;
116503      }
116504      assert( p==pColl );
116505    }
116506    return SQLITE_OK;
116507  }
116508  
116509  
116510  
116511  /*
116512  ** Locate and return an entry from the db.aCollSeq hash table. If the entry
116513  ** specified by zName and nName is not found and parameter 'create' is
116514  ** true, then create a new entry. Otherwise return NULL.
116515  **
116516  ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
116517  ** array of three CollSeq structures. The first is the collation sequence
116518  ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
116519  **
116520  ** Stored immediately after the three collation sequences is a copy of
116521  ** the collation sequence name. A pointer to this string is stored in
116522  ** each collation sequence structure.
116523  */
116524  static CollSeq *findCollSeqEntry(
116525    sqlite3 *db,          /* Database connection */
116526    const char *zName,    /* Name of the collating sequence */
116527    int create            /* Create a new entry if true */
116528  ){
116529    CollSeq *pColl;
116530    pColl = sqlite3HashFind(&db->aCollSeq, zName);
116531  
116532    if( 0==pColl && create ){
116533      int nName = sqlite3Strlen30(zName) + 1;
116534      pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
116535      if( pColl ){
116536        CollSeq *pDel = 0;
116537        pColl[0].zName = (char*)&pColl[3];
116538        pColl[0].enc = SQLITE_UTF8;
116539        pColl[1].zName = (char*)&pColl[3];
116540        pColl[1].enc = SQLITE_UTF16LE;
116541        pColl[2].zName = (char*)&pColl[3];
116542        pColl[2].enc = SQLITE_UTF16BE;
116543        memcpy(pColl[0].zName, zName, nName);
116544        pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
116545  
116546        /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
116547        ** return the pColl pointer to be deleted (because it wasn't added
116548        ** to the hash table).
116549        */
116550        assert( pDel==0 || pDel==pColl );
116551        if( pDel!=0 ){
116552          sqlite3OomFault(db);
116553          sqlite3DbFree(db, pDel);
116554          pColl = 0;
116555        }
116556      }
116557    }
116558    return pColl;
116559  }
116560  
116561  /*
116562  ** Parameter zName points to a UTF-8 encoded string nName bytes long.
116563  ** Return the CollSeq* pointer for the collation sequence named zName
116564  ** for the encoding 'enc' from the database 'db'.
116565  **
116566  ** If the entry specified is not found and 'create' is true, then create a
116567  ** new entry.  Otherwise return NULL.
116568  **
116569  ** A separate function sqlite3LocateCollSeq() is a wrapper around
116570  ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
116571  ** if necessary and generates an error message if the collating sequence
116572  ** cannot be found.
116573  **
116574  ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
116575  */
116576  SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
116577    sqlite3 *db,
116578    u8 enc,
116579    const char *zName,
116580    int create
116581  ){
116582    CollSeq *pColl;
116583    if( zName ){
116584      pColl = findCollSeqEntry(db, zName, create);
116585    }else{
116586      pColl = db->pDfltColl;
116587    }
116588    assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
116589    assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
116590    if( pColl ) pColl += enc-1;
116591    return pColl;
116592  }
116593  
116594  /* During the search for the best function definition, this procedure
116595  ** is called to test how well the function passed as the first argument
116596  ** matches the request for a function with nArg arguments in a system
116597  ** that uses encoding enc. The value returned indicates how well the
116598  ** request is matched. A higher value indicates a better match.
116599  **
116600  ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
116601  ** is also -1.  In other words, we are searching for a function that
116602  ** takes a variable number of arguments.
116603  **
116604  ** If nArg is -2 that means that we are searching for any function 
116605  ** regardless of the number of arguments it uses, so return a positive
116606  ** match score for any
116607  **
116608  ** The returned value is always between 0 and 6, as follows:
116609  **
116610  ** 0: Not a match.
116611  ** 1: UTF8/16 conversion required and function takes any number of arguments.
116612  ** 2: UTF16 byte order change required and function takes any number of args.
116613  ** 3: encoding matches and function takes any number of arguments
116614  ** 4: UTF8/16 conversion required - argument count matches exactly
116615  ** 5: UTF16 byte order conversion required - argument count matches exactly
116616  ** 6: Perfect match:  encoding and argument count match exactly.
116617  **
116618  ** If nArg==(-2) then any function with a non-null xSFunc is
116619  ** a perfect match and any function with xSFunc NULL is
116620  ** a non-match.
116621  */
116622  #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
116623  static int matchQuality(
116624    FuncDef *p,     /* The function we are evaluating for match quality */
116625    int nArg,       /* Desired number of arguments.  (-1)==any */
116626    u8 enc          /* Desired text encoding */
116627  ){
116628    int match;
116629  
116630    /* nArg of -2 is a special case */
116631    if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
116632  
116633    /* Wrong number of arguments means "no match" */
116634    if( p->nArg!=nArg && p->nArg>=0 ) return 0;
116635  
116636    /* Give a better score to a function with a specific number of arguments
116637    ** than to function that accepts any number of arguments. */
116638    if( p->nArg==nArg ){
116639      match = 4;
116640    }else{
116641      match = 1;
116642    }
116643  
116644    /* Bonus points if the text encoding matches */
116645    if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
116646      match += 2;  /* Exact encoding match */
116647    }else if( (enc & p->funcFlags & 2)!=0 ){
116648      match += 1;  /* Both are UTF16, but with different byte orders */
116649    }
116650  
116651    return match;
116652  }
116653  
116654  /*
116655  ** Search a FuncDefHash for a function with the given name.  Return
116656  ** a pointer to the matching FuncDef if found, or 0 if there is no match.
116657  */
116658  SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
116659    int h,               /* Hash of the name */
116660    const char *zFunc    /* Name of function */
116661  ){
116662    FuncDef *p;
116663    for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
116664      if( sqlite3StrICmp(p->zName, zFunc)==0 ){
116665        return p;
116666      }
116667    }
116668    return 0;
116669  }
116670  
116671  /*
116672  ** Insert a new FuncDef into a FuncDefHash hash table.
116673  */
116674  SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
116675    FuncDef *aDef,      /* List of global functions to be inserted */
116676    int nDef            /* Length of the apDef[] list */
116677  ){
116678    int i;
116679    for(i=0; i<nDef; i++){
116680      FuncDef *pOther;
116681      const char *zName = aDef[i].zName;
116682      int nName = sqlite3Strlen30(zName);
116683      int h = SQLITE_FUNC_HASH(zName[0], nName);
116684      assert( zName[0]>='a' && zName[0]<='z' );
116685      pOther = sqlite3FunctionSearch(h, zName);
116686      if( pOther ){
116687        assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
116688        aDef[i].pNext = pOther->pNext;
116689        pOther->pNext = &aDef[i];
116690      }else{
116691        aDef[i].pNext = 0;
116692        aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
116693        sqlite3BuiltinFunctions.a[h] = &aDef[i];
116694      }
116695    }
116696  }
116697    
116698    
116699  
116700  /*
116701  ** Locate a user function given a name, a number of arguments and a flag
116702  ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
116703  ** pointer to the FuncDef structure that defines that function, or return
116704  ** NULL if the function does not exist.
116705  **
116706  ** If the createFlag argument is true, then a new (blank) FuncDef
116707  ** structure is created and liked into the "db" structure if a
116708  ** no matching function previously existed.
116709  **
116710  ** If nArg is -2, then the first valid function found is returned.  A
116711  ** function is valid if xSFunc is non-zero.  The nArg==(-2)
116712  ** case is used to see if zName is a valid function name for some number
116713  ** of arguments.  If nArg is -2, then createFlag must be 0.
116714  **
116715  ** If createFlag is false, then a function with the required name and
116716  ** number of arguments may be returned even if the eTextRep flag does not
116717  ** match that requested.
116718  */
116719  SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
116720    sqlite3 *db,       /* An open database */
116721    const char *zName, /* Name of the function.  zero-terminated */
116722    int nArg,          /* Number of arguments.  -1 means any number */
116723    u8 enc,            /* Preferred text encoding */
116724    u8 createFlag      /* Create new entry if true and does not otherwise exist */
116725  ){
116726    FuncDef *p;         /* Iterator variable */
116727    FuncDef *pBest = 0; /* Best match found so far */
116728    int bestScore = 0;  /* Score of best match */
116729    int h;              /* Hash value */
116730    int nName;          /* Length of the name */
116731  
116732    assert( nArg>=(-2) );
116733    assert( nArg>=(-1) || createFlag==0 );
116734    nName = sqlite3Strlen30(zName);
116735  
116736    /* First search for a match amongst the application-defined functions.
116737    */
116738    p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
116739    while( p ){
116740      int score = matchQuality(p, nArg, enc);
116741      if( score>bestScore ){
116742        pBest = p;
116743        bestScore = score;
116744      }
116745      p = p->pNext;
116746    }
116747  
116748    /* If no match is found, search the built-in functions.
116749    **
116750    ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
116751    ** functions even if a prior app-defined function was found.  And give
116752    ** priority to built-in functions.
116753    **
116754    ** Except, if createFlag is true, that means that we are trying to
116755    ** install a new function.  Whatever FuncDef structure is returned it will
116756    ** have fields overwritten with new information appropriate for the
116757    ** new function.  But the FuncDefs for built-in functions are read-only.
116758    ** So we must not search for built-ins when creating a new function.
116759    */ 
116760    if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
116761      bestScore = 0;
116762      h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
116763      p = sqlite3FunctionSearch(h, zName);
116764      while( p ){
116765        int score = matchQuality(p, nArg, enc);
116766        if( score>bestScore ){
116767          pBest = p;
116768          bestScore = score;
116769        }
116770        p = p->pNext;
116771      }
116772    }
116773  
116774    /* If the createFlag parameter is true and the search did not reveal an
116775    ** exact match for the name, number of arguments and encoding, then add a
116776    ** new entry to the hash table and return it.
116777    */
116778    if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
116779        (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
116780      FuncDef *pOther;
116781      u8 *z;
116782      pBest->zName = (const char*)&pBest[1];
116783      pBest->nArg = (u16)nArg;
116784      pBest->funcFlags = enc;
116785      memcpy((char*)&pBest[1], zName, nName+1);
116786      for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
116787      pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
116788      if( pOther==pBest ){
116789        sqlite3DbFree(db, pBest);
116790        sqlite3OomFault(db);
116791        return 0;
116792      }else{
116793        pBest->pNext = pOther;
116794      }
116795    }
116796  
116797    if( pBest && (pBest->xSFunc || createFlag) ){
116798      return pBest;
116799    }
116800    return 0;
116801  }
116802  
116803  /*
116804  ** Free all resources held by the schema structure. The void* argument points
116805  ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
116806  ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
116807  ** of the schema hash tables).
116808  **
116809  ** The Schema.cache_size variable is not cleared.
116810  */
116811  SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
116812    Hash temp1;
116813    Hash temp2;
116814    HashElem *pElem;
116815    Schema *pSchema = (Schema *)p;
116816  
116817    temp1 = pSchema->tblHash;
116818    temp2 = pSchema->trigHash;
116819    sqlite3HashInit(&pSchema->trigHash);
116820    sqlite3HashClear(&pSchema->idxHash);
116821    for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
116822      sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
116823    }
116824    sqlite3HashClear(&temp2);
116825    sqlite3HashInit(&pSchema->tblHash);
116826    for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
116827      Table *pTab = sqliteHashData(pElem);
116828      sqlite3DeleteTable(0, pTab);
116829    }
116830    sqlite3HashClear(&temp1);
116831    sqlite3HashClear(&pSchema->fkeyHash);
116832    pSchema->pSeqTab = 0;
116833    if( pSchema->schemaFlags & DB_SchemaLoaded ){
116834      pSchema->iGeneration++;
116835    }
116836    pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
116837  }
116838  
116839  /*
116840  ** Find and return the schema associated with a BTree.  Create
116841  ** a new one if necessary.
116842  */
116843  SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
116844    Schema * p;
116845    if( pBt ){
116846      p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
116847    }else{
116848      p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
116849    }
116850    if( !p ){
116851      sqlite3OomFault(db);
116852    }else if ( 0==p->file_format ){
116853      sqlite3HashInit(&p->tblHash);
116854      sqlite3HashInit(&p->idxHash);
116855      sqlite3HashInit(&p->trigHash);
116856      sqlite3HashInit(&p->fkeyHash);
116857      p->enc = SQLITE_UTF8;
116858    }
116859    return p;
116860  }
116861  
116862  /************** End of callback.c ********************************************/
116863  /************** Begin file delete.c ******************************************/
116864  /*
116865  ** 2001 September 15
116866  **
116867  ** The author disclaims copyright to this source code.  In place of
116868  ** a legal notice, here is a blessing:
116869  **
116870  **    May you do good and not evil.
116871  **    May you find forgiveness for yourself and forgive others.
116872  **    May you share freely, never taking more than you give.
116873  **
116874  *************************************************************************
116875  ** This file contains C code routines that are called by the parser
116876  ** in order to generate code for DELETE FROM statements.
116877  */
116878  /* #include "sqliteInt.h" */
116879  
116880  /*
116881  ** While a SrcList can in general represent multiple tables and subqueries
116882  ** (as in the FROM clause of a SELECT statement) in this case it contains
116883  ** the name of a single table, as one might find in an INSERT, DELETE,
116884  ** or UPDATE statement.  Look up that table in the symbol table and
116885  ** return a pointer.  Set an error message and return NULL if the table 
116886  ** name is not found or if any other error occurs.
116887  **
116888  ** The following fields are initialized appropriate in pSrc:
116889  **
116890  **    pSrc->a[0].pTab       Pointer to the Table object
116891  **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
116892  **
116893  */
116894  SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
116895    struct SrcList_item *pItem = pSrc->a;
116896    Table *pTab;
116897    assert( pItem && pSrc->nSrc==1 );
116898    pTab = sqlite3LocateTableItem(pParse, 0, pItem);
116899    sqlite3DeleteTable(pParse->db, pItem->pTab);
116900    pItem->pTab = pTab;
116901    if( pTab ){
116902      pTab->nTabRef++;
116903    }
116904    if( sqlite3IndexedByLookup(pParse, pItem) ){
116905      pTab = 0;
116906    }
116907    return pTab;
116908  }
116909  
116910  /* Return true if table pTab is read-only.
116911  **
116912  ** A table is read-only if any of the following are true:
116913  **
116914  **   1) It is a virtual table and no implementation of the xUpdate method
116915  **      has been provided
116916  **
116917  **   2) It is a system table (i.e. sqlite_master), this call is not
116918  **      part of a nested parse and writable_schema pragma has not 
116919  **      been specified
116920  **
116921  **   3) The table is a shadow table, the database connection is in
116922  **      defensive mode, and the current sqlite3_prepare()
116923  **      is for a top-level SQL statement.
116924  */
116925  static int tabIsReadOnly(Parse *pParse, Table *pTab){
116926    sqlite3 *db;
116927    if( IsVirtual(pTab) ){
116928      return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
116929    }
116930    if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
116931    db = pParse->db;
116932    if( (pTab->tabFlags & TF_Readonly)!=0 ){
116933      return sqlite3WritableSchema(db)==0 && pParse->nested==0;
116934    }
116935    assert( pTab->tabFlags & TF_Shadow );
116936    return (db->flags & SQLITE_Defensive)!=0 
116937  #ifndef SQLITE_OMIT_VIRTUALTABLE
116938            && db->pVtabCtx==0
116939  #endif
116940            && db->nVdbeExec==0;
116941  }
116942  
116943  /*
116944  ** Check to make sure the given table is writable.  If it is not
116945  ** writable, generate an error message and return 1.  If it is
116946  ** writable return 0;
116947  */
116948  SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
116949    if( tabIsReadOnly(pParse, pTab) ){
116950      sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
116951      return 1;
116952    }
116953  #ifndef SQLITE_OMIT_VIEW
116954    if( !viewOk && pTab->pSelect ){
116955      sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
116956      return 1;
116957    }
116958  #endif
116959    return 0;
116960  }
116961  
116962  
116963  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
116964  /*
116965  ** Evaluate a view and store its result in an ephemeral table.  The
116966  ** pWhere argument is an optional WHERE clause that restricts the
116967  ** set of rows in the view that are to be added to the ephemeral table.
116968  */
116969  SQLITE_PRIVATE void sqlite3MaterializeView(
116970    Parse *pParse,       /* Parsing context */
116971    Table *pView,        /* View definition */
116972    Expr *pWhere,        /* Optional WHERE clause to be added */
116973    ExprList *pOrderBy,  /* Optional ORDER BY clause */
116974    Expr *pLimit,        /* Optional LIMIT clause */
116975    int iCur             /* Cursor number for ephemeral table */
116976  ){
116977    SelectDest dest;
116978    Select *pSel;
116979    SrcList *pFrom;
116980    sqlite3 *db = pParse->db;
116981    int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
116982    pWhere = sqlite3ExprDup(db, pWhere, 0);
116983    pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
116984    if( pFrom ){
116985      assert( pFrom->nSrc==1 );
116986      pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
116987      pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
116988      assert( pFrom->a[0].pOn==0 );
116989      assert( pFrom->a[0].pUsing==0 );
116990    }
116991    pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, 
116992                            SF_IncludeHidden, pLimit);
116993    sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
116994    sqlite3Select(pParse, pSel, &dest);
116995    sqlite3SelectDelete(db, pSel);
116996  }
116997  #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
116998  
116999  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
117000  /*
117001  ** Generate an expression tree to implement the WHERE, ORDER BY,
117002  ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
117003  **
117004  **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
117005  **                            \__________________________/
117006  **                               pLimitWhere (pInClause)
117007  */
117008  SQLITE_PRIVATE Expr *sqlite3LimitWhere(
117009    Parse *pParse,               /* The parser context */
117010    SrcList *pSrc,               /* the FROM clause -- which tables to scan */
117011    Expr *pWhere,                /* The WHERE clause.  May be null */
117012    ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
117013    Expr *pLimit,                /* The LIMIT clause.  May be null */
117014    char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
117015  ){
117016    sqlite3 *db = pParse->db;
117017    Expr *pLhs = NULL;           /* LHS of IN(SELECT...) operator */
117018    Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
117019    ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
117020    SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
117021    Select *pSelect = NULL;      /* Complete SELECT tree */
117022    Table *pTab;
117023  
117024    /* Check that there isn't an ORDER BY without a LIMIT clause.
117025    */
117026    if( pOrderBy && pLimit==0 ) {
117027      sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
117028      sqlite3ExprDelete(pParse->db, pWhere);
117029      sqlite3ExprListDelete(pParse->db, pOrderBy);
117030      return 0;
117031    }
117032  
117033    /* We only need to generate a select expression if there
117034    ** is a limit/offset term to enforce.
117035    */
117036    if( pLimit == 0 ) {
117037      return pWhere;
117038    }
117039  
117040    /* Generate a select expression tree to enforce the limit/offset 
117041    ** term for the DELETE or UPDATE statement.  For example:
117042    **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
117043    ** becomes:
117044    **   DELETE FROM table_a WHERE rowid IN ( 
117045    **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
117046    **   );
117047    */
117048  
117049    pTab = pSrc->a[0].pTab;
117050    if( HasRowid(pTab) ){
117051      pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
117052      pEList = sqlite3ExprListAppend(
117053          pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
117054      );
117055    }else{
117056      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117057      if( pPk->nKeyCol==1 ){
117058        const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
117059        pLhs = sqlite3Expr(db, TK_ID, zName);
117060        pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
117061      }else{
117062        int i;
117063        for(i=0; i<pPk->nKeyCol; i++){
117064          Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
117065          pEList = sqlite3ExprListAppend(pParse, pEList, p);
117066        }
117067        pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
117068        if( pLhs ){
117069          pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
117070        }
117071      }
117072    }
117073  
117074    /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
117075    ** and the SELECT subtree. */
117076    pSrc->a[0].pTab = 0;
117077    pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
117078    pSrc->a[0].pTab = pTab;
117079    pSrc->a[0].pIBIndex = 0;
117080  
117081    /* generate the SELECT expression tree. */
117082    pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, 
117083        pOrderBy,0,pLimit
117084    );
117085  
117086    /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
117087    pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
117088    sqlite3PExprAddSelect(pParse, pInClause, pSelect);
117089    return pInClause;
117090  }
117091  #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
117092         /*      && !defined(SQLITE_OMIT_SUBQUERY) */
117093  
117094  /*
117095  ** Generate code for a DELETE FROM statement.
117096  **
117097  **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
117098  **                 \________/       \________________/
117099  **                  pTabList              pWhere
117100  */
117101  SQLITE_PRIVATE void sqlite3DeleteFrom(
117102    Parse *pParse,         /* The parser context */
117103    SrcList *pTabList,     /* The table from which we should delete things */
117104    Expr *pWhere,          /* The WHERE clause.  May be null */
117105    ExprList *pOrderBy,    /* ORDER BY clause. May be null */
117106    Expr *pLimit           /* LIMIT clause. May be null */
117107  ){
117108    Vdbe *v;               /* The virtual database engine */
117109    Table *pTab;           /* The table from which records will be deleted */
117110    int i;                 /* Loop counter */
117111    WhereInfo *pWInfo;     /* Information about the WHERE clause */
117112    Index *pIdx;           /* For looping over indices of the table */
117113    int iTabCur;           /* Cursor number for the table */
117114    int iDataCur = 0;      /* VDBE cursor for the canonical data source */
117115    int iIdxCur = 0;       /* Cursor number of the first index */
117116    int nIdx;              /* Number of indices */
117117    sqlite3 *db;           /* Main database structure */
117118    AuthContext sContext;  /* Authorization context */
117119    NameContext sNC;       /* Name context to resolve expressions in */
117120    int iDb;               /* Database number */
117121    int memCnt = 0;        /* Memory cell used for change counting */
117122    int rcauth;            /* Value returned by authorization callback */
117123    int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
117124    int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
117125    u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
117126    Index *pPk;            /* The PRIMARY KEY index on the table */
117127    int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
117128    i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
117129    int iKey;              /* Memory cell holding key of row to be deleted */
117130    i16 nKey;              /* Number of memory cells in the row key */
117131    int iEphCur = 0;       /* Ephemeral table holding all primary key values */
117132    int iRowSet = 0;       /* Register for rowset of rows to delete */
117133    int addrBypass = 0;    /* Address of jump over the delete logic */
117134    int addrLoop = 0;      /* Top of the delete loop */
117135    int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
117136    int bComplex;          /* True if there are triggers or FKs or
117137                           ** subqueries in the WHERE clause */
117138   
117139  #ifndef SQLITE_OMIT_TRIGGER
117140    int isView;                  /* True if attempting to delete from a view */
117141    Trigger *pTrigger;           /* List of table triggers, if required */
117142  #endif
117143  
117144    memset(&sContext, 0, sizeof(sContext));
117145    db = pParse->db;
117146    if( pParse->nErr || db->mallocFailed ){
117147      goto delete_from_cleanup;
117148    }
117149    assert( pTabList->nSrc==1 );
117150  
117151  
117152    /* Locate the table which we want to delete.  This table has to be
117153    ** put in an SrcList structure because some of the subroutines we
117154    ** will be calling are designed to work with multiple tables and expect
117155    ** an SrcList* parameter instead of just a Table* parameter.
117156    */
117157    pTab = sqlite3SrcListLookup(pParse, pTabList);
117158    if( pTab==0 )  goto delete_from_cleanup;
117159  
117160    /* Figure out if we have any triggers and if the table being
117161    ** deleted from is a view
117162    */
117163  #ifndef SQLITE_OMIT_TRIGGER
117164    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
117165    isView = pTab->pSelect!=0;
117166  #else
117167  # define pTrigger 0
117168  # define isView 0
117169  #endif
117170    bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
117171  #ifdef SQLITE_OMIT_VIEW
117172  # undef isView
117173  # define isView 0
117174  #endif
117175  
117176  #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
117177    if( !isView ){
117178      pWhere = sqlite3LimitWhere(
117179          pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
117180      );
117181      pOrderBy = 0;
117182      pLimit = 0;
117183    }
117184  #endif
117185  
117186    /* If pTab is really a view, make sure it has been initialized.
117187    */
117188    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
117189      goto delete_from_cleanup;
117190    }
117191  
117192    if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
117193      goto delete_from_cleanup;
117194    }
117195    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117196    assert( iDb<db->nDb );
117197    rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, 
117198                              db->aDb[iDb].zDbSName);
117199    assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
117200    if( rcauth==SQLITE_DENY ){
117201      goto delete_from_cleanup;
117202    }
117203    assert(!isView || pTrigger);
117204  
117205    /* Assign cursor numbers to the table and all its indices.
117206    */
117207    assert( pTabList->nSrc==1 );
117208    iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
117209    for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
117210      pParse->nTab++;
117211    }
117212  
117213    /* Start the view context
117214    */
117215    if( isView ){
117216      sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
117217    }
117218  
117219    /* Begin generating code.
117220    */
117221    v = sqlite3GetVdbe(pParse);
117222    if( v==0 ){
117223      goto delete_from_cleanup;
117224    }
117225    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
117226    sqlite3BeginWriteOperation(pParse, bComplex, iDb);
117227  
117228    /* If we are trying to delete from a view, realize that view into
117229    ** an ephemeral table.
117230    */
117231  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
117232    if( isView ){
117233      sqlite3MaterializeView(pParse, pTab, 
117234          pWhere, pOrderBy, pLimit, iTabCur
117235      );
117236      iDataCur = iIdxCur = iTabCur;
117237      pOrderBy = 0;
117238      pLimit = 0;
117239    }
117240  #endif
117241  
117242    /* Resolve the column names in the WHERE clause.
117243    */
117244    memset(&sNC, 0, sizeof(sNC));
117245    sNC.pParse = pParse;
117246    sNC.pSrcList = pTabList;
117247    if( sqlite3ResolveExprNames(&sNC, pWhere) ){
117248      goto delete_from_cleanup;
117249    }
117250  
117251    /* Initialize the counter of the number of rows deleted, if
117252    ** we are counting rows.
117253    */
117254    if( (db->flags & SQLITE_CountRows)!=0
117255     && !pParse->nested
117256     && !pParse->pTriggerTab
117257    ){
117258      memCnt = ++pParse->nMem;
117259      sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
117260    }
117261  
117262  #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
117263    /* Special case: A DELETE without a WHERE clause deletes everything.
117264    ** It is easier just to erase the whole table. Prior to version 3.6.5,
117265    ** this optimization caused the row change count (the value returned by 
117266    ** API function sqlite3_count_changes) to be set incorrectly.
117267    **
117268    ** The "rcauth==SQLITE_OK" terms is the
117269    ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
117270    ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
117271    ** the truncate optimization is disabled and all rows are deleted
117272    ** individually.
117273    */
117274    if( rcauth==SQLITE_OK
117275     && pWhere==0
117276     && !bComplex
117277     && !IsVirtual(pTab)
117278  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
117279     && db->xPreUpdateCallback==0
117280  #endif
117281    ){
117282      assert( !isView );
117283      sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
117284      if( HasRowid(pTab) ){
117285        sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
117286                          pTab->zName, P4_STATIC);
117287      }
117288      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
117289        assert( pIdx->pSchema==pTab->pSchema );
117290        sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
117291      }
117292    }else
117293  #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
117294    {
117295      u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
117296      if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
117297      wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
117298      if( HasRowid(pTab) ){
117299        /* For a rowid table, initialize the RowSet to an empty set */
117300        pPk = 0;
117301        nPk = 1;
117302        iRowSet = ++pParse->nMem;
117303        sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
117304      }else{
117305        /* For a WITHOUT ROWID table, create an ephemeral table used to
117306        ** hold all primary keys for rows to be deleted. */
117307        pPk = sqlite3PrimaryKeyIndex(pTab);
117308        assert( pPk!=0 );
117309        nPk = pPk->nKeyCol;
117310        iPk = pParse->nMem+1;
117311        pParse->nMem += nPk;
117312        iEphCur = pParse->nTab++;
117313        addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
117314        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
117315      }
117316    
117317      /* Construct a query to find the rowid or primary key for every row
117318      ** to be deleted, based on the WHERE clause. Set variable eOnePass
117319      ** to indicate the strategy used to implement this delete:
117320      **
117321      **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
117322      **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
117323      **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
117324      */
117325      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
117326      if( pWInfo==0 ) goto delete_from_cleanup;
117327      eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
117328      assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
117329      assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
117330      if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
117331    
117332      /* Keep track of the number of rows to be deleted */
117333      if( memCnt ){
117334        sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
117335      }
117336    
117337      /* Extract the rowid or primary key for the current row */
117338      if( pPk ){
117339        for(i=0; i<nPk; i++){
117340          assert( pPk->aiColumn[i]>=0 );
117341          sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
117342                                          pPk->aiColumn[i], iPk+i);
117343        }
117344        iKey = iPk;
117345      }else{
117346        iKey = ++pParse->nMem;
117347        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
117348      }
117349    
117350      if( eOnePass!=ONEPASS_OFF ){
117351        /* For ONEPASS, no need to store the rowid/primary-key. There is only
117352        ** one, so just keep it in its register(s) and fall through to the
117353        ** delete code.  */
117354        nKey = nPk; /* OP_Found will use an unpacked key */
117355        aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
117356        if( aToOpen==0 ){
117357          sqlite3WhereEnd(pWInfo);
117358          goto delete_from_cleanup;
117359        }
117360        memset(aToOpen, 1, nIdx+1);
117361        aToOpen[nIdx+1] = 0;
117362        if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
117363        if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
117364        if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
117365      }else{
117366        if( pPk ){
117367          /* Add the PK key for this row to the temporary table */
117368          iKey = ++pParse->nMem;
117369          nKey = 0;   /* Zero tells OP_Found to use a composite key */
117370          sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
117371              sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
117372          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
117373        }else{
117374          /* Add the rowid of the row to be deleted to the RowSet */
117375          nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
117376          sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
117377        }
117378      }
117379    
117380      /* If this DELETE cannot use the ONEPASS strategy, this is the 
117381      ** end of the WHERE loop */
117382      if( eOnePass!=ONEPASS_OFF ){
117383        addrBypass = sqlite3VdbeMakeLabel(pParse);
117384      }else{
117385        sqlite3WhereEnd(pWInfo);
117386      }
117387    
117388      /* Unless this is a view, open cursors for the table we are 
117389      ** deleting from and all its indices. If this is a view, then the
117390      ** only effect this statement has is to fire the INSTEAD OF 
117391      ** triggers.
117392      */
117393      if( !isView ){
117394        int iAddrOnce = 0;
117395        if( eOnePass==ONEPASS_MULTI ){
117396          iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
117397        }
117398        testcase( IsVirtual(pTab) );
117399        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
117400                                   iTabCur, aToOpen, &iDataCur, &iIdxCur);
117401        assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
117402        assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
117403        if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
117404      }
117405    
117406      /* Set up a loop over the rowids/primary-keys that were found in the
117407      ** where-clause loop above.
117408      */
117409      if( eOnePass!=ONEPASS_OFF ){
117410        assert( nKey==nPk );  /* OP_Found will use an unpacked key */
117411        if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
117412          assert( pPk!=0 || pTab->pSelect!=0 );
117413          sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
117414          VdbeCoverage(v);
117415        }
117416      }else if( pPk ){
117417        addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
117418        if( IsVirtual(pTab) ){
117419          sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
117420        }else{
117421          sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
117422        }
117423        assert( nKey==0 );  /* OP_Found will use a composite key */
117424      }else{
117425        addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
117426        VdbeCoverage(v);
117427        assert( nKey==1 );
117428      }  
117429    
117430      /* Delete the row */
117431  #ifndef SQLITE_OMIT_VIRTUALTABLE
117432      if( IsVirtual(pTab) ){
117433        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
117434        sqlite3VtabMakeWritable(pParse, pTab);
117435        assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
117436        sqlite3MayAbort(pParse);
117437        if( eOnePass==ONEPASS_SINGLE ){
117438          sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
117439          if( sqlite3IsToplevel(pParse) ){
117440            pParse->isMultiWrite = 0;
117441          }
117442        }
117443        sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
117444        sqlite3VdbeChangeP5(v, OE_Abort);
117445      }else
117446  #endif
117447      {
117448        int count = (pParse->nested==0);    /* True to count changes */
117449        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
117450            iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
117451      }
117452    
117453      /* End of the loop over all rowids/primary-keys. */
117454      if( eOnePass!=ONEPASS_OFF ){
117455        sqlite3VdbeResolveLabel(v, addrBypass);
117456        sqlite3WhereEnd(pWInfo);
117457      }else if( pPk ){
117458        sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
117459        sqlite3VdbeJumpHere(v, addrLoop);
117460      }else{
117461        sqlite3VdbeGoto(v, addrLoop);
117462        sqlite3VdbeJumpHere(v, addrLoop);
117463      }     
117464    } /* End non-truncate path */
117465  
117466    /* Update the sqlite_sequence table by storing the content of the
117467    ** maximum rowid counter values recorded while inserting into
117468    ** autoincrement tables.
117469    */
117470    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
117471      sqlite3AutoincrementEnd(pParse);
117472    }
117473  
117474    /* Return the number of rows that were deleted. If this routine is 
117475    ** generating code because of a call to sqlite3NestedParse(), do not
117476    ** invoke the callback function.
117477    */
117478    if( memCnt ){
117479      sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
117480      sqlite3VdbeSetNumCols(v, 1);
117481      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
117482    }
117483  
117484  delete_from_cleanup:
117485    sqlite3AuthContextPop(&sContext);
117486    sqlite3SrcListDelete(db, pTabList);
117487    sqlite3ExprDelete(db, pWhere);
117488  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 
117489    sqlite3ExprListDelete(db, pOrderBy);
117490    sqlite3ExprDelete(db, pLimit);
117491  #endif
117492    sqlite3DbFree(db, aToOpen);
117493    return;
117494  }
117495  /* Make sure "isView" and other macros defined above are undefined. Otherwise
117496  ** they may interfere with compilation of other functions in this file
117497  ** (or in another file, if this file becomes part of the amalgamation).  */
117498  #ifdef isView
117499   #undef isView
117500  #endif
117501  #ifdef pTrigger
117502   #undef pTrigger
117503  #endif
117504  
117505  /*
117506  ** This routine generates VDBE code that causes a single row of a
117507  ** single table to be deleted.  Both the original table entry and
117508  ** all indices are removed.
117509  **
117510  ** Preconditions:
117511  **
117512  **   1.  iDataCur is an open cursor on the btree that is the canonical data
117513  **       store for the table.  (This will be either the table itself,
117514  **       in the case of a rowid table, or the PRIMARY KEY index in the case
117515  **       of a WITHOUT ROWID table.)
117516  **
117517  **   2.  Read/write cursors for all indices of pTab must be open as
117518  **       cursor number iIdxCur+i for the i-th index.
117519  **
117520  **   3.  The primary key for the row to be deleted must be stored in a
117521  **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
117522  **       that a search record formed from OP_MakeRecord is contained in the
117523  **       single memory location iPk.
117524  **
117525  ** eMode:
117526  **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
117527  **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
117528  **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
117529  **   then this function must seek iDataCur to the entry identified by iPk
117530  **   and nPk before reading from it.
117531  **
117532  **   If eMode is ONEPASS_MULTI, then this call is being made as part
117533  **   of a ONEPASS delete that affects multiple rows. In this case, if 
117534  **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
117535  **   iDataCur, then its position should be preserved following the delete
117536  **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
117537  **   position of iDataCur should be preserved instead.
117538  **
117539  ** iIdxNoSeek:
117540  **   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
117541  **   then it identifies an index cursor (from within array of cursors
117542  **   starting at iIdxCur) that already points to the index entry to be deleted.
117543  **   Except, this optimization is disabled if there are BEFORE triggers since
117544  **   the trigger body might have moved the cursor.
117545  */
117546  SQLITE_PRIVATE void sqlite3GenerateRowDelete(
117547    Parse *pParse,     /* Parsing context */
117548    Table *pTab,       /* Table containing the row to be deleted */
117549    Trigger *pTrigger, /* List of triggers to (potentially) fire */
117550    int iDataCur,      /* Cursor from which column data is extracted */
117551    int iIdxCur,       /* First index cursor */
117552    int iPk,           /* First memory cell containing the PRIMARY KEY */
117553    i16 nPk,           /* Number of PRIMARY KEY memory cells */
117554    u8 count,          /* If non-zero, increment the row change counter */
117555    u8 onconf,         /* Default ON CONFLICT policy for triggers */
117556    u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
117557    int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
117558  ){
117559    Vdbe *v = pParse->pVdbe;        /* Vdbe */
117560    int iOld = 0;                   /* First register in OLD.* array */
117561    int iLabel;                     /* Label resolved to end of generated code */
117562    u8 opSeek;                      /* Seek opcode */
117563  
117564    /* Vdbe is guaranteed to have been allocated by this stage. */
117565    assert( v );
117566    VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
117567                           iDataCur, iIdxCur, iPk, (int)nPk));
117568  
117569    /* Seek cursor iCur to the row to delete. If this row no longer exists 
117570    ** (this can happen if a trigger program has already deleted it), do
117571    ** not attempt to delete it or fire any DELETE triggers.  */
117572    iLabel = sqlite3VdbeMakeLabel(pParse);
117573    opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
117574    if( eMode==ONEPASS_OFF ){
117575      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
117576      VdbeCoverageIf(v, opSeek==OP_NotExists);
117577      VdbeCoverageIf(v, opSeek==OP_NotFound);
117578    }
117579   
117580    /* If there are any triggers to fire, allocate a range of registers to
117581    ** use for the old.* references in the triggers.  */
117582    if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
117583      u32 mask;                     /* Mask of OLD.* columns in use */
117584      int iCol;                     /* Iterator used while populating OLD.* */
117585      int addrStart;                /* Start of BEFORE trigger programs */
117586  
117587      /* TODO: Could use temporary registers here. Also could attempt to
117588      ** avoid copying the contents of the rowid register.  */
117589      mask = sqlite3TriggerColmask(
117590          pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
117591      );
117592      mask |= sqlite3FkOldmask(pParse, pTab);
117593      iOld = pParse->nMem+1;
117594      pParse->nMem += (1 + pTab->nCol);
117595  
117596      /* Populate the OLD.* pseudo-table register array. These values will be 
117597      ** used by any BEFORE and AFTER triggers that exist.  */
117598      sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
117599      for(iCol=0; iCol<pTab->nCol; iCol++){
117600        testcase( mask!=0xffffffff && iCol==31 );
117601        testcase( mask!=0xffffffff && iCol==32 );
117602        if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
117603          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
117604        }
117605      }
117606  
117607      /* Invoke BEFORE DELETE trigger programs. */
117608      addrStart = sqlite3VdbeCurrentAddr(v);
117609      sqlite3CodeRowTrigger(pParse, pTrigger, 
117610          TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
117611      );
117612  
117613      /* If any BEFORE triggers were coded, then seek the cursor to the 
117614      ** row to be deleted again. It may be that the BEFORE triggers moved
117615      ** the cursor or already deleted the row that the cursor was
117616      ** pointing to.
117617      **
117618      ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
117619      ** may have moved that cursor.
117620      */
117621      if( addrStart<sqlite3VdbeCurrentAddr(v) ){
117622        sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
117623        VdbeCoverageIf(v, opSeek==OP_NotExists);
117624        VdbeCoverageIf(v, opSeek==OP_NotFound);
117625        testcase( iIdxNoSeek>=0 );
117626        iIdxNoSeek = -1;
117627      }
117628  
117629      /* Do FK processing. This call checks that any FK constraints that
117630      ** refer to this table (i.e. constraints attached to other tables) 
117631      ** are not violated by deleting this row.  */
117632      sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
117633    }
117634  
117635    /* Delete the index and table entries. Skip this step if pTab is really
117636    ** a view (in which case the only effect of the DELETE statement is to
117637    ** fire the INSTEAD OF triggers).  
117638    **
117639    ** If variable 'count' is non-zero, then this OP_Delete instruction should
117640    ** invoke the update-hook. The pre-update-hook, on the other hand should
117641    ** be invoked unless table pTab is a system table. The difference is that
117642    ** the update-hook is not invoked for rows removed by REPLACE, but the 
117643    ** pre-update-hook is.
117644    */ 
117645    if( pTab->pSelect==0 ){
117646      u8 p5 = 0;
117647      sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
117648      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
117649      if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
117650        sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
117651      }
117652      if( eMode!=ONEPASS_OFF ){
117653        sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
117654      }
117655      if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
117656        sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
117657      }
117658      if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
117659      sqlite3VdbeChangeP5(v, p5);
117660    }
117661  
117662    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
117663    ** handle rows (possibly in other tables) that refer via a foreign key
117664    ** to the row just deleted. */ 
117665    sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
117666  
117667    /* Invoke AFTER DELETE trigger programs. */
117668    sqlite3CodeRowTrigger(pParse, pTrigger, 
117669        TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
117670    );
117671  
117672    /* Jump here if the row had already been deleted before any BEFORE
117673    ** trigger programs were invoked. Or if a trigger program throws a 
117674    ** RAISE(IGNORE) exception.  */
117675    sqlite3VdbeResolveLabel(v, iLabel);
117676    VdbeModuleComment((v, "END: GenRowDel()"));
117677  }
117678  
117679  /*
117680  ** This routine generates VDBE code that causes the deletion of all
117681  ** index entries associated with a single row of a single table, pTab
117682  **
117683  ** Preconditions:
117684  **
117685  **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
117686  **       btree for the table pTab.  (This will be either the table itself
117687  **       for rowid tables or to the primary key index for WITHOUT ROWID
117688  **       tables.)
117689  **
117690  **   2.  Read/write cursors for all indices of pTab must be open as
117691  **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
117692  **       index is the 0-th index.)
117693  **
117694  **   3.  The "iDataCur" cursor must be already be positioned on the row
117695  **       that is to be deleted.
117696  */
117697  SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
117698    Parse *pParse,     /* Parsing and code generating context */
117699    Table *pTab,       /* Table containing the row to be deleted */
117700    int iDataCur,      /* Cursor of table holding data. */
117701    int iIdxCur,       /* First index cursor */
117702    int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
117703    int iIdxNoSeek     /* Do not delete from this cursor */
117704  ){
117705    int i;             /* Index loop counter */
117706    int r1 = -1;       /* Register holding an index key */
117707    int iPartIdxLabel; /* Jump destination for skipping partial index entries */
117708    Index *pIdx;       /* Current index */
117709    Index *pPrior = 0; /* Prior index */
117710    Vdbe *v;           /* The prepared statement under construction */
117711    Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
117712  
117713    v = pParse->pVdbe;
117714    pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
117715    for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
117716      assert( iIdxCur+i!=iDataCur || pPk==pIdx );
117717      if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
117718      if( pIdx==pPk ) continue;
117719      if( iIdxCur+i==iIdxNoSeek ) continue;
117720      VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
117721      r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
117722          &iPartIdxLabel, pPrior, r1);
117723      sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
117724          pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
117725      sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
117726      pPrior = pIdx;
117727    }
117728  }
117729  
117730  /*
117731  ** Generate code that will assemble an index key and stores it in register
117732  ** regOut.  The key with be for index pIdx which is an index on pTab.
117733  ** iCur is the index of a cursor open on the pTab table and pointing to
117734  ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
117735  ** iCur must be the cursor of the PRIMARY KEY index.
117736  **
117737  ** Return a register number which is the first in a block of
117738  ** registers that holds the elements of the index key.  The
117739  ** block of registers has already been deallocated by the time
117740  ** this routine returns.
117741  **
117742  ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
117743  ** to that label if pIdx is a partial index that should be skipped.
117744  ** The label should be resolved using sqlite3ResolvePartIdxLabel().
117745  ** A partial index should be skipped if its WHERE clause evaluates
117746  ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
117747  ** will be set to zero which is an empty label that is ignored by
117748  ** sqlite3ResolvePartIdxLabel().
117749  **
117750  ** The pPrior and regPrior parameters are used to implement a cache to
117751  ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
117752  ** a pointer to a different index for which an index key has just been
117753  ** computed into register regPrior.  If the current pIdx index is generating
117754  ** its key into the same sequence of registers and if pPrior and pIdx share
117755  ** a column in common, then the register corresponding to that column already
117756  ** holds the correct value and the loading of that register is skipped.
117757  ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
117758  ** on a table with multiple indices, and especially with the ROWID or
117759  ** PRIMARY KEY columns of the index.
117760  */
117761  SQLITE_PRIVATE int sqlite3GenerateIndexKey(
117762    Parse *pParse,       /* Parsing context */
117763    Index *pIdx,         /* The index for which to generate a key */
117764    int iDataCur,        /* Cursor number from which to take column data */
117765    int regOut,          /* Put the new key into this register if not 0 */
117766    int prefixOnly,      /* Compute only a unique prefix of the key */
117767    int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
117768    Index *pPrior,       /* Previously generated index key */
117769    int regPrior         /* Register holding previous generated key */
117770  ){
117771    Vdbe *v = pParse->pVdbe;
117772    int j;
117773    int regBase;
117774    int nCol;
117775  
117776    if( piPartIdxLabel ){
117777      if( pIdx->pPartIdxWhere ){
117778        *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
117779        pParse->iSelfTab = iDataCur + 1;
117780        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
117781                              SQLITE_JUMPIFNULL);
117782        pParse->iSelfTab = 0;
117783      }else{
117784        *piPartIdxLabel = 0;
117785      }
117786    }
117787    nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
117788    regBase = sqlite3GetTempRange(pParse, nCol);
117789    if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
117790    for(j=0; j<nCol; j++){
117791      if( pPrior
117792       && pPrior->aiColumn[j]==pIdx->aiColumn[j]
117793       && pPrior->aiColumn[j]!=XN_EXPR
117794      ){
117795        /* This column was already computed by the previous index */
117796        continue;
117797      }
117798      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
117799      /* If the column affinity is REAL but the number is an integer, then it
117800      ** might be stored in the table as an integer (using a compact
117801      ** representation) then converted to REAL by an OP_RealAffinity opcode.
117802      ** But we are getting ready to store this value back into an index, where
117803      ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
117804      ** opcode if it is present */
117805      sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
117806    }
117807    if( regOut ){
117808      sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
117809      if( pIdx->pTable->pSelect ){
117810        const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
117811        sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
117812      }
117813    }
117814    sqlite3ReleaseTempRange(pParse, regBase, nCol);
117815    return regBase;
117816  }
117817  
117818  /*
117819  ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
117820  ** because it was a partial index, then this routine should be called to
117821  ** resolve that label.
117822  */
117823  SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
117824    if( iLabel ){
117825      sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
117826    }
117827  }
117828  
117829  /************** End of delete.c **********************************************/
117830  /************** Begin file func.c ********************************************/
117831  /*
117832  ** 2002 February 23
117833  **
117834  ** The author disclaims copyright to this source code.  In place of
117835  ** a legal notice, here is a blessing:
117836  **
117837  **    May you do good and not evil.
117838  **    May you find forgiveness for yourself and forgive others.
117839  **    May you share freely, never taking more than you give.
117840  **
117841  *************************************************************************
117842  ** This file contains the C-language implementations for many of the SQL
117843  ** functions of SQLite.  (Some function, and in particular the date and
117844  ** time functions, are implemented separately.)
117845  */
117846  /* #include "sqliteInt.h" */
117847  /* #include <stdlib.h> */
117848  /* #include <assert.h> */
117849  /* #include "vdbeInt.h" */
117850  
117851  /*
117852  ** Return the collating function associated with a function.
117853  */
117854  static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
117855    VdbeOp *pOp;
117856    assert( context->pVdbe!=0 );
117857    pOp = &context->pVdbe->aOp[context->iOp-1];
117858    assert( pOp->opcode==OP_CollSeq );
117859    assert( pOp->p4type==P4_COLLSEQ );
117860    return pOp->p4.pColl;
117861  }
117862  
117863  /*
117864  ** Indicate that the accumulator load should be skipped on this
117865  ** iteration of the aggregate loop.
117866  */
117867  static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
117868    assert( context->isError<=0 );
117869    context->isError = -1;
117870    context->skipFlag = 1;
117871  }
117872  
117873  /*
117874  ** Implementation of the non-aggregate min() and max() functions
117875  */
117876  static void minmaxFunc(
117877    sqlite3_context *context,
117878    int argc,
117879    sqlite3_value **argv
117880  ){
117881    int i;
117882    int mask;    /* 0 for min() or 0xffffffff for max() */
117883    int iBest;
117884    CollSeq *pColl;
117885  
117886    assert( argc>1 );
117887    mask = sqlite3_user_data(context)==0 ? 0 : -1;
117888    pColl = sqlite3GetFuncCollSeq(context);
117889    assert( pColl );
117890    assert( mask==-1 || mask==0 );
117891    iBest = 0;
117892    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
117893    for(i=1; i<argc; i++){
117894      if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
117895      if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
117896        testcase( mask==0 );
117897        iBest = i;
117898      }
117899    }
117900    sqlite3_result_value(context, argv[iBest]);
117901  }
117902  
117903  /*
117904  ** Return the type of the argument.
117905  */
117906  static void typeofFunc(
117907    sqlite3_context *context,
117908    int NotUsed,
117909    sqlite3_value **argv
117910  ){
117911    static const char *azType[] = { "integer", "real", "text", "blob", "null" };
117912    int i = sqlite3_value_type(argv[0]) - 1;
117913    UNUSED_PARAMETER(NotUsed);
117914    assert( i>=0 && i<ArraySize(azType) );
117915    assert( SQLITE_INTEGER==1 );
117916    assert( SQLITE_FLOAT==2 );
117917    assert( SQLITE_TEXT==3 );
117918    assert( SQLITE_BLOB==4 );
117919    assert( SQLITE_NULL==5 );
117920    /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
117921    ** the datatype code for the initial datatype of the sqlite3_value object
117922    ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
117923    ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
117924    sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
117925  }
117926  
117927  
117928  /*
117929  ** Implementation of the length() function
117930  */
117931  static void lengthFunc(
117932    sqlite3_context *context,
117933    int argc,
117934    sqlite3_value **argv
117935  ){
117936    assert( argc==1 );
117937    UNUSED_PARAMETER(argc);
117938    switch( sqlite3_value_type(argv[0]) ){
117939      case SQLITE_BLOB:
117940      case SQLITE_INTEGER:
117941      case SQLITE_FLOAT: {
117942        sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
117943        break;
117944      }
117945      case SQLITE_TEXT: {
117946        const unsigned char *z = sqlite3_value_text(argv[0]);
117947        const unsigned char *z0;
117948        unsigned char c;
117949        if( z==0 ) return;
117950        z0 = z;
117951        while( (c = *z)!=0 ){
117952          z++;
117953          if( c>=0xc0 ){
117954            while( (*z & 0xc0)==0x80 ){ z++; z0++; }
117955          }
117956        }
117957        sqlite3_result_int(context, (int)(z-z0));
117958        break;
117959      }
117960      default: {
117961        sqlite3_result_null(context);
117962        break;
117963      }
117964    }
117965  }
117966  
117967  /*
117968  ** Implementation of the abs() function.
117969  **
117970  ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
117971  ** the numeric argument X. 
117972  */
117973  static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
117974    assert( argc==1 );
117975    UNUSED_PARAMETER(argc);
117976    switch( sqlite3_value_type(argv[0]) ){
117977      case SQLITE_INTEGER: {
117978        i64 iVal = sqlite3_value_int64(argv[0]);
117979        if( iVal<0 ){
117980          if( iVal==SMALLEST_INT64 ){
117981            /* IMP: R-31676-45509 If X is the integer -9223372036854775808
117982            ** then abs(X) throws an integer overflow error since there is no
117983            ** equivalent positive 64-bit two complement value. */
117984            sqlite3_result_error(context, "integer overflow", -1);
117985            return;
117986          }
117987          iVal = -iVal;
117988        } 
117989        sqlite3_result_int64(context, iVal);
117990        break;
117991      }
117992      case SQLITE_NULL: {
117993        /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
117994        sqlite3_result_null(context);
117995        break;
117996      }
117997      default: {
117998        /* Because sqlite3_value_double() returns 0.0 if the argument is not
117999        ** something that can be converted into a number, we have:
118000        ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
118001        ** that cannot be converted to a numeric value.
118002        */
118003        double rVal = sqlite3_value_double(argv[0]);
118004        if( rVal<0 ) rVal = -rVal;
118005        sqlite3_result_double(context, rVal);
118006        break;
118007      }
118008    }
118009  }
118010  
118011  /*
118012  ** Implementation of the instr() function.
118013  **
118014  ** instr(haystack,needle) finds the first occurrence of needle
118015  ** in haystack and returns the number of previous characters plus 1,
118016  ** or 0 if needle does not occur within haystack.
118017  **
118018  ** If both haystack and needle are BLOBs, then the result is one more than
118019  ** the number of bytes in haystack prior to the first occurrence of needle,
118020  ** or 0 if needle never occurs in haystack.
118021  */
118022  static void instrFunc(
118023    sqlite3_context *context,
118024    int argc,
118025    sqlite3_value **argv
118026  ){
118027    const unsigned char *zHaystack;
118028    const unsigned char *zNeedle;
118029    int nHaystack;
118030    int nNeedle;
118031    int typeHaystack, typeNeedle;
118032    int N = 1;
118033    int isText;
118034    unsigned char firstChar;
118035  
118036    UNUSED_PARAMETER(argc);
118037    typeHaystack = sqlite3_value_type(argv[0]);
118038    typeNeedle = sqlite3_value_type(argv[1]);
118039    if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
118040    nHaystack = sqlite3_value_bytes(argv[0]);
118041    nNeedle = sqlite3_value_bytes(argv[1]);
118042    if( nNeedle>0 ){
118043      if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
118044        zHaystack = sqlite3_value_blob(argv[0]);
118045        zNeedle = sqlite3_value_blob(argv[1]);
118046        isText = 0;
118047      }else{
118048        zHaystack = sqlite3_value_text(argv[0]);
118049        zNeedle = sqlite3_value_text(argv[1]);
118050        isText = 1;
118051      }
118052      if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
118053      firstChar = zNeedle[0];
118054      while( nNeedle<=nHaystack
118055         && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
118056      ){
118057        N++;
118058        do{
118059          nHaystack--;
118060          zHaystack++;
118061        }while( isText && (zHaystack[0]&0xc0)==0x80 );
118062      }
118063      if( nNeedle>nHaystack ) N = 0;
118064    }
118065    sqlite3_result_int(context, N);
118066  }
118067  
118068  /*
118069  ** Implementation of the printf() function.
118070  */
118071  static void printfFunc(
118072    sqlite3_context *context,
118073    int argc,
118074    sqlite3_value **argv
118075  ){
118076    PrintfArguments x;
118077    StrAccum str;
118078    const char *zFormat;
118079    int n;
118080    sqlite3 *db = sqlite3_context_db_handle(context);
118081  
118082    if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
118083      x.nArg = argc-1;
118084      x.nUsed = 0;
118085      x.apArg = argv+1;
118086      sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
118087      str.printfFlags = SQLITE_PRINTF_SQLFUNC;
118088      sqlite3_str_appendf(&str, zFormat, &x);
118089      n = str.nChar;
118090      sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
118091                          SQLITE_DYNAMIC);
118092    }
118093  }
118094  
118095  /*
118096  ** Implementation of the substr() function.
118097  **
118098  ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
118099  ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
118100  ** of x.  If x is text, then we actually count UTF-8 characters.
118101  ** If x is a blob, then we count bytes.
118102  **
118103  ** If p1 is negative, then we begin abs(p1) from the end of x[].
118104  **
118105  ** If p2 is negative, return the p2 characters preceding p1.
118106  */
118107  static void substrFunc(
118108    sqlite3_context *context,
118109    int argc,
118110    sqlite3_value **argv
118111  ){
118112    const unsigned char *z;
118113    const unsigned char *z2;
118114    int len;
118115    int p0type;
118116    i64 p1, p2;
118117    int negP2 = 0;
118118  
118119    assert( argc==3 || argc==2 );
118120    if( sqlite3_value_type(argv[1])==SQLITE_NULL
118121     || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
118122    ){
118123      return;
118124    }
118125    p0type = sqlite3_value_type(argv[0]);
118126    p1 = sqlite3_value_int(argv[1]);
118127    if( p0type==SQLITE_BLOB ){
118128      len = sqlite3_value_bytes(argv[0]);
118129      z = sqlite3_value_blob(argv[0]);
118130      if( z==0 ) return;
118131      assert( len==sqlite3_value_bytes(argv[0]) );
118132    }else{
118133      z = sqlite3_value_text(argv[0]);
118134      if( z==0 ) return;
118135      len = 0;
118136      if( p1<0 ){
118137        for(z2=z; *z2; len++){
118138          SQLITE_SKIP_UTF8(z2);
118139        }
118140      }
118141    }
118142  #ifdef SQLITE_SUBSTR_COMPATIBILITY
118143    /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
118144    ** as substr(X,1,N) - it returns the first N characters of X.  This
118145    ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
118146    ** from 2009-02-02 for compatibility of applications that exploited the
118147    ** old buggy behavior. */
118148    if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
118149  #endif
118150    if( argc==3 ){
118151      p2 = sqlite3_value_int(argv[2]);
118152      if( p2<0 ){
118153        p2 = -p2;
118154        negP2 = 1;
118155      }
118156    }else{
118157      p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
118158    }
118159    if( p1<0 ){
118160      p1 += len;
118161      if( p1<0 ){
118162        p2 += p1;
118163        if( p2<0 ) p2 = 0;
118164        p1 = 0;
118165      }
118166    }else if( p1>0 ){
118167      p1--;
118168    }else if( p2>0 ){
118169      p2--;
118170    }
118171    if( negP2 ){
118172      p1 -= p2;
118173      if( p1<0 ){
118174        p2 += p1;
118175        p1 = 0;
118176      }
118177    }
118178    assert( p1>=0 && p2>=0 );
118179    if( p0type!=SQLITE_BLOB ){
118180      while( *z && p1 ){
118181        SQLITE_SKIP_UTF8(z);
118182        p1--;
118183      }
118184      for(z2=z; *z2 && p2; p2--){
118185        SQLITE_SKIP_UTF8(z2);
118186      }
118187      sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
118188                            SQLITE_UTF8);
118189    }else{
118190      if( p1+p2>len ){
118191        p2 = len-p1;
118192        if( p2<0 ) p2 = 0;
118193      }
118194      sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
118195    }
118196  }
118197  
118198  /*
118199  ** Implementation of the round() function
118200  */
118201  #ifndef SQLITE_OMIT_FLOATING_POINT
118202  static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
118203    int n = 0;
118204    double r;
118205    char *zBuf;
118206    assert( argc==1 || argc==2 );
118207    if( argc==2 ){
118208      if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
118209      n = sqlite3_value_int(argv[1]);
118210      if( n>30 ) n = 30;
118211      if( n<0 ) n = 0;
118212    }
118213    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
118214    r = sqlite3_value_double(argv[0]);
118215    /* If Y==0 and X will fit in a 64-bit int,
118216    ** handle the rounding directly,
118217    ** otherwise use printf.
118218    */
118219    if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
118220      r = (double)((sqlite_int64)(r+0.5));
118221    }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
118222      r = -(double)((sqlite_int64)((-r)+0.5));
118223    }else{
118224      zBuf = sqlite3_mprintf("%.*f",n,r);
118225      if( zBuf==0 ){
118226        sqlite3_result_error_nomem(context);
118227        return;
118228      }
118229      sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
118230      sqlite3_free(zBuf);
118231    }
118232    sqlite3_result_double(context, r);
118233  }
118234  #endif
118235  
118236  /*
118237  ** Allocate nByte bytes of space using sqlite3Malloc(). If the
118238  ** allocation fails, call sqlite3_result_error_nomem() to notify
118239  ** the database handle that malloc() has failed and return NULL.
118240  ** If nByte is larger than the maximum string or blob length, then
118241  ** raise an SQLITE_TOOBIG exception and return NULL.
118242  */
118243  static void *contextMalloc(sqlite3_context *context, i64 nByte){
118244    char *z;
118245    sqlite3 *db = sqlite3_context_db_handle(context);
118246    assert( nByte>0 );
118247    testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
118248    testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
118249    if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
118250      sqlite3_result_error_toobig(context);
118251      z = 0;
118252    }else{
118253      z = sqlite3Malloc(nByte);
118254      if( !z ){
118255        sqlite3_result_error_nomem(context);
118256      }
118257    }
118258    return z;
118259  }
118260  
118261  /*
118262  ** Implementation of the upper() and lower() SQL functions.
118263  */
118264  static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
118265    char *z1;
118266    const char *z2;
118267    int i, n;
118268    UNUSED_PARAMETER(argc);
118269    z2 = (char*)sqlite3_value_text(argv[0]);
118270    n = sqlite3_value_bytes(argv[0]);
118271    /* Verify that the call to _bytes() does not invalidate the _text() pointer */
118272    assert( z2==(char*)sqlite3_value_text(argv[0]) );
118273    if( z2 ){
118274      z1 = contextMalloc(context, ((i64)n)+1);
118275      if( z1 ){
118276        for(i=0; i<n; i++){
118277          z1[i] = (char)sqlite3Toupper(z2[i]);
118278        }
118279        sqlite3_result_text(context, z1, n, sqlite3_free);
118280      }
118281    }
118282  }
118283  static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
118284    char *z1;
118285    const char *z2;
118286    int i, n;
118287    UNUSED_PARAMETER(argc);
118288    z2 = (char*)sqlite3_value_text(argv[0]);
118289    n = sqlite3_value_bytes(argv[0]);
118290    /* Verify that the call to _bytes() does not invalidate the _text() pointer */
118291    assert( z2==(char*)sqlite3_value_text(argv[0]) );
118292    if( z2 ){
118293      z1 = contextMalloc(context, ((i64)n)+1);
118294      if( z1 ){
118295        for(i=0; i<n; i++){
118296          z1[i] = sqlite3Tolower(z2[i]);
118297        }
118298        sqlite3_result_text(context, z1, n, sqlite3_free);
118299      }
118300    }
118301  }
118302  
118303  /*
118304  ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
118305  ** as VDBE code so that unused argument values do not have to be computed.
118306  ** However, we still need some kind of function implementation for this
118307  ** routines in the function table.  The noopFunc macro provides this.
118308  ** noopFunc will never be called so it doesn't matter what the implementation
118309  ** is.  We might as well use the "version()" function as a substitute.
118310  */
118311  #define noopFunc versionFunc   /* Substitute function - never called */
118312  
118313  /*
118314  ** Implementation of random().  Return a random integer.  
118315  */
118316  static void randomFunc(
118317    sqlite3_context *context,
118318    int NotUsed,
118319    sqlite3_value **NotUsed2
118320  ){
118321    sqlite_int64 r;
118322    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118323    sqlite3_randomness(sizeof(r), &r);
118324    if( r<0 ){
118325      /* We need to prevent a random number of 0x8000000000000000 
118326      ** (or -9223372036854775808) since when you do abs() of that
118327      ** number of you get the same value back again.  To do this
118328      ** in a way that is testable, mask the sign bit off of negative
118329      ** values, resulting in a positive value.  Then take the 
118330      ** 2s complement of that positive value.  The end result can
118331      ** therefore be no less than -9223372036854775807.
118332      */
118333      r = -(r & LARGEST_INT64);
118334    }
118335    sqlite3_result_int64(context, r);
118336  }
118337  
118338  /*
118339  ** Implementation of randomblob(N).  Return a random blob
118340  ** that is N bytes long.
118341  */
118342  static void randomBlob(
118343    sqlite3_context *context,
118344    int argc,
118345    sqlite3_value **argv
118346  ){
118347    sqlite3_int64 n;
118348    unsigned char *p;
118349    assert( argc==1 );
118350    UNUSED_PARAMETER(argc);
118351    n = sqlite3_value_int64(argv[0]);
118352    if( n<1 ){
118353      n = 1;
118354    }
118355    p = contextMalloc(context, n);
118356    if( p ){
118357      sqlite3_randomness(n, p);
118358      sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
118359    }
118360  }
118361  
118362  /*
118363  ** Implementation of the last_insert_rowid() SQL function.  The return
118364  ** value is the same as the sqlite3_last_insert_rowid() API function.
118365  */
118366  static void last_insert_rowid(
118367    sqlite3_context *context, 
118368    int NotUsed, 
118369    sqlite3_value **NotUsed2
118370  ){
118371    sqlite3 *db = sqlite3_context_db_handle(context);
118372    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118373    /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
118374    ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
118375    ** function. */
118376    sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
118377  }
118378  
118379  /*
118380  ** Implementation of the changes() SQL function.
118381  **
118382  ** IMP: R-62073-11209 The changes() SQL function is a wrapper
118383  ** around the sqlite3_changes() C/C++ function and hence follows the same
118384  ** rules for counting changes.
118385  */
118386  static void changes(
118387    sqlite3_context *context,
118388    int NotUsed,
118389    sqlite3_value **NotUsed2
118390  ){
118391    sqlite3 *db = sqlite3_context_db_handle(context);
118392    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118393    sqlite3_result_int(context, sqlite3_changes(db));
118394  }
118395  
118396  /*
118397  ** Implementation of the total_changes() SQL function.  The return value is
118398  ** the same as the sqlite3_total_changes() API function.
118399  */
118400  static void total_changes(
118401    sqlite3_context *context,
118402    int NotUsed,
118403    sqlite3_value **NotUsed2
118404  ){
118405    sqlite3 *db = sqlite3_context_db_handle(context);
118406    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118407    /* IMP: R-52756-41993 This function is a wrapper around the
118408    ** sqlite3_total_changes() C/C++ interface. */
118409    sqlite3_result_int(context, sqlite3_total_changes(db));
118410  }
118411  
118412  /*
118413  ** A structure defining how to do GLOB-style comparisons.
118414  */
118415  struct compareInfo {
118416    u8 matchAll;          /* "*" or "%" */
118417    u8 matchOne;          /* "?" or "_" */
118418    u8 matchSet;          /* "[" or 0 */
118419    u8 noCase;            /* true to ignore case differences */
118420  };
118421  
118422  /*
118423  ** For LIKE and GLOB matching on EBCDIC machines, assume that every
118424  ** character is exactly one byte in size.  Also, provde the Utf8Read()
118425  ** macro for fast reading of the next character in the common case where
118426  ** the next character is ASCII.
118427  */
118428  #if defined(SQLITE_EBCDIC)
118429  # define sqlite3Utf8Read(A)        (*((*A)++))
118430  # define Utf8Read(A)               (*(A++))
118431  #else
118432  # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
118433  #endif
118434  
118435  static const struct compareInfo globInfo = { '*', '?', '[', 0 };
118436  /* The correct SQL-92 behavior is for the LIKE operator to ignore
118437  ** case.  Thus  'a' LIKE 'A' would be true. */
118438  static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
118439  /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
118440  ** is case sensitive causing 'a' LIKE 'A' to be false */
118441  static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
118442  
118443  /*
118444  ** Possible error returns from patternMatch()
118445  */
118446  #define SQLITE_MATCH             0
118447  #define SQLITE_NOMATCH           1
118448  #define SQLITE_NOWILDCARDMATCH   2
118449  
118450  /*
118451  ** Compare two UTF-8 strings for equality where the first string is
118452  ** a GLOB or LIKE expression.  Return values:
118453  **
118454  **    SQLITE_MATCH:            Match
118455  **    SQLITE_NOMATCH:          No match
118456  **    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
118457  **
118458  ** Globbing rules:
118459  **
118460  **      '*'       Matches any sequence of zero or more characters.
118461  **
118462  **      '?'       Matches exactly one character.
118463  **
118464  **     [...]      Matches one character from the enclosed list of
118465  **                characters.
118466  **
118467  **     [^...]     Matches one character not in the enclosed list.
118468  **
118469  ** With the [...] and [^...] matching, a ']' character can be included
118470  ** in the list by making it the first character after '[' or '^'.  A
118471  ** range of characters can be specified using '-'.  Example:
118472  ** "[a-z]" matches any single lower-case letter.  To match a '-', make
118473  ** it the last character in the list.
118474  **
118475  ** Like matching rules:
118476  ** 
118477  **      '%'       Matches any sequence of zero or more characters
118478  **
118479  ***     '_'       Matches any one character
118480  **
118481  **      Ec        Where E is the "esc" character and c is any other
118482  **                character, including '%', '_', and esc, match exactly c.
118483  **
118484  ** The comments within this routine usually assume glob matching.
118485  **
118486  ** This routine is usually quick, but can be N**2 in the worst case.
118487  */
118488  static int patternCompare(
118489    const u8 *zPattern,              /* The glob pattern */
118490    const u8 *zString,               /* The string to compare against the glob */
118491    const struct compareInfo *pInfo, /* Information about how to do the compare */
118492    u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
118493  ){
118494    u32 c, c2;                       /* Next pattern and input string chars */
118495    u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
118496    u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
118497    u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
118498    const u8 *zEscaped = 0;          /* One past the last escaped input char */
118499    
118500    while( (c = Utf8Read(zPattern))!=0 ){
118501      if( c==matchAll ){  /* Match "*" */
118502        /* Skip over multiple "*" characters in the pattern.  If there
118503        ** are also "?" characters, skip those as well, but consume a
118504        ** single character of the input string for each "?" skipped */
118505        while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
118506          if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
118507            return SQLITE_NOWILDCARDMATCH;
118508          }
118509        }
118510        if( c==0 ){
118511          return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
118512        }else if( c==matchOther ){
118513          if( pInfo->matchSet==0 ){
118514            c = sqlite3Utf8Read(&zPattern);
118515            if( c==0 ) return SQLITE_NOWILDCARDMATCH;
118516          }else{
118517            /* "[...]" immediately follows the "*".  We have to do a slow
118518            ** recursive search in this case, but it is an unusual case. */
118519            assert( matchOther<0x80 );  /* '[' is a single-byte character */
118520            while( *zString ){
118521              int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
118522              if( bMatch!=SQLITE_NOMATCH ) return bMatch;
118523              SQLITE_SKIP_UTF8(zString);
118524            }
118525            return SQLITE_NOWILDCARDMATCH;
118526          }
118527        }
118528  
118529        /* At this point variable c contains the first character of the
118530        ** pattern string past the "*".  Search in the input string for the
118531        ** first matching character and recursively continue the match from
118532        ** that point.
118533        **
118534        ** For a case-insensitive search, set variable cx to be the same as
118535        ** c but in the other case and search the input string for either
118536        ** c or cx.
118537        */
118538        if( c<=0x80 ){
118539          char zStop[3];
118540          int bMatch;
118541          if( noCase ){
118542            zStop[0] = sqlite3Toupper(c);
118543            zStop[1] = sqlite3Tolower(c);
118544            zStop[2] = 0;
118545          }else{
118546            zStop[0] = c;
118547            zStop[1] = 0;
118548          }
118549          while(1){
118550            zString += strcspn((const char*)zString, zStop);
118551            if( zString[0]==0 ) break;
118552            zString++;
118553            bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
118554            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
118555          }
118556        }else{
118557          int bMatch;
118558          while( (c2 = Utf8Read(zString))!=0 ){
118559            if( c2!=c ) continue;
118560            bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
118561            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
118562          }
118563        }
118564        return SQLITE_NOWILDCARDMATCH;
118565      }
118566      if( c==matchOther ){
118567        if( pInfo->matchSet==0 ){
118568          c = sqlite3Utf8Read(&zPattern);
118569          if( c==0 ) return SQLITE_NOMATCH;
118570          zEscaped = zPattern;
118571        }else{
118572          u32 prior_c = 0;
118573          int seen = 0;
118574          int invert = 0;
118575          c = sqlite3Utf8Read(&zString);
118576          if( c==0 ) return SQLITE_NOMATCH;
118577          c2 = sqlite3Utf8Read(&zPattern);
118578          if( c2=='^' ){
118579            invert = 1;
118580            c2 = sqlite3Utf8Read(&zPattern);
118581          }
118582          if( c2==']' ){
118583            if( c==']' ) seen = 1;
118584            c2 = sqlite3Utf8Read(&zPattern);
118585          }
118586          while( c2 && c2!=']' ){
118587            if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
118588              c2 = sqlite3Utf8Read(&zPattern);
118589              if( c>=prior_c && c<=c2 ) seen = 1;
118590              prior_c = 0;
118591            }else{
118592              if( c==c2 ){
118593                seen = 1;
118594              }
118595              prior_c = c2;
118596            }
118597            c2 = sqlite3Utf8Read(&zPattern);
118598          }
118599          if( c2==0 || (seen ^ invert)==0 ){
118600            return SQLITE_NOMATCH;
118601          }
118602          continue;
118603        }
118604      }
118605      c2 = Utf8Read(zString);
118606      if( c==c2 ) continue;
118607      if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
118608        continue;
118609      }
118610      if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
118611      return SQLITE_NOMATCH;
118612    }
118613    return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
118614  }
118615  
118616  /*
118617  ** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
118618  ** non-zero if there is no match.
118619  */
118620  SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
118621    return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
118622  }
118623  
118624  /*
118625  ** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
118626  ** a miss - like strcmp().
118627  */
118628  SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
118629    return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
118630  }
118631  
118632  /*
118633  ** Count the number of times that the LIKE operator (or GLOB which is
118634  ** just a variation of LIKE) gets called.  This is used for testing
118635  ** only.
118636  */
118637  #ifdef SQLITE_TEST
118638  SQLITE_API int sqlite3_like_count = 0;
118639  #endif
118640  
118641  
118642  /*
118643  ** Implementation of the like() SQL function.  This function implements
118644  ** the build-in LIKE operator.  The first argument to the function is the
118645  ** pattern and the second argument is the string.  So, the SQL statements:
118646  **
118647  **       A LIKE B
118648  **
118649  ** is implemented as like(B,A).
118650  **
118651  ** This same function (with a different compareInfo structure) computes
118652  ** the GLOB operator.
118653  */
118654  static void likeFunc(
118655    sqlite3_context *context, 
118656    int argc, 
118657    sqlite3_value **argv
118658  ){
118659    const unsigned char *zA, *zB;
118660    u32 escape;
118661    int nPat;
118662    sqlite3 *db = sqlite3_context_db_handle(context);
118663    struct compareInfo *pInfo = sqlite3_user_data(context);
118664  
118665  #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
118666    if( sqlite3_value_type(argv[0])==SQLITE_BLOB
118667     || sqlite3_value_type(argv[1])==SQLITE_BLOB
118668    ){
118669  #ifdef SQLITE_TEST
118670      sqlite3_like_count++;
118671  #endif
118672      sqlite3_result_int(context, 0);
118673      return;
118674    }
118675  #endif
118676    zB = sqlite3_value_text(argv[0]);
118677    zA = sqlite3_value_text(argv[1]);
118678  
118679    /* Limit the length of the LIKE or GLOB pattern to avoid problems
118680    ** of deep recursion and N*N behavior in patternCompare().
118681    */
118682    nPat = sqlite3_value_bytes(argv[0]);
118683    testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
118684    testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
118685    if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
118686      sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
118687      return;
118688    }
118689    assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
118690  
118691    if( argc==3 ){
118692      /* The escape character string must consist of a single UTF-8 character.
118693      ** Otherwise, return an error.
118694      */
118695      const unsigned char *zEsc = sqlite3_value_text(argv[2]);
118696      if( zEsc==0 ) return;
118697      if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
118698        sqlite3_result_error(context, 
118699            "ESCAPE expression must be a single character", -1);
118700        return;
118701      }
118702      escape = sqlite3Utf8Read(&zEsc);
118703    }else{
118704      escape = pInfo->matchSet;
118705    }
118706    if( zA && zB ){
118707  #ifdef SQLITE_TEST
118708      sqlite3_like_count++;
118709  #endif
118710      sqlite3_result_int(context,
118711                        patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
118712    }
118713  }
118714  
118715  /*
118716  ** Implementation of the NULLIF(x,y) function.  The result is the first
118717  ** argument if the arguments are different.  The result is NULL if the
118718  ** arguments are equal to each other.
118719  */
118720  static void nullifFunc(
118721    sqlite3_context *context,
118722    int NotUsed,
118723    sqlite3_value **argv
118724  ){
118725    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
118726    UNUSED_PARAMETER(NotUsed);
118727    if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
118728      sqlite3_result_value(context, argv[0]);
118729    }
118730  }
118731  
118732  /*
118733  ** Implementation of the sqlite_version() function.  The result is the version
118734  ** of the SQLite library that is running.
118735  */
118736  static void versionFunc(
118737    sqlite3_context *context,
118738    int NotUsed,
118739    sqlite3_value **NotUsed2
118740  ){
118741    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118742    /* IMP: R-48699-48617 This function is an SQL wrapper around the
118743    ** sqlite3_libversion() C-interface. */
118744    sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
118745  }
118746  
118747  /*
118748  ** Implementation of the sqlite_source_id() function. The result is a string
118749  ** that identifies the particular version of the source code used to build
118750  ** SQLite.
118751  */
118752  static void sourceidFunc(
118753    sqlite3_context *context,
118754    int NotUsed,
118755    sqlite3_value **NotUsed2
118756  ){
118757    UNUSED_PARAMETER2(NotUsed, NotUsed2);
118758    /* IMP: R-24470-31136 This function is an SQL wrapper around the
118759    ** sqlite3_sourceid() C interface. */
118760    sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
118761  }
118762  
118763  /*
118764  ** Implementation of the sqlite_log() function.  This is a wrapper around
118765  ** sqlite3_log().  The return value is NULL.  The function exists purely for
118766  ** its side-effects.
118767  */
118768  static void errlogFunc(
118769    sqlite3_context *context,
118770    int argc,
118771    sqlite3_value **argv
118772  ){
118773    UNUSED_PARAMETER(argc);
118774    UNUSED_PARAMETER(context);
118775    sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
118776  }
118777  
118778  /*
118779  ** Implementation of the sqlite_compileoption_used() function.
118780  ** The result is an integer that identifies if the compiler option
118781  ** was used to build SQLite.
118782  */
118783  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
118784  static void compileoptionusedFunc(
118785    sqlite3_context *context,
118786    int argc,
118787    sqlite3_value **argv
118788  ){
118789    const char *zOptName;
118790    assert( argc==1 );
118791    UNUSED_PARAMETER(argc);
118792    /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
118793    ** function is a wrapper around the sqlite3_compileoption_used() C/C++
118794    ** function.
118795    */
118796    if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
118797      sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
118798    }
118799  }
118800  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
118801  
118802  /*
118803  ** Implementation of the sqlite_compileoption_get() function. 
118804  ** The result is a string that identifies the compiler options 
118805  ** used to build SQLite.
118806  */
118807  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
118808  static void compileoptiongetFunc(
118809    sqlite3_context *context,
118810    int argc,
118811    sqlite3_value **argv
118812  ){
118813    int n;
118814    assert( argc==1 );
118815    UNUSED_PARAMETER(argc);
118816    /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
118817    ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
118818    */
118819    n = sqlite3_value_int(argv[0]);
118820    sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
118821  }
118822  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
118823  
118824  /* Array for converting from half-bytes (nybbles) into ASCII hex
118825  ** digits. */
118826  static const char hexdigits[] = {
118827    '0', '1', '2', '3', '4', '5', '6', '7',
118828    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
118829  };
118830  
118831  /*
118832  ** Implementation of the QUOTE() function.  This function takes a single
118833  ** argument.  If the argument is numeric, the return value is the same as
118834  ** the argument.  If the argument is NULL, the return value is the string
118835  ** "NULL".  Otherwise, the argument is enclosed in single quotes with
118836  ** single-quote escapes.
118837  */
118838  static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
118839    assert( argc==1 );
118840    UNUSED_PARAMETER(argc);
118841    switch( sqlite3_value_type(argv[0]) ){
118842      case SQLITE_FLOAT: {
118843        double r1, r2;
118844        char zBuf[50];
118845        r1 = sqlite3_value_double(argv[0]);
118846        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
118847        sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
118848        if( r1!=r2 ){
118849          sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
118850        }
118851        sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
118852        break;
118853      }
118854      case SQLITE_INTEGER: {
118855        sqlite3_result_value(context, argv[0]);
118856        break;
118857      }
118858      case SQLITE_BLOB: {
118859        char *zText = 0;
118860        char const *zBlob = sqlite3_value_blob(argv[0]);
118861        int nBlob = sqlite3_value_bytes(argv[0]);
118862        assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
118863        zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
118864        if( zText ){
118865          int i;
118866          for(i=0; i<nBlob; i++){
118867            zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
118868            zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
118869          }
118870          zText[(nBlob*2)+2] = '\'';
118871          zText[(nBlob*2)+3] = '\0';
118872          zText[0] = 'X';
118873          zText[1] = '\'';
118874          sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
118875          sqlite3_free(zText);
118876        }
118877        break;
118878      }
118879      case SQLITE_TEXT: {
118880        int i,j;
118881        u64 n;
118882        const unsigned char *zArg = sqlite3_value_text(argv[0]);
118883        char *z;
118884  
118885        if( zArg==0 ) return;
118886        for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
118887        z = contextMalloc(context, ((i64)i)+((i64)n)+3);
118888        if( z ){
118889          z[0] = '\'';
118890          for(i=0, j=1; zArg[i]; i++){
118891            z[j++] = zArg[i];
118892            if( zArg[i]=='\'' ){
118893              z[j++] = '\'';
118894            }
118895          }
118896          z[j++] = '\'';
118897          z[j] = 0;
118898          sqlite3_result_text(context, z, j, sqlite3_free);
118899        }
118900        break;
118901      }
118902      default: {
118903        assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
118904        sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
118905        break;
118906      }
118907    }
118908  }
118909  
118910  /*
118911  ** The unicode() function.  Return the integer unicode code-point value
118912  ** for the first character of the input string. 
118913  */
118914  static void unicodeFunc(
118915    sqlite3_context *context,
118916    int argc,
118917    sqlite3_value **argv
118918  ){
118919    const unsigned char *z = sqlite3_value_text(argv[0]);
118920    (void)argc;
118921    if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
118922  }
118923  
118924  /*
118925  ** The char() function takes zero or more arguments, each of which is
118926  ** an integer.  It constructs a string where each character of the string
118927  ** is the unicode character for the corresponding integer argument.
118928  */
118929  static void charFunc(
118930    sqlite3_context *context,
118931    int argc,
118932    sqlite3_value **argv
118933  ){
118934    unsigned char *z, *zOut;
118935    int i;
118936    zOut = z = sqlite3_malloc64( argc*4+1 );
118937    if( z==0 ){
118938      sqlite3_result_error_nomem(context);
118939      return;
118940    }
118941    for(i=0; i<argc; i++){
118942      sqlite3_int64 x;
118943      unsigned c;
118944      x = sqlite3_value_int64(argv[i]);
118945      if( x<0 || x>0x10ffff ) x = 0xfffd;
118946      c = (unsigned)(x & 0x1fffff);
118947      if( c<0x00080 ){
118948        *zOut++ = (u8)(c&0xFF);
118949      }else if( c<0x00800 ){
118950        *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
118951        *zOut++ = 0x80 + (u8)(c & 0x3F);
118952      }else if( c<0x10000 ){
118953        *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
118954        *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
118955        *zOut++ = 0x80 + (u8)(c & 0x3F);
118956      }else{
118957        *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
118958        *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
118959        *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
118960        *zOut++ = 0x80 + (u8)(c & 0x3F);
118961      }                                                    \
118962    }
118963    sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
118964  }
118965  
118966  /*
118967  ** The hex() function.  Interpret the argument as a blob.  Return
118968  ** a hexadecimal rendering as text.
118969  */
118970  static void hexFunc(
118971    sqlite3_context *context,
118972    int argc,
118973    sqlite3_value **argv
118974  ){
118975    int i, n;
118976    const unsigned char *pBlob;
118977    char *zHex, *z;
118978    assert( argc==1 );
118979    UNUSED_PARAMETER(argc);
118980    pBlob = sqlite3_value_blob(argv[0]);
118981    n = sqlite3_value_bytes(argv[0]);
118982    assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
118983    z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
118984    if( zHex ){
118985      for(i=0; i<n; i++, pBlob++){
118986        unsigned char c = *pBlob;
118987        *(z++) = hexdigits[(c>>4)&0xf];
118988        *(z++) = hexdigits[c&0xf];
118989      }
118990      *z = 0;
118991      sqlite3_result_text(context, zHex, n*2, sqlite3_free);
118992    }
118993  }
118994  
118995  /*
118996  ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
118997  */
118998  static void zeroblobFunc(
118999    sqlite3_context *context,
119000    int argc,
119001    sqlite3_value **argv
119002  ){
119003    i64 n;
119004    int rc;
119005    assert( argc==1 );
119006    UNUSED_PARAMETER(argc);
119007    n = sqlite3_value_int64(argv[0]);
119008    if( n<0 ) n = 0;
119009    rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
119010    if( rc ){
119011      sqlite3_result_error_code(context, rc);
119012    }
119013  }
119014  
119015  /*
119016  ** The replace() function.  Three arguments are all strings: call
119017  ** them A, B, and C. The result is also a string which is derived
119018  ** from A by replacing every occurrence of B with C.  The match
119019  ** must be exact.  Collating sequences are not used.
119020  */
119021  static void replaceFunc(
119022    sqlite3_context *context,
119023    int argc,
119024    sqlite3_value **argv
119025  ){
119026    const unsigned char *zStr;        /* The input string A */
119027    const unsigned char *zPattern;    /* The pattern string B */
119028    const unsigned char *zRep;        /* The replacement string C */
119029    unsigned char *zOut;              /* The output */
119030    int nStr;                /* Size of zStr */
119031    int nPattern;            /* Size of zPattern */
119032    int nRep;                /* Size of zRep */
119033    i64 nOut;                /* Maximum size of zOut */
119034    int loopLimit;           /* Last zStr[] that might match zPattern[] */
119035    int i, j;                /* Loop counters */
119036    unsigned cntExpand;      /* Number zOut expansions */
119037    sqlite3 *db = sqlite3_context_db_handle(context);
119038  
119039    assert( argc==3 );
119040    UNUSED_PARAMETER(argc);
119041    zStr = sqlite3_value_text(argv[0]);
119042    if( zStr==0 ) return;
119043    nStr = sqlite3_value_bytes(argv[0]);
119044    assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
119045    zPattern = sqlite3_value_text(argv[1]);
119046    if( zPattern==0 ){
119047      assert( sqlite3_value_type(argv[1])==SQLITE_NULL
119048              || sqlite3_context_db_handle(context)->mallocFailed );
119049      return;
119050    }
119051    if( zPattern[0]==0 ){
119052      assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
119053      sqlite3_result_value(context, argv[0]);
119054      return;
119055    }
119056    nPattern = sqlite3_value_bytes(argv[1]);
119057    assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
119058    zRep = sqlite3_value_text(argv[2]);
119059    if( zRep==0 ) return;
119060    nRep = sqlite3_value_bytes(argv[2]);
119061    assert( zRep==sqlite3_value_text(argv[2]) );
119062    nOut = nStr + 1;
119063    assert( nOut<SQLITE_MAX_LENGTH );
119064    zOut = contextMalloc(context, (i64)nOut);
119065    if( zOut==0 ){
119066      return;
119067    }
119068    loopLimit = nStr - nPattern;  
119069    cntExpand = 0;
119070    for(i=j=0; i<=loopLimit; i++){
119071      if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
119072        zOut[j++] = zStr[i];
119073      }else{
119074        if( nRep>nPattern ){
119075          nOut += nRep - nPattern;
119076          testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
119077          testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
119078          if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
119079            sqlite3_result_error_toobig(context);
119080            sqlite3_free(zOut);
119081            return;
119082          }
119083          cntExpand++;
119084          if( (cntExpand&(cntExpand-1))==0 ){
119085            /* Grow the size of the output buffer only on substitutions
119086            ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
119087            u8 *zOld;
119088            zOld = zOut;
119089            zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
119090            if( zOut==0 ){
119091              sqlite3_result_error_nomem(context);
119092              sqlite3_free(zOld);
119093              return;
119094            }
119095          }
119096        }
119097        memcpy(&zOut[j], zRep, nRep);
119098        j += nRep;
119099        i += nPattern-1;
119100      }
119101    }
119102    assert( j+nStr-i+1<=nOut );
119103    memcpy(&zOut[j], &zStr[i], nStr-i);
119104    j += nStr - i;
119105    assert( j<=nOut );
119106    zOut[j] = 0;
119107    sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
119108  }
119109  
119110  /*
119111  ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
119112  ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
119113  */
119114  static void trimFunc(
119115    sqlite3_context *context,
119116    int argc,
119117    sqlite3_value **argv
119118  ){
119119    const unsigned char *zIn;         /* Input string */
119120    const unsigned char *zCharSet;    /* Set of characters to trim */
119121    int nIn;                          /* Number of bytes in input */
119122    int flags;                        /* 1: trimleft  2: trimright  3: trim */
119123    int i;                            /* Loop counter */
119124    unsigned char *aLen = 0;          /* Length of each character in zCharSet */
119125    unsigned char **azChar = 0;       /* Individual characters in zCharSet */
119126    int nChar;                        /* Number of characters in zCharSet */
119127  
119128    if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
119129      return;
119130    }
119131    zIn = sqlite3_value_text(argv[0]);
119132    if( zIn==0 ) return;
119133    nIn = sqlite3_value_bytes(argv[0]);
119134    assert( zIn==sqlite3_value_text(argv[0]) );
119135    if( argc==1 ){
119136      static const unsigned char lenOne[] = { 1 };
119137      static unsigned char * const azOne[] = { (u8*)" " };
119138      nChar = 1;
119139      aLen = (u8*)lenOne;
119140      azChar = (unsigned char **)azOne;
119141      zCharSet = 0;
119142    }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
119143      return;
119144    }else{
119145      const unsigned char *z;
119146      for(z=zCharSet, nChar=0; *z; nChar++){
119147        SQLITE_SKIP_UTF8(z);
119148      }
119149      if( nChar>0 ){
119150        azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
119151        if( azChar==0 ){
119152          return;
119153        }
119154        aLen = (unsigned char*)&azChar[nChar];
119155        for(z=zCharSet, nChar=0; *z; nChar++){
119156          azChar[nChar] = (unsigned char *)z;
119157          SQLITE_SKIP_UTF8(z);
119158          aLen[nChar] = (u8)(z - azChar[nChar]);
119159        }
119160      }
119161    }
119162    if( nChar>0 ){
119163      flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
119164      if( flags & 1 ){
119165        while( nIn>0 ){
119166          int len = 0;
119167          for(i=0; i<nChar; i++){
119168            len = aLen[i];
119169            if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
119170          }
119171          if( i>=nChar ) break;
119172          zIn += len;
119173          nIn -= len;
119174        }
119175      }
119176      if( flags & 2 ){
119177        while( nIn>0 ){
119178          int len = 0;
119179          for(i=0; i<nChar; i++){
119180            len = aLen[i];
119181            if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
119182          }
119183          if( i>=nChar ) break;
119184          nIn -= len;
119185        }
119186      }
119187      if( zCharSet ){
119188        sqlite3_free(azChar);
119189      }
119190    }
119191    sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
119192  }
119193  
119194  
119195  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
119196  /*
119197  ** The "unknown" function is automatically substituted in place of
119198  ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
119199  ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
119200  ** When the "sqlite3" command-line shell is built using this functionality,
119201  ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
119202  ** involving application-defined functions to be examined in a generic
119203  ** sqlite3 shell.
119204  */
119205  static void unknownFunc(
119206    sqlite3_context *context,
119207    int argc,
119208    sqlite3_value **argv
119209  ){
119210    /* no-op */
119211  }
119212  #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
119213  
119214  
119215  /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
119216  ** is only available if the SQLITE_SOUNDEX compile-time option is used
119217  ** when SQLite is built.
119218  */
119219  #ifdef SQLITE_SOUNDEX
119220  /*
119221  ** Compute the soundex encoding of a word.
119222  **
119223  ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
119224  ** soundex encoding of the string X. 
119225  */
119226  static void soundexFunc(
119227    sqlite3_context *context,
119228    int argc,
119229    sqlite3_value **argv
119230  ){
119231    char zResult[8];
119232    const u8 *zIn;
119233    int i, j;
119234    static const unsigned char iCode[] = {
119235      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119236      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119237      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119238      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119239      0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
119240      1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
119241      0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
119242      1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
119243    };
119244    assert( argc==1 );
119245    zIn = (u8*)sqlite3_value_text(argv[0]);
119246    if( zIn==0 ) zIn = (u8*)"";
119247    for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
119248    if( zIn[i] ){
119249      u8 prevcode = iCode[zIn[i]&0x7f];
119250      zResult[0] = sqlite3Toupper(zIn[i]);
119251      for(j=1; j<4 && zIn[i]; i++){
119252        int code = iCode[zIn[i]&0x7f];
119253        if( code>0 ){
119254          if( code!=prevcode ){
119255            prevcode = code;
119256            zResult[j++] = code + '0';
119257          }
119258        }else{
119259          prevcode = 0;
119260        }
119261      }
119262      while( j<4 ){
119263        zResult[j++] = '0';
119264      }
119265      zResult[j] = 0;
119266      sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
119267    }else{
119268      /* IMP: R-64894-50321 The string "?000" is returned if the argument
119269      ** is NULL or contains no ASCII alphabetic characters. */
119270      sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
119271    }
119272  }
119273  #endif /* SQLITE_SOUNDEX */
119274  
119275  #ifndef SQLITE_OMIT_LOAD_EXTENSION
119276  /*
119277  ** A function that loads a shared-library extension then returns NULL.
119278  */
119279  static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
119280    const char *zFile = (const char *)sqlite3_value_text(argv[0]);
119281    const char *zProc;
119282    sqlite3 *db = sqlite3_context_db_handle(context);
119283    char *zErrMsg = 0;
119284  
119285    /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
119286    ** flag is set.  See the sqlite3_enable_load_extension() API.
119287    */
119288    if( (db->flags & SQLITE_LoadExtFunc)==0 ){
119289      sqlite3_result_error(context, "not authorized", -1);
119290      return;
119291    }
119292  
119293    if( argc==2 ){
119294      zProc = (const char *)sqlite3_value_text(argv[1]);
119295    }else{
119296      zProc = 0;
119297    }
119298    if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
119299      sqlite3_result_error(context, zErrMsg, -1);
119300      sqlite3_free(zErrMsg);
119301    }
119302  }
119303  #endif
119304  
119305  
119306  /*
119307  ** An instance of the following structure holds the context of a
119308  ** sum() or avg() aggregate computation.
119309  */
119310  typedef struct SumCtx SumCtx;
119311  struct SumCtx {
119312    double rSum;      /* Floating point sum */
119313    i64 iSum;         /* Integer sum */   
119314    i64 cnt;          /* Number of elements summed */
119315    u8 overflow;      /* True if integer overflow seen */
119316    u8 approx;        /* True if non-integer value was input to the sum */
119317  };
119318  
119319  /*
119320  ** Routines used to compute the sum, average, and total.
119321  **
119322  ** The SUM() function follows the (broken) SQL standard which means
119323  ** that it returns NULL if it sums over no inputs.  TOTAL returns
119324  ** 0.0 in that case.  In addition, TOTAL always returns a float where
119325  ** SUM might return an integer if it never encounters a floating point
119326  ** value.  TOTAL never fails, but SUM might through an exception if
119327  ** it overflows an integer.
119328  */
119329  static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
119330    SumCtx *p;
119331    int type;
119332    assert( argc==1 );
119333    UNUSED_PARAMETER(argc);
119334    p = sqlite3_aggregate_context(context, sizeof(*p));
119335    type = sqlite3_value_numeric_type(argv[0]);
119336    if( p && type!=SQLITE_NULL ){
119337      p->cnt++;
119338      if( type==SQLITE_INTEGER ){
119339        i64 v = sqlite3_value_int64(argv[0]);
119340        p->rSum += v;
119341        if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
119342          p->approx = p->overflow = 1;
119343        }
119344      }else{
119345        p->rSum += sqlite3_value_double(argv[0]);
119346        p->approx = 1;
119347      }
119348    }
119349  }
119350  #ifndef SQLITE_OMIT_WINDOWFUNC
119351  static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
119352    SumCtx *p;
119353    int type;
119354    assert( argc==1 );
119355    UNUSED_PARAMETER(argc);
119356    p = sqlite3_aggregate_context(context, sizeof(*p));
119357    type = sqlite3_value_numeric_type(argv[0]);
119358    /* p is always non-NULL because sumStep() will have been called first
119359    ** to initialize it */
119360    if( ALWAYS(p) && type!=SQLITE_NULL ){
119361      assert( p->cnt>0 );
119362      p->cnt--;
119363      assert( type==SQLITE_INTEGER || p->approx );
119364      if( type==SQLITE_INTEGER && p->approx==0 ){
119365        i64 v = sqlite3_value_int64(argv[0]);
119366        p->rSum -= v;
119367        p->iSum -= v;
119368      }else{
119369        p->rSum -= sqlite3_value_double(argv[0]);
119370      }
119371    }
119372  }
119373  #else
119374  # define sumInverse 0
119375  #endif /* SQLITE_OMIT_WINDOWFUNC */
119376  static void sumFinalize(sqlite3_context *context){
119377    SumCtx *p;
119378    p = sqlite3_aggregate_context(context, 0);
119379    if( p && p->cnt>0 ){
119380      if( p->overflow ){
119381        sqlite3_result_error(context,"integer overflow",-1);
119382      }else if( p->approx ){
119383        sqlite3_result_double(context, p->rSum);
119384      }else{
119385        sqlite3_result_int64(context, p->iSum);
119386      }
119387    }
119388  }
119389  static void avgFinalize(sqlite3_context *context){
119390    SumCtx *p;
119391    p = sqlite3_aggregate_context(context, 0);
119392    if( p && p->cnt>0 ){
119393      sqlite3_result_double(context, p->rSum/(double)p->cnt);
119394    }
119395  }
119396  static void totalFinalize(sqlite3_context *context){
119397    SumCtx *p;
119398    p = sqlite3_aggregate_context(context, 0);
119399    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
119400    sqlite3_result_double(context, p ? p->rSum : (double)0);
119401  }
119402  
119403  /*
119404  ** The following structure keeps track of state information for the
119405  ** count() aggregate function.
119406  */
119407  typedef struct CountCtx CountCtx;
119408  struct CountCtx {
119409    i64 n;
119410  #ifdef SQLITE_DEBUG
119411    int bInverse;                   /* True if xInverse() ever called */
119412  #endif
119413  };
119414  
119415  /*
119416  ** Routines to implement the count() aggregate function.
119417  */
119418  static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
119419    CountCtx *p;
119420    p = sqlite3_aggregate_context(context, sizeof(*p));
119421    if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
119422      p->n++;
119423    }
119424  
119425  #ifndef SQLITE_OMIT_DEPRECATED
119426    /* The sqlite3_aggregate_count() function is deprecated.  But just to make
119427    ** sure it still operates correctly, verify that its count agrees with our 
119428    ** internal count when using count(*) and when the total count can be
119429    ** expressed as a 32-bit integer. */
119430    assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
119431            || p->n==sqlite3_aggregate_count(context) );
119432  #endif
119433  }   
119434  static void countFinalize(sqlite3_context *context){
119435    CountCtx *p;
119436    p = sqlite3_aggregate_context(context, 0);
119437    sqlite3_result_int64(context, p ? p->n : 0);
119438  }
119439  #ifndef SQLITE_OMIT_WINDOWFUNC
119440  static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
119441    CountCtx *p;
119442    p = sqlite3_aggregate_context(ctx, sizeof(*p));
119443    /* p is always non-NULL since countStep() will have been called first */
119444    if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
119445      p->n--;
119446  #ifdef SQLITE_DEBUG
119447      p->bInverse = 1;
119448  #endif
119449    }
119450  }   
119451  #else
119452  # define countInverse 0
119453  #endif /* SQLITE_OMIT_WINDOWFUNC */
119454  
119455  /*
119456  ** Routines to implement min() and max() aggregate functions.
119457  */
119458  static void minmaxStep(
119459    sqlite3_context *context, 
119460    int NotUsed, 
119461    sqlite3_value **argv
119462  ){
119463    Mem *pArg  = (Mem *)argv[0];
119464    Mem *pBest;
119465    UNUSED_PARAMETER(NotUsed);
119466  
119467    pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
119468    if( !pBest ) return;
119469  
119470    if( sqlite3_value_type(pArg)==SQLITE_NULL ){
119471      if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
119472    }else if( pBest->flags ){
119473      int max;
119474      int cmp;
119475      CollSeq *pColl = sqlite3GetFuncCollSeq(context);
119476      /* This step function is used for both the min() and max() aggregates,
119477      ** the only difference between the two being that the sense of the
119478      ** comparison is inverted. For the max() aggregate, the
119479      ** sqlite3_user_data() function returns (void *)-1. For min() it
119480      ** returns (void *)db, where db is the sqlite3* database pointer.
119481      ** Therefore the next statement sets variable 'max' to 1 for the max()
119482      ** aggregate, or 0 for min().
119483      */
119484      max = sqlite3_user_data(context)!=0;
119485      cmp = sqlite3MemCompare(pBest, pArg, pColl);
119486      if( (max && cmp<0) || (!max && cmp>0) ){
119487        sqlite3VdbeMemCopy(pBest, pArg);
119488      }else{
119489        sqlite3SkipAccumulatorLoad(context);
119490      }
119491    }else{
119492      pBest->db = sqlite3_context_db_handle(context);
119493      sqlite3VdbeMemCopy(pBest, pArg);
119494    }
119495  }
119496  static void minMaxValueFinalize(sqlite3_context *context, int bValue){
119497    sqlite3_value *pRes;
119498    pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
119499    if( pRes ){
119500      if( pRes->flags ){
119501        sqlite3_result_value(context, pRes);
119502      }
119503      if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
119504    }
119505  }
119506  #ifndef SQLITE_OMIT_WINDOWFUNC
119507  static void minMaxValue(sqlite3_context *context){
119508    minMaxValueFinalize(context, 1);
119509  }
119510  #else
119511  # define minMaxValue 0
119512  #endif /* SQLITE_OMIT_WINDOWFUNC */
119513  static void minMaxFinalize(sqlite3_context *context){
119514    minMaxValueFinalize(context, 0);
119515  }
119516  
119517  /*
119518  ** group_concat(EXPR, ?SEPARATOR?)
119519  */
119520  static void groupConcatStep(
119521    sqlite3_context *context,
119522    int argc,
119523    sqlite3_value **argv
119524  ){
119525    const char *zVal;
119526    StrAccum *pAccum;
119527    const char *zSep;
119528    int nVal, nSep;
119529    assert( argc==1 || argc==2 );
119530    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
119531    pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
119532  
119533    if( pAccum ){
119534      sqlite3 *db = sqlite3_context_db_handle(context);
119535      int firstTerm = pAccum->mxAlloc==0;
119536      pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
119537      if( !firstTerm ){
119538        if( argc==2 ){
119539          zSep = (char*)sqlite3_value_text(argv[1]);
119540          nSep = sqlite3_value_bytes(argv[1]);
119541        }else{
119542          zSep = ",";
119543          nSep = 1;
119544        }
119545        if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
119546      }
119547      zVal = (char*)sqlite3_value_text(argv[0]);
119548      nVal = sqlite3_value_bytes(argv[0]);
119549      if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
119550    }
119551  }
119552  #ifndef SQLITE_OMIT_WINDOWFUNC
119553  static void groupConcatInverse(
119554    sqlite3_context *context,
119555    int argc,
119556    sqlite3_value **argv
119557  ){
119558    int n;
119559    StrAccum *pAccum;
119560    assert( argc==1 || argc==2 );
119561    if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
119562    pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
119563    /* pAccum is always non-NULL since groupConcatStep() will have always
119564    ** run frist to initialize it */
119565    if( ALWAYS(pAccum) ){
119566      n = sqlite3_value_bytes(argv[0]);
119567      if( argc==2 ){
119568        n += sqlite3_value_bytes(argv[1]);
119569      }else{
119570        n++;
119571      }
119572      if( n>=(int)pAccum->nChar ){
119573        pAccum->nChar = 0;
119574      }else{
119575        pAccum->nChar -= n;
119576        memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
119577      }
119578      if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
119579    }
119580  }
119581  #else
119582  # define groupConcatInverse 0
119583  #endif /* SQLITE_OMIT_WINDOWFUNC */
119584  static void groupConcatFinalize(sqlite3_context *context){
119585    StrAccum *pAccum;
119586    pAccum = sqlite3_aggregate_context(context, 0);
119587    if( pAccum ){
119588      if( pAccum->accError==SQLITE_TOOBIG ){
119589        sqlite3_result_error_toobig(context);
119590      }else if( pAccum->accError==SQLITE_NOMEM ){
119591        sqlite3_result_error_nomem(context);
119592      }else{    
119593        sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
119594                            sqlite3_free);
119595      }
119596    }
119597  }
119598  #ifndef SQLITE_OMIT_WINDOWFUNC
119599  static void groupConcatValue(sqlite3_context *context){
119600    sqlite3_str *pAccum;
119601    pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
119602    if( pAccum ){
119603      if( pAccum->accError==SQLITE_TOOBIG ){
119604        sqlite3_result_error_toobig(context);
119605      }else if( pAccum->accError==SQLITE_NOMEM ){
119606        sqlite3_result_error_nomem(context);
119607      }else{    
119608        const char *zText = sqlite3_str_value(pAccum);
119609        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
119610      }
119611    }
119612  }
119613  #else
119614  # define groupConcatValue 0
119615  #endif /* SQLITE_OMIT_WINDOWFUNC */
119616  
119617  /*
119618  ** This routine does per-connection function registration.  Most
119619  ** of the built-in functions above are part of the global function set.
119620  ** This routine only deals with those that are not global.
119621  */
119622  SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
119623    int rc = sqlite3_overload_function(db, "MATCH", 2);
119624    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
119625    if( rc==SQLITE_NOMEM ){
119626      sqlite3OomFault(db);
119627    }
119628  }
119629  
119630  /*
119631  ** Set the LIKEOPT flag on the 2-argument function with the given name.
119632  */
119633  static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
119634    FuncDef *pDef;
119635    pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
119636    if( ALWAYS(pDef) ){
119637      pDef->funcFlags |= flagVal;
119638    }
119639  }
119640  
119641  /*
119642  ** Register the built-in LIKE and GLOB functions.  The caseSensitive
119643  ** parameter determines whether or not the LIKE operator is case
119644  ** sensitive.  GLOB is always case sensitive.
119645  */
119646  SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
119647    struct compareInfo *pInfo;
119648    if( caseSensitive ){
119649      pInfo = (struct compareInfo*)&likeInfoAlt;
119650    }else{
119651      pInfo = (struct compareInfo*)&likeInfoNorm;
119652    }
119653    sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
119654    sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
119655    sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
119656        (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0, 0, 0);
119657    setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
119658    setLikeOptFlag(db, "like", 
119659        caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
119660  }
119661  
119662  /*
119663  ** pExpr points to an expression which implements a function.  If
119664  ** it is appropriate to apply the LIKE optimization to that function
119665  ** then set aWc[0] through aWc[2] to the wildcard characters and the
119666  ** escape character and then return TRUE.  If the function is not a 
119667  ** LIKE-style function then return FALSE.
119668  **
119669  ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
119670  ** operator if c is a string literal that is exactly one byte in length.
119671  ** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
119672  ** no ESCAPE clause.
119673  **
119674  ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
119675  ** the function (default for LIKE).  If the function makes the distinction
119676  ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
119677  ** false.
119678  */
119679  SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
119680    FuncDef *pDef;
119681    int nExpr;
119682    if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
119683      return 0;
119684    }
119685    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
119686    nExpr = pExpr->x.pList->nExpr;
119687    pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
119688    if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
119689      return 0;
119690    }
119691    if( nExpr<3 ){
119692      aWc[3] = 0;
119693    }else{
119694      Expr *pEscape = pExpr->x.pList->a[2].pExpr;
119695      char *zEscape;
119696      if( pEscape->op!=TK_STRING ) return 0;
119697      zEscape = pEscape->u.zToken;
119698      if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
119699      aWc[3] = zEscape[0];
119700    }
119701  
119702    /* The memcpy() statement assumes that the wildcard characters are
119703    ** the first three statements in the compareInfo structure.  The
119704    ** asserts() that follow verify that assumption
119705    */
119706    memcpy(aWc, pDef->pUserData, 3);
119707    assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
119708    assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
119709    assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
119710    *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
119711    return 1;
119712  }
119713  
119714  /*
119715  ** All of the FuncDef structures in the aBuiltinFunc[] array above
119716  ** to the global function hash table.  This occurs at start-time (as
119717  ** a consequence of calling sqlite3_initialize()).
119718  **
119719  ** After this routine runs
119720  */
119721  SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
119722    /*
119723    ** The following array holds FuncDef structures for all of the functions
119724    ** defined in this file.
119725    **
119726    ** The array cannot be constant since changes are made to the
119727    ** FuncDef.pHash elements at start-time.  The elements of this array
119728    ** are read-only after initialization is complete.
119729    **
119730    ** For peak efficiency, put the most frequently used function last.
119731    */
119732    static FuncDef aBuiltinFunc[] = {
119733  #ifdef SQLITE_SOUNDEX
119734      FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
119735  #endif
119736  #ifndef SQLITE_OMIT_LOAD_EXTENSION
119737      VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
119738      VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
119739  #endif
119740  #if SQLITE_USER_AUTHENTICATION
119741      FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
119742  #endif
119743  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
119744      DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
119745      DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
119746  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
119747      FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
119748      FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
119749      FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
119750  #ifdef SQLITE_DEBUG
119751      FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
119752  #endif
119753  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
119754      FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|
119755                                                       SQLITE_FUNC_TYPEOF),
119756  #endif
119757      FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
119758      FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
119759      FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
119760      FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
119761      FUNCTION(trim,               1, 3, 0, trimFunc         ),
119762      FUNCTION(trim,               2, 3, 0, trimFunc         ),
119763      FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
119764      FUNCTION(min,                0, 0, 1, 0                ),
119765      WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
119766                                            SQLITE_FUNC_MINMAX ),
119767      FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
119768      FUNCTION(max,                0, 1, 1, 0                ),
119769      WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
119770                                            SQLITE_FUNC_MINMAX ),
119771      FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
119772      FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
119773      FUNCTION(instr,              2, 0, 0, instrFunc        ),
119774      FUNCTION(printf,            -1, 0, 0, printfFunc       ),
119775      FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
119776      FUNCTION(char,              -1, 0, 0, charFunc         ),
119777      FUNCTION(abs,                1, 0, 0, absFunc          ),
119778  #ifndef SQLITE_OMIT_FLOATING_POINT
119779      FUNCTION(round,              1, 0, 0, roundFunc        ),
119780      FUNCTION(round,              2, 0, 0, roundFunc        ),
119781  #endif
119782      FUNCTION(upper,              1, 0, 0, upperFunc        ),
119783      FUNCTION(lower,              1, 0, 0, lowerFunc        ),
119784      FUNCTION(hex,                1, 0, 0, hexFunc          ),
119785      FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
119786      /*
119787      VFUNCTION(random,            0, 0, 0, randomFunc       ),
119788      VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
119789      */
119790      FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
119791      /*
119792      DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
119793      DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
119794      FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
119795      */
119796      FUNCTION(quote,              1, 0, 0, quoteFunc        ),
119797      /*
119798      VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
119799      VFUNCTION(changes,           0, 0, 0, changes          ),
119800      VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
119801      */
119802      FUNCTION(replace,            3, 0, 0, replaceFunc      ),
119803      /*
119804      FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
119805      */
119806      FUNCTION(substr,             2, 0, 0, substrFunc       ),
119807      FUNCTION(substr,             3, 0, 0, substrFunc       ),
119808      WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
119809      WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
119810      WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
119811      WAGGREGATE(count, 0,0,0, countStep, 
119812          countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT  ),
119813      WAGGREGATE(count, 1,0,0, countStep, 
119814          countFinalize, countFinalize, countInverse, 0  ),
119815      WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, 
119816          groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
119817      WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, 
119818          groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
119819    
119820      LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
119821  #ifdef SQLITE_CASE_SENSITIVE_LIKE
119822      LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
119823      LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
119824  #else
119825      LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
119826      LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
119827  #endif
119828  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
119829      FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
119830  #endif
119831      FUNCTION(coalesce,           1, 0, 0, 0                ),
119832      FUNCTION(coalesce,           0, 0, 0, 0                ),
119833      FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
119834    };
119835  #ifndef SQLITE_OMIT_ALTERTABLE
119836    sqlite3AlterFunctions();
119837  #endif
119838    sqlite3WindowFunctions();
119839  #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
119840    sqlite3AnalyzeFunctions();
119841  #endif
119842    sqlite3RegisterDateTimeFunctions();
119843    sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
119844  
119845  #if 0  /* Enable to print out how the built-in functions are hashed */
119846    {
119847      int i;
119848      FuncDef *p;
119849      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
119850        printf("FUNC-HASH %02d:", i);
119851        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
119852          int n = sqlite3Strlen30(p->zName);
119853          int h = p->zName[0] + n;
119854          printf(" %s(%d)", p->zName, h);
119855        }
119856        printf("\n");
119857      }
119858    }
119859  #endif
119860  }
119861  
119862  /************** End of func.c ************************************************/
119863  /************** Begin file fkey.c ********************************************/
119864  /*
119865  **
119866  ** The author disclaims copyright to this source code.  In place of
119867  ** a legal notice, here is a blessing:
119868  **
119869  **    May you do good and not evil.
119870  **    May you find forgiveness for yourself and forgive others.
119871  **    May you share freely, never taking more than you give.
119872  **
119873  *************************************************************************
119874  ** This file contains code used by the compiler to add foreign key
119875  ** support to compiled SQL statements.
119876  */
119877  /* #include "sqliteInt.h" */
119878  
119879  #ifndef SQLITE_OMIT_FOREIGN_KEY
119880  #ifndef SQLITE_OMIT_TRIGGER
119881  
119882  /*
119883  ** Deferred and Immediate FKs
119884  ** --------------------------
119885  **
119886  ** Foreign keys in SQLite come in two flavours: deferred and immediate.
119887  ** If an immediate foreign key constraint is violated,
119888  ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
119889  ** statement transaction rolled back. If a 
119890  ** deferred foreign key constraint is violated, no action is taken 
119891  ** immediately. However if the application attempts to commit the 
119892  ** transaction before fixing the constraint violation, the attempt fails.
119893  **
119894  ** Deferred constraints are implemented using a simple counter associated
119895  ** with the database handle. The counter is set to zero each time a 
119896  ** database transaction is opened. Each time a statement is executed 
119897  ** that causes a foreign key violation, the counter is incremented. Each
119898  ** time a statement is executed that removes an existing violation from
119899  ** the database, the counter is decremented. When the transaction is
119900  ** committed, the commit fails if the current value of the counter is
119901  ** greater than zero. This scheme has two big drawbacks:
119902  **
119903  **   * When a commit fails due to a deferred foreign key constraint, 
119904  **     there is no way to tell which foreign constraint is not satisfied,
119905  **     or which row it is not satisfied for.
119906  **
119907  **   * If the database contains foreign key violations when the 
119908  **     transaction is opened, this may cause the mechanism to malfunction.
119909  **
119910  ** Despite these problems, this approach is adopted as it seems simpler
119911  ** than the alternatives.
119912  **
119913  ** INSERT operations:
119914  **
119915  **   I.1) For each FK for which the table is the child table, search
119916  **        the parent table for a match. If none is found increment the
119917  **        constraint counter.
119918  **
119919  **   I.2) For each FK for which the table is the parent table, 
119920  **        search the child table for rows that correspond to the new
119921  **        row in the parent table. Decrement the counter for each row
119922  **        found (as the constraint is now satisfied).
119923  **
119924  ** DELETE operations:
119925  **
119926  **   D.1) For each FK for which the table is the child table, 
119927  **        search the parent table for a row that corresponds to the 
119928  **        deleted row in the child table. If such a row is not found, 
119929  **        decrement the counter.
119930  **
119931  **   D.2) For each FK for which the table is the parent table, search 
119932  **        the child table for rows that correspond to the deleted row 
119933  **        in the parent table. For each found increment the counter.
119934  **
119935  ** UPDATE operations:
119936  **
119937  **   An UPDATE command requires that all 4 steps above are taken, but only
119938  **   for FK constraints for which the affected columns are actually 
119939  **   modified (values must be compared at runtime).
119940  **
119941  ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
119942  ** This simplifies the implementation a bit.
119943  **
119944  ** For the purposes of immediate FK constraints, the OR REPLACE conflict
119945  ** resolution is considered to delete rows before the new row is inserted.
119946  ** If a delete caused by OR REPLACE violates an FK constraint, an exception
119947  ** is thrown, even if the FK constraint would be satisfied after the new 
119948  ** row is inserted.
119949  **
119950  ** Immediate constraints are usually handled similarly. The only difference 
119951  ** is that the counter used is stored as part of each individual statement
119952  ** object (struct Vdbe). If, after the statement has run, its immediate
119953  ** constraint counter is greater than zero,
119954  ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
119955  ** and the statement transaction is rolled back. An exception is an INSERT
119956  ** statement that inserts a single row only (no triggers). In this case,
119957  ** instead of using a counter, an exception is thrown immediately if the
119958  ** INSERT violates a foreign key constraint. This is necessary as such
119959  ** an INSERT does not open a statement transaction.
119960  **
119961  ** TODO: How should dropping a table be handled? How should renaming a 
119962  ** table be handled?
119963  **
119964  **
119965  ** Query API Notes
119966  ** ---------------
119967  **
119968  ** Before coding an UPDATE or DELETE row operation, the code-generator
119969  ** for those two operations needs to know whether or not the operation
119970  ** requires any FK processing and, if so, which columns of the original
119971  ** row are required by the FK processing VDBE code (i.e. if FKs were
119972  ** implemented using triggers, which of the old.* columns would be 
119973  ** accessed). No information is required by the code-generator before
119974  ** coding an INSERT operation. The functions used by the UPDATE/DELETE
119975  ** generation code to query for this information are:
119976  **
119977  **   sqlite3FkRequired() - Test to see if FK processing is required.
119978  **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
119979  **
119980  **
119981  ** Externally accessible module functions
119982  ** --------------------------------------
119983  **
119984  **   sqlite3FkCheck()    - Check for foreign key violations.
119985  **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
119986  **   sqlite3FkDelete()   - Delete an FKey structure.
119987  */
119988  
119989  /*
119990  ** VDBE Calling Convention
119991  ** -----------------------
119992  **
119993  ** Example:
119994  **
119995  **   For the following INSERT statement:
119996  **
119997  **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
119998  **     INSERT INTO t1 VALUES(1, 2, 3.1);
119999  **
120000  **   Register (x):        2    (type integer)
120001  **   Register (x+1):      1    (type integer)
120002  **   Register (x+2):      NULL (type NULL)
120003  **   Register (x+3):      3.1  (type real)
120004  */
120005  
120006  /*
120007  ** A foreign key constraint requires that the key columns in the parent
120008  ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
120009  ** Given that pParent is the parent table for foreign key constraint pFKey, 
120010  ** search the schema for a unique index on the parent key columns. 
120011  **
120012  ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
120013  ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
120014  ** is set to point to the unique index. 
120015  ** 
120016  ** If the parent key consists of a single column (the foreign key constraint
120017  ** is not a composite foreign key), output variable *paiCol is set to NULL.
120018  ** Otherwise, it is set to point to an allocated array of size N, where
120019  ** N is the number of columns in the parent key. The first element of the
120020  ** array is the index of the child table column that is mapped by the FK
120021  ** constraint to the parent table column stored in the left-most column
120022  ** of index *ppIdx. The second element of the array is the index of the
120023  ** child table column that corresponds to the second left-most column of
120024  ** *ppIdx, and so on.
120025  **
120026  ** If the required index cannot be found, either because:
120027  **
120028  **   1) The named parent key columns do not exist, or
120029  **
120030  **   2) The named parent key columns do exist, but are not subject to a
120031  **      UNIQUE or PRIMARY KEY constraint, or
120032  **
120033  **   3) No parent key columns were provided explicitly as part of the
120034  **      foreign key definition, and the parent table does not have a
120035  **      PRIMARY KEY, or
120036  **
120037  **   4) No parent key columns were provided explicitly as part of the
120038  **      foreign key definition, and the PRIMARY KEY of the parent table 
120039  **      consists of a different number of columns to the child key in 
120040  **      the child table.
120041  **
120042  ** then non-zero is returned, and a "foreign key mismatch" error loaded
120043  ** into pParse. If an OOM error occurs, non-zero is returned and the
120044  ** pParse->db->mallocFailed flag is set.
120045  */
120046  SQLITE_PRIVATE int sqlite3FkLocateIndex(
120047    Parse *pParse,                  /* Parse context to store any error in */
120048    Table *pParent,                 /* Parent table of FK constraint pFKey */
120049    FKey *pFKey,                    /* Foreign key to find index for */
120050    Index **ppIdx,                  /* OUT: Unique index on parent table */
120051    int **paiCol                    /* OUT: Map of index columns in pFKey */
120052  ){
120053    Index *pIdx = 0;                    /* Value to return via *ppIdx */
120054    int *aiCol = 0;                     /* Value to return via *paiCol */
120055    int nCol = pFKey->nCol;             /* Number of columns in parent key */
120056    char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
120057  
120058    /* The caller is responsible for zeroing output parameters. */
120059    assert( ppIdx && *ppIdx==0 );
120060    assert( !paiCol || *paiCol==0 );
120061    assert( pParse );
120062  
120063    /* If this is a non-composite (single column) foreign key, check if it 
120064    ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
120065    ** and *paiCol set to zero and return early. 
120066    **
120067    ** Otherwise, for a composite foreign key (more than one column), allocate
120068    ** space for the aiCol array (returned via output parameter *paiCol).
120069    ** Non-composite foreign keys do not require the aiCol array.
120070    */
120071    if( nCol==1 ){
120072      /* The FK maps to the IPK if any of the following are true:
120073      **
120074      **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
120075      **      mapped to the primary key of table pParent, or
120076      **   2) The FK is explicitly mapped to a column declared as INTEGER
120077      **      PRIMARY KEY.
120078      */
120079      if( pParent->iPKey>=0 ){
120080        if( !zKey ) return 0;
120081        if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
120082      }
120083    }else if( paiCol ){
120084      assert( nCol>1 );
120085      aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
120086      if( !aiCol ) return 1;
120087      *paiCol = aiCol;
120088    }
120089  
120090    for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
120091      if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ 
120092        /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
120093        ** of columns. If each indexed column corresponds to a foreign key
120094        ** column of pFKey, then this index is a winner.  */
120095  
120096        if( zKey==0 ){
120097          /* If zKey is NULL, then this foreign key is implicitly mapped to 
120098          ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
120099          ** identified by the test.  */
120100          if( IsPrimaryKeyIndex(pIdx) ){
120101            if( aiCol ){
120102              int i;
120103              for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
120104            }
120105            break;
120106          }
120107        }else{
120108          /* If zKey is non-NULL, then this foreign key was declared to
120109          ** map to an explicit list of columns in table pParent. Check if this
120110          ** index matches those columns. Also, check that the index uses
120111          ** the default collation sequences for each column. */
120112          int i, j;
120113          for(i=0; i<nCol; i++){
120114            i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
120115            const char *zDfltColl;            /* Def. collation for column */
120116            char *zIdxCol;                    /* Name of indexed column */
120117  
120118            if( iCol<0 ) break; /* No foreign keys against expression indexes */
120119  
120120            /* If the index uses a collation sequence that is different from
120121            ** the default collation sequence for the column, this index is
120122            ** unusable. Bail out early in this case.  */
120123            zDfltColl = pParent->aCol[iCol].zColl;
120124            if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
120125            if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
120126  
120127            zIdxCol = pParent->aCol[iCol].zName;
120128            for(j=0; j<nCol; j++){
120129              if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
120130                if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
120131                break;
120132              }
120133            }
120134            if( j==nCol ) break;
120135          }
120136          if( i==nCol ) break;      /* pIdx is usable */
120137        }
120138      }
120139    }
120140  
120141    if( !pIdx ){
120142      if( !pParse->disableTriggers ){
120143        sqlite3ErrorMsg(pParse,
120144             "foreign key mismatch - \"%w\" referencing \"%w\"",
120145             pFKey->pFrom->zName, pFKey->zTo);
120146      }
120147      sqlite3DbFree(pParse->db, aiCol);
120148      return 1;
120149    }
120150  
120151    *ppIdx = pIdx;
120152    return 0;
120153  }
120154  
120155  /*
120156  ** This function is called when a row is inserted into or deleted from the 
120157  ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
120158  ** on the child table of pFKey, this function is invoked twice for each row
120159  ** affected - once to "delete" the old row, and then again to "insert" the
120160  ** new row.
120161  **
120162  ** Each time it is called, this function generates VDBE code to locate the
120163  ** row in the parent table that corresponds to the row being inserted into 
120164  ** or deleted from the child table. If the parent row can be found, no 
120165  ** special action is taken. Otherwise, if the parent row can *not* be
120166  ** found in the parent table:
120167  **
120168  **   Operation | FK type   | Action taken
120169  **   --------------------------------------------------------------------------
120170  **   INSERT      immediate   Increment the "immediate constraint counter".
120171  **
120172  **   DELETE      immediate   Decrement the "immediate constraint counter".
120173  **
120174  **   INSERT      deferred    Increment the "deferred constraint counter".
120175  **
120176  **   DELETE      deferred    Decrement the "deferred constraint counter".
120177  **
120178  ** These operations are identified in the comment at the top of this file 
120179  ** (fkey.c) as "I.1" and "D.1".
120180  */
120181  static void fkLookupParent(
120182    Parse *pParse,        /* Parse context */
120183    int iDb,              /* Index of database housing pTab */
120184    Table *pTab,          /* Parent table of FK pFKey */
120185    Index *pIdx,          /* Unique index on parent key columns in pTab */
120186    FKey *pFKey,          /* Foreign key constraint */
120187    int *aiCol,           /* Map from parent key columns to child table columns */
120188    int regData,          /* Address of array containing child table row */
120189    int nIncr,            /* Increment constraint counter by this */
120190    int isIgnore          /* If true, pretend pTab contains all NULL values */
120191  ){
120192    int i;                                    /* Iterator variable */
120193    Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
120194    int iCur = pParse->nTab - 1;              /* Cursor number to use */
120195    int iOk = sqlite3VdbeMakeLabel(pParse);   /* jump here if parent key found */
120196  
120197    sqlite3VdbeVerifyAbortable(v,
120198      (!pFKey->isDeferred
120199        && !(pParse->db->flags & SQLITE_DeferFKs)
120200        && !pParse->pToplevel 
120201        && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
120202  
120203    /* If nIncr is less than zero, then check at runtime if there are any
120204    ** outstanding constraints to resolve. If there are not, there is no need
120205    ** to check if deleting this row resolves any outstanding violations.
120206    **
120207    ** Check if any of the key columns in the child table row are NULL. If 
120208    ** any are, then the constraint is considered satisfied. No need to 
120209    ** search for a matching row in the parent table.  */
120210    if( nIncr<0 ){
120211      sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
120212      VdbeCoverage(v);
120213    }
120214    for(i=0; i<pFKey->nCol; i++){
120215      int iReg = aiCol[i] + regData + 1;
120216      sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
120217    }
120218  
120219    if( isIgnore==0 ){
120220      if( pIdx==0 ){
120221        /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
120222        ** column of the parent table (table pTab).  */
120223        int iMustBeInt;               /* Address of MustBeInt instruction */
120224        int regTemp = sqlite3GetTempReg(pParse);
120225    
120226        /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
120227        ** apply the affinity of the parent key). If this fails, then there
120228        ** is no matching parent key. Before using MustBeInt, make a copy of
120229        ** the value. Otherwise, the value inserted into the child key column
120230        ** will have INTEGER affinity applied to it, which may not be correct.  */
120231        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
120232        iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
120233        VdbeCoverage(v);
120234    
120235        /* If the parent table is the same as the child table, and we are about
120236        ** to increment the constraint-counter (i.e. this is an INSERT operation),
120237        ** then check if the row being inserted matches itself. If so, do not
120238        ** increment the constraint-counter.  */
120239        if( pTab==pFKey->pFrom && nIncr==1 ){
120240          sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
120241          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
120242        }
120243    
120244        sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
120245        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
120246        sqlite3VdbeGoto(v, iOk);
120247        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
120248        sqlite3VdbeJumpHere(v, iMustBeInt);
120249        sqlite3ReleaseTempReg(pParse, regTemp);
120250      }else{
120251        int nCol = pFKey->nCol;
120252        int regTemp = sqlite3GetTempRange(pParse, nCol);
120253        int regRec = sqlite3GetTempReg(pParse);
120254    
120255        sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
120256        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
120257        for(i=0; i<nCol; i++){
120258          sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
120259        }
120260    
120261        /* If the parent table is the same as the child table, and we are about
120262        ** to increment the constraint-counter (i.e. this is an INSERT operation),
120263        ** then check if the row being inserted matches itself. If so, do not
120264        ** increment the constraint-counter. 
120265        **
120266        ** If any of the parent-key values are NULL, then the row cannot match 
120267        ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
120268        ** of the parent-key values are NULL (at this point it is known that
120269        ** none of the child key values are).
120270        */
120271        if( pTab==pFKey->pFrom && nIncr==1 ){
120272          int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
120273          for(i=0; i<nCol; i++){
120274            int iChild = aiCol[i]+1+regData;
120275            int iParent = pIdx->aiColumn[i]+1+regData;
120276            assert( pIdx->aiColumn[i]>=0 );
120277            assert( aiCol[i]!=pTab->iPKey );
120278            if( pIdx->aiColumn[i]==pTab->iPKey ){
120279              /* The parent key is a composite key that includes the IPK column */
120280              iParent = regData;
120281            }
120282            sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
120283            sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
120284          }
120285          sqlite3VdbeGoto(v, iOk);
120286        }
120287    
120288        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
120289                          sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
120290        sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
120291    
120292        sqlite3ReleaseTempReg(pParse, regRec);
120293        sqlite3ReleaseTempRange(pParse, regTemp, nCol);
120294      }
120295    }
120296  
120297    if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
120298     && !pParse->pToplevel 
120299     && !pParse->isMultiWrite 
120300    ){
120301      /* Special case: If this is an INSERT statement that will insert exactly
120302      ** one row into the table, raise a constraint immediately instead of
120303      ** incrementing a counter. This is necessary as the VM code is being
120304      ** generated for will not open a statement transaction.  */
120305      assert( nIncr==1 );
120306      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
120307          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
120308    }else{
120309      if( nIncr>0 && pFKey->isDeferred==0 ){
120310        sqlite3MayAbort(pParse);
120311      }
120312      sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
120313    }
120314  
120315    sqlite3VdbeResolveLabel(v, iOk);
120316    sqlite3VdbeAddOp1(v, OP_Close, iCur);
120317  }
120318  
120319  
120320  /*
120321  ** Return an Expr object that refers to a memory register corresponding
120322  ** to column iCol of table pTab.
120323  **
120324  ** regBase is the first of an array of register that contains the data
120325  ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
120326  ** column.  regBase+2 holds the second column, and so forth.
120327  */
120328  static Expr *exprTableRegister(
120329    Parse *pParse,     /* Parsing and code generating context */
120330    Table *pTab,       /* The table whose content is at r[regBase]... */
120331    int regBase,       /* Contents of table pTab */
120332    i16 iCol           /* Which column of pTab is desired */
120333  ){
120334    Expr *pExpr;
120335    Column *pCol;
120336    const char *zColl;
120337    sqlite3 *db = pParse->db;
120338  
120339    pExpr = sqlite3Expr(db, TK_REGISTER, 0);
120340    if( pExpr ){
120341      if( iCol>=0 && iCol!=pTab->iPKey ){
120342        pCol = &pTab->aCol[iCol];
120343        pExpr->iTable = regBase + iCol + 1;
120344        pExpr->affinity = pCol->affinity;
120345        zColl = pCol->zColl;
120346        if( zColl==0 ) zColl = db->pDfltColl->zName;
120347        pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
120348      }else{
120349        pExpr->iTable = regBase;
120350        pExpr->affinity = SQLITE_AFF_INTEGER;
120351      }
120352    }
120353    return pExpr;
120354  }
120355  
120356  /*
120357  ** Return an Expr object that refers to column iCol of table pTab which
120358  ** has cursor iCur.
120359  */
120360  static Expr *exprTableColumn(
120361    sqlite3 *db,      /* The database connection */
120362    Table *pTab,      /* The table whose column is desired */
120363    int iCursor,      /* The open cursor on the table */
120364    i16 iCol          /* The column that is wanted */
120365  ){
120366    Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
120367    if( pExpr ){
120368      pExpr->y.pTab = pTab;
120369      pExpr->iTable = iCursor;
120370      pExpr->iColumn = iCol;
120371    }
120372    return pExpr;
120373  }
120374  
120375  /*
120376  ** This function is called to generate code executed when a row is deleted
120377  ** from the parent table of foreign key constraint pFKey and, if pFKey is 
120378  ** deferred, when a row is inserted into the same table. When generating
120379  ** code for an SQL UPDATE operation, this function may be called twice -
120380  ** once to "delete" the old row and once to "insert" the new row.
120381  **
120382  ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
120383  ** the number of FK violations in the db) or +1 when deleting one (as this
120384  ** may increase the number of FK constraint problems).
120385  **
120386  ** The code generated by this function scans through the rows in the child
120387  ** table that correspond to the parent table row being deleted or inserted.
120388  ** For each child row found, one of the following actions is taken:
120389  **
120390  **   Operation | FK type   | Action taken
120391  **   --------------------------------------------------------------------------
120392  **   DELETE      immediate   Increment the "immediate constraint counter".
120393  **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
120394  **                           throw a "FOREIGN KEY constraint failed" exception.
120395  **
120396  **   INSERT      immediate   Decrement the "immediate constraint counter".
120397  **
120398  **   DELETE      deferred    Increment the "deferred constraint counter".
120399  **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
120400  **                           throw a "FOREIGN KEY constraint failed" exception.
120401  **
120402  **   INSERT      deferred    Decrement the "deferred constraint counter".
120403  **
120404  ** These operations are identified in the comment at the top of this file 
120405  ** (fkey.c) as "I.2" and "D.2".
120406  */
120407  static void fkScanChildren(
120408    Parse *pParse,                  /* Parse context */
120409    SrcList *pSrc,                  /* The child table to be scanned */
120410    Table *pTab,                    /* The parent table */
120411    Index *pIdx,                    /* Index on parent covering the foreign key */
120412    FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
120413    int *aiCol,                     /* Map from pIdx cols to child table cols */
120414    int regData,                    /* Parent row data starts here */
120415    int nIncr                       /* Amount to increment deferred counter by */
120416  ){
120417    sqlite3 *db = pParse->db;       /* Database handle */
120418    int i;                          /* Iterator variable */
120419    Expr *pWhere = 0;               /* WHERE clause to scan with */
120420    NameContext sNameContext;       /* Context used to resolve WHERE clause */
120421    WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
120422    int iFkIfZero = 0;              /* Address of OP_FkIfZero */
120423    Vdbe *v = sqlite3GetVdbe(pParse);
120424  
120425    assert( pIdx==0 || pIdx->pTable==pTab );
120426    assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
120427    assert( pIdx!=0 || pFKey->nCol==1 );
120428    assert( pIdx!=0 || HasRowid(pTab) );
120429  
120430    if( nIncr<0 ){
120431      iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
120432      VdbeCoverage(v);
120433    }
120434  
120435    /* Create an Expr object representing an SQL expression like:
120436    **
120437    **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
120438    **
120439    ** The collation sequence used for the comparison should be that of
120440    ** the parent key columns. The affinity of the parent key column should
120441    ** be applied to each child key value before the comparison takes place.
120442    */
120443    for(i=0; i<pFKey->nCol; i++){
120444      Expr *pLeft;                  /* Value from parent table row */
120445      Expr *pRight;                 /* Column ref to child table */
120446      Expr *pEq;                    /* Expression (pLeft = pRight) */
120447      i16 iCol;                     /* Index of column in child table */ 
120448      const char *zCol;             /* Name of column in child table */
120449  
120450      iCol = pIdx ? pIdx->aiColumn[i] : -1;
120451      pLeft = exprTableRegister(pParse, pTab, regData, iCol);
120452      iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
120453      assert( iCol>=0 );
120454      zCol = pFKey->pFrom->aCol[iCol].zName;
120455      pRight = sqlite3Expr(db, TK_ID, zCol);
120456      pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
120457      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
120458    }
120459  
120460    /* If the child table is the same as the parent table, then add terms
120461    ** to the WHERE clause that prevent this entry from being scanned.
120462    ** The added WHERE clause terms are like this:
120463    **
120464    **     $current_rowid!=rowid
120465    **     NOT( $current_a==a AND $current_b==b AND ... )
120466    **
120467    ** The first form is used for rowid tables.  The second form is used
120468    ** for WITHOUT ROWID tables. In the second form, the *parent* key is
120469    ** (a,b,...). Either the parent or primary key could be used to 
120470    ** uniquely identify the current row, but the parent key is more convenient
120471    ** as the required values have already been loaded into registers
120472    ** by the caller.
120473    */
120474    if( pTab==pFKey->pFrom && nIncr>0 ){
120475      Expr *pNe;                    /* Expression (pLeft != pRight) */
120476      Expr *pLeft;                  /* Value from parent table row */
120477      Expr *pRight;                 /* Column ref to child table */
120478      if( HasRowid(pTab) ){
120479        pLeft = exprTableRegister(pParse, pTab, regData, -1);
120480        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
120481        pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
120482      }else{
120483        Expr *pEq, *pAll = 0;
120484        assert( pIdx!=0 );
120485        for(i=0; i<pIdx->nKeyCol; i++){
120486          i16 iCol = pIdx->aiColumn[i];
120487          assert( iCol>=0 );
120488          pLeft = exprTableRegister(pParse, pTab, regData, iCol);
120489          pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
120490          pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
120491          pAll = sqlite3ExprAnd(db, pAll, pEq);
120492        }
120493        pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
120494      }
120495      pWhere = sqlite3ExprAnd(db, pWhere, pNe);
120496    }
120497  
120498    /* Resolve the references in the WHERE clause. */
120499    memset(&sNameContext, 0, sizeof(NameContext));
120500    sNameContext.pSrcList = pSrc;
120501    sNameContext.pParse = pParse;
120502    sqlite3ResolveExprNames(&sNameContext, pWhere);
120503  
120504    /* Create VDBE to loop through the entries in pSrc that match the WHERE
120505    ** clause. For each row found, increment either the deferred or immediate
120506    ** foreign key constraint counter. */
120507    if( pParse->nErr==0 ){
120508      pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
120509      sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
120510      if( pWInfo ){
120511        sqlite3WhereEnd(pWInfo);
120512      }
120513    }
120514  
120515    /* Clean up the WHERE clause constructed above. */
120516    sqlite3ExprDelete(db, pWhere);
120517    if( iFkIfZero ){
120518      sqlite3VdbeJumpHere(v, iFkIfZero);
120519    }
120520  }
120521  
120522  /*
120523  ** This function returns a linked list of FKey objects (connected by
120524  ** FKey.pNextTo) holding all children of table pTab.  For example,
120525  ** given the following schema:
120526  **
120527  **   CREATE TABLE t1(a PRIMARY KEY);
120528  **   CREATE TABLE t2(b REFERENCES t1(a);
120529  **
120530  ** Calling this function with table "t1" as an argument returns a pointer
120531  ** to the FKey structure representing the foreign key constraint on table
120532  ** "t2". Calling this function with "t2" as the argument would return a
120533  ** NULL pointer (as there are no FK constraints for which t2 is the parent
120534  ** table).
120535  */
120536  SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
120537    return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
120538  }
120539  
120540  /*
120541  ** The second argument is a Trigger structure allocated by the 
120542  ** fkActionTrigger() routine. This function deletes the Trigger structure
120543  ** and all of its sub-components.
120544  **
120545  ** The Trigger structure or any of its sub-components may be allocated from
120546  ** the lookaside buffer belonging to database handle dbMem.
120547  */
120548  static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
120549    if( p ){
120550      TriggerStep *pStep = p->step_list;
120551      sqlite3ExprDelete(dbMem, pStep->pWhere);
120552      sqlite3ExprListDelete(dbMem, pStep->pExprList);
120553      sqlite3SelectDelete(dbMem, pStep->pSelect);
120554      sqlite3ExprDelete(dbMem, p->pWhen);
120555      sqlite3DbFree(dbMem, p);
120556    }
120557  }
120558  
120559  /*
120560  ** This function is called to generate code that runs when table pTab is
120561  ** being dropped from the database. The SrcList passed as the second argument
120562  ** to this function contains a single entry guaranteed to resolve to
120563  ** table pTab.
120564  **
120565  ** Normally, no code is required. However, if either
120566  **
120567  **   (a) The table is the parent table of a FK constraint, or
120568  **   (b) The table is the child table of a deferred FK constraint and it is
120569  **       determined at runtime that there are outstanding deferred FK 
120570  **       constraint violations in the database,
120571  **
120572  ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
120573  ** the table from the database. Triggers are disabled while running this
120574  ** DELETE, but foreign key actions are not.
120575  */
120576  SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
120577    sqlite3 *db = pParse->db;
120578    if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
120579      int iSkip = 0;
120580      Vdbe *v = sqlite3GetVdbe(pParse);
120581  
120582      assert( v );                  /* VDBE has already been allocated */
120583      assert( pTab->pSelect==0 );   /* Not a view */
120584      if( sqlite3FkReferences(pTab)==0 ){
120585        /* Search for a deferred foreign key constraint for which this table
120586        ** is the child table. If one cannot be found, return without 
120587        ** generating any VDBE code. If one can be found, then jump over
120588        ** the entire DELETE if there are no outstanding deferred constraints
120589        ** when this statement is run.  */
120590        FKey *p;
120591        for(p=pTab->pFKey; p; p=p->pNextFrom){
120592          if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
120593        }
120594        if( !p ) return;
120595        iSkip = sqlite3VdbeMakeLabel(pParse);
120596        sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
120597      }
120598  
120599      pParse->disableTriggers = 1;
120600      sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
120601      pParse->disableTriggers = 0;
120602  
120603      /* If the DELETE has generated immediate foreign key constraint 
120604      ** violations, halt the VDBE and return an error at this point, before
120605      ** any modifications to the schema are made. This is because statement
120606      ** transactions are not able to rollback schema changes.  
120607      **
120608      ** If the SQLITE_DeferFKs flag is set, then this is not required, as
120609      ** the statement transaction will not be rolled back even if FK
120610      ** constraints are violated.
120611      */
120612      if( (db->flags & SQLITE_DeferFKs)==0 ){
120613        sqlite3VdbeVerifyAbortable(v, OE_Abort);
120614        sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
120615        VdbeCoverage(v);
120616        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
120617            OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
120618      }
120619  
120620      if( iSkip ){
120621        sqlite3VdbeResolveLabel(v, iSkip);
120622      }
120623    }
120624  }
120625  
120626  
120627  /*
120628  ** The second argument points to an FKey object representing a foreign key
120629  ** for which pTab is the child table. An UPDATE statement against pTab
120630  ** is currently being processed. For each column of the table that is 
120631  ** actually updated, the corresponding element in the aChange[] array
120632  ** is zero or greater (if a column is unmodified the corresponding element
120633  ** is set to -1). If the rowid column is modified by the UPDATE statement
120634  ** the bChngRowid argument is non-zero.
120635  **
120636  ** This function returns true if any of the columns that are part of the
120637  ** child key for FK constraint *p are modified.
120638  */
120639  static int fkChildIsModified(
120640    Table *pTab,                    /* Table being updated */
120641    FKey *p,                        /* Foreign key for which pTab is the child */
120642    int *aChange,                   /* Array indicating modified columns */
120643    int bChngRowid                  /* True if rowid is modified by this update */
120644  ){
120645    int i;
120646    for(i=0; i<p->nCol; i++){
120647      int iChildKey = p->aCol[i].iFrom;
120648      if( aChange[iChildKey]>=0 ) return 1;
120649      if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
120650    }
120651    return 0;
120652  }
120653  
120654  /*
120655  ** The second argument points to an FKey object representing a foreign key
120656  ** for which pTab is the parent table. An UPDATE statement against pTab
120657  ** is currently being processed. For each column of the table that is 
120658  ** actually updated, the corresponding element in the aChange[] array
120659  ** is zero or greater (if a column is unmodified the corresponding element
120660  ** is set to -1). If the rowid column is modified by the UPDATE statement
120661  ** the bChngRowid argument is non-zero.
120662  **
120663  ** This function returns true if any of the columns that are part of the
120664  ** parent key for FK constraint *p are modified.
120665  */
120666  static int fkParentIsModified(
120667    Table *pTab, 
120668    FKey *p, 
120669    int *aChange, 
120670    int bChngRowid
120671  ){
120672    int i;
120673    for(i=0; i<p->nCol; i++){
120674      char *zKey = p->aCol[i].zCol;
120675      int iKey;
120676      for(iKey=0; iKey<pTab->nCol; iKey++){
120677        if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
120678          Column *pCol = &pTab->aCol[iKey];
120679          if( zKey ){
120680            if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
120681          }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
120682            return 1;
120683          }
120684        }
120685      }
120686    }
120687    return 0;
120688  }
120689  
120690  /*
120691  ** Return true if the parser passed as the first argument is being
120692  ** used to code a trigger that is really a "SET NULL" action belonging
120693  ** to trigger pFKey.
120694  */
120695  static int isSetNullAction(Parse *pParse, FKey *pFKey){
120696    Parse *pTop = sqlite3ParseToplevel(pParse);
120697    if( pTop->pTriggerPrg ){
120698      Trigger *p = pTop->pTriggerPrg->pTrigger;
120699      if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
120700       || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
120701      ){
120702        return 1;
120703      }
120704    }
120705    return 0;
120706  }
120707  
120708  /*
120709  ** This function is called when inserting, deleting or updating a row of
120710  ** table pTab to generate VDBE code to perform foreign key constraint 
120711  ** processing for the operation.
120712  **
120713  ** For a DELETE operation, parameter regOld is passed the index of the
120714  ** first register in an array of (pTab->nCol+1) registers containing the
120715  ** rowid of the row being deleted, followed by each of the column values
120716  ** of the row being deleted, from left to right. Parameter regNew is passed
120717  ** zero in this case.
120718  **
120719  ** For an INSERT operation, regOld is passed zero and regNew is passed the
120720  ** first register of an array of (pTab->nCol+1) registers containing the new
120721  ** row data.
120722  **
120723  ** For an UPDATE operation, this function is called twice. Once before
120724  ** the original record is deleted from the table using the calling convention
120725  ** described for DELETE. Then again after the original record is deleted
120726  ** but before the new record is inserted using the INSERT convention. 
120727  */
120728  SQLITE_PRIVATE void sqlite3FkCheck(
120729    Parse *pParse,                  /* Parse context */
120730    Table *pTab,                    /* Row is being deleted from this table */ 
120731    int regOld,                     /* Previous row data is stored here */
120732    int regNew,                     /* New row data is stored here */
120733    int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
120734    int bChngRowid                  /* True if rowid is UPDATEd */
120735  ){
120736    sqlite3 *db = pParse->db;       /* Database handle */
120737    FKey *pFKey;                    /* Used to iterate through FKs */
120738    int iDb;                        /* Index of database containing pTab */
120739    const char *zDb;                /* Name of database containing pTab */
120740    int isIgnoreErrors = pParse->disableTriggers;
120741  
120742    /* Exactly one of regOld and regNew should be non-zero. */
120743    assert( (regOld==0)!=(regNew==0) );
120744  
120745    /* If foreign-keys are disabled, this function is a no-op. */
120746    if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
120747  
120748    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120749    zDb = db->aDb[iDb].zDbSName;
120750  
120751    /* Loop through all the foreign key constraints for which pTab is the
120752    ** child table (the table that the foreign key definition is part of).  */
120753    for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
120754      Table *pTo;                   /* Parent table of foreign key pFKey */
120755      Index *pIdx = 0;              /* Index on key columns in pTo */
120756      int *aiFree = 0;
120757      int *aiCol;
120758      int iCol;
120759      int i;
120760      int bIgnore = 0;
120761  
120762      if( aChange 
120763       && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
120764       && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
120765      ){
120766        continue;
120767      }
120768  
120769      /* Find the parent table of this foreign key. Also find a unique index 
120770      ** on the parent key columns in the parent table. If either of these 
120771      ** schema items cannot be located, set an error in pParse and return 
120772      ** early.  */
120773      if( pParse->disableTriggers ){
120774        pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
120775      }else{
120776        pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
120777      }
120778      if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
120779        assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
120780        if( !isIgnoreErrors || db->mallocFailed ) return;
120781        if( pTo==0 ){
120782          /* If isIgnoreErrors is true, then a table is being dropped. In this
120783          ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
120784          ** before actually dropping it in order to check FK constraints.
120785          ** If the parent table of an FK constraint on the current table is
120786          ** missing, behave as if it is empty. i.e. decrement the relevant
120787          ** FK counter for each row of the current table with non-NULL keys.
120788          */
120789          Vdbe *v = sqlite3GetVdbe(pParse);
120790          int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
120791          for(i=0; i<pFKey->nCol; i++){
120792            int iReg = pFKey->aCol[i].iFrom + regOld + 1;
120793            sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
120794          }
120795          sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
120796        }
120797        continue;
120798      }
120799      assert( pFKey->nCol==1 || (aiFree && pIdx) );
120800  
120801      if( aiFree ){
120802        aiCol = aiFree;
120803      }else{
120804        iCol = pFKey->aCol[0].iFrom;
120805        aiCol = &iCol;
120806      }
120807      for(i=0; i<pFKey->nCol; i++){
120808        if( aiCol[i]==pTab->iPKey ){
120809          aiCol[i] = -1;
120810        }
120811        assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
120812  #ifndef SQLITE_OMIT_AUTHORIZATION
120813        /* Request permission to read the parent key columns. If the 
120814        ** authorization callback returns SQLITE_IGNORE, behave as if any
120815        ** values read from the parent table are NULL. */
120816        if( db->xAuth ){
120817          int rcauth;
120818          char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
120819          rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
120820          bIgnore = (rcauth==SQLITE_IGNORE);
120821        }
120822  #endif
120823      }
120824  
120825      /* Take a shared-cache advisory read-lock on the parent table. Allocate 
120826      ** a cursor to use to search the unique index on the parent key columns 
120827      ** in the parent table.  */
120828      sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
120829      pParse->nTab++;
120830  
120831      if( regOld!=0 ){
120832        /* A row is being removed from the child table. Search for the parent.
120833        ** If the parent does not exist, removing the child row resolves an 
120834        ** outstanding foreign key constraint violation. */
120835        fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
120836      }
120837      if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
120838        /* A row is being added to the child table. If a parent row cannot
120839        ** be found, adding the child row has violated the FK constraint. 
120840        **
120841        ** If this operation is being performed as part of a trigger program
120842        ** that is actually a "SET NULL" action belonging to this very 
120843        ** foreign key, then omit this scan altogether. As all child key
120844        ** values are guaranteed to be NULL, it is not possible for adding
120845        ** this row to cause an FK violation.  */
120846        fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
120847      }
120848  
120849      sqlite3DbFree(db, aiFree);
120850    }
120851  
120852    /* Loop through all the foreign key constraints that refer to this table.
120853    ** (the "child" constraints) */
120854    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
120855      Index *pIdx = 0;              /* Foreign key index for pFKey */
120856      SrcList *pSrc;
120857      int *aiCol = 0;
120858  
120859      if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
120860        continue;
120861      }
120862  
120863      if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
120864       && !pParse->pToplevel && !pParse->isMultiWrite 
120865      ){
120866        assert( regOld==0 && regNew!=0 );
120867        /* Inserting a single row into a parent table cannot cause (or fix)
120868        ** an immediate foreign key violation. So do nothing in this case.  */
120869        continue;
120870      }
120871  
120872      if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
120873        if( !isIgnoreErrors || db->mallocFailed ) return;
120874        continue;
120875      }
120876      assert( aiCol || pFKey->nCol==1 );
120877  
120878      /* Create a SrcList structure containing the child table.  We need the
120879      ** child table as a SrcList for sqlite3WhereBegin() */
120880      pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
120881      if( pSrc ){
120882        struct SrcList_item *pItem = pSrc->a;
120883        pItem->pTab = pFKey->pFrom;
120884        pItem->zName = pFKey->pFrom->zName;
120885        pItem->pTab->nTabRef++;
120886        pItem->iCursor = pParse->nTab++;
120887    
120888        if( regNew!=0 ){
120889          fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
120890        }
120891        if( regOld!=0 ){
120892          int eAction = pFKey->aAction[aChange!=0];
120893          fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
120894          /* If this is a deferred FK constraint, or a CASCADE or SET NULL
120895          ** action applies, then any foreign key violations caused by
120896          ** removing the parent key will be rectified by the action trigger.
120897          ** So do not set the "may-abort" flag in this case.
120898          **
120899          ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
120900          ** may-abort flag will eventually be set on this statement anyway
120901          ** (when this function is called as part of processing the UPDATE
120902          ** within the action trigger).
120903          **
120904          ** Note 2: At first glance it may seem like SQLite could simply omit
120905          ** all OP_FkCounter related scans when either CASCADE or SET NULL
120906          ** applies. The trouble starts if the CASCADE or SET NULL action 
120907          ** trigger causes other triggers or action rules attached to the 
120908          ** child table to fire. In these cases the fk constraint counters
120909          ** might be set incorrectly if any OP_FkCounter related scans are 
120910          ** omitted.  */
120911          if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
120912            sqlite3MayAbort(pParse);
120913          }
120914        }
120915        pItem->zName = 0;
120916        sqlite3SrcListDelete(db, pSrc);
120917      }
120918      sqlite3DbFree(db, aiCol);
120919    }
120920  }
120921  
120922  #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
120923  
120924  /*
120925  ** This function is called before generating code to update or delete a 
120926  ** row contained in table pTab.
120927  */
120928  SQLITE_PRIVATE u32 sqlite3FkOldmask(
120929    Parse *pParse,                  /* Parse context */
120930    Table *pTab                     /* Table being modified */
120931  ){
120932    u32 mask = 0;
120933    if( pParse->db->flags&SQLITE_ForeignKeys ){
120934      FKey *p;
120935      int i;
120936      for(p=pTab->pFKey; p; p=p->pNextFrom){
120937        for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
120938      }
120939      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
120940        Index *pIdx = 0;
120941        sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
120942        if( pIdx ){
120943          for(i=0; i<pIdx->nKeyCol; i++){
120944            assert( pIdx->aiColumn[i]>=0 );
120945            mask |= COLUMN_MASK(pIdx->aiColumn[i]);
120946          }
120947        }
120948      }
120949    }
120950    return mask;
120951  }
120952  
120953  
120954  /*
120955  ** This function is called before generating code to update or delete a 
120956  ** row contained in table pTab. If the operation is a DELETE, then
120957  ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
120958  ** to an array of size N, where N is the number of columns in table pTab.
120959  ** If the i'th column is not modified by the UPDATE, then the corresponding 
120960  ** entry in the aChange[] array is set to -1. If the column is modified,
120961  ** the value is 0 or greater. Parameter chngRowid is set to true if the
120962  ** UPDATE statement modifies the rowid fields of the table.
120963  **
120964  ** If any foreign key processing will be required, this function returns
120965  ** non-zero. If there is no foreign key related processing, this function 
120966  ** returns zero.
120967  **
120968  ** For an UPDATE, this function returns 2 if:
120969  **
120970  **   * There are any FKs for which pTab is the child and the parent table, or
120971  **   * the UPDATE modifies one or more parent keys for which the action is
120972  **     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
120973  **
120974  ** Or, assuming some other foreign key processing is required, 1.
120975  */
120976  SQLITE_PRIVATE int sqlite3FkRequired(
120977    Parse *pParse,                  /* Parse context */
120978    Table *pTab,                    /* Table being modified */
120979    int *aChange,                   /* Non-NULL for UPDATE operations */
120980    int chngRowid                   /* True for UPDATE that affects rowid */
120981  ){
120982    int eRet = 0;
120983    if( pParse->db->flags&SQLITE_ForeignKeys ){
120984      if( !aChange ){
120985        /* A DELETE operation. Foreign key processing is required if the 
120986        ** table in question is either the child or parent table for any 
120987        ** foreign key constraint.  */
120988        eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
120989      }else{
120990        /* This is an UPDATE. Foreign key processing is only required if the
120991        ** operation modifies one or more child or parent key columns. */
120992        FKey *p;
120993  
120994        /* Check if any child key columns are being modified. */
120995        for(p=pTab->pFKey; p; p=p->pNextFrom){
120996          if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
120997          if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
120998            eRet = 1;
120999          }
121000        }
121001  
121002        /* Check if any parent key columns are being modified. */
121003        for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
121004          if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
121005            if( p->aAction[1]!=OE_None ) return 2;
121006            eRet = 1;
121007          }
121008        }
121009      }
121010    }
121011    return eRet;
121012  }
121013  
121014  /*
121015  ** This function is called when an UPDATE or DELETE operation is being 
121016  ** compiled on table pTab, which is the parent table of foreign-key pFKey.
121017  ** If the current operation is an UPDATE, then the pChanges parameter is
121018  ** passed a pointer to the list of columns being modified. If it is a
121019  ** DELETE, pChanges is passed a NULL pointer.
121020  **
121021  ** It returns a pointer to a Trigger structure containing a trigger
121022  ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
121023  ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
121024  ** returned (these actions require no special handling by the triggers
121025  ** sub-system, code for them is created by fkScanChildren()).
121026  **
121027  ** For example, if pFKey is the foreign key and pTab is table "p" in 
121028  ** the following schema:
121029  **
121030  **   CREATE TABLE p(pk PRIMARY KEY);
121031  **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
121032  **
121033  ** then the returned trigger structure is equivalent to:
121034  **
121035  **   CREATE TRIGGER ... DELETE ON p BEGIN
121036  **     DELETE FROM c WHERE ck = old.pk;
121037  **   END;
121038  **
121039  ** The returned pointer is cached as part of the foreign key object. It
121040  ** is eventually freed along with the rest of the foreign key object by 
121041  ** sqlite3FkDelete().
121042  */
121043  static Trigger *fkActionTrigger(
121044    Parse *pParse,                  /* Parse context */
121045    Table *pTab,                    /* Table being updated or deleted from */
121046    FKey *pFKey,                    /* Foreign key to get action for */
121047    ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
121048  ){
121049    sqlite3 *db = pParse->db;       /* Database handle */
121050    int action;                     /* One of OE_None, OE_Cascade etc. */
121051    Trigger *pTrigger;              /* Trigger definition to return */
121052    int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
121053  
121054    action = pFKey->aAction[iAction];
121055    if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
121056      return 0;
121057    }
121058    pTrigger = pFKey->apTrigger[iAction];
121059  
121060    if( action!=OE_None && !pTrigger ){
121061      char const *zFrom;            /* Name of child table */
121062      int nFrom;                    /* Length in bytes of zFrom */
121063      Index *pIdx = 0;              /* Parent key index for this FK */
121064      int *aiCol = 0;               /* child table cols -> parent key cols */
121065      TriggerStep *pStep = 0;        /* First (only) step of trigger program */
121066      Expr *pWhere = 0;             /* WHERE clause of trigger step */
121067      ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
121068      Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
121069      int i;                        /* Iterator variable */
121070      Expr *pWhen = 0;              /* WHEN clause for the trigger */
121071  
121072      if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
121073      assert( aiCol || pFKey->nCol==1 );
121074  
121075      for(i=0; i<pFKey->nCol; i++){
121076        Token tOld = { "old", 3 };  /* Literal "old" token */
121077        Token tNew = { "new", 3 };  /* Literal "new" token */
121078        Token tFromCol;             /* Name of column in child table */
121079        Token tToCol;               /* Name of column in parent table */
121080        int iFromCol;               /* Idx of column in child table */
121081        Expr *pEq;                  /* tFromCol = OLD.tToCol */
121082  
121083        iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
121084        assert( iFromCol>=0 );
121085        assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
121086        assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
121087        sqlite3TokenInit(&tToCol,
121088                     pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
121089        sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
121090  
121091        /* Create the expression "OLD.zToCol = zFromCol". It is important
121092        ** that the "OLD.zToCol" term is on the LHS of the = operator, so
121093        ** that the affinity and collation sequence associated with the
121094        ** parent table are used for the comparison. */
121095        pEq = sqlite3PExpr(pParse, TK_EQ,
121096            sqlite3PExpr(pParse, TK_DOT, 
121097              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
121098              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
121099            sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
121100        );
121101        pWhere = sqlite3ExprAnd(db, pWhere, pEq);
121102  
121103        /* For ON UPDATE, construct the next term of the WHEN clause.
121104        ** The final WHEN clause will be like this:
121105        **
121106        **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
121107        */
121108        if( pChanges ){
121109          pEq = sqlite3PExpr(pParse, TK_IS,
121110              sqlite3PExpr(pParse, TK_DOT, 
121111                sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
121112                sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
121113              sqlite3PExpr(pParse, TK_DOT, 
121114                sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
121115                sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
121116              );
121117          pWhen = sqlite3ExprAnd(db, pWhen, pEq);
121118        }
121119    
121120        if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
121121          Expr *pNew;
121122          if( action==OE_Cascade ){
121123            pNew = sqlite3PExpr(pParse, TK_DOT, 
121124              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
121125              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
121126          }else if( action==OE_SetDflt ){
121127            Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
121128            if( pDflt ){
121129              pNew = sqlite3ExprDup(db, pDflt, 0);
121130            }else{
121131              pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
121132            }
121133          }else{
121134            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
121135          }
121136          pList = sqlite3ExprListAppend(pParse, pList, pNew);
121137          sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
121138        }
121139      }
121140      sqlite3DbFree(db, aiCol);
121141  
121142      zFrom = pFKey->pFrom->zName;
121143      nFrom = sqlite3Strlen30(zFrom);
121144  
121145      if( action==OE_Restrict ){
121146        Token tFrom;
121147        Expr *pRaise; 
121148  
121149        tFrom.z = zFrom;
121150        tFrom.n = nFrom;
121151        pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
121152        if( pRaise ){
121153          pRaise->affinity = OE_Abort;
121154        }
121155        pSelect = sqlite3SelectNew(pParse, 
121156            sqlite3ExprListAppend(pParse, 0, pRaise),
121157            sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
121158            pWhere,
121159            0, 0, 0, 0, 0
121160        );
121161        pWhere = 0;
121162      }
121163  
121164      /* Disable lookaside memory allocation */
121165      db->lookaside.bDisable++;
121166  
121167      pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
121168          sizeof(Trigger) +         /* struct Trigger */
121169          sizeof(TriggerStep) +     /* Single step in trigger program */
121170          nFrom + 1                 /* Space for pStep->zTarget */
121171      );
121172      if( pTrigger ){
121173        pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
121174        pStep->zTarget = (char *)&pStep[1];
121175        memcpy((char *)pStep->zTarget, zFrom, nFrom);
121176    
121177        pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
121178        pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
121179        pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
121180        if( pWhen ){
121181          pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
121182          pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
121183        }
121184      }
121185  
121186      /* Re-enable the lookaside buffer, if it was disabled earlier. */
121187      db->lookaside.bDisable--;
121188  
121189      sqlite3ExprDelete(db, pWhere);
121190      sqlite3ExprDelete(db, pWhen);
121191      sqlite3ExprListDelete(db, pList);
121192      sqlite3SelectDelete(db, pSelect);
121193      if( db->mallocFailed==1 ){
121194        fkTriggerDelete(db, pTrigger);
121195        return 0;
121196      }
121197      assert( pStep!=0 );
121198  
121199      switch( action ){
121200        case OE_Restrict:
121201          pStep->op = TK_SELECT; 
121202          break;
121203        case OE_Cascade: 
121204          if( !pChanges ){ 
121205            pStep->op = TK_DELETE; 
121206            break; 
121207          }
121208        default:
121209          pStep->op = TK_UPDATE;
121210      }
121211      pStep->pTrig = pTrigger;
121212      pTrigger->pSchema = pTab->pSchema;
121213      pTrigger->pTabSchema = pTab->pSchema;
121214      pFKey->apTrigger[iAction] = pTrigger;
121215      pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
121216    }
121217  
121218    return pTrigger;
121219  }
121220  
121221  /*
121222  ** This function is called when deleting or updating a row to implement
121223  ** any required CASCADE, SET NULL or SET DEFAULT actions.
121224  */
121225  SQLITE_PRIVATE void sqlite3FkActions(
121226    Parse *pParse,                  /* Parse context */
121227    Table *pTab,                    /* Table being updated or deleted from */
121228    ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
121229    int regOld,                     /* Address of array containing old row */
121230    int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
121231    int bChngRowid                  /* True if rowid is UPDATEd */
121232  ){
121233    /* If foreign-key support is enabled, iterate through all FKs that 
121234    ** refer to table pTab. If there is an action associated with the FK 
121235    ** for this operation (either update or delete), invoke the associated 
121236    ** trigger sub-program.  */
121237    if( pParse->db->flags&SQLITE_ForeignKeys ){
121238      FKey *pFKey;                  /* Iterator variable */
121239      for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
121240        if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
121241          Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
121242          if( pAct ){
121243            sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
121244          }
121245        }
121246      }
121247    }
121248  }
121249  
121250  #endif /* ifndef SQLITE_OMIT_TRIGGER */
121251  
121252  /*
121253  ** Free all memory associated with foreign key definitions attached to
121254  ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
121255  ** hash table.
121256  */
121257  SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
121258    FKey *pFKey;                    /* Iterator variable */
121259    FKey *pNext;                    /* Copy of pFKey->pNextFrom */
121260  
121261    assert( db==0 || IsVirtual(pTab)
121262           || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
121263    for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
121264  
121265      /* Remove the FK from the fkeyHash hash table. */
121266      if( !db || db->pnBytesFreed==0 ){
121267        if( pFKey->pPrevTo ){
121268          pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
121269        }else{
121270          void *p = (void *)pFKey->pNextTo;
121271          const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
121272          sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
121273        }
121274        if( pFKey->pNextTo ){
121275          pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
121276        }
121277      }
121278  
121279      /* EV: R-30323-21917 Each foreign key constraint in SQLite is
121280      ** classified as either immediate or deferred.
121281      */
121282      assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
121283  
121284      /* Delete any triggers created to implement actions for this FK. */
121285  #ifndef SQLITE_OMIT_TRIGGER
121286      fkTriggerDelete(db, pFKey->apTrigger[0]);
121287      fkTriggerDelete(db, pFKey->apTrigger[1]);
121288  #endif
121289  
121290      pNext = pFKey->pNextFrom;
121291      sqlite3DbFree(db, pFKey);
121292    }
121293  }
121294  #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
121295  
121296  /************** End of fkey.c ************************************************/
121297  /************** Begin file insert.c ******************************************/
121298  /*
121299  ** 2001 September 15
121300  **
121301  ** The author disclaims copyright to this source code.  In place of
121302  ** a legal notice, here is a blessing:
121303  **
121304  **    May you do good and not evil.
121305  **    May you find forgiveness for yourself and forgive others.
121306  **    May you share freely, never taking more than you give.
121307  **
121308  *************************************************************************
121309  ** This file contains C code routines that are called by the parser
121310  ** to handle INSERT statements in SQLite.
121311  */
121312  /* #include "sqliteInt.h" */
121313  
121314  /*
121315  ** Generate code that will 
121316  **
121317  **   (1) acquire a lock for table pTab then
121318  **   (2) open pTab as cursor iCur.
121319  **
121320  ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
121321  ** for that table that is actually opened.
121322  */
121323  SQLITE_PRIVATE void sqlite3OpenTable(
121324    Parse *pParse,  /* Generate code into this VDBE */
121325    int iCur,       /* The cursor number of the table */
121326    int iDb,        /* The database index in sqlite3.aDb[] */
121327    Table *pTab,    /* The table to be opened */
121328    int opcode      /* OP_OpenRead or OP_OpenWrite */
121329  ){
121330    Vdbe *v;
121331    assert( !IsVirtual(pTab) );
121332    v = sqlite3GetVdbe(pParse);
121333    assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
121334    sqlite3TableLock(pParse, iDb, pTab->tnum, 
121335                     (opcode==OP_OpenWrite)?1:0, pTab->zName);
121336    if( HasRowid(pTab) ){
121337      sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
121338      VdbeComment((v, "%s", pTab->zName));
121339    }else{
121340      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
121341      assert( pPk!=0 );
121342      assert( pPk->tnum==pTab->tnum );
121343      sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
121344      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
121345      VdbeComment((v, "%s", pTab->zName));
121346    }
121347  }
121348  
121349  /*
121350  ** Return a pointer to the column affinity string associated with index
121351  ** pIdx. A column affinity string has one character for each column in 
121352  ** the table, according to the affinity of the column:
121353  **
121354  **  Character      Column affinity
121355  **  ------------------------------
121356  **  'A'            BLOB
121357  **  'B'            TEXT
121358  **  'C'            NUMERIC
121359  **  'D'            INTEGER
121360  **  'F'            REAL
121361  **
121362  ** An extra 'D' is appended to the end of the string to cover the
121363  ** rowid that appears as the last column in every index.
121364  **
121365  ** Memory for the buffer containing the column index affinity string
121366  ** is managed along with the rest of the Index structure. It will be
121367  ** released when sqlite3DeleteIndex() is called.
121368  */
121369  SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
121370    if( !pIdx->zColAff ){
121371      /* The first time a column affinity string for a particular index is
121372      ** required, it is allocated and populated here. It is then stored as
121373      ** a member of the Index structure for subsequent use.
121374      **
121375      ** The column affinity string will eventually be deleted by
121376      ** sqliteDeleteIndex() when the Index structure itself is cleaned
121377      ** up.
121378      */
121379      int n;
121380      Table *pTab = pIdx->pTable;
121381      pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
121382      if( !pIdx->zColAff ){
121383        sqlite3OomFault(db);
121384        return 0;
121385      }
121386      for(n=0; n<pIdx->nColumn; n++){
121387        i16 x = pIdx->aiColumn[n];
121388        if( x>=0 ){
121389          pIdx->zColAff[n] = pTab->aCol[x].affinity;
121390        }else if( x==XN_ROWID ){
121391          pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
121392        }else{
121393          char aff;
121394          assert( x==XN_EXPR );
121395          assert( pIdx->aColExpr!=0 );
121396          aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
121397          if( aff==0 ) aff = SQLITE_AFF_BLOB;
121398          pIdx->zColAff[n] = aff;
121399        }
121400      }
121401      pIdx->zColAff[n] = 0;
121402    }
121403   
121404    return pIdx->zColAff;
121405  }
121406  
121407  /*
121408  ** Compute the affinity string for table pTab, if it has not already been
121409  ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
121410  **
121411  ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
121412  ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
121413  ** for register iReg and following.  Or if affinities exists and iReg==0,
121414  ** then just set the P4 operand of the previous opcode (which should  be
121415  ** an OP_MakeRecord) to the affinity string.
121416  **
121417  ** A column affinity string has one character per column:
121418  **
121419  **  Character      Column affinity
121420  **  ------------------------------
121421  **  'A'            BLOB
121422  **  'B'            TEXT
121423  **  'C'            NUMERIC
121424  **  'D'            INTEGER
121425  **  'E'            REAL
121426  */
121427  SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
121428    int i;
121429    char *zColAff = pTab->zColAff;
121430    if( zColAff==0 ){
121431      sqlite3 *db = sqlite3VdbeDb(v);
121432      zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
121433      if( !zColAff ){
121434        sqlite3OomFault(db);
121435        return;
121436      }
121437  
121438      for(i=0; i<pTab->nCol; i++){
121439        zColAff[i] = pTab->aCol[i].affinity;
121440      }
121441      do{
121442        zColAff[i--] = 0;
121443      }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
121444      pTab->zColAff = zColAff;
121445    }
121446    assert( zColAff!=0 );
121447    i = sqlite3Strlen30NN(zColAff);
121448    if( i ){
121449      if( iReg ){
121450        sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
121451      }else{
121452        sqlite3VdbeChangeP4(v, -1, zColAff, i);
121453      }
121454    }
121455  }
121456  
121457  /*
121458  ** Return non-zero if the table pTab in database iDb or any of its indices
121459  ** have been opened at any point in the VDBE program. This is used to see if 
121460  ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
121461  ** run without using a temporary table for the results of the SELECT. 
121462  */
121463  static int readsTable(Parse *p, int iDb, Table *pTab){
121464    Vdbe *v = sqlite3GetVdbe(p);
121465    int i;
121466    int iEnd = sqlite3VdbeCurrentAddr(v);
121467  #ifndef SQLITE_OMIT_VIRTUALTABLE
121468    VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
121469  #endif
121470  
121471    for(i=1; i<iEnd; i++){
121472      VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
121473      assert( pOp!=0 );
121474      if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
121475        Index *pIndex;
121476        int tnum = pOp->p2;
121477        if( tnum==pTab->tnum ){
121478          return 1;
121479        }
121480        for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
121481          if( tnum==pIndex->tnum ){
121482            return 1;
121483          }
121484        }
121485      }
121486  #ifndef SQLITE_OMIT_VIRTUALTABLE
121487      if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
121488        assert( pOp->p4.pVtab!=0 );
121489        assert( pOp->p4type==P4_VTAB );
121490        return 1;
121491      }
121492  #endif
121493    }
121494    return 0;
121495  }
121496  
121497  #ifndef SQLITE_OMIT_AUTOINCREMENT
121498  /*
121499  ** Locate or create an AutoincInfo structure associated with table pTab
121500  ** which is in database iDb.  Return the register number for the register
121501  ** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
121502  ** table.  (Also return zero when doing a VACUUM since we do not want to
121503  ** update the AUTOINCREMENT counters during a VACUUM.)
121504  **
121505  ** There is at most one AutoincInfo structure per table even if the
121506  ** same table is autoincremented multiple times due to inserts within
121507  ** triggers.  A new AutoincInfo structure is created if this is the
121508  ** first use of table pTab.  On 2nd and subsequent uses, the original
121509  ** AutoincInfo structure is used.
121510  **
121511  ** Four consecutive registers are allocated:
121512  **
121513  **   (1)  The name of the pTab table.
121514  **   (2)  The maximum ROWID of pTab.
121515  **   (3)  The rowid in sqlite_sequence of pTab
121516  **   (4)  The original value of the max ROWID in pTab, or NULL if none
121517  **
121518  ** The 2nd register is the one that is returned.  That is all the
121519  ** insert routine needs to know about.
121520  */
121521  static int autoIncBegin(
121522    Parse *pParse,      /* Parsing context */
121523    int iDb,            /* Index of the database holding pTab */
121524    Table *pTab         /* The table we are writing to */
121525  ){
121526    int memId = 0;      /* Register holding maximum rowid */
121527    assert( pParse->db->aDb[iDb].pSchema!=0 );
121528    if( (pTab->tabFlags & TF_Autoincrement)!=0
121529     && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
121530    ){
121531      Parse *pToplevel = sqlite3ParseToplevel(pParse);
121532      AutoincInfo *pInfo;
121533      Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
121534  
121535      /* Verify that the sqlite_sequence table exists and is an ordinary
121536      ** rowid table with exactly two columns.
121537      ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
121538      if( pSeqTab==0
121539       || !HasRowid(pSeqTab)
121540       || IsVirtual(pSeqTab)
121541       || pSeqTab->nCol!=2
121542      ){
121543        pParse->nErr++;
121544        pParse->rc = SQLITE_CORRUPT_SEQUENCE;
121545        return 0;
121546      }
121547  
121548      pInfo = pToplevel->pAinc;
121549      while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
121550      if( pInfo==0 ){
121551        pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
121552        if( pInfo==0 ) return 0;
121553        pInfo->pNext = pToplevel->pAinc;
121554        pToplevel->pAinc = pInfo;
121555        pInfo->pTab = pTab;
121556        pInfo->iDb = iDb;
121557        pToplevel->nMem++;                  /* Register to hold name of table */
121558        pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
121559        pToplevel->nMem +=2;       /* Rowid in sqlite_sequence + orig max val */
121560      }
121561      memId = pInfo->regCtr;
121562    }
121563    return memId;
121564  }
121565  
121566  /*
121567  ** This routine generates code that will initialize all of the
121568  ** register used by the autoincrement tracker.  
121569  */
121570  SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
121571    AutoincInfo *p;            /* Information about an AUTOINCREMENT */
121572    sqlite3 *db = pParse->db;  /* The database connection */
121573    Db *pDb;                   /* Database only autoinc table */
121574    int memId;                 /* Register holding max rowid */
121575    Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
121576  
121577    /* This routine is never called during trigger-generation.  It is
121578    ** only called from the top-level */
121579    assert( pParse->pTriggerTab==0 );
121580    assert( sqlite3IsToplevel(pParse) );
121581  
121582    assert( v );   /* We failed long ago if this is not so */
121583    for(p = pParse->pAinc; p; p = p->pNext){
121584      static const int iLn = VDBE_OFFSET_LINENO(2);
121585      static const VdbeOpList autoInc[] = {
121586        /* 0  */ {OP_Null,    0,  0, 0},
121587        /* 1  */ {OP_Rewind,  0, 10, 0},
121588        /* 2  */ {OP_Column,  0,  0, 0},
121589        /* 3  */ {OP_Ne,      0,  9, 0},
121590        /* 4  */ {OP_Rowid,   0,  0, 0},
121591        /* 5  */ {OP_Column,  0,  1, 0},
121592        /* 6  */ {OP_AddImm,  0,  0, 0},
121593        /* 7  */ {OP_Copy,    0,  0, 0},
121594        /* 8  */ {OP_Goto,    0, 11, 0},
121595        /* 9  */ {OP_Next,    0,  2, 0},
121596        /* 10 */ {OP_Integer, 0,  0, 0},
121597        /* 11 */ {OP_Close,   0,  0, 0} 
121598      };
121599      VdbeOp *aOp;
121600      pDb = &db->aDb[p->iDb];
121601      memId = p->regCtr;
121602      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
121603      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
121604      sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
121605      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
121606      if( aOp==0 ) break;
121607      aOp[0].p2 = memId;
121608      aOp[0].p3 = memId+2;
121609      aOp[2].p3 = memId;
121610      aOp[3].p1 = memId-1;
121611      aOp[3].p3 = memId;
121612      aOp[3].p5 = SQLITE_JUMPIFNULL;
121613      aOp[4].p2 = memId+1;
121614      aOp[5].p3 = memId;
121615      aOp[6].p1 = memId;
121616      aOp[7].p2 = memId+2;
121617      aOp[7].p1 = memId;
121618      aOp[10].p2 = memId;
121619      if( pParse->nTab==0 ) pParse->nTab = 1;
121620    }
121621  }
121622  
121623  /*
121624  ** Update the maximum rowid for an autoincrement calculation.
121625  **
121626  ** This routine should be called when the regRowid register holds a
121627  ** new rowid that is about to be inserted.  If that new rowid is
121628  ** larger than the maximum rowid in the memId memory cell, then the
121629  ** memory cell is updated.
121630  */
121631  static void autoIncStep(Parse *pParse, int memId, int regRowid){
121632    if( memId>0 ){
121633      sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
121634    }
121635  }
121636  
121637  /*
121638  ** This routine generates the code needed to write autoincrement
121639  ** maximum rowid values back into the sqlite_sequence register.
121640  ** Every statement that might do an INSERT into an autoincrement
121641  ** table (either directly or through triggers) needs to call this
121642  ** routine just before the "exit" code.
121643  */
121644  static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
121645    AutoincInfo *p;
121646    Vdbe *v = pParse->pVdbe;
121647    sqlite3 *db = pParse->db;
121648  
121649    assert( v );
121650    for(p = pParse->pAinc; p; p = p->pNext){
121651      static const int iLn = VDBE_OFFSET_LINENO(2);
121652      static const VdbeOpList autoIncEnd[] = {
121653        /* 0 */ {OP_NotNull,     0, 2, 0},
121654        /* 1 */ {OP_NewRowid,    0, 0, 0},
121655        /* 2 */ {OP_MakeRecord,  0, 2, 0},
121656        /* 3 */ {OP_Insert,      0, 0, 0},
121657        /* 4 */ {OP_Close,       0, 0, 0}
121658      };
121659      VdbeOp *aOp;
121660      Db *pDb = &db->aDb[p->iDb];
121661      int iRec;
121662      int memId = p->regCtr;
121663  
121664      iRec = sqlite3GetTempReg(pParse);
121665      assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
121666      sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
121667      VdbeCoverage(v);
121668      sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
121669      aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
121670      if( aOp==0 ) break;
121671      aOp[0].p1 = memId+1;
121672      aOp[1].p2 = memId+1;
121673      aOp[2].p1 = memId-1;
121674      aOp[2].p3 = iRec;
121675      aOp[3].p2 = iRec;
121676      aOp[3].p3 = memId+1;
121677      aOp[3].p5 = OPFLAG_APPEND;
121678      sqlite3ReleaseTempReg(pParse, iRec);
121679    }
121680  }
121681  SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
121682    if( pParse->pAinc ) autoIncrementEnd(pParse);
121683  }
121684  #else
121685  /*
121686  ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
121687  ** above are all no-ops
121688  */
121689  # define autoIncBegin(A,B,C) (0)
121690  # define autoIncStep(A,B,C)
121691  #endif /* SQLITE_OMIT_AUTOINCREMENT */
121692  
121693  
121694  /* Forward declaration */
121695  static int xferOptimization(
121696    Parse *pParse,        /* Parser context */
121697    Table *pDest,         /* The table we are inserting into */
121698    Select *pSelect,      /* A SELECT statement to use as the data source */
121699    int onError,          /* How to handle constraint errors */
121700    int iDbDest           /* The database of pDest */
121701  );
121702  
121703  /*
121704  ** This routine is called to handle SQL of the following forms:
121705  **
121706  **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
121707  **    insert into TABLE (IDLIST) select
121708  **    insert into TABLE (IDLIST) default values
121709  **
121710  ** The IDLIST following the table name is always optional.  If omitted,
121711  ** then a list of all (non-hidden) columns for the table is substituted.
121712  ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
121713  ** is omitted.
121714  **
121715  ** For the pSelect parameter holds the values to be inserted for the
121716  ** first two forms shown above.  A VALUES clause is really just short-hand
121717  ** for a SELECT statement that omits the FROM clause and everything else
121718  ** that follows.  If the pSelect parameter is NULL, that means that the
121719  ** DEFAULT VALUES form of the INSERT statement is intended.
121720  **
121721  ** The code generated follows one of four templates.  For a simple
121722  ** insert with data coming from a single-row VALUES clause, the code executes
121723  ** once straight down through.  Pseudo-code follows (we call this
121724  ** the "1st template"):
121725  **
121726  **         open write cursor to <table> and its indices
121727  **         put VALUES clause expressions into registers
121728  **         write the resulting record into <table>
121729  **         cleanup
121730  **
121731  ** The three remaining templates assume the statement is of the form
121732  **
121733  **   INSERT INTO <table> SELECT ...
121734  **
121735  ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
121736  ** in other words if the SELECT pulls all columns from a single table
121737  ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
121738  ** if <table2> and <table1> are distinct tables but have identical
121739  ** schemas, including all the same indices, then a special optimization
121740  ** is invoked that copies raw records from <table2> over to <table1>.
121741  ** See the xferOptimization() function for the implementation of this
121742  ** template.  This is the 2nd template.
121743  **
121744  **         open a write cursor to <table>
121745  **         open read cursor on <table2>
121746  **         transfer all records in <table2> over to <table>
121747  **         close cursors
121748  **         foreach index on <table>
121749  **           open a write cursor on the <table> index
121750  **           open a read cursor on the corresponding <table2> index
121751  **           transfer all records from the read to the write cursors
121752  **           close cursors
121753  **         end foreach
121754  **
121755  ** The 3rd template is for when the second template does not apply
121756  ** and the SELECT clause does not read from <table> at any time.
121757  ** The generated code follows this template:
121758  **
121759  **         X <- A
121760  **         goto B
121761  **      A: setup for the SELECT
121762  **         loop over the rows in the SELECT
121763  **           load values into registers R..R+n
121764  **           yield X
121765  **         end loop
121766  **         cleanup after the SELECT
121767  **         end-coroutine X
121768  **      B: open write cursor to <table> and its indices
121769  **      C: yield X, at EOF goto D
121770  **         insert the select result into <table> from R..R+n
121771  **         goto C
121772  **      D: cleanup
121773  **
121774  ** The 4th template is used if the insert statement takes its
121775  ** values from a SELECT but the data is being inserted into a table
121776  ** that is also read as part of the SELECT.  In the third form,
121777  ** we have to use an intermediate table to store the results of
121778  ** the select.  The template is like this:
121779  **
121780  **         X <- A
121781  **         goto B
121782  **      A: setup for the SELECT
121783  **         loop over the tables in the SELECT
121784  **           load value into register R..R+n
121785  **           yield X
121786  **         end loop
121787  **         cleanup after the SELECT
121788  **         end co-routine R
121789  **      B: open temp table
121790  **      L: yield X, at EOF goto M
121791  **         insert row from R..R+n into temp table
121792  **         goto L
121793  **      M: open write cursor to <table> and its indices
121794  **         rewind temp table
121795  **      C: loop over rows of intermediate table
121796  **           transfer values form intermediate table into <table>
121797  **         end loop
121798  **      D: cleanup
121799  */
121800  SQLITE_PRIVATE void sqlite3Insert(
121801    Parse *pParse,        /* Parser context */
121802    SrcList *pTabList,    /* Name of table into which we are inserting */
121803    Select *pSelect,      /* A SELECT statement to use as the data source */
121804    IdList *pColumn,      /* Column names corresponding to IDLIST. */
121805    int onError,          /* How to handle constraint errors */
121806    Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
121807  ){
121808    sqlite3 *db;          /* The main database structure */
121809    Table *pTab;          /* The table to insert into.  aka TABLE */
121810    int i, j;             /* Loop counters */
121811    Vdbe *v;              /* Generate code into this virtual machine */
121812    Index *pIdx;          /* For looping over indices of the table */
121813    int nColumn;          /* Number of columns in the data */
121814    int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
121815    int iDataCur = 0;     /* VDBE cursor that is the main data repository */
121816    int iIdxCur = 0;      /* First index cursor */
121817    int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
121818    int endOfLoop;        /* Label for the end of the insertion loop */
121819    int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
121820    int addrInsTop = 0;   /* Jump to label "D" */
121821    int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
121822    SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
121823    int iDb;              /* Index of database holding TABLE */
121824    u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
121825    u8 appendFlag = 0;    /* True if the insert is likely to be an append */
121826    u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
121827    u8 bIdListInOrder;    /* True if IDLIST is in table order */
121828    ExprList *pList = 0;  /* List of VALUES() to be inserted  */
121829  
121830    /* Register allocations */
121831    int regFromSelect = 0;/* Base register for data coming from SELECT */
121832    int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
121833    int regRowCount = 0;  /* Memory cell used for the row counter */
121834    int regIns;           /* Block of regs holding rowid+data being inserted */
121835    int regRowid;         /* registers holding insert rowid */
121836    int regData;          /* register holding first column to insert */
121837    int *aRegIdx = 0;     /* One register allocated to each index */
121838  
121839  #ifndef SQLITE_OMIT_TRIGGER
121840    int isView;                 /* True if attempting to insert into a view */
121841    Trigger *pTrigger;          /* List of triggers on pTab, if required */
121842    int tmask;                  /* Mask of trigger times */
121843  #endif
121844  
121845    db = pParse->db;
121846    if( pParse->nErr || db->mallocFailed ){
121847      goto insert_cleanup;
121848    }
121849    dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
121850  
121851    /* If the Select object is really just a simple VALUES() list with a
121852    ** single row (the common case) then keep that one row of values
121853    ** and discard the other (unused) parts of the pSelect object
121854    */
121855    if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
121856      pList = pSelect->pEList;
121857      pSelect->pEList = 0;
121858      sqlite3SelectDelete(db, pSelect);
121859      pSelect = 0;
121860    }
121861  
121862    /* Locate the table into which we will be inserting new information.
121863    */
121864    assert( pTabList->nSrc==1 );
121865    pTab = sqlite3SrcListLookup(pParse, pTabList);
121866    if( pTab==0 ){
121867      goto insert_cleanup;
121868    }
121869    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121870    assert( iDb<db->nDb );
121871    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
121872                         db->aDb[iDb].zDbSName) ){
121873      goto insert_cleanup;
121874    }
121875    withoutRowid = !HasRowid(pTab);
121876  
121877    /* Figure out if we have any triggers and if the table being
121878    ** inserted into is a view
121879    */
121880  #ifndef SQLITE_OMIT_TRIGGER
121881    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
121882    isView = pTab->pSelect!=0;
121883  #else
121884  # define pTrigger 0
121885  # define tmask 0
121886  # define isView 0
121887  #endif
121888  #ifdef SQLITE_OMIT_VIEW
121889  # undef isView
121890  # define isView 0
121891  #endif
121892    assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
121893  
121894    /* If pTab is really a view, make sure it has been initialized.
121895    ** ViewGetColumnNames() is a no-op if pTab is not a view.
121896    */
121897    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
121898      goto insert_cleanup;
121899    }
121900  
121901    /* Cannot insert into a read-only table.
121902    */
121903    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
121904      goto insert_cleanup;
121905    }
121906  
121907    /* Allocate a VDBE
121908    */
121909    v = sqlite3GetVdbe(pParse);
121910    if( v==0 ) goto insert_cleanup;
121911    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
121912    sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
121913  
121914  #ifndef SQLITE_OMIT_XFER_OPT
121915    /* If the statement is of the form
121916    **
121917    **       INSERT INTO <table1> SELECT * FROM <table2>;
121918    **
121919    ** Then special optimizations can be applied that make the transfer
121920    ** very fast and which reduce fragmentation of indices.
121921    **
121922    ** This is the 2nd template.
121923    */
121924    if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
121925      assert( !pTrigger );
121926      assert( pList==0 );
121927      goto insert_end;
121928    }
121929  #endif /* SQLITE_OMIT_XFER_OPT */
121930  
121931    /* If this is an AUTOINCREMENT table, look up the sequence number in the
121932    ** sqlite_sequence table and store it in memory cell regAutoinc.
121933    */
121934    regAutoinc = autoIncBegin(pParse, iDb, pTab);
121935  
121936    /* Allocate registers for holding the rowid of the new row,
121937    ** the content of the new row, and the assembled row record.
121938    */
121939    regRowid = regIns = pParse->nMem+1;
121940    pParse->nMem += pTab->nCol + 1;
121941    if( IsVirtual(pTab) ){
121942      regRowid++;
121943      pParse->nMem++;
121944    }
121945    regData = regRowid+1;
121946  
121947    /* If the INSERT statement included an IDLIST term, then make sure
121948    ** all elements of the IDLIST really are columns of the table and 
121949    ** remember the column indices.
121950    **
121951    ** If the table has an INTEGER PRIMARY KEY column and that column
121952    ** is named in the IDLIST, then record in the ipkColumn variable
121953    ** the index into IDLIST of the primary key column.  ipkColumn is
121954    ** the index of the primary key as it appears in IDLIST, not as
121955    ** is appears in the original table.  (The index of the INTEGER
121956    ** PRIMARY KEY in the original table is pTab->iPKey.)
121957    */
121958    bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
121959    if( pColumn ){
121960      for(i=0; i<pColumn->nId; i++){
121961        pColumn->a[i].idx = -1;
121962      }
121963      for(i=0; i<pColumn->nId; i++){
121964        for(j=0; j<pTab->nCol; j++){
121965          if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
121966            pColumn->a[i].idx = j;
121967            if( i!=j ) bIdListInOrder = 0;
121968            if( j==pTab->iPKey ){
121969              ipkColumn = i;  assert( !withoutRowid );
121970            }
121971            break;
121972          }
121973        }
121974        if( j>=pTab->nCol ){
121975          if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
121976            ipkColumn = i;
121977            bIdListInOrder = 0;
121978          }else{
121979            sqlite3ErrorMsg(pParse, "table %S has no column named %s",
121980                pTabList, 0, pColumn->a[i].zName);
121981            pParse->checkSchema = 1;
121982            goto insert_cleanup;
121983          }
121984        }
121985      }
121986    }
121987  
121988    /* Figure out how many columns of data are supplied.  If the data
121989    ** is coming from a SELECT statement, then generate a co-routine that
121990    ** produces a single row of the SELECT on each invocation.  The
121991    ** co-routine is the common header to the 3rd and 4th templates.
121992    */
121993    if( pSelect ){
121994      /* Data is coming from a SELECT or from a multi-row VALUES clause.
121995      ** Generate a co-routine to run the SELECT. */
121996      int regYield;       /* Register holding co-routine entry-point */
121997      int addrTop;        /* Top of the co-routine */
121998      int rc;             /* Result code */
121999  
122000      regYield = ++pParse->nMem;
122001      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
122002      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
122003      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
122004      dest.iSdst = bIdListInOrder ? regData : 0;
122005      dest.nSdst = pTab->nCol;
122006      rc = sqlite3Select(pParse, pSelect, &dest);
122007      regFromSelect = dest.iSdst;
122008      if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
122009      sqlite3VdbeEndCoroutine(v, regYield);
122010      sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
122011      assert( pSelect->pEList );
122012      nColumn = pSelect->pEList->nExpr;
122013  
122014      /* Set useTempTable to TRUE if the result of the SELECT statement
122015      ** should be written into a temporary table (template 4).  Set to
122016      ** FALSE if each output row of the SELECT can be written directly into
122017      ** the destination table (template 3).
122018      **
122019      ** A temp table must be used if the table being updated is also one
122020      ** of the tables being read by the SELECT statement.  Also use a 
122021      ** temp table in the case of row triggers.
122022      */
122023      if( pTrigger || readsTable(pParse, iDb, pTab) ){
122024        useTempTable = 1;
122025      }
122026  
122027      if( useTempTable ){
122028        /* Invoke the coroutine to extract information from the SELECT
122029        ** and add it to a transient table srcTab.  The code generated
122030        ** here is from the 4th template:
122031        **
122032        **      B: open temp table
122033        **      L: yield X, goto M at EOF
122034        **         insert row from R..R+n into temp table
122035        **         goto L
122036        **      M: ...
122037        */
122038        int regRec;          /* Register to hold packed record */
122039        int regTempRowid;    /* Register to hold temp table ROWID */
122040        int addrL;           /* Label "L" */
122041  
122042        srcTab = pParse->nTab++;
122043        regRec = sqlite3GetTempReg(pParse);
122044        regTempRowid = sqlite3GetTempReg(pParse);
122045        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
122046        addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
122047        sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
122048        sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
122049        sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
122050        sqlite3VdbeGoto(v, addrL);
122051        sqlite3VdbeJumpHere(v, addrL);
122052        sqlite3ReleaseTempReg(pParse, regRec);
122053        sqlite3ReleaseTempReg(pParse, regTempRowid);
122054      }
122055    }else{
122056      /* This is the case if the data for the INSERT is coming from a 
122057      ** single-row VALUES clause
122058      */
122059      NameContext sNC;
122060      memset(&sNC, 0, sizeof(sNC));
122061      sNC.pParse = pParse;
122062      srcTab = -1;
122063      assert( useTempTable==0 );
122064      if( pList ){
122065        nColumn = pList->nExpr;
122066        if( sqlite3ResolveExprListNames(&sNC, pList) ){
122067          goto insert_cleanup;
122068        }
122069      }else{
122070        nColumn = 0;
122071      }
122072    }
122073  
122074    /* If there is no IDLIST term but the table has an integer primary
122075    ** key, the set the ipkColumn variable to the integer primary key 
122076    ** column index in the original table definition.
122077    */
122078    if( pColumn==0 && nColumn>0 ){
122079      ipkColumn = pTab->iPKey;
122080    }
122081  
122082    /* Make sure the number of columns in the source data matches the number
122083    ** of columns to be inserted into the table.
122084    */
122085    for(i=0; i<pTab->nCol; i++){
122086      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
122087    }
122088    if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
122089      sqlite3ErrorMsg(pParse, 
122090         "table %S has %d columns but %d values were supplied",
122091         pTabList, 0, pTab->nCol-nHidden, nColumn);
122092      goto insert_cleanup;
122093    }
122094    if( pColumn!=0 && nColumn!=pColumn->nId ){
122095      sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
122096      goto insert_cleanup;
122097    }
122098      
122099    /* Initialize the count of rows to be inserted
122100    */
122101    if( (db->flags & SQLITE_CountRows)!=0
122102     && !pParse->nested
122103     && !pParse->pTriggerTab
122104    ){
122105      regRowCount = ++pParse->nMem;
122106      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
122107    }
122108  
122109    /* If this is not a view, open the table and and all indices */
122110    if( !isView ){
122111      int nIdx;
122112      nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
122113                                        &iDataCur, &iIdxCur);
122114      aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
122115      if( aRegIdx==0 ){
122116        goto insert_cleanup;
122117      }
122118      for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
122119        assert( pIdx );
122120        aRegIdx[i] = ++pParse->nMem;
122121        pParse->nMem += pIdx->nColumn;
122122      }
122123    }
122124  #ifndef SQLITE_OMIT_UPSERT
122125    if( pUpsert ){
122126      if( IsVirtual(pTab) ){
122127        sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
122128                pTab->zName);
122129        goto insert_cleanup;
122130      }
122131      pTabList->a[0].iCursor = iDataCur;
122132      pUpsert->pUpsertSrc = pTabList;
122133      pUpsert->regData = regData;
122134      pUpsert->iDataCur = iDataCur;
122135      pUpsert->iIdxCur = iIdxCur;
122136      if( pUpsert->pUpsertTarget ){
122137        sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
122138      }
122139    }
122140  #endif
122141  
122142  
122143    /* This is the top of the main insertion loop */
122144    if( useTempTable ){
122145      /* This block codes the top of loop only.  The complete loop is the
122146      ** following pseudocode (template 4):
122147      **
122148      **         rewind temp table, if empty goto D
122149      **      C: loop over rows of intermediate table
122150      **           transfer values form intermediate table into <table>
122151      **         end loop
122152      **      D: ...
122153      */
122154      addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
122155      addrCont = sqlite3VdbeCurrentAddr(v);
122156    }else if( pSelect ){
122157      /* This block codes the top of loop only.  The complete loop is the
122158      ** following pseudocode (template 3):
122159      **
122160      **      C: yield X, at EOF goto D
122161      **         insert the select result into <table> from R..R+n
122162      **         goto C
122163      **      D: ...
122164      */
122165      addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
122166      VdbeCoverage(v);
122167    }
122168  
122169    /* Run the BEFORE and INSTEAD OF triggers, if there are any
122170    */
122171    endOfLoop = sqlite3VdbeMakeLabel(pParse);
122172    if( tmask & TRIGGER_BEFORE ){
122173      int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
122174  
122175      /* build the NEW.* reference row.  Note that if there is an INTEGER
122176      ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
122177      ** translated into a unique ID for the row.  But on a BEFORE trigger,
122178      ** we do not know what the unique ID will be (because the insert has
122179      ** not happened yet) so we substitute a rowid of -1
122180      */
122181      if( ipkColumn<0 ){
122182        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
122183      }else{
122184        int addr1;
122185        assert( !withoutRowid );
122186        if( useTempTable ){
122187          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
122188        }else{
122189          assert( pSelect==0 );  /* Otherwise useTempTable is true */
122190          sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
122191        }
122192        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
122193        sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
122194        sqlite3VdbeJumpHere(v, addr1);
122195        sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
122196      }
122197  
122198      /* Cannot have triggers on a virtual table. If it were possible,
122199      ** this block would have to account for hidden column.
122200      */
122201      assert( !IsVirtual(pTab) );
122202  
122203      /* Create the new column data
122204      */
122205      for(i=j=0; i<pTab->nCol; i++){
122206        if( pColumn ){
122207          for(j=0; j<pColumn->nId; j++){
122208            if( pColumn->a[j].idx==i ) break;
122209          }
122210        }
122211        if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
122212              || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
122213          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
122214        }else if( useTempTable ){
122215          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
122216        }else{
122217          assert( pSelect==0 ); /* Otherwise useTempTable is true */
122218          sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
122219        }
122220        if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
122221      }
122222  
122223      /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
122224      ** do not attempt any conversions before assembling the record.
122225      ** If this is a real table, attempt conversions as required by the
122226      ** table column affinities.
122227      */
122228      if( !isView ){
122229        sqlite3TableAffinity(v, pTab, regCols+1);
122230      }
122231  
122232      /* Fire BEFORE or INSTEAD OF triggers */
122233      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
122234          pTab, regCols-pTab->nCol-1, onError, endOfLoop);
122235  
122236      sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
122237    }
122238  
122239    /* Compute the content of the next row to insert into a range of
122240    ** registers beginning at regIns.
122241    */
122242    if( !isView ){
122243      if( IsVirtual(pTab) ){
122244        /* The row that the VUpdate opcode will delete: none */
122245        sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
122246      }
122247      if( ipkColumn>=0 ){
122248        if( useTempTable ){
122249          sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
122250        }else if( pSelect ){
122251          sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
122252        }else{
122253          Expr *pIpk = pList->a[ipkColumn].pExpr;
122254          if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
122255            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
122256            appendFlag = 1;
122257          }else{
122258            sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
122259          }
122260        }
122261        /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
122262        ** to generate a unique primary key value.
122263        */
122264        if( !appendFlag ){
122265          int addr1;
122266          if( !IsVirtual(pTab) ){
122267            addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
122268            sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
122269            sqlite3VdbeJumpHere(v, addr1);
122270          }else{
122271            addr1 = sqlite3VdbeCurrentAddr(v);
122272            sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
122273          }
122274          sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
122275        }
122276      }else if( IsVirtual(pTab) || withoutRowid ){
122277        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
122278      }else{
122279        sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
122280        appendFlag = 1;
122281      }
122282      autoIncStep(pParse, regAutoinc, regRowid);
122283  
122284      /* Compute data for all columns of the new entry, beginning
122285      ** with the first column.
122286      */
122287      nHidden = 0;
122288      for(i=0; i<pTab->nCol; i++){
122289        int iRegStore = regRowid+1+i;
122290        if( i==pTab->iPKey ){
122291          /* The value of the INTEGER PRIMARY KEY column is always a NULL.
122292          ** Whenever this column is read, the rowid will be substituted
122293          ** in its place.  Hence, fill this column with a NULL to avoid
122294          ** taking up data space with information that will never be used.
122295          ** As there may be shallow copies of this value, make it a soft-NULL */
122296          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
122297          continue;
122298        }
122299        if( pColumn==0 ){
122300          if( IsHiddenColumn(&pTab->aCol[i]) ){
122301            j = -1;
122302            nHidden++;
122303          }else{
122304            j = i - nHidden;
122305          }
122306        }else{
122307          for(j=0; j<pColumn->nId; j++){
122308            if( pColumn->a[j].idx==i ) break;
122309          }
122310        }
122311        if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
122312          sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
122313        }else if( useTempTable ){
122314          sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
122315        }else if( pSelect ){
122316          if( regFromSelect!=regData ){
122317            sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
122318          }
122319        }else{
122320          sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
122321        }
122322      }
122323  
122324      /* Generate code to check constraints and generate index keys and
122325      ** do the insertion.
122326      */
122327  #ifndef SQLITE_OMIT_VIRTUALTABLE
122328      if( IsVirtual(pTab) ){
122329        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
122330        sqlite3VtabMakeWritable(pParse, pTab);
122331        sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
122332        sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
122333        sqlite3MayAbort(pParse);
122334      }else
122335  #endif
122336      {
122337        int isReplace;    /* Set to true if constraints may cause a replace */
122338        int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
122339        sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
122340            regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
122341        );
122342        sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
122343  
122344        /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
122345        ** constraints or (b) there are no triggers and this table is not a
122346        ** parent table in a foreign key constraint. It is safe to set the
122347        ** flag in the second case as if any REPLACE constraint is hit, an
122348        ** OP_Delete or OP_IdxDelete instruction will be executed on each 
122349        ** cursor that is disturbed. And these instructions both clear the
122350        ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
122351        ** functionality.  */
122352        bUseSeek = (isReplace==0 || (pTrigger==0 &&
122353            ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
122354        ));
122355        sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
122356            regIns, aRegIdx, 0, appendFlag, bUseSeek
122357        );
122358      }
122359    }
122360  
122361    /* Update the count of rows that are inserted
122362    */
122363    if( regRowCount ){
122364      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
122365    }
122366  
122367    if( pTrigger ){
122368      /* Code AFTER triggers */
122369      sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
122370          pTab, regData-2-pTab->nCol, onError, endOfLoop);
122371    }
122372  
122373    /* The bottom of the main insertion loop, if the data source
122374    ** is a SELECT statement.
122375    */
122376    sqlite3VdbeResolveLabel(v, endOfLoop);
122377    if( useTempTable ){
122378      sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
122379      sqlite3VdbeJumpHere(v, addrInsTop);
122380      sqlite3VdbeAddOp1(v, OP_Close, srcTab);
122381    }else if( pSelect ){
122382      sqlite3VdbeGoto(v, addrCont);
122383      sqlite3VdbeJumpHere(v, addrInsTop);
122384    }
122385  
122386  insert_end:
122387    /* Update the sqlite_sequence table by storing the content of the
122388    ** maximum rowid counter values recorded while inserting into
122389    ** autoincrement tables.
122390    */
122391    if( pParse->nested==0 && pParse->pTriggerTab==0 ){
122392      sqlite3AutoincrementEnd(pParse);
122393    }
122394  
122395    /*
122396    ** Return the number of rows inserted. If this routine is 
122397    ** generating code because of a call to sqlite3NestedParse(), do not
122398    ** invoke the callback function.
122399    */
122400    if( regRowCount ){
122401      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
122402      sqlite3VdbeSetNumCols(v, 1);
122403      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
122404    }
122405  
122406  insert_cleanup:
122407    sqlite3SrcListDelete(db, pTabList);
122408    sqlite3ExprListDelete(db, pList);
122409    sqlite3UpsertDelete(db, pUpsert);
122410    sqlite3SelectDelete(db, pSelect);
122411    sqlite3IdListDelete(db, pColumn);
122412    sqlite3DbFree(db, aRegIdx);
122413  }
122414  
122415  /* Make sure "isView" and other macros defined above are undefined. Otherwise
122416  ** they may interfere with compilation of other functions in this file
122417  ** (or in another file, if this file becomes part of the amalgamation).  */
122418  #ifdef isView
122419   #undef isView
122420  #endif
122421  #ifdef pTrigger
122422   #undef pTrigger
122423  #endif
122424  #ifdef tmask
122425   #undef tmask
122426  #endif
122427  
122428  /*
122429  ** Meanings of bits in of pWalker->eCode for 
122430  ** sqlite3ExprReferencesUpdatedColumn()
122431  */
122432  #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
122433  #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
122434  
122435  /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
122436  *  Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
122437  ** expression node references any of the
122438  ** columns that are being modifed by an UPDATE statement.
122439  */
122440  static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
122441    if( pExpr->op==TK_COLUMN ){
122442      assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
122443      if( pExpr->iColumn>=0 ){
122444        if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
122445          pWalker->eCode |= CKCNSTRNT_COLUMN;
122446        }
122447      }else{
122448        pWalker->eCode |= CKCNSTRNT_ROWID;
122449      }
122450    }
122451    return WRC_Continue;
122452  }
122453  
122454  /*
122455  ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
122456  ** only columns that are modified by the UPDATE are those for which
122457  ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
122458  **
122459  ** Return true if CHECK constraint pExpr uses any of the
122460  ** changing columns (or the rowid if it is changing).  In other words,
122461  ** return true if this CHECK constraint must be validated for
122462  ** the new row in the UPDATE statement.
122463  **
122464  ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
122465  ** The operation of this routine is the same - return true if an only if
122466  ** the expression uses one or more of columns identified by the second and
122467  ** third arguments.
122468  */
122469  SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
122470    Expr *pExpr,    /* The expression to be checked */
122471    int *aiChng,    /* aiChng[x]>=0 if column x changed by the UPDATE */
122472    int chngRowid   /* True if UPDATE changes the rowid */
122473  ){
122474    Walker w;
122475    memset(&w, 0, sizeof(w));
122476    w.eCode = 0;
122477    w.xExprCallback = checkConstraintExprNode;
122478    w.u.aiCol = aiChng;
122479    sqlite3WalkExpr(&w, pExpr);
122480    if( !chngRowid ){
122481      testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
122482      w.eCode &= ~CKCNSTRNT_ROWID;
122483    }
122484    testcase( w.eCode==0 );
122485    testcase( w.eCode==CKCNSTRNT_COLUMN );
122486    testcase( w.eCode==CKCNSTRNT_ROWID );
122487    testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
122488    return w.eCode!=0;
122489  }
122490  
122491  /*
122492  ** Generate code to do constraint checks prior to an INSERT or an UPDATE
122493  ** on table pTab.
122494  **
122495  ** The regNewData parameter is the first register in a range that contains
122496  ** the data to be inserted or the data after the update.  There will be
122497  ** pTab->nCol+1 registers in this range.  The first register (the one
122498  ** that regNewData points to) will contain the new rowid, or NULL in the
122499  ** case of a WITHOUT ROWID table.  The second register in the range will
122500  ** contain the content of the first table column.  The third register will
122501  ** contain the content of the second table column.  And so forth.
122502  **
122503  ** The regOldData parameter is similar to regNewData except that it contains
122504  ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
122505  ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
122506  ** checking regOldData for zero.
122507  **
122508  ** For an UPDATE, the pkChng boolean is true if the true primary key (the
122509  ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
122510  ** might be modified by the UPDATE.  If pkChng is false, then the key of
122511  ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
122512  **
122513  ** For an INSERT, the pkChng boolean indicates whether or not the rowid
122514  ** was explicitly specified as part of the INSERT statement.  If pkChng
122515  ** is zero, it means that the either rowid is computed automatically or
122516  ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
122517  ** pkChng will only be true if the INSERT statement provides an integer
122518  ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
122519  **
122520  ** The code generated by this routine will store new index entries into
122521  ** registers identified by aRegIdx[].  No index entry is created for
122522  ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
122523  ** the same as the order of indices on the linked list of indices
122524  ** at pTab->pIndex.
122525  **
122526  ** The caller must have already opened writeable cursors on the main
122527  ** table and all applicable indices (that is to say, all indices for which
122528  ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
122529  ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
122530  ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
122531  ** for the first index in the pTab->pIndex list.  Cursors for other indices
122532  ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
122533  **
122534  ** This routine also generates code to check constraints.  NOT NULL,
122535  ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
122536  ** then the appropriate action is performed.  There are five possible
122537  ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
122538  **
122539  **  Constraint type  Action       What Happens
122540  **  ---------------  ----------   ----------------------------------------
122541  **  any              ROLLBACK     The current transaction is rolled back and
122542  **                                sqlite3_step() returns immediately with a
122543  **                                return code of SQLITE_CONSTRAINT.
122544  **
122545  **  any              ABORT        Back out changes from the current command
122546  **                                only (do not do a complete rollback) then
122547  **                                cause sqlite3_step() to return immediately
122548  **                                with SQLITE_CONSTRAINT.
122549  **
122550  **  any              FAIL         Sqlite3_step() returns immediately with a
122551  **                                return code of SQLITE_CONSTRAINT.  The
122552  **                                transaction is not rolled back and any
122553  **                                changes to prior rows are retained.
122554  **
122555  **  any              IGNORE       The attempt in insert or update the current
122556  **                                row is skipped, without throwing an error.
122557  **                                Processing continues with the next row.
122558  **                                (There is an immediate jump to ignoreDest.)
122559  **
122560  **  NOT NULL         REPLACE      The NULL value is replace by the default
122561  **                                value for that column.  If the default value
122562  **                                is NULL, the action is the same as ABORT.
122563  **
122564  **  UNIQUE           REPLACE      The other row that conflicts with the row
122565  **                                being inserted is removed.
122566  **
122567  **  CHECK            REPLACE      Illegal.  The results in an exception.
122568  **
122569  ** Which action to take is determined by the overrideError parameter.
122570  ** Or if overrideError==OE_Default, then the pParse->onError parameter
122571  ** is used.  Or if pParse->onError==OE_Default then the onError value
122572  ** for the constraint is used.
122573  */
122574  SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
122575    Parse *pParse,       /* The parser context */
122576    Table *pTab,         /* The table being inserted or updated */
122577    int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
122578    int iDataCur,        /* Canonical data cursor (main table or PK index) */
122579    int iIdxCur,         /* First index cursor */
122580    int regNewData,      /* First register in a range holding values to insert */
122581    int regOldData,      /* Previous content.  0 for INSERTs */
122582    u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
122583    u8 overrideError,    /* Override onError to this if not OE_Default */
122584    int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
122585    int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
122586    int *aiChng,         /* column i is unchanged if aiChng[i]<0 */
122587    Upsert *pUpsert      /* ON CONFLICT clauses, if any.  NULL otherwise */
122588  ){
122589    Vdbe *v;             /* VDBE under constrution */
122590    Index *pIdx;         /* Pointer to one of the indices */
122591    Index *pPk = 0;      /* The PRIMARY KEY index */
122592    sqlite3 *db;         /* Database connection */
122593    int i;               /* loop counter */
122594    int ix;              /* Index loop counter */
122595    int nCol;            /* Number of columns */
122596    int onError;         /* Conflict resolution strategy */
122597    int addr1;           /* Address of jump instruction */
122598    int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
122599    int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
122600    Index *pUpIdx = 0;   /* Index to which to apply the upsert */
122601    u8 isUpdate;         /* True if this is an UPDATE operation */
122602    u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
122603    int upsertBypass = 0;  /* Address of Goto to bypass upsert subroutine */
122604    int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
122605    int ipkTop = 0;        /* Top of the IPK uniqueness check */
122606    int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
122607  
122608    isUpdate = regOldData!=0;
122609    db = pParse->db;
122610    v = sqlite3GetVdbe(pParse);
122611    assert( v!=0 );
122612    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
122613    nCol = pTab->nCol;
122614    
122615    /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
122616    ** normal rowid tables.  nPkField is the number of key fields in the 
122617    ** pPk index or 1 for a rowid table.  In other words, nPkField is the
122618    ** number of fields in the true primary key of the table. */
122619    if( HasRowid(pTab) ){
122620      pPk = 0;
122621      nPkField = 1;
122622    }else{
122623      pPk = sqlite3PrimaryKeyIndex(pTab);
122624      nPkField = pPk->nKeyCol;
122625    }
122626  
122627    /* Record that this module has started */
122628    VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
122629                       iDataCur, iIdxCur, regNewData, regOldData, pkChng));
122630  
122631    /* Test all NOT NULL constraints.
122632    */
122633    for(i=0; i<nCol; i++){
122634      if( i==pTab->iPKey ){
122635        continue;        /* ROWID is never NULL */
122636      }
122637      if( aiChng && aiChng[i]<0 ){
122638        /* Don't bother checking for NOT NULL on columns that do not change */
122639        continue;
122640      }
122641      onError = pTab->aCol[i].notNull;
122642      if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
122643      if( overrideError!=OE_Default ){
122644        onError = overrideError;
122645      }else if( onError==OE_Default ){
122646        onError = OE_Abort;
122647      }
122648      if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
122649        onError = OE_Abort;
122650      }
122651      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
122652          || onError==OE_Ignore || onError==OE_Replace );
122653      addr1 = 0;
122654      switch( onError ){
122655        case OE_Replace: {
122656          assert( onError==OE_Replace );
122657          addr1 = sqlite3VdbeMakeLabel(pParse);
122658          sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
122659            VdbeCoverage(v);
122660          sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
122661          sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
122662            VdbeCoverage(v);
122663          onError = OE_Abort;
122664          /* Fall through into the OE_Abort case to generate code that runs
122665          ** if both the input and the default value are NULL */
122666        }
122667        case OE_Abort:
122668          sqlite3MayAbort(pParse);
122669          /* Fall through */
122670        case OE_Rollback:
122671        case OE_Fail: {
122672          char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
122673                                      pTab->aCol[i].zName);
122674          sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
122675                            regNewData+1+i);
122676          sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
122677          sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
122678          VdbeCoverage(v);
122679          if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
122680          break;
122681        }
122682        default: {
122683          assert( onError==OE_Ignore );
122684          sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
122685          VdbeCoverage(v);
122686          break;
122687        }
122688      }
122689    }
122690  
122691    /* Test all CHECK constraints
122692    */
122693  #ifndef SQLITE_OMIT_CHECK
122694    if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
122695      ExprList *pCheck = pTab->pCheck;
122696      pParse->iSelfTab = -(regNewData+1);
122697      onError = overrideError!=OE_Default ? overrideError : OE_Abort;
122698      for(i=0; i<pCheck->nExpr; i++){
122699        int allOk;
122700        Expr *pExpr = pCheck->a[i].pExpr;
122701        if( aiChng
122702         && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
122703        ){
122704          /* The check constraints do not reference any of the columns being
122705          ** updated so there is no point it verifying the check constraint */
122706          continue;
122707        }
122708        allOk = sqlite3VdbeMakeLabel(pParse);
122709        sqlite3VdbeVerifyAbortable(v, onError);
122710        sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
122711        if( onError==OE_Ignore ){
122712          sqlite3VdbeGoto(v, ignoreDest);
122713        }else{
122714          char *zName = pCheck->a[i].zName;
122715          if( zName==0 ) zName = pTab->zName;
122716          if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
122717          sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
122718                                onError, zName, P4_TRANSIENT,
122719                                P5_ConstraintCheck);
122720        }
122721        sqlite3VdbeResolveLabel(v, allOk);
122722      }
122723      pParse->iSelfTab = 0;
122724    }
122725  #endif /* !defined(SQLITE_OMIT_CHECK) */
122726  
122727    /* UNIQUE and PRIMARY KEY constraints should be handled in the following
122728    ** order:
122729    **
122730    **   (1)  OE_Update
122731    **   (2)  OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
122732    **   (3)  OE_Replace
122733    **
122734    ** OE_Fail and OE_Ignore must happen before any changes are made.
122735    ** OE_Update guarantees that only a single row will change, so it
122736    ** must happen before OE_Replace.  Technically, OE_Abort and OE_Rollback
122737    ** could happen in any order, but they are grouped up front for
122738    ** convenience.
122739    **
122740    ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
122741    ** The order of constraints used to have OE_Update as (2) and OE_Abort
122742    ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
122743    ** constraint before any others, so it had to be moved.
122744    **
122745    ** Constraint checking code is generated in this order:
122746    **   (A)  The rowid constraint
122747    **   (B)  Unique index constraints that do not have OE_Replace as their
122748    **        default conflict resolution strategy
122749    **   (C)  Unique index that do use OE_Replace by default.
122750    **
122751    ** The ordering of (2) and (3) is accomplished by making sure the linked
122752    ** list of indexes attached to a table puts all OE_Replace indexes last
122753    ** in the list.  See sqlite3CreateIndex() for where that happens.
122754    */
122755  
122756    if( pUpsert ){
122757      if( pUpsert->pUpsertTarget==0 ){
122758        /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
122759        ** Make all unique constraint resolution be OE_Ignore */
122760        assert( pUpsert->pUpsertSet==0 );
122761        overrideError = OE_Ignore;
122762        pUpsert = 0;
122763      }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
122764        /* If the constraint-target uniqueness check must be run first.
122765        ** Jump to that uniqueness check now */
122766        upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
122767        VdbeComment((v, "UPSERT constraint goes first"));
122768      }
122769    }
122770  
122771    /* If rowid is changing, make sure the new rowid does not previously
122772    ** exist in the table.
122773    */
122774    if( pkChng && pPk==0 ){
122775      int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
122776  
122777      /* Figure out what action to take in case of a rowid collision */
122778      onError = pTab->keyConf;
122779      if( overrideError!=OE_Default ){
122780        onError = overrideError;
122781      }else if( onError==OE_Default ){
122782        onError = OE_Abort;
122783      }
122784  
122785      /* figure out whether or not upsert applies in this case */
122786      if( pUpsert && pUpsert->pUpsertIdx==0 ){
122787        if( pUpsert->pUpsertSet==0 ){
122788          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
122789        }else{
122790          onError = OE_Update;  /* DO UPDATE */
122791        }
122792      }
122793  
122794      /* If the response to a rowid conflict is REPLACE but the response
122795      ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
122796      ** to defer the running of the rowid conflict checking until after
122797      ** the UNIQUE constraints have run.
122798      */
122799      if( onError==OE_Replace      /* IPK rule is REPLACE */
122800       && onError!=overrideError   /* Rules for other contraints are different */
122801       && pTab->pIndex             /* There exist other constraints */
122802      ){
122803        ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
122804        VdbeComment((v, "defer IPK REPLACE until last"));
122805      }
122806  
122807      if( isUpdate ){
122808        /* pkChng!=0 does not mean that the rowid has changed, only that
122809        ** it might have changed.  Skip the conflict logic below if the rowid
122810        ** is unchanged. */
122811        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
122812        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
122813        VdbeCoverage(v);
122814      }
122815  
122816      /* Check to see if the new rowid already exists in the table.  Skip
122817      ** the following conflict logic if it does not. */
122818      VdbeNoopComment((v, "uniqueness check for ROWID"));
122819      sqlite3VdbeVerifyAbortable(v, onError);
122820      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
122821      VdbeCoverage(v);
122822  
122823      switch( onError ){
122824        default: {
122825          onError = OE_Abort;
122826          /* Fall thru into the next case */
122827        }
122828        case OE_Rollback:
122829        case OE_Abort:
122830        case OE_Fail: {
122831          testcase( onError==OE_Rollback );
122832          testcase( onError==OE_Abort );
122833          testcase( onError==OE_Fail );
122834          sqlite3RowidConstraint(pParse, onError, pTab);
122835          break;
122836        }
122837        case OE_Replace: {
122838          /* If there are DELETE triggers on this table and the
122839          ** recursive-triggers flag is set, call GenerateRowDelete() to
122840          ** remove the conflicting row from the table. This will fire
122841          ** the triggers and remove both the table and index b-tree entries.
122842          **
122843          ** Otherwise, if there are no triggers or the recursive-triggers
122844          ** flag is not set, but the table has one or more indexes, call 
122845          ** GenerateRowIndexDelete(). This removes the index b-tree entries 
122846          ** only. The table b-tree entry will be replaced by the new entry 
122847          ** when it is inserted.  
122848          **
122849          ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
122850          ** also invoke MultiWrite() to indicate that this VDBE may require
122851          ** statement rollback (if the statement is aborted after the delete
122852          ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
122853          ** but being more selective here allows statements like:
122854          **
122855          **   REPLACE INTO t(rowid) VALUES($newrowid)
122856          **
122857          ** to run without a statement journal if there are no indexes on the
122858          ** table.
122859          */
122860          Trigger *pTrigger = 0;
122861          if( db->flags&SQLITE_RecTriggers ){
122862            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
122863          }
122864          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
122865            sqlite3MultiWrite(pParse);
122866            sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
122867                                     regNewData, 1, 0, OE_Replace, 1, -1);
122868          }else{
122869  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
122870            assert( HasRowid(pTab) );
122871            /* This OP_Delete opcode fires the pre-update-hook only. It does
122872            ** not modify the b-tree. It is more efficient to let the coming
122873            ** OP_Insert replace the existing entry than it is to delete the
122874            ** existing entry and then insert a new one. */
122875            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
122876            sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
122877  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
122878            if( pTab->pIndex ){
122879              sqlite3MultiWrite(pParse);
122880              sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
122881            }
122882          }
122883          seenReplace = 1;
122884          break;
122885        }
122886  #ifndef SQLITE_OMIT_UPSERT
122887        case OE_Update: {
122888          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
122889          /* Fall through */
122890        }
122891  #endif
122892        case OE_Ignore: {
122893          testcase( onError==OE_Ignore );
122894          sqlite3VdbeGoto(v, ignoreDest);
122895          break;
122896        }
122897      }
122898      sqlite3VdbeResolveLabel(v, addrRowidOk);
122899      if( ipkTop ){
122900        ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
122901        sqlite3VdbeJumpHere(v, ipkTop-1);
122902      }
122903    }
122904  
122905    /* Test all UNIQUE constraints by creating entries for each UNIQUE
122906    ** index and making sure that duplicate entries do not already exist.
122907    ** Compute the revised record entries for indices as we go.
122908    **
122909    ** This loop also handles the case of the PRIMARY KEY index for a
122910    ** WITHOUT ROWID table.
122911    */
122912    for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
122913      int regIdx;          /* Range of registers hold conent for pIdx */
122914      int regR;            /* Range of registers holding conflicting PK */
122915      int iThisCur;        /* Cursor for this UNIQUE index */
122916      int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
122917  
122918      if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
122919      if( pUpIdx==pIdx ){
122920        addrUniqueOk = upsertJump+1;
122921        upsertBypass = sqlite3VdbeGoto(v, 0);
122922        VdbeComment((v, "Skip upsert subroutine"));
122923        sqlite3VdbeJumpHere(v, upsertJump);
122924      }else{
122925        addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
122926      }
122927      if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
122928        sqlite3TableAffinity(v, pTab, regNewData+1);
122929        bAffinityDone = 1;
122930      }
122931      VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
122932      iThisCur = iIdxCur+ix;
122933  
122934  
122935      /* Skip partial indices for which the WHERE clause is not true */
122936      if( pIdx->pPartIdxWhere ){
122937        sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
122938        pParse->iSelfTab = -(regNewData+1);
122939        sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
122940                              SQLITE_JUMPIFNULL);
122941        pParse->iSelfTab = 0;
122942      }
122943  
122944      /* Create a record for this index entry as it should appear after
122945      ** the insert or update.  Store that record in the aRegIdx[ix] register
122946      */
122947      regIdx = aRegIdx[ix]+1;
122948      for(i=0; i<pIdx->nColumn; i++){
122949        int iField = pIdx->aiColumn[i];
122950        int x;
122951        if( iField==XN_EXPR ){
122952          pParse->iSelfTab = -(regNewData+1);
122953          sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
122954          pParse->iSelfTab = 0;
122955          VdbeComment((v, "%s column %d", pIdx->zName, i));
122956        }else{
122957          if( iField==XN_ROWID || iField==pTab->iPKey ){
122958            x = regNewData;
122959          }else{
122960            x = iField + regNewData + 1;
122961          }
122962          sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
122963          VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
122964        }
122965      }
122966      sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
122967      VdbeComment((v, "for %s", pIdx->zName));
122968  #ifdef SQLITE_ENABLE_NULL_TRIM
122969      if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
122970  #endif
122971  
122972      /* In an UPDATE operation, if this index is the PRIMARY KEY index 
122973      ** of a WITHOUT ROWID table and there has been no change the
122974      ** primary key, then no collision is possible.  The collision detection
122975      ** logic below can all be skipped. */
122976      if( isUpdate && pPk==pIdx && pkChng==0 ){
122977        sqlite3VdbeResolveLabel(v, addrUniqueOk);
122978        continue;
122979      }
122980  
122981      /* Find out what action to take in case there is a uniqueness conflict */
122982      onError = pIdx->onError;
122983      if( onError==OE_None ){ 
122984        sqlite3VdbeResolveLabel(v, addrUniqueOk);
122985        continue;  /* pIdx is not a UNIQUE index */
122986      }
122987      if( overrideError!=OE_Default ){
122988        onError = overrideError;
122989      }else if( onError==OE_Default ){
122990        onError = OE_Abort;
122991      }
122992  
122993      /* Figure out if the upsert clause applies to this index */
122994      if( pUpIdx==pIdx ){
122995        if( pUpsert->pUpsertSet==0 ){
122996          onError = OE_Ignore;  /* DO NOTHING is the same as INSERT OR IGNORE */
122997        }else{
122998          onError = OE_Update;  /* DO UPDATE */
122999        }
123000      }
123001  
123002      /* Collision detection may be omitted if all of the following are true:
123003      **   (1) The conflict resolution algorithm is REPLACE
123004      **   (2) The table is a WITHOUT ROWID table
123005      **   (3) There are no secondary indexes on the table
123006      **   (4) No delete triggers need to be fired if there is a conflict
123007      **   (5) No FK constraint counters need to be updated if a conflict occurs.
123008      **
123009      ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
123010      ** must be explicitly deleted in order to ensure any pre-update hook
123011      ** is invoked.  */ 
123012  #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
123013      if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
123014       && pPk==pIdx                                   /* Condition 2 */
123015       && onError==OE_Replace                         /* Condition 1 */
123016       && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
123017            0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
123018       && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
123019           (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
123020      ){
123021        sqlite3VdbeResolveLabel(v, addrUniqueOk);
123022        continue;
123023      }
123024  #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
123025  
123026      /* Check to see if the new index entry will be unique */
123027      sqlite3VdbeVerifyAbortable(v, onError);
123028      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
123029                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);
123030  
123031      /* Generate code to handle collisions */
123032      regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
123033      if( isUpdate || onError==OE_Replace ){
123034        if( HasRowid(pTab) ){
123035          sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
123036          /* Conflict only if the rowid of the existing index entry
123037          ** is different from old-rowid */
123038          if( isUpdate ){
123039            sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
123040            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
123041            VdbeCoverage(v);
123042          }
123043        }else{
123044          int x;
123045          /* Extract the PRIMARY KEY from the end of the index entry and
123046          ** store it in registers regR..regR+nPk-1 */
123047          if( pIdx!=pPk ){
123048            for(i=0; i<pPk->nKeyCol; i++){
123049              assert( pPk->aiColumn[i]>=0 );
123050              x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
123051              sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
123052              VdbeComment((v, "%s.%s", pTab->zName,
123053                           pTab->aCol[pPk->aiColumn[i]].zName));
123054            }
123055          }
123056          if( isUpdate ){
123057            /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
123058            ** table, only conflict if the new PRIMARY KEY values are actually
123059            ** different from the old.
123060            **
123061            ** For a UNIQUE index, only conflict if the PRIMARY KEY values
123062            ** of the matched index row are different from the original PRIMARY
123063            ** KEY values of this row before the update.  */
123064            int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
123065            int op = OP_Ne;
123066            int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
123067    
123068            for(i=0; i<pPk->nKeyCol; i++){
123069              char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
123070              x = pPk->aiColumn[i];
123071              assert( x>=0 );
123072              if( i==(pPk->nKeyCol-1) ){
123073                addrJump = addrUniqueOk;
123074                op = OP_Eq;
123075              }
123076              sqlite3VdbeAddOp4(v, op, 
123077                  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
123078              );
123079              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
123080              VdbeCoverageIf(v, op==OP_Eq);
123081              VdbeCoverageIf(v, op==OP_Ne);
123082            }
123083          }
123084        }
123085      }
123086  
123087      /* Generate code that executes if the new index entry is not unique */
123088      assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
123089          || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
123090      switch( onError ){
123091        case OE_Rollback:
123092        case OE_Abort:
123093        case OE_Fail: {
123094          testcase( onError==OE_Rollback );
123095          testcase( onError==OE_Abort );
123096          testcase( onError==OE_Fail );
123097          sqlite3UniqueConstraint(pParse, onError, pIdx);
123098          break;
123099        }
123100  #ifndef SQLITE_OMIT_UPSERT
123101        case OE_Update: {
123102          sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
123103          /* Fall through */
123104        }
123105  #endif
123106        case OE_Ignore: {
123107          testcase( onError==OE_Ignore );
123108          sqlite3VdbeGoto(v, ignoreDest);
123109          break;
123110        }
123111        default: {
123112          Trigger *pTrigger = 0;
123113          assert( onError==OE_Replace );
123114          if( db->flags&SQLITE_RecTriggers ){
123115            pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
123116          }
123117          if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
123118            sqlite3MultiWrite(pParse);
123119          }
123120          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
123121              regR, nPkField, 0, OE_Replace,
123122              (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
123123          seenReplace = 1;
123124          break;
123125        }
123126      }
123127      if( pUpIdx==pIdx ){
123128        sqlite3VdbeGoto(v, upsertJump+1);
123129        sqlite3VdbeJumpHere(v, upsertBypass);
123130      }else{
123131        sqlite3VdbeResolveLabel(v, addrUniqueOk);
123132      }
123133      if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
123134    }
123135  
123136    /* If the IPK constraint is a REPLACE, run it last */
123137    if( ipkTop ){
123138      sqlite3VdbeGoto(v, ipkTop);
123139      VdbeComment((v, "Do IPK REPLACE"));
123140      sqlite3VdbeJumpHere(v, ipkBottom);
123141    }
123142  
123143    *pbMayReplace = seenReplace;
123144    VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
123145  }
123146  
123147  #ifdef SQLITE_ENABLE_NULL_TRIM
123148  /*
123149  ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
123150  ** to be the number of columns in table pTab that must not be NULL-trimmed.
123151  **
123152  ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
123153  */
123154  SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
123155    u16 i;
123156  
123157    /* Records with omitted columns are only allowed for schema format
123158    ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
123159    if( pTab->pSchema->file_format<2 ) return;
123160  
123161    for(i=pTab->nCol-1; i>0; i--){
123162      if( pTab->aCol[i].pDflt!=0 ) break;
123163      if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
123164    }
123165    sqlite3VdbeChangeP5(v, i+1);
123166  }
123167  #endif
123168  
123169  /*
123170  ** This routine generates code to finish the INSERT or UPDATE operation
123171  ** that was started by a prior call to sqlite3GenerateConstraintChecks.
123172  ** A consecutive range of registers starting at regNewData contains the
123173  ** rowid and the content to be inserted.
123174  **
123175  ** The arguments to this routine should be the same as the first six
123176  ** arguments to sqlite3GenerateConstraintChecks.
123177  */
123178  SQLITE_PRIVATE void sqlite3CompleteInsertion(
123179    Parse *pParse,      /* The parser context */
123180    Table *pTab,        /* the table into which we are inserting */
123181    int iDataCur,       /* Cursor of the canonical data source */
123182    int iIdxCur,        /* First index cursor */
123183    int regNewData,     /* Range of content */
123184    int *aRegIdx,       /* Register used by each index.  0 for unused indices */
123185    int update_flags,   /* True for UPDATE, False for INSERT */
123186    int appendBias,     /* True if this is likely to be an append */
123187    int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
123188  ){
123189    Vdbe *v;            /* Prepared statements under construction */
123190    Index *pIdx;        /* An index being inserted or updated */
123191    u8 pik_flags;       /* flag values passed to the btree insert */
123192    int regData;        /* Content registers (after the rowid) */
123193    int regRec;         /* Register holding assembled record for the table */
123194    int i;              /* Loop counter */
123195    u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
123196  
123197    assert( update_flags==0
123198         || update_flags==OPFLAG_ISUPDATE
123199         || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
123200    );
123201  
123202    v = sqlite3GetVdbe(pParse);
123203    assert( v!=0 );
123204    assert( pTab->pSelect==0 );  /* This table is not a VIEW */
123205    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
123206      if( aRegIdx[i]==0 ) continue;
123207      bAffinityDone = 1;
123208      if( pIdx->pPartIdxWhere ){
123209        sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
123210        VdbeCoverage(v);
123211      }
123212      pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
123213      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
123214        assert( pParse->nested==0 );
123215        pik_flags |= OPFLAG_NCHANGE;
123216        pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
123217  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
123218        if( update_flags==0 ){
123219          int r = sqlite3GetTempReg(pParse);
123220          sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
123221          sqlite3VdbeAddOp4(v, OP_Insert, 
123222              iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
123223          );
123224          sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
123225          sqlite3ReleaseTempReg(pParse, r);
123226        }
123227  #endif
123228      }
123229      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
123230                           aRegIdx[i]+1,
123231                           pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
123232      sqlite3VdbeChangeP5(v, pik_flags);
123233    }
123234    if( !HasRowid(pTab) ) return;
123235    regData = regNewData + 1;
123236    regRec = sqlite3GetTempReg(pParse);
123237    sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
123238    sqlite3SetMakeRecordP5(v, pTab);
123239    if( !bAffinityDone ){
123240      sqlite3TableAffinity(v, pTab, 0);
123241    }
123242    if( pParse->nested ){
123243      pik_flags = 0;
123244    }else{
123245      pik_flags = OPFLAG_NCHANGE;
123246      pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
123247    }
123248    if( appendBias ){
123249      pik_flags |= OPFLAG_APPEND;
123250    }
123251    if( useSeekResult ){
123252      pik_flags |= OPFLAG_USESEEKRESULT;
123253    }
123254    sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
123255    if( !pParse->nested ){
123256      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
123257    }
123258    sqlite3VdbeChangeP5(v, pik_flags);
123259  }
123260  
123261  /*
123262  ** Allocate cursors for the pTab table and all its indices and generate
123263  ** code to open and initialized those cursors.
123264  **
123265  ** The cursor for the object that contains the complete data (normally
123266  ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
123267  ** ROWID table) is returned in *piDataCur.  The first index cursor is
123268  ** returned in *piIdxCur.  The number of indices is returned.
123269  **
123270  ** Use iBase as the first cursor (either the *piDataCur for rowid tables
123271  ** or the first index for WITHOUT ROWID tables) if it is non-negative.
123272  ** If iBase is negative, then allocate the next available cursor.
123273  **
123274  ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
123275  ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
123276  ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
123277  ** pTab->pIndex list.
123278  **
123279  ** If pTab is a virtual table, then this routine is a no-op and the
123280  ** *piDataCur and *piIdxCur values are left uninitialized.
123281  */
123282  SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
123283    Parse *pParse,   /* Parsing context */
123284    Table *pTab,     /* Table to be opened */
123285    int op,          /* OP_OpenRead or OP_OpenWrite */
123286    u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
123287    int iBase,       /* Use this for the table cursor, if there is one */
123288    u8 *aToOpen,     /* If not NULL: boolean for each table and index */
123289    int *piDataCur,  /* Write the database source cursor number here */
123290    int *piIdxCur    /* Write the first index cursor number here */
123291  ){
123292    int i;
123293    int iDb;
123294    int iDataCur;
123295    Index *pIdx;
123296    Vdbe *v;
123297  
123298    assert( op==OP_OpenRead || op==OP_OpenWrite );
123299    assert( op==OP_OpenWrite || p5==0 );
123300    if( IsVirtual(pTab) ){
123301      /* This routine is a no-op for virtual tables. Leave the output
123302      ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
123303      ** can detect if they are used by mistake in the caller. */
123304      return 0;
123305    }
123306    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
123307    v = sqlite3GetVdbe(pParse);
123308    assert( v!=0 );
123309    if( iBase<0 ) iBase = pParse->nTab;
123310    iDataCur = iBase++;
123311    if( piDataCur ) *piDataCur = iDataCur;
123312    if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
123313      sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
123314    }else{
123315      sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
123316    }
123317    if( piIdxCur ) *piIdxCur = iBase;
123318    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
123319      int iIdxCur = iBase++;
123320      assert( pIdx->pSchema==pTab->pSchema );
123321      if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
123322        if( piDataCur ) *piDataCur = iIdxCur;
123323        p5 = 0;
123324      }
123325      if( aToOpen==0 || aToOpen[i+1] ){
123326        sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
123327        sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
123328        sqlite3VdbeChangeP5(v, p5);
123329        VdbeComment((v, "%s", pIdx->zName));
123330      }
123331    }
123332    if( iBase>pParse->nTab ) pParse->nTab = iBase;
123333    return i;
123334  }
123335  
123336  
123337  #ifdef SQLITE_TEST
123338  /*
123339  ** The following global variable is incremented whenever the
123340  ** transfer optimization is used.  This is used for testing
123341  ** purposes only - to make sure the transfer optimization really
123342  ** is happening when it is supposed to.
123343  */
123344  SQLITE_API int sqlite3_xferopt_count;
123345  #endif /* SQLITE_TEST */
123346  
123347  
123348  #ifndef SQLITE_OMIT_XFER_OPT
123349  /*
123350  ** Check to see if index pSrc is compatible as a source of data
123351  ** for index pDest in an insert transfer optimization.  The rules
123352  ** for a compatible index:
123353  **
123354  **    *   The index is over the same set of columns
123355  **    *   The same DESC and ASC markings occurs on all columns
123356  **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
123357  **    *   The same collating sequence on each column
123358  **    *   The index has the exact same WHERE clause
123359  */
123360  static int xferCompatibleIndex(Index *pDest, Index *pSrc){
123361    int i;
123362    assert( pDest && pSrc );
123363    assert( pDest->pTable!=pSrc->pTable );
123364    if( pDest->nKeyCol!=pSrc->nKeyCol ){
123365      return 0;   /* Different number of columns */
123366    }
123367    if( pDest->onError!=pSrc->onError ){
123368      return 0;   /* Different conflict resolution strategies */
123369    }
123370    for(i=0; i<pSrc->nKeyCol; i++){
123371      if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
123372        return 0;   /* Different columns indexed */
123373      }
123374      if( pSrc->aiColumn[i]==XN_EXPR ){
123375        assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
123376        if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
123377                               pDest->aColExpr->a[i].pExpr, -1)!=0 ){
123378          return 0;   /* Different expressions in the index */
123379        }
123380      }
123381      if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
123382        return 0;   /* Different sort orders */
123383      }
123384      if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
123385        return 0;   /* Different collating sequences */
123386      }
123387    }
123388    if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
123389      return 0;     /* Different WHERE clauses */
123390    }
123391  
123392    /* If no test above fails then the indices must be compatible */
123393    return 1;
123394  }
123395  
123396  /*
123397  ** Attempt the transfer optimization on INSERTs of the form
123398  **
123399  **     INSERT INTO tab1 SELECT * FROM tab2;
123400  **
123401  ** The xfer optimization transfers raw records from tab2 over to tab1.  
123402  ** Columns are not decoded and reassembled, which greatly improves
123403  ** performance.  Raw index records are transferred in the same way.
123404  **
123405  ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
123406  ** There are lots of rules for determining compatibility - see comments
123407  ** embedded in the code for details.
123408  **
123409  ** This routine returns TRUE if the optimization is guaranteed to be used.
123410  ** Sometimes the xfer optimization will only work if the destination table
123411  ** is empty - a factor that can only be determined at run-time.  In that
123412  ** case, this routine generates code for the xfer optimization but also
123413  ** does a test to see if the destination table is empty and jumps over the
123414  ** xfer optimization code if the test fails.  In that case, this routine
123415  ** returns FALSE so that the caller will know to go ahead and generate
123416  ** an unoptimized transfer.  This routine also returns FALSE if there
123417  ** is no chance that the xfer optimization can be applied.
123418  **
123419  ** This optimization is particularly useful at making VACUUM run faster.
123420  */
123421  static int xferOptimization(
123422    Parse *pParse,        /* Parser context */
123423    Table *pDest,         /* The table we are inserting into */
123424    Select *pSelect,      /* A SELECT statement to use as the data source */
123425    int onError,          /* How to handle constraint errors */
123426    int iDbDest           /* The database of pDest */
123427  ){
123428    sqlite3 *db = pParse->db;
123429    ExprList *pEList;                /* The result set of the SELECT */
123430    Table *pSrc;                     /* The table in the FROM clause of SELECT */
123431    Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
123432    struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
123433    int i;                           /* Loop counter */
123434    int iDbSrc;                      /* The database of pSrc */
123435    int iSrc, iDest;                 /* Cursors from source and destination */
123436    int addr1, addr2;                /* Loop addresses */
123437    int emptyDestTest = 0;           /* Address of test for empty pDest */
123438    int emptySrcTest = 0;            /* Address of test for empty pSrc */
123439    Vdbe *v;                         /* The VDBE we are building */
123440    int regAutoinc;                  /* Memory register used by AUTOINC */
123441    int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
123442    int regData, regRowid;           /* Registers holding data and rowid */
123443  
123444    if( pSelect==0 ){
123445      return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
123446    }
123447    if( pParse->pWith || pSelect->pWith ){
123448      /* Do not attempt to process this query if there are an WITH clauses
123449      ** attached to it. Proceeding may generate a false "no such table: xxx"
123450      ** error if pSelect reads from a CTE named "xxx".  */
123451      return 0;
123452    }
123453    if( sqlite3TriggerList(pParse, pDest) ){
123454      return 0;   /* tab1 must not have triggers */
123455    }
123456  #ifndef SQLITE_OMIT_VIRTUALTABLE
123457    if( IsVirtual(pDest) ){
123458      return 0;   /* tab1 must not be a virtual table */
123459    }
123460  #endif
123461    if( onError==OE_Default ){
123462      if( pDest->iPKey>=0 ) onError = pDest->keyConf;
123463      if( onError==OE_Default ) onError = OE_Abort;
123464    }
123465    assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
123466    if( pSelect->pSrc->nSrc!=1 ){
123467      return 0;   /* FROM clause must have exactly one term */
123468    }
123469    if( pSelect->pSrc->a[0].pSelect ){
123470      return 0;   /* FROM clause cannot contain a subquery */
123471    }
123472    if( pSelect->pWhere ){
123473      return 0;   /* SELECT may not have a WHERE clause */
123474    }
123475    if( pSelect->pOrderBy ){
123476      return 0;   /* SELECT may not have an ORDER BY clause */
123477    }
123478    /* Do not need to test for a HAVING clause.  If HAVING is present but
123479    ** there is no ORDER BY, we will get an error. */
123480    if( pSelect->pGroupBy ){
123481      return 0;   /* SELECT may not have a GROUP BY clause */
123482    }
123483    if( pSelect->pLimit ){
123484      return 0;   /* SELECT may not have a LIMIT clause */
123485    }
123486    if( pSelect->pPrior ){
123487      return 0;   /* SELECT may not be a compound query */
123488    }
123489    if( pSelect->selFlags & SF_Distinct ){
123490      return 0;   /* SELECT may not be DISTINCT */
123491    }
123492    pEList = pSelect->pEList;
123493    assert( pEList!=0 );
123494    if( pEList->nExpr!=1 ){
123495      return 0;   /* The result set must have exactly one column */
123496    }
123497    assert( pEList->a[0].pExpr );
123498    if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
123499      return 0;   /* The result set must be the special operator "*" */
123500    }
123501  
123502    /* At this point we have established that the statement is of the
123503    ** correct syntactic form to participate in this optimization.  Now
123504    ** we have to check the semantics.
123505    */
123506    pItem = pSelect->pSrc->a;
123507    pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
123508    if( pSrc==0 ){
123509      return 0;   /* FROM clause does not contain a real table */
123510    }
123511    if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
123512      testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
123513      return 0;   /* tab1 and tab2 may not be the same table */
123514    }
123515    if( HasRowid(pDest)!=HasRowid(pSrc) ){
123516      return 0;   /* source and destination must both be WITHOUT ROWID or not */
123517    }
123518  #ifndef SQLITE_OMIT_VIRTUALTABLE
123519    if( IsVirtual(pSrc) ){
123520      return 0;   /* tab2 must not be a virtual table */
123521    }
123522  #endif
123523    if( pSrc->pSelect ){
123524      return 0;   /* tab2 may not be a view */
123525    }
123526    if( pDest->nCol!=pSrc->nCol ){
123527      return 0;   /* Number of columns must be the same in tab1 and tab2 */
123528    }
123529    if( pDest->iPKey!=pSrc->iPKey ){
123530      return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
123531    }
123532    for(i=0; i<pDest->nCol; i++){
123533      Column *pDestCol = &pDest->aCol[i];
123534      Column *pSrcCol = &pSrc->aCol[i];
123535  #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
123536      if( (db->mDbFlags & DBFLAG_Vacuum)==0 
123537       && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 
123538      ){
123539        return 0;    /* Neither table may have __hidden__ columns */
123540      }
123541  #endif
123542      if( pDestCol->affinity!=pSrcCol->affinity ){
123543        return 0;    /* Affinity must be the same on all columns */
123544      }
123545      if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
123546        return 0;    /* Collating sequence must be the same on all columns */
123547      }
123548      if( pDestCol->notNull && !pSrcCol->notNull ){
123549        return 0;    /* tab2 must be NOT NULL if tab1 is */
123550      }
123551      /* Default values for second and subsequent columns need to match. */
123552      if( i>0 ){
123553        assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
123554        assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
123555        if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
123556         || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
123557                                         pSrcCol->pDflt->u.zToken)!=0)
123558        ){
123559          return 0;    /* Default values must be the same for all columns */
123560        }
123561      }
123562    }
123563    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
123564      if( IsUniqueIndex(pDestIdx) ){
123565        destHasUniqueIdx = 1;
123566      }
123567      for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
123568        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
123569      }
123570      if( pSrcIdx==0 ){
123571        return 0;    /* pDestIdx has no corresponding index in pSrc */
123572      }
123573    }
123574  #ifndef SQLITE_OMIT_CHECK
123575    if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
123576      return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
123577    }
123578  #endif
123579  #ifndef SQLITE_OMIT_FOREIGN_KEY
123580    /* Disallow the transfer optimization if the destination table constains
123581    ** any foreign key constraints.  This is more restrictive than necessary.
123582    ** But the main beneficiary of the transfer optimization is the VACUUM 
123583    ** command, and the VACUUM command disables foreign key constraints.  So
123584    ** the extra complication to make this rule less restrictive is probably
123585    ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
123586    */
123587    if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
123588      return 0;
123589    }
123590  #endif
123591    if( (db->flags & SQLITE_CountRows)!=0 ){
123592      return 0;  /* xfer opt does not play well with PRAGMA count_changes */
123593    }
123594  
123595    /* If we get this far, it means that the xfer optimization is at
123596    ** least a possibility, though it might only work if the destination
123597    ** table (tab1) is initially empty.
123598    */
123599  #ifdef SQLITE_TEST
123600    sqlite3_xferopt_count++;
123601  #endif
123602    iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
123603    v = sqlite3GetVdbe(pParse);
123604    sqlite3CodeVerifySchema(pParse, iDbSrc);
123605    iSrc = pParse->nTab++;
123606    iDest = pParse->nTab++;
123607    regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
123608    regData = sqlite3GetTempReg(pParse);
123609    regRowid = sqlite3GetTempReg(pParse);
123610    sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
123611    assert( HasRowid(pDest) || destHasUniqueIdx );
123612    if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
123613        (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
123614     || destHasUniqueIdx                              /* (2) */
123615     || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
123616    )){
123617      /* In some circumstances, we are able to run the xfer optimization
123618      ** only if the destination table is initially empty. Unless the
123619      ** DBFLAG_Vacuum flag is set, this block generates code to make
123620      ** that determination. If DBFLAG_Vacuum is set, then the destination
123621      ** table is always empty.
123622      **
123623      ** Conditions under which the destination must be empty:
123624      **
123625      ** (1) There is no INTEGER PRIMARY KEY but there are indices.
123626      **     (If the destination is not initially empty, the rowid fields
123627      **     of index entries might need to change.)
123628      **
123629      ** (2) The destination has a unique index.  (The xfer optimization 
123630      **     is unable to test uniqueness.)
123631      **
123632      ** (3) onError is something other than OE_Abort and OE_Rollback.
123633      */
123634      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
123635      emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
123636      sqlite3VdbeJumpHere(v, addr1);
123637    }
123638    if( HasRowid(pSrc) ){
123639      u8 insFlags;
123640      sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
123641      emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
123642      if( pDest->iPKey>=0 ){
123643        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
123644        sqlite3VdbeVerifyAbortable(v, onError);
123645        addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
123646        VdbeCoverage(v);
123647        sqlite3RowidConstraint(pParse, onError, pDest);
123648        sqlite3VdbeJumpHere(v, addr2);
123649        autoIncStep(pParse, regAutoinc, regRowid);
123650      }else if( pDest->pIndex==0 ){
123651        addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
123652      }else{
123653        addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
123654        assert( (pDest->tabFlags & TF_Autoincrement)==0 );
123655      }
123656      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
123657      if( db->mDbFlags & DBFLAG_Vacuum ){
123658        sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
123659        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
123660                             OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
123661      }else{
123662        insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
123663      }
123664      sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
123665                        (char*)pDest, P4_TABLE);
123666      sqlite3VdbeChangeP5(v, insFlags);
123667      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
123668      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
123669      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
123670    }else{
123671      sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
123672      sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
123673    }
123674    for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
123675      u8 idxInsFlags = 0;
123676      for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
123677        if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
123678      }
123679      assert( pSrcIdx );
123680      sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
123681      sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
123682      VdbeComment((v, "%s", pSrcIdx->zName));
123683      sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
123684      sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
123685      sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
123686      VdbeComment((v, "%s", pDestIdx->zName));
123687      addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
123688      sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
123689      if( db->mDbFlags & DBFLAG_Vacuum ){
123690        /* This INSERT command is part of a VACUUM operation, which guarantees
123691        ** that the destination table is empty. If all indexed columns use
123692        ** collation sequence BINARY, then it can also be assumed that the
123693        ** index will be populated by inserting keys in strictly sorted 
123694        ** order. In this case, instead of seeking within the b-tree as part
123695        ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
123696        ** OP_IdxInsert to seek to the point within the b-tree where each key 
123697        ** should be inserted. This is faster.
123698        **
123699        ** If any of the indexed columns use a collation sequence other than
123700        ** BINARY, this optimization is disabled. This is because the user 
123701        ** might change the definition of a collation sequence and then run
123702        ** a VACUUM command. In that case keys may not be written in strictly
123703        ** sorted order.  */
123704        for(i=0; i<pSrcIdx->nColumn; i++){
123705          const char *zColl = pSrcIdx->azColl[i];
123706          if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
123707        }
123708        if( i==pSrcIdx->nColumn ){
123709          idxInsFlags = OPFLAG_USESEEKRESULT;
123710          sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
123711        }
123712      }
123713      if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
123714        idxInsFlags |= OPFLAG_NCHANGE;
123715      }
123716      sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
123717      sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
123718      sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
123719      sqlite3VdbeJumpHere(v, addr1);
123720      sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
123721      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
123722    }
123723    if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
123724    sqlite3ReleaseTempReg(pParse, regRowid);
123725    sqlite3ReleaseTempReg(pParse, regData);
123726    if( emptyDestTest ){
123727      sqlite3AutoincrementEnd(pParse);
123728      sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
123729      sqlite3VdbeJumpHere(v, emptyDestTest);
123730      sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
123731      return 0;
123732    }else{
123733      return 1;
123734    }
123735  }
123736  #endif /* SQLITE_OMIT_XFER_OPT */
123737  
123738  /************** End of insert.c **********************************************/
123739  /************** Begin file legacy.c ******************************************/
123740  /*
123741  ** 2001 September 15
123742  **
123743  ** The author disclaims copyright to this source code.  In place of
123744  ** a legal notice, here is a blessing:
123745  **
123746  **    May you do good and not evil.
123747  **    May you find forgiveness for yourself and forgive others.
123748  **    May you share freely, never taking more than you give.
123749  **
123750  *************************************************************************
123751  ** Main file for the SQLite library.  The routines in this file
123752  ** implement the programmer interface to the library.  Routines in
123753  ** other files are for internal use by SQLite and should not be
123754  ** accessed by users of the library.
123755  */
123756  
123757  /* #include "sqliteInt.h" */
123758  
123759  /*
123760  ** Execute SQL code.  Return one of the SQLITE_ success/failure
123761  ** codes.  Also write an error message into memory obtained from
123762  ** malloc() and make *pzErrMsg point to that message.
123763  **
123764  ** If the SQL is a query, then for each row in the query result
123765  ** the xCallback() function is called.  pArg becomes the first
123766  ** argument to xCallback().  If xCallback=NULL then no callback
123767  ** is invoked, even for queries.
123768  */
123769  SQLITE_API int sqlite3_exec(
123770    sqlite3 *db,                /* The database on which the SQL executes */
123771    const char *zSql,           /* The SQL to be executed */
123772    sqlite3_callback xCallback, /* Invoke this callback routine */
123773    void *pArg,                 /* First argument to xCallback() */
123774    char **pzErrMsg             /* Write error messages here */
123775  ){
123776    int rc = SQLITE_OK;         /* Return code */
123777    const char *zLeftover;      /* Tail of unprocessed SQL */
123778    sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
123779    char **azCols = 0;          /* Names of result columns */
123780    int callbackIsInit;         /* True if callback data is initialized */
123781  
123782    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
123783    if( zSql==0 ) zSql = "";
123784  
123785    sqlite3_mutex_enter(db->mutex);
123786    sqlite3Error(db, SQLITE_OK);
123787    while( rc==SQLITE_OK && zSql[0] ){
123788      int nCol = 0;
123789      char **azVals = 0;
123790  
123791      pStmt = 0;
123792      rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
123793      assert( rc==SQLITE_OK || pStmt==0 );
123794      if( rc!=SQLITE_OK ){
123795        continue;
123796      }
123797      if( !pStmt ){
123798        /* this happens for a comment or white-space */
123799        zSql = zLeftover;
123800        continue;
123801      }
123802      callbackIsInit = 0;
123803  
123804      while( 1 ){
123805        int i;
123806        rc = sqlite3_step(pStmt);
123807  
123808        /* Invoke the callback function if required */
123809        if( xCallback && (SQLITE_ROW==rc || 
123810            (SQLITE_DONE==rc && !callbackIsInit
123811                             && db->flags&SQLITE_NullCallback)) ){
123812          if( !callbackIsInit ){
123813            nCol = sqlite3_column_count(pStmt);
123814            azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
123815            if( azCols==0 ){
123816              goto exec_out;
123817            }
123818            for(i=0; i<nCol; i++){
123819              azCols[i] = (char *)sqlite3_column_name(pStmt, i);
123820              /* sqlite3VdbeSetColName() installs column names as UTF8
123821              ** strings so there is no way for sqlite3_column_name() to fail. */
123822              assert( azCols[i]!=0 );
123823            }
123824            callbackIsInit = 1;
123825          }
123826          if( rc==SQLITE_ROW ){
123827            azVals = &azCols[nCol];
123828            for(i=0; i<nCol; i++){
123829              azVals[i] = (char *)sqlite3_column_text(pStmt, i);
123830              if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
123831                sqlite3OomFault(db);
123832                goto exec_out;
123833              }
123834            }
123835            azVals[i] = 0;
123836          }
123837          if( xCallback(pArg, nCol, azVals, azCols) ){
123838            /* EVIDENCE-OF: R-38229-40159 If the callback function to
123839            ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
123840            ** return SQLITE_ABORT. */
123841            rc = SQLITE_ABORT;
123842            sqlite3VdbeFinalize((Vdbe *)pStmt);
123843            pStmt = 0;
123844            sqlite3Error(db, SQLITE_ABORT);
123845            goto exec_out;
123846          }
123847        }
123848  
123849        if( rc!=SQLITE_ROW ){
123850          rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
123851          pStmt = 0;
123852          zSql = zLeftover;
123853          while( sqlite3Isspace(zSql[0]) ) zSql++;
123854          break;
123855        }
123856      }
123857  
123858      sqlite3DbFree(db, azCols);
123859      azCols = 0;
123860    }
123861  
123862  exec_out:
123863    if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
123864    sqlite3DbFree(db, azCols);
123865  
123866    rc = sqlite3ApiExit(db, rc);
123867    if( rc!=SQLITE_OK && pzErrMsg ){
123868      *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
123869      if( *pzErrMsg==0 ){
123870        rc = SQLITE_NOMEM_BKPT;
123871        sqlite3Error(db, SQLITE_NOMEM);
123872      }
123873    }else if( pzErrMsg ){
123874      *pzErrMsg = 0;
123875    }
123876  
123877    assert( (rc&db->errMask)==rc );
123878    sqlite3_mutex_leave(db->mutex);
123879    return rc;
123880  }
123881  
123882  /************** End of legacy.c **********************************************/
123883  /************** Begin file loadext.c *****************************************/
123884  /*
123885  ** 2006 June 7
123886  **
123887  ** The author disclaims copyright to this source code.  In place of
123888  ** a legal notice, here is a blessing:
123889  **
123890  **    May you do good and not evil.
123891  **    May you find forgiveness for yourself and forgive others.
123892  **    May you share freely, never taking more than you give.
123893  **
123894  *************************************************************************
123895  ** This file contains code used to dynamically load extensions into
123896  ** the SQLite library.
123897  */
123898  
123899  #ifndef SQLITE_CORE
123900    #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
123901  #endif
123902  /************** Include sqlite3ext.h in the middle of loadext.c **************/
123903  /************** Begin file sqlite3ext.h **************************************/
123904  /*
123905  ** 2006 June 7
123906  **
123907  ** The author disclaims copyright to this source code.  In place of
123908  ** a legal notice, here is a blessing:
123909  **
123910  **    May you do good and not evil.
123911  **    May you find forgiveness for yourself and forgive others.
123912  **    May you share freely, never taking more than you give.
123913  **
123914  *************************************************************************
123915  ** This header file defines the SQLite interface for use by
123916  ** shared libraries that want to be imported as extensions into
123917  ** an SQLite instance.  Shared libraries that intend to be loaded
123918  ** as extensions by SQLite should #include this file instead of 
123919  ** sqlite3.h.
123920  */
123921  #ifndef SQLITE3EXT_H
123922  #define SQLITE3EXT_H
123923  /* #include "sqlite3.h" */
123924  
123925  /*
123926  ** The following structure holds pointers to all of the SQLite API
123927  ** routines.
123928  **
123929  ** WARNING:  In order to maintain backwards compatibility, add new
123930  ** interfaces to the end of this structure only.  If you insert new
123931  ** interfaces in the middle of this structure, then older different
123932  ** versions of SQLite will not be able to load each other's shared
123933  ** libraries!
123934  */
123935  struct sqlite3_api_routines {
123936    void * (*aggregate_context)(sqlite3_context*,int nBytes);
123937    int  (*aggregate_count)(sqlite3_context*);
123938    int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
123939    int  (*bind_double)(sqlite3_stmt*,int,double);
123940    int  (*bind_int)(sqlite3_stmt*,int,int);
123941    int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
123942    int  (*bind_null)(sqlite3_stmt*,int);
123943    int  (*bind_parameter_count)(sqlite3_stmt*);
123944    int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
123945    const char * (*bind_parameter_name)(sqlite3_stmt*,int);
123946    int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
123947    int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
123948    int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
123949    int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
123950    int  (*busy_timeout)(sqlite3*,int ms);
123951    int  (*changes)(sqlite3*);
123952    int  (*close)(sqlite3*);
123953    int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
123954                             int eTextRep,const char*));
123955    int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
123956                               int eTextRep,const void*));
123957    const void * (*column_blob)(sqlite3_stmt*,int iCol);
123958    int  (*column_bytes)(sqlite3_stmt*,int iCol);
123959    int  (*column_bytes16)(sqlite3_stmt*,int iCol);
123960    int  (*column_count)(sqlite3_stmt*pStmt);
123961    const char * (*column_database_name)(sqlite3_stmt*,int);
123962    const void * (*column_database_name16)(sqlite3_stmt*,int);
123963    const char * (*column_decltype)(sqlite3_stmt*,int i);
123964    const void * (*column_decltype16)(sqlite3_stmt*,int);
123965    double  (*column_double)(sqlite3_stmt*,int iCol);
123966    int  (*column_int)(sqlite3_stmt*,int iCol);
123967    sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
123968    const char * (*column_name)(sqlite3_stmt*,int);
123969    const void * (*column_name16)(sqlite3_stmt*,int);
123970    const char * (*column_origin_name)(sqlite3_stmt*,int);
123971    const void * (*column_origin_name16)(sqlite3_stmt*,int);
123972    const char * (*column_table_name)(sqlite3_stmt*,int);
123973    const void * (*column_table_name16)(sqlite3_stmt*,int);
123974    const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
123975    const void * (*column_text16)(sqlite3_stmt*,int iCol);
123976    int  (*column_type)(sqlite3_stmt*,int iCol);
123977    sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
123978    void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
123979    int  (*complete)(const char*sql);
123980    int  (*complete16)(const void*sql);
123981    int  (*create_collation)(sqlite3*,const char*,int,void*,
123982                             int(*)(void*,int,const void*,int,const void*));
123983    int  (*create_collation16)(sqlite3*,const void*,int,void*,
123984                               int(*)(void*,int,const void*,int,const void*));
123985    int  (*create_function)(sqlite3*,const char*,int,int,void*,
123986                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
123987                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
123988                            void (*xFinal)(sqlite3_context*));
123989    int  (*create_function16)(sqlite3*,const void*,int,int,void*,
123990                              void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
123991                              void (*xStep)(sqlite3_context*,int,sqlite3_value**),
123992                              void (*xFinal)(sqlite3_context*));
123993    int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
123994    int  (*data_count)(sqlite3_stmt*pStmt);
123995    sqlite3 * (*db_handle)(sqlite3_stmt*);
123996    int (*declare_vtab)(sqlite3*,const char*);
123997    int  (*enable_shared_cache)(int);
123998    int  (*errcode)(sqlite3*db);
123999    const char * (*errmsg)(sqlite3*);
124000    const void * (*errmsg16)(sqlite3*);
124001    int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
124002    int  (*expired)(sqlite3_stmt*);
124003    int  (*finalize)(sqlite3_stmt*pStmt);
124004    void  (*free)(void*);
124005    void  (*free_table)(char**result);
124006    int  (*get_autocommit)(sqlite3*);
124007    void * (*get_auxdata)(sqlite3_context*,int);
124008    int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
124009    int  (*global_recover)(void);
124010    void  (*interruptx)(sqlite3*);
124011    sqlite_int64  (*last_insert_rowid)(sqlite3*);
124012    const char * (*libversion)(void);
124013    int  (*libversion_number)(void);
124014    void *(*malloc)(int);
124015    char * (*mprintf)(const char*,...);
124016    int  (*open)(const char*,sqlite3**);
124017    int  (*open16)(const void*,sqlite3**);
124018    int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
124019    int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
124020    void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
124021    void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
124022    void *(*realloc)(void*,int);
124023    int  (*reset)(sqlite3_stmt*pStmt);
124024    void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
124025    void  (*result_double)(sqlite3_context*,double);
124026    void  (*result_error)(sqlite3_context*,const char*,int);
124027    void  (*result_error16)(sqlite3_context*,const void*,int);
124028    void  (*result_int)(sqlite3_context*,int);
124029    void  (*result_int64)(sqlite3_context*,sqlite_int64);
124030    void  (*result_null)(sqlite3_context*);
124031    void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
124032    void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
124033    void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
124034    void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
124035    void  (*result_value)(sqlite3_context*,sqlite3_value*);
124036    void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
124037    int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
124038                           const char*,const char*),void*);
124039    void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
124040    char * (*xsnprintf)(int,char*,const char*,...);
124041    int  (*step)(sqlite3_stmt*);
124042    int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
124043                                  char const**,char const**,int*,int*,int*);
124044    void  (*thread_cleanup)(void);
124045    int  (*total_changes)(sqlite3*);
124046    void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
124047    int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
124048    void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
124049                                           sqlite_int64),void*);
124050    void * (*user_data)(sqlite3_context*);
124051    const void * (*value_blob)(sqlite3_value*);
124052    int  (*value_bytes)(sqlite3_value*);
124053    int  (*value_bytes16)(sqlite3_value*);
124054    double  (*value_double)(sqlite3_value*);
124055    int  (*value_int)(sqlite3_value*);
124056    sqlite_int64  (*value_int64)(sqlite3_value*);
124057    int  (*value_numeric_type)(sqlite3_value*);
124058    const unsigned char * (*value_text)(sqlite3_value*);
124059    const void * (*value_text16)(sqlite3_value*);
124060    const void * (*value_text16be)(sqlite3_value*);
124061    const void * (*value_text16le)(sqlite3_value*);
124062    int  (*value_type)(sqlite3_value*);
124063    char *(*vmprintf)(const char*,va_list);
124064    /* Added ??? */
124065    int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
124066    /* Added by 3.3.13 */
124067    int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
124068    int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
124069    int (*clear_bindings)(sqlite3_stmt*);
124070    /* Added by 3.4.1 */
124071    int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
124072                            void (*xDestroy)(void *));
124073    /* Added by 3.5.0 */
124074    int (*bind_zeroblob)(sqlite3_stmt*,int,int);
124075    int (*blob_bytes)(sqlite3_blob*);
124076    int (*blob_close)(sqlite3_blob*);
124077    int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
124078                     int,sqlite3_blob**);
124079    int (*blob_read)(sqlite3_blob*,void*,int,int);
124080    int (*blob_write)(sqlite3_blob*,const void*,int,int);
124081    int (*create_collation_v2)(sqlite3*,const char*,int,void*,
124082                               int(*)(void*,int,const void*,int,const void*),
124083                               void(*)(void*));
124084    int (*file_control)(sqlite3*,const char*,int,void*);
124085    sqlite3_int64 (*memory_highwater)(int);
124086    sqlite3_int64 (*memory_used)(void);
124087    sqlite3_mutex *(*mutex_alloc)(int);
124088    void (*mutex_enter)(sqlite3_mutex*);
124089    void (*mutex_free)(sqlite3_mutex*);
124090    void (*mutex_leave)(sqlite3_mutex*);
124091    int (*mutex_try)(sqlite3_mutex*);
124092    int (*open_v2)(const char*,sqlite3**,int,const char*);
124093    int (*release_memory)(int);
124094    void (*result_error_nomem)(sqlite3_context*);
124095    void (*result_error_toobig)(sqlite3_context*);
124096    int (*sleep)(int);
124097    void (*soft_heap_limit)(int);
124098    sqlite3_vfs *(*vfs_find)(const char*);
124099    int (*vfs_register)(sqlite3_vfs*,int);
124100    int (*vfs_unregister)(sqlite3_vfs*);
124101    int (*xthreadsafe)(void);
124102    void (*result_zeroblob)(sqlite3_context*,int);
124103    void (*result_error_code)(sqlite3_context*,int);
124104    int (*test_control)(int, ...);
124105    void (*randomness)(int,void*);
124106    sqlite3 *(*context_db_handle)(sqlite3_context*);
124107    int (*extended_result_codes)(sqlite3*,int);
124108    int (*limit)(sqlite3*,int,int);
124109    sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
124110    const char *(*sql)(sqlite3_stmt*);
124111    int (*status)(int,int*,int*,int);
124112    int (*backup_finish)(sqlite3_backup*);
124113    sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
124114    int (*backup_pagecount)(sqlite3_backup*);
124115    int (*backup_remaining)(sqlite3_backup*);
124116    int (*backup_step)(sqlite3_backup*,int);
124117    const char *(*compileoption_get)(int);
124118    int (*compileoption_used)(const char*);
124119    int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
124120                              void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
124121                              void (*xStep)(sqlite3_context*,int,sqlite3_value**),
124122                              void (*xFinal)(sqlite3_context*),
124123                              void(*xDestroy)(void*));
124124    int (*db_config)(sqlite3*,int,...);
124125    sqlite3_mutex *(*db_mutex)(sqlite3*);
124126    int (*db_status)(sqlite3*,int,int*,int*,int);
124127    int (*extended_errcode)(sqlite3*);
124128    void (*log)(int,const char*,...);
124129    sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
124130    const char *(*sourceid)(void);
124131    int (*stmt_status)(sqlite3_stmt*,int,int);
124132    int (*strnicmp)(const char*,const char*,int);
124133    int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
124134    int (*wal_autocheckpoint)(sqlite3*,int);
124135    int (*wal_checkpoint)(sqlite3*,const char*);
124136    void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
124137    int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
124138    int (*vtab_config)(sqlite3*,int op,...);
124139    int (*vtab_on_conflict)(sqlite3*);
124140    /* Version 3.7.16 and later */
124141    int (*close_v2)(sqlite3*);
124142    const char *(*db_filename)(sqlite3*,const char*);
124143    int (*db_readonly)(sqlite3*,const char*);
124144    int (*db_release_memory)(sqlite3*);
124145    const char *(*errstr)(int);
124146    int (*stmt_busy)(sqlite3_stmt*);
124147    int (*stmt_readonly)(sqlite3_stmt*);
124148    int (*stricmp)(const char*,const char*);
124149    int (*uri_boolean)(const char*,const char*,int);
124150    sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
124151    const char *(*uri_parameter)(const char*,const char*);
124152    char *(*xvsnprintf)(int,char*,const char*,va_list);
124153    int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
124154    /* Version 3.8.7 and later */
124155    int (*auto_extension)(void(*)(void));
124156    int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
124157                       void(*)(void*));
124158    int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
124159                        void(*)(void*),unsigned char);
124160    int (*cancel_auto_extension)(void(*)(void));
124161    int (*load_extension)(sqlite3*,const char*,const char*,char**);
124162    void *(*malloc64)(sqlite3_uint64);
124163    sqlite3_uint64 (*msize)(void*);
124164    void *(*realloc64)(void*,sqlite3_uint64);
124165    void (*reset_auto_extension)(void);
124166    void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
124167                          void(*)(void*));
124168    void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
124169                           void(*)(void*), unsigned char);
124170    int (*strglob)(const char*,const char*);
124171    /* Version 3.8.11 and later */
124172    sqlite3_value *(*value_dup)(const sqlite3_value*);
124173    void (*value_free)(sqlite3_value*);
124174    int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
124175    int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
124176    /* Version 3.9.0 and later */
124177    unsigned int (*value_subtype)(sqlite3_value*);
124178    void (*result_subtype)(sqlite3_context*,unsigned int);
124179    /* Version 3.10.0 and later */
124180    int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
124181    int (*strlike)(const char*,const char*,unsigned int);
124182    int (*db_cacheflush)(sqlite3*);
124183    /* Version 3.12.0 and later */
124184    int (*system_errno)(sqlite3*);
124185    /* Version 3.14.0 and later */
124186    int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
124187    char *(*expanded_sql)(sqlite3_stmt*);
124188    /* Version 3.18.0 and later */
124189    void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
124190    /* Version 3.20.0 and later */
124191    int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
124192                      sqlite3_stmt**,const char**);
124193    int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
124194                        sqlite3_stmt**,const void**);
124195    int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
124196    void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
124197    void *(*value_pointer)(sqlite3_value*,const char*);
124198    int (*vtab_nochange)(sqlite3_context*);
124199    int (*value_nochange)(sqlite3_value*);
124200    const char *(*vtab_collation)(sqlite3_index_info*,int);
124201    /* Version 3.24.0 and later */
124202    int (*keyword_count)(void);
124203    int (*keyword_name)(int,const char**,int*);
124204    int (*keyword_check)(const char*,int);
124205    sqlite3_str *(*str_new)(sqlite3*);
124206    char *(*str_finish)(sqlite3_str*);
124207    void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
124208    void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
124209    void (*str_append)(sqlite3_str*, const char *zIn, int N);
124210    void (*str_appendall)(sqlite3_str*, const char *zIn);
124211    void (*str_appendchar)(sqlite3_str*, int N, char C);
124212    void (*str_reset)(sqlite3_str*);
124213    int (*str_errcode)(sqlite3_str*);
124214    int (*str_length)(sqlite3_str*);
124215    char *(*str_value)(sqlite3_str*);
124216    /* Version 3.25.0 and later */
124217    int (*create_window_function)(sqlite3*,const char*,int,int,void*,
124218                              void (*xStep)(sqlite3_context*,int,sqlite3_value**),
124219                              void (*xFinal)(sqlite3_context*),
124220                              void (*xValue)(sqlite3_context*),
124221                              void (*xInv)(sqlite3_context*,int,sqlite3_value**),
124222                              void(*xDestroy)(void*));
124223    /* Version 3.26.0 and later */
124224    const char *(*normalized_sql)(sqlite3_stmt*);
124225  };
124226  
124227  /*
124228  ** This is the function signature used for all extension entry points.  It
124229  ** is also defined in the file "loadext.c".
124230  */
124231  typedef int (*sqlite3_loadext_entry)(
124232    sqlite3 *db,                       /* Handle to the database. */
124233    char **pzErrMsg,                   /* Used to set error string on failure. */
124234    const sqlite3_api_routines *pThunk /* Extension API function pointers. */
124235  );
124236  
124237  /*
124238  ** The following macros redefine the API routines so that they are
124239  ** redirected through the global sqlite3_api structure.
124240  **
124241  ** This header file is also used by the loadext.c source file
124242  ** (part of the main SQLite library - not an extension) so that
124243  ** it can get access to the sqlite3_api_routines structure
124244  ** definition.  But the main library does not want to redefine
124245  ** the API.  So the redefinition macros are only valid if the
124246  ** SQLITE_CORE macros is undefined.
124247  */
124248  #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
124249  #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
124250  #ifndef SQLITE_OMIT_DEPRECATED
124251  #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
124252  #endif
124253  #define sqlite3_bind_blob              sqlite3_api->bind_blob
124254  #define sqlite3_bind_double            sqlite3_api->bind_double
124255  #define sqlite3_bind_int               sqlite3_api->bind_int
124256  #define sqlite3_bind_int64             sqlite3_api->bind_int64
124257  #define sqlite3_bind_null              sqlite3_api->bind_null
124258  #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
124259  #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
124260  #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
124261  #define sqlite3_bind_text              sqlite3_api->bind_text
124262  #define sqlite3_bind_text16            sqlite3_api->bind_text16
124263  #define sqlite3_bind_value             sqlite3_api->bind_value
124264  #define sqlite3_busy_handler           sqlite3_api->busy_handler
124265  #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
124266  #define sqlite3_changes                sqlite3_api->changes
124267  #define sqlite3_close                  sqlite3_api->close
124268  #define sqlite3_collation_needed       sqlite3_api->collation_needed
124269  #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
124270  #define sqlite3_column_blob            sqlite3_api->column_blob
124271  #define sqlite3_column_bytes           sqlite3_api->column_bytes
124272  #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
124273  #define sqlite3_column_count           sqlite3_api->column_count
124274  #define sqlite3_column_database_name   sqlite3_api->column_database_name
124275  #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
124276  #define sqlite3_column_decltype        sqlite3_api->column_decltype
124277  #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
124278  #define sqlite3_column_double          sqlite3_api->column_double
124279  #define sqlite3_column_int             sqlite3_api->column_int
124280  #define sqlite3_column_int64           sqlite3_api->column_int64
124281  #define sqlite3_column_name            sqlite3_api->column_name
124282  #define sqlite3_column_name16          sqlite3_api->column_name16
124283  #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
124284  #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
124285  #define sqlite3_column_table_name      sqlite3_api->column_table_name
124286  #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
124287  #define sqlite3_column_text            sqlite3_api->column_text
124288  #define sqlite3_column_text16          sqlite3_api->column_text16
124289  #define sqlite3_column_type            sqlite3_api->column_type
124290  #define sqlite3_column_value           sqlite3_api->column_value
124291  #define sqlite3_commit_hook            sqlite3_api->commit_hook
124292  #define sqlite3_complete               sqlite3_api->complete
124293  #define sqlite3_complete16             sqlite3_api->complete16
124294  #define sqlite3_create_collation       sqlite3_api->create_collation
124295  #define sqlite3_create_collation16     sqlite3_api->create_collation16
124296  #define sqlite3_create_function        sqlite3_api->create_function
124297  #define sqlite3_create_function16      sqlite3_api->create_function16
124298  #define sqlite3_create_module          sqlite3_api->create_module
124299  #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
124300  #define sqlite3_data_count             sqlite3_api->data_count
124301  #define sqlite3_db_handle              sqlite3_api->db_handle
124302  #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
124303  #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
124304  #define sqlite3_errcode                sqlite3_api->errcode
124305  #define sqlite3_errmsg                 sqlite3_api->errmsg
124306  #define sqlite3_errmsg16               sqlite3_api->errmsg16
124307  #define sqlite3_exec                   sqlite3_api->exec
124308  #ifndef SQLITE_OMIT_DEPRECATED
124309  #define sqlite3_expired                sqlite3_api->expired
124310  #endif
124311  #define sqlite3_finalize               sqlite3_api->finalize
124312  #define sqlite3_free                   sqlite3_api->free
124313  #define sqlite3_free_table             sqlite3_api->free_table
124314  #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
124315  #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
124316  #define sqlite3_get_table              sqlite3_api->get_table
124317  #ifndef SQLITE_OMIT_DEPRECATED
124318  #define sqlite3_global_recover         sqlite3_api->global_recover
124319  #endif
124320  #define sqlite3_interrupt              sqlite3_api->interruptx
124321  #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
124322  #define sqlite3_libversion             sqlite3_api->libversion
124323  #define sqlite3_libversion_number      sqlite3_api->libversion_number
124324  #define sqlite3_malloc                 sqlite3_api->malloc
124325  #define sqlite3_mprintf                sqlite3_api->mprintf
124326  #define sqlite3_open                   sqlite3_api->open
124327  #define sqlite3_open16                 sqlite3_api->open16
124328  #define sqlite3_prepare                sqlite3_api->prepare
124329  #define sqlite3_prepare16              sqlite3_api->prepare16
124330  #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
124331  #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
124332  #define sqlite3_profile                sqlite3_api->profile
124333  #define sqlite3_progress_handler       sqlite3_api->progress_handler
124334  #define sqlite3_realloc                sqlite3_api->realloc
124335  #define sqlite3_reset                  sqlite3_api->reset
124336  #define sqlite3_result_blob            sqlite3_api->result_blob
124337  #define sqlite3_result_double          sqlite3_api->result_double
124338  #define sqlite3_result_error           sqlite3_api->result_error
124339  #define sqlite3_result_error16         sqlite3_api->result_error16
124340  #define sqlite3_result_int             sqlite3_api->result_int
124341  #define sqlite3_result_int64           sqlite3_api->result_int64
124342  #define sqlite3_result_null            sqlite3_api->result_null
124343  #define sqlite3_result_text            sqlite3_api->result_text
124344  #define sqlite3_result_text16          sqlite3_api->result_text16
124345  #define sqlite3_result_text16be        sqlite3_api->result_text16be
124346  #define sqlite3_result_text16le        sqlite3_api->result_text16le
124347  #define sqlite3_result_value           sqlite3_api->result_value
124348  #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
124349  #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
124350  #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
124351  #define sqlite3_snprintf               sqlite3_api->xsnprintf
124352  #define sqlite3_step                   sqlite3_api->step
124353  #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
124354  #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
124355  #define sqlite3_total_changes          sqlite3_api->total_changes
124356  #define sqlite3_trace                  sqlite3_api->trace
124357  #ifndef SQLITE_OMIT_DEPRECATED
124358  #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
124359  #endif
124360  #define sqlite3_update_hook            sqlite3_api->update_hook
124361  #define sqlite3_user_data              sqlite3_api->user_data
124362  #define sqlite3_value_blob             sqlite3_api->value_blob
124363  #define sqlite3_value_bytes            sqlite3_api->value_bytes
124364  #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
124365  #define sqlite3_value_double           sqlite3_api->value_double
124366  #define sqlite3_value_int              sqlite3_api->value_int
124367  #define sqlite3_value_int64            sqlite3_api->value_int64
124368  #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
124369  #define sqlite3_value_text             sqlite3_api->value_text
124370  #define sqlite3_value_text16           sqlite3_api->value_text16
124371  #define sqlite3_value_text16be         sqlite3_api->value_text16be
124372  #define sqlite3_value_text16le         sqlite3_api->value_text16le
124373  #define sqlite3_value_type             sqlite3_api->value_type
124374  #define sqlite3_vmprintf               sqlite3_api->vmprintf
124375  #define sqlite3_vsnprintf              sqlite3_api->xvsnprintf
124376  #define sqlite3_overload_function      sqlite3_api->overload_function
124377  #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
124378  #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
124379  #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
124380  #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
124381  #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
124382  #define sqlite3_blob_close             sqlite3_api->blob_close
124383  #define sqlite3_blob_open              sqlite3_api->blob_open
124384  #define sqlite3_blob_read              sqlite3_api->blob_read
124385  #define sqlite3_blob_write             sqlite3_api->blob_write
124386  #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
124387  #define sqlite3_file_control           sqlite3_api->file_control
124388  #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
124389  #define sqlite3_memory_used            sqlite3_api->memory_used
124390  #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
124391  #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
124392  #define sqlite3_mutex_free             sqlite3_api->mutex_free
124393  #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
124394  #define sqlite3_mutex_try              sqlite3_api->mutex_try
124395  #define sqlite3_open_v2                sqlite3_api->open_v2
124396  #define sqlite3_release_memory         sqlite3_api->release_memory
124397  #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
124398  #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
124399  #define sqlite3_sleep                  sqlite3_api->sleep
124400  #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
124401  #define sqlite3_vfs_find               sqlite3_api->vfs_find
124402  #define sqlite3_vfs_register           sqlite3_api->vfs_register
124403  #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
124404  #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
124405  #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
124406  #define sqlite3_result_error_code      sqlite3_api->result_error_code
124407  #define sqlite3_test_control           sqlite3_api->test_control
124408  #define sqlite3_randomness             sqlite3_api->randomness
124409  #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
124410  #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
124411  #define sqlite3_limit                  sqlite3_api->limit
124412  #define sqlite3_next_stmt              sqlite3_api->next_stmt
124413  #define sqlite3_sql                    sqlite3_api->sql
124414  #define sqlite3_status                 sqlite3_api->status
124415  #define sqlite3_backup_finish          sqlite3_api->backup_finish
124416  #define sqlite3_backup_init            sqlite3_api->backup_init
124417  #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
124418  #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
124419  #define sqlite3_backup_step            sqlite3_api->backup_step
124420  #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
124421  #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
124422  #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
124423  #define sqlite3_db_config              sqlite3_api->db_config
124424  #define sqlite3_db_mutex               sqlite3_api->db_mutex
124425  #define sqlite3_db_status              sqlite3_api->db_status
124426  #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
124427  #define sqlite3_log                    sqlite3_api->log
124428  #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
124429  #define sqlite3_sourceid               sqlite3_api->sourceid
124430  #define sqlite3_stmt_status            sqlite3_api->stmt_status
124431  #define sqlite3_strnicmp               sqlite3_api->strnicmp
124432  #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
124433  #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
124434  #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
124435  #define sqlite3_wal_hook               sqlite3_api->wal_hook
124436  #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
124437  #define sqlite3_vtab_config            sqlite3_api->vtab_config
124438  #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
124439  /* Version 3.7.16 and later */
124440  #define sqlite3_close_v2               sqlite3_api->close_v2
124441  #define sqlite3_db_filename            sqlite3_api->db_filename
124442  #define sqlite3_db_readonly            sqlite3_api->db_readonly
124443  #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
124444  #define sqlite3_errstr                 sqlite3_api->errstr
124445  #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
124446  #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
124447  #define sqlite3_stricmp                sqlite3_api->stricmp
124448  #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
124449  #define sqlite3_uri_int64              sqlite3_api->uri_int64
124450  #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
124451  #define sqlite3_uri_vsnprintf          sqlite3_api->xvsnprintf
124452  #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
124453  /* Version 3.8.7 and later */
124454  #define sqlite3_auto_extension         sqlite3_api->auto_extension
124455  #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
124456  #define sqlite3_bind_text64            sqlite3_api->bind_text64
124457  #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
124458  #define sqlite3_load_extension         sqlite3_api->load_extension
124459  #define sqlite3_malloc64               sqlite3_api->malloc64
124460  #define sqlite3_msize                  sqlite3_api->msize
124461  #define sqlite3_realloc64              sqlite3_api->realloc64
124462  #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
124463  #define sqlite3_result_blob64          sqlite3_api->result_blob64
124464  #define sqlite3_result_text64          sqlite3_api->result_text64
124465  #define sqlite3_strglob                sqlite3_api->strglob
124466  /* Version 3.8.11 and later */
124467  #define sqlite3_value_dup              sqlite3_api->value_dup
124468  #define sqlite3_value_free             sqlite3_api->value_free
124469  #define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
124470  #define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
124471  /* Version 3.9.0 and later */
124472  #define sqlite3_value_subtype          sqlite3_api->value_subtype
124473  #define sqlite3_result_subtype         sqlite3_api->result_subtype
124474  /* Version 3.10.0 and later */
124475  #define sqlite3_status64               sqlite3_api->status64
124476  #define sqlite3_strlike                sqlite3_api->strlike
124477  #define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
124478  /* Version 3.12.0 and later */
124479  #define sqlite3_system_errno           sqlite3_api->system_errno
124480  /* Version 3.14.0 and later */
124481  #define sqlite3_trace_v2               sqlite3_api->trace_v2
124482  #define sqlite3_expanded_sql           sqlite3_api->expanded_sql
124483  /* Version 3.18.0 and later */
124484  #define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
124485  /* Version 3.20.0 and later */
124486  #define sqlite3_prepare_v3             sqlite3_api->prepare_v3
124487  #define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
124488  #define sqlite3_bind_pointer           sqlite3_api->bind_pointer
124489  #define sqlite3_result_pointer         sqlite3_api->result_pointer
124490  #define sqlite3_value_pointer          sqlite3_api->value_pointer
124491  /* Version 3.22.0 and later */
124492  #define sqlite3_vtab_nochange          sqlite3_api->vtab_nochange
124493  #define sqlite3_value_nochange         sqlite3_api->value_nochange
124494  #define sqlite3_vtab_collation         sqlite3_api->vtab_collation
124495  /* Version 3.24.0 and later */
124496  #define sqlite3_keyword_count          sqlite3_api->keyword_count
124497  #define sqlite3_keyword_name           sqlite3_api->keyword_name
124498  #define sqlite3_keyword_check          sqlite3_api->keyword_check
124499  #define sqlite3_str_new                sqlite3_api->str_new
124500  #define sqlite3_str_finish             sqlite3_api->str_finish
124501  #define sqlite3_str_appendf            sqlite3_api->str_appendf
124502  #define sqlite3_str_vappendf           sqlite3_api->str_vappendf
124503  #define sqlite3_str_append             sqlite3_api->str_append
124504  #define sqlite3_str_appendall          sqlite3_api->str_appendall
124505  #define sqlite3_str_appendchar         sqlite3_api->str_appendchar
124506  #define sqlite3_str_reset              sqlite3_api->str_reset
124507  #define sqlite3_str_errcode            sqlite3_api->str_errcode
124508  #define sqlite3_str_length             sqlite3_api->str_length
124509  #define sqlite3_str_value              sqlite3_api->str_value
124510  /* Version 3.25.0 and later */
124511  #define sqlite3_create_window_function sqlite3_api->create_window_function
124512  /* Version 3.26.0 and later */
124513  #define sqlite3_normalized_sql         sqlite3_api->normalized_sql
124514  #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
124515  
124516  #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
124517    /* This case when the file really is being compiled as a loadable 
124518    ** extension */
124519  # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
124520  # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
124521  # define SQLITE_EXTENSION_INIT3     \
124522      extern const sqlite3_api_routines *sqlite3_api;
124523  #else
124524    /* This case when the file is being statically linked into the 
124525    ** application */
124526  # define SQLITE_EXTENSION_INIT1     /*no-op*/
124527  # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
124528  # define SQLITE_EXTENSION_INIT3     /*no-op*/
124529  #endif
124530  
124531  #endif /* SQLITE3EXT_H */
124532  
124533  /************** End of sqlite3ext.h ******************************************/
124534  /************** Continuing where we left off in loadext.c ********************/
124535  /* #include "sqliteInt.h" */
124536  
124537  #ifndef SQLITE_OMIT_LOAD_EXTENSION
124538  /*
124539  ** Some API routines are omitted when various features are
124540  ** excluded from a build of SQLite.  Substitute a NULL pointer
124541  ** for any missing APIs.
124542  */
124543  #ifndef SQLITE_ENABLE_COLUMN_METADATA
124544  # define sqlite3_column_database_name   0
124545  # define sqlite3_column_database_name16 0
124546  # define sqlite3_column_table_name      0
124547  # define sqlite3_column_table_name16    0
124548  # define sqlite3_column_origin_name     0
124549  # define sqlite3_column_origin_name16   0
124550  #endif
124551  
124552  #ifdef SQLITE_OMIT_AUTHORIZATION
124553  # define sqlite3_set_authorizer         0
124554  #endif
124555  
124556  #ifdef SQLITE_OMIT_UTF16
124557  # define sqlite3_bind_text16            0
124558  # define sqlite3_collation_needed16     0
124559  # define sqlite3_column_decltype16      0
124560  # define sqlite3_column_name16          0
124561  # define sqlite3_column_text16          0
124562  # define sqlite3_complete16             0
124563  # define sqlite3_create_collation16     0
124564  # define sqlite3_create_function16      0
124565  # define sqlite3_errmsg16               0
124566  # define sqlite3_open16                 0
124567  # define sqlite3_prepare16              0
124568  # define sqlite3_prepare16_v2           0
124569  # define sqlite3_prepare16_v3           0
124570  # define sqlite3_result_error16         0
124571  # define sqlite3_result_text16          0
124572  # define sqlite3_result_text16be        0
124573  # define sqlite3_result_text16le        0
124574  # define sqlite3_value_text16           0
124575  # define sqlite3_value_text16be         0
124576  # define sqlite3_value_text16le         0
124577  # define sqlite3_column_database_name16 0
124578  # define sqlite3_column_table_name16    0
124579  # define sqlite3_column_origin_name16   0
124580  #endif
124581  
124582  #ifdef SQLITE_OMIT_COMPLETE
124583  # define sqlite3_complete 0
124584  # define sqlite3_complete16 0
124585  #endif
124586  
124587  #ifdef SQLITE_OMIT_DECLTYPE
124588  # define sqlite3_column_decltype16      0
124589  # define sqlite3_column_decltype        0
124590  #endif
124591  
124592  #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
124593  # define sqlite3_progress_handler 0
124594  #endif
124595  
124596  #ifdef SQLITE_OMIT_VIRTUALTABLE
124597  # define sqlite3_create_module 0
124598  # define sqlite3_create_module_v2 0
124599  # define sqlite3_declare_vtab 0
124600  # define sqlite3_vtab_config 0
124601  # define sqlite3_vtab_on_conflict 0
124602  # define sqlite3_vtab_collation 0
124603  #endif
124604  
124605  #ifdef SQLITE_OMIT_SHARED_CACHE
124606  # define sqlite3_enable_shared_cache 0
124607  #endif
124608  
124609  #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
124610  # define sqlite3_profile       0
124611  # define sqlite3_trace         0
124612  #endif
124613  
124614  #ifdef SQLITE_OMIT_GET_TABLE
124615  # define sqlite3_free_table    0
124616  # define sqlite3_get_table     0
124617  #endif
124618  
124619  #ifdef SQLITE_OMIT_INCRBLOB
124620  #define sqlite3_bind_zeroblob  0
124621  #define sqlite3_blob_bytes     0
124622  #define sqlite3_blob_close     0
124623  #define sqlite3_blob_open      0
124624  #define sqlite3_blob_read      0
124625  #define sqlite3_blob_write     0
124626  #define sqlite3_blob_reopen    0
124627  #endif
124628  
124629  #if defined(SQLITE_OMIT_TRACE)
124630  # define sqlite3_trace_v2      0
124631  #endif
124632  
124633  /*
124634  ** The following structure contains pointers to all SQLite API routines.
124635  ** A pointer to this structure is passed into extensions when they are
124636  ** loaded so that the extension can make calls back into the SQLite
124637  ** library.
124638  **
124639  ** When adding new APIs, add them to the bottom of this structure
124640  ** in order to preserve backwards compatibility.
124641  **
124642  ** Extensions that use newer APIs should first call the
124643  ** sqlite3_libversion_number() to make sure that the API they
124644  ** intend to use is supported by the library.  Extensions should
124645  ** also check to make sure that the pointer to the function is
124646  ** not NULL before calling it.
124647  */
124648  static const sqlite3_api_routines sqlite3Apis = {
124649    sqlite3_aggregate_context,
124650  #ifndef SQLITE_OMIT_DEPRECATED
124651    sqlite3_aggregate_count,
124652  #else
124653    0,
124654  #endif
124655    sqlite3_bind_blob,
124656    sqlite3_bind_double,
124657    sqlite3_bind_int,
124658    sqlite3_bind_int64,
124659    sqlite3_bind_null,
124660    sqlite3_bind_parameter_count,
124661    sqlite3_bind_parameter_index,
124662    sqlite3_bind_parameter_name,
124663    sqlite3_bind_text,
124664    sqlite3_bind_text16,
124665    sqlite3_bind_value,
124666    sqlite3_busy_handler,
124667    sqlite3_busy_timeout,
124668    sqlite3_changes,
124669    sqlite3_close,
124670    sqlite3_collation_needed,
124671    sqlite3_collation_needed16,
124672    sqlite3_column_blob,
124673    sqlite3_column_bytes,
124674    sqlite3_column_bytes16,
124675    sqlite3_column_count,
124676    sqlite3_column_database_name,
124677    sqlite3_column_database_name16,
124678    sqlite3_column_decltype,
124679    sqlite3_column_decltype16,
124680    sqlite3_column_double,
124681    sqlite3_column_int,
124682    sqlite3_column_int64,
124683    sqlite3_column_name,
124684    sqlite3_column_name16,
124685    sqlite3_column_origin_name,
124686    sqlite3_column_origin_name16,
124687    sqlite3_column_table_name,
124688    sqlite3_column_table_name16,
124689    sqlite3_column_text,
124690    sqlite3_column_text16,
124691    sqlite3_column_type,
124692    sqlite3_column_value,
124693    sqlite3_commit_hook,
124694    sqlite3_complete,
124695    sqlite3_complete16,
124696    sqlite3_create_collation,
124697    sqlite3_create_collation16,
124698    sqlite3_create_function,
124699    sqlite3_create_function16,
124700    sqlite3_create_module,
124701    sqlite3_data_count,
124702    sqlite3_db_handle,
124703    sqlite3_declare_vtab,
124704    sqlite3_enable_shared_cache,
124705    sqlite3_errcode,
124706    sqlite3_errmsg,
124707    sqlite3_errmsg16,
124708    sqlite3_exec,
124709  #ifndef SQLITE_OMIT_DEPRECATED
124710    sqlite3_expired,
124711  #else
124712    0,
124713  #endif
124714    sqlite3_finalize,
124715    sqlite3_free,
124716    sqlite3_free_table,
124717    sqlite3_get_autocommit,
124718    sqlite3_get_auxdata,
124719    sqlite3_get_table,
124720    0,     /* Was sqlite3_global_recover(), but that function is deprecated */
124721    sqlite3_interrupt,
124722    sqlite3_last_insert_rowid,
124723    sqlite3_libversion,
124724    sqlite3_libversion_number,
124725    sqlite3_malloc,
124726    sqlite3_mprintf,
124727    sqlite3_open,
124728    sqlite3_open16,
124729    sqlite3_prepare,
124730    sqlite3_prepare16,
124731    sqlite3_profile,
124732    sqlite3_progress_handler,
124733    sqlite3_realloc,
124734    sqlite3_reset,
124735    sqlite3_result_blob,
124736    sqlite3_result_double,
124737    sqlite3_result_error,
124738    sqlite3_result_error16,
124739    sqlite3_result_int,
124740    sqlite3_result_int64,
124741    sqlite3_result_null,
124742    sqlite3_result_text,
124743    sqlite3_result_text16,
124744    sqlite3_result_text16be,
124745    sqlite3_result_text16le,
124746    sqlite3_result_value,
124747    sqlite3_rollback_hook,
124748    sqlite3_set_authorizer,
124749    sqlite3_set_auxdata,
124750    sqlite3_snprintf,
124751    sqlite3_step,
124752    sqlite3_table_column_metadata,
124753  #ifndef SQLITE_OMIT_DEPRECATED
124754    sqlite3_thread_cleanup,
124755  #else
124756    0,
124757  #endif
124758    sqlite3_total_changes,
124759    sqlite3_trace,
124760  #ifndef SQLITE_OMIT_DEPRECATED
124761    sqlite3_transfer_bindings,
124762  #else
124763    0,
124764  #endif
124765    sqlite3_update_hook,
124766    sqlite3_user_data,
124767    sqlite3_value_blob,
124768    sqlite3_value_bytes,
124769    sqlite3_value_bytes16,
124770    sqlite3_value_double,
124771    sqlite3_value_int,
124772    sqlite3_value_int64,
124773    sqlite3_value_numeric_type,
124774    sqlite3_value_text,
124775    sqlite3_value_text16,
124776    sqlite3_value_text16be,
124777    sqlite3_value_text16le,
124778    sqlite3_value_type,
124779    sqlite3_vmprintf,
124780    /*
124781    ** The original API set ends here.  All extensions can call any
124782    ** of the APIs above provided that the pointer is not NULL.  But
124783    ** before calling APIs that follow, extension should check the
124784    ** sqlite3_libversion_number() to make sure they are dealing with
124785    ** a library that is new enough to support that API.
124786    *************************************************************************
124787    */
124788    sqlite3_overload_function,
124789  
124790    /*
124791    ** Added after 3.3.13
124792    */
124793    sqlite3_prepare_v2,
124794    sqlite3_prepare16_v2,
124795    sqlite3_clear_bindings,
124796  
124797    /*
124798    ** Added for 3.4.1
124799    */
124800    sqlite3_create_module_v2,
124801  
124802    /*
124803    ** Added for 3.5.0
124804    */
124805    sqlite3_bind_zeroblob,
124806    sqlite3_blob_bytes,
124807    sqlite3_blob_close,
124808    sqlite3_blob_open,
124809    sqlite3_blob_read,
124810    sqlite3_blob_write,
124811    sqlite3_create_collation_v2,
124812    sqlite3_file_control,
124813    sqlite3_memory_highwater,
124814    sqlite3_memory_used,
124815  #ifdef SQLITE_MUTEX_OMIT
124816    0, 
124817    0, 
124818    0,
124819    0,
124820    0,
124821  #else
124822    sqlite3_mutex_alloc,
124823    sqlite3_mutex_enter,
124824    sqlite3_mutex_free,
124825    sqlite3_mutex_leave,
124826    sqlite3_mutex_try,
124827  #endif
124828    sqlite3_open_v2,
124829    sqlite3_release_memory,
124830    sqlite3_result_error_nomem,
124831    sqlite3_result_error_toobig,
124832    sqlite3_sleep,
124833    sqlite3_soft_heap_limit,
124834    sqlite3_vfs_find,
124835    sqlite3_vfs_register,
124836    sqlite3_vfs_unregister,
124837  
124838    /*
124839    ** Added for 3.5.8
124840    */
124841    sqlite3_threadsafe,
124842    sqlite3_result_zeroblob,
124843    sqlite3_result_error_code,
124844    sqlite3_test_control,
124845    sqlite3_randomness,
124846    sqlite3_context_db_handle,
124847  
124848    /*
124849    ** Added for 3.6.0
124850    */
124851    sqlite3_extended_result_codes,
124852    sqlite3_limit,
124853    sqlite3_next_stmt,
124854    sqlite3_sql,
124855    sqlite3_status,
124856  
124857    /*
124858    ** Added for 3.7.4
124859    */
124860    sqlite3_backup_finish,
124861    sqlite3_backup_init,
124862    sqlite3_backup_pagecount,
124863    sqlite3_backup_remaining,
124864    sqlite3_backup_step,
124865  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
124866    sqlite3_compileoption_get,
124867    sqlite3_compileoption_used,
124868  #else
124869    0,
124870    0,
124871  #endif
124872    sqlite3_create_function_v2,
124873    sqlite3_db_config,
124874    sqlite3_db_mutex,
124875    sqlite3_db_status,
124876    sqlite3_extended_errcode,
124877    sqlite3_log,
124878    sqlite3_soft_heap_limit64,
124879    sqlite3_sourceid,
124880    sqlite3_stmt_status,
124881    sqlite3_strnicmp,
124882  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
124883    sqlite3_unlock_notify,
124884  #else
124885    0,
124886  #endif
124887  #ifndef SQLITE_OMIT_WAL
124888    sqlite3_wal_autocheckpoint,
124889    sqlite3_wal_checkpoint,
124890    sqlite3_wal_hook,
124891  #else
124892    0,
124893    0,
124894    0,
124895  #endif
124896    sqlite3_blob_reopen,
124897    sqlite3_vtab_config,
124898    sqlite3_vtab_on_conflict,
124899    sqlite3_close_v2,
124900    sqlite3_db_filename,
124901    sqlite3_db_readonly,
124902    sqlite3_db_release_memory,
124903    sqlite3_errstr,
124904    sqlite3_stmt_busy,
124905    sqlite3_stmt_readonly,
124906    sqlite3_stricmp,
124907    sqlite3_uri_boolean,
124908    sqlite3_uri_int64,
124909    sqlite3_uri_parameter,
124910    sqlite3_vsnprintf,
124911    sqlite3_wal_checkpoint_v2,
124912    /* Version 3.8.7 and later */
124913    sqlite3_auto_extension,
124914    sqlite3_bind_blob64,
124915    sqlite3_bind_text64,
124916    sqlite3_cancel_auto_extension,
124917    sqlite3_load_extension,
124918    sqlite3_malloc64,
124919    sqlite3_msize,
124920    sqlite3_realloc64,
124921    sqlite3_reset_auto_extension,
124922    sqlite3_result_blob64,
124923    sqlite3_result_text64,
124924    sqlite3_strglob,
124925    /* Version 3.8.11 and later */
124926    (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
124927    sqlite3_value_free,
124928    sqlite3_result_zeroblob64,
124929    sqlite3_bind_zeroblob64,
124930    /* Version 3.9.0 and later */
124931    sqlite3_value_subtype,
124932    sqlite3_result_subtype,
124933    /* Version 3.10.0 and later */
124934    sqlite3_status64,
124935    sqlite3_strlike,
124936    sqlite3_db_cacheflush,
124937    /* Version 3.12.0 and later */
124938    sqlite3_system_errno,
124939    /* Version 3.14.0 and later */
124940    sqlite3_trace_v2,
124941    sqlite3_expanded_sql,
124942    /* Version 3.18.0 and later */
124943    sqlite3_set_last_insert_rowid,
124944    /* Version 3.20.0 and later */
124945    sqlite3_prepare_v3,
124946    sqlite3_prepare16_v3,
124947    sqlite3_bind_pointer,
124948    sqlite3_result_pointer,
124949    sqlite3_value_pointer,
124950    /* Version 3.22.0 and later */
124951    sqlite3_vtab_nochange,
124952    sqlite3_value_nochange,
124953    sqlite3_vtab_collation,
124954    /* Version 3.24.0 and later */
124955    sqlite3_keyword_count,
124956    sqlite3_keyword_name,
124957    sqlite3_keyword_check,
124958    sqlite3_str_new,
124959    sqlite3_str_finish,
124960    sqlite3_str_appendf,
124961    sqlite3_str_vappendf,
124962    sqlite3_str_append,
124963    sqlite3_str_appendall,
124964    sqlite3_str_appendchar,
124965    sqlite3_str_reset,
124966    sqlite3_str_errcode,
124967    sqlite3_str_length,
124968    sqlite3_str_value,
124969    /* Version 3.25.0 and later */
124970    sqlite3_create_window_function,
124971    /* Version 3.26.0 and later */
124972  #ifdef SQLITE_ENABLE_NORMALIZE
124973    sqlite3_normalized_sql
124974  #else
124975    0
124976  #endif
124977  };
124978  
124979  /*
124980  ** Attempt to load an SQLite extension library contained in the file
124981  ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
124982  ** default entry point name (sqlite3_extension_init) is used.  Use
124983  ** of the default name is recommended.
124984  **
124985  ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
124986  **
124987  ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
124988  ** error message text.  The calling function should free this memory
124989  ** by calling sqlite3DbFree(db, ).
124990  */
124991  static int sqlite3LoadExtension(
124992    sqlite3 *db,          /* Load the extension into this database connection */
124993    const char *zFile,    /* Name of the shared library containing extension */
124994    const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
124995    char **pzErrMsg       /* Put error message here if not 0 */
124996  ){
124997    sqlite3_vfs *pVfs = db->pVfs;
124998    void *handle;
124999    sqlite3_loadext_entry xInit;
125000    char *zErrmsg = 0;
125001    const char *zEntry;
125002    char *zAltEntry = 0;
125003    void **aHandle;
125004    u64 nMsg = 300 + sqlite3Strlen30(zFile);
125005    int ii;
125006    int rc;
125007  
125008    /* Shared library endings to try if zFile cannot be loaded as written */
125009    static const char *azEndings[] = {
125010  #if SQLITE_OS_WIN
125011       "dll"   
125012  #elif defined(__APPLE__)
125013       "dylib"
125014  #else
125015       "so"
125016  #endif
125017    };
125018  
125019  
125020    if( pzErrMsg ) *pzErrMsg = 0;
125021  
125022    /* Ticket #1863.  To avoid a creating security problems for older
125023    ** applications that relink against newer versions of SQLite, the
125024    ** ability to run load_extension is turned off by default.  One
125025    ** must call either sqlite3_enable_load_extension(db) or
125026    ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
125027    ** to turn on extension loading.
125028    */
125029    if( (db->flags & SQLITE_LoadExtension)==0 ){
125030      if( pzErrMsg ){
125031        *pzErrMsg = sqlite3_mprintf("not authorized");
125032      }
125033      return SQLITE_ERROR;
125034    }
125035  
125036    zEntry = zProc ? zProc : "sqlite3_extension_init";
125037  
125038    handle = sqlite3OsDlOpen(pVfs, zFile);
125039  #if SQLITE_OS_UNIX || SQLITE_OS_WIN
125040    for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
125041      char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
125042      if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
125043      handle = sqlite3OsDlOpen(pVfs, zAltFile);
125044      sqlite3_free(zAltFile);
125045    }
125046  #endif
125047    if( handle==0 ){
125048      if( pzErrMsg ){
125049        *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
125050        if( zErrmsg ){
125051          sqlite3_snprintf(nMsg, zErrmsg, 
125052              "unable to open shared library [%s]", zFile);
125053          sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
125054        }
125055      }
125056      return SQLITE_ERROR;
125057    }
125058    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
125059  
125060    /* If no entry point was specified and the default legacy
125061    ** entry point name "sqlite3_extension_init" was not found, then
125062    ** construct an entry point name "sqlite3_X_init" where the X is
125063    ** replaced by the lowercase value of every ASCII alphabetic 
125064    ** character in the filename after the last "/" upto the first ".",
125065    ** and eliding the first three characters if they are "lib".  
125066    ** Examples:
125067    **
125068    **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
125069    **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
125070    */
125071    if( xInit==0 && zProc==0 ){
125072      int iFile, iEntry, c;
125073      int ncFile = sqlite3Strlen30(zFile);
125074      zAltEntry = sqlite3_malloc64(ncFile+30);
125075      if( zAltEntry==0 ){
125076        sqlite3OsDlClose(pVfs, handle);
125077        return SQLITE_NOMEM_BKPT;
125078      }
125079      memcpy(zAltEntry, "sqlite3_", 8);
125080      for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
125081      iFile++;
125082      if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
125083      for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
125084        if( sqlite3Isalpha(c) ){
125085          zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
125086        }
125087      }
125088      memcpy(zAltEntry+iEntry, "_init", 6);
125089      zEntry = zAltEntry;
125090      xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
125091    }
125092    if( xInit==0 ){
125093      if( pzErrMsg ){
125094        nMsg += sqlite3Strlen30(zEntry);
125095        *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
125096        if( zErrmsg ){
125097          sqlite3_snprintf(nMsg, zErrmsg,
125098              "no entry point [%s] in shared library [%s]", zEntry, zFile);
125099          sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
125100        }
125101      }
125102      sqlite3OsDlClose(pVfs, handle);
125103      sqlite3_free(zAltEntry);
125104      return SQLITE_ERROR;
125105    }
125106    sqlite3_free(zAltEntry);
125107    rc = xInit(db, &zErrmsg, &sqlite3Apis);
125108    if( rc ){
125109      if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
125110      if( pzErrMsg ){
125111        *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
125112      }
125113      sqlite3_free(zErrmsg);
125114      sqlite3OsDlClose(pVfs, handle);
125115      return SQLITE_ERROR;
125116    }
125117  
125118    /* Append the new shared library handle to the db->aExtension array. */
125119    aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
125120    if( aHandle==0 ){
125121      return SQLITE_NOMEM_BKPT;
125122    }
125123    if( db->nExtension>0 ){
125124      memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
125125    }
125126    sqlite3DbFree(db, db->aExtension);
125127    db->aExtension = aHandle;
125128  
125129    db->aExtension[db->nExtension++] = handle;
125130    return SQLITE_OK;
125131  }
125132  SQLITE_API int sqlite3_load_extension(
125133    sqlite3 *db,          /* Load the extension into this database connection */
125134    const char *zFile,    /* Name of the shared library containing extension */
125135    const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
125136    char **pzErrMsg       /* Put error message here if not 0 */
125137  ){
125138    int rc;
125139    sqlite3_mutex_enter(db->mutex);
125140    rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
125141    rc = sqlite3ApiExit(db, rc);
125142    sqlite3_mutex_leave(db->mutex);
125143    return rc;
125144  }
125145  
125146  /*
125147  ** Call this routine when the database connection is closing in order
125148  ** to clean up loaded extensions
125149  */
125150  SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
125151    int i;
125152    assert( sqlite3_mutex_held(db->mutex) );
125153    for(i=0; i<db->nExtension; i++){
125154      sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
125155    }
125156    sqlite3DbFree(db, db->aExtension);
125157  }
125158  
125159  /*
125160  ** Enable or disable extension loading.  Extension loading is disabled by
125161  ** default so as not to open security holes in older applications.
125162  */
125163  SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
125164    sqlite3_mutex_enter(db->mutex);
125165    if( onoff ){
125166      db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
125167    }else{
125168      db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
125169    }
125170    sqlite3_mutex_leave(db->mutex);
125171    return SQLITE_OK;
125172  }
125173  
125174  #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
125175  
125176  /*
125177  ** The following object holds the list of automatically loaded
125178  ** extensions.
125179  **
125180  ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
125181  ** mutex must be held while accessing this list.
125182  */
125183  typedef struct sqlite3AutoExtList sqlite3AutoExtList;
125184  static SQLITE_WSD struct sqlite3AutoExtList {
125185    u32 nExt;              /* Number of entries in aExt[] */          
125186    void (**aExt)(void);   /* Pointers to the extension init functions */
125187  } sqlite3Autoext = { 0, 0 };
125188  
125189  /* The "wsdAutoext" macro will resolve to the autoextension
125190  ** state vector.  If writable static data is unsupported on the target,
125191  ** we have to locate the state vector at run-time.  In the more common
125192  ** case where writable static data is supported, wsdStat can refer directly
125193  ** to the "sqlite3Autoext" state vector declared above.
125194  */
125195  #ifdef SQLITE_OMIT_WSD
125196  # define wsdAutoextInit \
125197    sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
125198  # define wsdAutoext x[0]
125199  #else
125200  # define wsdAutoextInit
125201  # define wsdAutoext sqlite3Autoext
125202  #endif
125203  
125204  
125205  /*
125206  ** Register a statically linked extension that is automatically
125207  ** loaded by every new database connection.
125208  */
125209  SQLITE_API int sqlite3_auto_extension(
125210    void (*xInit)(void)
125211  ){
125212    int rc = SQLITE_OK;
125213  #ifndef SQLITE_OMIT_AUTOINIT
125214    rc = sqlite3_initialize();
125215    if( rc ){
125216      return rc;
125217    }else
125218  #endif
125219    {
125220      u32 i;
125221  #if SQLITE_THREADSAFE
125222      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
125223  #endif
125224      wsdAutoextInit;
125225      sqlite3_mutex_enter(mutex);
125226      for(i=0; i<wsdAutoext.nExt; i++){
125227        if( wsdAutoext.aExt[i]==xInit ) break;
125228      }
125229      if( i==wsdAutoext.nExt ){
125230        u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
125231        void (**aNew)(void);
125232        aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
125233        if( aNew==0 ){
125234          rc = SQLITE_NOMEM_BKPT;
125235        }else{
125236          wsdAutoext.aExt = aNew;
125237          wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
125238          wsdAutoext.nExt++;
125239        }
125240      }
125241      sqlite3_mutex_leave(mutex);
125242      assert( (rc&0xff)==rc );
125243      return rc;
125244    }
125245  }
125246  
125247  /*
125248  ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
125249  ** set of routines that is invoked for each new database connection, if it
125250  ** is currently on the list.  If xInit is not on the list, then this
125251  ** routine is a no-op.
125252  **
125253  ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
125254  ** was not on the list.
125255  */
125256  SQLITE_API int sqlite3_cancel_auto_extension(
125257    void (*xInit)(void)
125258  ){
125259  #if SQLITE_THREADSAFE
125260    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
125261  #endif
125262    int i;
125263    int n = 0;
125264    wsdAutoextInit;
125265    sqlite3_mutex_enter(mutex);
125266    for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
125267      if( wsdAutoext.aExt[i]==xInit ){
125268        wsdAutoext.nExt--;
125269        wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
125270        n++;
125271        break;
125272      }
125273    }
125274    sqlite3_mutex_leave(mutex);
125275    return n;
125276  }
125277  
125278  /*
125279  ** Reset the automatic extension loading mechanism.
125280  */
125281  SQLITE_API void sqlite3_reset_auto_extension(void){
125282  #ifndef SQLITE_OMIT_AUTOINIT
125283    if( sqlite3_initialize()==SQLITE_OK )
125284  #endif
125285    {
125286  #if SQLITE_THREADSAFE
125287      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
125288  #endif
125289      wsdAutoextInit;
125290      sqlite3_mutex_enter(mutex);
125291      sqlite3_free(wsdAutoext.aExt);
125292      wsdAutoext.aExt = 0;
125293      wsdAutoext.nExt = 0;
125294      sqlite3_mutex_leave(mutex);
125295    }
125296  }
125297  
125298  /*
125299  ** Load all automatic extensions.
125300  **
125301  ** If anything goes wrong, set an error in the database connection.
125302  */
125303  SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
125304    u32 i;
125305    int go = 1;
125306    int rc;
125307    sqlite3_loadext_entry xInit;
125308  
125309    wsdAutoextInit;
125310    if( wsdAutoext.nExt==0 ){
125311      /* Common case: early out without every having to acquire a mutex */
125312      return;
125313    }
125314    for(i=0; go; i++){
125315      char *zErrmsg;
125316  #if SQLITE_THREADSAFE
125317      sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
125318  #endif
125319  #ifdef SQLITE_OMIT_LOAD_EXTENSION
125320      const sqlite3_api_routines *pThunk = 0;
125321  #else
125322      const sqlite3_api_routines *pThunk = &sqlite3Apis;
125323  #endif
125324      sqlite3_mutex_enter(mutex);
125325      if( i>=wsdAutoext.nExt ){
125326        xInit = 0;
125327        go = 0;
125328      }else{
125329        xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
125330      }
125331      sqlite3_mutex_leave(mutex);
125332      zErrmsg = 0;
125333      if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
125334        sqlite3ErrorWithMsg(db, rc,
125335              "automatic extension loading failed: %s", zErrmsg);
125336        go = 0;
125337      }
125338      sqlite3_free(zErrmsg);
125339    }
125340  }
125341  
125342  /************** End of loadext.c *********************************************/
125343  /************** Begin file pragma.c ******************************************/
125344  /*
125345  ** 2003 April 6
125346  **
125347  ** The author disclaims copyright to this source code.  In place of
125348  ** a legal notice, here is a blessing:
125349  **
125350  **    May you do good and not evil.
125351  **    May you find forgiveness for yourself and forgive others.
125352  **    May you share freely, never taking more than you give.
125353  **
125354  *************************************************************************
125355  ** This file contains code used to implement the PRAGMA command.
125356  */
125357  /* #include "sqliteInt.h" */
125358  
125359  #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
125360  #  if defined(__APPLE__)
125361  #    define SQLITE_ENABLE_LOCKING_STYLE 1
125362  #  else
125363  #    define SQLITE_ENABLE_LOCKING_STYLE 0
125364  #  endif
125365  #endif
125366  
125367  /***************************************************************************
125368  ** The "pragma.h" include file is an automatically generated file that
125369  ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
125370  ** object.  This ensures that the aPragmaName[] table is arranged in
125371  ** lexicographical order to facility a binary search of the pragma name.
125372  ** Do not edit pragma.h directly.  Edit and rerun the script in at 
125373  ** ../tool/mkpragmatab.tcl. */
125374  /************** Include pragma.h in the middle of pragma.c *******************/
125375  /************** Begin file pragma.h ******************************************/
125376  /* DO NOT EDIT!
125377  ** This file is automatically generated by the script at
125378  ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
125379  ** that script and rerun it.
125380  */
125381  
125382  /* The various pragma types */
125383  #define PragTyp_HEADER_VALUE                   0
125384  #define PragTyp_AUTO_VACUUM                    1
125385  #define PragTyp_FLAG                           2
125386  #define PragTyp_BUSY_TIMEOUT                   3
125387  #define PragTyp_CACHE_SIZE                     4
125388  #define PragTyp_CACHE_SPILL                    5
125389  #define PragTyp_CASE_SENSITIVE_LIKE            6
125390  #define PragTyp_COLLATION_LIST                 7
125391  #define PragTyp_COMPILE_OPTIONS                8
125392  #define PragTyp_DATA_STORE_DIRECTORY           9
125393  #define PragTyp_DATABASE_LIST                 10
125394  #define PragTyp_DEFAULT_CACHE_SIZE            11
125395  #define PragTyp_ENCODING                      12
125396  #define PragTyp_FOREIGN_KEY_CHECK             13
125397  #define PragTyp_FOREIGN_KEY_LIST              14
125398  #define PragTyp_FUNCTION_LIST                 15
125399  #define PragTyp_INCREMENTAL_VACUUM            16
125400  #define PragTyp_INDEX_INFO                    17
125401  #define PragTyp_INDEX_LIST                    18
125402  #define PragTyp_INTEGRITY_CHECK               19
125403  #define PragTyp_JOURNAL_MODE                  20
125404  #define PragTyp_JOURNAL_SIZE_LIMIT            21
125405  #define PragTyp_LOCK_PROXY_FILE               22
125406  #define PragTyp_LOCKING_MODE                  23
125407  #define PragTyp_PAGE_COUNT                    24
125408  #define PragTyp_MMAP_SIZE                     25
125409  #define PragTyp_MODULE_LIST                   26
125410  #define PragTyp_OPTIMIZE                      27
125411  #define PragTyp_PAGE_SIZE                     28
125412  #define PragTyp_PRAGMA_LIST                   29
125413  #define PragTyp_SECURE_DELETE                 30
125414  #define PragTyp_SHRINK_MEMORY                 31
125415  #define PragTyp_SOFT_HEAP_LIMIT               32
125416  #define PragTyp_SYNCHRONOUS                   33
125417  #define PragTyp_TABLE_INFO                    34
125418  #define PragTyp_TEMP_STORE                    35
125419  #define PragTyp_TEMP_STORE_DIRECTORY          36
125420  #define PragTyp_THREADS                       37
125421  #define PragTyp_WAL_AUTOCHECKPOINT            38
125422  #define PragTyp_WAL_CHECKPOINT                39
125423  #define PragTyp_ACTIVATE_EXTENSIONS           40
125424  #define PragTyp_HEXKEY                        41
125425  #define PragTyp_KEY                           42
125426  #define PragTyp_LOCK_STATUS                   43
125427  #define PragTyp_STATS                         44
125428  
125429  #define PragTyp_LIST_BRANCHES                 47
125430  #define PragTyp_BRANCH                        48
125431  #define PragTyp_NEW_BRANCH                    49
125432  #define PragTyp_RENAME_BRANCH                 50
125433  #define PragTyp_DEL_BRANCH                    51
125434  #define PragTyp_BRANCH_TRUNCATE               52
125435  
125436  #define PragTyp_BRANCH_INFO                   53
125437  #define PragTyp_BRANCH_LOG                    54
125438  #define PragTyp_BRANCH_DIFF                   55
125439  #define PragTyp_BRANCH_MERGE                  56
125440  #define PragTyp_BRANCH_REBASE                 57
125441  #define PragTyp_DISCARD_COMMITS               58
125442  #define PragTyp_BRANCH_TREE                   59
125443  
125444  // PRAGMA rename_branch old_name new_name
125445  // PRAGMA rename_branch(old_name, new_name)
125446  
125447  // PRAGMA branch_result=json
125448  // PRAGMA branch_result=rows
125449  
125450  /* Property flags associated with various pragma. */
125451  #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
125452  #define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
125453  #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
125454  #define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
125455  #define PragFlg_Result0    0x10 /* Acts as query when no argument */
125456  #define PragFlg_Result1    0x20 /* Acts as query when has one argument */
125457  #define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
125458  #define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
125459  
125460  /* Names of columns for pragmas that return multi-column result
125461  ** or that return single-column results where the name of the
125462  ** result column is different from the name of the pragma
125463  */
125464  static const char *const pragCName[] = {
125465    /*   0 */ "id",          /* Used by: foreign_key_list */
125466    /*   1 */ "seq",        
125467    /*   2 */ "table",      
125468    /*   3 */ "from",       
125469    /*   4 */ "to",         
125470    /*   5 */ "on_update",  
125471    /*   6 */ "on_delete",  
125472    /*   7 */ "match",      
125473    /*   8 */ "cid",         /* Used by: table_xinfo */
125474    /*   9 */ "name",       
125475    /*  10 */ "type",       
125476    /*  11 */ "notnull",    
125477    /*  12 */ "dflt_value", 
125478    /*  13 */ "pk",         
125479    /*  14 */ "hidden",     
125480                             /* table_info reuses 8 */
125481    /*  15 */ "seqno",       /* Used by: index_xinfo */
125482    /*  16 */ "cid",        
125483    /*  17 */ "name",       
125484    /*  18 */ "desc",       
125485    /*  19 */ "coll",       
125486    /*  20 */ "key",        
125487    /*  21 */ "tbl",         /* Used by: stats */
125488    /*  22 */ "idx",        
125489    /*  23 */ "wdth",       
125490    /*  24 */ "hght",       
125491    /*  25 */ "flgs",       
125492    /*  26 */ "seq",         /* Used by: index_list */
125493    /*  27 */ "name",       
125494    /*  28 */ "unique",     
125495    /*  29 */ "origin",     
125496    /*  30 */ "partial",    
125497    /*  31 */ "table",       /* Used by: foreign_key_check */
125498    /*  32 */ "rowid",      
125499    /*  33 */ "parent",     
125500    /*  34 */ "fkid",       
125501                             /* index_info reuses 15 */
125502    /*  35 */ "seq",         /* Used by: database_list */
125503    /*  36 */ "name",       
125504    /*  37 */ "file",       
125505    /*  38 */ "busy",        /* Used by: wal_checkpoint */
125506    /*  39 */ "log",        
125507    /*  40 */ "checkpointed",
125508    /*  41 */ "name",        /* Used by: function_list */
125509    /*  42 */ "builtin",    
125510                             /* collation_list reuses 26 */
125511    /*  43 */ "database",    /* Used by: lock_status */
125512    /*  44 */ "status",     
125513    /*  45 */ "cache_size",  /* Used by: default_cache_size */
125514                             /* module_list pragma_list reuses 9 */
125515    /*  46 */ "timeout",     /* Used by: busy_timeout */
125516  
125517    /*  47 */ "branch",      /* Used by: branch, branches, new_branch */
125518    /*  48 */ "commit",      /* Used by: branch_log */
125519    /*  49 */ "sql",
125520    /*  50 */ "tree",        /* Used by: branch_tree */
125521  };
125522  
125523  /* Definitions of all built-in pragmas */
125524  typedef struct PragmaName {
125525    const char *const zName; /* Name of pragma */
125526    u8 ePragTyp;             /* PragTyp_XXX value */
125527    u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
125528    u8 iPragCName;           /* Start of column names in pragCName[] */
125529    u8 nPragCName;           /* Num of col names. 0 means use pragma name */
125530    u64 iArg;                /* Extra argument */
125531  } PragmaName;
125532  static const PragmaName aPragmaName[] = {
125533  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
125534   {/* zName:     */ "activate_extensions",
125535    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
125536    /* ePragFlg:  */ 0,
125537    /* ColNames:  */ 0, 0,
125538    /* iArg:      */ 0 },
125539  #endif
125540  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
125541   {/* zName:     */ "application_id",
125542    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
125543    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
125544    /* ColNames:  */ 0, 0,
125545    /* iArg:      */ BTREE_APPLICATION_ID },
125546  #endif
125547  #if !defined(SQLITE_OMIT_AUTOVACUUM)
125548   {/* zName:     */ "auto_vacuum",
125549    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
125550    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
125551    /* ColNames:  */ 0, 0,
125552    /* iArg:      */ 0 },
125553  #endif
125554  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125555  #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
125556   {/* zName:     */ "automatic_index",
125557    /* ePragTyp:  */ PragTyp_FLAG,
125558    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125559    /* ColNames:  */ 0, 0,
125560    /* iArg:      */ SQLITE_AutoIndex },
125561  #endif
125562  #endif
125563   {/* zName:     */ "branch",
125564    /* ePragTyp:  */ PragTyp_BRANCH,
125565    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,   // PragFlg_Result0|PragFlg_Result1
125566    /* ColNames:  */ 47, 1,
125567    /* iArg:      */ 0 },
125568   {/* zName:     */ "branch_diff",
125569    /* ePragTyp:  */ PragTyp_BRANCH_DIFF,
125570    /* ePragFlg:  */ PragFlg_Result1,
125571    /* ColNames:  */ 0, 0,
125572    /* iArg:      */ 0 },
125573   {/* zName:     */ "branch_info",
125574    /* ePragTyp:  */ PragTyp_BRANCH_INFO,
125575    /* ePragFlg:  */ PragFlg_Result1,
125576    /* ColNames:  */ 0, 0,
125577    /* iArg:      */ 0 },
125578   {/* zName:     */ "branch_log",
125579    /* ePragTyp:  */ PragTyp_BRANCH_LOG,
125580    /* ePragFlg:  */ PragFlg_Result0,
125581    /* ColNames:  */ 47, 3,
125582    /* iArg:      */ 0 },
125583   {/* zName:     */ "branch_merge",
125584    /* ePragTyp:  */ PragTyp_BRANCH_MERGE,
125585    /* ePragFlg:  */ PragFlg_Result0,
125586    /* ColNames:  */ 0, 0,
125587    /* iArg:      */ 0 },
125588   {/* zName:     */ "branch_rebase",
125589    /* ePragTyp:  */ PragTyp_BRANCH_REBASE,
125590    /* ePragFlg:  */ PragFlg_Result0,
125591    /* ColNames:  */ 0, 0,
125592    /* iArg:      */ 0 },
125593   {/* zName:     */ "branch_tree",
125594    /* ePragTyp:  */ PragTyp_BRANCH_TREE,
125595    /* ePragFlg:  */ PragFlg_Result0,
125596    /* ColNames:  */ 50, 1,
125597    /* iArg:      */ 0 },
125598   {/* zName:     */ "branch_truncate",
125599    /* ePragTyp:  */ PragTyp_BRANCH_TRUNCATE,
125600    /* ePragFlg:  */ PragFlg_Result0,
125601    /* ColNames:  */ 0, 0,
125602    /* iArg:      */ 0 },
125603   {/* zName:     */ "branches",
125604    /* ePragTyp:  */ PragTyp_LIST_BRANCHES,
125605    /* ePragFlg:  */ PragFlg_Result0,
125606    /* ColNames:  */ 47, 1,
125607    /* iArg:      */ 0 },
125608   {/* zName:     */ "busy_timeout",
125609    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
125610    /* ePragFlg:  */ PragFlg_Result0,
125611    /* ColNames:  */ 46, 1,
125612    /* iArg:      */ 0 },
125613  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
125614   {/* zName:     */ "cache_size",
125615    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
125616    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
125617    /* ColNames:  */ 0, 0,
125618    /* iArg:      */ 0 },
125619  #endif
125620  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125621   {/* zName:     */ "cache_spill",
125622    /* ePragTyp:  */ PragTyp_CACHE_SPILL,
125623    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
125624    /* ColNames:  */ 0, 0,
125625    /* iArg:      */ 0 },
125626  #endif
125627   {/* zName:     */ "case_sensitive_like",
125628    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
125629    /* ePragFlg:  */ PragFlg_NoColumns,
125630    /* ColNames:  */ 0, 0,
125631    /* iArg:      */ 0 },
125632   {/* zName:     */ "cell_size_check",
125633    /* ePragTyp:  */ PragTyp_FLAG,
125634    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125635    /* ColNames:  */ 0, 0,
125636    /* iArg:      */ SQLITE_CellSizeCk },
125637  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125638   {/* zName:     */ "checkpoint_fullfsync",
125639    /* ePragTyp:  */ PragTyp_FLAG,
125640    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125641    /* ColNames:  */ 0, 0,
125642    /* iArg:      */ SQLITE_CkptFullFSync },
125643  #endif
125644  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
125645   {/* zName:     */ "collation_list",
125646    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
125647    /* ePragFlg:  */ PragFlg_Result0,
125648    /* ColNames:  */ 26, 2,
125649    /* iArg:      */ 0 },
125650  #endif
125651  #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
125652   {/* zName:     */ "compile_options",
125653    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
125654    /* ePragFlg:  */ PragFlg_Result0,
125655    /* ColNames:  */ 0, 0,
125656    /* iArg:      */ 0 },
125657  #endif
125658  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125659   {/* zName:     */ "count_changes",
125660    /* ePragTyp:  */ PragTyp_FLAG,
125661    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125662    /* ColNames:  */ 0, 0,
125663    /* iArg:      */ SQLITE_CountRows },
125664  #endif
125665  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
125666   {/* zName:     */ "data_store_directory",
125667    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
125668    /* ePragFlg:  */ PragFlg_NoColumns1,
125669    /* ColNames:  */ 0, 0,
125670    /* iArg:      */ 0 },
125671  #endif
125672  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
125673   {/* zName:     */ "data_version",
125674    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
125675    /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
125676    /* ColNames:  */ 0, 0,
125677    /* iArg:      */ BTREE_DATA_VERSION },
125678  #endif
125679  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
125680   {/* zName:     */ "database_list",
125681    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
125682    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
125683    /* ColNames:  */ 35, 3,
125684    /* iArg:      */ 0 },
125685  #endif
125686  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
125687   {/* zName:     */ "default_cache_size",
125688    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
125689    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
125690    /* ColNames:  */ 45, 1,
125691    /* iArg:      */ 0 },
125692  #endif
125693  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125694  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
125695   {/* zName:     */ "defer_foreign_keys",
125696    /* ePragTyp:  */ PragTyp_FLAG,
125697    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125698    /* ColNames:  */ 0, 0,
125699    /* iArg:      */ SQLITE_DeferFKs },
125700  #endif
125701  #endif
125702   {/* zName:     */ "del_branch",
125703    /* ePragTyp:  */ PragTyp_DEL_BRANCH,
125704    /* ePragFlg:  */ PragFlg_Result1,
125705    /* ColNames:  */ 0, 0,
125706    /* iArg:      */ 0 },
125707   {/* zName:     */ "discard_commits",
125708    /* ePragTyp:  */ PragTyp_DISCARD_COMMITS,
125709    /* ePragFlg:  */ PragFlg_Result0,
125710    /* ColNames:  */ 0, 0,
125711    /* iArg:      */ 0 },
125712  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125713   {/* zName:     */ "empty_result_callbacks",
125714    /* ePragTyp:  */ PragTyp_FLAG,
125715    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125716    /* ColNames:  */ 0, 0,
125717    /* iArg:      */ SQLITE_NullCallback },
125718  #endif
125719  #if !defined(SQLITE_OMIT_UTF16)
125720   {/* zName:     */ "encoding",
125721    /* ePragTyp:  */ PragTyp_ENCODING,
125722    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125723    /* ColNames:  */ 0, 0,
125724    /* iArg:      */ 0 },
125725  #endif
125726  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
125727   {/* zName:     */ "foreign_key_check",
125728    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
125729    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
125730    /* ColNames:  */ 31, 4,
125731    /* iArg:      */ 0 },
125732  #endif
125733  #if !defined(SQLITE_OMIT_FOREIGN_KEY)
125734   {/* zName:     */ "foreign_key_list",
125735    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
125736    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
125737    /* ColNames:  */ 0, 8,
125738    /* iArg:      */ 0 },
125739  #endif
125740  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125741  #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
125742   {/* zName:     */ "foreign_keys",
125743    /* ePragTyp:  */ PragTyp_FLAG,
125744    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125745    /* ColNames:  */ 0, 0,
125746    /* iArg:      */ SQLITE_ForeignKeys },
125747  #endif
125748  #endif
125749  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
125750   {/* zName:     */ "freelist_count",
125751    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
125752    /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
125753    /* ColNames:  */ 0, 0,
125754    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
125755  #endif
125756  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125757   {/* zName:     */ "full_column_names",
125758    /* ePragTyp:  */ PragTyp_FLAG,
125759    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125760    /* ColNames:  */ 0, 0,
125761    /* iArg:      */ SQLITE_FullColNames },
125762   {/* zName:     */ "fullfsync",
125763    /* ePragTyp:  */ PragTyp_FLAG,
125764    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125765    /* ColNames:  */ 0, 0,
125766    /* iArg:      */ SQLITE_FullFSync },
125767  #endif
125768  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
125769  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
125770   {/* zName:     */ "function_list",
125771    /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
125772    /* ePragFlg:  */ PragFlg_Result0,
125773    /* ColNames:  */ 41, 2,
125774    /* iArg:      */ 0 },
125775  #endif
125776  #endif
125777  #if defined(SQLITE_HAS_CODEC)
125778   {/* zName:     */ "hexkey",
125779    /* ePragTyp:  */ PragTyp_HEXKEY,
125780    /* ePragFlg:  */ 0,
125781    /* ColNames:  */ 0, 0,
125782    /* iArg:      */ 2 },
125783   {/* zName:     */ "hexrekey",
125784    /* ePragTyp:  */ PragTyp_HEXKEY,
125785    /* ePragFlg:  */ 0,
125786    /* ColNames:  */ 0, 0,
125787    /* iArg:      */ 3 },
125788  #endif
125789  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125790  #if !defined(SQLITE_OMIT_CHECK)
125791   {/* zName:     */ "ignore_check_constraints",
125792    /* ePragTyp:  */ PragTyp_FLAG,
125793    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125794    /* ColNames:  */ 0, 0,
125795    /* iArg:      */ SQLITE_IgnoreChecks },
125796  #endif
125797  #endif
125798  #if !defined(SQLITE_OMIT_AUTOVACUUM)
125799   {/* zName:     */ "incremental_vacuum",
125800    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
125801    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
125802    /* ColNames:  */ 0, 0,
125803    /* iArg:      */ 0 },
125804  #endif
125805  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
125806   {/* zName:     */ "index_info",
125807    /* ePragTyp:  */ PragTyp_INDEX_INFO,
125808    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
125809    /* ColNames:  */ 15, 3,
125810    /* iArg:      */ 0 },
125811   {/* zName:     */ "index_list",
125812    /* ePragTyp:  */ PragTyp_INDEX_LIST,
125813    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
125814    /* ColNames:  */ 26, 5,
125815    /* iArg:      */ 0 },
125816   {/* zName:     */ "index_xinfo",
125817    /* ePragTyp:  */ PragTyp_INDEX_INFO,
125818    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
125819    /* ColNames:  */ 15, 6,
125820    /* iArg:      */ 1 },
125821  #endif
125822  #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
125823   {/* zName:     */ "integrity_check",
125824    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
125825    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
125826    /* ColNames:  */ 0, 0,
125827    /* iArg:      */ 0 },
125828  #endif
125829  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
125830   {/* zName:     */ "journal_mode",
125831    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
125832    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
125833    /* ColNames:  */ 0, 0,
125834    /* iArg:      */ 0 },
125835   {/* zName:     */ "journal_size_limit",
125836    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
125837    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
125838    /* ColNames:  */ 0, 0,
125839    /* iArg:      */ 0 },
125840  #endif
125841  #if defined(SQLITE_HAS_CODEC)
125842   {/* zName:     */ "key",
125843    /* ePragTyp:  */ PragTyp_KEY,
125844    /* ePragFlg:  */ 0,
125845    /* ColNames:  */ 0, 0,
125846    /* iArg:      */ 0 },
125847  #endif
125848  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125849   {/* zName:     */ "legacy_alter_table",
125850    /* ePragTyp:  */ PragTyp_FLAG,
125851    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125852    /* ColNames:  */ 0, 0,
125853    /* iArg:      */ SQLITE_LegacyAlter },
125854   {/* zName:     */ "legacy_file_format",
125855    /* ePragTyp:  */ PragTyp_FLAG,
125856    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125857    /* ColNames:  */ 0, 0,
125858    /* iArg:      */ SQLITE_LegacyFileFmt },
125859  #endif
125860  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
125861   {/* zName:     */ "lock_proxy_file",
125862    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
125863    /* ePragFlg:  */ PragFlg_NoColumns1,
125864    /* ColNames:  */ 0, 0,
125865    /* iArg:      */ 0 },
125866  #endif
125867  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
125868   {/* zName:     */ "lock_status",
125869    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
125870    /* ePragFlg:  */ PragFlg_Result0,
125871    /* ColNames:  */ 43, 2,
125872    /* iArg:      */ 0 },
125873  #endif
125874  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
125875   {/* zName:     */ "locking_mode",
125876    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
125877    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
125878    /* ColNames:  */ 0, 0,
125879    /* iArg:      */ 0 },
125880   {/* zName:     */ "max_page_count",
125881    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
125882    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
125883    /* ColNames:  */ 0, 0,
125884    /* iArg:      */ 0 },
125885   {/* zName:     */ "mmap_size",
125886    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
125887    /* ePragFlg:  */ 0,
125888    /* ColNames:  */ 0, 0,
125889    /* iArg:      */ 0 },
125890  #endif
125891  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
125892  #if !defined(SQLITE_OMIT_VIRTUALTABLE)
125893  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
125894   {/* zName:     */ "module_list",
125895    /* ePragTyp:  */ PragTyp_MODULE_LIST,
125896    /* ePragFlg:  */ PragFlg_Result0,
125897    /* ColNames:  */ 9, 1,
125898    /* iArg:      */ 0 },
125899  #endif
125900  #endif
125901  #endif
125902   {/* zName:     */ "new_branch",
125903    /* ePragTyp:  */ PragTyp_NEW_BRANCH,
125904    /* ePragFlg:  */ PragFlg_Result1,
125905    /* ColNames:  */ 47, 1,
125906    /* iArg:      */ 0 },
125907   {/* zName:     */ "optimize",
125908    /* ePragTyp:  */ PragTyp_OPTIMIZE,
125909    /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
125910    /* ColNames:  */ 0, 0,
125911    /* iArg:      */ 0 },
125912  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
125913   {/* zName:     */ "page_count",
125914    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
125915    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
125916    /* ColNames:  */ 0, 0,
125917    /* iArg:      */ 0 },
125918   {/* zName:     */ "page_size",
125919    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
125920    /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
125921    /* ColNames:  */ 0, 0,
125922    /* iArg:      */ 0 },
125923  #endif
125924  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125925  #if defined(SQLITE_DEBUG)
125926   {/* zName:     */ "parser_trace",
125927    /* ePragTyp:  */ PragTyp_FLAG,
125928    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125929    /* ColNames:  */ 0, 0,
125930    /* iArg:      */ SQLITE_ParserTrace },
125931  #endif
125932  #endif
125933  #if defined(SQLITE_INTROSPECTION_PRAGMAS)
125934   {/* zName:     */ "pragma_list",
125935    /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
125936    /* ePragFlg:  */ PragFlg_Result0,
125937    /* ColNames:  */ 9, 1,
125938    /* iArg:      */ 0 },
125939  #endif
125940  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125941   {/* zName:     */ "query_only",
125942    /* ePragTyp:  */ PragTyp_FLAG,
125943    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125944    /* ColNames:  */ 0, 0,
125945    /* iArg:      */ SQLITE_QueryOnly },
125946  #endif
125947  #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
125948   {/* zName:     */ "quick_check",
125949    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
125950    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
125951    /* ColNames:  */ 0, 0,
125952    /* iArg:      */ 0 },
125953  #endif
125954  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125955   {/* zName:     */ "read_uncommitted",
125956    /* ePragTyp:  */ PragTyp_FLAG,
125957    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125958    /* ColNames:  */ 0, 0,
125959    /* iArg:      */ SQLITE_ReadUncommit },
125960   {/* zName:     */ "recursive_triggers",
125961    /* ePragTyp:  */ PragTyp_FLAG,
125962    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125963    /* ColNames:  */ 0, 0,
125964    /* iArg:      */ SQLITE_RecTriggers },
125965  #endif
125966  #if defined(SQLITE_HAS_CODEC)
125967   {/* zName:     */ "rekey",
125968    /* ePragTyp:  */ PragTyp_KEY,
125969    /* ePragFlg:  */ 0,
125970    /* ColNames:  */ 0, 0,
125971    /* iArg:      */ 1 },
125972  #endif
125973   {/* zName:     */ "rename_branch",
125974    /* ePragTyp:  */ PragTyp_RENAME_BRANCH,
125975    /* ePragFlg:  */ PragFlg_NoColumns|PragFlg_NoColumns1,
125976    /* ColNames:  */ 0, 0,
125977    /* iArg:      */ 0 },
125978  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
125979   {/* zName:     */ "reverse_unordered_selects",
125980    /* ePragTyp:  */ PragTyp_FLAG,
125981    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
125982    /* ColNames:  */ 0, 0,
125983    /* iArg:      */ SQLITE_ReverseOrder },
125984  #endif
125985  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
125986   {/* zName:     */ "schema_version",
125987    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
125988    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
125989    /* ColNames:  */ 0, 0,
125990    /* iArg:      */ BTREE_SCHEMA_VERSION },
125991  #endif
125992  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
125993   {/* zName:     */ "secure_delete",
125994    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
125995    /* ePragFlg:  */ PragFlg_Result0,
125996    /* ColNames:  */ 0, 0,
125997    /* iArg:      */ 0 },
125998  #endif
125999  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
126000   {/* zName:     */ "short_column_names",
126001    /* ePragTyp:  */ PragTyp_FLAG,
126002    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126003    /* ColNames:  */ 0, 0,
126004    /* iArg:      */ SQLITE_ShortColNames },
126005  #endif
126006   {/* zName:     */ "shrink_memory",
126007    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
126008    /* ePragFlg:  */ PragFlg_NoColumns,
126009    /* ColNames:  */ 0, 0,
126010    /* iArg:      */ 0 },
126011   {/* zName:     */ "soft_heap_limit",
126012    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
126013    /* ePragFlg:  */ PragFlg_Result0,
126014    /* ColNames:  */ 0, 0,
126015    /* iArg:      */ 0 },
126016  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
126017  #if defined(SQLITE_DEBUG)
126018   {/* zName:     */ "sql_trace",
126019    /* ePragTyp:  */ PragTyp_FLAG,
126020    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126021    /* ColNames:  */ 0, 0,
126022    /* iArg:      */ SQLITE_SqlTrace },
126023  #endif
126024  #endif
126025  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
126026   {/* zName:     */ "stats",
126027    /* ePragTyp:  */ PragTyp_STATS,
126028    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
126029    /* ColNames:  */ 21, 5,
126030    /* iArg:      */ 0 },
126031  #endif
126032  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
126033   {/* zName:     */ "synchronous",
126034    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
126035    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
126036    /* ColNames:  */ 0, 0,
126037    /* iArg:      */ 0 },
126038  #endif
126039  #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
126040   {/* zName:     */ "table_info",
126041    /* ePragTyp:  */ PragTyp_TABLE_INFO,
126042    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
126043    /* ColNames:  */ 8, 6,
126044    /* iArg:      */ 0 },
126045   {/* zName:     */ "table_xinfo",
126046    /* ePragTyp:  */ PragTyp_TABLE_INFO,
126047    /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
126048    /* ColNames:  */ 8, 7,
126049    /* iArg:      */ 1 },
126050  #endif
126051  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
126052   {/* zName:     */ "temp_store",
126053    /* ePragTyp:  */ PragTyp_TEMP_STORE,
126054    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126055    /* ColNames:  */ 0, 0,
126056    /* iArg:      */ 0 },
126057   {/* zName:     */ "temp_store_directory",
126058    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
126059    /* ePragFlg:  */ PragFlg_NoColumns1,
126060    /* ColNames:  */ 0, 0,
126061    /* iArg:      */ 0 },
126062  #endif
126063  #if defined(SQLITE_HAS_CODEC)
126064   {/* zName:     */ "textkey",
126065    /* ePragTyp:  */ PragTyp_KEY,
126066    /* ePragFlg:  */ 0,
126067    /* ColNames:  */ 0, 0,
126068    /* iArg:      */ 4 },
126069   {/* zName:     */ "textrekey",
126070    /* ePragTyp:  */ PragTyp_KEY,
126071    /* ePragFlg:  */ 0,
126072    /* ColNames:  */ 0, 0,
126073    /* iArg:      */ 5 },
126074  #endif
126075   {/* zName:     */ "threads",
126076    /* ePragTyp:  */ PragTyp_THREADS,
126077    /* ePragFlg:  */ PragFlg_Result0,
126078    /* ColNames:  */ 0, 0,
126079    /* iArg:      */ 0 },
126080  #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
126081   {/* zName:     */ "user_version",
126082    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
126083    /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
126084    /* ColNames:  */ 0, 0,
126085    /* iArg:      */ BTREE_USER_VERSION },
126086  #endif
126087  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
126088  #if defined(SQLITE_DEBUG)
126089   {/* zName:     */ "vdbe_addoptrace",
126090    /* ePragTyp:  */ PragTyp_FLAG,
126091    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126092    /* ColNames:  */ 0, 0,
126093    /* iArg:      */ SQLITE_VdbeAddopTrace },
126094   {/* zName:     */ "vdbe_debug",
126095    /* ePragTyp:  */ PragTyp_FLAG,
126096    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126097    /* ColNames:  */ 0, 0,
126098    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
126099   {/* zName:     */ "vdbe_eqp",
126100    /* ePragTyp:  */ PragTyp_FLAG,
126101    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126102    /* ColNames:  */ 0, 0,
126103    /* iArg:      */ SQLITE_VdbeEQP },
126104   {/* zName:     */ "vdbe_listing",
126105    /* ePragTyp:  */ PragTyp_FLAG,
126106    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126107    /* ColNames:  */ 0, 0,
126108    /* iArg:      */ SQLITE_VdbeListing },
126109   {/* zName:     */ "vdbe_trace",
126110    /* ePragTyp:  */ PragTyp_FLAG,
126111    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126112    /* ColNames:  */ 0, 0,
126113    /* iArg:      */ SQLITE_VdbeTrace },
126114  #endif
126115  #endif
126116  #if !defined(SQLITE_OMIT_WAL)
126117   {/* zName:     */ "wal_autocheckpoint",
126118    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
126119    /* ePragFlg:  */ 0,
126120    /* ColNames:  */ 0, 0,
126121    /* iArg:      */ 0 },
126122   {/* zName:     */ "wal_checkpoint",
126123    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
126124    /* ePragFlg:  */ PragFlg_NeedSchema,
126125    /* ColNames:  */ 38, 3,
126126    /* iArg:      */ 0 },
126127  #endif
126128  #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
126129   {/* zName:     */ "writable_schema",
126130    /* ePragTyp:  */ PragTyp_FLAG,
126131    /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
126132    /* ColNames:  */ 0, 0,
126133    /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
126134  #endif
126135  };
126136  /* Number of pragmas: 62 on by default, 81 total. */
126137  
126138  /************** End of pragma.h **********************************************/
126139  /************** Continuing where we left off in pragma.c *********************/
126140  
126141  /*
126142  ** Interpret the given string as a safety level.  Return 0 for OFF,
126143  ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
126144  ** unrecognized string argument.  The FULL and EXTRA option is disallowed
126145  ** if the omitFull parameter it 1.
126146  **
126147  ** Note that the values returned are one less that the values that
126148  ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
126149  ** to support legacy SQL code.  The safety level used to be boolean
126150  ** and older scripts may have used numbers 0 for OFF and 1 for ON.
126151  */
126152  static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
126153                               /* 123456789 123456789 123 */
126154    static const char zText[] = "onoffalseyestruextrafull";
126155    static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
126156    static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
126157    static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
126158                              /* on no off false yes true extra full */
126159    int i, n;
126160    if( sqlite3Isdigit(*z) ){
126161      return (u8)sqlite3Atoi(z);
126162    }
126163    n = sqlite3Strlen30(z);
126164    for(i=0; i<ArraySize(iLength); i++){
126165      if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
126166       && (!omitFull || iValue[i]<=1)
126167      ){
126168        return iValue[i];
126169      }
126170    }
126171    return dflt;
126172  }
126173  
126174  /*
126175  ** Interpret the given string as a boolean value.
126176  */
126177  SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
126178    return getSafetyLevel(z,1,dflt)!=0;
126179  }
126180  
126181  /* The sqlite3GetBoolean() function is used by other modules but the
126182  ** remainder of this file is specific to PRAGMA processing.  So omit
126183  ** the rest of the file if PRAGMAs are omitted from the build.
126184  */
126185  #if !defined(SQLITE_OMIT_PRAGMA)
126186  
126187  /*
126188  ** Interpret the given string as a locking mode value.
126189  */
126190  static int getLockingMode(const char *z){
126191    if( z ){
126192      if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
126193      if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
126194    }
126195    return PAGER_LOCKINGMODE_QUERY;
126196  }
126197  
126198  #ifndef SQLITE_OMIT_AUTOVACUUM
126199  /*
126200  ** Interpret the given string as an auto-vacuum mode value.
126201  **
126202  ** The following strings, "none", "full" and "incremental" are 
126203  ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
126204  */
126205  static int getAutoVacuum(const char *z){
126206    int i;
126207    if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
126208    if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
126209    if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
126210    i = sqlite3Atoi(z);
126211    return (u8)((i>=0&&i<=2)?i:0);
126212  }
126213  #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
126214  
126215  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
126216  /*
126217  ** Interpret the given string as a temp db location. Return 1 for file
126218  ** backed temporary databases, 2 for the Red-Black tree in memory database
126219  ** and 0 to use the compile-time default.
126220  */
126221  static int getTempStore(const char *z){
126222    if( z[0]>='0' && z[0]<='2' ){
126223      return z[0] - '0';
126224    }else if( sqlite3StrICmp(z, "file")==0 ){
126225      return 1;
126226    }else if( sqlite3StrICmp(z, "memory")==0 ){
126227      return 2;
126228    }else{
126229      return 0;
126230    }
126231  }
126232  #endif /* SQLITE_PAGER_PRAGMAS */
126233  
126234  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
126235  /*
126236  ** Invalidate temp storage, either when the temp storage is changed
126237  ** from default, or when 'file' and the temp_store_directory has changed
126238  */
126239  static int invalidateTempStorage(Parse *pParse){
126240    sqlite3 *db = pParse->db;
126241    if( db->aDb[1].pBt!=0 ){
126242      if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
126243        sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
126244          "from within a transaction");
126245        return SQLITE_ERROR;
126246      }
126247      sqlite3BtreeClose(db->aDb[1].pBt);
126248      db->aDb[1].pBt = 0;
126249      sqlite3ResetAllSchemasOfConnection(db);
126250    }
126251    return SQLITE_OK;
126252  }
126253  #endif /* SQLITE_PAGER_PRAGMAS */
126254  
126255  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
126256  /*
126257  ** If the TEMP database is open, close it and mark the database schema
126258  ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
126259  ** or DEFAULT_TEMP_STORE pragmas.
126260  */
126261  static int changeTempStorage(Parse *pParse, const char *zStorageType){
126262    int ts = getTempStore(zStorageType);
126263    sqlite3 *db = pParse->db;
126264    if( db->temp_store==ts ) return SQLITE_OK;
126265    if( invalidateTempStorage( pParse ) != SQLITE_OK ){
126266      return SQLITE_ERROR;
126267    }
126268    db->temp_store = (u8)ts;
126269    return SQLITE_OK;
126270  }
126271  #endif /* SQLITE_PAGER_PRAGMAS */
126272  
126273  /*
126274  ** Set result column names for a pragma.
126275  */
126276  static void setPragmaResultColumnNames(
126277    Vdbe *v,                     /* The query under construction */
126278    const PragmaName *pPragma    /* The pragma */
126279  ){
126280    u8 n = pPragma->nPragCName;
126281    sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
126282    if( n==0 ){
126283      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
126284    }else{
126285      int i, j;
126286      for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
126287        sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
126288      }
126289    }
126290  }
126291  
126292  /*
126293  ** Generate code to return a single integer value.
126294  */
126295  static void returnSingleInt(Vdbe *v, i64 value){
126296    sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
126297    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
126298  }
126299  
126300  /*
126301  ** Generate code to return a single text value.
126302  */
126303  static void returnSingleText(
126304    Vdbe *v,                /* Prepared statement under construction */
126305    const char *zValue      /* Value to be returned */
126306  ){
126307    if( zValue ){
126308      sqlite3VdbeLoadString(v, 1, (const char*)zValue);
126309      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
126310    }
126311  }
126312  
126313  
126314  /*
126315  ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
126316  ** set these values for all pagers.
126317  */
126318  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
126319  static void setAllPagerFlags(sqlite3 *db){
126320    if( db->autoCommit ){
126321      Db *pDb = db->aDb;
126322      int n = db->nDb;
126323      assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
126324      assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
126325      assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
126326      assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
126327               ==  PAGER_FLAGS_MASK );
126328      assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
126329      while( (n--) > 0 ){
126330        if( pDb->pBt ){
126331          sqlite3BtreeSetPagerFlags(pDb->pBt,
126332                   pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
126333        }
126334        pDb++;
126335      }
126336    }
126337  }
126338  #else
126339  # define setAllPagerFlags(X)  /* no-op */
126340  #endif
126341  
126342  
126343  /*
126344  ** Return a human-readable name for a constraint resolution action.
126345  */
126346  #ifndef SQLITE_OMIT_FOREIGN_KEY
126347  static const char *actionName(u8 action){
126348    const char *zName;
126349    switch( action ){
126350      case OE_SetNull:  zName = "SET NULL";        break;
126351      case OE_SetDflt:  zName = "SET DEFAULT";     break;
126352      case OE_Cascade:  zName = "CASCADE";         break;
126353      case OE_Restrict: zName = "RESTRICT";        break;
126354      default:          zName = "NO ACTION";  
126355                        assert( action==OE_None ); break;
126356    }
126357    return zName;
126358  }
126359  #endif
126360  
126361  
126362  /*
126363  ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
126364  ** defined in pager.h. This function returns the associated lowercase
126365  ** journal-mode name.
126366  */
126367  SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
126368    static char * const azModeName[] = {
126369      "delete", "persist", "off", "truncate", "memory"
126370  #ifndef SQLITE_OMIT_WAL
126371       , "wal"
126372  #endif
126373       , "branches"
126374    };
126375    assert( PAGER_JOURNALMODE_DELETE==0 );
126376    assert( PAGER_JOURNALMODE_PERSIST==1 );
126377    assert( PAGER_JOURNALMODE_OFF==2 );
126378    assert( PAGER_JOURNALMODE_TRUNCATE==3 );
126379    assert( PAGER_JOURNALMODE_MEMORY==4 );
126380    assert( PAGER_JOURNALMODE_WAL==5 );
126381    assert( PAGER_JOURNALMODE_BRANCHES==6 );
126382    assert( eMode>=0 && eMode<=ArraySize(azModeName) );
126383  
126384    if( eMode>=ArraySize(azModeName) ) return 0;
126385    return azModeName[eMode];
126386  }
126387  
126388  /*
126389  ** Locate a pragma in the aPragmaName[] array.
126390  */
126391  static const PragmaName *pragmaLocate(const char *zName){
126392    int upr, lwr, mid = 0, rc;
126393    lwr = 0;
126394    upr = ArraySize(aPragmaName)-1;
126395    while( lwr<=upr ){
126396      mid = (lwr+upr)/2;
126397      rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
126398      if( rc==0 ) break;
126399      if( rc<0 ){
126400        upr = mid - 1;
126401      }else{
126402        lwr = mid + 1;
126403      }
126404    }
126405    return lwr>upr ? 0 : &aPragmaName[mid];
126406  }
126407  
126408  /*
126409  ** Helper subroutine for PRAGMA integrity_check:
126410  **
126411  ** Generate code to output a single-column result row with a value of the
126412  ** string held in register 3.  Decrement the result count in register 1
126413  ** and halt if the maximum number of result rows have been issued.
126414  */
126415  static int integrityCheckResultRow(Vdbe *v){
126416    int addr;
126417    sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
126418    addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
126419    VdbeCoverage(v);
126420    sqlite3VdbeAddOp0(v, OP_Halt);
126421    return addr;
126422  }
126423  
126424  /*
126425  ** Process a pragma statement.  
126426  **
126427  ** Pragmas are of this form:
126428  **
126429  **      PRAGMA [schema.]id [= value]
126430  **
126431  ** The identifier might also be a string.  The value is a string, and
126432  ** identifier, or a number.  If minusFlag is true, then the value is
126433  ** a number that was preceded by a minus sign.
126434  **
126435  ** If the left side is "database.id" then pId1 is the database name
126436  ** and pId2 is the id.  If the left side is just "id" then pId1 is the
126437  ** id and pId2 is any empty string.
126438  */
126439  SQLITE_PRIVATE void sqlite3Pragma(
126440    Parse *pParse, 
126441    Token *pId1,        /* First part of [schema.]id field */
126442    Token *pId2,        /* Second part of [schema.]id field, or NULL */
126443    Token *pValue,      /* Token for <value>, or NULL */
126444    int minusFlag       /* True if a '-' sign preceded <value> */
126445  ){
126446    char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
126447    char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
126448    const char *zDb = 0;   /* The database name */
126449    Token *pId;            /* Pointer to <id> token */
126450    char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
126451    int iDb;               /* Database index for <database> */
126452    int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
126453    sqlite3 *db = pParse->db;    /* The database connection */
126454    Db *pDb;                     /* The specific database being pragmaed */
126455    Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
126456    const PragmaName *pPragma;   /* The pragma */
126457  
126458    if( v==0 ) return;
126459    sqlite3VdbeRunOnlyOnce(v);
126460    pParse->nMem = 2;
126461  
126462    /* Interpret the [schema.] part of the pragma statement. iDb is the
126463    ** index of the database this pragma is being applied to in db.aDb[]. */
126464    iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
126465    if( iDb<0 ) return;
126466    pDb = &db->aDb[iDb];
126467  
126468    /* If the temp database has been explicitly named as part of the 
126469    ** pragma, make sure it is open. 
126470    */
126471    if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
126472      return;
126473    }
126474  
126475    zLeft = sqlite3NameFromToken(db, pId);
126476    if( !zLeft ) return;
126477    if( minusFlag ){
126478      zRight = sqlite3MPrintf(db, "-%T", pValue);
126479    }else{
126480      zRight = sqlite3NameFromToken(db, pValue);
126481    }
126482  
126483    assert( pId2 );
126484    zDb = pId2->n>0 ? pDb->zDbSName : 0;
126485    if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
126486      goto pragma_out;
126487    }
126488  
126489    /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
126490    ** connection.  If it returns SQLITE_OK, then assume that the VFS
126491    ** handled the pragma and generate a no-op prepared statement.
126492    **
126493    ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
126494    ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
126495    ** object corresponding to the database file to which the pragma
126496    ** statement refers.
126497    **
126498    ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
126499    ** file control is an array of pointers to strings (char**) in which the
126500    ** second element of the array is the name of the pragma and the third
126501    ** element is the argument to the pragma or NULL if the pragma has no
126502    ** argument.
126503    */
126504    aFcntl[0] = 0;
126505    aFcntl[1] = zLeft;
126506    aFcntl[2] = zRight;
126507    aFcntl[3] = 0;
126508    db->busyHandler.nBusy = 0;
126509    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
126510    if( rc==SQLITE_OK ){
126511      sqlite3VdbeSetNumCols(v, 1);
126512      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
126513      returnSingleText(v, aFcntl[0]);
126514      sqlite3_free(aFcntl[0]);
126515      goto pragma_out;
126516    }
126517    if( rc!=SQLITE_NOTFOUND ){
126518      if( aFcntl[0] ){
126519        sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
126520        sqlite3_free(aFcntl[0]);
126521      }
126522      pParse->nErr++;
126523      pParse->rc = rc;
126524      goto pragma_out;
126525    }
126526  
126527    /* Locate the pragma in the lookup table */
126528    pPragma = pragmaLocate(zLeft);
126529    if( pPragma==0 ) goto pragma_out;
126530  
126531    /* Make sure the database schema is loaded if the pragma requires that */
126532    if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
126533      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
126534    }
126535  
126536    /* Register the result column names for pragmas that return results */
126537    if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 
126538     && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
126539    ){
126540      setPragmaResultColumnNames(v, pPragma);
126541    }
126542  
126543    /* Jump to the appropriate pragma handler */
126544    switch( pPragma->ePragTyp ){
126545    
126546  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
126547    /*
126548    **  PRAGMA [schema.]default_cache_size
126549    **  PRAGMA [schema.]default_cache_size=N
126550    **
126551    ** The first form reports the current persistent setting for the
126552    ** page cache size.  The value returned is the maximum number of
126553    ** pages in the page cache.  The second form sets both the current
126554    ** page cache size value and the persistent page cache size value
126555    ** stored in the database file.
126556    **
126557    ** Older versions of SQLite would set the default cache size to a
126558    ** negative number to indicate synchronous=OFF.  These days, synchronous
126559    ** is always on by default regardless of the sign of the default cache
126560    ** size.  But continue to take the absolute value of the default cache
126561    ** size of historical compatibility.
126562    */
126563    case PragTyp_DEFAULT_CACHE_SIZE: {
126564      static const int iLn = VDBE_OFFSET_LINENO(2);
126565      static const VdbeOpList getCacheSize[] = {
126566        { OP_Transaction, 0, 0,        0},                         /* 0 */
126567        { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
126568        { OP_IfPos,       1, 8,        0},
126569        { OP_Integer,     0, 2,        0},
126570        { OP_Subtract,    1, 2,        1},
126571        { OP_IfPos,       1, 8,        0},
126572        { OP_Integer,     0, 1,        0},                         /* 6 */
126573        { OP_Noop,        0, 0,        0},
126574        { OP_ResultRow,   1, 1,        0},
126575      };
126576      VdbeOp *aOp;
126577      sqlite3VdbeUsesBtree(v, iDb);
126578      if( !zRight ){
126579        pParse->nMem += 2;
126580        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
126581        aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
126582        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
126583        aOp[0].p1 = iDb;
126584        aOp[1].p1 = iDb;
126585        aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
126586      }else{
126587        int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
126588        sqlite3BeginWriteOperation(pParse, 0, iDb);
126589        sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
126590        assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
126591        pDb->pSchema->cache_size = size;
126592        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
126593      }
126594      break;
126595    }
126596  #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
126597  
126598  #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
126599    /*
126600    **  PRAGMA [schema.]page_size
126601    **  PRAGMA [schema.]page_size=N
126602    **
126603    ** The first form reports the current setting for the
126604    ** database page size in bytes.  The second form sets the
126605    ** database page size value.  The value can only be set if
126606    ** the database has not yet been created.
126607    */
126608    case PragTyp_PAGE_SIZE: {
126609      Btree *pBt = pDb->pBt;
126610      assert( pBt!=0 );
126611      if( !zRight ){
126612        int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
126613        returnSingleInt(v, size);
126614      }else{
126615        /* Malloc may fail when setting the page-size, as there is an internal
126616        ** buffer that the pager module resizes using sqlite3_realloc().
126617        */
126618        db->nextPagesize = sqlite3Atoi(zRight);
126619        if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
126620          sqlite3OomFault(db);
126621        }
126622      }
126623      break;
126624    }
126625  
126626    /*
126627    **  PRAGMA [schema.]secure_delete
126628    **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
126629    **
126630    ** The first form reports the current setting for the
126631    ** secure_delete flag.  The second form changes the secure_delete
126632    ** flag setting and reports the new value.
126633    */
126634    case PragTyp_SECURE_DELETE: {
126635      Btree *pBt = pDb->pBt;
126636      int b = -1;
126637      assert( pBt!=0 );
126638      if( zRight ){
126639        if( sqlite3_stricmp(zRight, "fast")==0 ){
126640          b = 2;
126641        }else{
126642          b = sqlite3GetBoolean(zRight, 0);
126643        }
126644      }
126645      if( pId2->n==0 && b>=0 ){
126646        int ii;
126647        for(ii=0; ii<db->nDb; ii++){
126648          sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
126649        }
126650      }
126651      b = sqlite3BtreeSecureDelete(pBt, b);
126652      returnSingleInt(v, b);
126653      break;
126654    }
126655  
126656    /*
126657    **  PRAGMA [schema.]max_page_count
126658    **  PRAGMA [schema.]max_page_count=N
126659    **
126660    ** The first form reports the current setting for the
126661    ** maximum number of pages in the database file.  The 
126662    ** second form attempts to change this setting.  Both
126663    ** forms return the current setting.
126664    **
126665    ** The absolute value of N is used.  This is undocumented and might
126666    ** change.  The only purpose is to provide an easy way to test
126667    ** the sqlite3AbsInt32() function.
126668    **
126669    **  PRAGMA [schema.]page_count
126670    **
126671    ** Return the number of pages in the specified database.
126672    */
126673    case PragTyp_PAGE_COUNT: {
126674      int iReg;
126675      sqlite3CodeVerifySchema(pParse, iDb);
126676      iReg = ++pParse->nMem;
126677      if( sqlite3Tolower(zLeft[0])=='p' ){
126678        sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
126679      }else{
126680        sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
126681                          sqlite3AbsInt32(sqlite3Atoi(zRight)));
126682      }
126683      sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
126684      break;
126685    }
126686  
126687    /*
126688    **  PRAGMA [schema.]locking_mode
126689    **  PRAGMA [schema.]locking_mode = (normal|exclusive)
126690    */
126691    case PragTyp_LOCKING_MODE: {
126692      const char *zRet = "normal";
126693      int eMode = getLockingMode(zRight);
126694  
126695      if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
126696        /* Simple "PRAGMA locking_mode;" statement. This is a query for
126697        ** the current default locking mode (which may be different to
126698        ** the locking-mode of the main database).
126699        */
126700        eMode = db->dfltLockMode;
126701      }else{
126702        Pager *pPager;
126703        if( pId2->n==0 ){
126704          /* This indicates that no database name was specified as part
126705          ** of the PRAGMA command. In this case the locking-mode must be
126706          ** set on all attached databases, as well as the main db file.
126707          **
126708          ** Also, the sqlite3.dfltLockMode variable is set so that
126709          ** any subsequently attached databases also use the specified
126710          ** locking mode.
126711          */
126712          int ii;
126713          assert(pDb==&db->aDb[0]);
126714          for(ii=2; ii<db->nDb; ii++){
126715            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
126716            sqlite3PagerLockingMode(pPager, eMode);
126717          }
126718          db->dfltLockMode = (u8)eMode;
126719        }
126720        pPager = sqlite3BtreePager(pDb->pBt);
126721        eMode = sqlite3PagerLockingMode(pPager, eMode);
126722      }
126723  
126724      assert( eMode==PAGER_LOCKINGMODE_NORMAL
126725              || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
126726      if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
126727        zRet = "exclusive";
126728      }
126729      returnSingleText(v, zRet);
126730      break;
126731    }
126732  
126733    /*
126734    **  PRAGMA [schema.]journal_mode
126735    **  PRAGMA [schema.]journal_mode =
126736    **                      (delete|persist|off|truncate|memory|wal|off)
126737    */
126738    case PragTyp_JOURNAL_MODE: {
126739      int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
126740      int ii;           /* Loop counter */
126741  
126742      if( zRight==0 ){
126743        /* If there is no "=MODE" part of the pragma, do a query for the
126744        ** current mode */
126745        eMode = PAGER_JOURNALMODE_QUERY;
126746      }else{
126747        const char *zMode;
126748        int n = sqlite3Strlen30(zRight);
126749        for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
126750          if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
126751        }
126752        if( !zMode ){
126753          /* If the "=MODE" part does not match any known journal mode,
126754          ** then do a query */
126755          eMode = PAGER_JOURNALMODE_QUERY;
126756        }
126757      }
126758      if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
126759        /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
126760        iDb = 0;
126761        pId2->n = 1;
126762      }
126763      for(ii=db->nDb-1; ii>=0; ii--){
126764        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
126765          sqlite3VdbeUsesBtree(v, ii);
126766          sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
126767        }
126768      }
126769      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
126770      break;
126771    }
126772  
126773    /*
126774    **  PRAGMA [schema.]journal_size_limit
126775    **  PRAGMA [schema.]journal_size_limit=N
126776    **
126777    ** Get or set the size limit on rollback journal files.
126778    */
126779    case PragTyp_JOURNAL_SIZE_LIMIT: {
126780      Pager *pPager = sqlite3BtreePager(pDb->pBt);
126781      i64 iLimit = -2;
126782      if( zRight ){
126783        sqlite3DecOrHexToI64(zRight, &iLimit);
126784        if( iLimit<-1 ) iLimit = -1;
126785      }
126786      iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
126787      returnSingleInt(v, iLimit);
126788      break;
126789    }
126790  
126791  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
126792  
126793    /*
126794    **  PRAGMA [schema.]auto_vacuum
126795    **  PRAGMA [schema.]auto_vacuum=N
126796    **
126797    ** Get or set the value of the database 'auto-vacuum' parameter.
126798    ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
126799    */
126800  #ifndef SQLITE_OMIT_AUTOVACUUM
126801    case PragTyp_AUTO_VACUUM: {
126802      Btree *pBt = pDb->pBt;
126803      assert( pBt!=0 );
126804      if( !zRight ){
126805        returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
126806      }else{
126807        int eAuto = getAutoVacuum(zRight);
126808        assert( eAuto>=0 && eAuto<=2 );
126809        db->nextAutovac = (u8)eAuto;
126810        /* Call SetAutoVacuum() to set initialize the internal auto and
126811        ** incr-vacuum flags. This is required in case this connection
126812        ** creates the database file. It is important that it is created
126813        ** as an auto-vacuum capable db.
126814        */
126815        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
126816        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
126817          /* When setting the auto_vacuum mode to either "full" or 
126818          ** "incremental", write the value of meta[6] in the database
126819          ** file. Before writing to meta[6], check that meta[3] indicates
126820          ** that this really is an auto-vacuum capable database.
126821          */
126822          static const int iLn = VDBE_OFFSET_LINENO(2);
126823          static const VdbeOpList setMeta6[] = {
126824            { OP_Transaction,    0,         1,                 0},    /* 0 */
126825            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
126826            { OP_If,             1,         0,                 0},    /* 2 */
126827            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
126828            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
126829          };
126830          VdbeOp *aOp;
126831          int iAddr = sqlite3VdbeCurrentAddr(v);
126832          sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
126833          aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
126834          if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
126835          aOp[0].p1 = iDb;
126836          aOp[1].p1 = iDb;
126837          aOp[2].p2 = iAddr+4;
126838          aOp[4].p1 = iDb;
126839          aOp[4].p3 = eAuto - 1;
126840          sqlite3VdbeUsesBtree(v, iDb);
126841        }
126842      }
126843      break;
126844    }
126845  #endif
126846  
126847    /*
126848    **  PRAGMA [schema.]incremental_vacuum(N)
126849    **
126850    ** Do N steps of incremental vacuuming on a database.
126851    */
126852  #ifndef SQLITE_OMIT_AUTOVACUUM
126853    case PragTyp_INCREMENTAL_VACUUM: {
126854      int iLimit, addr;
126855      if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
126856        iLimit = 0x7fffffff;
126857      }
126858      sqlite3BeginWriteOperation(pParse, 0, iDb);
126859      sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
126860      addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
126861      sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
126862      sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
126863      sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
126864      sqlite3VdbeJumpHere(v, addr);
126865      break;
126866    }
126867  #endif
126868  
126869  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
126870    /*
126871    **  PRAGMA [schema.]cache_size
126872    **  PRAGMA [schema.]cache_size=N
126873    **
126874    ** The first form reports the current local setting for the
126875    ** page cache size. The second form sets the local
126876    ** page cache size value.  If N is positive then that is the
126877    ** number of pages in the cache.  If N is negative, then the
126878    ** number of pages is adjusted so that the cache uses -N kibibytes
126879    ** of memory.
126880    */
126881    case PragTyp_CACHE_SIZE: {
126882      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
126883      if( !zRight ){
126884        returnSingleInt(v, pDb->pSchema->cache_size);
126885      }else{
126886        int size = sqlite3Atoi(zRight);
126887        pDb->pSchema->cache_size = size;
126888        sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
126889      }
126890      break;
126891    }
126892  
126893    /*
126894    **  PRAGMA [schema.]cache_spill
126895    **  PRAGMA cache_spill=BOOLEAN
126896    **  PRAGMA [schema.]cache_spill=N
126897    **
126898    ** The first form reports the current local setting for the
126899    ** page cache spill size. The second form turns cache spill on
126900    ** or off.  When turnning cache spill on, the size is set to the
126901    ** current cache_size.  The third form sets a spill size that
126902    ** may be different form the cache size.
126903    ** If N is positive then that is the
126904    ** number of pages in the cache.  If N is negative, then the
126905    ** number of pages is adjusted so that the cache uses -N kibibytes
126906    ** of memory.
126907    **
126908    ** If the number of cache_spill pages is less then the number of
126909    ** cache_size pages, no spilling occurs until the page count exceeds
126910    ** the number of cache_size pages.
126911    **
126912    ** The cache_spill=BOOLEAN setting applies to all attached schemas,
126913    ** not just the schema specified.
126914    */
126915    case PragTyp_CACHE_SPILL: {
126916      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
126917      if( !zRight ){
126918        returnSingleInt(v,
126919           (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
126920              sqlite3BtreeSetSpillSize(pDb->pBt,0));
126921      }else{
126922        int size = 1;
126923        if( sqlite3GetInt32(zRight, &size) ){
126924          sqlite3BtreeSetSpillSize(pDb->pBt, size);
126925        }
126926        if( sqlite3GetBoolean(zRight, size!=0) ){
126927          db->flags |= SQLITE_CacheSpill;
126928        }else{
126929          db->flags &= ~(u64)SQLITE_CacheSpill;
126930        }
126931        setAllPagerFlags(db);
126932      }
126933      break;
126934    }
126935  
126936    /*
126937    **  PRAGMA [schema.]mmap_size(N)
126938    **
126939    ** Used to set mapping size limit. The mapping size limit is
126940    ** used to limit the aggregate size of all memory mapped regions of the
126941    ** database file. If this parameter is set to zero, then memory mapping
126942    ** is not used at all.  If N is negative, then the default memory map
126943    ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
126944    ** The parameter N is measured in bytes.
126945    **
126946    ** This value is advisory.  The underlying VFS is free to memory map
126947    ** as little or as much as it wants.  Except, if N is set to 0 then the
126948    ** upper layers will never invoke the xFetch interfaces to the VFS.
126949    */
126950    case PragTyp_MMAP_SIZE: {
126951      sqlite3_int64 sz;
126952  #if SQLITE_MAX_MMAP_SIZE>0
126953      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
126954      if( zRight ){
126955        int ii;
126956        sqlite3DecOrHexToI64(zRight, &sz);
126957        if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
126958        if( pId2->n==0 ) db->szMmap = sz;
126959        for(ii=db->nDb-1; ii>=0; ii--){
126960          if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
126961            sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
126962          }
126963        }
126964      }
126965      sz = -1;
126966      rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
126967  #else
126968      sz = 0;
126969      rc = SQLITE_OK;
126970  #endif
126971      if( rc==SQLITE_OK ){
126972        returnSingleInt(v, sz);
126973      }else if( rc!=SQLITE_NOTFOUND ){
126974        pParse->nErr++;
126975        pParse->rc = rc;
126976      }
126977      break;
126978    }
126979  
126980    /*
126981    **   PRAGMA temp_store
126982    **   PRAGMA temp_store = "default"|"memory"|"file"
126983    **
126984    ** Return or set the local value of the temp_store flag.  Changing
126985    ** the local value does not make changes to the disk file and the default
126986    ** value will be restored the next time the database is opened.
126987    **
126988    ** Note that it is possible for the library compile-time options to
126989    ** override this setting
126990    */
126991    case PragTyp_TEMP_STORE: {
126992      if( !zRight ){
126993        returnSingleInt(v, db->temp_store);
126994      }else{
126995        changeTempStorage(pParse, zRight);
126996      }
126997      break;
126998    }
126999  
127000    /*
127001    **   PRAGMA temp_store_directory
127002    **   PRAGMA temp_store_directory = ""|"directory_name"
127003    **
127004    ** Return or set the local value of the temp_store_directory flag.  Changing
127005    ** the value sets a specific directory to be used for temporary files.
127006    ** Setting to a null string reverts to the default temporary directory search.
127007    ** If temporary directory is changed, then invalidateTempStorage.
127008    **
127009    */
127010    case PragTyp_TEMP_STORE_DIRECTORY: {
127011      if( !zRight ){
127012        returnSingleText(v, sqlite3_temp_directory);
127013      }else{
127014  #ifndef SQLITE_OMIT_WSD
127015        if( zRight[0] ){
127016          int res;
127017          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
127018          if( rc!=SQLITE_OK || res==0 ){
127019            sqlite3ErrorMsg(pParse, "not a writable directory");
127020            goto pragma_out;
127021          }
127022        }
127023        if( SQLITE_TEMP_STORE==0
127024         || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
127025         || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
127026        ){
127027          invalidateTempStorage(pParse);
127028        }
127029        sqlite3_free(sqlite3_temp_directory);
127030        if( zRight[0] ){
127031          sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
127032        }else{
127033          sqlite3_temp_directory = 0;
127034        }
127035  #endif /* SQLITE_OMIT_WSD */
127036      }
127037      break;
127038    }
127039  
127040  #if SQLITE_OS_WIN
127041    /*
127042    **   PRAGMA data_store_directory
127043    **   PRAGMA data_store_directory = ""|"directory_name"
127044    **
127045    ** Return or set the local value of the data_store_directory flag.  Changing
127046    ** the value sets a specific directory to be used for database files that
127047    ** were specified with a relative pathname.  Setting to a null string reverts
127048    ** to the default database directory, which for database files specified with
127049    ** a relative path will probably be based on the current directory for the
127050    ** process.  Database file specified with an absolute path are not impacted
127051    ** by this setting, regardless of its value.
127052    **
127053    */
127054    case PragTyp_DATA_STORE_DIRECTORY: {
127055      if( !zRight ){
127056        returnSingleText(v, sqlite3_data_directory);
127057      }else{
127058  #ifndef SQLITE_OMIT_WSD
127059        if( zRight[0] ){
127060          int res;
127061          rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
127062          if( rc!=SQLITE_OK || res==0 ){
127063            sqlite3ErrorMsg(pParse, "not a writable directory");
127064            goto pragma_out;
127065          }
127066        }
127067        sqlite3_free(sqlite3_data_directory);
127068        if( zRight[0] ){
127069          sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
127070        }else{
127071          sqlite3_data_directory = 0;
127072        }
127073  #endif /* SQLITE_OMIT_WSD */
127074      }
127075      break;
127076    }
127077  #endif
127078  
127079  #if SQLITE_ENABLE_LOCKING_STYLE
127080    /*
127081    **   PRAGMA [schema.]lock_proxy_file
127082    **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
127083    **
127084    ** Return or set the value of the lock_proxy_file flag.  Changing
127085    ** the value sets a specific file to be used for database access locks.
127086    **
127087    */
127088    case PragTyp_LOCK_PROXY_FILE: {
127089      if( !zRight ){
127090        Pager *pPager = sqlite3BtreePager(pDb->pBt);
127091        char *proxy_file_path = NULL;
127092        sqlite3_file *pFile = sqlite3PagerFile(pPager);
127093        sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
127094                             &proxy_file_path);
127095        returnSingleText(v, proxy_file_path);
127096      }else{
127097        Pager *pPager = sqlite3BtreePager(pDb->pBt);
127098        sqlite3_file *pFile = sqlite3PagerFile(pPager);
127099        int res;
127100        if( zRight[0] ){
127101          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
127102                                       zRight);
127103        } else {
127104          res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
127105                                       NULL);
127106        }
127107        if( res!=SQLITE_OK ){
127108          sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
127109          goto pragma_out;
127110        }
127111      }
127112      break;
127113    }
127114  #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
127115      
127116    /*
127117    **   PRAGMA [schema.]synchronous
127118    **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
127119    **
127120    ** Return or set the local value of the synchronous flag.  Changing
127121    ** the local value does not make changes to the disk file and the
127122    ** default value will be restored the next time the database is
127123    ** opened.
127124    */
127125    case PragTyp_SYNCHRONOUS: {
127126      if( !zRight ){
127127        returnSingleInt(v, pDb->safety_level-1);
127128      }else{
127129        if( !db->autoCommit ){
127130          sqlite3ErrorMsg(pParse, 
127131              "Safety level may not be changed inside a transaction");
127132        }else if( iDb!=1 ){
127133          int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
127134          if( iLevel==0 ) iLevel = 1;
127135          pDb->safety_level = iLevel;
127136          pDb->bSyncSet = 1;
127137          setAllPagerFlags(db);
127138        }
127139      }
127140      break;
127141    }
127142  #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
127143  
127144  #ifndef SQLITE_OMIT_FLAG_PRAGMAS
127145    case PragTyp_FLAG: {
127146      if( zRight==0 ){
127147        setPragmaResultColumnNames(v, pPragma);
127148        returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
127149      }else{
127150        u64 mask = pPragma->iArg;    /* Mask of bits to set or clear. */
127151        if( db->autoCommit==0 ){
127152          /* Foreign key support may not be enabled or disabled while not
127153          ** in auto-commit mode.  */
127154          mask &= ~(SQLITE_ForeignKeys);
127155        }
127156  #if SQLITE_USER_AUTHENTICATION
127157        if( db->auth.authLevel==UAUTH_User ){
127158          /* Do not allow non-admin users to modify the schema arbitrarily */
127159          mask &= ~(SQLITE_WriteSchema);
127160        }
127161  #endif
127162  
127163        if( sqlite3GetBoolean(zRight, 0) ){
127164          db->flags |= mask;
127165        }else{
127166          db->flags &= ~mask;
127167          if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
127168        }
127169  
127170        /* Many of the flag-pragmas modify the code generated by the SQL 
127171        ** compiler (eg. count_changes). So add an opcode to expire all
127172        ** compiled SQL statements after modifying a pragma value.
127173        */
127174        sqlite3VdbeAddOp0(v, OP_Expire);
127175        setAllPagerFlags(db);
127176      }
127177      break;
127178    }
127179  #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
127180  
127181  #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
127182    /*
127183    **   PRAGMA table_info(<table>)
127184    **
127185    ** Return a single row for each column of the named table. The columns of
127186    ** the returned data set are:
127187    **
127188    ** cid:        Column id (numbered from left to right, starting at 0)
127189    ** name:       Column name
127190    ** type:       Column declaration type.
127191    ** notnull:    True if 'NOT NULL' is part of column declaration
127192    ** dflt_value: The default value for the column, if any.
127193    ** pk:         Non-zero for PK fields.
127194    */
127195    case PragTyp_TABLE_INFO: if( zRight ){
127196      Table *pTab;
127197      pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
127198      if( pTab ){
127199        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127200        int i, k;
127201        int nHidden = 0;
127202        Column *pCol;
127203        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
127204        pParse->nMem = 7;
127205        sqlite3CodeVerifySchema(pParse, iTabDb);
127206        sqlite3ViewGetColumnNames(pParse, pTab);
127207        for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
127208          int isHidden = IsHiddenColumn(pCol);
127209          if( isHidden && pPragma->iArg==0 ){
127210            nHidden++;
127211            continue;
127212          }
127213          if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
127214            k = 0;
127215          }else if( pPk==0 ){
127216            k = 1;
127217          }else{
127218            for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
127219          }
127220          assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
127221          sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
127222                 i-nHidden,
127223                 pCol->zName,
127224                 sqlite3ColumnType(pCol,""),
127225                 pCol->notNull ? 1 : 0,
127226                 pCol->pDflt ? pCol->pDflt->u.zToken : 0,
127227                 k,
127228                 isHidden);
127229        }
127230      }
127231    }
127232    break;
127233  
127234  #ifdef SQLITE_DEBUG
127235    case PragTyp_STATS: {
127236      Index *pIdx;
127237      HashElem *i;
127238      pParse->nMem = 5;
127239      sqlite3CodeVerifySchema(pParse, iDb);
127240      for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
127241        Table *pTab = sqliteHashData(i);
127242        sqlite3VdbeMultiLoad(v, 1, "ssiii",
127243             pTab->zName,
127244             0,
127245             pTab->szTabRow,
127246             pTab->nRowLogEst,
127247             pTab->tabFlags);
127248        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127249          sqlite3VdbeMultiLoad(v, 2, "siiiX",
127250             pIdx->zName,
127251             pIdx->szIdxRow,
127252             pIdx->aiRowLogEst[0],
127253             pIdx->hasStat1);
127254          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
127255        }
127256      }
127257    }
127258    break;
127259  #endif
127260  
127261    case PragTyp_INDEX_INFO: if( zRight ){
127262      Index *pIdx;
127263      Table *pTab;
127264      pIdx = sqlite3FindIndex(db, zRight, zDb);
127265      if( pIdx ){
127266        int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
127267        int i;
127268        int mx;
127269        if( pPragma->iArg ){
127270          /* PRAGMA index_xinfo (newer version with more rows and columns) */
127271          mx = pIdx->nColumn;
127272          pParse->nMem = 6;
127273        }else{
127274          /* PRAGMA index_info (legacy version) */
127275          mx = pIdx->nKeyCol;
127276          pParse->nMem = 3;
127277        }
127278        pTab = pIdx->pTable;
127279        sqlite3CodeVerifySchema(pParse, iIdxDb);
127280        assert( pParse->nMem<=pPragma->nPragCName );
127281        for(i=0; i<mx; i++){
127282          i16 cnum = pIdx->aiColumn[i];
127283          sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
127284                               cnum<0 ? 0 : pTab->aCol[cnum].zName);
127285          if( pPragma->iArg ){
127286            sqlite3VdbeMultiLoad(v, 4, "isiX",
127287              pIdx->aSortOrder[i],
127288              pIdx->azColl[i],
127289              i<pIdx->nKeyCol);
127290          }
127291          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
127292        }
127293      }
127294    }
127295    break;
127296  
127297    case PragTyp_INDEX_LIST: if( zRight ){
127298      Index *pIdx;
127299      Table *pTab;
127300      int i;
127301      pTab = sqlite3FindTable(db, zRight, zDb);
127302      if( pTab ){
127303        int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127304        pParse->nMem = 5;
127305        sqlite3CodeVerifySchema(pParse, iTabDb);
127306        for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
127307          const char *azOrigin[] = { "c", "u", "pk" };
127308          sqlite3VdbeMultiLoad(v, 1, "isisi",
127309             i,
127310             pIdx->zName,
127311             IsUniqueIndex(pIdx),
127312             azOrigin[pIdx->idxType],
127313             pIdx->pPartIdxWhere!=0);
127314        }
127315      }
127316    }
127317    break;
127318  
127319    case PragTyp_DATABASE_LIST: {
127320      int i;
127321      pParse->nMem = 3;
127322      for(i=0; i<db->nDb; i++){
127323        if( db->aDb[i].pBt==0 ) continue;
127324        assert( db->aDb[i].zDbSName!=0 );
127325        sqlite3VdbeMultiLoad(v, 1, "iss",
127326           i,
127327           db->aDb[i].zDbSName,
127328           sqlite3BtreeGetFilename(db->aDb[i].pBt));
127329      }
127330    }
127331    break;
127332  
127333    case PragTyp_COLLATION_LIST: {
127334      int i = 0;
127335      HashElem *p;
127336      pParse->nMem = 2;
127337      for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
127338        CollSeq *pColl = (CollSeq *)sqliteHashData(p);
127339        sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
127340      }
127341    }
127342    break;
127343  
127344  #ifdef SQLITE_INTROSPECTION_PRAGMAS
127345    case PragTyp_FUNCTION_LIST: {
127346      int i;
127347      HashElem *j;
127348      FuncDef *p;
127349      pParse->nMem = 2;
127350      for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
127351        for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
127352          if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
127353          sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
127354        }
127355      }
127356      for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
127357        p = (FuncDef*)sqliteHashData(j);
127358        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
127359      }
127360    }
127361    break;
127362  
127363  #ifndef SQLITE_OMIT_VIRTUALTABLE
127364    case PragTyp_MODULE_LIST: {
127365      HashElem *j;
127366      pParse->nMem = 1;
127367      for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
127368        Module *pMod = (Module*)sqliteHashData(j);
127369        sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
127370      }
127371    }
127372    break;
127373  #endif /* SQLITE_OMIT_VIRTUALTABLE */
127374  
127375    case PragTyp_PRAGMA_LIST: {
127376      int i;
127377      for(i=0; i<ArraySize(aPragmaName); i++){
127378        sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
127379      }
127380    }
127381    break;
127382  #endif /* SQLITE_INTROSPECTION_PRAGMAS */
127383  
127384  #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
127385  
127386  #ifndef SQLITE_OMIT_FOREIGN_KEY
127387    case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
127388      FKey *pFK;
127389      Table *pTab;
127390      pTab = sqlite3FindTable(db, zRight, zDb);
127391      if( pTab ){
127392        pFK = pTab->pFKey;
127393        if( pFK ){
127394          int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127395          int i = 0; 
127396          pParse->nMem = 8;
127397          sqlite3CodeVerifySchema(pParse, iTabDb);
127398          while(pFK){
127399            int j;
127400            for(j=0; j<pFK->nCol; j++){
127401              sqlite3VdbeMultiLoad(v, 1, "iissssss",
127402                     i,
127403                     j,
127404                     pFK->zTo,
127405                     pTab->aCol[pFK->aCol[j].iFrom].zName,
127406                     pFK->aCol[j].zCol,
127407                     actionName(pFK->aAction[1]),  /* ON UPDATE */
127408                     actionName(pFK->aAction[0]),  /* ON DELETE */
127409                     "NONE");
127410            }
127411            ++i;
127412            pFK = pFK->pNextFrom;
127413          }
127414        }
127415      }
127416    }
127417    break;
127418  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
127419  
127420  #ifndef SQLITE_OMIT_FOREIGN_KEY
127421  #ifndef SQLITE_OMIT_TRIGGER
127422    case PragTyp_FOREIGN_KEY_CHECK: {
127423      FKey *pFK;             /* A foreign key constraint */
127424      Table *pTab;           /* Child table contain "REFERENCES" keyword */
127425      Table *pParent;        /* Parent table that child points to */
127426      Index *pIdx;           /* Index in the parent table */
127427      int i;                 /* Loop counter:  Foreign key number for pTab */
127428      int j;                 /* Loop counter:  Field of the foreign key */
127429      HashElem *k;           /* Loop counter:  Next table in schema */
127430      int x;                 /* result variable */
127431      int regResult;         /* 3 registers to hold a result row */
127432      int regKey;            /* Register to hold key for checking the FK */
127433      int regRow;            /* Registers to hold a row from pTab */
127434      int addrTop;           /* Top of a loop checking foreign keys */
127435      int addrOk;            /* Jump here if the key is OK */
127436      int *aiCols;           /* child to parent column mapping */
127437  
127438      regResult = pParse->nMem+1;
127439      pParse->nMem += 4;
127440      regKey = ++pParse->nMem;
127441      regRow = ++pParse->nMem;
127442      k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
127443      while( k ){
127444        int iTabDb;
127445        if( zRight ){
127446          pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
127447          k = 0;
127448        }else{
127449          pTab = (Table*)sqliteHashData(k);
127450          k = sqliteHashNext(k);
127451        }
127452        if( pTab==0 || pTab->pFKey==0 ) continue;
127453        iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127454        sqlite3CodeVerifySchema(pParse, iTabDb);
127455        sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
127456        if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
127457        sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
127458        sqlite3VdbeLoadString(v, regResult, pTab->zName);
127459        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
127460          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
127461          if( pParent==0 ) continue;
127462          pIdx = 0;
127463          sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
127464          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
127465          if( x==0 ){
127466            if( pIdx==0 ){
127467              sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
127468            }else{
127469              sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
127470              sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
127471            }
127472          }else{
127473            k = 0;
127474            break;
127475          }
127476        }
127477        assert( pParse->nErr>0 || pFK==0 );
127478        if( pFK ) break;
127479        if( pParse->nTab<i ) pParse->nTab = i;
127480        addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
127481        for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
127482          pParent = sqlite3FindTable(db, pFK->zTo, zDb);
127483          pIdx = 0;
127484          aiCols = 0;
127485          if( pParent ){
127486            x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
127487            assert( x==0 );
127488          }
127489          addrOk = sqlite3VdbeMakeLabel(pParse);
127490  
127491          /* Generate code to read the child key values into registers
127492          ** regRow..regRow+n. If any of the child key values are NULL, this 
127493          ** row cannot cause an FK violation. Jump directly to addrOk in 
127494          ** this case. */
127495          for(j=0; j<pFK->nCol; j++){
127496            int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
127497            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
127498            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
127499          }
127500  
127501          /* Generate code to query the parent index for a matching parent
127502          ** key. If a match is found, jump to addrOk. */
127503          if( pIdx ){
127504            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
127505                sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
127506            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
127507            VdbeCoverage(v);
127508          }else if( pParent ){
127509            int jmp = sqlite3VdbeCurrentAddr(v)+2;
127510            sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
127511            sqlite3VdbeGoto(v, addrOk);
127512            assert( pFK->nCol==1 );
127513          }
127514  
127515          /* Generate code to report an FK violation to the caller. */
127516          if( HasRowid(pTab) ){
127517            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
127518          }else{
127519            sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
127520          }
127521          sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
127522          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
127523          sqlite3VdbeResolveLabel(v, addrOk);
127524          sqlite3DbFree(db, aiCols);
127525        }
127526        sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
127527        sqlite3VdbeJumpHere(v, addrTop);
127528      }
127529    }
127530    break;
127531  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
127532  #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
127533  
127534    /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
127535    ** used will be case sensitive or not depending on the RHS.
127536    */
127537    case PragTyp_CASE_SENSITIVE_LIKE: {
127538      if( zRight ){
127539        sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
127540      }
127541    }
127542    break;
127543  
127544  #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
127545  # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
127546  #endif
127547  
127548  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
127549    /*    PRAGMA integrity_check
127550    **    PRAGMA integrity_check(N)
127551    **    PRAGMA quick_check
127552    **    PRAGMA quick_check(N)
127553    **
127554    ** Verify the integrity of the database.
127555    **
127556    ** The "quick_check" is reduced version of 
127557    ** integrity_check designed to detect most database corruption
127558    ** without the overhead of cross-checking indexes.  Quick_check
127559    ** is linear time wherease integrity_check is O(NlogN).
127560    */
127561    case PragTyp_INTEGRITY_CHECK: {
127562      int i, j, addr, mxErr;
127563  
127564      int isQuick = (sqlite3Tolower(zLeft[0])=='q');
127565  
127566      /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
127567      ** then iDb is set to the index of the database identified by <db>.
127568      ** In this case, the integrity of database iDb only is verified by
127569      ** the VDBE created below.
127570      **
127571      ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
127572      ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
127573      ** to -1 here, to indicate that the VDBE should verify the integrity
127574      ** of all attached databases.  */
127575      assert( iDb>=0 );
127576      assert( iDb==0 || pId2->z );
127577      if( pId2->z==0 ) iDb = -1;
127578  
127579      /* Initialize the VDBE program */
127580      pParse->nMem = 6;
127581  
127582      /* Set the maximum error count */
127583      mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
127584      if( zRight ){
127585        sqlite3GetInt32(zRight, &mxErr);
127586        if( mxErr<=0 ){
127587          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
127588        }
127589      }
127590      sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
127591  
127592      /* Do an integrity check on each database file */
127593      for(i=0; i<db->nDb; i++){
127594        HashElem *x;     /* For looping over tables in the schema */
127595        Hash *pTbls;     /* Set of all tables in the schema */
127596        int *aRoot;      /* Array of root page numbers of all btrees */
127597        int cnt = 0;     /* Number of entries in aRoot[] */
127598        int mxIdx = 0;   /* Maximum number of indexes for any table */
127599  
127600        if( OMIT_TEMPDB && i==1 ) continue;
127601        if( iDb>=0 && i!=iDb ) continue;
127602  
127603        sqlite3CodeVerifySchema(pParse, i);
127604  
127605        /* Do an integrity check of the B-Tree
127606        **
127607        ** Begin by finding the root pages numbers
127608        ** for all tables and indices in the database.
127609        */
127610        assert( sqlite3SchemaMutexHeld(db, i, 0) );
127611        pTbls = &db->aDb[i].pSchema->tblHash;
127612        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
127613          Table *pTab = sqliteHashData(x);  /* Current table */
127614          Index *pIdx;                      /* An index on pTab */
127615          int nIdx;                         /* Number of indexes on pTab */
127616          if( HasRowid(pTab) ) cnt++;
127617          for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
127618          if( nIdx>mxIdx ) mxIdx = nIdx;
127619        }
127620        aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
127621        if( aRoot==0 ) break;
127622        for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
127623          Table *pTab = sqliteHashData(x);
127624          Index *pIdx;
127625          if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
127626          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127627            aRoot[++cnt] = pIdx->tnum;
127628          }
127629        }
127630        aRoot[0] = cnt;
127631  
127632        /* Make sure sufficient number of registers have been allocated */
127633        pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
127634        sqlite3ClearTempRegCache(pParse);
127635  
127636        /* Do the b-tree integrity checks */
127637        sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
127638        sqlite3VdbeChangeP5(v, (u8)i);
127639        addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
127640        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
127641           sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
127642           P4_DYNAMIC);
127643        sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
127644        integrityCheckResultRow(v);
127645        sqlite3VdbeJumpHere(v, addr);
127646  
127647        /* Make sure all the indices are constructed correctly.
127648        */
127649        for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
127650          Table *pTab = sqliteHashData(x);
127651          Index *pIdx, *pPk;
127652          Index *pPrior = 0;
127653          int loopTop;
127654          int iDataCur, iIdxCur;
127655          int r1 = -1;
127656  
127657          if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
127658          pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
127659          sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
127660                                     1, 0, &iDataCur, &iIdxCur);
127661          /* reg[7] counts the number of entries in the table.
127662          ** reg[8+i] counts the number of entries in the i-th index 
127663          */
127664          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
127665          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
127666            sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
127667          }
127668          assert( pParse->nMem>=8+j );
127669          assert( sqlite3NoTempsInRange(pParse,1,7+j) );
127670          sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
127671          loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
127672          if( !isQuick ){
127673            /* Sanity check on record header decoding */
127674            sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
127675            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
127676          }
127677          /* Verify that all NOT NULL columns really are NOT NULL */
127678          for(j=0; j<pTab->nCol; j++){
127679            char *zErr;
127680            int jmp2;
127681            if( j==pTab->iPKey ) continue;
127682            if( pTab->aCol[j].notNull==0 ) continue;
127683            sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
127684            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
127685            jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
127686            zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
127687                                pTab->aCol[j].zName);
127688            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
127689            integrityCheckResultRow(v);
127690            sqlite3VdbeJumpHere(v, jmp2);
127691          }
127692          /* Verify CHECK constraints */
127693          if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
127694            ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
127695            if( db->mallocFailed==0 ){
127696              int addrCkFault = sqlite3VdbeMakeLabel(pParse);
127697              int addrCkOk = sqlite3VdbeMakeLabel(pParse);
127698              char *zErr;
127699              int k;
127700              pParse->iSelfTab = iDataCur + 1;
127701              for(k=pCheck->nExpr-1; k>0; k--){
127702                sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
127703              }
127704              sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 
127705                  SQLITE_JUMPIFNULL);
127706              sqlite3VdbeResolveLabel(v, addrCkFault);
127707              pParse->iSelfTab = 0;
127708              zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
127709                  pTab->zName);
127710              sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
127711              integrityCheckResultRow(v);
127712              sqlite3VdbeResolveLabel(v, addrCkOk);
127713            }
127714            sqlite3ExprListDelete(db, pCheck);
127715          }
127716          if( !isQuick ){ /* Omit the remaining tests for quick_check */
127717            /* Validate index entries for the current row */
127718            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
127719              int jmp2, jmp3, jmp4, jmp5;
127720              int ckUniq = sqlite3VdbeMakeLabel(pParse);
127721              if( pPk==pIdx ) continue;
127722              r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
127723                                           pPrior, r1);
127724              pPrior = pIdx;
127725              sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
127726              /* Verify that an index entry exists for the current table row */
127727              jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
127728                                          pIdx->nColumn); VdbeCoverage(v);
127729              sqlite3VdbeLoadString(v, 3, "row ");
127730              sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
127731              sqlite3VdbeLoadString(v, 4, " missing from index ");
127732              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
127733              jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
127734              sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
127735              jmp4 = integrityCheckResultRow(v);
127736              sqlite3VdbeJumpHere(v, jmp2);
127737              /* For UNIQUE indexes, verify that only one entry exists with the
127738              ** current key.  The entry is unique if (1) any column is NULL
127739              ** or (2) the next entry has a different key */
127740              if( IsUniqueIndex(pIdx) ){
127741                int uniqOk = sqlite3VdbeMakeLabel(pParse);
127742                int jmp6;
127743                int kk;
127744                for(kk=0; kk<pIdx->nKeyCol; kk++){
127745                  int iCol = pIdx->aiColumn[kk];
127746                  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
127747                  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
127748                  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
127749                  VdbeCoverage(v);
127750                }
127751                jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
127752                sqlite3VdbeGoto(v, uniqOk);
127753                sqlite3VdbeJumpHere(v, jmp6);
127754                sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
127755                                     pIdx->nKeyCol); VdbeCoverage(v);
127756                sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
127757                sqlite3VdbeGoto(v, jmp5);
127758                sqlite3VdbeResolveLabel(v, uniqOk);
127759              }
127760              sqlite3VdbeJumpHere(v, jmp4);
127761              sqlite3ResolvePartIdxLabel(pParse, jmp3);
127762            }
127763          }
127764          sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
127765          sqlite3VdbeJumpHere(v, loopTop-1);
127766  #ifndef SQLITE_OMIT_BTREECOUNT
127767          if( !isQuick ){
127768            sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
127769            for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
127770              if( pPk==pIdx ) continue;
127771              sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
127772              addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
127773              sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
127774              sqlite3VdbeLoadString(v, 4, pIdx->zName);
127775              sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
127776              integrityCheckResultRow(v);
127777              sqlite3VdbeJumpHere(v, addr);
127778            }
127779          }
127780  #endif /* SQLITE_OMIT_BTREECOUNT */
127781        } 
127782      }
127783      {
127784        static const int iLn = VDBE_OFFSET_LINENO(2);
127785        static const VdbeOpList endCode[] = {
127786          { OP_AddImm,      1, 0,        0},    /* 0 */
127787          { OP_IfNotZero,   1, 4,        0},    /* 1 */
127788          { OP_String8,     0, 3,        0},    /* 2 */
127789          { OP_ResultRow,   3, 1,        0},    /* 3 */
127790          { OP_Halt,        0, 0,        0},    /* 4 */
127791          { OP_String8,     0, 3,        0},    /* 5 */
127792          { OP_Goto,        0, 3,        0},    /* 6 */
127793        };
127794        VdbeOp *aOp;
127795  
127796        aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
127797        if( aOp ){
127798          aOp[0].p2 = 1-mxErr;
127799          aOp[2].p4type = P4_STATIC;
127800          aOp[2].p4.z = "ok";
127801          aOp[5].p4type = P4_STATIC;
127802          aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
127803        }
127804        sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
127805      }
127806    }
127807    break;
127808  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
127809  
127810  #ifndef SQLITE_OMIT_UTF16
127811    /*
127812    **   PRAGMA encoding
127813    **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
127814    **
127815    ** In its first form, this pragma returns the encoding of the main
127816    ** database. If the database is not initialized, it is initialized now.
127817    **
127818    ** The second form of this pragma is a no-op if the main database file
127819    ** has not already been initialized. In this case it sets the default
127820    ** encoding that will be used for the main database file if a new file
127821    ** is created. If an existing main database file is opened, then the
127822    ** default text encoding for the existing database is used.
127823    ** 
127824    ** In all cases new databases created using the ATTACH command are
127825    ** created to use the same default text encoding as the main database. If
127826    ** the main database has not been initialized and/or created when ATTACH
127827    ** is executed, this is done before the ATTACH operation.
127828    **
127829    ** In the second form this pragma sets the text encoding to be used in
127830    ** new database files created using this database handle. It is only
127831    ** useful if invoked immediately after the main database i
127832    */
127833    case PragTyp_ENCODING: {
127834      static const struct EncName {
127835        char *zName;
127836        u8 enc;
127837      } encnames[] = {
127838        { "UTF8",     SQLITE_UTF8        },
127839        { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
127840        { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
127841        { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
127842        { "UTF16le",  SQLITE_UTF16LE     },
127843        { "UTF16be",  SQLITE_UTF16BE     },
127844        { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
127845        { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
127846        { 0, 0 }
127847      };
127848      const struct EncName *pEnc;
127849      if( !zRight ){    /* "PRAGMA encoding" */
127850        if( sqlite3ReadSchema(pParse) ) goto pragma_out;
127851        assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
127852        assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
127853        assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
127854        returnSingleText(v, encnames[ENC(pParse->db)].zName);
127855      }else{                        /* "PRAGMA encoding = XXX" */
127856        /* Only change the value of sqlite.enc if the database handle is not
127857        ** initialized. If the main database exists, the new sqlite.enc value
127858        ** will be overwritten when the schema is next loaded. If it does not
127859        ** already exists, it will be created to use the new encoding value.
127860        */
127861        if( 
127862          !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
127863          DbHasProperty(db, 0, DB_Empty) 
127864        ){
127865          for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
127866            if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
127867              SCHEMA_ENC(db) = ENC(db) =
127868                  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
127869              break;
127870            }
127871          }
127872          if( !pEnc->zName ){
127873            sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
127874          }
127875        }
127876      }
127877    }
127878    break;
127879  #endif /* SQLITE_OMIT_UTF16 */
127880  
127881  #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
127882    /*
127883    **   PRAGMA [schema.]schema_version
127884    **   PRAGMA [schema.]schema_version = <integer>
127885    **
127886    **   PRAGMA [schema.]user_version
127887    **   PRAGMA [schema.]user_version = <integer>
127888    **
127889    **   PRAGMA [schema.]freelist_count
127890    **
127891    **   PRAGMA [schema.]data_version
127892    **
127893    **   PRAGMA [schema.]application_id
127894    **   PRAGMA [schema.]application_id = <integer>
127895    **
127896    ** The pragma's schema_version and user_version are used to set or get
127897    ** the value of the schema-version and user-version, respectively. Both
127898    ** the schema-version and the user-version are 32-bit signed integers
127899    ** stored in the database header.
127900    **
127901    ** The schema-cookie is usually only manipulated internally by SQLite. It
127902    ** is incremented by SQLite whenever the database schema is modified (by
127903    ** creating or dropping a table or index). The schema version is used by
127904    ** SQLite each time a query is executed to ensure that the internal cache
127905    ** of the schema used when compiling the SQL query matches the schema of
127906    ** the database against which the compiled query is actually executed.
127907    ** Subverting this mechanism by using "PRAGMA schema_version" to modify
127908    ** the schema-version is potentially dangerous and may lead to program
127909    ** crashes or database corruption. Use with caution!
127910    **
127911    ** The user-version is not used internally by SQLite. It may be used by
127912    ** applications for any purpose.
127913    */
127914    case PragTyp_HEADER_VALUE: {
127915      int iCookie = pPragma->iArg;  /* Which cookie to read or write */
127916      sqlite3VdbeUsesBtree(v, iDb);
127917      if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
127918        /* Write the specified cookie value */
127919        static const VdbeOpList setCookie[] = {
127920          { OP_Transaction,    0,  1,  0},    /* 0 */
127921          { OP_SetCookie,      0,  0,  0},    /* 1 */
127922        };
127923        VdbeOp *aOp;
127924        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
127925        aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
127926        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
127927        aOp[0].p1 = iDb;
127928        aOp[1].p1 = iDb;
127929        aOp[1].p2 = iCookie;
127930        aOp[1].p3 = sqlite3Atoi(zRight);
127931      }else{
127932        /* Read the specified cookie value */
127933        static const VdbeOpList readCookie[] = {
127934          { OP_Transaction,     0,  0,  0},    /* 0 */
127935          { OP_ReadCookie,      0,  1,  0},    /* 1 */
127936          { OP_ResultRow,       1,  1,  0}
127937        };
127938        VdbeOp *aOp;
127939        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
127940        aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
127941        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
127942        aOp[0].p1 = iDb;
127943        aOp[1].p1 = iDb;
127944        aOp[1].p3 = iCookie;
127945        sqlite3VdbeReusable(v);
127946      }
127947    }
127948    break;
127949  #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
127950  
127951  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
127952    /*
127953    **   PRAGMA compile_options
127954    **
127955    ** Return the names of all compile-time options used in this build,
127956    ** one option per row.
127957    */
127958    case PragTyp_COMPILE_OPTIONS: {
127959      int i = 0;
127960      const char *zOpt;
127961      pParse->nMem = 1;
127962      while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
127963        sqlite3VdbeLoadString(v, 1, zOpt);
127964        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
127965      }
127966      sqlite3VdbeReusable(v);
127967    }
127968    break;
127969  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
127970  
127971  #ifndef SQLITE_OMIT_WAL
127972    /*
127973    **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
127974    **
127975    ** Checkpoint the database.
127976    */
127977    case PragTyp_WAL_CHECKPOINT: {
127978      int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
127979      int eMode = SQLITE_CHECKPOINT_PASSIVE;
127980      if( zRight ){
127981        if( sqlite3StrICmp(zRight, "full")==0 ){
127982          eMode = SQLITE_CHECKPOINT_FULL;
127983        }else if( sqlite3StrICmp(zRight, "restart")==0 ){
127984          eMode = SQLITE_CHECKPOINT_RESTART;
127985        }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
127986          eMode = SQLITE_CHECKPOINT_TRUNCATE;
127987        }
127988      }
127989      pParse->nMem = 3;
127990      sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
127991      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
127992    }
127993    break;
127994  
127995    /*
127996    **   PRAGMA wal_autocheckpoint
127997    **   PRAGMA wal_autocheckpoint = N
127998    **
127999    ** Configure a database connection to automatically checkpoint a database
128000    ** after accumulating N frames in the log. Or query for the current value
128001    ** of N.
128002    */
128003    case PragTyp_WAL_AUTOCHECKPOINT: {
128004      if( zRight ){
128005        sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
128006      }
128007      returnSingleInt(v, 
128008         db->xWalCallback==sqlite3WalDefaultHook ? 
128009             SQLITE_PTR_TO_INT(db->pWalArg) : 0);
128010    }
128011    break;
128012  #endif
128013  
128014    /*
128015    **  PRAGMA shrink_memory
128016    **
128017    ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
128018    ** connection on which it is invoked to free up as much memory as it
128019    ** can, by calling sqlite3_db_release_memory().
128020    */
128021    case PragTyp_SHRINK_MEMORY: {
128022      sqlite3_db_release_memory(db);
128023      break;
128024    }
128025  
128026    /*
128027    **  PRAGMA optimize
128028    **  PRAGMA optimize(MASK)
128029    **  PRAGMA schema.optimize
128030    **  PRAGMA schema.optimize(MASK)
128031    **
128032    ** Attempt to optimize the database.  All schemas are optimized in the first
128033    ** two forms, and only the specified schema is optimized in the latter two.
128034    **
128035    ** The details of optimizations performed by this pragma are expected
128036    ** to change and improve over time.  Applications should anticipate that
128037    ** this pragma will perform new optimizations in future releases.
128038    **
128039    ** The optional argument is a bitmask of optimizations to perform:
128040    **
128041    **    0x0001    Debugging mode.  Do not actually perform any optimizations
128042    **              but instead return one line of text for each optimization
128043    **              that would have been done.  Off by default.
128044    **
128045    **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
128046    **              See below for additional information.
128047    **
128048    **    0x0004    (Not yet implemented) Record usage and performance 
128049    **              information from the current session in the
128050    **              database file so that it will be available to "optimize"
128051    **              pragmas run by future database connections.
128052    **
128053    **    0x0008    (Not yet implemented) Create indexes that might have
128054    **              been helpful to recent queries
128055    **
128056    ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
128057    ** of the optimizations listed above except Debug Mode, including new
128058    ** optimizations that have not yet been invented.  If new optimizations are
128059    ** ever added that should be off by default, those off-by-default 
128060    ** optimizations will have bitmasks of 0x10000 or larger.
128061    **
128062    ** DETERMINATION OF WHEN TO RUN ANALYZE
128063    **
128064    ** In the current implementation, a table is analyzed if only if all of
128065    ** the following are true:
128066    **
128067    ** (1) MASK bit 0x02 is set.
128068    **
128069    ** (2) The query planner used sqlite_stat1-style statistics for one or
128070    **     more indexes of the table at some point during the lifetime of
128071    **     the current connection.
128072    **
128073    ** (3) One or more indexes of the table are currently unanalyzed OR
128074    **     the number of rows in the table has increased by 25 times or more
128075    **     since the last time ANALYZE was run.
128076    **
128077    ** The rules for when tables are analyzed are likely to change in
128078    ** future releases.
128079    */
128080    case PragTyp_OPTIMIZE: {
128081      int iDbLast;           /* Loop termination point for the schema loop */
128082      int iTabCur;           /* Cursor for a table whose size needs checking */
128083      HashElem *k;           /* Loop over tables of a schema */
128084      Schema *pSchema;       /* The current schema */
128085      Table *pTab;           /* A table in the schema */
128086      Index *pIdx;           /* An index of the table */
128087      LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
128088      char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
128089      u32 opMask;            /* Mask of operations to perform */
128090  
128091      if( zRight ){
128092        opMask = (u32)sqlite3Atoi(zRight);
128093        if( (opMask & 0x02)==0 ) break;
128094      }else{
128095        opMask = 0xfffe;
128096      }
128097      iTabCur = pParse->nTab++;
128098      for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
128099        if( iDb==1 ) continue;
128100        sqlite3CodeVerifySchema(pParse, iDb);
128101        pSchema = db->aDb[iDb].pSchema;
128102        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
128103          pTab = (Table*)sqliteHashData(k);
128104  
128105          /* If table pTab has not been used in a way that would benefit from
128106          ** having analysis statistics during the current session, then skip it.
128107          ** This also has the effect of skipping virtual tables and views */
128108          if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
128109  
128110          /* Reanalyze if the table is 25 times larger than the last analysis */
128111          szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
128112          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
128113            if( !pIdx->hasStat1 ){
128114              szThreshold = 0; /* Always analyze if any index lacks statistics */
128115              break;
128116            }
128117          }
128118          if( szThreshold ){
128119            sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
128120            sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 
128121                           sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
128122            VdbeCoverage(v);
128123          }
128124          zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
128125                                   db->aDb[iDb].zDbSName, pTab->zName);
128126          if( opMask & 0x01 ){
128127            int r1 = sqlite3GetTempReg(pParse);
128128            sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
128129            sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
128130          }else{
128131            sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
128132          }
128133        }
128134      }
128135      sqlite3VdbeAddOp0(v, OP_Expire);
128136      break;
128137    }
128138  
128139    /*
128140    **   PRAGMA busy_timeout
128141    **   PRAGMA busy_timeout = N
128142    **
128143    ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
128144    ** if one is set.  If no busy handler or a different busy handler is set
128145    ** then 0 is returned.  Setting the busy_timeout to 0 or negative
128146    ** disables the timeout.
128147    */
128148    /*case PragTyp_BUSY_TIMEOUT*/ default: {
128149      assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
128150      if( zRight ){
128151        sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
128152      }
128153      returnSingleInt(v, db->busyTimeout);
128154      break;
128155    }
128156  
128157    /*
128158    **   PRAGMA soft_heap_limit
128159    **   PRAGMA soft_heap_limit = N
128160    **
128161    ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
128162    ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
128163    ** specified and is a non-negative integer.
128164    ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
128165    ** returns the same integer that would be returned by the
128166    ** sqlite3_soft_heap_limit64(-1) C-language function.
128167    */
128168    case PragTyp_SOFT_HEAP_LIMIT: {
128169      sqlite3_int64 N;
128170      if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
128171        sqlite3_soft_heap_limit64(N);
128172      }
128173      returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
128174      break;
128175    }
128176  
128177    /*
128178    **   PRAGMA threads
128179    **   PRAGMA threads = N
128180    **
128181    ** Configure the maximum number of worker threads.  Return the new
128182    ** maximum, which might be less than requested.
128183    */
128184    case PragTyp_THREADS: {
128185      sqlite3_int64 N;
128186      if( zRight
128187       && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
128188       && N>=0
128189      ){
128190        sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
128191      }
128192      returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
128193      break;
128194    }
128195  
128196  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
128197    /*
128198    ** Report the current state of file logs for all databases
128199    */
128200    case PragTyp_LOCK_STATUS: {
128201      static const char *const azLockName[] = {
128202        "unlocked", "shared", "reserved", "pending", "exclusive"
128203      };
128204      int i;
128205      pParse->nMem = 2;
128206      for(i=0; i<db->nDb; i++){
128207        Btree *pBt;
128208        const char *zState = "unknown";
128209        int j;
128210        if( db->aDb[i].zDbSName==0 ) continue;
128211        pBt = db->aDb[i].pBt;
128212        if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
128213          zState = "closed";
128214        }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
128215                                       SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
128216           zState = azLockName[j];
128217        }
128218        sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
128219      }
128220      break;
128221    }
128222  #endif
128223  
128224    case PragTyp_LIST_BRANCHES: {
128225      Btree *pBtree = db->aDb[iDb].pBt;
128226      Pager *pPager = getPagerFromBtree(pBtree);
128227      if( pPager && pPager->lmdb ){
128228        lmdb *lmdb = pPager->lmdb;
128229        /* if the db is being accessed by many db connections */
128230        if( !lmdb->singleConnection ){
128231          /* check if the db was modified in another db connection */
128232          if( sqlite3BranchCheckReloadDb(pPager,0)!=SQLITE_OK ){
128233            sqlite3ErrorMsg(pParse, "failed to reload branch info");
128234            goto pragma_out;
128235          }
128236        }
128237        if( lmdb->useJson ){
128238          char *result = pragma_get_branch_list(lmdb);
128239          if( result ){
128240            returnSingleText(v, result);
128241            sqlite3_free(result);
128242          }
128243        } else {
128244          int i;
128245          pParse->nMem = 1;
128246          for( i=1; i <= lmdb->num_branches; i++ ){
128247            if( lmdb->branches[i].visible ){
128248              sqlite3VdbeLoadString(v, 1, lmdb->branches[i].name);
128249              sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
128250            }
128251          }
128252        }
128253      }
128254      break;
128255    }
128256  
128257    case PragTyp_BRANCH: {
128258      if( zRight ){
128259        char *zName, *zCommit;
128260        u64 iCommit=0;
128261        rc = 0;
128262        zName = zRight;
128263        zCommit = stripchr(zName, '.');
128264        if( zCommit ){
128265          rc = sqlite3AtoU64(zCommit, &iCommit, strlen(zCommit), SQLITE_UTF8);
128266          if( rc ) rc = SQLITE_MISUSE;
128267        }
128268        if( rc==SQLITE_OK ){
128269          rc = pragma_set_current_branch(db, iDb, zName, iCommit);
128270        }
128271        if( rc ){
128272          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128273        }
128274      } else {
128275        char *result = pragma_get_current_branch(db, iDb, pParse);
128276        if( result ){
128277          returnSingleText(v, result);
128278          sqlite3_free(result);
128279        }
128280      }
128281      break;
128282    }
128283  
128284    case PragTyp_NEW_BRANCH: {
128285      if( zRight ){
128286        char *zName, *zSource, *zCommit;
128287        zName = zRight;
128288        zSource = stripstri(zName, " at ");
128289        zCommit = stripchr(zSource, '.');
128290        rc = pragma_new_branch(db, iDb, zName, zSource, zCommit);
128291        //rc = pragma_new_branch(pDb, zName, zSource, iCommit);
128292        //rc = pragma_new_branch(pDb->pBt, zName, zSource, iCommit);
128293        if( rc ){
128294          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128295        }
128296        //zErr = pragma_new_branch(db, iDb, zName, zSource, iCommit);
128297        //if( zErr ){
128298        //  sqlite3ErrorMsg(pParse, zErr);
128299        //  sqlite3_free(zErr);
128300        //}
128301      } else {
128302        sqlite3ErrorMsg(pParse, "argument required");
128303      }
128304      break;
128305    }
128306  
128307    case PragTyp_RENAME_BRANCH: {
128308      char *old_name, *new_name;
128309      old_name = zRight;
128310      new_name = stripchr(old_name, ' ');
128311      rc = pragma_rename_branch(db, iDb, old_name, new_name);
128312      //rc = pragma_rename_branch(pDb, old_name, new_name);
128313      //rc = pragma_rename_branch(pDb->pBt, old_name, new_name);
128314      if( rc ){
128315        sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128316      }
128317      //if( zErr ){
128318        //sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
128319      //  sqlite3ErrorMsg(pParse, zErr);
128320      //  sqlite3_free(zErr);
128321      //}
128322      break;
128323    }
128324  
128325    case PragTyp_BRANCH_TRUNCATE: {
128326      if( zRight ){
128327        char *zName, *zCommit;
128328        u64 iCommit=0;
128329        rc = 0;
128330        zName = zRight;
128331        zCommit = stripchr(zName, '.');
128332        if( zCommit ){
128333          rc = sqlite3AtoU64(zCommit, &iCommit, strlen(zCommit), SQLITE_UTF8);
128334          if( rc ) rc = SQLITE_MISUSE;
128335        }
128336        if( rc==SQLITE_OK ){
128337          rc = pragma_truncate_branch(db, iDb, zName, iCommit);
128338        }
128339        if( rc ){
128340          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128341        }
128342      }
128343      break;
128344    }
128345  
128346    case PragTyp_DEL_BRANCH: {  /* it is not possible to delete the current branch. the app must select another one first */
128347      if( zRight ){
128348        rc = pragma_delete_branch(db, iDb, zRight);
128349        if( rc ){
128350          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128351        }
128352  #if 0
128353        else {
128354          returnSingleText(v, "OK");
128355        }
128356  #endif
128357      }
128358      break;
128359    }
128360  
128361    case PragTyp_BRANCH_INFO: {
128362      if( zRight ){
128363        char *result = pragma_get_branch_info(db, iDb, zRight);
128364        //char *result = pragma_get_branch_info(pDb, zRight);
128365        //char *result = pragma_get_branch_info(pDb->pBt, zRight);
128366        if( result ){
128367          returnSingleText(v, result);
128368          sqlite3_free(result);
128369        }
128370      }
128371      break;
128372    }
128373  
128374    case PragTyp_BRANCH_TREE: {
128375      char *result;
128376      rc = pragma_branch_tree(db, iDb, &result);
128377      if( rc ){
128378        sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128379      } else {
128380        returnSingleText(v, result);
128381        sqlite3_free(result);
128382      }
128383      break;
128384    }
128385  
128386  #ifndef OMIT_BRANCH_LOG
128387    case PragTyp_BRANCH_LOG: {
128388      char *msg=NULL;
128389      if( zRight==0 ){
128390        rc = pragma_get_branch_log(db, iDb, NULL, pParse);
128391      } else if( strncmp(zRight,"--set ",6)==0 ){
128392        rc = pragma_branch_edit_log(db, iDb, BRANCH_LOG_SET, zRight+6, &msg);
128393        //rc = pragma_set_branch_log(db, iDb, zRight+6);
128394      } else if( strncmp(zRight,"--add ",6)==0 ){
128395        rc = pragma_branch_edit_log(db, iDb, BRANCH_LOG_ADD, zRight+6, &msg);
128396        //rc = pragma_add_branch_log(db, iDb, zRight+6);
128397      } else if( strncmp(zRight,"--del ",6)==0 ){
128398        rc = pragma_branch_edit_log(db, iDb, BRANCH_LOG_DEL, zRight+6, &msg);
128399        //rc = pragma_del_branch_log(db, iDb, zRight+6);
128400      } else {
128401        rc = pragma_get_branch_log(db, iDb, zRight, pParse);
128402      }
128403  
128404      if( rc ){
128405        sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128406      } else if( msg ){
128407        returnSingleText(v, msg);
128408        sqlite3_free(msg);
128409      }
128410  
128411      break;
128412    }
128413  #else
128414    case PragTyp_BRANCH_LOG: {
128415      //pParse->nMem = 1;
128416      sqlite3VdbeSetNumCols(v, 1);
128417      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "branch_log", SQLITE_STATIC);
128418      returnSingleText(v, "disabled");
128419      break;
128420    }
128421  #endif
128422  
128423    case PragTyp_BRANCH_DIFF: {
128424      char *commit1, *commit2, *result;
128425      commit1 = zRight;
128426      commit2 = stripchr(commit1, ' ');
128427      result = pragma_branch_diff(db, iDb, commit1, commit2);
128428      //result = pragma_branch_diff(pDb, commit1, commit2);
128429      //result = pragma_branch_diff(pDb->pBt, commit1, commit2);
128430      if( result ){
128431        returnSingleText(v, result);
128432        sqlite3_free(result);
128433      }
128434      break;
128435    }
128436  
128437    case PragTyp_BRANCH_MERGE: {
128438      if( strncmp(zRight,"--forward ",10)==0 ){
128439        char *zparent, *zchild, *znum_commits;
128440        zparent = stripchr(zRight, ' ');
128441        zchild = stripchr(zparent, ' ');
128442        znum_commits = stripchr(zchild, ' ');
128443        rc = pragma_branch_forward_merge(db, iDb, zparent, zchild, znum_commits);
128444        if( rc ){
128445          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128446        } else {
128447          returnSingleText(v, "OK");
128448        }
128449      } else {
128450        // rc = pragma_branch_merge(db, iDb, commit1, commit2);
128451        sqlite3ErrorMsg(pParse, "invalid command. usage: PRAGMA branch_merge --forward {parent} {child} {num_commits}");
128452      }
128453  //    if( rc ){
128454  //      sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128455  //    } else {
128456  //      returnSingleText(v, "OK");
128457  //    }
128458      break;
128459    }
128460  
128461    case PragTyp_DISCARD_COMMITS: {
128462      if( zRight ){
128463        rc = pragma_discard_commits(db, iDb, zRight);
128464        if( rc ){
128465          sqlite3ErrorMsg(pParse, sqlite3ErrStr(rc));
128466        } else {
128467          returnSingleText(v, "OK");
128468        }
128469      }
128470      break;
128471    }
128472  
128473  
128474  #ifdef SQLITE_HAS_CODEC
128475    /* Pragma        iArg
128476    ** ----------   ------
128477    **  key           0
128478    **  rekey         1
128479    **  hexkey        2
128480    **  hexrekey      3
128481    **  textkey       4
128482    **  textrekey     5
128483    */
128484    case PragTyp_KEY: {
128485      if( zRight ){
128486        int n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
128487        if( (pPragma->iArg & 1)==0 ){
128488          sqlite3_key_v2(db, zDb, zRight, n);
128489        }else{
128490          sqlite3_rekey_v2(db, zDb, zRight, n);
128491        }
128492      }
128493      break;
128494    }
128495    case PragTyp_HEXKEY: {
128496      if( zRight ){
128497        u8 iByte;
128498        int i;
128499        char zKey[40];
128500        for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
128501          iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
128502          if( (i&1)!=0 ) zKey[i/2] = iByte;
128503        }
128504        if( (pPragma->iArg & 1)==0 ){
128505          sqlite3_key_v2(db, zDb, zKey, i/2);
128506        }else{
128507          sqlite3_rekey_v2(db, zDb, zKey, i/2);
128508        }
128509      }
128510      break;
128511    }
128512  #endif
128513  #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
128514    case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
128515  #ifdef SQLITE_HAS_CODEC
128516      if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
128517        sqlite3_activate_see(&zRight[4]);
128518      }
128519  #endif
128520  #ifdef SQLITE_ENABLE_CEROD
128521      if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
128522        sqlite3_activate_cerod(&zRight[6]);
128523      }
128524  #endif
128525    }
128526    break;
128527  #endif
128528  
128529    } /* End of the PRAGMA switch */
128530  
128531    /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
128532    ** purpose is to execute assert() statements to verify that if the
128533    ** PragFlg_NoColumns1 flag is set and the caller specified an argument
128534    ** to the PRAGMA, the implementation has not added any OP_ResultRow 
128535    ** instructions to the VM.  */
128536    if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
128537      sqlite3VdbeVerifyNoResultRow(v);
128538    }
128539  
128540  pragma_out:
128541    sqlite3DbFree(db, zLeft);
128542    sqlite3DbFree(db, zRight);
128543  }
128544  #ifndef SQLITE_OMIT_VIRTUALTABLE
128545  /*****************************************************************************
128546  ** Implementation of an eponymous virtual table that runs a pragma.
128547  **
128548  */
128549  typedef struct PragmaVtab PragmaVtab;
128550  typedef struct PragmaVtabCursor PragmaVtabCursor;
128551  struct PragmaVtab {
128552    sqlite3_vtab base;        /* Base class.  Must be first */
128553    sqlite3 *db;              /* The database connection to which it belongs */
128554    const PragmaName *pName;  /* Name of the pragma */
128555    u8 nHidden;               /* Number of hidden columns */
128556    u8 iHidden;               /* Index of the first hidden column */
128557  };
128558  struct PragmaVtabCursor {
128559    sqlite3_vtab_cursor base; /* Base class.  Must be first */
128560    sqlite3_stmt *pPragma;    /* The pragma statement to run */
128561    sqlite_int64 iRowid;      /* Current rowid */
128562    char *azArg[2];           /* Value of the argument and schema */
128563  };
128564  
128565  /* 
128566  ** Pragma virtual table module xConnect method.
128567  */
128568  static int pragmaVtabConnect(
128569    sqlite3 *db,
128570    void *pAux,
128571    int argc, const char *const*argv,
128572    sqlite3_vtab **ppVtab,
128573    char **pzErr
128574  ){
128575    const PragmaName *pPragma = (const PragmaName*)pAux;
128576    PragmaVtab *pTab = 0;
128577    int rc;
128578    int i, j;
128579    char cSep = '(';
128580    StrAccum acc;
128581    char zBuf[200];
128582  
128583    UNUSED_PARAMETER(argc);
128584    UNUSED_PARAMETER(argv);
128585    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
128586    sqlite3_str_appendall(&acc, "CREATE TABLE x");
128587    for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
128588      sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
128589      cSep = ',';
128590    }
128591    if( i==0 ){
128592      sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
128593      i++;
128594    }
128595    j = 0;
128596    if( pPragma->mPragFlg & PragFlg_Result1 ){
128597      sqlite3_str_appendall(&acc, ",arg HIDDEN");
128598      j++;
128599    }
128600    if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
128601      sqlite3_str_appendall(&acc, ",schema HIDDEN");
128602      j++;
128603    }
128604    sqlite3_str_append(&acc, ")", 1);
128605    sqlite3StrAccumFinish(&acc);
128606    assert( strlen(zBuf) < sizeof(zBuf)-1 );
128607    rc = sqlite3_declare_vtab(db, zBuf);
128608    if( rc==SQLITE_OK ){
128609      pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
128610      if( pTab==0 ){
128611        rc = SQLITE_NOMEM;
128612      }else{
128613        memset(pTab, 0, sizeof(PragmaVtab));
128614        pTab->pName = pPragma;
128615        pTab->db = db;
128616        pTab->iHidden = i;
128617        pTab->nHidden = j;
128618      }
128619    }else{
128620      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
128621    }
128622  
128623    *ppVtab = (sqlite3_vtab*)pTab;
128624    return rc;
128625  }
128626  
128627  /* 
128628  ** Pragma virtual table module xDisconnect method.
128629  */
128630  static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
128631    PragmaVtab *pTab = (PragmaVtab*)pVtab;
128632    sqlite3_free(pTab);
128633    return SQLITE_OK;
128634  }
128635  
128636  /* Figure out the best index to use to search a pragma virtual table.
128637  **
128638  ** There are not really any index choices.  But we want to encourage the
128639  ** query planner to give == constraints on as many hidden parameters as
128640  ** possible, and especially on the first hidden parameter.  So return a
128641  ** high cost if hidden parameters are unconstrained.
128642  */
128643  static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
128644    PragmaVtab *pTab = (PragmaVtab*)tab;
128645    const struct sqlite3_index_constraint *pConstraint;
128646    int i, j;
128647    int seen[2];
128648  
128649    pIdxInfo->estimatedCost = (double)1;
128650    if( pTab->nHidden==0 ){ return SQLITE_OK; }
128651    pConstraint = pIdxInfo->aConstraint;
128652    seen[0] = 0;
128653    seen[1] = 0;
128654    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
128655      if( pConstraint->usable==0 ) continue;
128656      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
128657      if( pConstraint->iColumn < pTab->iHidden ) continue;
128658      j = pConstraint->iColumn - pTab->iHidden;
128659      assert( j < 2 );
128660      seen[j] = i+1;
128661    }
128662    if( seen[0]==0 ){
128663      pIdxInfo->estimatedCost = (double)2147483647;
128664      pIdxInfo->estimatedRows = 2147483647;
128665      return SQLITE_OK;
128666    }
128667    j = seen[0]-1;
128668    pIdxInfo->aConstraintUsage[j].argvIndex = 1;
128669    pIdxInfo->aConstraintUsage[j].omit = 1;
128670    if( seen[1]==0 ) return SQLITE_OK;
128671    pIdxInfo->estimatedCost = (double)20;
128672    pIdxInfo->estimatedRows = 20;
128673    j = seen[1]-1;
128674    pIdxInfo->aConstraintUsage[j].argvIndex = 2;
128675    pIdxInfo->aConstraintUsage[j].omit = 1;
128676    return SQLITE_OK;
128677  }
128678  
128679  /* Create a new cursor for the pragma virtual table */
128680  static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
128681    PragmaVtabCursor *pCsr;
128682    pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
128683    if( pCsr==0 ) return SQLITE_NOMEM;
128684    memset(pCsr, 0, sizeof(PragmaVtabCursor));
128685    pCsr->base.pVtab = pVtab;
128686    *ppCursor = &pCsr->base;
128687    return SQLITE_OK;
128688  }
128689  
128690  /* Clear all content from pragma virtual table cursor. */
128691  static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
128692    int i;
128693    sqlite3_finalize(pCsr->pPragma);
128694    pCsr->pPragma = 0;
128695    for(i=0; i<ArraySize(pCsr->azArg); i++){
128696      sqlite3_free(pCsr->azArg[i]);
128697      pCsr->azArg[i] = 0;
128698    }
128699  }
128700  
128701  /* Close a pragma virtual table cursor */
128702  static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
128703    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
128704    pragmaVtabCursorClear(pCsr);
128705    sqlite3_free(pCsr);
128706    return SQLITE_OK;
128707  }
128708  
128709  /* Advance the pragma virtual table cursor to the next row */
128710  static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
128711    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
128712    int rc = SQLITE_OK;
128713  
128714    /* Increment the xRowid value */
128715    pCsr->iRowid++;
128716    assert( pCsr->pPragma );
128717    if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
128718      rc = sqlite3_finalize(pCsr->pPragma);
128719      pCsr->pPragma = 0;
128720      pragmaVtabCursorClear(pCsr);
128721    }
128722    return rc;
128723  }
128724  
128725  /* 
128726  ** Pragma virtual table module xFilter method.
128727  */
128728  static int pragmaVtabFilter(
128729    sqlite3_vtab_cursor *pVtabCursor, 
128730    int idxNum, const char *idxStr,
128731    int argc, sqlite3_value **argv
128732  ){
128733    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
128734    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
128735    int rc;
128736    int i, j;
128737    StrAccum acc;
128738    char *zSql;
128739  
128740    UNUSED_PARAMETER(idxNum);
128741    UNUSED_PARAMETER(idxStr);
128742    pragmaVtabCursorClear(pCsr);
128743    j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
128744    for(i=0; i<argc; i++, j++){
128745      const char *zText = (const char*)sqlite3_value_text(argv[i]);
128746      assert( j<ArraySize(pCsr->azArg) );
128747      assert( pCsr->azArg[j]==0 );
128748      if( zText ){
128749        pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
128750        if( pCsr->azArg[j]==0 ){
128751          return SQLITE_NOMEM;
128752        }
128753      }
128754    }
128755    sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
128756    sqlite3_str_appendall(&acc, "PRAGMA ");
128757    if( pCsr->azArg[1] ){
128758      sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
128759    }
128760    sqlite3_str_appendall(&acc, pTab->pName->zName);
128761    if( pCsr->azArg[0] ){
128762      sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
128763    }
128764    zSql = sqlite3StrAccumFinish(&acc);
128765    if( zSql==0 ) return SQLITE_NOMEM;
128766    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
128767    sqlite3_free(zSql);
128768    if( rc!=SQLITE_OK ){
128769      pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
128770      return rc;
128771    }
128772    return pragmaVtabNext(pVtabCursor);
128773  }
128774  
128775  /*
128776  ** Pragma virtual table module xEof method.
128777  */
128778  static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
128779    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
128780    return (pCsr->pPragma==0);
128781  }
128782  
128783  /* The xColumn method simply returns the corresponding column from
128784  ** the PRAGMA.  
128785  */
128786  static int pragmaVtabColumn(
128787    sqlite3_vtab_cursor *pVtabCursor, 
128788    sqlite3_context *ctx, 
128789    int i
128790  ){
128791    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
128792    PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
128793    if( i<pTab->iHidden ){
128794      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
128795    }else{
128796      sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
128797    }
128798    return SQLITE_OK;
128799  }
128800  
128801  /* 
128802  ** Pragma virtual table module xRowid method.
128803  */
128804  static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
128805    PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
128806    *p = pCsr->iRowid;
128807    return SQLITE_OK;
128808  }
128809  
128810  /* The pragma virtual table object */
128811  static const sqlite3_module pragmaVtabModule = {
128812    0,                           /* iVersion */
128813    0,                           /* xCreate - create a table */
128814    pragmaVtabConnect,           /* xConnect - connect to an existing table */
128815    pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
128816    pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
128817    0,                           /* xDestroy - Drop a table */
128818    pragmaVtabOpen,              /* xOpen - open a cursor */
128819    pragmaVtabClose,             /* xClose - close a cursor */
128820    pragmaVtabFilter,            /* xFilter - configure scan constraints */
128821    pragmaVtabNext,              /* xNext - advance a cursor */
128822    pragmaVtabEof,               /* xEof */
128823    pragmaVtabColumn,            /* xColumn - read data */
128824    pragmaVtabRowid,             /* xRowid - read data */
128825    0,                           /* xUpdate - write data */
128826    0,                           /* xBegin - begin transaction */
128827    0,                           /* xSync - sync transaction */
128828    0,                           /* xCommit - commit transaction */
128829    0,                           /* xRollback - rollback transaction */
128830    0,                           /* xFindFunction - function overloading */
128831    0,                           /* xRename - rename the table */
128832    0,                           /* xSavepoint */
128833    0,                           /* xRelease */
128834    0,                           /* xRollbackTo */
128835    0                            /* xShadowName */
128836  };
128837  
128838  /*
128839  ** Check to see if zTabName is really the name of a pragma.  If it is,
128840  ** then register an eponymous virtual table for that pragma and return
128841  ** a pointer to the Module object for the new virtual table.
128842  */
128843  SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
128844    const PragmaName *pName;
128845    assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
128846    pName = pragmaLocate(zName+7);
128847    if( pName==0 ) return 0;
128848    if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
128849    assert( sqlite3HashFind(&db->aModule, zName)==0 );
128850    return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
128851  }
128852  
128853  #endif /* SQLITE_OMIT_VIRTUALTABLE */
128854  
128855  #endif /* SQLITE_OMIT_PRAGMA */
128856  
128857  /************** End of pragma.c **********************************************/
128858  /************** Begin file prepare.c *****************************************/
128859  /*
128860  ** 2005 May 25
128861  **
128862  ** The author disclaims copyright to this source code.  In place of
128863  ** a legal notice, here is a blessing:
128864  **
128865  **    May you do good and not evil.
128866  **    May you find forgiveness for yourself and forgive others.
128867  **    May you share freely, never taking more than you give.
128868  **
128869  *************************************************************************
128870  ** This file contains the implementation of the sqlite3_prepare()
128871  ** interface, and routines that contribute to loading the database schema
128872  ** from disk.
128873  */
128874  /* #include "sqliteInt.h" */
128875  
128876  /*
128877  ** Fill the InitData structure with an error message that indicates
128878  ** that the database is corrupt.
128879  */
128880  static void corruptSchema(
128881    InitData *pData,     /* Initialization context */
128882    const char *zObj,    /* Object being parsed at the point of error */
128883    const char *zExtra   /* Error information */
128884  ){
128885    sqlite3 *db = pData->db;
128886    if( db->mallocFailed ){
128887      pData->rc = SQLITE_NOMEM_BKPT;
128888    }else if( pData->pzErrMsg[0]!=0 ){
128889      /* A error message has already been generated.  Do not overwrite it */
128890    }else if( pData->mInitFlags & INITFLAG_AlterTable ){
128891      *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
128892      pData->rc = SQLITE_ERROR;
128893    }else if( db->flags & SQLITE_WriteSchema ){
128894      pData->rc = SQLITE_CORRUPT_BKPT;
128895    }else{
128896      char *z;
128897      if( zObj==0 ) zObj = "?";
128898      z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
128899      if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
128900      *pData->pzErrMsg = z;
128901      pData->rc = SQLITE_CORRUPT_BKPT;
128902    }
128903  }
128904  
128905  /*
128906  ** Check to see if any sibling index (another index on the same table)
128907  ** of pIndex has the same root page number, and if it does, return true.
128908  ** This would indicate a corrupt schema.
128909  */
128910  SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
128911    Index *p;
128912    for(p=pIndex->pTable->pIndex; p; p=p->pNext){
128913      if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
128914    }
128915    return 0;
128916  }
128917  
128918  /*
128919  ** This is the callback routine for the code that initializes the
128920  ** database.  See sqlite3Init() below for additional information.
128921  ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
128922  **
128923  ** Each callback contains the following information:
128924  **
128925  **     argv[0] = name of thing being created
128926  **     argv[1] = root page number for table or index. 0 for trigger or view.
128927  **     argv[2] = SQL text for the CREATE statement.
128928  **
128929  */
128930  SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
128931    InitData *pData = (InitData*)pInit;
128932    sqlite3 *db = pData->db;
128933    int iDb = pData->iDb;
128934  
128935    assert( argc==3 );
128936    UNUSED_PARAMETER2(NotUsed, argc);
128937    assert( sqlite3_mutex_held(db->mutex) );
128938    DbClearProperty(db, iDb, DB_Empty);
128939    pData->nInitRow++;
128940    if( db->mallocFailed ){
128941      corruptSchema(pData, argv[0], 0);
128942      return 1;
128943    }
128944  
128945    assert( iDb>=0 && iDb<db->nDb );
128946    if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
128947    if( argv[1]==0 ){
128948      corruptSchema(pData, argv[0], 0);
128949    }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
128950      /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
128951      ** But because db->init.busy is set to 1, no VDBE code is generated
128952      ** or executed.  All the parser does is build the internal data
128953      ** structures that describe the table, index, or view.
128954      */
128955      int rc;
128956      u8 saved_iDb = db->init.iDb;
128957      sqlite3_stmt *pStmt;
128958      TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
128959  
128960      assert( db->init.busy );
128961      db->init.iDb = iDb;
128962      db->init.newTnum = sqlite3Atoi(argv[1]);
128963      db->init.orphanTrigger = 0;
128964      TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
128965      rc = db->errCode;
128966      assert( (rc&0xFF)==(rcp&0xFF) );
128967      db->init.iDb = saved_iDb;
128968      /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
128969      if( SQLITE_OK!=rc ){
128970        if( db->init.orphanTrigger ){
128971          assert( iDb==1 );
128972        }else{
128973          pData->rc = rc;
128974          if( rc==SQLITE_NOMEM ){
128975            sqlite3OomFault(db);
128976          }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
128977            corruptSchema(pData, argv[0], sqlite3_errmsg(db));
128978          }
128979        }
128980      }
128981      sqlite3_finalize(pStmt);
128982    }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
128983      corruptSchema(pData, argv[0], 0);
128984    }else{
128985      /* If the SQL column is blank it means this is an index that
128986      ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
128987      ** constraint for a CREATE TABLE.  The index should have already
128988      ** been created when we processed the CREATE TABLE.  All we have
128989      ** to do here is record the root page number for that index.
128990      */
128991      Index *pIndex;
128992      pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
128993      if( pIndex==0
128994       || sqlite3GetInt32(argv[1],&pIndex->tnum)==0
128995       || pIndex->tnum<2
128996       || sqlite3IndexHasDuplicateRootPage(pIndex)
128997      ){
128998        corruptSchema(pData, argv[0], pIndex?"invalid rootpage":"orphan index");
128999      }
129000    }
129001    return 0;
129002  }
129003  
129004  /*
129005  ** Attempt to read the database schema and initialize internal
129006  ** data structures for a single database file.  The index of the
129007  ** database file is given by iDb.  iDb==0 is used for the main
129008  ** database.  iDb==1 should never be used.  iDb>=2 is used for
129009  ** auxiliary databases.  Return one of the SQLITE_ error codes to
129010  ** indicate success or failure.
129011  */
129012  SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
129013    int rc;
129014    int i;
129015  #ifndef SQLITE_OMIT_DEPRECATED
129016    int size;
129017  #endif
129018    Db *pDb;
129019    char const *azArg[4];
129020    int meta[5];
129021    InitData initData;
129022    const char *zMasterName;
129023    int openedTransaction = 0;
129024  
129025    assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
129026    assert( iDb>=0 && iDb<db->nDb );
129027    assert( db->aDb[iDb].pSchema );
129028    assert( sqlite3_mutex_held(db->mutex) );
129029    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
129030  
129031    db->init.busy = 1;
129032  
129033    /* Construct the in-memory representation schema tables (sqlite_master or
129034    ** sqlite_temp_master) by invoking the parser directly.  The appropriate
129035    ** table name will be inserted automatically by the parser so we can just
129036    ** use the abbreviation "x" here.  The parser will also automatically tag
129037    ** the schema table as read-only. */
129038    azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
129039    azArg[1] = "1";
129040    azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
129041                              "rootpage int,sql text)";
129042    azArg[3] = 0;
129043    initData.db = db;
129044    initData.iDb = iDb;
129045    initData.rc = SQLITE_OK;
129046    initData.pzErrMsg = pzErrMsg;
129047    initData.mInitFlags = mFlags;
129048    initData.nInitRow = 0;
129049    sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
129050    if( initData.rc ){
129051      rc = initData.rc;
129052      goto error_out;
129053    }
129054  
129055    /* Create a cursor to hold the database open
129056    */
129057    pDb = &db->aDb[iDb];
129058    if( pDb->pBt==0 ){
129059      assert( iDb==1 );
129060      DbSetProperty(db, 1, DB_SchemaLoaded);
129061      rc = SQLITE_OK;
129062      goto error_out;
129063    }
129064  
129065    /* If there is not already a read-only (or read-write) transaction opened
129066    ** on the b-tree database, open one now. If a transaction is opened, it 
129067    ** will be closed before this function returns.  */
129068    sqlite3BtreeEnter(pDb->pBt);
129069    if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
129070      rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
129071      if( rc!=SQLITE_OK ){
129072        sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
129073        goto initone_error_out;
129074      }
129075      openedTransaction = 1;
129076    }
129077  
129078    /* Get the database meta information.
129079    **
129080    ** Meta values are as follows:
129081    **    meta[0]   Schema cookie.  Changes with each schema change.
129082    **    meta[1]   File format of schema layer.
129083    **    meta[2]   Size of the page cache.
129084    **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
129085    **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
129086    **    meta[5]   User version
129087    **    meta[6]   Incremental vacuum mode
129088    **    meta[7]   unused
129089    **    meta[8]   unused
129090    **    meta[9]   unused
129091    **
129092    ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
129093    ** the possible values of meta[4].
129094    */
129095    for(i=0; i<ArraySize(meta); i++){
129096      sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
129097    }
129098    if( (db->flags & SQLITE_ResetDatabase)!=0 ){
129099      memset(meta, 0, sizeof(meta));
129100    }
129101    pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
129102  
129103    /* If opening a non-empty database, check the text encoding. For the
129104    ** main database, set sqlite3.enc to the encoding of the main database.
129105    ** For an attached db, it is an error if the encoding is not the same
129106    ** as sqlite3.enc.
129107    */
129108    if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
129109      if( iDb==0 ){
129110  #ifndef SQLITE_OMIT_UTF16
129111        u8 encoding;
129112        /* If opening the main database, set ENC(db). */
129113        encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
129114        if( encoding==0 ) encoding = SQLITE_UTF8;
129115        ENC(db) = encoding;
129116  #else
129117        ENC(db) = SQLITE_UTF8;
129118  #endif
129119      }else{
129120        /* If opening an attached database, the encoding much match ENC(db) */
129121        if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
129122          sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
129123              " text encoding as main database");
129124          rc = SQLITE_ERROR;
129125          goto initone_error_out;
129126        }
129127      }
129128    }else{
129129      DbSetProperty(db, iDb, DB_Empty);
129130    }
129131    pDb->pSchema->enc = ENC(db);
129132  
129133    if( pDb->pSchema->cache_size==0 ){
129134  #ifndef SQLITE_OMIT_DEPRECATED
129135      size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
129136      if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
129137      pDb->pSchema->cache_size = size;
129138  #else
129139      pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
129140  #endif
129141      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
129142    }
129143  
129144    /*
129145    ** file_format==1    Version 3.0.0.
129146    ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
129147    ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
129148    ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
129149    */
129150    pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
129151    if( pDb->pSchema->file_format==0 ){
129152      pDb->pSchema->file_format = 1;
129153    }
129154    if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
129155      sqlite3SetString(pzErrMsg, db, "unsupported file format");
129156      rc = SQLITE_ERROR;
129157      goto initone_error_out;
129158    }
129159  
129160    /* Ticket #2804:  When we open a database in the newer file format,
129161    ** clear the legacy_file_format pragma flag so that a VACUUM will
129162    ** not downgrade the database and thus invalidate any descending
129163    ** indices that the user might have created.
129164    */
129165    if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
129166      db->flags &= ~(u64)SQLITE_LegacyFileFmt;
129167    }
129168  
129169    /* Read the schema information out of the schema tables
129170    */
129171    assert( db->init.busy );
129172    {
129173      char *zSql;
129174      zSql = sqlite3MPrintf(db, 
129175          "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
129176          db->aDb[iDb].zDbSName, zMasterName);
129177  #ifndef SQLITE_OMIT_AUTHORIZATION
129178      {
129179        sqlite3_xauth xAuth;
129180        xAuth = db->xAuth;
129181        db->xAuth = 0;
129182  #endif
129183        rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
129184  #ifndef SQLITE_OMIT_AUTHORIZATION
129185        db->xAuth = xAuth;
129186      }
129187  #endif
129188      if( rc==SQLITE_OK ) rc = initData.rc;
129189      sqlite3DbFree(db, zSql);
129190  #ifndef SQLITE_OMIT_ANALYZE
129191      if( rc==SQLITE_OK ){
129192        sqlite3AnalysisLoad(db, iDb);
129193      }
129194  #endif
129195    }
129196    if( db->mallocFailed ){
129197      rc = SQLITE_NOMEM_BKPT;
129198      sqlite3ResetAllSchemasOfConnection(db);
129199    }
129200    if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
129201      /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
129202      ** the schema loaded, even if errors occurred. In this situation the 
129203      ** current sqlite3_prepare() operation will fail, but the following one
129204      ** will attempt to compile the supplied statement against whatever subset
129205      ** of the schema was loaded before the error occurred. The primary
129206      ** purpose of this is to allow access to the sqlite_master table
129207      ** even when its contents have been corrupted.
129208      */
129209      DbSetProperty(db, iDb, DB_SchemaLoaded);
129210      rc = SQLITE_OK;
129211    }
129212  
129213    /* Jump here for an error that occurs after successfully allocating
129214    ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
129215    ** before that point, jump to error_out.
129216    */
129217  initone_error_out:
129218    if( openedTransaction ){
129219      sqlite3BtreeCommit(pDb->pBt);
129220    }
129221    sqlite3BtreeLeave(pDb->pBt);
129222  
129223  error_out:
129224    if( rc ){
129225      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
129226        sqlite3OomFault(db);
129227      }
129228      sqlite3ResetOneSchema(db, iDb);
129229    }
129230    db->init.busy = 0;
129231    return rc;
129232  }
129233  
129234  /*
129235  ** Initialize all database files - the main database file, the file
129236  ** used to store temporary tables, and any additional database files
129237  ** created using ATTACH statements.  Return a success code.  If an
129238  ** error occurs, write an error message into *pzErrMsg.
129239  **
129240  ** After a database is initialized, the DB_SchemaLoaded bit is set
129241  ** bit is set in the flags field of the Db structure. If the database
129242  ** file was of zero-length, then the DB_Empty flag is also set.
129243  */
129244  SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
129245    int i, rc;
129246    int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
129247    
129248    assert( sqlite3_mutex_held(db->mutex) );
129249    assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
129250    assert( db->init.busy==0 );
129251    ENC(db) = SCHEMA_ENC(db);
129252    assert( db->nDb>0 );
129253    /* Do the main schema first */
129254    if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
129255      rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
129256      if( rc ) return rc;
129257    }
129258    /* All other schemas after the main schema. The "temp" schema must be last */
129259    for(i=db->nDb-1; i>0; i--){
129260      assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
129261      if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
129262        rc = sqlite3InitOne(db, i, pzErrMsg, 0);
129263        if( rc ) return rc;
129264      }
129265    }
129266    if( commit_internal ){
129267      sqlite3CommitInternalChanges(db);
129268    }
129269    return SQLITE_OK;
129270  }
129271  
129272  /*
129273  ** This routine is a no-op if the database schema is already initialized.
129274  ** Otherwise, the schema is loaded. An error code is returned.
129275  */
129276  SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
129277    int rc = SQLITE_OK;
129278    sqlite3 *db = pParse->db;
129279    assert( sqlite3_mutex_held(db->mutex) );
129280    if( !db->init.busy ){
129281      rc = sqlite3Init(db, &pParse->zErrMsg);
129282      if( rc!=SQLITE_OK ){
129283        pParse->rc = rc;
129284        pParse->nErr++;
129285      }else if( db->noSharedCache ){
129286        db->mDbFlags |= DBFLAG_SchemaKnownOk;
129287      }
129288    }
129289    return rc;
129290  }
129291  
129292  
129293  /*
129294  ** Check schema cookies in all databases.  If any cookie is out
129295  ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
129296  ** make no changes to pParse->rc.
129297  */
129298  static void schemaIsValid(Parse *pParse){
129299    sqlite3 *db = pParse->db;
129300    int iDb;
129301    int rc;
129302    int cookie;
129303  
129304    assert( pParse->checkSchema );
129305    assert( sqlite3_mutex_held(db->mutex) );
129306    for(iDb=0; iDb<db->nDb; iDb++){
129307      int openedTransaction = 0;         /* True if a transaction is opened */
129308      Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
129309      if( pBt==0 ) continue;
129310  
129311      /* If there is not already a read-only (or read-write) transaction opened
129312      ** on the b-tree database, open one now. If a transaction is opened, it 
129313      ** will be closed immediately after reading the meta-value. */
129314      if( !sqlite3BtreeIsInReadTrans(pBt) ){
129315        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
129316        if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
129317          sqlite3OomFault(db);
129318        }
129319        if( rc!=SQLITE_OK ) return;
129320        openedTransaction = 1;
129321      }
129322  
129323      /* Read the schema cookie from the database. If it does not match the 
129324      ** value stored as part of the in-memory schema representation,
129325      ** set Parse.rc to SQLITE_SCHEMA. */
129326      sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
129327      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
129328      if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
129329        sqlite3ResetOneSchema(db, iDb);
129330        pParse->rc = SQLITE_SCHEMA;
129331      }
129332  
129333      /* Close the transaction, if one was opened. */
129334      if( openedTransaction ){
129335        sqlite3BtreeCommit(pBt);
129336      }
129337    }
129338  }
129339  
129340  /*
129341  ** Convert a schema pointer into the iDb index that indicates
129342  ** which database file in db->aDb[] the schema refers to.
129343  **
129344  ** If the same database is attached more than once, the first
129345  ** attached database is returned.
129346  */
129347  SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
129348    int i = -1000000;
129349  
129350    /* If pSchema is NULL, then return -1000000. This happens when code in 
129351    ** expr.c is trying to resolve a reference to a transient table (i.e. one
129352    ** created by a sub-select). In this case the return value of this 
129353    ** function should never be used.
129354    **
129355    ** We return -1000000 instead of the more usual -1 simply because using
129356    ** -1000000 as the incorrect index into db->aDb[] is much 
129357    ** more likely to cause a segfault than -1 (of course there are assert()
129358    ** statements too, but it never hurts to play the odds).
129359    */
129360    assert( sqlite3_mutex_held(db->mutex) );
129361    if( pSchema ){
129362      for(i=0; 1; i++){
129363        assert( i<db->nDb );
129364        if( db->aDb[i].pSchema==pSchema ){
129365          break;
129366        }
129367      }
129368      assert( i>=0 && i<db->nDb );
129369    }
129370    return i;
129371  }
129372  
129373  /*
129374  ** Free all memory allocations in the pParse object
129375  */
129376  SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
129377    sqlite3 *db = pParse->db;
129378    sqlite3DbFree(db, pParse->aLabel);
129379    sqlite3ExprListDelete(db, pParse->pConstExpr);
129380    if( db ){
129381      assert( db->lookaside.bDisable >= pParse->disableLookaside );
129382      db->lookaside.bDisable -= pParse->disableLookaside;
129383    }
129384    pParse->disableLookaside = 0;
129385  }
129386  
129387  /*
129388  ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
129389  */
129390  static int sqlite3Prepare(
129391    sqlite3 *db,              /* Database handle. */
129392    const char *zSql,         /* UTF-8 encoded SQL statement. */
129393    int nBytes,               /* Length of zSql in bytes. */
129394    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
129395    Vdbe *pReprepare,         /* VM being reprepared */
129396    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129397    const char **pzTail       /* OUT: End of parsed string */
129398  ){
129399    char *zErrMsg = 0;        /* Error message */
129400    int rc = SQLITE_OK;       /* Result code */
129401    int i;                    /* Loop counter */
129402    Parse sParse;             /* Parsing context */
129403  
129404    memset(&sParse, 0, PARSE_HDR_SZ);
129405    memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
129406    sParse.pReprepare = pReprepare;
129407    assert( ppStmt && *ppStmt==0 );
129408    /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
129409    assert( sqlite3_mutex_held(db->mutex) );
129410  
129411    /* For a long-term use prepared statement avoid the use of
129412    ** lookaside memory.
129413    */
129414    if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
129415      sParse.disableLookaside++;
129416      db->lookaside.bDisable++;
129417    }
129418    sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
129419  
129420    /* Check to verify that it is possible to get a read lock on all
129421    ** database schemas.  The inability to get a read lock indicates that
129422    ** some other database connection is holding a write-lock, which in
129423    ** turn means that the other connection has made uncommitted changes
129424    ** to the schema.
129425    **
129426    ** Were we to proceed and prepare the statement against the uncommitted
129427    ** schema changes and if those schema changes are subsequently rolled
129428    ** back and different changes are made in their place, then when this
129429    ** prepared statement goes to run the schema cookie would fail to detect
129430    ** the schema change.  Disaster would follow.
129431    **
129432    ** This thread is currently holding mutexes on all Btrees (because
129433    ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
129434    ** is not possible for another thread to start a new schema change
129435    ** while this routine is running.  Hence, we do not need to hold 
129436    ** locks on the schema, we just need to make sure nobody else is 
129437    ** holding them.
129438    **
129439    ** Note that setting READ_UNCOMMITTED overrides most lock detection,
129440    ** but it does *not* override schema lock detection, so this all still
129441    ** works even if READ_UNCOMMITTED is set.
129442    */
129443    for(i=0; i<db->nDb; i++) {
129444      Btree *pBt = db->aDb[i].pBt;
129445      if( pBt ){
129446        assert( sqlite3BtreeHoldsMutex(pBt) );
129447        rc = sqlite3BtreeSchemaLocked(pBt);
129448        if( rc ){
129449          const char *zDb = db->aDb[i].zDbSName;
129450          sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
129451          testcase( db->flags & SQLITE_ReadUncommit );
129452          goto end_prepare;
129453        }
129454      }
129455    }
129456  
129457    sqlite3VtabUnlockList(db);
129458  
129459    sParse.db = db;
129460    if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
129461      char *zSqlCopy;
129462      int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
129463      testcase( nBytes==mxLen );
129464      testcase( nBytes==mxLen+1 );
129465      if( nBytes>mxLen ){
129466        sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
129467        rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
129468        goto end_prepare;
129469      }
129470      zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
129471      if( zSqlCopy ){
129472        sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
129473        sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
129474        sqlite3DbFree(db, zSqlCopy);
129475      }else{
129476        sParse.zTail = &zSql[nBytes];
129477      }
129478    }else{
129479      sqlite3RunParser(&sParse, zSql, &zErrMsg);
129480    }
129481    assert( 0==sParse.nQueryLoop );
129482  
129483    if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
129484    if( sParse.checkSchema ){
129485      schemaIsValid(&sParse);
129486    }
129487    if( db->mallocFailed ){
129488      sParse.rc = SQLITE_NOMEM_BKPT;
129489    }
129490    if( pzTail ){
129491      *pzTail = sParse.zTail;
129492    }
129493    rc = sParse.rc;
129494  
129495  #ifndef SQLITE_OMIT_EXPLAIN
129496    if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
129497      static const char * const azColName[] = {
129498         "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
129499         "id", "parent", "notused", "detail"
129500      };
129501      int iFirst, mx;
129502      if( sParse.explain==2 ){
129503        sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
129504        iFirst = 8;
129505        mx = 12;
129506      }else{
129507        sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
129508        iFirst = 0;
129509        mx = 8;
129510      }
129511      for(i=iFirst; i<mx; i++){
129512        sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
129513                              azColName[i], SQLITE_STATIC);
129514      }
129515    }
129516  #endif
129517  
129518    if( db->init.busy==0 ){
129519      sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
129520    }
129521    if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
129522      sqlite3VdbeFinalize(sParse.pVdbe);
129523      assert(!(*ppStmt));
129524    }else{
129525      *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
129526    }
129527  
129528    if( zErrMsg ){
129529      sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
129530      sqlite3DbFree(db, zErrMsg);
129531    }else{
129532      sqlite3Error(db, rc);
129533    }
129534  
129535    /* Delete any TriggerPrg structures allocated while parsing this statement. */
129536    while( sParse.pTriggerPrg ){
129537      TriggerPrg *pT = sParse.pTriggerPrg;
129538      sParse.pTriggerPrg = pT->pNext;
129539      sqlite3DbFree(db, pT);
129540    }
129541  
129542  end_prepare:
129543  
129544    sqlite3ParserReset(&sParse);
129545    return rc;
129546  }
129547  static int sqlite3LockAndPrepare(
129548    sqlite3 *db,              /* Database handle. */
129549    const char *zSql,         /* UTF-8 encoded SQL statement. */
129550    int nBytes,               /* Length of zSql in bytes. */
129551    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
129552    Vdbe *pOld,               /* VM being reprepared */
129553    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129554    const char **pzTail       /* OUT: End of parsed string */
129555  ){
129556    int rc;
129557    int cnt = 0;
129558  
129559  #ifdef SQLITE_ENABLE_API_ARMOR
129560    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
129561  #endif
129562    *ppStmt = 0;
129563    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
129564      return SQLITE_MISUSE_BKPT;
129565    }
129566    sqlite3_mutex_enter(db->mutex);
129567    sqlite3BtreeEnterAll(db);
129568    do{
129569      /* Make multiple attempts to compile the SQL, until it either succeeds
129570      ** or encounters a permanent error.  A schema problem after one schema
129571      ** reset is considered a permanent error. */
129572      rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
129573      assert( rc==SQLITE_OK || *ppStmt==0 );
129574    }while( rc==SQLITE_ERROR_RETRY
129575         || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
129576    sqlite3BtreeLeaveAll(db);
129577    rc = sqlite3ApiExit(db, rc);
129578    assert( (rc&db->errMask)==rc );
129579    sqlite3_mutex_leave(db->mutex);
129580    return rc;
129581  }
129582  
129583  
129584  /*
129585  ** Rerun the compilation of a statement after a schema change.
129586  **
129587  ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
129588  ** if the statement cannot be recompiled because another connection has
129589  ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
129590  ** occurs, return SQLITE_SCHEMA.
129591  */
129592  SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
129593    int rc;
129594    sqlite3_stmt *pNew;
129595    const char *zSql;
129596    sqlite3 *db;
129597    u8 prepFlags;
129598  
129599    assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
129600    zSql = sqlite3_sql((sqlite3_stmt *)p);
129601    assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
129602    db = sqlite3VdbeDb(p);
129603    assert( sqlite3_mutex_held(db->mutex) );
129604    prepFlags = sqlite3VdbePrepareFlags(p);
129605    rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
129606    if( rc ){
129607      if( rc==SQLITE_NOMEM ){
129608        sqlite3OomFault(db);
129609      }
129610      assert( pNew==0 );
129611      return rc;
129612    }else{
129613      assert( pNew!=0 );
129614    }
129615    sqlite3VdbeSwap((Vdbe*)pNew, p);
129616    sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
129617    sqlite3VdbeResetStepResult((Vdbe*)pNew);
129618    sqlite3VdbeFinalize((Vdbe*)pNew);
129619    return SQLITE_OK;
129620  }
129621  
129622  
129623  /*
129624  ** Two versions of the official API.  Legacy and new use.  In the legacy
129625  ** version, the original SQL text is not saved in the prepared statement
129626  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
129627  ** sqlite3_step().  In the new version, the original SQL text is retained
129628  ** and the statement is automatically recompiled if an schema change
129629  ** occurs.
129630  */
129631  SQLITE_API int sqlite3_prepare(
129632    sqlite3 *db,              /* Database handle. */
129633    const char *zSql,         /* UTF-8 encoded SQL statement. */
129634    int nBytes,               /* Length of zSql in bytes. */
129635    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129636    const char **pzTail       /* OUT: End of parsed string */
129637  ){
129638    int rc;
129639    rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
129640    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
129641    return rc;
129642  }
129643  SQLITE_API int sqlite3_prepare_v2(
129644    sqlite3 *db,              /* Database handle. */
129645    const char *zSql,         /* UTF-8 encoded SQL statement. */
129646    int nBytes,               /* Length of zSql in bytes. */
129647    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129648    const char **pzTail       /* OUT: End of parsed string */
129649  ){
129650    int rc;
129651    /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
129652    ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
129653    ** parameter.
129654    **
129655    ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
129656    rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
129657                               ppStmt,pzTail);
129658    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
129659    return rc;
129660  }
129661  SQLITE_API int sqlite3_prepare_v3(
129662    sqlite3 *db,              /* Database handle. */
129663    const char *zSql,         /* UTF-8 encoded SQL statement. */
129664    int nBytes,               /* Length of zSql in bytes. */
129665    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
129666    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129667    const char **pzTail       /* OUT: End of parsed string */
129668  ){
129669    int rc;
129670    /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
129671    ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
129672    ** which is a bit array consisting of zero or more of the
129673    ** SQLITE_PREPARE_* flags.
129674    **
129675    ** Proof by comparison to the implementation of sqlite3_prepare_v2()
129676    ** directly above. */
129677    rc = sqlite3LockAndPrepare(db,zSql,nBytes,
129678                   SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
129679                   0,ppStmt,pzTail);
129680    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
129681    return rc;
129682  }
129683  
129684  
129685  #ifndef SQLITE_OMIT_UTF16
129686  /*
129687  ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
129688  */
129689  static int sqlite3Prepare16(
129690    sqlite3 *db,              /* Database handle. */ 
129691    const void *zSql,         /* UTF-16 encoded SQL statement. */
129692    int nBytes,               /* Length of zSql in bytes. */
129693    u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
129694    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129695    const void **pzTail       /* OUT: End of parsed string */
129696  ){
129697    /* This function currently works by first transforming the UTF-16
129698    ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
129699    ** tricky bit is figuring out the pointer to return in *pzTail.
129700    */
129701    char *zSql8;
129702    const char *zTail8 = 0;
129703    int rc = SQLITE_OK;
129704  
129705  #ifdef SQLITE_ENABLE_API_ARMOR
129706    if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
129707  #endif
129708    *ppStmt = 0;
129709    if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
129710      return SQLITE_MISUSE_BKPT;
129711    }
129712    if( nBytes>=0 ){
129713      int sz;
129714      const char *z = (const char*)zSql;
129715      for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
129716      nBytes = sz;
129717    }
129718    sqlite3_mutex_enter(db->mutex);
129719    zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
129720    if( zSql8 ){
129721      rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
129722    }
129723  
129724    if( zTail8 && pzTail ){
129725      /* If sqlite3_prepare returns a tail pointer, we calculate the
129726      ** equivalent pointer into the UTF-16 string by counting the unicode
129727      ** characters between zSql8 and zTail8, and then returning a pointer
129728      ** the same number of characters into the UTF-16 string.
129729      */
129730      int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
129731      *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
129732    }
129733    sqlite3DbFree(db, zSql8); 
129734    rc = sqlite3ApiExit(db, rc);
129735    sqlite3_mutex_leave(db->mutex);
129736    return rc;
129737  }
129738  
129739  /*
129740  ** Two versions of the official API.  Legacy and new use.  In the legacy
129741  ** version, the original SQL text is not saved in the prepared statement
129742  ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
129743  ** sqlite3_step().  In the new version, the original SQL text is retained
129744  ** and the statement is automatically recompiled if an schema change
129745  ** occurs.
129746  */
129747  SQLITE_API int sqlite3_prepare16(
129748    sqlite3 *db,              /* Database handle. */ 
129749    const void *zSql,         /* UTF-16 encoded SQL statement. */
129750    int nBytes,               /* Length of zSql in bytes. */
129751    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129752    const void **pzTail       /* OUT: End of parsed string */
129753  ){
129754    int rc;
129755    rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
129756    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
129757    return rc;
129758  }
129759  SQLITE_API int sqlite3_prepare16_v2(
129760    sqlite3 *db,              /* Database handle. */ 
129761    const void *zSql,         /* UTF-16 encoded SQL statement. */
129762    int nBytes,               /* Length of zSql in bytes. */
129763    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129764    const void **pzTail       /* OUT: End of parsed string */
129765  ){
129766    int rc;
129767    rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
129768    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
129769    return rc;
129770  }
129771  SQLITE_API int sqlite3_prepare16_v3(
129772    sqlite3 *db,              /* Database handle. */ 
129773    const void *zSql,         /* UTF-16 encoded SQL statement. */
129774    int nBytes,               /* Length of zSql in bytes. */
129775    unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
129776    sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
129777    const void **pzTail       /* OUT: End of parsed string */
129778  ){
129779    int rc;
129780    rc = sqlite3Prepare16(db,zSql,nBytes,
129781           SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
129782           ppStmt,pzTail);
129783    assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
129784    return rc;
129785  }
129786  
129787  #endif /* SQLITE_OMIT_UTF16 */
129788  
129789  /************** End of prepare.c *********************************************/
129790  /************** Begin file select.c ******************************************/
129791  /*
129792  ** 2001 September 15
129793  **
129794  ** The author disclaims copyright to this source code.  In place of
129795  ** a legal notice, here is a blessing:
129796  **
129797  **    May you do good and not evil.
129798  **    May you find forgiveness for yourself and forgive others.
129799  **    May you share freely, never taking more than you give.
129800  **
129801  *************************************************************************
129802  ** This file contains C code routines that are called by the parser
129803  ** to handle SELECT statements in SQLite.
129804  */
129805  /* #include "sqliteInt.h" */
129806  
129807  /*
129808  ** Trace output macros
129809  */
129810  #if SELECTTRACE_ENABLED
129811  /***/ int sqlite3SelectTrace = 0;
129812  # define SELECTTRACE(K,P,S,X)  \
129813    if(sqlite3SelectTrace&(K))   \
129814      sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
129815      sqlite3DebugPrintf X
129816  #else
129817  # define SELECTTRACE(K,P,S,X)
129818  #endif
129819  
129820  
129821  /*
129822  ** An instance of the following object is used to record information about
129823  ** how to process the DISTINCT keyword, to simplify passing that information
129824  ** into the selectInnerLoop() routine.
129825  */
129826  typedef struct DistinctCtx DistinctCtx;
129827  struct DistinctCtx {
129828    u8 isTnct;      /* True if the DISTINCT keyword is present */
129829    u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
129830    int tabTnct;    /* Ephemeral table used for DISTINCT processing */
129831    int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
129832  };
129833  
129834  /*
129835  ** An instance of the following object is used to record information about
129836  ** the ORDER BY (or GROUP BY) clause of query is being coded.
129837  **
129838  ** The aDefer[] array is used by the sorter-references optimization. For
129839  ** example, assuming there is no index that can be used for the ORDER BY,
129840  ** for the query:
129841  **
129842  **     SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
129843  **
129844  ** it may be more efficient to add just the "a" values to the sorter, and
129845  ** retrieve the associated "bigblob" values directly from table t1 as the
129846  ** 10 smallest "a" values are extracted from the sorter.
129847  **
129848  ** When the sorter-reference optimization is used, there is one entry in the
129849  ** aDefer[] array for each database table that may be read as values are
129850  ** extracted from the sorter.
129851  */
129852  typedef struct SortCtx SortCtx;
129853  struct SortCtx {
129854    ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
129855    int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
129856    int iECursor;         /* Cursor number for the sorter */
129857    int regReturn;        /* Register holding block-output return address */
129858    int labelBkOut;       /* Start label for the block-output subroutine */
129859    int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
129860    int labelDone;        /* Jump here when done, ex: LIMIT reached */
129861    int labelOBLopt;      /* Jump here when sorter is full */
129862    u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
129863  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
129864    u8 nDefer;            /* Number of valid entries in aDefer[] */
129865    struct DeferredCsr {
129866      Table *pTab;        /* Table definition */
129867      int iCsr;           /* Cursor number for table */
129868      int nKey;           /* Number of PK columns for table pTab (>=1) */
129869    } aDefer[4];
129870  #endif
129871    struct RowLoadInfo *pDeferredRowLoad;  /* Deferred row loading info or NULL */
129872  };
129873  #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
129874  
129875  /*
129876  ** Delete all the content of a Select structure.  Deallocate the structure
129877  ** itself only if bFree is true.
129878  */
129879  static void clearSelect(sqlite3 *db, Select *p, int bFree){
129880    while( p ){
129881      Select *pPrior = p->pPrior;
129882      sqlite3ExprListDelete(db, p->pEList);
129883      sqlite3SrcListDelete(db, p->pSrc);
129884      sqlite3ExprDelete(db, p->pWhere);
129885      sqlite3ExprListDelete(db, p->pGroupBy);
129886      sqlite3ExprDelete(db, p->pHaving);
129887      sqlite3ExprListDelete(db, p->pOrderBy);
129888      sqlite3ExprDelete(db, p->pLimit);
129889  #ifndef SQLITE_OMIT_WINDOWFUNC
129890      if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
129891        sqlite3WindowListDelete(db, p->pWinDefn);
129892      }
129893  #endif
129894      if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
129895      if( bFree ) sqlite3DbFreeNN(db, p);
129896      p = pPrior;
129897      bFree = 1;
129898    }
129899  }
129900  
129901  /*
129902  ** Initialize a SelectDest structure.
129903  */
129904  SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
129905    pDest->eDest = (u8)eDest;
129906    pDest->iSDParm = iParm;
129907    pDest->zAffSdst = 0;
129908    pDest->iSdst = 0;
129909    pDest->nSdst = 0;
129910  }
129911  
129912  
129913  /*
129914  ** Allocate a new Select structure and return a pointer to that
129915  ** structure.
129916  */
129917  SQLITE_PRIVATE Select *sqlite3SelectNew(
129918    Parse *pParse,        /* Parsing context */
129919    ExprList *pEList,     /* which columns to include in the result */
129920    SrcList *pSrc,        /* the FROM clause -- which tables to scan */
129921    Expr *pWhere,         /* the WHERE clause */
129922    ExprList *pGroupBy,   /* the GROUP BY clause */
129923    Expr *pHaving,        /* the HAVING clause */
129924    ExprList *pOrderBy,   /* the ORDER BY clause */
129925    u32 selFlags,         /* Flag parameters, such as SF_Distinct */
129926    Expr *pLimit          /* LIMIT value.  NULL means not used */
129927  ){
129928    Select *pNew;
129929    Select standin;
129930    pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
129931    if( pNew==0 ){
129932      assert( pParse->db->mallocFailed );
129933      pNew = &standin;
129934    }
129935    if( pEList==0 ){
129936      pEList = sqlite3ExprListAppend(pParse, 0,
129937                                     sqlite3Expr(pParse->db,TK_ASTERISK,0));
129938    }
129939    pNew->pEList = pEList;
129940    pNew->op = TK_SELECT;
129941    pNew->selFlags = selFlags;
129942    pNew->iLimit = 0;
129943    pNew->iOffset = 0;
129944    pNew->selId = ++pParse->nSelect;
129945    pNew->addrOpenEphm[0] = -1;
129946    pNew->addrOpenEphm[1] = -1;
129947    pNew->nSelectRow = 0;
129948    if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
129949    pNew->pSrc = pSrc;
129950    pNew->pWhere = pWhere;
129951    pNew->pGroupBy = pGroupBy;
129952    pNew->pHaving = pHaving;
129953    pNew->pOrderBy = pOrderBy;
129954    pNew->pPrior = 0;
129955    pNew->pNext = 0;
129956    pNew->pLimit = pLimit;
129957    pNew->pWith = 0;
129958  #ifndef SQLITE_OMIT_WINDOWFUNC
129959    pNew->pWin = 0;
129960    pNew->pWinDefn = 0;
129961  #endif
129962    if( pParse->db->mallocFailed ) {
129963      clearSelect(pParse->db, pNew, pNew!=&standin);
129964      pNew = 0;
129965    }else{
129966      assert( pNew->pSrc!=0 || pParse->nErr>0 );
129967    }
129968    assert( pNew!=&standin );
129969    return pNew;
129970  }
129971  
129972  
129973  /*
129974  ** Delete the given Select structure and all of its substructures.
129975  */
129976  SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
129977    if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
129978  }
129979  
129980  /*
129981  ** Return a pointer to the right-most SELECT statement in a compound.
129982  */
129983  static Select *findRightmost(Select *p){
129984    while( p->pNext ) p = p->pNext;
129985    return p;
129986  }
129987  
129988  /*
129989  ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
129990  ** type of join.  Return an integer constant that expresses that type
129991  ** in terms of the following bit values:
129992  **
129993  **     JT_INNER
129994  **     JT_CROSS
129995  **     JT_OUTER
129996  **     JT_NATURAL
129997  **     JT_LEFT
129998  **     JT_RIGHT
129999  **
130000  ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
130001  **
130002  ** If an illegal or unsupported join type is seen, then still return
130003  ** a join type, but put an error in the pParse structure.
130004  */
130005  SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
130006    int jointype = 0;
130007    Token *apAll[3];
130008    Token *p;
130009                               /*   0123456789 123456789 123456789 123 */
130010    static const char zKeyText[] = "naturaleftouterightfullinnercross";
130011    static const struct {
130012      u8 i;        /* Beginning of keyword text in zKeyText[] */
130013      u8 nChar;    /* Length of the keyword in characters */
130014      u8 code;     /* Join type mask */
130015    } aKeyword[] = {
130016      /* natural */ { 0,  7, JT_NATURAL                },
130017      /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
130018      /* outer   */ { 10, 5, JT_OUTER                  },
130019      /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
130020      /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
130021      /* inner   */ { 23, 5, JT_INNER                  },
130022      /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
130023    };
130024    int i, j;
130025    apAll[0] = pA;
130026    apAll[1] = pB;
130027    apAll[2] = pC;
130028    for(i=0; i<3 && apAll[i]; i++){
130029      p = apAll[i];
130030      for(j=0; j<ArraySize(aKeyword); j++){
130031        if( p->n==aKeyword[j].nChar 
130032            && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
130033          jointype |= aKeyword[j].code;
130034          break;
130035        }
130036      }
130037      testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
130038      if( j>=ArraySize(aKeyword) ){
130039        jointype |= JT_ERROR;
130040        break;
130041      }
130042    }
130043    if(
130044       (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
130045       (jointype & JT_ERROR)!=0
130046    ){
130047      const char *zSp = " ";
130048      assert( pB!=0 );
130049      if( pC==0 ){ zSp++; }
130050      sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
130051         "%T %T%s%T", pA, pB, zSp, pC);
130052      jointype = JT_INNER;
130053    }else if( (jointype & JT_OUTER)!=0 
130054           && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
130055      sqlite3ErrorMsg(pParse, 
130056        "RIGHT and FULL OUTER JOINs are not currently supported");
130057      jointype = JT_INNER;
130058    }
130059    return jointype;
130060  }
130061  
130062  /*
130063  ** Return the index of a column in a table.  Return -1 if the column
130064  ** is not contained in the table.
130065  */
130066  static int columnIndex(Table *pTab, const char *zCol){
130067    int i;
130068    for(i=0; i<pTab->nCol; i++){
130069      if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
130070    }
130071    return -1;
130072  }
130073  
130074  /*
130075  ** Search the first N tables in pSrc, from left to right, looking for a
130076  ** table that has a column named zCol.  
130077  **
130078  ** When found, set *piTab and *piCol to the table index and column index
130079  ** of the matching column and return TRUE.
130080  **
130081  ** If not found, return FALSE.
130082  */
130083  static int tableAndColumnIndex(
130084    SrcList *pSrc,       /* Array of tables to search */
130085    int N,               /* Number of tables in pSrc->a[] to search */
130086    const char *zCol,    /* Name of the column we are looking for */
130087    int *piTab,          /* Write index of pSrc->a[] here */
130088    int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
130089  ){
130090    int i;               /* For looping over tables in pSrc */
130091    int iCol;            /* Index of column matching zCol */
130092  
130093    assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
130094    for(i=0; i<N; i++){
130095      iCol = columnIndex(pSrc->a[i].pTab, zCol);
130096      if( iCol>=0 ){
130097        if( piTab ){
130098          *piTab = i;
130099          *piCol = iCol;
130100        }
130101        return 1;
130102      }
130103    }
130104    return 0;
130105  }
130106  
130107  /*
130108  ** This function is used to add terms implied by JOIN syntax to the
130109  ** WHERE clause expression of a SELECT statement. The new term, which
130110  ** is ANDed with the existing WHERE clause, is of the form:
130111  **
130112  **    (tab1.col1 = tab2.col2)
130113  **
130114  ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
130115  ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
130116  ** column iColRight of tab2.
130117  */
130118  static void addWhereTerm(
130119    Parse *pParse,                  /* Parsing context */
130120    SrcList *pSrc,                  /* List of tables in FROM clause */
130121    int iLeft,                      /* Index of first table to join in pSrc */
130122    int iColLeft,                   /* Index of column in first table */
130123    int iRight,                     /* Index of second table in pSrc */
130124    int iColRight,                  /* Index of column in second table */
130125    int isOuterJoin,                /* True if this is an OUTER join */
130126    Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
130127  ){
130128    sqlite3 *db = pParse->db;
130129    Expr *pE1;
130130    Expr *pE2;
130131    Expr *pEq;
130132  
130133    assert( iLeft<iRight );
130134    assert( pSrc->nSrc>iRight );
130135    assert( pSrc->a[iLeft].pTab );
130136    assert( pSrc->a[iRight].pTab );
130137  
130138    pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
130139    pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
130140  
130141    pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
130142    if( pEq && isOuterJoin ){
130143      ExprSetProperty(pEq, EP_FromJoin);
130144      assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
130145      ExprSetVVAProperty(pEq, EP_NoReduce);
130146      pEq->iRightJoinTable = (i16)pE2->iTable;
130147    }
130148    *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
130149  }
130150  
130151  /*
130152  ** Set the EP_FromJoin property on all terms of the given expression.
130153  ** And set the Expr.iRightJoinTable to iTable for every term in the
130154  ** expression.
130155  **
130156  ** The EP_FromJoin property is used on terms of an expression to tell
130157  ** the LEFT OUTER JOIN processing logic that this term is part of the
130158  ** join restriction specified in the ON or USING clause and not a part
130159  ** of the more general WHERE clause.  These terms are moved over to the
130160  ** WHERE clause during join processing but we need to remember that they
130161  ** originated in the ON or USING clause.
130162  **
130163  ** The Expr.iRightJoinTable tells the WHERE clause processing that the
130164  ** expression depends on table iRightJoinTable even if that table is not
130165  ** explicitly mentioned in the expression.  That information is needed
130166  ** for cases like this:
130167  **
130168  **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
130169  **
130170  ** The where clause needs to defer the handling of the t1.x=5
130171  ** term until after the t2 loop of the join.  In that way, a
130172  ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
130173  ** defer the handling of t1.x=5, it will be processed immediately
130174  ** after the t1 loop and rows with t1.x!=5 will never appear in
130175  ** the output, which is incorrect.
130176  */
130177  static void setJoinExpr(Expr *p, int iTable){
130178    while( p ){
130179      ExprSetProperty(p, EP_FromJoin);
130180      assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
130181      ExprSetVVAProperty(p, EP_NoReduce);
130182      p->iRightJoinTable = (i16)iTable;
130183      if( p->op==TK_FUNCTION && p->x.pList ){
130184        int i;
130185        for(i=0; i<p->x.pList->nExpr; i++){
130186          setJoinExpr(p->x.pList->a[i].pExpr, iTable);
130187        }
130188      }
130189      setJoinExpr(p->pLeft, iTable);
130190      p = p->pRight;
130191    } 
130192  }
130193  
130194  /* Undo the work of setJoinExpr().  In the expression tree p, convert every
130195  ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
130196  ** an ordinary term that omits the EP_FromJoin mark.
130197  **
130198  ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
130199  */
130200  static void unsetJoinExpr(Expr *p, int iTable){
130201    while( p ){
130202      if( ExprHasProperty(p, EP_FromJoin)
130203       && (iTable<0 || p->iRightJoinTable==iTable) ){
130204        ExprClearProperty(p, EP_FromJoin);
130205      }
130206      if( p->op==TK_FUNCTION && p->x.pList ){
130207        int i;
130208        for(i=0; i<p->x.pList->nExpr; i++){
130209          unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
130210        }
130211      }
130212      unsetJoinExpr(p->pLeft, iTable);
130213      p = p->pRight;
130214    } 
130215  }
130216  
130217  /*
130218  ** This routine processes the join information for a SELECT statement.
130219  ** ON and USING clauses are converted into extra terms of the WHERE clause.
130220  ** NATURAL joins also create extra WHERE clause terms.
130221  **
130222  ** The terms of a FROM clause are contained in the Select.pSrc structure.
130223  ** The left most table is the first entry in Select.pSrc.  The right-most
130224  ** table is the last entry.  The join operator is held in the entry to
130225  ** the left.  Thus entry 0 contains the join operator for the join between
130226  ** entries 0 and 1.  Any ON or USING clauses associated with the join are
130227  ** also attached to the left entry.
130228  **
130229  ** This routine returns the number of errors encountered.
130230  */
130231  static int sqliteProcessJoin(Parse *pParse, Select *p){
130232    SrcList *pSrc;                  /* All tables in the FROM clause */
130233    int i, j;                       /* Loop counters */
130234    struct SrcList_item *pLeft;     /* Left table being joined */
130235    struct SrcList_item *pRight;    /* Right table being joined */
130236  
130237    pSrc = p->pSrc;
130238    pLeft = &pSrc->a[0];
130239    pRight = &pLeft[1];
130240    for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
130241      Table *pRightTab = pRight->pTab;
130242      int isOuter;
130243  
130244      if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
130245      isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
130246  
130247      /* When the NATURAL keyword is present, add WHERE clause terms for
130248      ** every column that the two tables have in common.
130249      */
130250      if( pRight->fg.jointype & JT_NATURAL ){
130251        if( pRight->pOn || pRight->pUsing ){
130252          sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
130253             "an ON or USING clause", 0);
130254          return 1;
130255        }
130256        for(j=0; j<pRightTab->nCol; j++){
130257          char *zName;   /* Name of column in the right table */
130258          int iLeft;     /* Matching left table */
130259          int iLeftCol;  /* Matching column in the left table */
130260  
130261          zName = pRightTab->aCol[j].zName;
130262          if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
130263            addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
130264                         isOuter, &p->pWhere);
130265          }
130266        }
130267      }
130268  
130269      /* Disallow both ON and USING clauses in the same join
130270      */
130271      if( pRight->pOn && pRight->pUsing ){
130272        sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
130273          "clauses in the same join");
130274        return 1;
130275      }
130276  
130277      /* Add the ON clause to the end of the WHERE clause, connected by
130278      ** an AND operator.
130279      */
130280      if( pRight->pOn ){
130281        if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
130282        p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
130283        pRight->pOn = 0;
130284      }
130285  
130286      /* Create extra terms on the WHERE clause for each column named
130287      ** in the USING clause.  Example: If the two tables to be joined are 
130288      ** A and B and the USING clause names X, Y, and Z, then add this
130289      ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
130290      ** Report an error if any column mentioned in the USING clause is
130291      ** not contained in both tables to be joined.
130292      */
130293      if( pRight->pUsing ){
130294        IdList *pList = pRight->pUsing;
130295        for(j=0; j<pList->nId; j++){
130296          char *zName;     /* Name of the term in the USING clause */
130297          int iLeft;       /* Table on the left with matching column name */
130298          int iLeftCol;    /* Column number of matching column on the left */
130299          int iRightCol;   /* Column number of matching column on the right */
130300  
130301          zName = pList->a[j].zName;
130302          iRightCol = columnIndex(pRightTab, zName);
130303          if( iRightCol<0
130304           || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
130305          ){
130306            sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
130307              "not present in both tables", zName);
130308            return 1;
130309          }
130310          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
130311                       isOuter, &p->pWhere);
130312        }
130313      }
130314    }
130315    return 0;
130316  }
130317  
130318  /*
130319  ** An instance of this object holds information (beyond pParse and pSelect)
130320  ** needed to load the next result row that is to be added to the sorter.
130321  */
130322  typedef struct RowLoadInfo RowLoadInfo;
130323  struct RowLoadInfo {
130324    int regResult;               /* Store results in array of registers here */
130325    u8 ecelFlags;                /* Flag argument to ExprCodeExprList() */
130326  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130327    ExprList *pExtra;            /* Extra columns needed by sorter refs */
130328    int regExtraResult;          /* Where to load the extra columns */
130329  #endif
130330  };
130331  
130332  /*
130333  ** This routine does the work of loading query data into an array of
130334  ** registers so that it can be added to the sorter.
130335  */
130336  static void innerLoopLoadRow(
130337    Parse *pParse,             /* Statement under construction */
130338    Select *pSelect,           /* The query being coded */
130339    RowLoadInfo *pInfo         /* Info needed to complete the row load */
130340  ){
130341    sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
130342                            0, pInfo->ecelFlags);
130343  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130344    if( pInfo->pExtra ){
130345      sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
130346      sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
130347    }
130348  #endif
130349  }
130350  
130351  /*
130352  ** Code the OP_MakeRecord instruction that generates the entry to be
130353  ** added into the sorter.
130354  **
130355  ** Return the register in which the result is stored.
130356  */
130357  static int makeSorterRecord(
130358    Parse *pParse,
130359    SortCtx *pSort,
130360    Select *pSelect,
130361    int regBase,
130362    int nBase
130363  ){
130364    int nOBSat = pSort->nOBSat;
130365    Vdbe *v = pParse->pVdbe;
130366    int regOut = ++pParse->nMem;
130367    if( pSort->pDeferredRowLoad ){
130368      innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
130369    }
130370    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
130371    return regOut;
130372  }
130373  
130374  /*
130375  ** Generate code that will push the record in registers regData
130376  ** through regData+nData-1 onto the sorter.
130377  */
130378  static void pushOntoSorter(
130379    Parse *pParse,         /* Parser context */
130380    SortCtx *pSort,        /* Information about the ORDER BY clause */
130381    Select *pSelect,       /* The whole SELECT statement */
130382    int regData,           /* First register holding data to be sorted */
130383    int regOrigData,       /* First register holding data before packing */
130384    int nData,             /* Number of elements in the regData data array */
130385    int nPrefixReg         /* No. of reg prior to regData available for use */
130386  ){
130387    Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
130388    int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
130389    int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
130390    int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
130391    int regBase;                                     /* Regs for sorter record */
130392    int regRecord = 0;                               /* Assembled sorter record */
130393    int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
130394    int op;                            /* Opcode to add sorter record to sorter */
130395    int iLimit;                        /* LIMIT counter */
130396    int iSkip = 0;                     /* End of the sorter insert loop */
130397  
130398    assert( bSeq==0 || bSeq==1 );
130399  
130400    /* Three cases:
130401    **   (1) The data to be sorted has already been packed into a Record
130402    **       by a prior OP_MakeRecord.  In this case nData==1 and regData
130403    **       will be completely unrelated to regOrigData.
130404    **   (2) All output columns are included in the sort record.  In that
130405    **       case regData==regOrigData.
130406    **   (3) Some output columns are omitted from the sort record due to
130407    **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
130408    **       SQLITE_ECEL_OMITREF optimization, or due to the 
130409    **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
130410    **       regOrigData is 0 to prevent this routine from trying to copy
130411    **       values that might not yet exist.
130412    */
130413    assert( nData==1 || regData==regOrigData || regOrigData==0 );
130414  
130415    if( nPrefixReg ){
130416      assert( nPrefixReg==nExpr+bSeq );
130417      regBase = regData - nPrefixReg;
130418    }else{
130419      regBase = pParse->nMem + 1;
130420      pParse->nMem += nBase;
130421    }
130422    assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
130423    iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
130424    pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
130425    sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
130426                            SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
130427    if( bSeq ){
130428      sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
130429    }
130430    if( nPrefixReg==0 && nData>0 ){
130431      sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
130432    }
130433    if( nOBSat>0 ){
130434      int regPrevKey;   /* The first nOBSat columns of the previous row */
130435      int addrFirst;    /* Address of the OP_IfNot opcode */
130436      int addrJmp;      /* Address of the OP_Jump opcode */
130437      VdbeOp *pOp;      /* Opcode that opens the sorter */
130438      int nKey;         /* Number of sorting key columns, including OP_Sequence */
130439      KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
130440  
130441      regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
130442      regPrevKey = pParse->nMem+1;
130443      pParse->nMem += pSort->nOBSat;
130444      nKey = nExpr - pSort->nOBSat + bSeq;
130445      if( bSeq ){
130446        addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
130447      }else{
130448        addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
130449      }
130450      VdbeCoverage(v);
130451      sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
130452      pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
130453      if( pParse->db->mallocFailed ) return;
130454      pOp->p2 = nKey + nData;
130455      pKI = pOp->p4.pKeyInfo;
130456      memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
130457      sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
130458      testcase( pKI->nAllField > pKI->nKeyField+2 );
130459      pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
130460                                             pKI->nAllField-pKI->nKeyField-1);
130461      addrJmp = sqlite3VdbeCurrentAddr(v);
130462      sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
130463      pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
130464      pSort->regReturn = ++pParse->nMem;
130465      sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
130466      sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
130467      if( iLimit ){
130468        sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
130469        VdbeCoverage(v);
130470      }
130471      sqlite3VdbeJumpHere(v, addrFirst);
130472      sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
130473      sqlite3VdbeJumpHere(v, addrJmp);
130474    }
130475    if( iLimit ){
130476      /* At this point the values for the new sorter entry are stored
130477      ** in an array of registers. They need to be composed into a record
130478      ** and inserted into the sorter if either (a) there are currently
130479      ** less than LIMIT+OFFSET items or (b) the new record is smaller than 
130480      ** the largest record currently in the sorter. If (b) is true and there
130481      ** are already LIMIT+OFFSET items in the sorter, delete the largest
130482      ** entry before inserting the new one. This way there are never more 
130483      ** than LIMIT+OFFSET items in the sorter.
130484      **
130485      ** If the new record does not need to be inserted into the sorter,
130486      ** jump to the next iteration of the loop. If the pSort->labelOBLopt
130487      ** value is not zero, then it is a label of where to jump.  Otherwise,
130488      ** just bypass the row insert logic.  See the header comment on the
130489      ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
130490      */
130491      int iCsr = pSort->iECursor;
130492      sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
130493      VdbeCoverage(v);
130494      sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
130495      iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
130496                                   iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
130497      VdbeCoverage(v);
130498      sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
130499    }
130500    if( regRecord==0 ){
130501      regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
130502    }
130503    if( pSort->sortFlags & SORTFLAG_UseSorter ){
130504      op = OP_SorterInsert;
130505    }else{
130506      op = OP_IdxInsert;
130507    }
130508    sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
130509                         regBase+nOBSat, nBase-nOBSat);
130510    if( iSkip ){
130511      sqlite3VdbeChangeP2(v, iSkip,
130512           pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
130513    }
130514  }
130515  
130516  /*
130517  ** Add code to implement the OFFSET
130518  */
130519  static void codeOffset(
130520    Vdbe *v,          /* Generate code into this VM */
130521    int iOffset,      /* Register holding the offset counter */
130522    int iContinue     /* Jump here to skip the current record */
130523  ){
130524    if( iOffset>0 ){
130525      sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
130526      VdbeComment((v, "OFFSET"));
130527    }
130528  }
130529  
130530  /*
130531  ** Add code that will check to make sure the N registers starting at iMem
130532  ** form a distinct entry.  iTab is a sorting index that holds previously
130533  ** seen combinations of the N values.  A new entry is made in iTab
130534  ** if the current N values are new.
130535  **
130536  ** A jump to addrRepeat is made and the N+1 values are popped from the
130537  ** stack if the top N elements are not distinct.
130538  */
130539  static void codeDistinct(
130540    Parse *pParse,     /* Parsing and code generating context */
130541    int iTab,          /* A sorting index used to test for distinctness */
130542    int addrRepeat,    /* Jump to here if not distinct */
130543    int N,             /* Number of elements */
130544    int iMem           /* First element */
130545  ){
130546    Vdbe *v;
130547    int r1;
130548  
130549    v = pParse->pVdbe;
130550    r1 = sqlite3GetTempReg(pParse);
130551    sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
130552    sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
130553    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
130554    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
130555    sqlite3ReleaseTempReg(pParse, r1);
130556  }
130557  
130558  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130559  /*
130560  ** This function is called as part of inner-loop generation for a SELECT
130561  ** statement with an ORDER BY that is not optimized by an index. It 
130562  ** determines the expressions, if any, that the sorter-reference 
130563  ** optimization should be used for. The sorter-reference optimization
130564  ** is used for SELECT queries like:
130565  **
130566  **   SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
130567  **
130568  ** If the optimization is used for expression "bigblob", then instead of
130569  ** storing values read from that column in the sorter records, the PK of
130570  ** the row from table t1 is stored instead. Then, as records are extracted from
130571  ** the sorter to return to the user, the required value of bigblob is
130572  ** retrieved directly from table t1. If the values are very large, this 
130573  ** can be more efficient than storing them directly in the sorter records.
130574  **
130575  ** The ExprList_item.bSorterRef flag is set for each expression in pEList 
130576  ** for which the sorter-reference optimization should be enabled. 
130577  ** Additionally, the pSort->aDefer[] array is populated with entries
130578  ** for all cursors required to evaluate all selected expressions. Finally.
130579  ** output variable (*ppExtra) is set to an expression list containing
130580  ** expressions for all extra PK values that should be stored in the
130581  ** sorter records.
130582  */
130583  static void selectExprDefer(
130584    Parse *pParse,                  /* Leave any error here */
130585    SortCtx *pSort,                 /* Sorter context */
130586    ExprList *pEList,               /* Expressions destined for sorter */
130587    ExprList **ppExtra              /* Expressions to append to sorter record */
130588  ){
130589    int i;
130590    int nDefer = 0;
130591    ExprList *pExtra = 0;
130592    for(i=0; i<pEList->nExpr; i++){
130593      struct ExprList_item *pItem = &pEList->a[i];
130594      if( pItem->u.x.iOrderByCol==0 ){
130595        Expr *pExpr = pItem->pExpr;
130596        Table *pTab = pExpr->y.pTab;
130597        if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
130598         && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
130599        ){
130600          int j;
130601          for(j=0; j<nDefer; j++){
130602            if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
130603          }
130604          if( j==nDefer ){
130605            if( nDefer==ArraySize(pSort->aDefer) ){
130606              continue;
130607            }else{
130608              int nKey = 1;
130609              int k;
130610              Index *pPk = 0;
130611              if( !HasRowid(pTab) ){
130612                pPk = sqlite3PrimaryKeyIndex(pTab);
130613                nKey = pPk->nKeyCol;
130614              }
130615              for(k=0; k<nKey; k++){
130616                Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
130617                if( pNew ){
130618                  pNew->iTable = pExpr->iTable;
130619                  pNew->y.pTab = pExpr->y.pTab;
130620                  pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
130621                  pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
130622                }
130623              }
130624              pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
130625              pSort->aDefer[nDefer].iCsr = pExpr->iTable;
130626              pSort->aDefer[nDefer].nKey = nKey;
130627              nDefer++;
130628            }
130629          }
130630          pItem->bSorterRef = 1;
130631        }
130632      }
130633    }
130634    pSort->nDefer = (u8)nDefer;
130635    *ppExtra = pExtra;
130636  }
130637  #endif
130638  
130639  /*
130640  ** This routine generates the code for the inside of the inner loop
130641  ** of a SELECT.
130642  **
130643  ** If srcTab is negative, then the p->pEList expressions
130644  ** are evaluated in order to get the data for this row.  If srcTab is
130645  ** zero or more, then data is pulled from srcTab and p->pEList is used only 
130646  ** to get the number of columns and the collation sequence for each column.
130647  */
130648  static void selectInnerLoop(
130649    Parse *pParse,          /* The parser context */
130650    Select *p,              /* The complete select statement being coded */
130651    int srcTab,             /* Pull data from this table if non-negative */
130652    SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
130653    DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
130654    SelectDest *pDest,      /* How to dispose of the results */
130655    int iContinue,          /* Jump here to continue with next row */
130656    int iBreak              /* Jump here to break out of the inner loop */
130657  ){
130658    Vdbe *v = pParse->pVdbe;
130659    int i;
130660    int hasDistinct;            /* True if the DISTINCT keyword is present */
130661    int eDest = pDest->eDest;   /* How to dispose of results */
130662    int iParm = pDest->iSDParm; /* First argument to disposal method */
130663    int nResultCol;             /* Number of result columns */
130664    int nPrefixReg = 0;         /* Number of extra registers before regResult */
130665    RowLoadInfo sRowLoadInfo;   /* Info for deferred row loading */
130666  
130667    /* Usually, regResult is the first cell in an array of memory cells
130668    ** containing the current result row. In this case regOrig is set to the
130669    ** same value. However, if the results are being sent to the sorter, the
130670    ** values for any expressions that are also part of the sort-key are omitted
130671    ** from this array. In this case regOrig is set to zero.  */
130672    int regResult;              /* Start of memory holding current results */
130673    int regOrig;                /* Start of memory holding full result (or 0) */
130674  
130675    assert( v );
130676    assert( p->pEList!=0 );
130677    hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
130678    if( pSort && pSort->pOrderBy==0 ) pSort = 0;
130679    if( pSort==0 && !hasDistinct ){
130680      assert( iContinue!=0 );
130681      codeOffset(v, p->iOffset, iContinue);
130682    }
130683  
130684    /* Pull the requested columns.
130685    */
130686    nResultCol = p->pEList->nExpr;
130687  
130688    if( pDest->iSdst==0 ){
130689      if( pSort ){
130690        nPrefixReg = pSort->pOrderBy->nExpr;
130691        if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
130692        pParse->nMem += nPrefixReg;
130693      }
130694      pDest->iSdst = pParse->nMem+1;
130695      pParse->nMem += nResultCol;
130696    }else if( pDest->iSdst+nResultCol > pParse->nMem ){
130697      /* This is an error condition that can result, for example, when a SELECT
130698      ** on the right-hand side of an INSERT contains more result columns than
130699      ** there are columns in the table on the left.  The error will be caught
130700      ** and reported later.  But we need to make sure enough memory is allocated
130701      ** to avoid other spurious errors in the meantime. */
130702      pParse->nMem += nResultCol;
130703    }
130704    pDest->nSdst = nResultCol;
130705    regOrig = regResult = pDest->iSdst;
130706    if( srcTab>=0 ){
130707      for(i=0; i<nResultCol; i++){
130708        sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
130709        VdbeComment((v, "%s", p->pEList->a[i].zName));
130710      }
130711    }else if( eDest!=SRT_Exists ){
130712  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130713      ExprList *pExtra = 0;
130714  #endif
130715      /* If the destination is an EXISTS(...) expression, the actual
130716      ** values returned by the SELECT are not required.
130717      */
130718      u8 ecelFlags;    /* "ecel" is an abbreviation of "ExprCodeExprList" */
130719      ExprList *pEList;
130720      if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
130721        ecelFlags = SQLITE_ECEL_DUP;
130722      }else{
130723        ecelFlags = 0;
130724      }
130725      if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
130726        /* For each expression in p->pEList that is a copy of an expression in
130727        ** the ORDER BY clause (pSort->pOrderBy), set the associated 
130728        ** iOrderByCol value to one more than the index of the ORDER BY 
130729        ** expression within the sort-key that pushOntoSorter() will generate.
130730        ** This allows the p->pEList field to be omitted from the sorted record,
130731        ** saving space and CPU cycles.  */
130732        ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
130733  
130734        for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
130735          int j;
130736          if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
130737            p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
130738          }
130739        }
130740  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130741        selectExprDefer(pParse, pSort, p->pEList, &pExtra);
130742        if( pExtra && pParse->db->mallocFailed==0 ){
130743          /* If there are any extra PK columns to add to the sorter records,
130744          ** allocate extra memory cells and adjust the OpenEphemeral 
130745          ** instruction to account for the larger records. This is only
130746          ** required if there are one or more WITHOUT ROWID tables with
130747          ** composite primary keys in the SortCtx.aDefer[] array.  */
130748          VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
130749          pOp->p2 += (pExtra->nExpr - pSort->nDefer);
130750          pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
130751          pParse->nMem += pExtra->nExpr;
130752        }
130753  #endif
130754  
130755        /* Adjust nResultCol to account for columns that are omitted
130756        ** from the sorter by the optimizations in this branch */
130757        pEList = p->pEList;
130758        for(i=0; i<pEList->nExpr; i++){
130759          if( pEList->a[i].u.x.iOrderByCol>0
130760  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130761           || pEList->a[i].bSorterRef
130762  #endif
130763          ){
130764            nResultCol--;
130765            regOrig = 0;
130766          }
130767        }
130768  
130769        testcase( regOrig );
130770        testcase( eDest==SRT_Set );
130771        testcase( eDest==SRT_Mem );
130772        testcase( eDest==SRT_Coroutine );
130773        testcase( eDest==SRT_Output );
130774        assert( eDest==SRT_Set || eDest==SRT_Mem 
130775             || eDest==SRT_Coroutine || eDest==SRT_Output );
130776      }
130777      sRowLoadInfo.regResult = regResult;
130778      sRowLoadInfo.ecelFlags = ecelFlags;
130779  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
130780      sRowLoadInfo.pExtra = pExtra;
130781      sRowLoadInfo.regExtraResult = regResult + nResultCol;
130782      if( pExtra ) nResultCol += pExtra->nExpr;
130783  #endif
130784      if( p->iLimit
130785       && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 
130786       && nPrefixReg>0
130787      ){
130788        assert( pSort!=0 );
130789        assert( hasDistinct==0 );
130790        pSort->pDeferredRowLoad = &sRowLoadInfo;
130791        regOrig = 0;
130792      }else{
130793        innerLoopLoadRow(pParse, p, &sRowLoadInfo);
130794      }
130795    }
130796  
130797    /* If the DISTINCT keyword was present on the SELECT statement
130798    ** and this row has been seen before, then do not make this row
130799    ** part of the result.
130800    */
130801    if( hasDistinct ){
130802      switch( pDistinct->eTnctType ){
130803        case WHERE_DISTINCT_ORDERED: {
130804          VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
130805          int iJump;              /* Jump destination */
130806          int regPrev;            /* Previous row content */
130807  
130808          /* Allocate space for the previous row */
130809          regPrev = pParse->nMem+1;
130810          pParse->nMem += nResultCol;
130811  
130812          /* Change the OP_OpenEphemeral coded earlier to an OP_Null
130813          ** sets the MEM_Cleared bit on the first register of the
130814          ** previous value.  This will cause the OP_Ne below to always
130815          ** fail on the first iteration of the loop even if the first
130816          ** row is all NULLs.
130817          */
130818          sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
130819          pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
130820          pOp->opcode = OP_Null;
130821          pOp->p1 = 1;
130822          pOp->p2 = regPrev;
130823  
130824          iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
130825          for(i=0; i<nResultCol; i++){
130826            CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
130827            if( i<nResultCol-1 ){
130828              sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
130829              VdbeCoverage(v);
130830            }else{
130831              sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
130832              VdbeCoverage(v);
130833             }
130834            sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
130835            sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
130836          }
130837          assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
130838          sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
130839          break;
130840        }
130841  
130842        case WHERE_DISTINCT_UNIQUE: {
130843          sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
130844          break;
130845        }
130846  
130847        default: {
130848          assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
130849          codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
130850                       regResult);
130851          break;
130852        }
130853      }
130854      if( pSort==0 ){
130855        codeOffset(v, p->iOffset, iContinue);
130856      }
130857    }
130858  
130859    switch( eDest ){
130860      /* In this mode, write each query result to the key of the temporary
130861      ** table iParm.
130862      */
130863  #ifndef SQLITE_OMIT_COMPOUND_SELECT
130864      case SRT_Union: {
130865        int r1;
130866        r1 = sqlite3GetTempReg(pParse);
130867        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
130868        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
130869        sqlite3ReleaseTempReg(pParse, r1);
130870        break;
130871      }
130872  
130873      /* Construct a record from the query result, but instead of
130874      ** saving that record, use it as a key to delete elements from
130875      ** the temporary table iParm.
130876      */
130877      case SRT_Except: {
130878        sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
130879        break;
130880      }
130881  #endif /* SQLITE_OMIT_COMPOUND_SELECT */
130882  
130883      /* Store the result as data using a unique key.
130884      */
130885      case SRT_Fifo:
130886      case SRT_DistFifo:
130887      case SRT_Table:
130888      case SRT_EphemTab: {
130889        int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
130890        testcase( eDest==SRT_Table );
130891        testcase( eDest==SRT_EphemTab );
130892        testcase( eDest==SRT_Fifo );
130893        testcase( eDest==SRT_DistFifo );
130894        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
130895  #ifndef SQLITE_OMIT_CTE
130896        if( eDest==SRT_DistFifo ){
130897          /* If the destination is DistFifo, then cursor (iParm+1) is open
130898          ** on an ephemeral index. If the current row is already present
130899          ** in the index, do not write it to the output. If not, add the
130900          ** current row to the index and proceed with writing it to the
130901          ** output table as well.  */
130902          int addr = sqlite3VdbeCurrentAddr(v) + 4;
130903          sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
130904          VdbeCoverage(v);
130905          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
130906          assert( pSort==0 );
130907        }
130908  #endif
130909        if( pSort ){
130910          assert( regResult==regOrig );
130911          pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
130912        }else{
130913          int r2 = sqlite3GetTempReg(pParse);
130914          sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
130915          sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
130916          sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
130917          sqlite3ReleaseTempReg(pParse, r2);
130918        }
130919        sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
130920        break;
130921      }
130922  
130923  #ifndef SQLITE_OMIT_SUBQUERY
130924      /* If we are creating a set for an "expr IN (SELECT ...)" construct,
130925      ** then there should be a single item on the stack.  Write this
130926      ** item into the set table with bogus data.
130927      */
130928      case SRT_Set: {
130929        if( pSort ){
130930          /* At first glance you would think we could optimize out the
130931          ** ORDER BY in this case since the order of entries in the set
130932          ** does not matter.  But there might be a LIMIT clause, in which
130933          ** case the order does matter */
130934          pushOntoSorter(
130935              pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
130936        }else{
130937          int r1 = sqlite3GetTempReg(pParse);
130938          assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
130939          sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 
130940              r1, pDest->zAffSdst, nResultCol);
130941          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
130942          sqlite3ReleaseTempReg(pParse, r1);
130943        }
130944        break;
130945      }
130946  
130947      /* If any row exist in the result set, record that fact and abort.
130948      */
130949      case SRT_Exists: {
130950        sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
130951        /* The LIMIT clause will terminate the loop for us */
130952        break;
130953      }
130954  
130955      /* If this is a scalar select that is part of an expression, then
130956      ** store the results in the appropriate memory cell or array of 
130957      ** memory cells and break out of the scan loop.
130958      */
130959      case SRT_Mem: {
130960        if( pSort ){
130961          assert( nResultCol<=pDest->nSdst );
130962          pushOntoSorter(
130963              pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
130964        }else{
130965          assert( nResultCol==pDest->nSdst );
130966          assert( regResult==iParm );
130967          /* The LIMIT clause will jump out of the loop for us */
130968        }
130969        break;
130970      }
130971  #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
130972  
130973      case SRT_Coroutine:       /* Send data to a co-routine */
130974      case SRT_Output: {        /* Return the results */
130975        testcase( eDest==SRT_Coroutine );
130976        testcase( eDest==SRT_Output );
130977        if( pSort ){
130978          pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
130979                         nPrefixReg);
130980        }else if( eDest==SRT_Coroutine ){
130981          sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
130982        }else{
130983          sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
130984        }
130985        break;
130986      }
130987  
130988  #ifndef SQLITE_OMIT_CTE
130989      /* Write the results into a priority queue that is order according to
130990      ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
130991      ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
130992      ** pSO->nExpr columns, then make sure all keys are unique by adding a
130993      ** final OP_Sequence column.  The last column is the record as a blob.
130994      */
130995      case SRT_DistQueue:
130996      case SRT_Queue: {
130997        int nKey;
130998        int r1, r2, r3;
130999        int addrTest = 0;
131000        ExprList *pSO;
131001        pSO = pDest->pOrderBy;
131002        assert( pSO );
131003        nKey = pSO->nExpr;
131004        r1 = sqlite3GetTempReg(pParse);
131005        r2 = sqlite3GetTempRange(pParse, nKey+2);
131006        r3 = r2+nKey+1;
131007        if( eDest==SRT_DistQueue ){
131008          /* If the destination is DistQueue, then cursor (iParm+1) is open
131009          ** on a second ephemeral index that holds all values every previously
131010          ** added to the queue. */
131011          addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
131012                                          regResult, nResultCol);
131013          VdbeCoverage(v);
131014        }
131015        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
131016        if( eDest==SRT_DistQueue ){
131017          sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
131018          sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
131019        }
131020        for(i=0; i<nKey; i++){
131021          sqlite3VdbeAddOp2(v, OP_SCopy,
131022                            regResult + pSO->a[i].u.x.iOrderByCol - 1,
131023                            r2+i);
131024        }
131025        sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
131026        sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
131027        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
131028        if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
131029        sqlite3ReleaseTempReg(pParse, r1);
131030        sqlite3ReleaseTempRange(pParse, r2, nKey+2);
131031        break;
131032      }
131033  #endif /* SQLITE_OMIT_CTE */
131034  
131035  
131036  
131037  #if !defined(SQLITE_OMIT_TRIGGER)
131038      /* Discard the results.  This is used for SELECT statements inside
131039      ** the body of a TRIGGER.  The purpose of such selects is to call
131040      ** user-defined functions that have side effects.  We do not care
131041      ** about the actual results of the select.
131042      */
131043      default: {
131044        assert( eDest==SRT_Discard );
131045        break;
131046      }
131047  #endif
131048    }
131049  
131050    /* Jump to the end of the loop if the LIMIT is reached.  Except, if
131051    ** there is a sorter, in which case the sorter has already limited
131052    ** the output for us.
131053    */
131054    if( pSort==0 && p->iLimit ){
131055      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
131056    }
131057  }
131058  
131059  /*
131060  ** Allocate a KeyInfo object sufficient for an index of N key columns and
131061  ** X extra columns.
131062  */
131063  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
131064    int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
131065    KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
131066    if( p ){
131067      p->aSortOrder = (u8*)&p->aColl[N+X];
131068      p->nKeyField = (u16)N;
131069      p->nAllField = (u16)(N+X);
131070      p->enc = ENC(db);
131071      p->db = db;
131072      p->nRef = 1;
131073      memset(&p[1], 0, nExtra);
131074    }else{
131075      sqlite3OomFault(db);
131076    }
131077    return p;
131078  }
131079  
131080  /*
131081  ** Deallocate a KeyInfo object
131082  */
131083  SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
131084    if( p ){
131085      assert( p->nRef>0 );
131086      p->nRef--;
131087      if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
131088    }
131089  }
131090  
131091  /*
131092  ** Make a new pointer to a KeyInfo object
131093  */
131094  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
131095    if( p ){
131096      assert( p->nRef>0 );
131097      p->nRef++;
131098    }
131099    return p;
131100  }
131101  
131102  #ifdef SQLITE_DEBUG
131103  /*
131104  ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
131105  ** can only be changed if this is just a single reference to the object.
131106  **
131107  ** This routine is used only inside of assert() statements.
131108  */
131109  SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
131110  #endif /* SQLITE_DEBUG */
131111  
131112  /*
131113  ** Given an expression list, generate a KeyInfo structure that records
131114  ** the collating sequence for each expression in that expression list.
131115  **
131116  ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
131117  ** KeyInfo structure is appropriate for initializing a virtual index to
131118  ** implement that clause.  If the ExprList is the result set of a SELECT
131119  ** then the KeyInfo structure is appropriate for initializing a virtual
131120  ** index to implement a DISTINCT test.
131121  **
131122  ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
131123  ** function is responsible for seeing that this structure is eventually
131124  ** freed.
131125  */
131126  SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
131127    Parse *pParse,       /* Parsing context */
131128    ExprList *pList,     /* Form the KeyInfo object from this ExprList */
131129    int iStart,          /* Begin with this column of pList */
131130    int nExtra           /* Add this many extra columns to the end */
131131  ){
131132    int nExpr;
131133    KeyInfo *pInfo;
131134    struct ExprList_item *pItem;
131135    sqlite3 *db = pParse->db;
131136    int i;
131137  
131138    nExpr = pList->nExpr;
131139    pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
131140    if( pInfo ){
131141      assert( sqlite3KeyInfoIsWriteable(pInfo) );
131142      for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
131143        pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
131144        pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
131145      }
131146    }
131147    return pInfo;
131148  }
131149  
131150  /*
131151  ** Name of the connection operator, used for error messages.
131152  */
131153  static const char *selectOpName(int id){
131154    char *z;
131155    switch( id ){
131156      case TK_ALL:       z = "UNION ALL";   break;
131157      case TK_INTERSECT: z = "INTERSECT";   break;
131158      case TK_EXCEPT:    z = "EXCEPT";      break;
131159      default:           z = "UNION";       break;
131160    }
131161    return z;
131162  }
131163  
131164  #ifndef SQLITE_OMIT_EXPLAIN
131165  /*
131166  ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
131167  ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
131168  ** where the caption is of the form:
131169  **
131170  **   "USE TEMP B-TREE FOR xxx"
131171  **
131172  ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
131173  ** is determined by the zUsage argument.
131174  */
131175  static void explainTempTable(Parse *pParse, const char *zUsage){
131176    ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
131177  }
131178  
131179  /*
131180  ** Assign expression b to lvalue a. A second, no-op, version of this macro
131181  ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
131182  ** in sqlite3Select() to assign values to structure member variables that
131183  ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
131184  ** code with #ifndef directives.
131185  */
131186  # define explainSetInteger(a, b) a = b
131187  
131188  #else
131189  /* No-op versions of the explainXXX() functions and macros. */
131190  # define explainTempTable(y,z)
131191  # define explainSetInteger(y,z)
131192  #endif
131193  
131194  
131195  /*
131196  ** If the inner loop was generated using a non-null pOrderBy argument,
131197  ** then the results were placed in a sorter.  After the loop is terminated
131198  ** we need to run the sorter and output the results.  The following
131199  ** routine generates the code needed to do that.
131200  */
131201  static void generateSortTail(
131202    Parse *pParse,    /* Parsing context */
131203    Select *p,        /* The SELECT statement */
131204    SortCtx *pSort,   /* Information on the ORDER BY clause */
131205    int nColumn,      /* Number of columns of data */
131206    SelectDest *pDest /* Write the sorted results here */
131207  ){
131208    Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
131209    int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
131210    int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
131211    int addr;                       /* Top of output loop. Jump for Next. */
131212    int addrOnce = 0;
131213    int iTab;
131214    ExprList *pOrderBy = pSort->pOrderBy;
131215    int eDest = pDest->eDest;
131216    int iParm = pDest->iSDParm;
131217    int regRow;
131218    int regRowid;
131219    int iCol;
131220    int nKey;                       /* Number of key columns in sorter record */
131221    int iSortTab;                   /* Sorter cursor to read from */
131222    int i;
131223    int bSeq;                       /* True if sorter record includes seq. no. */
131224    int nRefKey = 0;
131225    struct ExprList_item *aOutEx = p->pEList->a;
131226  
131227    assert( addrBreak<0 );
131228    if( pSort->labelBkOut ){
131229      sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
131230      sqlite3VdbeGoto(v, addrBreak);
131231      sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
131232    }
131233  
131234  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
131235    /* Open any cursors needed for sorter-reference expressions */
131236    for(i=0; i<pSort->nDefer; i++){
131237      Table *pTab = pSort->aDefer[i].pTab;
131238      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
131239      sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
131240      nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
131241    }
131242  #endif
131243  
131244    iTab = pSort->iECursor;
131245    if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
131246      regRowid = 0;
131247      regRow = pDest->iSdst;
131248    }else{
131249      regRowid = sqlite3GetTempReg(pParse);
131250      if( eDest==SRT_EphemTab || eDest==SRT_Table ){
131251        regRow = sqlite3GetTempReg(pParse);
131252        nColumn = 0;
131253      }else{
131254        regRow = sqlite3GetTempRange(pParse, nColumn);
131255      }
131256    }
131257    nKey = pOrderBy->nExpr - pSort->nOBSat;
131258    if( pSort->sortFlags & SORTFLAG_UseSorter ){
131259      int regSortOut = ++pParse->nMem;
131260      iSortTab = pParse->nTab++;
131261      if( pSort->labelBkOut ){
131262        addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
131263      }
131264      sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 
131265          nKey+1+nColumn+nRefKey);
131266      if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
131267      addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
131268      VdbeCoverage(v);
131269      codeOffset(v, p->iOffset, addrContinue);
131270      sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
131271      bSeq = 0;
131272    }else{
131273      addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
131274      codeOffset(v, p->iOffset, addrContinue);
131275      iSortTab = iTab;
131276      bSeq = 1;
131277    }
131278    for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
131279  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
131280      if( aOutEx[i].bSorterRef ) continue;
131281  #endif
131282      if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
131283    }
131284  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
131285    if( pSort->nDefer ){
131286      int iKey = iCol+1;
131287      int regKey = sqlite3GetTempRange(pParse, nRefKey);
131288  
131289      for(i=0; i<pSort->nDefer; i++){
131290        int iCsr = pSort->aDefer[i].iCsr;
131291        Table *pTab = pSort->aDefer[i].pTab;
131292        int nKey = pSort->aDefer[i].nKey;
131293  
131294        sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
131295        if( HasRowid(pTab) ){
131296          sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
131297          sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 
131298              sqlite3VdbeCurrentAddr(v)+1, regKey);
131299        }else{
131300          int k;
131301          int iJmp;
131302          assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
131303          for(k=0; k<nKey; k++){
131304            sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
131305          }
131306          iJmp = sqlite3VdbeCurrentAddr(v);
131307          sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
131308          sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
131309          sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
131310        }
131311      }
131312      sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
131313    }
131314  #endif
131315    for(i=nColumn-1; i>=0; i--){
131316  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
131317      if( aOutEx[i].bSorterRef ){
131318        sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
131319      }else
131320  #endif
131321      {
131322        int iRead;
131323        if( aOutEx[i].u.x.iOrderByCol ){
131324          iRead = aOutEx[i].u.x.iOrderByCol-1;
131325        }else{
131326          iRead = iCol--;
131327        }
131328        sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
131329        VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
131330      }
131331    }
131332    switch( eDest ){
131333      case SRT_Table:
131334      case SRT_EphemTab: {
131335        sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
131336        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
131337        sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
131338        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
131339        break;
131340      }
131341  #ifndef SQLITE_OMIT_SUBQUERY
131342      case SRT_Set: {
131343        assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
131344        sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
131345                          pDest->zAffSdst, nColumn);
131346        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
131347        break;
131348      }
131349      case SRT_Mem: {
131350        /* The LIMIT clause will terminate the loop for us */
131351        break;
131352      }
131353  #endif
131354      default: {
131355        assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
131356        testcase( eDest==SRT_Output );
131357        testcase( eDest==SRT_Coroutine );
131358        if( eDest==SRT_Output ){
131359          sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
131360        }else{
131361          sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
131362        }
131363        break;
131364      }
131365    }
131366    if( regRowid ){
131367      if( eDest==SRT_Set ){
131368        sqlite3ReleaseTempRange(pParse, regRow, nColumn);
131369      }else{
131370        sqlite3ReleaseTempReg(pParse, regRow);
131371      }
131372      sqlite3ReleaseTempReg(pParse, regRowid);
131373    }
131374    /* The bottom of the loop
131375    */
131376    sqlite3VdbeResolveLabel(v, addrContinue);
131377    if( pSort->sortFlags & SORTFLAG_UseSorter ){
131378      sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
131379    }else{
131380      sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
131381    }
131382    if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
131383    sqlite3VdbeResolveLabel(v, addrBreak);
131384  }
131385  
131386  /*
131387  ** Return a pointer to a string containing the 'declaration type' of the
131388  ** expression pExpr. The string may be treated as static by the caller.
131389  **
131390  ** Also try to estimate the size of the returned value and return that
131391  ** result in *pEstWidth.
131392  **
131393  ** The declaration type is the exact datatype definition extracted from the
131394  ** original CREATE TABLE statement if the expression is a column. The
131395  ** declaration type for a ROWID field is INTEGER. Exactly when an expression
131396  ** is considered a column can be complex in the presence of subqueries. The
131397  ** result-set expression in all of the following SELECT statements is 
131398  ** considered a column by this function.
131399  **
131400  **   SELECT col FROM tbl;
131401  **   SELECT (SELECT col FROM tbl;
131402  **   SELECT (SELECT col FROM tbl);
131403  **   SELECT abc FROM (SELECT col AS abc FROM tbl);
131404  ** 
131405  ** The declaration type for any expression other than a column is NULL.
131406  **
131407  ** This routine has either 3 or 6 parameters depending on whether or not
131408  ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
131409  */
131410  #ifdef SQLITE_ENABLE_COLUMN_METADATA
131411  # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
131412  #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
131413  # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
131414  #endif
131415  static const char *columnTypeImpl(
131416    NameContext *pNC, 
131417  #ifndef SQLITE_ENABLE_COLUMN_METADATA
131418    Expr *pExpr
131419  #else
131420    Expr *pExpr,
131421    const char **pzOrigDb,
131422    const char **pzOrigTab,
131423    const char **pzOrigCol
131424  #endif
131425  ){
131426    char const *zType = 0;
131427    int j;
131428  #ifdef SQLITE_ENABLE_COLUMN_METADATA
131429    char const *zOrigDb = 0;
131430    char const *zOrigTab = 0;
131431    char const *zOrigCol = 0;
131432  #endif
131433  
131434    assert( pExpr!=0 );
131435    assert( pNC->pSrcList!=0 );
131436    assert( pExpr->op!=TK_AGG_COLUMN );  /* This routine runes before aggregates
131437                                         ** are processed */
131438    switch( pExpr->op ){
131439      case TK_COLUMN: {
131440        /* The expression is a column. Locate the table the column is being
131441        ** extracted from in NameContext.pSrcList. This table may be real
131442        ** database table or a subquery.
131443        */
131444        Table *pTab = 0;            /* Table structure column is extracted from */
131445        Select *pS = 0;             /* Select the column is extracted from */
131446        int iCol = pExpr->iColumn;  /* Index of column in pTab */
131447        while( pNC && !pTab ){
131448          SrcList *pTabList = pNC->pSrcList;
131449          for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
131450          if( j<pTabList->nSrc ){
131451            pTab = pTabList->a[j].pTab;
131452            pS = pTabList->a[j].pSelect;
131453          }else{
131454            pNC = pNC->pNext;
131455          }
131456        }
131457  
131458        if( pTab==0 ){
131459          /* At one time, code such as "SELECT new.x" within a trigger would
131460          ** cause this condition to run.  Since then, we have restructured how
131461          ** trigger code is generated and so this condition is no longer 
131462          ** possible. However, it can still be true for statements like
131463          ** the following:
131464          **
131465          **   CREATE TABLE t1(col INTEGER);
131466          **   SELECT (SELECT t1.col) FROM FROM t1;
131467          **
131468          ** when columnType() is called on the expression "t1.col" in the 
131469          ** sub-select. In this case, set the column type to NULL, even
131470          ** though it should really be "INTEGER".
131471          **
131472          ** This is not a problem, as the column type of "t1.col" is never
131473          ** used. When columnType() is called on the expression 
131474          ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
131475          ** branch below.  */
131476          break;
131477        }
131478  
131479        assert( pTab && pExpr->y.pTab==pTab );
131480        if( pS ){
131481          /* The "table" is actually a sub-select or a view in the FROM clause
131482          ** of the SELECT statement. Return the declaration type and origin
131483          ** data for the result-set column of the sub-select.
131484          */
131485          if( iCol>=0 && iCol<pS->pEList->nExpr ){
131486            /* If iCol is less than zero, then the expression requests the
131487            ** rowid of the sub-select or view. This expression is legal (see 
131488            ** test case misc2.2.2) - it always evaluates to NULL.
131489            */
131490            NameContext sNC;
131491            Expr *p = pS->pEList->a[iCol].pExpr;
131492            sNC.pSrcList = pS->pSrc;
131493            sNC.pNext = pNC;
131494            sNC.pParse = pNC->pParse;
131495            zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 
131496          }
131497        }else{
131498          /* A real table or a CTE table */
131499          assert( !pS );
131500  #ifdef SQLITE_ENABLE_COLUMN_METADATA
131501          if( iCol<0 ) iCol = pTab->iPKey;
131502          assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
131503          if( iCol<0 ){
131504            zType = "INTEGER";
131505            zOrigCol = "rowid";
131506          }else{
131507            zOrigCol = pTab->aCol[iCol].zName;
131508            zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
131509          }
131510          zOrigTab = pTab->zName;
131511          if( pNC->pParse && pTab->pSchema ){
131512            int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
131513            zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
131514          }
131515  #else
131516          assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
131517          if( iCol<0 ){
131518            zType = "INTEGER";
131519          }else{
131520            zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
131521          }
131522  #endif
131523        }
131524        break;
131525      }
131526  #ifndef SQLITE_OMIT_SUBQUERY
131527      case TK_SELECT: {
131528        /* The expression is a sub-select. Return the declaration type and
131529        ** origin info for the single column in the result set of the SELECT
131530        ** statement.
131531        */
131532        NameContext sNC;
131533        Select *pS = pExpr->x.pSelect;
131534        Expr *p = pS->pEList->a[0].pExpr;
131535        assert( ExprHasProperty(pExpr, EP_xIsSelect) );
131536        sNC.pSrcList = pS->pSrc;
131537        sNC.pNext = pNC;
131538        sNC.pParse = pNC->pParse;
131539        zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 
131540        break;
131541      }
131542  #endif
131543    }
131544  
131545  #ifdef SQLITE_ENABLE_COLUMN_METADATA  
131546    if( pzOrigDb ){
131547      assert( pzOrigTab && pzOrigCol );
131548      *pzOrigDb = zOrigDb;
131549      *pzOrigTab = zOrigTab;
131550      *pzOrigCol = zOrigCol;
131551    }
131552  #endif
131553    return zType;
131554  }
131555  
131556  /*
131557  ** Generate code that will tell the VDBE the declaration types of columns
131558  ** in the result set.
131559  */
131560  static void generateColumnTypes(
131561    Parse *pParse,      /* Parser context */
131562    SrcList *pTabList,  /* List of tables */
131563    ExprList *pEList    /* Expressions defining the result set */
131564  ){
131565  #ifndef SQLITE_OMIT_DECLTYPE
131566    Vdbe *v = pParse->pVdbe;
131567    int i;
131568    NameContext sNC;
131569    sNC.pSrcList = pTabList;
131570    sNC.pParse = pParse;
131571    sNC.pNext = 0;
131572    for(i=0; i<pEList->nExpr; i++){
131573      Expr *p = pEList->a[i].pExpr;
131574      const char *zType;
131575  #ifdef SQLITE_ENABLE_COLUMN_METADATA
131576      const char *zOrigDb = 0;
131577      const char *zOrigTab = 0;
131578      const char *zOrigCol = 0;
131579      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
131580  
131581      /* The vdbe must make its own copy of the column-type and other 
131582      ** column specific strings, in case the schema is reset before this
131583      ** virtual machine is deleted.
131584      */
131585      sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
131586      sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
131587      sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
131588  #else
131589      zType = columnType(&sNC, p, 0, 0, 0);
131590  #endif
131591      sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
131592    }
131593  #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
131594  }
131595  
131596  
131597  /*
131598  ** Compute the column names for a SELECT statement.
131599  **
131600  ** The only guarantee that SQLite makes about column names is that if the
131601  ** column has an AS clause assigning it a name, that will be the name used.
131602  ** That is the only documented guarantee.  However, countless applications
131603  ** developed over the years have made baseless assumptions about column names
131604  ** and will break if those assumptions changes.  Hence, use extreme caution
131605  ** when modifying this routine to avoid breaking legacy.
131606  **
131607  ** See Also: sqlite3ColumnsFromExprList()
131608  **
131609  ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
131610  ** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
131611  ** applications should operate this way.  Nevertheless, we need to support the
131612  ** other modes for legacy:
131613  **
131614  **    short=OFF, full=OFF:      Column name is the text of the expression has it
131615  **                              originally appears in the SELECT statement.  In
131616  **                              other words, the zSpan of the result expression.
131617  **
131618  **    short=ON, full=OFF:       (This is the default setting).  If the result
131619  **                              refers directly to a table column, then the
131620  **                              result column name is just the table column
131621  **                              name: COLUMN.  Otherwise use zSpan.
131622  **
131623  **    full=ON, short=ANY:       If the result refers directly to a table column,
131624  **                              then the result column name with the table name
131625  **                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
131626  */
131627  static void generateColumnNames(
131628    Parse *pParse,      /* Parser context */
131629    Select *pSelect     /* Generate column names for this SELECT statement */
131630  ){
131631    Vdbe *v = pParse->pVdbe;
131632    int i;
131633    Table *pTab;
131634    SrcList *pTabList;
131635    ExprList *pEList;
131636    sqlite3 *db = pParse->db;
131637    int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
131638    int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
131639  
131640  #ifndef SQLITE_OMIT_EXPLAIN
131641    /* If this is an EXPLAIN, skip this step */
131642    if( pParse->explain ){
131643      return;
131644    }
131645  #endif
131646  
131647    if( pParse->colNamesSet ) return;
131648    /* Column names are determined by the left-most term of a compound select */
131649    while( pSelect->pPrior ) pSelect = pSelect->pPrior;
131650    SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
131651    pTabList = pSelect->pSrc;
131652    pEList = pSelect->pEList;
131653    assert( v!=0 );
131654    assert( pTabList!=0 );
131655    pParse->colNamesSet = 1;
131656    fullName = (db->flags & SQLITE_FullColNames)!=0;
131657    srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
131658    sqlite3VdbeSetNumCols(v, pEList->nExpr);
131659    for(i=0; i<pEList->nExpr; i++){
131660      Expr *p = pEList->a[i].pExpr;
131661  
131662      assert( p!=0 );
131663      assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
131664      assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
131665      if( pEList->a[i].zName ){
131666        /* An AS clause always takes first priority */
131667        char *zName = pEList->a[i].zName;
131668        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
131669      }else if( srcName && p->op==TK_COLUMN ){
131670        char *zCol;
131671        int iCol = p->iColumn;
131672        pTab = p->y.pTab;
131673        assert( pTab!=0 );
131674        if( iCol<0 ) iCol = pTab->iPKey;
131675        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
131676        if( iCol<0 ){
131677          zCol = "rowid";
131678        }else{
131679          zCol = pTab->aCol[iCol].zName;
131680        }
131681        if( fullName ){
131682          char *zName = 0;
131683          zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
131684          sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
131685        }else{
131686          sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
131687        }
131688      }else{
131689        const char *z = pEList->a[i].zSpan;
131690        z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
131691        sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
131692      }
131693    }
131694    generateColumnTypes(pParse, pTabList, pEList);
131695  }
131696  
131697  /*
131698  ** Given an expression list (which is really the list of expressions
131699  ** that form the result set of a SELECT statement) compute appropriate
131700  ** column names for a table that would hold the expression list.
131701  **
131702  ** All column names will be unique.
131703  **
131704  ** Only the column names are computed.  Column.zType, Column.zColl,
131705  ** and other fields of Column are zeroed.
131706  **
131707  ** Return SQLITE_OK on success.  If a memory allocation error occurs,
131708  ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
131709  **
131710  ** The only guarantee that SQLite makes about column names is that if the
131711  ** column has an AS clause assigning it a name, that will be the name used.
131712  ** That is the only documented guarantee.  However, countless applications
131713  ** developed over the years have made baseless assumptions about column names
131714  ** and will break if those assumptions changes.  Hence, use extreme caution
131715  ** when modifying this routine to avoid breaking legacy.
131716  **
131717  ** See Also: generateColumnNames()
131718  */
131719  SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
131720    Parse *pParse,          /* Parsing context */
131721    ExprList *pEList,       /* Expr list from which to derive column names */
131722    i16 *pnCol,             /* Write the number of columns here */
131723    Column **paCol          /* Write the new column list here */
131724  ){
131725    sqlite3 *db = pParse->db;   /* Database connection */
131726    int i, j;                   /* Loop counters */
131727    u32 cnt;                    /* Index added to make the name unique */
131728    Column *aCol, *pCol;        /* For looping over result columns */
131729    int nCol;                   /* Number of columns in the result set */
131730    char *zName;                /* Column name */
131731    int nName;                  /* Size of name in zName[] */
131732    Hash ht;                    /* Hash table of column names */
131733  
131734    sqlite3HashInit(&ht);
131735    if( pEList ){
131736      nCol = pEList->nExpr;
131737      aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
131738      testcase( aCol==0 );
131739      if( nCol>32767 ) nCol = 32767;
131740    }else{
131741      nCol = 0;
131742      aCol = 0;
131743    }
131744    assert( nCol==(i16)nCol );
131745    *pnCol = nCol;
131746    *paCol = aCol;
131747  
131748    for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
131749      /* Get an appropriate name for the column
131750      */
131751      if( (zName = pEList->a[i].zName)!=0 ){
131752        /* If the column contains an "AS <name>" phrase, use <name> as the name */
131753      }else{
131754        Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
131755        while( pColExpr->op==TK_DOT ){
131756          pColExpr = pColExpr->pRight;
131757          assert( pColExpr!=0 );
131758        }
131759        assert( pColExpr->op!=TK_AGG_COLUMN );
131760        if( pColExpr->op==TK_COLUMN ){
131761          /* For columns use the column name name */
131762          int iCol = pColExpr->iColumn;
131763          Table *pTab = pColExpr->y.pTab;
131764          assert( pTab!=0 );
131765          if( iCol<0 ) iCol = pTab->iPKey;
131766          zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
131767        }else if( pColExpr->op==TK_ID ){
131768          assert( !ExprHasProperty(pColExpr, EP_IntValue) );
131769          zName = pColExpr->u.zToken;
131770        }else{
131771          /* Use the original text of the column expression as its name */
131772          zName = pEList->a[i].zSpan;
131773        }
131774      }
131775      if( zName ){
131776        zName = sqlite3DbStrDup(db, zName);
131777      }else{
131778        zName = sqlite3MPrintf(db,"column%d",i+1);
131779      }
131780  
131781      /* Make sure the column name is unique.  If the name is not unique,
131782      ** append an integer to the name so that it becomes unique.
131783      */
131784      cnt = 0;
131785      while( zName && sqlite3HashFind(&ht, zName)!=0 ){
131786        nName = sqlite3Strlen30(zName);
131787        if( nName>0 ){
131788          for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
131789          if( zName[j]==':' ) nName = j;
131790        }
131791        zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
131792        if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
131793      }
131794      pCol->zName = zName;
131795      sqlite3ColumnPropertiesFromName(0, pCol);
131796      if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
131797        sqlite3OomFault(db);
131798      }
131799    }
131800    sqlite3HashClear(&ht);
131801    if( db->mallocFailed ){
131802      for(j=0; j<i; j++){
131803        sqlite3DbFree(db, aCol[j].zName);
131804      }
131805      sqlite3DbFree(db, aCol);
131806      *paCol = 0;
131807      *pnCol = 0;
131808      return SQLITE_NOMEM_BKPT;
131809    }
131810    return SQLITE_OK;
131811  }
131812  
131813  /*
131814  ** Add type and collation information to a column list based on
131815  ** a SELECT statement.
131816  ** 
131817  ** The column list presumably came from selectColumnNamesFromExprList().
131818  ** The column list has only names, not types or collations.  This
131819  ** routine goes through and adds the types and collations.
131820  **
131821  ** This routine requires that all identifiers in the SELECT
131822  ** statement be resolved.
131823  */
131824  SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
131825    Parse *pParse,        /* Parsing contexts */
131826    Table *pTab,          /* Add column type information to this table */
131827    Select *pSelect       /* SELECT used to determine types and collations */
131828  ){
131829    sqlite3 *db = pParse->db;
131830    NameContext sNC;
131831    Column *pCol;
131832    CollSeq *pColl;
131833    int i;
131834    Expr *p;
131835    struct ExprList_item *a;
131836  
131837    assert( pSelect!=0 );
131838    assert( (pSelect->selFlags & SF_Resolved)!=0 );
131839    assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
131840    if( db->mallocFailed ) return;
131841    memset(&sNC, 0, sizeof(sNC));
131842    sNC.pSrcList = pSelect->pSrc;
131843    a = pSelect->pEList->a;
131844    for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
131845      const char *zType;
131846      int n, m;
131847      p = a[i].pExpr;
131848      zType = columnType(&sNC, p, 0, 0, 0);
131849      /* pCol->szEst = ... // Column size est for SELECT tables never used */
131850      pCol->affinity = sqlite3ExprAffinity(p);
131851      if( zType ){
131852        m = sqlite3Strlen30(zType);
131853        n = sqlite3Strlen30(pCol->zName);
131854        pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
131855        if( pCol->zName ){
131856          memcpy(&pCol->zName[n+1], zType, m+1);
131857          pCol->colFlags |= COLFLAG_HASTYPE;
131858        }
131859      }
131860      if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
131861      pColl = sqlite3ExprCollSeq(pParse, p);
131862      if( pColl && pCol->zColl==0 ){
131863        pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
131864      }
131865    }
131866    pTab->szTabRow = 1; /* Any non-zero value works */
131867  }
131868  
131869  /*
131870  ** Given a SELECT statement, generate a Table structure that describes
131871  ** the result set of that SELECT.
131872  */
131873  SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
131874    Table *pTab;
131875    sqlite3 *db = pParse->db;
131876    u64 savedFlags;
131877  
131878    savedFlags = db->flags;
131879    db->flags &= ~(u64)SQLITE_FullColNames;
131880    db->flags |= SQLITE_ShortColNames;
131881    sqlite3SelectPrep(pParse, pSelect, 0);
131882    db->flags = savedFlags;
131883    if( pParse->nErr ) return 0;
131884    while( pSelect->pPrior ) pSelect = pSelect->pPrior;
131885    pTab = sqlite3DbMallocZero(db, sizeof(Table) );
131886    if( pTab==0 ){
131887      return 0;
131888    }
131889    /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
131890    ** is disabled */
131891    assert( db->lookaside.bDisable );
131892    pTab->nTabRef = 1;
131893    pTab->zName = 0;
131894    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
131895    sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
131896    sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
131897    pTab->iPKey = -1;
131898    if( db->mallocFailed ){
131899      sqlite3DeleteTable(db, pTab);
131900      return 0;
131901    }
131902    return pTab;
131903  }
131904  
131905  /*
131906  ** Get a VDBE for the given parser context.  Create a new one if necessary.
131907  ** If an error occurs, return NULL and leave a message in pParse.
131908  */
131909  SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
131910    if( pParse->pVdbe ){
131911      return pParse->pVdbe;
131912    }
131913    if( pParse->pToplevel==0
131914     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
131915    ){
131916      pParse->okConstFactor = 1;
131917    }
131918    return sqlite3VdbeCreate(pParse);
131919  }
131920  
131921  
131922  /*
131923  ** Compute the iLimit and iOffset fields of the SELECT based on the
131924  ** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
131925  ** that appear in the original SQL statement after the LIMIT and OFFSET
131926  ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
131927  ** are the integer memory register numbers for counters used to compute 
131928  ** the limit and offset.  If there is no limit and/or offset, then 
131929  ** iLimit and iOffset are negative.
131930  **
131931  ** This routine changes the values of iLimit and iOffset only if
131932  ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight.  iLimit
131933  ** and iOffset should have been preset to appropriate default values (zero)
131934  ** prior to calling this routine.
131935  **
131936  ** The iOffset register (if it exists) is initialized to the value
131937  ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
131938  ** iOffset+1 is initialized to LIMIT+OFFSET.
131939  **
131940  ** Only if pLimit->pLeft!=0 do the limit registers get
131941  ** redefined.  The UNION ALL operator uses this property to force
131942  ** the reuse of the same limit and offset registers across multiple
131943  ** SELECT statements.
131944  */
131945  static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
131946    Vdbe *v = 0;
131947    int iLimit = 0;
131948    int iOffset;
131949    int n;
131950    Expr *pLimit = p->pLimit;
131951  
131952    if( p->iLimit ) return;
131953  
131954    /* 
131955    ** "LIMIT -1" always shows all rows.  There is some
131956    ** controversy about what the correct behavior should be.
131957    ** The current implementation interprets "LIMIT 0" to mean
131958    ** no rows.
131959    */
131960    if( pLimit ){
131961      assert( pLimit->op==TK_LIMIT );
131962      assert( pLimit->pLeft!=0 );
131963      p->iLimit = iLimit = ++pParse->nMem;
131964      v = sqlite3GetVdbe(pParse);
131965      assert( v!=0 );
131966      if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
131967        sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
131968        VdbeComment((v, "LIMIT counter"));
131969        if( n==0 ){
131970          sqlite3VdbeGoto(v, iBreak);
131971        }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
131972          p->nSelectRow = sqlite3LogEst((u64)n);
131973          p->selFlags |= SF_FixedLimit;
131974        }
131975      }else{
131976        sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
131977        sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
131978        VdbeComment((v, "LIMIT counter"));
131979        sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
131980      }
131981      if( pLimit->pRight ){
131982        p->iOffset = iOffset = ++pParse->nMem;
131983        pParse->nMem++;   /* Allocate an extra register for limit+offset */
131984        sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
131985        sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
131986        VdbeComment((v, "OFFSET counter"));
131987        sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
131988        VdbeComment((v, "LIMIT+OFFSET"));
131989      }
131990    }
131991  }
131992  
131993  #ifndef SQLITE_OMIT_COMPOUND_SELECT
131994  /*
131995  ** Return the appropriate collating sequence for the iCol-th column of
131996  ** the result set for the compound-select statement "p".  Return NULL if
131997  ** the column has no default collating sequence.
131998  **
131999  ** The collating sequence for the compound select is taken from the
132000  ** left-most term of the select that has a collating sequence.
132001  */
132002  static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
132003    CollSeq *pRet;
132004    if( p->pPrior ){
132005      pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
132006    }else{
132007      pRet = 0;
132008    }
132009    assert( iCol>=0 );
132010    /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
132011    ** have been thrown during name resolution and we would not have gotten
132012    ** this far */
132013    if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
132014      pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
132015    }
132016    return pRet;
132017  }
132018  
132019  /*
132020  ** The select statement passed as the second parameter is a compound SELECT
132021  ** with an ORDER BY clause. This function allocates and returns a KeyInfo
132022  ** structure suitable for implementing the ORDER BY.
132023  **
132024  ** Space to hold the KeyInfo structure is obtained from malloc. The calling
132025  ** function is responsible for ensuring that this structure is eventually
132026  ** freed.
132027  */
132028  static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
132029    ExprList *pOrderBy = p->pOrderBy;
132030    int nOrderBy = p->pOrderBy->nExpr;
132031    sqlite3 *db = pParse->db;
132032    KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
132033    if( pRet ){
132034      int i;
132035      for(i=0; i<nOrderBy; i++){
132036        struct ExprList_item *pItem = &pOrderBy->a[i];
132037        Expr *pTerm = pItem->pExpr;
132038        CollSeq *pColl;
132039  
132040        if( pTerm->flags & EP_Collate ){
132041          pColl = sqlite3ExprCollSeq(pParse, pTerm);
132042        }else{
132043          pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
132044          if( pColl==0 ) pColl = db->pDfltColl;
132045          pOrderBy->a[i].pExpr =
132046            sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
132047        }
132048        assert( sqlite3KeyInfoIsWriteable(pRet) );
132049        pRet->aColl[i] = pColl;
132050        pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
132051      }
132052    }
132053  
132054    return pRet;
132055  }
132056  
132057  #ifndef SQLITE_OMIT_CTE
132058  /*
132059  ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
132060  ** query of the form:
132061  **
132062  **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
132063  **                         \___________/             \_______________/
132064  **                           p->pPrior                      p
132065  **
132066  **
132067  ** There is exactly one reference to the recursive-table in the FROM clause
132068  ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
132069  **
132070  ** The setup-query runs once to generate an initial set of rows that go
132071  ** into a Queue table.  Rows are extracted from the Queue table one by
132072  ** one.  Each row extracted from Queue is output to pDest.  Then the single
132073  ** extracted row (now in the iCurrent table) becomes the content of the
132074  ** recursive-table for a recursive-query run.  The output of the recursive-query
132075  ** is added back into the Queue table.  Then another row is extracted from Queue
132076  ** and the iteration continues until the Queue table is empty.
132077  **
132078  ** If the compound query operator is UNION then no duplicate rows are ever
132079  ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
132080  ** that have ever been inserted into Queue and causes duplicates to be
132081  ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
132082  ** 
132083  ** If the query has an ORDER BY, then entries in the Queue table are kept in
132084  ** ORDER BY order and the first entry is extracted for each cycle.  Without
132085  ** an ORDER BY, the Queue table is just a FIFO.
132086  **
132087  ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
132088  ** have been output to pDest.  A LIMIT of zero means to output no rows and a
132089  ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
132090  ** with a positive value, then the first OFFSET outputs are discarded rather
132091  ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
132092  ** rows have been skipped.
132093  */
132094  static void generateWithRecursiveQuery(
132095    Parse *pParse,        /* Parsing context */
132096    Select *p,            /* The recursive SELECT to be coded */
132097    SelectDest *pDest     /* What to do with query results */
132098  ){
132099    SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
132100    int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
132101    Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
132102    Select *pSetup = p->pPrior;   /* The setup query */
132103    int addrTop;                  /* Top of the loop */
132104    int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
132105    int iCurrent = 0;             /* The Current table */
132106    int regCurrent;               /* Register holding Current table */
132107    int iQueue;                   /* The Queue table */
132108    int iDistinct = 0;            /* To ensure unique results if UNION */
132109    int eDest = SRT_Fifo;         /* How to write to Queue */
132110    SelectDest destQueue;         /* SelectDest targetting the Queue table */
132111    int i;                        /* Loop counter */
132112    int rc;                       /* Result code */
132113    ExprList *pOrderBy;           /* The ORDER BY clause */
132114    Expr *pLimit;                 /* Saved LIMIT and OFFSET */
132115    int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
132116  
132117  #ifndef SQLITE_OMIT_WINDOWFUNC
132118    if( p->pWin ){
132119      sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
132120      return;
132121    }
132122  #endif
132123  
132124    /* Obtain authorization to do a recursive query */
132125    if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
132126  
132127    /* Process the LIMIT and OFFSET clauses, if they exist */
132128    addrBreak = sqlite3VdbeMakeLabel(pParse);
132129    p->nSelectRow = 320;  /* 4 billion rows */
132130    computeLimitRegisters(pParse, p, addrBreak);
132131    pLimit = p->pLimit;
132132    regLimit = p->iLimit;
132133    regOffset = p->iOffset;
132134    p->pLimit = 0;
132135    p->iLimit = p->iOffset = 0;
132136    pOrderBy = p->pOrderBy;
132137  
132138    /* Locate the cursor number of the Current table */
132139    for(i=0; ALWAYS(i<pSrc->nSrc); i++){
132140      if( pSrc->a[i].fg.isRecursive ){
132141        iCurrent = pSrc->a[i].iCursor;
132142        break;
132143      }
132144    }
132145  
132146    /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
132147    ** the Distinct table must be exactly one greater than Queue in order
132148    ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
132149    iQueue = pParse->nTab++;
132150    if( p->op==TK_UNION ){
132151      eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
132152      iDistinct = pParse->nTab++;
132153    }else{
132154      eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
132155    }
132156    sqlite3SelectDestInit(&destQueue, eDest, iQueue);
132157  
132158    /* Allocate cursors for Current, Queue, and Distinct. */
132159    regCurrent = ++pParse->nMem;
132160    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
132161    if( pOrderBy ){
132162      KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
132163      sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
132164                        (char*)pKeyInfo, P4_KEYINFO);
132165      destQueue.pOrderBy = pOrderBy;
132166    }else{
132167      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
132168    }
132169    VdbeComment((v, "Queue table"));
132170    if( iDistinct ){
132171      p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
132172      p->selFlags |= SF_UsesEphemeral;
132173    }
132174  
132175    /* Detach the ORDER BY clause from the compound SELECT */
132176    p->pOrderBy = 0;
132177  
132178    /* Store the results of the setup-query in Queue. */
132179    pSetup->pNext = 0;
132180    ExplainQueryPlan((pParse, 1, "SETUP"));
132181    rc = sqlite3Select(pParse, pSetup, &destQueue);
132182    pSetup->pNext = p;
132183    if( rc ) goto end_of_recursive_query;
132184  
132185    /* Find the next row in the Queue and output that row */
132186    addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
132187  
132188    /* Transfer the next row in Queue over to Current */
132189    sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
132190    if( pOrderBy ){
132191      sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
132192    }else{
132193      sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
132194    }
132195    sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
132196  
132197    /* Output the single row in Current */
132198    addrCont = sqlite3VdbeMakeLabel(pParse);
132199    codeOffset(v, regOffset, addrCont);
132200    selectInnerLoop(pParse, p, iCurrent,
132201        0, 0, pDest, addrCont, addrBreak);
132202    if( regLimit ){
132203      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
132204      VdbeCoverage(v);
132205    }
132206    sqlite3VdbeResolveLabel(v, addrCont);
132207  
132208    /* Execute the recursive SELECT taking the single row in Current as
132209    ** the value for the recursive-table. Store the results in the Queue.
132210    */
132211    if( p->selFlags & SF_Aggregate ){
132212      sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
132213    }else{
132214      p->pPrior = 0;
132215      ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
132216      sqlite3Select(pParse, p, &destQueue);
132217      assert( p->pPrior==0 );
132218      p->pPrior = pSetup;
132219    }
132220  
132221    /* Keep running the loop until the Queue is empty */
132222    sqlite3VdbeGoto(v, addrTop);
132223    sqlite3VdbeResolveLabel(v, addrBreak);
132224  
132225  end_of_recursive_query:
132226    sqlite3ExprListDelete(pParse->db, p->pOrderBy);
132227    p->pOrderBy = pOrderBy;
132228    p->pLimit = pLimit;
132229    return;
132230  }
132231  #endif /* SQLITE_OMIT_CTE */
132232  
132233  /* Forward references */
132234  static int multiSelectOrderBy(
132235    Parse *pParse,        /* Parsing context */
132236    Select *p,            /* The right-most of SELECTs to be coded */
132237    SelectDest *pDest     /* What to do with query results */
132238  );
132239  
132240  /*
132241  ** Handle the special case of a compound-select that originates from a
132242  ** VALUES clause.  By handling this as a special case, we avoid deep
132243  ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
132244  ** on a VALUES clause.
132245  **
132246  ** Because the Select object originates from a VALUES clause:
132247  **   (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
132248  **   (2) All terms are UNION ALL
132249  **   (3) There is no ORDER BY clause
132250  **
132251  ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
132252  ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
132253  ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
132254  ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
132255  */
132256  static int multiSelectValues(
132257    Parse *pParse,        /* Parsing context */
132258    Select *p,            /* The right-most of SELECTs to be coded */
132259    SelectDest *pDest     /* What to do with query results */
132260  ){
132261    int nRow = 1;
132262    int rc = 0;
132263    int bShowAll = p->pLimit==0;
132264    assert( p->selFlags & SF_MultiValue );
132265    do{
132266      assert( p->selFlags & SF_Values );
132267      assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
132268      assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
132269      if( p->pPrior==0 ) break;
132270      assert( p->pPrior->pNext==p );
132271      p = p->pPrior;
132272      nRow += bShowAll;
132273    }while(1);
132274    ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
132275                      nRow==1 ? "" : "S"));
132276    while( p ){
132277      selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
132278      if( !bShowAll ) break;
132279      p->nSelectRow = nRow;
132280      p = p->pNext;
132281    }
132282    return rc;
132283  }
132284  
132285  /*
132286  ** This routine is called to process a compound query form from
132287  ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
132288  ** INTERSECT
132289  **
132290  ** "p" points to the right-most of the two queries.  the query on the
132291  ** left is p->pPrior.  The left query could also be a compound query
132292  ** in which case this routine will be called recursively. 
132293  **
132294  ** The results of the total query are to be written into a destination
132295  ** of type eDest with parameter iParm.
132296  **
132297  ** Example 1:  Consider a three-way compound SQL statement.
132298  **
132299  **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
132300  **
132301  ** This statement is parsed up as follows:
132302  **
132303  **     SELECT c FROM t3
132304  **      |
132305  **      `----->  SELECT b FROM t2
132306  **                |
132307  **                `------>  SELECT a FROM t1
132308  **
132309  ** The arrows in the diagram above represent the Select.pPrior pointer.
132310  ** So if this routine is called with p equal to the t3 query, then
132311  ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
132312  **
132313  ** Notice that because of the way SQLite parses compound SELECTs, the
132314  ** individual selects always group from left to right.
132315  */
132316  static int multiSelect(
132317    Parse *pParse,        /* Parsing context */
132318    Select *p,            /* The right-most of SELECTs to be coded */
132319    SelectDest *pDest     /* What to do with query results */
132320  ){
132321    int rc = SQLITE_OK;   /* Success code from a subroutine */
132322    Select *pPrior;       /* Another SELECT immediately to our left */
132323    Vdbe *v;              /* Generate code to this VDBE */
132324    SelectDest dest;      /* Alternative data destination */
132325    Select *pDelete = 0;  /* Chain of simple selects to delete */
132326    sqlite3 *db;          /* Database connection */
132327  
132328    /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
132329    ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
132330    */
132331    assert( p && p->pPrior );  /* Calling function guarantees this much */
132332    assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
132333    db = pParse->db;
132334    pPrior = p->pPrior;
132335    dest = *pDest;
132336    if( pPrior->pOrderBy || pPrior->pLimit ){
132337      sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
132338        pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
132339      rc = 1;
132340      goto multi_select_end;
132341    }
132342  
132343    v = sqlite3GetVdbe(pParse);
132344    assert( v!=0 );  /* The VDBE already created by calling function */
132345  
132346    /* Create the destination temporary table if necessary
132347    */
132348    if( dest.eDest==SRT_EphemTab ){
132349      assert( p->pEList );
132350      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
132351      dest.eDest = SRT_Table;
132352    }
132353  
132354    /* Special handling for a compound-select that originates as a VALUES clause.
132355    */
132356    if( p->selFlags & SF_MultiValue ){
132357      rc = multiSelectValues(pParse, p, &dest);
132358      goto multi_select_end;
132359    }
132360  
132361    /* Make sure all SELECTs in the statement have the same number of elements
132362    ** in their result sets.
132363    */
132364    assert( p->pEList && pPrior->pEList );
132365    assert( p->pEList->nExpr==pPrior->pEList->nExpr );
132366  
132367  #ifndef SQLITE_OMIT_CTE
132368    if( p->selFlags & SF_Recursive ){
132369      generateWithRecursiveQuery(pParse, p, &dest);
132370    }else
132371  #endif
132372  
132373    /* Compound SELECTs that have an ORDER BY clause are handled separately.
132374    */
132375    if( p->pOrderBy ){
132376      return multiSelectOrderBy(pParse, p, pDest);
132377    }else{
132378  
132379  #ifndef SQLITE_OMIT_EXPLAIN
132380      if( pPrior->pPrior==0 ){
132381        ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
132382        ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
132383      }
132384  #endif
132385  
132386      /* Generate code for the left and right SELECT statements.
132387      */
132388      switch( p->op ){
132389        case TK_ALL: {
132390          int addr = 0;
132391          int nLimit;
132392          assert( !pPrior->pLimit );
132393          pPrior->iLimit = p->iLimit;
132394          pPrior->iOffset = p->iOffset;
132395          pPrior->pLimit = p->pLimit;
132396          rc = sqlite3Select(pParse, pPrior, &dest);
132397          p->pLimit = 0;
132398          if( rc ){
132399            goto multi_select_end;
132400          }
132401          p->pPrior = 0;
132402          p->iLimit = pPrior->iLimit;
132403          p->iOffset = pPrior->iOffset;
132404          if( p->iLimit ){
132405            addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
132406            VdbeComment((v, "Jump ahead if LIMIT reached"));
132407            if( p->iOffset ){
132408              sqlite3VdbeAddOp3(v, OP_OffsetLimit,
132409                                p->iLimit, p->iOffset+1, p->iOffset);
132410            }
132411          }
132412          ExplainQueryPlan((pParse, 1, "UNION ALL"));
132413          rc = sqlite3Select(pParse, p, &dest);
132414          testcase( rc!=SQLITE_OK );
132415          pDelete = p->pPrior;
132416          p->pPrior = pPrior;
132417          p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
132418          if( pPrior->pLimit
132419           && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
132420           && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
132421          ){
132422            p->nSelectRow = sqlite3LogEst((u64)nLimit);
132423          }
132424          if( addr ){
132425            sqlite3VdbeJumpHere(v, addr);
132426          }
132427          break;
132428        }
132429        case TK_EXCEPT:
132430        case TK_UNION: {
132431          int unionTab;    /* Cursor number of the temp table holding result */
132432          u8 op = 0;       /* One of the SRT_ operations to apply to self */
132433          int priorOp;     /* The SRT_ operation to apply to prior selects */
132434          Expr *pLimit;    /* Saved values of p->nLimit  */
132435          int addr;
132436          SelectDest uniondest;
132437    
132438          testcase( p->op==TK_EXCEPT );
132439          testcase( p->op==TK_UNION );
132440          priorOp = SRT_Union;
132441          if( dest.eDest==priorOp ){
132442            /* We can reuse a temporary table generated by a SELECT to our
132443            ** right.
132444            */
132445            assert( p->pLimit==0 );      /* Not allowed on leftward elements */
132446            unionTab = dest.iSDParm;
132447          }else{
132448            /* We will need to create our own temporary table to hold the
132449            ** intermediate results.
132450            */
132451            unionTab = pParse->nTab++;
132452            assert( p->pOrderBy==0 );
132453            addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
132454            assert( p->addrOpenEphm[0] == -1 );
132455            p->addrOpenEphm[0] = addr;
132456            findRightmost(p)->selFlags |= SF_UsesEphemeral;
132457            assert( p->pEList );
132458          }
132459    
132460          /* Code the SELECT statements to our left
132461          */
132462          assert( !pPrior->pOrderBy );
132463          sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
132464          rc = sqlite3Select(pParse, pPrior, &uniondest);
132465          if( rc ){
132466            goto multi_select_end;
132467          }
132468    
132469          /* Code the current SELECT statement
132470          */
132471          if( p->op==TK_EXCEPT ){
132472            op = SRT_Except;
132473          }else{
132474            assert( p->op==TK_UNION );
132475            op = SRT_Union;
132476          }
132477          p->pPrior = 0;
132478          pLimit = p->pLimit;
132479          p->pLimit = 0;
132480          uniondest.eDest = op;
132481          ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
132482                            selectOpName(p->op)));
132483          rc = sqlite3Select(pParse, p, &uniondest);
132484          testcase( rc!=SQLITE_OK );
132485          /* Query flattening in sqlite3Select() might refill p->pOrderBy.
132486          ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
132487          sqlite3ExprListDelete(db, p->pOrderBy);
132488          pDelete = p->pPrior;
132489          p->pPrior = pPrior;
132490          p->pOrderBy = 0;
132491          if( p->op==TK_UNION ){
132492            p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
132493          }
132494          sqlite3ExprDelete(db, p->pLimit);
132495          p->pLimit = pLimit;
132496          p->iLimit = 0;
132497          p->iOffset = 0;
132498    
132499          /* Convert the data in the temporary table into whatever form
132500          ** it is that we currently need.
132501          */
132502          assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
132503          if( dest.eDest!=priorOp ){
132504            int iCont, iBreak, iStart;
132505            assert( p->pEList );
132506            iBreak = sqlite3VdbeMakeLabel(pParse);
132507            iCont = sqlite3VdbeMakeLabel(pParse);
132508            computeLimitRegisters(pParse, p, iBreak);
132509            sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
132510            iStart = sqlite3VdbeCurrentAddr(v);
132511            selectInnerLoop(pParse, p, unionTab,
132512                            0, 0, &dest, iCont, iBreak);
132513            sqlite3VdbeResolveLabel(v, iCont);
132514            sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
132515            sqlite3VdbeResolveLabel(v, iBreak);
132516            sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
132517          }
132518          break;
132519        }
132520        default: assert( p->op==TK_INTERSECT ); {
132521          int tab1, tab2;
132522          int iCont, iBreak, iStart;
132523          Expr *pLimit;
132524          int addr;
132525          SelectDest intersectdest;
132526          int r1;
132527    
132528          /* INTERSECT is different from the others since it requires
132529          ** two temporary tables.  Hence it has its own case.  Begin
132530          ** by allocating the tables we will need.
132531          */
132532          tab1 = pParse->nTab++;
132533          tab2 = pParse->nTab++;
132534          assert( p->pOrderBy==0 );
132535    
132536          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
132537          assert( p->addrOpenEphm[0] == -1 );
132538          p->addrOpenEphm[0] = addr;
132539          findRightmost(p)->selFlags |= SF_UsesEphemeral;
132540          assert( p->pEList );
132541    
132542          /* Code the SELECTs to our left into temporary table "tab1".
132543          */
132544          sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
132545          rc = sqlite3Select(pParse, pPrior, &intersectdest);
132546          if( rc ){
132547            goto multi_select_end;
132548          }
132549    
132550          /* Code the current SELECT into temporary table "tab2"
132551          */
132552          addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
132553          assert( p->addrOpenEphm[1] == -1 );
132554          p->addrOpenEphm[1] = addr;
132555          p->pPrior = 0;
132556          pLimit = p->pLimit;
132557          p->pLimit = 0;
132558          intersectdest.iSDParm = tab2;
132559          ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
132560                            selectOpName(p->op)));
132561          rc = sqlite3Select(pParse, p, &intersectdest);
132562          testcase( rc!=SQLITE_OK );
132563          pDelete = p->pPrior;
132564          p->pPrior = pPrior;
132565          if( p->nSelectRow>pPrior->nSelectRow ){
132566            p->nSelectRow = pPrior->nSelectRow;
132567          }
132568          sqlite3ExprDelete(db, p->pLimit);
132569          p->pLimit = pLimit;
132570    
132571          /* Generate code to take the intersection of the two temporary
132572          ** tables.
132573          */
132574          assert( p->pEList );
132575          iBreak = sqlite3VdbeMakeLabel(pParse);
132576          iCont = sqlite3VdbeMakeLabel(pParse);
132577          computeLimitRegisters(pParse, p, iBreak);
132578          sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
132579          r1 = sqlite3GetTempReg(pParse);
132580          iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
132581          sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
132582          VdbeCoverage(v);
132583          sqlite3ReleaseTempReg(pParse, r1);
132584          selectInnerLoop(pParse, p, tab1,
132585                          0, 0, &dest, iCont, iBreak);
132586          sqlite3VdbeResolveLabel(v, iCont);
132587          sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
132588          sqlite3VdbeResolveLabel(v, iBreak);
132589          sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
132590          sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
132591          break;
132592        }
132593      }
132594    
132595    #ifndef SQLITE_OMIT_EXPLAIN
132596      if( p->pNext==0 ){
132597        ExplainQueryPlanPop(pParse);
132598      }
132599    #endif
132600    }
132601    
132602    /* Compute collating sequences used by 
132603    ** temporary tables needed to implement the compound select.
132604    ** Attach the KeyInfo structure to all temporary tables.
132605    **
132606    ** This section is run by the right-most SELECT statement only.
132607    ** SELECT statements to the left always skip this part.  The right-most
132608    ** SELECT might also skip this part if it has no ORDER BY clause and
132609    ** no temp tables are required.
132610    */
132611    if( p->selFlags & SF_UsesEphemeral ){
132612      int i;                        /* Loop counter */
132613      KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
132614      Select *pLoop;                /* For looping through SELECT statements */
132615      CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
132616      int nCol;                     /* Number of columns in result set */
132617  
132618      assert( p->pNext==0 );
132619      nCol = p->pEList->nExpr;
132620      pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
132621      if( !pKeyInfo ){
132622        rc = SQLITE_NOMEM_BKPT;
132623        goto multi_select_end;
132624      }
132625      for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
132626        *apColl = multiSelectCollSeq(pParse, p, i);
132627        if( 0==*apColl ){
132628          *apColl = db->pDfltColl;
132629        }
132630      }
132631  
132632      for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
132633        for(i=0; i<2; i++){
132634          int addr = pLoop->addrOpenEphm[i];
132635          if( addr<0 ){
132636            /* If [0] is unused then [1] is also unused.  So we can
132637            ** always safely abort as soon as the first unused slot is found */
132638            assert( pLoop->addrOpenEphm[1]<0 );
132639            break;
132640          }
132641          sqlite3VdbeChangeP2(v, addr, nCol);
132642          sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
132643                              P4_KEYINFO);
132644          pLoop->addrOpenEphm[i] = -1;
132645        }
132646      }
132647      sqlite3KeyInfoUnref(pKeyInfo);
132648    }
132649  
132650  multi_select_end:
132651    pDest->iSdst = dest.iSdst;
132652    pDest->nSdst = dest.nSdst;
132653    sqlite3SelectDelete(db, pDelete);
132654    return rc;
132655  }
132656  #endif /* SQLITE_OMIT_COMPOUND_SELECT */
132657  
132658  /*
132659  ** Error message for when two or more terms of a compound select have different
132660  ** size result sets.
132661  */
132662  SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
132663    if( p->selFlags & SF_Values ){
132664      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
132665    }else{
132666      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
132667        " do not have the same number of result columns", selectOpName(p->op));
132668    }
132669  }
132670  
132671  /*
132672  ** Code an output subroutine for a coroutine implementation of a
132673  ** SELECT statment.
132674  **
132675  ** The data to be output is contained in pIn->iSdst.  There are
132676  ** pIn->nSdst columns to be output.  pDest is where the output should
132677  ** be sent.
132678  **
132679  ** regReturn is the number of the register holding the subroutine
132680  ** return address.
132681  **
132682  ** If regPrev>0 then it is the first register in a vector that
132683  ** records the previous output.  mem[regPrev] is a flag that is false
132684  ** if there has been no previous output.  If regPrev>0 then code is
132685  ** generated to suppress duplicates.  pKeyInfo is used for comparing
132686  ** keys.
132687  **
132688  ** If the LIMIT found in p->iLimit is reached, jump immediately to
132689  ** iBreak.
132690  */
132691  static int generateOutputSubroutine(
132692    Parse *pParse,          /* Parsing context */
132693    Select *p,              /* The SELECT statement */
132694    SelectDest *pIn,        /* Coroutine supplying data */
132695    SelectDest *pDest,      /* Where to send the data */
132696    int regReturn,          /* The return address register */
132697    int regPrev,            /* Previous result register.  No uniqueness if 0 */
132698    KeyInfo *pKeyInfo,      /* For comparing with previous entry */
132699    int iBreak              /* Jump here if we hit the LIMIT */
132700  ){
132701    Vdbe *v = pParse->pVdbe;
132702    int iContinue;
132703    int addr;
132704  
132705    addr = sqlite3VdbeCurrentAddr(v);
132706    iContinue = sqlite3VdbeMakeLabel(pParse);
132707  
132708    /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
132709    */
132710    if( regPrev ){
132711      int addr1, addr2;
132712      addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
132713      addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
132714                                (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
132715      sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
132716      sqlite3VdbeJumpHere(v, addr1);
132717      sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
132718      sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
132719    }
132720    if( pParse->db->mallocFailed ) return 0;
132721  
132722    /* Suppress the first OFFSET entries if there is an OFFSET clause
132723    */
132724    codeOffset(v, p->iOffset, iContinue);
132725  
132726    assert( pDest->eDest!=SRT_Exists );
132727    assert( pDest->eDest!=SRT_Table );
132728    switch( pDest->eDest ){
132729      /* Store the result as data using a unique key.
132730      */
132731      case SRT_EphemTab: {
132732        int r1 = sqlite3GetTempReg(pParse);
132733        int r2 = sqlite3GetTempReg(pParse);
132734        sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
132735        sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
132736        sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
132737        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
132738        sqlite3ReleaseTempReg(pParse, r2);
132739        sqlite3ReleaseTempReg(pParse, r1);
132740        break;
132741      }
132742  
132743  #ifndef SQLITE_OMIT_SUBQUERY
132744      /* If we are creating a set for an "expr IN (SELECT ...)".
132745      */
132746      case SRT_Set: {
132747        int r1;
132748        testcase( pIn->nSdst>1 );
132749        r1 = sqlite3GetTempReg(pParse);
132750        sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 
132751            r1, pDest->zAffSdst, pIn->nSdst);
132752        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
132753                             pIn->iSdst, pIn->nSdst);
132754        sqlite3ReleaseTempReg(pParse, r1);
132755        break;
132756      }
132757  
132758      /* If this is a scalar select that is part of an expression, then
132759      ** store the results in the appropriate memory cell and break out
132760      ** of the scan loop.
132761      */
132762      case SRT_Mem: {
132763        assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
132764        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
132765        /* The LIMIT clause will jump out of the loop for us */
132766        break;
132767      }
132768  #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
132769  
132770      /* The results are stored in a sequence of registers
132771      ** starting at pDest->iSdst.  Then the co-routine yields.
132772      */
132773      case SRT_Coroutine: {
132774        if( pDest->iSdst==0 ){
132775          pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
132776          pDest->nSdst = pIn->nSdst;
132777        }
132778        sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
132779        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
132780        break;
132781      }
132782  
132783      /* If none of the above, then the result destination must be
132784      ** SRT_Output.  This routine is never called with any other
132785      ** destination other than the ones handled above or SRT_Output.
132786      **
132787      ** For SRT_Output, results are stored in a sequence of registers.  
132788      ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
132789      ** return the next row of result.
132790      */
132791      default: {
132792        assert( pDest->eDest==SRT_Output );
132793        sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
132794        break;
132795      }
132796    }
132797  
132798    /* Jump to the end of the loop if the LIMIT is reached.
132799    */
132800    if( p->iLimit ){
132801      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
132802    }
132803  
132804    /* Generate the subroutine return
132805    */
132806    sqlite3VdbeResolveLabel(v, iContinue);
132807    sqlite3VdbeAddOp1(v, OP_Return, regReturn);
132808  
132809    return addr;
132810  }
132811  
132812  /*
132813  ** Alternative compound select code generator for cases when there
132814  ** is an ORDER BY clause.
132815  **
132816  ** We assume a query of the following form:
132817  **
132818  **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
132819  **
132820  ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
132821  ** is to code both <selectA> and <selectB> with the ORDER BY clause as
132822  ** co-routines.  Then run the co-routines in parallel and merge the results
132823  ** into the output.  In addition to the two coroutines (called selectA and
132824  ** selectB) there are 7 subroutines:
132825  **
132826  **    outA:    Move the output of the selectA coroutine into the output
132827  **             of the compound query.
132828  **
132829  **    outB:    Move the output of the selectB coroutine into the output
132830  **             of the compound query.  (Only generated for UNION and
132831  **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
132832  **             appears only in B.)
132833  **
132834  **    AltB:    Called when there is data from both coroutines and A<B.
132835  **
132836  **    AeqB:    Called when there is data from both coroutines and A==B.
132837  **
132838  **    AgtB:    Called when there is data from both coroutines and A>B.
132839  **
132840  **    EofA:    Called when data is exhausted from selectA.
132841  **
132842  **    EofB:    Called when data is exhausted from selectB.
132843  **
132844  ** The implementation of the latter five subroutines depend on which 
132845  ** <operator> is used:
132846  **
132847  **
132848  **             UNION ALL         UNION            EXCEPT          INTERSECT
132849  **          -------------  -----------------  --------------  -----------------
132850  **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
132851  **
132852  **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
132853  **
132854  **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
132855  **
132856  **   EofA:   outB, nextB      outB, nextB          halt             halt
132857  **
132858  **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
132859  **
132860  ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
132861  ** causes an immediate jump to EofA and an EOF on B following nextB causes
132862  ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
132863  ** following nextX causes a jump to the end of the select processing.
132864  **
132865  ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
132866  ** within the output subroutine.  The regPrev register set holds the previously
132867  ** output value.  A comparison is made against this value and the output
132868  ** is skipped if the next results would be the same as the previous.
132869  **
132870  ** The implementation plan is to implement the two coroutines and seven
132871  ** subroutines first, then put the control logic at the bottom.  Like this:
132872  **
132873  **          goto Init
132874  **     coA: coroutine for left query (A)
132875  **     coB: coroutine for right query (B)
132876  **    outA: output one row of A
132877  **    outB: output one row of B (UNION and UNION ALL only)
132878  **    EofA: ...
132879  **    EofB: ...
132880  **    AltB: ...
132881  **    AeqB: ...
132882  **    AgtB: ...
132883  **    Init: initialize coroutine registers
132884  **          yield coA
132885  **          if eof(A) goto EofA
132886  **          yield coB
132887  **          if eof(B) goto EofB
132888  **    Cmpr: Compare A, B
132889  **          Jump AltB, AeqB, AgtB
132890  **     End: ...
132891  **
132892  ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
132893  ** actually called using Gosub and they do not Return.  EofA and EofB loop
132894  ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
132895  ** and AgtB jump to either L2 or to one of EofA or EofB.
132896  */
132897  #ifndef SQLITE_OMIT_COMPOUND_SELECT
132898  static int multiSelectOrderBy(
132899    Parse *pParse,        /* Parsing context */
132900    Select *p,            /* The right-most of SELECTs to be coded */
132901    SelectDest *pDest     /* What to do with query results */
132902  ){
132903    int i, j;             /* Loop counters */
132904    Select *pPrior;       /* Another SELECT immediately to our left */
132905    Vdbe *v;              /* Generate code to this VDBE */
132906    SelectDest destA;     /* Destination for coroutine A */
132907    SelectDest destB;     /* Destination for coroutine B */
132908    int regAddrA;         /* Address register for select-A coroutine */
132909    int regAddrB;         /* Address register for select-B coroutine */
132910    int addrSelectA;      /* Address of the select-A coroutine */
132911    int addrSelectB;      /* Address of the select-B coroutine */
132912    int regOutA;          /* Address register for the output-A subroutine */
132913    int regOutB;          /* Address register for the output-B subroutine */
132914    int addrOutA;         /* Address of the output-A subroutine */
132915    int addrOutB = 0;     /* Address of the output-B subroutine */
132916    int addrEofA;         /* Address of the select-A-exhausted subroutine */
132917    int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
132918    int addrEofB;         /* Address of the select-B-exhausted subroutine */
132919    int addrAltB;         /* Address of the A<B subroutine */
132920    int addrAeqB;         /* Address of the A==B subroutine */
132921    int addrAgtB;         /* Address of the A>B subroutine */
132922    int regLimitA;        /* Limit register for select-A */
132923    int regLimitB;        /* Limit register for select-A */
132924    int regPrev;          /* A range of registers to hold previous output */
132925    int savedLimit;       /* Saved value of p->iLimit */
132926    int savedOffset;      /* Saved value of p->iOffset */
132927    int labelCmpr;        /* Label for the start of the merge algorithm */
132928    int labelEnd;         /* Label for the end of the overall SELECT stmt */
132929    int addr1;            /* Jump instructions that get retargetted */
132930    int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
132931    KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
132932    KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
132933    sqlite3 *db;          /* Database connection */
132934    ExprList *pOrderBy;   /* The ORDER BY clause */
132935    int nOrderBy;         /* Number of terms in the ORDER BY clause */
132936    int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
132937  
132938    assert( p->pOrderBy!=0 );
132939    assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
132940    db = pParse->db;
132941    v = pParse->pVdbe;
132942    assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
132943    labelEnd = sqlite3VdbeMakeLabel(pParse);
132944    labelCmpr = sqlite3VdbeMakeLabel(pParse);
132945  
132946  
132947    /* Patch up the ORDER BY clause
132948    */
132949    op = p->op;  
132950    pPrior = p->pPrior;
132951    assert( pPrior->pOrderBy==0 );
132952    pOrderBy = p->pOrderBy;
132953    assert( pOrderBy );
132954    nOrderBy = pOrderBy->nExpr;
132955  
132956    /* For operators other than UNION ALL we have to make sure that
132957    ** the ORDER BY clause covers every term of the result set.  Add
132958    ** terms to the ORDER BY clause as necessary.
132959    */
132960    if( op!=TK_ALL ){
132961      for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
132962        struct ExprList_item *pItem;
132963        for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
132964          assert( pItem->u.x.iOrderByCol>0 );
132965          if( pItem->u.x.iOrderByCol==i ) break;
132966        }
132967        if( j==nOrderBy ){
132968          Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
132969          if( pNew==0 ) return SQLITE_NOMEM_BKPT;
132970          pNew->flags |= EP_IntValue;
132971          pNew->u.iValue = i;
132972          p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
132973          if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
132974        }
132975      }
132976    }
132977  
132978    /* Compute the comparison permutation and keyinfo that is used with
132979    ** the permutation used to determine if the next
132980    ** row of results comes from selectA or selectB.  Also add explicit
132981    ** collations to the ORDER BY clause terms so that when the subqueries
132982    ** to the right and the left are evaluated, they use the correct
132983    ** collation.
132984    */
132985    aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
132986    if( aPermute ){
132987      struct ExprList_item *pItem;
132988      aPermute[0] = nOrderBy;
132989      for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
132990        assert( pItem->u.x.iOrderByCol>0 );
132991        assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
132992        aPermute[i] = pItem->u.x.iOrderByCol - 1;
132993      }
132994      pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
132995    }else{
132996      pKeyMerge = 0;
132997    }
132998  
132999    /* Reattach the ORDER BY clause to the query.
133000    */
133001    p->pOrderBy = pOrderBy;
133002    pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
133003  
133004    /* Allocate a range of temporary registers and the KeyInfo needed
133005    ** for the logic that removes duplicate result rows when the
133006    ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
133007    */
133008    if( op==TK_ALL ){
133009      regPrev = 0;
133010    }else{
133011      int nExpr = p->pEList->nExpr;
133012      assert( nOrderBy>=nExpr || db->mallocFailed );
133013      regPrev = pParse->nMem+1;
133014      pParse->nMem += nExpr+1;
133015      sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
133016      pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
133017      if( pKeyDup ){
133018        assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
133019        for(i=0; i<nExpr; i++){
133020          pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
133021          pKeyDup->aSortOrder[i] = 0;
133022        }
133023      }
133024    }
133025   
133026    /* Separate the left and the right query from one another
133027    */
133028    p->pPrior = 0;
133029    pPrior->pNext = 0;
133030    sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
133031    if( pPrior->pPrior==0 ){
133032      sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
133033    }
133034  
133035    /* Compute the limit registers */
133036    computeLimitRegisters(pParse, p, labelEnd);
133037    if( p->iLimit && op==TK_ALL ){
133038      regLimitA = ++pParse->nMem;
133039      regLimitB = ++pParse->nMem;
133040      sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
133041                                    regLimitA);
133042      sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
133043    }else{
133044      regLimitA = regLimitB = 0;
133045    }
133046    sqlite3ExprDelete(db, p->pLimit);
133047    p->pLimit = 0;
133048  
133049    regAddrA = ++pParse->nMem;
133050    regAddrB = ++pParse->nMem;
133051    regOutA = ++pParse->nMem;
133052    regOutB = ++pParse->nMem;
133053    sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
133054    sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
133055  
133056    ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
133057  
133058    /* Generate a coroutine to evaluate the SELECT statement to the
133059    ** left of the compound operator - the "A" select.
133060    */
133061    addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
133062    addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
133063    VdbeComment((v, "left SELECT"));
133064    pPrior->iLimit = regLimitA;
133065    ExplainQueryPlan((pParse, 1, "LEFT"));
133066    sqlite3Select(pParse, pPrior, &destA);
133067    sqlite3VdbeEndCoroutine(v, regAddrA);
133068    sqlite3VdbeJumpHere(v, addr1);
133069  
133070    /* Generate a coroutine to evaluate the SELECT statement on 
133071    ** the right - the "B" select
133072    */
133073    addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
133074    addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
133075    VdbeComment((v, "right SELECT"));
133076    savedLimit = p->iLimit;
133077    savedOffset = p->iOffset;
133078    p->iLimit = regLimitB;
133079    p->iOffset = 0;  
133080    ExplainQueryPlan((pParse, 1, "RIGHT"));
133081    sqlite3Select(pParse, p, &destB);
133082    p->iLimit = savedLimit;
133083    p->iOffset = savedOffset;
133084    sqlite3VdbeEndCoroutine(v, regAddrB);
133085  
133086    /* Generate a subroutine that outputs the current row of the A
133087    ** select as the next output row of the compound select.
133088    */
133089    VdbeNoopComment((v, "Output routine for A"));
133090    addrOutA = generateOutputSubroutine(pParse,
133091                   p, &destA, pDest, regOutA,
133092                   regPrev, pKeyDup, labelEnd);
133093    
133094    /* Generate a subroutine that outputs the current row of the B
133095    ** select as the next output row of the compound select.
133096    */
133097    if( op==TK_ALL || op==TK_UNION ){
133098      VdbeNoopComment((v, "Output routine for B"));
133099      addrOutB = generateOutputSubroutine(pParse,
133100                   p, &destB, pDest, regOutB,
133101                   regPrev, pKeyDup, labelEnd);
133102    }
133103    sqlite3KeyInfoUnref(pKeyDup);
133104  
133105    /* Generate a subroutine to run when the results from select A
133106    ** are exhausted and only data in select B remains.
133107    */
133108    if( op==TK_EXCEPT || op==TK_INTERSECT ){
133109      addrEofA_noB = addrEofA = labelEnd;
133110    }else{  
133111      VdbeNoopComment((v, "eof-A subroutine"));
133112      addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
133113      addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
133114                                       VdbeCoverage(v);
133115      sqlite3VdbeGoto(v, addrEofA);
133116      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
133117    }
133118  
133119    /* Generate a subroutine to run when the results from select B
133120    ** are exhausted and only data in select A remains.
133121    */
133122    if( op==TK_INTERSECT ){
133123      addrEofB = addrEofA;
133124      if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
133125    }else{  
133126      VdbeNoopComment((v, "eof-B subroutine"));
133127      addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
133128      sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
133129      sqlite3VdbeGoto(v, addrEofB);
133130    }
133131  
133132    /* Generate code to handle the case of A<B
133133    */
133134    VdbeNoopComment((v, "A-lt-B subroutine"));
133135    addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
133136    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
133137    sqlite3VdbeGoto(v, labelCmpr);
133138  
133139    /* Generate code to handle the case of A==B
133140    */
133141    if( op==TK_ALL ){
133142      addrAeqB = addrAltB;
133143    }else if( op==TK_INTERSECT ){
133144      addrAeqB = addrAltB;
133145      addrAltB++;
133146    }else{
133147      VdbeNoopComment((v, "A-eq-B subroutine"));
133148      addrAeqB =
133149      sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
133150      sqlite3VdbeGoto(v, labelCmpr);
133151    }
133152  
133153    /* Generate code to handle the case of A>B
133154    */
133155    VdbeNoopComment((v, "A-gt-B subroutine"));
133156    addrAgtB = sqlite3VdbeCurrentAddr(v);
133157    if( op==TK_ALL || op==TK_UNION ){
133158      sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
133159    }
133160    sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
133161    sqlite3VdbeGoto(v, labelCmpr);
133162  
133163    /* This code runs once to initialize everything.
133164    */
133165    sqlite3VdbeJumpHere(v, addr1);
133166    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
133167    sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
133168  
133169    /* Implement the main merge loop
133170    */
133171    sqlite3VdbeResolveLabel(v, labelCmpr);
133172    sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
133173    sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
133174                           (char*)pKeyMerge, P4_KEYINFO);
133175    sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
133176    sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
133177  
133178    /* Jump to the this point in order to terminate the query.
133179    */
133180    sqlite3VdbeResolveLabel(v, labelEnd);
133181  
133182    /* Reassembly the compound query so that it will be freed correctly
133183    ** by the calling function */
133184    if( p->pPrior ){
133185      sqlite3SelectDelete(db, p->pPrior);
133186    }
133187    p->pPrior = pPrior;
133188    pPrior->pNext = p;
133189  
133190    /*** TBD:  Insert subroutine calls to close cursors on incomplete
133191    **** subqueries ****/
133192    ExplainQueryPlanPop(pParse);
133193    return pParse->nErr!=0;
133194  }
133195  #endif
133196  
133197  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
133198  
133199  /* An instance of the SubstContext object describes an substitution edit
133200  ** to be performed on a parse tree.
133201  **
133202  ** All references to columns in table iTable are to be replaced by corresponding
133203  ** expressions in pEList.
133204  */
133205  typedef struct SubstContext {
133206    Parse *pParse;            /* The parsing context */
133207    int iTable;               /* Replace references to this table */
133208    int iNewTable;            /* New table number */
133209    int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */
133210    ExprList *pEList;         /* Replacement expressions */
133211  } SubstContext;
133212  
133213  /* Forward Declarations */
133214  static void substExprList(SubstContext*, ExprList*);
133215  static void substSelect(SubstContext*, Select*, int);
133216  
133217  /*
133218  ** Scan through the expression pExpr.  Replace every reference to
133219  ** a column in table number iTable with a copy of the iColumn-th
133220  ** entry in pEList.  (But leave references to the ROWID column 
133221  ** unchanged.)
133222  **
133223  ** This routine is part of the flattening procedure.  A subquery
133224  ** whose result set is defined by pEList appears as entry in the
133225  ** FROM clause of a SELECT such that the VDBE cursor assigned to that
133226  ** FORM clause entry is iTable.  This routine makes the necessary 
133227  ** changes to pExpr so that it refers directly to the source table
133228  ** of the subquery rather the result set of the subquery.
133229  */
133230  static Expr *substExpr(
133231    SubstContext *pSubst,  /* Description of the substitution */
133232    Expr *pExpr            /* Expr in which substitution occurs */
133233  ){
133234    if( pExpr==0 ) return 0;
133235    if( ExprHasProperty(pExpr, EP_FromJoin)
133236     && pExpr->iRightJoinTable==pSubst->iTable
133237    ){
133238      pExpr->iRightJoinTable = pSubst->iNewTable;
133239    }
133240    if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
133241      if( pExpr->iColumn<0 ){
133242        pExpr->op = TK_NULL;
133243      }else{
133244        Expr *pNew;
133245        Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
133246        Expr ifNullRow;
133247        assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
133248        assert( pExpr->pRight==0 );
133249        if( sqlite3ExprIsVector(pCopy) ){
133250          sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
133251        }else{
133252          sqlite3 *db = pSubst->pParse->db;
133253          if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
133254            memset(&ifNullRow, 0, sizeof(ifNullRow));
133255            ifNullRow.op = TK_IF_NULL_ROW;
133256            ifNullRow.pLeft = pCopy;
133257            ifNullRow.iTable = pSubst->iNewTable;
133258            pCopy = &ifNullRow;
133259          }
133260          testcase( ExprHasProperty(pCopy, EP_Subquery) );
133261          pNew = sqlite3ExprDup(db, pCopy, 0);
133262          if( pNew && pSubst->isLeftJoin ){
133263            ExprSetProperty(pNew, EP_CanBeNull);
133264          }
133265          if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
133266            pNew->iRightJoinTable = pExpr->iRightJoinTable;
133267            ExprSetProperty(pNew, EP_FromJoin);
133268          }
133269          sqlite3ExprDelete(db, pExpr);
133270          pExpr = pNew;
133271        }
133272      }
133273    }else{
133274      if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
133275        pExpr->iTable = pSubst->iNewTable;
133276      }
133277      pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
133278      pExpr->pRight = substExpr(pSubst, pExpr->pRight);
133279      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
133280        substSelect(pSubst, pExpr->x.pSelect, 1);
133281      }else{
133282        substExprList(pSubst, pExpr->x.pList);
133283      }
133284    }
133285    return pExpr;
133286  }
133287  static void substExprList(
133288    SubstContext *pSubst, /* Description of the substitution */
133289    ExprList *pList       /* List to scan and in which to make substitutes */
133290  ){
133291    int i;
133292    if( pList==0 ) return;
133293    for(i=0; i<pList->nExpr; i++){
133294      pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
133295    }
133296  }
133297  static void substSelect(
133298    SubstContext *pSubst, /* Description of the substitution */
133299    Select *p,            /* SELECT statement in which to make substitutions */
133300    int doPrior           /* Do substitutes on p->pPrior too */
133301  ){
133302    SrcList *pSrc;
133303    struct SrcList_item *pItem;
133304    int i;
133305    if( !p ) return;
133306    do{
133307      substExprList(pSubst, p->pEList);
133308      substExprList(pSubst, p->pGroupBy);
133309      substExprList(pSubst, p->pOrderBy);
133310      p->pHaving = substExpr(pSubst, p->pHaving);
133311      p->pWhere = substExpr(pSubst, p->pWhere);
133312      pSrc = p->pSrc;
133313      assert( pSrc!=0 );
133314      for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
133315        substSelect(pSubst, pItem->pSelect, 1);
133316        if( pItem->fg.isTabFunc ){
133317          substExprList(pSubst, pItem->u1.pFuncArg);
133318        }
133319      }
133320    }while( doPrior && (p = p->pPrior)!=0 );
133321  }
133322  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
133323  
133324  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
133325  /*
133326  ** This routine attempts to flatten subqueries as a performance optimization.
133327  ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
133328  **
133329  ** To understand the concept of flattening, consider the following
133330  ** query:
133331  **
133332  **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
133333  **
133334  ** The default way of implementing this query is to execute the
133335  ** subquery first and store the results in a temporary table, then
133336  ** run the outer query on that temporary table.  This requires two
133337  ** passes over the data.  Furthermore, because the temporary table
133338  ** has no indices, the WHERE clause on the outer query cannot be
133339  ** optimized.
133340  **
133341  ** This routine attempts to rewrite queries such as the above into
133342  ** a single flat select, like this:
133343  **
133344  **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
133345  **
133346  ** The code generated for this simplification gives the same result
133347  ** but only has to scan the data once.  And because indices might 
133348  ** exist on the table t1, a complete scan of the data might be
133349  ** avoided.
133350  **
133351  ** Flattening is subject to the following constraints:
133352  **
133353  **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
133354  **        The subquery and the outer query cannot both be aggregates.
133355  **
133356  **  (**)  We no longer attempt to flatten aggregate subqueries. Was:
133357  **        (2) If the subquery is an aggregate then
133358  **        (2a) the outer query must not be a join and
133359  **        (2b) the outer query must not use subqueries
133360  **             other than the one FROM-clause subquery that is a candidate
133361  **             for flattening.  (This is due to ticket [2f7170d73bf9abf80]
133362  **             from 2015-02-09.)
133363  **
133364  **   (3)  If the subquery is the right operand of a LEFT JOIN then
133365  **        (3a) the subquery may not be a join and
133366  **        (3b) the FROM clause of the subquery may not contain a virtual
133367  **             table and
133368  **        (3c) the outer query may not be an aggregate.
133369  **
133370  **   (4)  The subquery can not be DISTINCT.
133371  **
133372  **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
133373  **        sub-queries that were excluded from this optimization. Restriction 
133374  **        (4) has since been expanded to exclude all DISTINCT subqueries.
133375  **
133376  **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
133377  **        If the subquery is aggregate, the outer query may not be DISTINCT.
133378  **
133379  **   (7)  The subquery must have a FROM clause.  TODO:  For subqueries without
133380  **        A FROM clause, consider adding a FROM clause with the special
133381  **        table sqlite_once that consists of a single row containing a
133382  **        single NULL.
133383  **
133384  **   (8)  If the subquery uses LIMIT then the outer query may not be a join.
133385  **
133386  **   (9)  If the subquery uses LIMIT then the outer query may not be aggregate.
133387  **
133388  **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
133389  **        accidently carried the comment forward until 2014-09-15.  Original
133390  **        constraint: "If the subquery is aggregate then the outer query 
133391  **        may not use LIMIT."
133392  **
133393  **  (11)  The subquery and the outer query may not both have ORDER BY clauses.
133394  **
133395  **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
133396  **        a separate restriction deriving from ticket #350.
133397  **
133398  **  (13)  The subquery and outer query may not both use LIMIT.
133399  **
133400  **  (14)  The subquery may not use OFFSET.
133401  **
133402  **  (15)  If the outer query is part of a compound select, then the
133403  **        subquery may not use LIMIT.
133404  **        (See ticket #2339 and ticket [02a8e81d44]).
133405  **
133406  **  (16)  If the outer query is aggregate, then the subquery may not
133407  **        use ORDER BY.  (Ticket #2942)  This used to not matter
133408  **        until we introduced the group_concat() function.  
133409  **
133410  **  (17)  If the subquery is a compound select, then
133411  **        (17a) all compound operators must be a UNION ALL, and
133412  **        (17b) no terms within the subquery compound may be aggregate
133413  **              or DISTINCT, and
133414  **        (17c) every term within the subquery compound must have a FROM clause
133415  **        (17d) the outer query may not be
133416  **              (17d1) aggregate, or
133417  **              (17d2) DISTINCT, or
133418  **              (17d3) a join.
133419  **
133420  **        The parent and sub-query may contain WHERE clauses. Subject to
133421  **        rules (11), (13) and (14), they may also contain ORDER BY,
133422  **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
133423  **        operator other than UNION ALL because all the other compound
133424  **        operators have an implied DISTINCT which is disallowed by
133425  **        restriction (4).
133426  **
133427  **        Also, each component of the sub-query must return the same number
133428  **        of result columns. This is actually a requirement for any compound
133429  **        SELECT statement, but all the code here does is make sure that no
133430  **        such (illegal) sub-query is flattened. The caller will detect the
133431  **        syntax error and return a detailed message.
133432  **
133433  **  (18)  If the sub-query is a compound select, then all terms of the
133434  **        ORDER BY clause of the parent must be simple references to 
133435  **        columns of the sub-query.
133436  **
133437  **  (19)  If the subquery uses LIMIT then the outer query may not
133438  **        have a WHERE clause.
133439  **
133440  **  (20)  If the sub-query is a compound select, then it must not use
133441  **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
133442  **        somewhat by saying that the terms of the ORDER BY clause must
133443  **        appear as unmodified result columns in the outer query.  But we
133444  **        have other optimizations in mind to deal with that case.
133445  **
133446  **  (21)  If the subquery uses LIMIT then the outer query may not be
133447  **        DISTINCT.  (See ticket [752e1646fc]).
133448  **
133449  **  (22)  The subquery may not be a recursive CTE.
133450  **
133451  **  (**)  Subsumed into restriction (17d3).  Was: If the outer query is
133452  **        a recursive CTE, then the sub-query may not be a compound query.
133453  **        This restriction is because transforming the
133454  **        parent to a compound query confuses the code that handles
133455  **        recursive queries in multiSelect().
133456  **
133457  **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
133458  **        The subquery may not be an aggregate that uses the built-in min() or 
133459  **        or max() functions.  (Without this restriction, a query like:
133460  **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
133461  **        return the value X for which Y was maximal.)
133462  **
133463  **  (25)  If either the subquery or the parent query contains a window
133464  **        function in the select list or ORDER BY clause, flattening
133465  **        is not attempted.
133466  **
133467  **
133468  ** In this routine, the "p" parameter is a pointer to the outer query.
133469  ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
133470  ** uses aggregates.
133471  **
133472  ** If flattening is not attempted, this routine is a no-op and returns 0.
133473  ** If flattening is attempted this routine returns 1.
133474  **
133475  ** All of the expression analysis must occur on both the outer query and
133476  ** the subquery before this routine runs.
133477  */
133478  static int flattenSubquery(
133479    Parse *pParse,       /* Parsing context */
133480    Select *p,           /* The parent or outer SELECT statement */
133481    int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
133482    int isAgg            /* True if outer SELECT uses aggregate functions */
133483  ){
133484    const char *zSavedAuthContext = pParse->zAuthContext;
133485    Select *pParent;    /* Current UNION ALL term of the other query */
133486    Select *pSub;       /* The inner query or "subquery" */
133487    Select *pSub1;      /* Pointer to the rightmost select in sub-query */
133488    SrcList *pSrc;      /* The FROM clause of the outer query */
133489    SrcList *pSubSrc;   /* The FROM clause of the subquery */
133490    int iParent;        /* VDBE cursor number of the pSub result set temp table */
133491    int iNewParent = -1;/* Replacement table for iParent */
133492    int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */    
133493    int i;              /* Loop counter */
133494    Expr *pWhere;                    /* The WHERE clause */
133495    struct SrcList_item *pSubitem;   /* The subquery */
133496    sqlite3 *db = pParse->db;
133497  
133498    /* Check to see if flattening is permitted.  Return 0 if not.
133499    */
133500    assert( p!=0 );
133501    assert( p->pPrior==0 );
133502    if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
133503    pSrc = p->pSrc;
133504    assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
133505    pSubitem = &pSrc->a[iFrom];
133506    iParent = pSubitem->iCursor;
133507    pSub = pSubitem->pSelect;
133508    assert( pSub!=0 );
133509  
133510  #ifndef SQLITE_OMIT_WINDOWFUNC
133511    if( p->pWin || pSub->pWin ) return 0;                  /* Restriction (25) */
133512  #endif
133513  
133514    pSubSrc = pSub->pSrc;
133515    assert( pSubSrc );
133516    /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
133517    ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
133518    ** because they could be computed at compile-time.  But when LIMIT and OFFSET
133519    ** became arbitrary expressions, we were forced to add restrictions (13)
133520    ** and (14). */
133521    if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
133522    if( pSub->pLimit && pSub->pLimit->pRight ) return 0;   /* Restriction (14) */
133523    if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
133524      return 0;                                            /* Restriction (15) */
133525    }
133526    if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
133527    if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (4)  */
133528    if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
133529       return 0;         /* Restrictions (8)(9) */
133530    }
133531    if( p->pOrderBy && pSub->pOrderBy ){
133532       return 0;                                           /* Restriction (11) */
133533    }
133534    if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
133535    if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
133536    if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
133537       return 0;         /* Restriction (21) */
133538    }
133539    if( pSub->selFlags & (SF_Recursive) ){
133540      return 0; /* Restrictions (22) */
133541    }
133542  
133543    /*
133544    ** If the subquery is the right operand of a LEFT JOIN, then the
133545    ** subquery may not be a join itself (3a). Example of why this is not
133546    ** allowed:
133547    **
133548    **         t1 LEFT OUTER JOIN (t2 JOIN t3)
133549    **
133550    ** If we flatten the above, we would get
133551    **
133552    **         (t1 LEFT OUTER JOIN t2) JOIN t3
133553    **
133554    ** which is not at all the same thing.
133555    **
133556    ** If the subquery is the right operand of a LEFT JOIN, then the outer
133557    ** query cannot be an aggregate. (3c)  This is an artifact of the way
133558    ** aggregates are processed - there is no mechanism to determine if
133559    ** the LEFT JOIN table should be all-NULL.
133560    **
133561    ** See also tickets #306, #350, and #3300.
133562    */
133563    if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
133564      isLeftJoin = 1;
133565      if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
133566        /*  (3a)             (3c)     (3b) */
133567        return 0;
133568      }
133569    }
133570  #ifdef SQLITE_EXTRA_IFNULLROW
133571    else if( iFrom>0 && !isAgg ){
133572      /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
133573      ** every reference to any result column from subquery in a join, even
133574      ** though they are not necessary.  This will stress-test the OP_IfNullRow 
133575      ** opcode. */
133576      isLeftJoin = -1;
133577    }
133578  #endif
133579  
133580    /* Restriction (17): If the sub-query is a compound SELECT, then it must
133581    ** use only the UNION ALL operator. And none of the simple select queries
133582    ** that make up the compound SELECT are allowed to be aggregate or distinct
133583    ** queries.
133584    */
133585    if( pSub->pPrior ){
133586      if( pSub->pOrderBy ){
133587        return 0;  /* Restriction (20) */
133588      }
133589      if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
133590        return 0; /* (17d1), (17d2), or (17d3) */
133591      }
133592      for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
133593        testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
133594        testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
133595        assert( pSub->pSrc!=0 );
133596        assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
133597        if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
133598         || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
133599         || pSub1->pSrc->nSrc<1                                  /* (17c) */
133600        ){
133601          return 0;
133602        }
133603        testcase( pSub1->pSrc->nSrc>1 );
133604      }
133605  
133606      /* Restriction (18). */
133607      if( p->pOrderBy ){
133608        int ii;
133609        for(ii=0; ii<p->pOrderBy->nExpr; ii++){
133610          if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
133611        }
133612      }
133613    }
133614  
133615    /* Ex-restriction (23):
133616    ** The only way that the recursive part of a CTE can contain a compound
133617    ** subquery is for the subquery to be one term of a join.  But if the
133618    ** subquery is a join, then the flattening has already been stopped by
133619    ** restriction (17d3)
133620    */
133621    assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
133622  
133623    /***** If we reach this point, flattening is permitted. *****/
133624    SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
133625                     pSub->selId, pSub, iFrom));
133626  
133627    /* Authorize the subquery */
133628    pParse->zAuthContext = pSubitem->zName;
133629    TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
133630    testcase( i==SQLITE_DENY );
133631    pParse->zAuthContext = zSavedAuthContext;
133632  
133633    /* If the sub-query is a compound SELECT statement, then (by restrictions
133634    ** 17 and 18 above) it must be a UNION ALL and the parent query must 
133635    ** be of the form:
133636    **
133637    **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
133638    **
133639    ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
133640    ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
133641    ** OFFSET clauses and joins them to the left-hand-side of the original
133642    ** using UNION ALL operators. In this case N is the number of simple
133643    ** select statements in the compound sub-query.
133644    **
133645    ** Example:
133646    **
133647    **     SELECT a+1 FROM (
133648    **        SELECT x FROM tab
133649    **        UNION ALL
133650    **        SELECT y FROM tab
133651    **        UNION ALL
133652    **        SELECT abs(z*2) FROM tab2
133653    **     ) WHERE a!=5 ORDER BY 1
133654    **
133655    ** Transformed into:
133656    **
133657    **     SELECT x+1 FROM tab WHERE x+1!=5
133658    **     UNION ALL
133659    **     SELECT y+1 FROM tab WHERE y+1!=5
133660    **     UNION ALL
133661    **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
133662    **     ORDER BY 1
133663    **
133664    ** We call this the "compound-subquery flattening".
133665    */
133666    for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
133667      Select *pNew;
133668      ExprList *pOrderBy = p->pOrderBy;
133669      Expr *pLimit = p->pLimit;
133670      Select *pPrior = p->pPrior;
133671      p->pOrderBy = 0;
133672      p->pSrc = 0;
133673      p->pPrior = 0;
133674      p->pLimit = 0;
133675      pNew = sqlite3SelectDup(db, p, 0);
133676      p->pLimit = pLimit;
133677      p->pOrderBy = pOrderBy;
133678      p->pSrc = pSrc;
133679      p->op = TK_ALL;
133680      if( pNew==0 ){
133681        p->pPrior = pPrior;
133682      }else{
133683        pNew->pPrior = pPrior;
133684        if( pPrior ) pPrior->pNext = pNew;
133685        pNew->pNext = p;
133686        p->pPrior = pNew;
133687        SELECTTRACE(2,pParse,p,("compound-subquery flattener"
133688                                " creates %u as peer\n",pNew->selId));
133689      }
133690      if( db->mallocFailed ) return 1;
133691    }
133692  
133693    /* Begin flattening the iFrom-th entry of the FROM clause 
133694    ** in the outer query.
133695    */
133696    pSub = pSub1 = pSubitem->pSelect;
133697  
133698    /* Delete the transient table structure associated with the
133699    ** subquery
133700    */
133701    sqlite3DbFree(db, pSubitem->zDatabase);
133702    sqlite3DbFree(db, pSubitem->zName);
133703    sqlite3DbFree(db, pSubitem->zAlias);
133704    pSubitem->zDatabase = 0;
133705    pSubitem->zName = 0;
133706    pSubitem->zAlias = 0;
133707    pSubitem->pSelect = 0;
133708  
133709    /* Defer deleting the Table object associated with the
133710    ** subquery until code generation is
133711    ** complete, since there may still exist Expr.pTab entries that
133712    ** refer to the subquery even after flattening.  Ticket #3346.
133713    **
133714    ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
133715    */
133716    if( ALWAYS(pSubitem->pTab!=0) ){
133717      Table *pTabToDel = pSubitem->pTab;
133718      if( pTabToDel->nTabRef==1 ){
133719        Parse *pToplevel = sqlite3ParseToplevel(pParse);
133720        pTabToDel->pNextZombie = pToplevel->pZombieTab;
133721        pToplevel->pZombieTab = pTabToDel;
133722      }else{
133723        pTabToDel->nTabRef--;
133724      }
133725      pSubitem->pTab = 0;
133726    }
133727  
133728    /* The following loop runs once for each term in a compound-subquery
133729    ** flattening (as described above).  If we are doing a different kind
133730    ** of flattening - a flattening other than a compound-subquery flattening -
133731    ** then this loop only runs once.
133732    **
133733    ** This loop moves all of the FROM elements of the subquery into the
133734    ** the FROM clause of the outer query.  Before doing this, remember
133735    ** the cursor number for the original outer query FROM element in
133736    ** iParent.  The iParent cursor will never be used.  Subsequent code
133737    ** will scan expressions looking for iParent references and replace
133738    ** those references with expressions that resolve to the subquery FROM
133739    ** elements we are now copying in.
133740    */
133741    for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
133742      int nSubSrc;
133743      u8 jointype = 0;
133744      pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
133745      nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
133746      pSrc = pParent->pSrc;     /* FROM clause of the outer query */
133747  
133748      if( pSrc ){
133749        assert( pParent==p );  /* First time through the loop */
133750        jointype = pSubitem->fg.jointype;
133751      }else{
133752        assert( pParent!=p );  /* 2nd and subsequent times through the loop */
133753        pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
133754        if( pSrc==0 ) break;
133755        pParent->pSrc = pSrc;
133756      }
133757  
133758      /* The subquery uses a single slot of the FROM clause of the outer
133759      ** query.  If the subquery has more than one element in its FROM clause,
133760      ** then expand the outer query to make space for it to hold all elements
133761      ** of the subquery.
133762      **
133763      ** Example:
133764      **
133765      **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
133766      **
133767      ** The outer query has 3 slots in its FROM clause.  One slot of the
133768      ** outer query (the middle slot) is used by the subquery.  The next
133769      ** block of code will expand the outer query FROM clause to 4 slots.
133770      ** The middle slot is expanded to two slots in order to make space
133771      ** for the two elements in the FROM clause of the subquery.
133772      */
133773      if( nSubSrc>1 ){
133774        pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
133775        if( pSrc==0 ) break;
133776        pParent->pSrc = pSrc;
133777      }
133778  
133779      /* Transfer the FROM clause terms from the subquery into the
133780      ** outer query.
133781      */
133782      for(i=0; i<nSubSrc; i++){
133783        sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
133784        assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
133785        pSrc->a[i+iFrom] = pSubSrc->a[i];
133786        iNewParent = pSubSrc->a[i].iCursor;
133787        memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
133788      }
133789      pSrc->a[iFrom].fg.jointype = jointype;
133790    
133791      /* Now begin substituting subquery result set expressions for 
133792      ** references to the iParent in the outer query.
133793      ** 
133794      ** Example:
133795      **
133796      **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
133797      **   \                     \_____________ subquery __________/          /
133798      **    \_____________________ outer query ______________________________/
133799      **
133800      ** We look at every expression in the outer query and every place we see
133801      ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
133802      */
133803      if( pSub->pOrderBy ){
133804        /* At this point, any non-zero iOrderByCol values indicate that the
133805        ** ORDER BY column expression is identical to the iOrderByCol'th
133806        ** expression returned by SELECT statement pSub. Since these values
133807        ** do not necessarily correspond to columns in SELECT statement pParent,
133808        ** zero them before transfering the ORDER BY clause.
133809        **
133810        ** Not doing this may cause an error if a subsequent call to this
133811        ** function attempts to flatten a compound sub-query into pParent
133812        ** (the only way this can happen is if the compound sub-query is
133813        ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
133814        ExprList *pOrderBy = pSub->pOrderBy;
133815        for(i=0; i<pOrderBy->nExpr; i++){
133816          pOrderBy->a[i].u.x.iOrderByCol = 0;
133817        }
133818        assert( pParent->pOrderBy==0 );
133819        pParent->pOrderBy = pOrderBy;
133820        pSub->pOrderBy = 0;
133821      }
133822      pWhere = pSub->pWhere;
133823      pSub->pWhere = 0;
133824      if( isLeftJoin>0 ){
133825        setJoinExpr(pWhere, iNewParent);
133826      }
133827      pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
133828      if( db->mallocFailed==0 ){
133829        SubstContext x;
133830        x.pParse = pParse;
133831        x.iTable = iParent;
133832        x.iNewTable = iNewParent;
133833        x.isLeftJoin = isLeftJoin;
133834        x.pEList = pSub->pEList;
133835        substSelect(&x, pParent, 0);
133836      }
133837    
133838      /* The flattened query is distinct if either the inner or the
133839      ** outer query is distinct. 
133840      */
133841      pParent->selFlags |= pSub->selFlags & SF_Distinct;
133842    
133843      /*
133844      ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
133845      **
133846      ** One is tempted to try to add a and b to combine the limits.  But this
133847      ** does not work if either limit is negative.
133848      */
133849      if( pSub->pLimit ){
133850        pParent->pLimit = pSub->pLimit;
133851        pSub->pLimit = 0;
133852      }
133853    }
133854  
133855    /* Finially, delete what is left of the subquery and return
133856    ** success.
133857    */
133858    sqlite3SelectDelete(db, pSub1);
133859  
133860  #if SELECTTRACE_ENABLED
133861    if( sqlite3SelectTrace & 0x100 ){
133862      SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
133863      sqlite3TreeViewSelect(0, p, 0);
133864    }
133865  #endif
133866  
133867    return 1;
133868  }
133869  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
133870  
133871  /*
133872  ** A structure to keep track of all of the column values that are fixed to
133873  ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
133874  */
133875  typedef struct WhereConst WhereConst;
133876  struct WhereConst {
133877    Parse *pParse;   /* Parsing context */
133878    int nConst;      /* Number for COLUMN=CONSTANT terms */
133879    int nChng;       /* Number of times a constant is propagated */
133880    Expr **apExpr;   /* [i*2] is COLUMN and [i*2+1] is VALUE */
133881  };
133882  
133883  /*
133884  ** Add a new entry to the pConst object.  Except, do not add duplicate
133885  ** pColumn entires.
133886  */
133887  static void constInsert(
133888    WhereConst *pConst,      /* The WhereConst into which we are inserting */
133889    Expr *pColumn,           /* The COLUMN part of the constraint */
133890    Expr *pValue             /* The VALUE part of the constraint */
133891  ){
133892    int i;
133893    assert( pColumn->op==TK_COLUMN );
133894  
133895    /* 2018-10-25 ticket [cf5ed20f]
133896    ** Make sure the same pColumn is not inserted more than once */
133897    for(i=0; i<pConst->nConst; i++){
133898      const Expr *pExpr = pConst->apExpr[i*2];
133899      assert( pExpr->op==TK_COLUMN );
133900      if( pExpr->iTable==pColumn->iTable
133901       && pExpr->iColumn==pColumn->iColumn
133902      ){
133903        return;  /* Already present.  Return without doing anything. */
133904      }
133905    }
133906  
133907    pConst->nConst++;
133908    pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
133909                           pConst->nConst*2*sizeof(Expr*));
133910    if( pConst->apExpr==0 ){
133911      pConst->nConst = 0;
133912    }else{
133913      if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
133914      pConst->apExpr[pConst->nConst*2-2] = pColumn;
133915      pConst->apExpr[pConst->nConst*2-1] = pValue;
133916    }
133917  }
133918  
133919  /*
133920  ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
133921  ** is a constant expression and where the term must be true because it
133922  ** is part of the AND-connected terms of the expression.  For each term
133923  ** found, add it to the pConst structure.
133924  */
133925  static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
133926    Expr *pRight, *pLeft;
133927    if( pExpr==0 ) return;
133928    if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
133929    if( pExpr->op==TK_AND ){
133930      findConstInWhere(pConst, pExpr->pRight);
133931      findConstInWhere(pConst, pExpr->pLeft);
133932      return;
133933    }
133934    if( pExpr->op!=TK_EQ ) return;
133935    pRight = pExpr->pRight;
133936    pLeft = pExpr->pLeft;
133937    assert( pRight!=0 );
133938    assert( pLeft!=0 );
133939    if( pRight->op==TK_COLUMN
133940     && !ExprHasProperty(pRight, EP_FixedCol)
133941     && sqlite3ExprIsConstant(pLeft)
133942     && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
133943    ){
133944      constInsert(pConst, pRight, pLeft);
133945    }else
133946    if( pLeft->op==TK_COLUMN
133947     && !ExprHasProperty(pLeft, EP_FixedCol)
133948     && sqlite3ExprIsConstant(pRight)
133949     && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
133950    ){
133951      constInsert(pConst, pLeft, pRight);
133952    }
133953  }
133954  
133955  /*
133956  ** This is a Walker expression callback.  pExpr is a candidate expression
133957  ** to be replaced by a value.  If pExpr is equivalent to one of the
133958  ** columns named in pWalker->u.pConst, then overwrite it with its
133959  ** corresponding value.
133960  */
133961  static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
133962    int i;
133963    WhereConst *pConst;
133964    if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
133965    if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
133966    pConst = pWalker->u.pConst;
133967    for(i=0; i<pConst->nConst; i++){
133968      Expr *pColumn = pConst->apExpr[i*2];
133969      if( pColumn==pExpr ) continue;
133970      if( pColumn->iTable!=pExpr->iTable ) continue;
133971      if( pColumn->iColumn!=pExpr->iColumn ) continue;
133972      /* A match is found.  Add the EP_FixedCol property */
133973      pConst->nChng++;
133974      ExprClearProperty(pExpr, EP_Leaf);
133975      ExprSetProperty(pExpr, EP_FixedCol);
133976      assert( pExpr->pLeft==0 );
133977      pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
133978      break;
133979    }
133980    return WRC_Prune;
133981  }
133982  
133983  /*
133984  ** The WHERE-clause constant propagation optimization.
133985  **
133986  ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
133987  ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
133988  ** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
133989  ** then throughout the query replace all other occurrences of COLUMN
133990  ** with CONSTANT within the WHERE clause.
133991  **
133992  ** For example, the query:
133993  **
133994  **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
133995  **
133996  ** Is transformed into
133997  **
133998  **      SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
133999  **
134000  ** Return true if any transformations where made and false if not.
134001  **
134002  ** Implementation note:  Constant propagation is tricky due to affinity
134003  ** and collating sequence interactions.  Consider this example:
134004  **
134005  **    CREATE TABLE t1(a INT,b TEXT);
134006  **    INSERT INTO t1 VALUES(123,'0123');
134007  **    SELECT * FROM t1 WHERE a=123 AND b=a;
134008  **    SELECT * FROM t1 WHERE a=123 AND b=123;
134009  **
134010  ** The two SELECT statements above should return different answers.  b=a
134011  ** is alway true because the comparison uses numeric affinity, but b=123
134012  ** is false because it uses text affinity and '0123' is not the same as '123'.
134013  ** To work around this, the expression tree is not actually changed from
134014  ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
134015  ** and the "123" value is hung off of the pLeft pointer.  Code generator
134016  ** routines know to generate the constant "123" instead of looking up the
134017  ** column value.  Also, to avoid collation problems, this optimization is
134018  ** only attempted if the "a=123" term uses the default BINARY collation.
134019  */
134020  static int propagateConstants(
134021    Parse *pParse,   /* The parsing context */
134022    Select *p        /* The query in which to propagate constants */
134023  ){
134024    WhereConst x;
134025    Walker w;
134026    int nChng = 0;
134027    x.pParse = pParse;
134028    do{
134029      x.nConst = 0;
134030      x.nChng = 0;
134031      x.apExpr = 0;
134032      findConstInWhere(&x, p->pWhere);
134033      if( x.nConst ){
134034        memset(&w, 0, sizeof(w));
134035        w.pParse = pParse;
134036        w.xExprCallback = propagateConstantExprRewrite;
134037        w.xSelectCallback = sqlite3SelectWalkNoop;
134038        w.xSelectCallback2 = 0;
134039        w.walkerDepth = 0;
134040        w.u.pConst = &x;
134041        sqlite3WalkExpr(&w, p->pWhere);
134042        sqlite3DbFree(x.pParse->db, x.apExpr);
134043        nChng += x.nChng;
134044      }
134045    }while( x.nChng );  
134046    return nChng;
134047  }
134048  
134049  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
134050  /*
134051  ** Make copies of relevant WHERE clause terms of the outer query into
134052  ** the WHERE clause of subquery.  Example:
134053  **
134054  **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
134055  **
134056  ** Transformed into:
134057  **
134058  **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
134059  **     WHERE x=5 AND y=10;
134060  **
134061  ** The hope is that the terms added to the inner query will make it more
134062  ** efficient.
134063  **
134064  ** Do not attempt this optimization if:
134065  **
134066  **   (1) (** This restriction was removed on 2017-09-29.  We used to
134067  **           disallow this optimization for aggregate subqueries, but now
134068  **           it is allowed by putting the extra terms on the HAVING clause.
134069  **           The added HAVING clause is pointless if the subquery lacks
134070  **           a GROUP BY clause.  But such a HAVING clause is also harmless
134071  **           so there does not appear to be any reason to add extra logic
134072  **           to suppress it. **)
134073  **
134074  **   (2) The inner query is the recursive part of a common table expression.
134075  **
134076  **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
134077  **       clause would change the meaning of the LIMIT).
134078  **
134079  **   (4) The inner query is the right operand of a LEFT JOIN and the
134080  **       expression to be pushed down does not come from the ON clause
134081  **       on that LEFT JOIN.
134082  **
134083  **   (5) The WHERE clause expression originates in the ON or USING clause
134084  **       of a LEFT JOIN where iCursor is not the right-hand table of that
134085  **       left join.  An example:
134086  **
134087  **           SELECT *
134088  **           FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
134089  **           JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
134090  **           LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
134091  **
134092  **       The correct answer is three rows:  (1,1,NULL),(2,2,8),(2,2,9).
134093  **       But if the (b2=2) term were to be pushed down into the bb subquery,
134094  **       then the (1,1,NULL) row would be suppressed.
134095  **
134096  **   (6) The inner query features one or more window-functions (since 
134097  **       changes to the WHERE clause of the inner query could change the 
134098  **       window over which window functions are calculated).
134099  **
134100  ** Return 0 if no changes are made and non-zero if one or more WHERE clause
134101  ** terms are duplicated into the subquery.
134102  */
134103  static int pushDownWhereTerms(
134104    Parse *pParse,        /* Parse context (for malloc() and error reporting) */
134105    Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
134106    Expr *pWhere,         /* The WHERE clause of the outer query */
134107    int iCursor,          /* Cursor number of the subquery */
134108    int isLeftJoin        /* True if pSubq is the right term of a LEFT JOIN */
134109  ){
134110    Expr *pNew;
134111    int nChng = 0;
134112    if( pWhere==0 ) return 0;
134113    if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */
134114  
134115  #ifndef SQLITE_OMIT_WINDOWFUNC
134116    if( pSubq->pWin ) return 0;    /* restriction (6) */
134117  #endif
134118  
134119  #ifdef SQLITE_DEBUG
134120    /* Only the first term of a compound can have a WITH clause.  But make
134121    ** sure no other terms are marked SF_Recursive in case something changes
134122    ** in the future.
134123    */
134124    {
134125      Select *pX;  
134126      for(pX=pSubq; pX; pX=pX->pPrior){
134127        assert( (pX->selFlags & (SF_Recursive))==0 );
134128      }
134129    }
134130  #endif
134131  
134132    if( pSubq->pLimit!=0 ){
134133      return 0; /* restriction (3) */
134134    }
134135    while( pWhere->op==TK_AND ){
134136      nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
134137                                  iCursor, isLeftJoin);
134138      pWhere = pWhere->pLeft;
134139    }
134140    if( isLeftJoin
134141     && (ExprHasProperty(pWhere,EP_FromJoin)==0
134142           || pWhere->iRightJoinTable!=iCursor)
134143    ){
134144      return 0; /* restriction (4) */
134145    }
134146    if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
134147      return 0; /* restriction (5) */
134148    }
134149    if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
134150      nChng++;
134151      while( pSubq ){
134152        SubstContext x;
134153        pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
134154        unsetJoinExpr(pNew, -1);
134155        x.pParse = pParse;
134156        x.iTable = iCursor;
134157        x.iNewTable = iCursor;
134158        x.isLeftJoin = 0;
134159        x.pEList = pSubq->pEList;
134160        pNew = substExpr(&x, pNew);
134161        if( pSubq->selFlags & SF_Aggregate ){
134162          pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
134163        }else{
134164          pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
134165        }
134166        pSubq = pSubq->pPrior;
134167      }
134168    }
134169    return nChng;
134170  }
134171  #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
134172  
134173  /*
134174  ** The pFunc is the only aggregate function in the query.  Check to see
134175  ** if the query is a candidate for the min/max optimization. 
134176  **
134177  ** If the query is a candidate for the min/max optimization, then set
134178  ** *ppMinMax to be an ORDER BY clause to be used for the optimization
134179  ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
134180  ** whether pFunc is a min() or max() function.
134181  **
134182  ** If the query is not a candidate for the min/max optimization, return
134183  ** WHERE_ORDERBY_NORMAL (which must be zero).
134184  **
134185  ** This routine must be called after aggregate functions have been
134186  ** located but before their arguments have been subjected to aggregate
134187  ** analysis.
134188  */
134189  static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
134190    int eRet = WHERE_ORDERBY_NORMAL;      /* Return value */
134191    ExprList *pEList = pFunc->x.pList;    /* Arguments to agg function */
134192    const char *zFunc;                    /* Name of aggregate function pFunc */
134193    ExprList *pOrderBy;
134194    u8 sortOrder;
134195  
134196    assert( *ppMinMax==0 );
134197    assert( pFunc->op==TK_AGG_FUNCTION );
134198    if( pEList==0 || pEList->nExpr!=1 ) return eRet;
134199    zFunc = pFunc->u.zToken;
134200    if( sqlite3StrICmp(zFunc, "min")==0 ){
134201      eRet = WHERE_ORDERBY_MIN;
134202      sortOrder = SQLITE_SO_ASC;
134203    }else if( sqlite3StrICmp(zFunc, "max")==0 ){
134204      eRet = WHERE_ORDERBY_MAX;
134205      sortOrder = SQLITE_SO_DESC;
134206    }else{
134207      return eRet;
134208    }
134209    *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
134210    assert( pOrderBy!=0 || db->mallocFailed );
134211    if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
134212    return eRet;
134213  }
134214  
134215  /*
134216  ** The select statement passed as the first argument is an aggregate query.
134217  ** The second argument is the associated aggregate-info object. This 
134218  ** function tests if the SELECT is of the form:
134219  **
134220  **   SELECT count(*) FROM <tbl>
134221  **
134222  ** where table is a database table, not a sub-select or view. If the query
134223  ** does match this pattern, then a pointer to the Table object representing
134224  ** <tbl> is returned. Otherwise, 0 is returned.
134225  */
134226  static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
134227    Table *pTab;
134228    Expr *pExpr;
134229  
134230    assert( !p->pGroupBy );
134231  
134232    if( p->pWhere || p->pEList->nExpr!=1 
134233     || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
134234    ){
134235      return 0;
134236    }
134237    pTab = p->pSrc->a[0].pTab;
134238    pExpr = p->pEList->a[0].pExpr;
134239    assert( pTab && !pTab->pSelect && pExpr );
134240  
134241    if( IsVirtual(pTab) ) return 0;
134242    if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
134243    if( NEVER(pAggInfo->nFunc==0) ) return 0;
134244    if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
134245    if( pExpr->flags&EP_Distinct ) return 0;
134246  
134247    return pTab;
134248  }
134249  
134250  /*
134251  ** If the source-list item passed as an argument was augmented with an
134252  ** INDEXED BY clause, then try to locate the specified index. If there
134253  ** was such a clause and the named index cannot be found, return 
134254  ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
134255  ** pFrom->pIndex and return SQLITE_OK.
134256  */
134257  SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
134258    if( pFrom->pTab && pFrom->fg.isIndexedBy ){
134259      Table *pTab = pFrom->pTab;
134260      char *zIndexedBy = pFrom->u1.zIndexedBy;
134261      Index *pIdx;
134262      for(pIdx=pTab->pIndex; 
134263          pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 
134264          pIdx=pIdx->pNext
134265      );
134266      if( !pIdx ){
134267        sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
134268        pParse->checkSchema = 1;
134269        return SQLITE_ERROR;
134270      }
134271      pFrom->pIBIndex = pIdx;
134272    }
134273    return SQLITE_OK;
134274  }
134275  /*
134276  ** Detect compound SELECT statements that use an ORDER BY clause with 
134277  ** an alternative collating sequence.
134278  **
134279  **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
134280  **
134281  ** These are rewritten as a subquery:
134282  **
134283  **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
134284  **     ORDER BY ... COLLATE ...
134285  **
134286  ** This transformation is necessary because the multiSelectOrderBy() routine
134287  ** above that generates the code for a compound SELECT with an ORDER BY clause
134288  ** uses a merge algorithm that requires the same collating sequence on the
134289  ** result columns as on the ORDER BY clause.  See ticket
134290  ** http://www.sqlite.org/src/info/6709574d2a
134291  **
134292  ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
134293  ** The UNION ALL operator works fine with multiSelectOrderBy() even when
134294  ** there are COLLATE terms in the ORDER BY.
134295  */
134296  static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
134297    int i;
134298    Select *pNew;
134299    Select *pX;
134300    sqlite3 *db;
134301    struct ExprList_item *a;
134302    SrcList *pNewSrc;
134303    Parse *pParse;
134304    Token dummy;
134305  
134306    if( p->pPrior==0 ) return WRC_Continue;
134307    if( p->pOrderBy==0 ) return WRC_Continue;
134308    for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
134309    if( pX==0 ) return WRC_Continue;
134310    a = p->pOrderBy->a;
134311    for(i=p->pOrderBy->nExpr-1; i>=0; i--){
134312      if( a[i].pExpr->flags & EP_Collate ) break;
134313    }
134314    if( i<0 ) return WRC_Continue;
134315  
134316    /* If we reach this point, that means the transformation is required. */
134317  
134318    pParse = pWalker->pParse;
134319    db = pParse->db;
134320    pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
134321    if( pNew==0 ) return WRC_Abort;
134322    memset(&dummy, 0, sizeof(dummy));
134323    pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
134324    if( pNewSrc==0 ) return WRC_Abort;
134325    *pNew = *p;
134326    p->pSrc = pNewSrc;
134327    p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
134328    p->op = TK_SELECT;
134329    p->pWhere = 0;
134330    pNew->pGroupBy = 0;
134331    pNew->pHaving = 0;
134332    pNew->pOrderBy = 0;
134333    p->pPrior = 0;
134334    p->pNext = 0;
134335    p->pWith = 0;
134336    p->selFlags &= ~SF_Compound;
134337    assert( (p->selFlags & SF_Converted)==0 );
134338    p->selFlags |= SF_Converted;
134339    assert( pNew->pPrior!=0 );
134340    pNew->pPrior->pNext = pNew;
134341    pNew->pLimit = 0;
134342    return WRC_Continue;
134343  }
134344  
134345  /*
134346  ** Check to see if the FROM clause term pFrom has table-valued function
134347  ** arguments.  If it does, leave an error message in pParse and return
134348  ** non-zero, since pFrom is not allowed to be a table-valued function.
134349  */
134350  static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
134351    if( pFrom->fg.isTabFunc ){
134352      sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
134353      return 1;
134354    }
134355    return 0;
134356  }
134357  
134358  #ifndef SQLITE_OMIT_CTE
134359  /*
134360  ** Argument pWith (which may be NULL) points to a linked list of nested 
134361  ** WITH contexts, from inner to outermost. If the table identified by 
134362  ** FROM clause element pItem is really a common-table-expression (CTE) 
134363  ** then return a pointer to the CTE definition for that table. Otherwise
134364  ** return NULL.
134365  **
134366  ** If a non-NULL value is returned, set *ppContext to point to the With
134367  ** object that the returned CTE belongs to.
134368  */
134369  static struct Cte *searchWith(
134370    With *pWith,                    /* Current innermost WITH clause */
134371    struct SrcList_item *pItem,     /* FROM clause element to resolve */
134372    With **ppContext                /* OUT: WITH clause return value belongs to */
134373  ){
134374    const char *zName;
134375    if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
134376      With *p;
134377      for(p=pWith; p; p=p->pOuter){
134378        int i;
134379        for(i=0; i<p->nCte; i++){
134380          if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
134381            *ppContext = p;
134382            return &p->a[i];
134383          }
134384        }
134385      }
134386    }
134387    return 0;
134388  }
134389  
134390  /* The code generator maintains a stack of active WITH clauses
134391  ** with the inner-most WITH clause being at the top of the stack.
134392  **
134393  ** This routine pushes the WITH clause passed as the second argument
134394  ** onto the top of the stack. If argument bFree is true, then this
134395  ** WITH clause will never be popped from the stack. In this case it
134396  ** should be freed along with the Parse object. In other cases, when
134397  ** bFree==0, the With object will be freed along with the SELECT 
134398  ** statement with which it is associated.
134399  */
134400  SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
134401    assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
134402    if( pWith ){
134403      assert( pParse->pWith!=pWith );
134404      pWith->pOuter = pParse->pWith;
134405      pParse->pWith = pWith;
134406      if( bFree ) pParse->pWithToFree = pWith;
134407    }
134408  }
134409  
134410  /*
134411  ** This function checks if argument pFrom refers to a CTE declared by 
134412  ** a WITH clause on the stack currently maintained by the parser. And,
134413  ** if currently processing a CTE expression, if it is a recursive
134414  ** reference to the current CTE.
134415  **
134416  ** If pFrom falls into either of the two categories above, pFrom->pTab
134417  ** and other fields are populated accordingly. The caller should check
134418  ** (pFrom->pTab!=0) to determine whether or not a successful match
134419  ** was found.
134420  **
134421  ** Whether or not a match is found, SQLITE_OK is returned if no error
134422  ** occurs. If an error does occur, an error message is stored in the
134423  ** parser and some error code other than SQLITE_OK returned.
134424  */
134425  static int withExpand(
134426    Walker *pWalker, 
134427    struct SrcList_item *pFrom
134428  ){
134429    Parse *pParse = pWalker->pParse;
134430    sqlite3 *db = pParse->db;
134431    struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
134432    With *pWith;                    /* WITH clause that pCte belongs to */
134433  
134434    assert( pFrom->pTab==0 );
134435  
134436    pCte = searchWith(pParse->pWith, pFrom, &pWith);
134437    if( pCte ){
134438      Table *pTab;
134439      ExprList *pEList;
134440      Select *pSel;
134441      Select *pLeft;                /* Left-most SELECT statement */
134442      int bMayRecursive;            /* True if compound joined by UNION [ALL] */
134443      With *pSavedWith;             /* Initial value of pParse->pWith */
134444  
134445      /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
134446      ** recursive reference to CTE pCte. Leave an error in pParse and return
134447      ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
134448      ** In this case, proceed.  */
134449      if( pCte->zCteErr ){
134450        sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
134451        return SQLITE_ERROR;
134452      }
134453      if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
134454  
134455      assert( pFrom->pTab==0 );
134456      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
134457      if( pTab==0 ) return WRC_Abort;
134458      pTab->nTabRef = 1;
134459      pTab->zName = sqlite3DbStrDup(db, pCte->zName);
134460      pTab->iPKey = -1;
134461      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
134462      pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
134463      pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
134464      if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
134465      assert( pFrom->pSelect );
134466  
134467      /* Check if this is a recursive CTE. */
134468      pSel = pFrom->pSelect;
134469      bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
134470      if( bMayRecursive ){
134471        int i;
134472        SrcList *pSrc = pFrom->pSelect->pSrc;
134473        for(i=0; i<pSrc->nSrc; i++){
134474          struct SrcList_item *pItem = &pSrc->a[i];
134475          if( pItem->zDatabase==0 
134476           && pItem->zName!=0 
134477           && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
134478            ){
134479            pItem->pTab = pTab;
134480            pItem->fg.isRecursive = 1;
134481            pTab->nTabRef++;
134482            pSel->selFlags |= SF_Recursive;
134483          }
134484        }
134485      }
134486  
134487      /* Only one recursive reference is permitted. */ 
134488      if( pTab->nTabRef>2 ){
134489        sqlite3ErrorMsg(
134490            pParse, "multiple references to recursive table: %s", pCte->zName
134491        );
134492        return SQLITE_ERROR;
134493      }
134494      assert( pTab->nTabRef==1 || 
134495              ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
134496  
134497      pCte->zCteErr = "circular reference: %s";
134498      pSavedWith = pParse->pWith;
134499      pParse->pWith = pWith;
134500      if( bMayRecursive ){
134501        Select *pPrior = pSel->pPrior;
134502        assert( pPrior->pWith==0 );
134503        pPrior->pWith = pSel->pWith;
134504        sqlite3WalkSelect(pWalker, pPrior);
134505        pPrior->pWith = 0;
134506      }else{
134507        sqlite3WalkSelect(pWalker, pSel);
134508      }
134509      pParse->pWith = pWith;
134510  
134511      for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
134512      pEList = pLeft->pEList;
134513      if( pCte->pCols ){
134514        if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
134515          sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
134516              pCte->zName, pEList->nExpr, pCte->pCols->nExpr
134517          );
134518          pParse->pWith = pSavedWith;
134519          return SQLITE_ERROR;
134520        }
134521        pEList = pCte->pCols;
134522      }
134523  
134524      sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
134525      if( bMayRecursive ){
134526        if( pSel->selFlags & SF_Recursive ){
134527          pCte->zCteErr = "multiple recursive references: %s";
134528        }else{
134529          pCte->zCteErr = "recursive reference in a subquery: %s";
134530        }
134531        sqlite3WalkSelect(pWalker, pSel);
134532      }
134533      pCte->zCteErr = 0;
134534      pParse->pWith = pSavedWith;
134535    }
134536  
134537    return SQLITE_OK;
134538  }
134539  #endif
134540  
134541  #ifndef SQLITE_OMIT_CTE
134542  /*
134543  ** If the SELECT passed as the second argument has an associated WITH 
134544  ** clause, pop it from the stack stored as part of the Parse object.
134545  **
134546  ** This function is used as the xSelectCallback2() callback by
134547  ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
134548  ** names and other FROM clause elements. 
134549  */
134550  static void selectPopWith(Walker *pWalker, Select *p){
134551    Parse *pParse = pWalker->pParse;
134552    if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
134553      With *pWith = findRightmost(p)->pWith;
134554      if( pWith!=0 ){
134555        assert( pParse->pWith==pWith );
134556        pParse->pWith = pWith->pOuter;
134557      }
134558    }
134559  }
134560  #else
134561  #define selectPopWith 0
134562  #endif
134563  
134564  /*
134565  ** The SrcList_item structure passed as the second argument represents a
134566  ** sub-query in the FROM clause of a SELECT statement. This function
134567  ** allocates and populates the SrcList_item.pTab object. If successful,
134568  ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
134569  ** SQLITE_NOMEM.
134570  */
134571  SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
134572    Select *pSel = pFrom->pSelect;
134573    Table *pTab;
134574  
134575    assert( pSel );
134576    pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
134577    if( pTab==0 ) return SQLITE_NOMEM;
134578    pTab->nTabRef = 1;
134579    if( pFrom->zAlias ){
134580      pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
134581    }else{
134582      pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
134583    }
134584    while( pSel->pPrior ){ pSel = pSel->pPrior; }
134585    sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
134586    pTab->iPKey = -1;
134587    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
134588    pTab->tabFlags |= TF_Ephemeral;
134589  
134590    return SQLITE_OK;
134591  }
134592  
134593  /*
134594  ** This routine is a Walker callback for "expanding" a SELECT statement.
134595  ** "Expanding" means to do the following:
134596  **
134597  **    (1)  Make sure VDBE cursor numbers have been assigned to every
134598  **         element of the FROM clause.
134599  **
134600  **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
134601  **         defines FROM clause.  When views appear in the FROM clause,
134602  **         fill pTabList->a[].pSelect with a copy of the SELECT statement
134603  **         that implements the view.  A copy is made of the view's SELECT
134604  **         statement so that we can freely modify or delete that statement
134605  **         without worrying about messing up the persistent representation
134606  **         of the view.
134607  **
134608  **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
134609  **         on joins and the ON and USING clause of joins.
134610  **
134611  **    (4)  Scan the list of columns in the result set (pEList) looking
134612  **         for instances of the "*" operator or the TABLE.* operator.
134613  **         If found, expand each "*" to be every column in every table
134614  **         and TABLE.* to be every column in TABLE.
134615  **
134616  */
134617  static int selectExpander(Walker *pWalker, Select *p){
134618    Parse *pParse = pWalker->pParse;
134619    int i, j, k;
134620    SrcList *pTabList;
134621    ExprList *pEList;
134622    struct SrcList_item *pFrom;
134623    sqlite3 *db = pParse->db;
134624    Expr *pE, *pRight, *pExpr;
134625    u16 selFlags = p->selFlags;
134626    u32 elistFlags = 0;
134627  
134628    p->selFlags |= SF_Expanded;
134629    if( db->mallocFailed  ){
134630      return WRC_Abort;
134631    }
134632    assert( p->pSrc!=0 );
134633    if( (selFlags & SF_Expanded)!=0 ){
134634      return WRC_Prune;
134635    }
134636    pTabList = p->pSrc;
134637    pEList = p->pEList;
134638    sqlite3WithPush(pParse, p->pWith, 0);
134639  
134640    /* Make sure cursor numbers have been assigned to all entries in
134641    ** the FROM clause of the SELECT statement.
134642    */
134643    sqlite3SrcListAssignCursors(pParse, pTabList);
134644  
134645    /* Look up every table named in the FROM clause of the select.  If
134646    ** an entry of the FROM clause is a subquery instead of a table or view,
134647    ** then create a transient table structure to describe the subquery.
134648    */
134649    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
134650      Table *pTab;
134651      assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
134652      if( pFrom->fg.isRecursive ) continue;
134653      assert( pFrom->pTab==0 );
134654  #ifndef SQLITE_OMIT_CTE
134655      if( withExpand(pWalker, pFrom) ) return WRC_Abort;
134656      if( pFrom->pTab ) {} else
134657  #endif
134658      if( pFrom->zName==0 ){
134659  #ifndef SQLITE_OMIT_SUBQUERY
134660        Select *pSel = pFrom->pSelect;
134661        /* A sub-query in the FROM clause of a SELECT */
134662        assert( pSel!=0 );
134663        assert( pFrom->pTab==0 );
134664        if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
134665        if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
134666  #endif
134667      }else{
134668        /* An ordinary table or view name in the FROM clause */
134669        assert( pFrom->pTab==0 );
134670        pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
134671        if( pTab==0 ) return WRC_Abort;
134672        if( pTab->nTabRef>=0xffff ){
134673          sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
134674             pTab->zName);
134675          pFrom->pTab = 0;
134676          return WRC_Abort;
134677        }
134678        pTab->nTabRef++;
134679        if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
134680          return WRC_Abort;
134681        }
134682  #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
134683        if( IsVirtual(pTab) || pTab->pSelect ){
134684          i16 nCol;
134685          if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
134686          assert( pFrom->pSelect==0 );
134687          pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
134688          nCol = pTab->nCol;
134689          pTab->nCol = -1;
134690          sqlite3WalkSelect(pWalker, pFrom->pSelect);
134691          pTab->nCol = nCol;
134692        }
134693  #endif
134694      }
134695  
134696      /* Locate the index named by the INDEXED BY clause, if any. */
134697      if( sqlite3IndexedByLookup(pParse, pFrom) ){
134698        return WRC_Abort;
134699      }
134700    }
134701  
134702    /* Process NATURAL keywords, and ON and USING clauses of joins.
134703    */
134704    if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
134705      return WRC_Abort;
134706    }
134707  
134708    /* For every "*" that occurs in the column list, insert the names of
134709    ** all columns in all tables.  And for every TABLE.* insert the names
134710    ** of all columns in TABLE.  The parser inserted a special expression
134711    ** with the TK_ASTERISK operator for each "*" that it found in the column
134712    ** list.  The following code just has to locate the TK_ASTERISK
134713    ** expressions and expand each one to the list of all columns in
134714    ** all tables.
134715    **
134716    ** The first loop just checks to see if there are any "*" operators
134717    ** that need expanding.
134718    */
134719    for(k=0; k<pEList->nExpr; k++){
134720      pE = pEList->a[k].pExpr;
134721      if( pE->op==TK_ASTERISK ) break;
134722      assert( pE->op!=TK_DOT || pE->pRight!=0 );
134723      assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
134724      if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
134725      elistFlags |= pE->flags;
134726    }
134727    if( k<pEList->nExpr ){
134728      /*
134729      ** If we get here it means the result set contains one or more "*"
134730      ** operators that need to be expanded.  Loop through each expression
134731      ** in the result set and expand them one by one.
134732      */
134733      struct ExprList_item *a = pEList->a;
134734      ExprList *pNew = 0;
134735      int flags = pParse->db->flags;
134736      int longNames = (flags & SQLITE_FullColNames)!=0
134737                        && (flags & SQLITE_ShortColNames)==0;
134738  
134739      for(k=0; k<pEList->nExpr; k++){
134740        pE = a[k].pExpr;
134741        elistFlags |= pE->flags;
134742        pRight = pE->pRight;
134743        assert( pE->op!=TK_DOT || pRight!=0 );
134744        if( pE->op!=TK_ASTERISK
134745         && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
134746        ){
134747          /* This particular expression does not need to be expanded.
134748          */
134749          pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
134750          if( pNew ){
134751            pNew->a[pNew->nExpr-1].zName = a[k].zName;
134752            pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
134753            a[k].zName = 0;
134754            a[k].zSpan = 0;
134755          }
134756          a[k].pExpr = 0;
134757        }else{
134758          /* This expression is a "*" or a "TABLE.*" and needs to be
134759          ** expanded. */
134760          int tableSeen = 0;      /* Set to 1 when TABLE matches */
134761          char *zTName = 0;       /* text of name of TABLE */
134762          if( pE->op==TK_DOT ){
134763            assert( pE->pLeft!=0 );
134764            assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
134765            zTName = pE->pLeft->u.zToken;
134766          }
134767          for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
134768            Table *pTab = pFrom->pTab;
134769            Select *pSub = pFrom->pSelect;
134770            char *zTabName = pFrom->zAlias;
134771            const char *zSchemaName = 0;
134772            int iDb;
134773            if( zTabName==0 ){
134774              zTabName = pTab->zName;
134775            }
134776            if( db->mallocFailed ) break;
134777            if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
134778              pSub = 0;
134779              if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
134780                continue;
134781              }
134782              iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
134783              zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
134784            }
134785            for(j=0; j<pTab->nCol; j++){
134786              char *zName = pTab->aCol[j].zName;
134787              char *zColname;  /* The computed column name */
134788              char *zToFree;   /* Malloced string that needs to be freed */
134789              Token sColname;  /* Computed column name as a token */
134790  
134791              assert( zName );
134792              if( zTName && pSub
134793               && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
134794              ){
134795                continue;
134796              }
134797  
134798              /* If a column is marked as 'hidden', omit it from the expanded
134799              ** result-set list unless the SELECT has the SF_IncludeHidden
134800              ** bit set.
134801              */
134802              if( (p->selFlags & SF_IncludeHidden)==0
134803               && IsHiddenColumn(&pTab->aCol[j]) 
134804              ){
134805                continue;
134806              }
134807              tableSeen = 1;
134808  
134809              if( i>0 && zTName==0 ){
134810                if( (pFrom->fg.jointype & JT_NATURAL)!=0
134811                  && tableAndColumnIndex(pTabList, i, zName, 0, 0)
134812                ){
134813                  /* In a NATURAL join, omit the join columns from the 
134814                  ** table to the right of the join */
134815                  continue;
134816                }
134817                if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
134818                  /* In a join with a USING clause, omit columns in the
134819                  ** using clause from the table on the right. */
134820                  continue;
134821                }
134822              }
134823              pRight = sqlite3Expr(db, TK_ID, zName);
134824              zColname = zName;
134825              zToFree = 0;
134826              if( longNames || pTabList->nSrc>1 ){
134827                Expr *pLeft;
134828                pLeft = sqlite3Expr(db, TK_ID, zTabName);
134829                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
134830                if( zSchemaName ){
134831                  pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
134832                  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
134833                }
134834                if( longNames ){
134835                  zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
134836                  zToFree = zColname;
134837                }
134838              }else{
134839                pExpr = pRight;
134840              }
134841              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
134842              sqlite3TokenInit(&sColname, zColname);
134843              sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
134844              if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
134845                struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
134846                if( pSub ){
134847                  pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
134848                  testcase( pX->zSpan==0 );
134849                }else{
134850                  pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
134851                                             zSchemaName, zTabName, zColname);
134852                  testcase( pX->zSpan==0 );
134853                }
134854                pX->bSpanIsTab = 1;
134855              }
134856              sqlite3DbFree(db, zToFree);
134857            }
134858          }
134859          if( !tableSeen ){
134860            if( zTName ){
134861              sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
134862            }else{
134863              sqlite3ErrorMsg(pParse, "no tables specified");
134864            }
134865          }
134866        }
134867      }
134868      sqlite3ExprListDelete(db, pEList);
134869      p->pEList = pNew;
134870    }
134871    if( p->pEList ){
134872      if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
134873        sqlite3ErrorMsg(pParse, "too many columns in result set");
134874        return WRC_Abort;
134875      }
134876      if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
134877        p->selFlags |= SF_ComplexResult;
134878      }
134879    }
134880    return WRC_Continue;
134881  }
134882  
134883  /*
134884  ** No-op routine for the parse-tree walker.
134885  **
134886  ** When this routine is the Walker.xExprCallback then expression trees
134887  ** are walked without any actions being taken at each node.  Presumably,
134888  ** when this routine is used for Walker.xExprCallback then 
134889  ** Walker.xSelectCallback is set to do something useful for every 
134890  ** subquery in the parser tree.
134891  */
134892  SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
134893    UNUSED_PARAMETER2(NotUsed, NotUsed2);
134894    return WRC_Continue;
134895  }
134896  
134897  /*
134898  ** No-op routine for the parse-tree walker for SELECT statements.
134899  ** subquery in the parser tree.
134900  */
134901  SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
134902    UNUSED_PARAMETER2(NotUsed, NotUsed2);
134903    return WRC_Continue;
134904  }
134905  
134906  #if SQLITE_DEBUG
134907  /*
134908  ** Always assert.  This xSelectCallback2 implementation proves that the
134909  ** xSelectCallback2 is never invoked.
134910  */
134911  SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
134912    UNUSED_PARAMETER2(NotUsed, NotUsed2);
134913    assert( 0 );
134914  }
134915  #endif
134916  /*
134917  ** This routine "expands" a SELECT statement and all of its subqueries.
134918  ** For additional information on what it means to "expand" a SELECT
134919  ** statement, see the comment on the selectExpand worker callback above.
134920  **
134921  ** Expanding a SELECT statement is the first step in processing a
134922  ** SELECT statement.  The SELECT statement must be expanded before
134923  ** name resolution is performed.
134924  **
134925  ** If anything goes wrong, an error message is written into pParse.
134926  ** The calling function can detect the problem by looking at pParse->nErr
134927  ** and/or pParse->db->mallocFailed.
134928  */
134929  static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
134930    Walker w;
134931    w.xExprCallback = sqlite3ExprWalkNoop;
134932    w.pParse = pParse;
134933    if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
134934      w.xSelectCallback = convertCompoundSelectToSubquery;
134935      w.xSelectCallback2 = 0;
134936      sqlite3WalkSelect(&w, pSelect);
134937    }
134938    w.xSelectCallback = selectExpander;
134939    w.xSelectCallback2 = selectPopWith;
134940    sqlite3WalkSelect(&w, pSelect);
134941  }
134942  
134943  
134944  #ifndef SQLITE_OMIT_SUBQUERY
134945  /*
134946  ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
134947  ** interface.
134948  **
134949  ** For each FROM-clause subquery, add Column.zType and Column.zColl
134950  ** information to the Table structure that represents the result set
134951  ** of that subquery.
134952  **
134953  ** The Table structure that represents the result set was constructed
134954  ** by selectExpander() but the type and collation information was omitted
134955  ** at that point because identifiers had not yet been resolved.  This
134956  ** routine is called after identifier resolution.
134957  */
134958  static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
134959    Parse *pParse;
134960    int i;
134961    SrcList *pTabList;
134962    struct SrcList_item *pFrom;
134963  
134964    assert( p->selFlags & SF_Resolved );
134965    if( p->selFlags & SF_HasTypeInfo ) return;
134966    p->selFlags |= SF_HasTypeInfo;
134967    pParse = pWalker->pParse;
134968    pTabList = p->pSrc;
134969    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
134970      Table *pTab = pFrom->pTab;
134971      assert( pTab!=0 );
134972      if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
134973        /* A sub-query in the FROM clause of a SELECT */
134974        Select *pSel = pFrom->pSelect;
134975        if( pSel ){
134976          while( pSel->pPrior ) pSel = pSel->pPrior;
134977          sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
134978        }
134979      }
134980    }
134981  }
134982  #endif
134983  
134984  
134985  /*
134986  ** This routine adds datatype and collating sequence information to
134987  ** the Table structures of all FROM-clause subqueries in a
134988  ** SELECT statement.
134989  **
134990  ** Use this routine after name resolution.
134991  */
134992  static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
134993  #ifndef SQLITE_OMIT_SUBQUERY
134994    Walker w;
134995    w.xSelectCallback = sqlite3SelectWalkNoop;
134996    w.xSelectCallback2 = selectAddSubqueryTypeInfo;
134997    w.xExprCallback = sqlite3ExprWalkNoop;
134998    w.pParse = pParse;
134999    sqlite3WalkSelect(&w, pSelect);
135000  #endif
135001  }
135002  
135003  
135004  /*
135005  ** This routine sets up a SELECT statement for processing.  The
135006  ** following is accomplished:
135007  **
135008  **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
135009  **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
135010  **     *  ON and USING clauses are shifted into WHERE statements
135011  **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
135012  **     *  Identifiers in expression are matched to tables.
135013  **
135014  ** This routine acts recursively on all subqueries within the SELECT.
135015  */
135016  SQLITE_PRIVATE void sqlite3SelectPrep(
135017    Parse *pParse,         /* The parser context */
135018    Select *p,             /* The SELECT statement being coded. */
135019    NameContext *pOuterNC  /* Name context for container */
135020  ){
135021    assert( p!=0 || pParse->db->mallocFailed );
135022    if( pParse->db->mallocFailed ) return;
135023    if( p->selFlags & SF_HasTypeInfo ) return;
135024    sqlite3SelectExpand(pParse, p);
135025    if( pParse->nErr || pParse->db->mallocFailed ) return;
135026    sqlite3ResolveSelectNames(pParse, p, pOuterNC);
135027    if( pParse->nErr || pParse->db->mallocFailed ) return;
135028    sqlite3SelectAddTypeInfo(pParse, p);
135029  }
135030  
135031  /*
135032  ** Reset the aggregate accumulator.
135033  **
135034  ** The aggregate accumulator is a set of memory cells that hold
135035  ** intermediate results while calculating an aggregate.  This
135036  ** routine generates code that stores NULLs in all of those memory
135037  ** cells.
135038  */
135039  static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
135040    Vdbe *v = pParse->pVdbe;
135041    int i;
135042    struct AggInfo_func *pFunc;
135043    int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
135044    if( nReg==0 ) return;
135045  #ifdef SQLITE_DEBUG
135046    /* Verify that all AggInfo registers are within the range specified by
135047    ** AggInfo.mnReg..AggInfo.mxReg */
135048    assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
135049    for(i=0; i<pAggInfo->nColumn; i++){
135050      assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
135051           && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
135052    }
135053    for(i=0; i<pAggInfo->nFunc; i++){
135054      assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
135055           && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
135056    }
135057  #endif
135058    sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
135059    for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
135060      if( pFunc->iDistinct>=0 ){
135061        Expr *pE = pFunc->pExpr;
135062        assert( !ExprHasProperty(pE, EP_xIsSelect) );
135063        if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
135064          sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
135065             "argument");
135066          pFunc->iDistinct = -1;
135067        }else{
135068          KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
135069          sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
135070                            (char*)pKeyInfo, P4_KEYINFO);
135071        }
135072      }
135073    }
135074  }
135075  
135076  /*
135077  ** Invoke the OP_AggFinalize opcode for every aggregate function
135078  ** in the AggInfo structure.
135079  */
135080  static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
135081    Vdbe *v = pParse->pVdbe;
135082    int i;
135083    struct AggInfo_func *pF;
135084    for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
135085      ExprList *pList = pF->pExpr->x.pList;
135086      assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
135087      sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
135088      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
135089    }
135090  }
135091  
135092  
135093  /*
135094  ** Update the accumulator memory cells for an aggregate based on
135095  ** the current cursor position.
135096  **
135097  ** If regAcc is non-zero and there are no min() or max() aggregates
135098  ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
135099  ** registers i register regAcc contains 0. The caller will take care
135100  ** of setting and clearing regAcc.
135101  */
135102  static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
135103    Vdbe *v = pParse->pVdbe;
135104    int i;
135105    int regHit = 0;
135106    int addrHitTest = 0;
135107    struct AggInfo_func *pF;
135108    struct AggInfo_col *pC;
135109  
135110    pAggInfo->directMode = 1;
135111    for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
135112      int nArg;
135113      int addrNext = 0;
135114      int regAgg;
135115      ExprList *pList = pF->pExpr->x.pList;
135116      assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
135117      if( pList ){
135118        nArg = pList->nExpr;
135119        regAgg = sqlite3GetTempRange(pParse, nArg);
135120        sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
135121      }else{
135122        nArg = 0;
135123        regAgg = 0;
135124      }
135125      if( pF->iDistinct>=0 ){
135126        addrNext = sqlite3VdbeMakeLabel(pParse);
135127        testcase( nArg==0 );  /* Error condition */
135128        testcase( nArg>1 );   /* Also an error */
135129        codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
135130      }
135131      if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
135132        CollSeq *pColl = 0;
135133        struct ExprList_item *pItem;
135134        int j;
135135        assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
135136        for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
135137          pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
135138        }
135139        if( !pColl ){
135140          pColl = pParse->db->pDfltColl;
135141        }
135142        if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
135143        sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
135144      }
135145      sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
135146      sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
135147      sqlite3VdbeChangeP5(v, (u8)nArg);
135148      sqlite3ReleaseTempRange(pParse, regAgg, nArg);
135149      if( addrNext ){
135150        sqlite3VdbeResolveLabel(v, addrNext);
135151      }
135152    }
135153    if( regHit==0 && pAggInfo->nAccumulator ){
135154      regHit = regAcc;
135155    }
135156    if( regHit ){
135157      addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
135158    }
135159    for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
135160      sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
135161    }
135162    pAggInfo->directMode = 0;
135163    if( addrHitTest ){
135164      sqlite3VdbeJumpHere(v, addrHitTest);
135165    }
135166  }
135167  
135168  /*
135169  ** Add a single OP_Explain instruction to the VDBE to explain a simple
135170  ** count(*) query ("SELECT count(*) FROM pTab").
135171  */
135172  #ifndef SQLITE_OMIT_EXPLAIN
135173  static void explainSimpleCount(
135174    Parse *pParse,                  /* Parse context */
135175    Table *pTab,                    /* Table being queried */
135176    Index *pIdx                     /* Index used to optimize scan, or NULL */
135177  ){
135178    if( pParse->explain==2 ){
135179      int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
135180      sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
135181          pTab->zName,
135182          bCover ? " USING COVERING INDEX " : "",
135183          bCover ? pIdx->zName : ""
135184      );
135185    }
135186  }
135187  #else
135188  # define explainSimpleCount(a,b,c)
135189  #endif
135190  
135191  /*
135192  ** sqlite3WalkExpr() callback used by havingToWhere().
135193  **
135194  ** If the node passed to the callback is a TK_AND node, return 
135195  ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
135196  **
135197  ** Otherwise, return WRC_Prune. In this case, also check if the 
135198  ** sub-expression matches the criteria for being moved to the WHERE
135199  ** clause. If so, add it to the WHERE clause and replace the sub-expression
135200  ** within the HAVING expression with a constant "1".
135201  */
135202  static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
135203    if( pExpr->op!=TK_AND ){
135204      Select *pS = pWalker->u.pSelect;
135205      if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
135206        sqlite3 *db = pWalker->pParse->db;
135207        Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
135208        if( pNew ){
135209          Expr *pWhere = pS->pWhere;
135210          SWAP(Expr, *pNew, *pExpr);
135211          pNew = sqlite3ExprAnd(db, pWhere, pNew);
135212          pS->pWhere = pNew;
135213          pWalker->eCode = 1;
135214        }
135215      }
135216      return WRC_Prune;
135217    }
135218    return WRC_Continue;
135219  }
135220  
135221  /*
135222  ** Transfer eligible terms from the HAVING clause of a query, which is
135223  ** processed after grouping, to the WHERE clause, which is processed before
135224  ** grouping. For example, the query:
135225  **
135226  **   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
135227  **
135228  ** can be rewritten as:
135229  **
135230  **   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
135231  **
135232  ** A term of the HAVING expression is eligible for transfer if it consists
135233  ** entirely of constants and expressions that are also GROUP BY terms that
135234  ** use the "BINARY" collation sequence.
135235  */
135236  static void havingToWhere(Parse *pParse, Select *p){
135237    Walker sWalker;
135238    memset(&sWalker, 0, sizeof(sWalker));
135239    sWalker.pParse = pParse;
135240    sWalker.xExprCallback = havingToWhereExprCb;
135241    sWalker.u.pSelect = p;
135242    sqlite3WalkExpr(&sWalker, p->pHaving);
135243  #if SELECTTRACE_ENABLED
135244    if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
135245      SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
135246      sqlite3TreeViewSelect(0, p, 0);
135247    }
135248  #endif
135249  }
135250  
135251  /*
135252  ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
135253  ** If it is, then return the SrcList_item for the prior view.  If it is not,
135254  ** then return 0.
135255  */
135256  static struct SrcList_item *isSelfJoinView(
135257    SrcList *pTabList,           /* Search for self-joins in this FROM clause */
135258    struct SrcList_item *pThis   /* Search for prior reference to this subquery */
135259  ){
135260    struct SrcList_item *pItem;
135261    for(pItem = pTabList->a; pItem<pThis; pItem++){
135262      Select *pS1;
135263      if( pItem->pSelect==0 ) continue;
135264      if( pItem->fg.viaCoroutine ) continue;
135265      if( pItem->zName==0 ) continue;
135266      if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
135267      if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
135268      pS1 = pItem->pSelect;
135269      if( pThis->pSelect->selId!=pS1->selId ){
135270        /* The query flattener left two different CTE tables with identical
135271        ** names in the same FROM clause. */
135272        continue;
135273      }
135274      if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) ){
135275        /* The view was modified by some other optimization such as
135276        ** pushDownWhereTerms() */
135277        continue;
135278      }
135279      return pItem;
135280    }
135281    return 0;
135282  }
135283  
135284  #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
135285  /*
135286  ** Attempt to transform a query of the form
135287  **
135288  **    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
135289  **
135290  ** Into this:
135291  **
135292  **    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
135293  **
135294  ** The transformation only works if all of the following are true:
135295  **
135296  **   *  The subquery is a UNION ALL of two or more terms
135297  **   *  The subquery does not have a LIMIT clause
135298  **   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
135299  **   *  The outer query is a simple count(*)
135300  **
135301  ** Return TRUE if the optimization is undertaken.
135302  */
135303  static int countOfViewOptimization(Parse *pParse, Select *p){
135304    Select *pSub, *pPrior;
135305    Expr *pExpr;
135306    Expr *pCount;
135307    sqlite3 *db;
135308    if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate */
135309    if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
135310    pExpr = p->pEList->a[0].pExpr;
135311    if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
135312    if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Is count() */
135313    if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
135314    if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in FROM  */
135315    pSub = p->pSrc->a[0].pSelect;
135316    if( pSub==0 ) return 0;                           /* The FROM is a subquery */
135317    if( pSub->pPrior==0 ) return 0;                   /* Must be a compound ry */
135318    do{
135319      if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
135320      if( pSub->pWhere ) return 0;                      /* No WHERE clause */
135321      if( pSub->pLimit ) return 0;                      /* No LIMIT clause */
135322      if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
135323      pSub = pSub->pPrior;                              /* Repeat over compound */
135324    }while( pSub );
135325  
135326    /* If we reach this point then it is OK to perform the transformation */
135327  
135328    db = pParse->db;
135329    pCount = pExpr;
135330    pExpr = 0;
135331    pSub = p->pSrc->a[0].pSelect;
135332    p->pSrc->a[0].pSelect = 0;
135333    sqlite3SrcListDelete(db, p->pSrc);
135334    p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
135335    while( pSub ){
135336      Expr *pTerm;
135337      pPrior = pSub->pPrior;
135338      pSub->pPrior = 0;
135339      pSub->pNext = 0;
135340      pSub->selFlags |= SF_Aggregate;
135341      pSub->selFlags &= ~SF_Compound;
135342      pSub->nSelectRow = 0;
135343      sqlite3ExprListDelete(db, pSub->pEList);
135344      pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
135345      pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
135346      pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
135347      sqlite3PExprAddSelect(pParse, pTerm, pSub);
135348      if( pExpr==0 ){
135349        pExpr = pTerm;
135350      }else{
135351        pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
135352      }
135353      pSub = pPrior;
135354    }
135355    p->pEList->a[0].pExpr = pExpr;
135356    p->selFlags &= ~SF_Aggregate;
135357  
135358  #if SELECTTRACE_ENABLED
135359    if( sqlite3SelectTrace & 0x400 ){
135360      SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
135361      sqlite3TreeViewSelect(0, p, 0);
135362    }
135363  #endif
135364    return 1;
135365  }
135366  #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
135367  
135368  /*
135369  ** Generate code for the SELECT statement given in the p argument.  
135370  **
135371  ** The results are returned according to the SelectDest structure.
135372  ** See comments in sqliteInt.h for further information.
135373  **
135374  ** This routine returns the number of errors.  If any errors are
135375  ** encountered, then an appropriate error message is left in
135376  ** pParse->zErrMsg.
135377  **
135378  ** This routine does NOT free the Select structure passed in.  The
135379  ** calling function needs to do that.
135380  */
135381  SQLITE_PRIVATE int sqlite3Select(
135382    Parse *pParse,         /* The parser context */
135383    Select *p,             /* The SELECT statement being coded. */
135384    SelectDest *pDest      /* What to do with the query results */
135385  ){
135386    int i, j;              /* Loop counters */
135387    WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
135388    Vdbe *v;               /* The virtual machine under construction */
135389    int isAgg;             /* True for select lists like "count(*)" */
135390    ExprList *pEList = 0;  /* List of columns to extract. */
135391    SrcList *pTabList;     /* List of tables to select from */
135392    Expr *pWhere;          /* The WHERE clause.  May be NULL */
135393    ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
135394    Expr *pHaving;         /* The HAVING clause.  May be NULL */
135395    int rc = 1;            /* Value to return from this function */
135396    DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
135397    SortCtx sSort;         /* Info on how to code the ORDER BY clause */
135398    AggInfo sAggInfo;      /* Information used by aggregate queries */
135399    int iEnd;              /* Address of the end of the query */
135400    sqlite3 *db;           /* The database connection */
135401    ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
135402    u8 minMaxFlag;                 /* Flag for min/max queries */
135403  
135404    db = pParse->db;
135405    v = sqlite3GetVdbe(pParse);
135406    if( p==0 || db->mallocFailed || pParse->nErr ){
135407      return 1;
135408    }
135409    if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
135410    memset(&sAggInfo, 0, sizeof(sAggInfo));
135411  #if SELECTTRACE_ENABLED
135412    SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
135413    if( sqlite3SelectTrace & 0x100 ){
135414      sqlite3TreeViewSelect(0, p, 0);
135415    }
135416  #endif
135417  
135418    assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
135419    assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
135420    assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
135421    assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
135422    if( IgnorableOrderby(pDest) ){
135423      assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
135424             pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
135425             pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
135426             pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
135427      /* If ORDER BY makes no difference in the output then neither does
135428      ** DISTINCT so it can be removed too. */
135429      sqlite3ExprListDelete(db, p->pOrderBy);
135430      p->pOrderBy = 0;
135431      p->selFlags &= ~SF_Distinct;
135432    }
135433    sqlite3SelectPrep(pParse, p, 0);
135434    if( pParse->nErr || db->mallocFailed ){
135435      goto select_end;
135436    }
135437    assert( p->pEList!=0 );
135438  #if SELECTTRACE_ENABLED
135439    if( sqlite3SelectTrace & 0x104 ){
135440      SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
135441      sqlite3TreeViewSelect(0, p, 0);
135442    }
135443  #endif
135444  
135445    if( pDest->eDest==SRT_Output ){
135446      generateColumnNames(pParse, p);
135447    }
135448  
135449  #ifndef SQLITE_OMIT_WINDOWFUNC
135450    if( sqlite3WindowRewrite(pParse, p) ){
135451      goto select_end;
135452    }
135453  #if SELECTTRACE_ENABLED
135454    if( sqlite3SelectTrace & 0x108 ){
135455      SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
135456      sqlite3TreeViewSelect(0, p, 0);
135457    }
135458  #endif
135459  #endif /* SQLITE_OMIT_WINDOWFUNC */
135460    pTabList = p->pSrc;
135461    isAgg = (p->selFlags & SF_Aggregate)!=0;
135462    memset(&sSort, 0, sizeof(sSort));
135463    sSort.pOrderBy = p->pOrderBy;
135464  
135465    /* Try to various optimizations (flattening subqueries, and strength
135466    ** reduction of join operators) in the FROM clause up into the main query
135467    */
135468  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
135469    for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
135470      struct SrcList_item *pItem = &pTabList->a[i];
135471      Select *pSub = pItem->pSelect;
135472      Table *pTab = pItem->pTab;
135473  
135474      /* Convert LEFT JOIN into JOIN if there are terms of the right table
135475      ** of the LEFT JOIN used in the WHERE clause.
135476      */
135477      if( (pItem->fg.jointype & JT_LEFT)!=0
135478       && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
135479       && OptimizationEnabled(db, SQLITE_SimplifyJoin)
135480      ){
135481        SELECTTRACE(0x100,pParse,p,
135482                  ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
135483        pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
135484        unsetJoinExpr(p->pWhere, pItem->iCursor);
135485      }
135486  
135487      /* No futher action if this term of the FROM clause is no a subquery */
135488      if( pSub==0 ) continue;
135489  
135490      /* Catch mismatch in the declared columns of a view and the number of
135491      ** columns in the SELECT on the RHS */
135492      if( pTab->nCol!=pSub->pEList->nExpr ){
135493        sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
135494                        pTab->nCol, pTab->zName, pSub->pEList->nExpr);
135495        goto select_end;
135496      }
135497  
135498      /* Do not try to flatten an aggregate subquery.
135499      **
135500      ** Flattening an aggregate subquery is only possible if the outer query
135501      ** is not a join.  But if the outer query is not a join, then the subquery
135502      ** will be implemented as a co-routine and there is no advantage to
135503      ** flattening in that case.
135504      */
135505      if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
135506      assert( pSub->pGroupBy==0 );
135507  
135508      /* If the outer query contains a "complex" result set (that is,
135509      ** if the result set of the outer query uses functions or subqueries)
135510      ** and if the subquery contains an ORDER BY clause and if
135511      ** it will be implemented as a co-routine, then do not flatten.  This
135512      ** restriction allows SQL constructs like this:
135513      **
135514      **  SELECT expensive_function(x)
135515      **    FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
135516      **
135517      ** The expensive_function() is only computed on the 10 rows that
135518      ** are output, rather than every row of the table.
135519      **
135520      ** The requirement that the outer query have a complex result set
135521      ** means that flattening does occur on simpler SQL constraints without
135522      ** the expensive_function() like:
135523      **
135524      **  SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
135525      */
135526      if( pSub->pOrderBy!=0
135527       && i==0
135528       && (p->selFlags & SF_ComplexResult)!=0
135529       && (pTabList->nSrc==1
135530           || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
135531      ){
135532        continue;
135533      }
135534  
135535      if( flattenSubquery(pParse, p, i, isAgg) ){
135536        if( pParse->nErr ) goto select_end;
135537        /* This subquery can be absorbed into its parent. */
135538        i = -1;
135539      }
135540      pTabList = p->pSrc;
135541      if( db->mallocFailed ) goto select_end;
135542      if( !IgnorableOrderby(pDest) ){
135543        sSort.pOrderBy = p->pOrderBy;
135544      }
135545    }
135546  #endif
135547  
135548  #ifndef SQLITE_OMIT_COMPOUND_SELECT
135549    /* Handle compound SELECT statements using the separate multiSelect()
135550    ** procedure.
135551    */
135552    if( p->pPrior ){
135553      rc = multiSelect(pParse, p, pDest);
135554  #if SELECTTRACE_ENABLED
135555      SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
135556      if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
135557        sqlite3TreeViewSelect(0, p, 0);
135558      }
135559  #endif
135560      if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
135561      return rc;
135562    }
135563  #endif
135564  
135565    /* Do the WHERE-clause constant propagation optimization if this is
135566    ** a join.  No need to speed time on this operation for non-join queries
135567    ** as the equivalent optimization will be handled by query planner in
135568    ** sqlite3WhereBegin().
135569    */
135570    if( pTabList->nSrc>1
135571     && OptimizationEnabled(db, SQLITE_PropagateConst)
135572     && propagateConstants(pParse, p)
135573    ){
135574  #if SELECTTRACE_ENABLED
135575      if( sqlite3SelectTrace & 0x100 ){
135576        SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
135577        sqlite3TreeViewSelect(0, p, 0);
135578      }
135579  #endif
135580    }else{
135581      SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
135582    }
135583  
135584  #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
135585    if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
135586     && countOfViewOptimization(pParse, p)
135587    ){
135588      if( db->mallocFailed ) goto select_end;
135589      pEList = p->pEList;
135590      pTabList = p->pSrc;
135591    }
135592  #endif
135593  
135594    /* For each term in the FROM clause, do two things:
135595    ** (1) Authorized unreferenced tables
135596    ** (2) Generate code for all sub-queries
135597    */
135598    for(i=0; i<pTabList->nSrc; i++){
135599      struct SrcList_item *pItem = &pTabList->a[i];
135600      SelectDest dest;
135601      Select *pSub;
135602  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
135603      const char *zSavedAuthContext;
135604  #endif
135605  
135606      /* Issue SQLITE_READ authorizations with a fake column name for any
135607      ** tables that are referenced but from which no values are extracted.
135608      ** Examples of where these kinds of null SQLITE_READ authorizations
135609      ** would occur:
135610      **
135611      **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
135612      **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
135613      **
135614      ** The fake column name is an empty string.  It is possible for a table to
135615      ** have a column named by the empty string, in which case there is no way to
135616      ** distinguish between an unreferenced table and an actual reference to the
135617      ** "" column. The original design was for the fake column name to be a NULL,
135618      ** which would be unambiguous.  But legacy authorization callbacks might
135619      ** assume the column name is non-NULL and segfault.  The use of an empty
135620      ** string for the fake column name seems safer.
135621      */
135622      if( pItem->colUsed==0 ){
135623        sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
135624      }
135625  
135626  #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
135627      /* Generate code for all sub-queries in the FROM clause
135628      */
135629      pSub = pItem->pSelect;
135630      if( pSub==0 ) continue;
135631  
135632      /* The code for a subquery should only be generated once, though it is
135633      ** technically harmless for it to be generated multiple times. The
135634      ** following assert() will detect if something changes to cause
135635      ** the same subquery to be coded multiple times, as a signal to the
135636      ** developers to try to optimize the situation. */
135637      assert( pItem->addrFillSub==0 );
135638  
135639      /* Increment Parse.nHeight by the height of the largest expression
135640      ** tree referred to by this, the parent select. The child select
135641      ** may contain expression trees of at most
135642      ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
135643      ** more conservative than necessary, but much easier than enforcing
135644      ** an exact limit.
135645      */
135646      pParse->nHeight += sqlite3SelectExprHeight(p);
135647  
135648      /* Make copies of constant WHERE-clause terms in the outer query down
135649      ** inside the subquery.  This can help the subquery to run more efficiently.
135650      */
135651      if( OptimizationEnabled(db, SQLITE_PushDown)
135652       && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
135653                             (pItem->fg.jointype & JT_OUTER)!=0)
135654      ){
135655  #if SELECTTRACE_ENABLED
135656        if( sqlite3SelectTrace & 0x100 ){
135657          SELECTTRACE(0x100,pParse,p,
135658              ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
135659          sqlite3TreeViewSelect(0, p, 0);
135660        }
135661  #endif
135662      }else{
135663        SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
135664      }
135665  
135666      zSavedAuthContext = pParse->zAuthContext;
135667      pParse->zAuthContext = pItem->zName;
135668  
135669      /* Generate code to implement the subquery
135670      **
135671      ** The subquery is implemented as a co-routine if the subquery is
135672      ** guaranteed to be the outer loop (so that it does not need to be
135673      ** computed more than once)
135674      **
135675      ** TODO: Are there other reasons beside (1) to use a co-routine
135676      ** implementation?
135677      */
135678      if( i==0
135679       && (pTabList->nSrc==1
135680              || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
135681      ){
135682        /* Implement a co-routine that will return a single row of the result
135683        ** set on each invocation.
135684        */
135685        int addrTop = sqlite3VdbeCurrentAddr(v)+1;
135686       
135687        pItem->regReturn = ++pParse->nMem;
135688        sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
135689        VdbeComment((v, "%s", pItem->pTab->zName));
135690        pItem->addrFillSub = addrTop;
135691        sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
135692        ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
135693        sqlite3Select(pParse, pSub, &dest);
135694        pItem->pTab->nRowLogEst = pSub->nSelectRow;
135695        pItem->fg.viaCoroutine = 1;
135696        pItem->regResult = dest.iSdst;
135697        sqlite3VdbeEndCoroutine(v, pItem->regReturn);
135698        sqlite3VdbeJumpHere(v, addrTop-1);
135699        sqlite3ClearTempRegCache(pParse);
135700      }else{
135701        /* Generate a subroutine that will fill an ephemeral table with
135702        ** the content of this subquery.  pItem->addrFillSub will point
135703        ** to the address of the generated subroutine.  pItem->regReturn
135704        ** is a register allocated to hold the subroutine return address
135705        */
135706        int topAddr;
135707        int onceAddr = 0;
135708        int retAddr;
135709        struct SrcList_item *pPrior;
135710  
135711        assert( pItem->addrFillSub==0 );
135712        pItem->regReturn = ++pParse->nMem;
135713        topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
135714        pItem->addrFillSub = topAddr+1;
135715        if( pItem->fg.isCorrelated==0 ){
135716          /* If the subquery is not correlated and if we are not inside of
135717          ** a trigger, then we only need to compute the value of the subquery
135718          ** once. */
135719          onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
135720          VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
135721        }else{
135722          VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
135723        }
135724        pPrior = isSelfJoinView(pTabList, pItem);
135725        if( pPrior ){
135726          sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
135727          assert( pPrior->pSelect!=0 );
135728          pSub->nSelectRow = pPrior->pSelect->nSelectRow;
135729        }else{
135730          sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
135731          ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
135732          sqlite3Select(pParse, pSub, &dest);
135733        }
135734        pItem->pTab->nRowLogEst = pSub->nSelectRow;
135735        if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
135736        retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
135737        VdbeComment((v, "end %s", pItem->pTab->zName));
135738        sqlite3VdbeChangeP1(v, topAddr, retAddr);
135739        sqlite3ClearTempRegCache(pParse);
135740      }
135741      if( db->mallocFailed ) goto select_end;
135742      pParse->nHeight -= sqlite3SelectExprHeight(p);
135743      pParse->zAuthContext = zSavedAuthContext;
135744  #endif
135745    }
135746  
135747    /* Various elements of the SELECT copied into local variables for
135748    ** convenience */
135749    pEList = p->pEList;
135750    pWhere = p->pWhere;
135751    pGroupBy = p->pGroupBy;
135752    pHaving = p->pHaving;
135753    sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
135754  
135755  #if SELECTTRACE_ENABLED
135756    if( sqlite3SelectTrace & 0x400 ){
135757      SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
135758      sqlite3TreeViewSelect(0, p, 0);
135759    }
135760  #endif
135761  
135762    /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
135763    ** if the select-list is the same as the ORDER BY list, then this query
135764    ** can be rewritten as a GROUP BY. In other words, this:
135765    **
135766    **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
135767    **
135768    ** is transformed to:
135769    **
135770    **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
135771    **
135772    ** The second form is preferred as a single index (or temp-table) may be 
135773    ** used for both the ORDER BY and DISTINCT processing. As originally 
135774    ** written the query must use a temp-table for at least one of the ORDER 
135775    ** BY and DISTINCT, and an index or separate temp-table for the other.
135776    */
135777    if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
135778     && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
135779    ){
135780      p->selFlags &= ~SF_Distinct;
135781      pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
135782      /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
135783      ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
135784      ** original setting of the SF_Distinct flag, not the current setting */
135785      assert( sDistinct.isTnct );
135786  
135787  #if SELECTTRACE_ENABLED
135788      if( sqlite3SelectTrace & 0x400 ){
135789        SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
135790        sqlite3TreeViewSelect(0, p, 0);
135791      }
135792  #endif
135793    }
135794  
135795    /* If there is an ORDER BY clause, then create an ephemeral index to
135796    ** do the sorting.  But this sorting ephemeral index might end up
135797    ** being unused if the data can be extracted in pre-sorted order.
135798    ** If that is the case, then the OP_OpenEphemeral instruction will be
135799    ** changed to an OP_Noop once we figure out that the sorting index is
135800    ** not needed.  The sSort.addrSortIndex variable is used to facilitate
135801    ** that change.
135802    */
135803    if( sSort.pOrderBy ){
135804      KeyInfo *pKeyInfo;
135805      pKeyInfo = sqlite3KeyInfoFromExprList(
135806          pParse, sSort.pOrderBy, 0, pEList->nExpr);
135807      sSort.iECursor = pParse->nTab++;
135808      sSort.addrSortIndex =
135809        sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
135810            sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
135811            (char*)pKeyInfo, P4_KEYINFO
135812        );
135813    }else{
135814      sSort.addrSortIndex = -1;
135815    }
135816  
135817    /* If the output is destined for a temporary table, open that table.
135818    */
135819    if( pDest->eDest==SRT_EphemTab ){
135820      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
135821    }
135822  
135823    /* Set the limiter.
135824    */
135825    iEnd = sqlite3VdbeMakeLabel(pParse);
135826    if( (p->selFlags & SF_FixedLimit)==0 ){
135827      p->nSelectRow = 320;  /* 4 billion rows */
135828    }
135829    computeLimitRegisters(pParse, p, iEnd);
135830    if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
135831      sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
135832      sSort.sortFlags |= SORTFLAG_UseSorter;
135833    }
135834  
135835    /* Open an ephemeral index to use for the distinct set.
135836    */
135837    if( p->selFlags & SF_Distinct ){
135838      sDistinct.tabTnct = pParse->nTab++;
135839      sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
135840                         sDistinct.tabTnct, 0, 0,
135841                         (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
135842                         P4_KEYINFO);
135843      sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
135844      sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
135845    }else{
135846      sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
135847    }
135848  
135849    if( !isAgg && pGroupBy==0 ){
135850      /* No aggregate functions and no GROUP BY clause */
135851      u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
135852                     | (p->selFlags & SF_FixedLimit);
135853  #ifndef SQLITE_OMIT_WINDOWFUNC
135854      Window *pWin = p->pWin;      /* Master window object (or NULL) */
135855      if( pWin ){
135856        sqlite3WindowCodeInit(pParse, pWin);
135857      }
135858  #endif
135859      assert( WHERE_USE_LIMIT==SF_FixedLimit );
135860  
135861  
135862      /* Begin the database scan. */
135863      SELECTTRACE(1,pParse,p,("WhereBegin\n"));
135864      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
135865                                 p->pEList, wctrlFlags, p->nSelectRow);
135866      if( pWInfo==0 ) goto select_end;
135867      if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
135868        p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
135869      }
135870      if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
135871        sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
135872      }
135873      if( sSort.pOrderBy ){
135874        sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
135875        sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
135876        if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
135877          sSort.pOrderBy = 0;
135878        }
135879      }
135880  
135881      /* If sorting index that was created by a prior OP_OpenEphemeral 
135882      ** instruction ended up not being needed, then change the OP_OpenEphemeral
135883      ** into an OP_Noop.
135884      */
135885      if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
135886        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
135887      }
135888  
135889      assert( p->pEList==pEList );
135890  #ifndef SQLITE_OMIT_WINDOWFUNC
135891      if( pWin ){
135892        int addrGosub = sqlite3VdbeMakeLabel(pParse);
135893        int iCont = sqlite3VdbeMakeLabel(pParse);
135894        int iBreak = sqlite3VdbeMakeLabel(pParse);
135895        int regGosub = ++pParse->nMem;
135896  
135897        sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
135898  
135899        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
135900        sqlite3VdbeResolveLabel(v, addrGosub);
135901        VdbeNoopComment((v, "inner-loop subroutine"));
135902        sSort.labelOBLopt = 0;
135903        selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
135904        sqlite3VdbeResolveLabel(v, iCont);
135905        sqlite3VdbeAddOp1(v, OP_Return, regGosub);
135906        VdbeComment((v, "end inner-loop subroutine"));
135907        sqlite3VdbeResolveLabel(v, iBreak);
135908      }else
135909  #endif /* SQLITE_OMIT_WINDOWFUNC */
135910      {
135911        /* Use the standard inner loop. */
135912        selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
135913            sqlite3WhereContinueLabel(pWInfo),
135914            sqlite3WhereBreakLabel(pWInfo));
135915  
135916        /* End the database scan loop.
135917        */
135918        sqlite3WhereEnd(pWInfo);
135919      }
135920    }else{
135921      /* This case when there exist aggregate functions or a GROUP BY clause
135922      ** or both */
135923      NameContext sNC;    /* Name context for processing aggregate information */
135924      int iAMem;          /* First Mem address for storing current GROUP BY */
135925      int iBMem;          /* First Mem address for previous GROUP BY */
135926      int iUseFlag;       /* Mem address holding flag indicating that at least
135927                          ** one row of the input to the aggregator has been
135928                          ** processed */
135929      int iAbortFlag;     /* Mem address which causes query abort if positive */
135930      int groupBySort;    /* Rows come from source in GROUP BY order */
135931      int addrEnd;        /* End of processing for this SELECT */
135932      int sortPTab = 0;   /* Pseudotable used to decode sorting results */
135933      int sortOut = 0;    /* Output register from the sorter */
135934      int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
135935  
135936      /* Remove any and all aliases between the result set and the
135937      ** GROUP BY clause.
135938      */
135939      if( pGroupBy ){
135940        int k;                        /* Loop counter */
135941        struct ExprList_item *pItem;  /* For looping over expression in a list */
135942  
135943        for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
135944          pItem->u.x.iAlias = 0;
135945        }
135946        for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
135947          pItem->u.x.iAlias = 0;
135948        }
135949        assert( 66==sqlite3LogEst(100) );
135950        if( p->nSelectRow>66 ) p->nSelectRow = 66;
135951      }else{
135952        assert( 0==sqlite3LogEst(1) );
135953        p->nSelectRow = 0;
135954      }
135955  
135956      /* If there is both a GROUP BY and an ORDER BY clause and they are
135957      ** identical, then it may be possible to disable the ORDER BY clause 
135958      ** on the grounds that the GROUP BY will cause elements to come out 
135959      ** in the correct order. It also may not - the GROUP BY might use a
135960      ** database index that causes rows to be grouped together as required
135961      ** but not actually sorted. Either way, record the fact that the
135962      ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
135963      ** variable.  */
135964      if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
135965        orderByGrp = 1;
135966      }
135967   
135968      /* Create a label to jump to when we want to abort the query */
135969      addrEnd = sqlite3VdbeMakeLabel(pParse);
135970  
135971      /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
135972      ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
135973      ** SELECT statement.
135974      */
135975      memset(&sNC, 0, sizeof(sNC));
135976      sNC.pParse = pParse;
135977      sNC.pSrcList = pTabList;
135978      sNC.uNC.pAggInfo = &sAggInfo;
135979      VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
135980      sAggInfo.mnReg = pParse->nMem+1;
135981      sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
135982      sAggInfo.pGroupBy = pGroupBy;
135983      sqlite3ExprAnalyzeAggList(&sNC, pEList);
135984      sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
135985      if( pHaving ){
135986        if( pGroupBy ){
135987          assert( pWhere==p->pWhere );
135988          assert( pHaving==p->pHaving );
135989          assert( pGroupBy==p->pGroupBy );
135990          havingToWhere(pParse, p);
135991          pWhere = p->pWhere;
135992        }
135993        sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
135994      }
135995      sAggInfo.nAccumulator = sAggInfo.nColumn;
135996      if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
135997        minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
135998      }else{
135999        minMaxFlag = WHERE_ORDERBY_NORMAL;
136000      }
136001      for(i=0; i<sAggInfo.nFunc; i++){
136002        assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
136003        sNC.ncFlags |= NC_InAggFunc;
136004        sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
136005        sNC.ncFlags &= ~NC_InAggFunc;
136006      }
136007      sAggInfo.mxReg = pParse->nMem;
136008      if( db->mallocFailed ) goto select_end;
136009  #if SELECTTRACE_ENABLED
136010      if( sqlite3SelectTrace & 0x400 ){
136011        int ii;
136012        SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
136013        sqlite3TreeViewSelect(0, p, 0);
136014        for(ii=0; ii<sAggInfo.nColumn; ii++){
136015          sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
136016              ii, sAggInfo.aCol[ii].iMem);
136017          sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
136018        }
136019        for(ii=0; ii<sAggInfo.nFunc; ii++){
136020          sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
136021              ii, sAggInfo.aFunc[ii].iMem);
136022          sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
136023        }
136024      }
136025  #endif
136026  
136027  
136028      /* Processing for aggregates with GROUP BY is very different and
136029      ** much more complex than aggregates without a GROUP BY.
136030      */
136031      if( pGroupBy ){
136032        KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
136033        int addr1;          /* A-vs-B comparision jump */
136034        int addrOutputRow;  /* Start of subroutine that outputs a result row */
136035        int regOutputRow;   /* Return address register for output subroutine */
136036        int addrSetAbort;   /* Set the abort flag and return */
136037        int addrTopOfLoop;  /* Top of the input loop */
136038        int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
136039        int addrReset;      /* Subroutine for resetting the accumulator */
136040        int regReset;       /* Return address register for reset subroutine */
136041  
136042        /* If there is a GROUP BY clause we might need a sorting index to
136043        ** implement it.  Allocate that sorting index now.  If it turns out
136044        ** that we do not need it after all, the OP_SorterOpen instruction
136045        ** will be converted into a Noop.  
136046        */
136047        sAggInfo.sortingIdx = pParse->nTab++;
136048        pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
136049        addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
136050            sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
136051            0, (char*)pKeyInfo, P4_KEYINFO);
136052  
136053        /* Initialize memory locations used by GROUP BY aggregate processing
136054        */
136055        iUseFlag = ++pParse->nMem;
136056        iAbortFlag = ++pParse->nMem;
136057        regOutputRow = ++pParse->nMem;
136058        addrOutputRow = sqlite3VdbeMakeLabel(pParse);
136059        regReset = ++pParse->nMem;
136060        addrReset = sqlite3VdbeMakeLabel(pParse);
136061        iAMem = pParse->nMem + 1;
136062        pParse->nMem += pGroupBy->nExpr;
136063        iBMem = pParse->nMem + 1;
136064        pParse->nMem += pGroupBy->nExpr;
136065        sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
136066        VdbeComment((v, "clear abort flag"));
136067        sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
136068  
136069        /* Begin a loop that will extract all source rows in GROUP BY order.
136070        ** This might involve two separate loops with an OP_Sort in between, or
136071        ** it might be a single loop that uses an index to extract information
136072        ** in the right order to begin with.
136073        */
136074        sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
136075        SELECTTRACE(1,pParse,p,("WhereBegin\n"));
136076        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
136077            WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
136078        );
136079        if( pWInfo==0 ) goto select_end;
136080        if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
136081          /* The optimizer is able to deliver rows in group by order so
136082          ** we do not have to sort.  The OP_OpenEphemeral table will be
136083          ** cancelled later because we still need to use the pKeyInfo
136084          */
136085          groupBySort = 0;
136086        }else{
136087          /* Rows are coming out in undetermined order.  We have to push
136088          ** each row into a sorting index, terminate the first loop,
136089          ** then loop over the sorting index in order to get the output
136090          ** in sorted order
136091          */
136092          int regBase;
136093          int regRecord;
136094          int nCol;
136095          int nGroupBy;
136096  
136097          explainTempTable(pParse, 
136098              (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
136099                      "DISTINCT" : "GROUP BY");
136100  
136101          groupBySort = 1;
136102          nGroupBy = pGroupBy->nExpr;
136103          nCol = nGroupBy;
136104          j = nGroupBy;
136105          for(i=0; i<sAggInfo.nColumn; i++){
136106            if( sAggInfo.aCol[i].iSorterColumn>=j ){
136107              nCol++;
136108              j++;
136109            }
136110          }
136111          regBase = sqlite3GetTempRange(pParse, nCol);
136112          sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
136113          j = nGroupBy;
136114          for(i=0; i<sAggInfo.nColumn; i++){
136115            struct AggInfo_col *pCol = &sAggInfo.aCol[i];
136116            if( pCol->iSorterColumn>=j ){
136117              int r1 = j + regBase;
136118              sqlite3ExprCodeGetColumnOfTable(v,
136119                                 pCol->pTab, pCol->iTable, pCol->iColumn, r1);
136120              j++;
136121            }
136122          }
136123          regRecord = sqlite3GetTempReg(pParse);
136124          sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
136125          sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
136126          sqlite3ReleaseTempReg(pParse, regRecord);
136127          sqlite3ReleaseTempRange(pParse, regBase, nCol);
136128          sqlite3WhereEnd(pWInfo);
136129          sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
136130          sortOut = sqlite3GetTempReg(pParse);
136131          sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
136132          sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
136133          VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
136134          sAggInfo.useSortingIdx = 1;
136135        }
136136  
136137        /* If the index or temporary table used by the GROUP BY sort
136138        ** will naturally deliver rows in the order required by the ORDER BY
136139        ** clause, cancel the ephemeral table open coded earlier.
136140        **
136141        ** This is an optimization - the correct answer should result regardless.
136142        ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 
136143        ** disable this optimization for testing purposes.  */
136144        if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 
136145         && (groupBySort || sqlite3WhereIsSorted(pWInfo))
136146        ){
136147          sSort.pOrderBy = 0;
136148          sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
136149        }
136150  
136151        /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
136152        ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
136153        ** Then compare the current GROUP BY terms against the GROUP BY terms
136154        ** from the previous row currently stored in a0, a1, a2...
136155        */
136156        addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
136157        if( groupBySort ){
136158          sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
136159                            sortOut, sortPTab);
136160        }
136161        for(j=0; j<pGroupBy->nExpr; j++){
136162          if( groupBySort ){
136163            sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
136164          }else{
136165            sAggInfo.directMode = 1;
136166            sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
136167          }
136168        }
136169        sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
136170                            (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
136171        addr1 = sqlite3VdbeCurrentAddr(v);
136172        sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
136173  
136174        /* Generate code that runs whenever the GROUP BY changes.
136175        ** Changes in the GROUP BY are detected by the previous code
136176        ** block.  If there were no changes, this block is skipped.
136177        **
136178        ** This code copies current group by terms in b0,b1,b2,...
136179        ** over to a0,a1,a2.  It then calls the output subroutine
136180        ** and resets the aggregate accumulator registers in preparation
136181        ** for the next GROUP BY batch.
136182        */
136183        sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
136184        sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
136185        VdbeComment((v, "output one row"));
136186        sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
136187        VdbeComment((v, "check abort flag"));
136188        sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
136189        VdbeComment((v, "reset accumulator"));
136190  
136191        /* Update the aggregate accumulators based on the content of
136192        ** the current row
136193        */
136194        sqlite3VdbeJumpHere(v, addr1);
136195        updateAccumulator(pParse, iUseFlag, &sAggInfo);
136196        sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
136197        VdbeComment((v, "indicate data in accumulator"));
136198  
136199        /* End of the loop
136200        */
136201        if( groupBySort ){
136202          sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
136203          VdbeCoverage(v);
136204        }else{
136205          sqlite3WhereEnd(pWInfo);
136206          sqlite3VdbeChangeToNoop(v, addrSortingIdx);
136207        }
136208  
136209        /* Output the final row of result
136210        */
136211        sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
136212        VdbeComment((v, "output final row"));
136213  
136214        /* Jump over the subroutines
136215        */
136216        sqlite3VdbeGoto(v, addrEnd);
136217  
136218        /* Generate a subroutine that outputs a single row of the result
136219        ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
136220        ** is less than or equal to zero, the subroutine is a no-op.  If
136221        ** the processing calls for the query to abort, this subroutine
136222        ** increments the iAbortFlag memory location before returning in
136223        ** order to signal the caller to abort.
136224        */
136225        addrSetAbort = sqlite3VdbeCurrentAddr(v);
136226        sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
136227        VdbeComment((v, "set abort flag"));
136228        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
136229        sqlite3VdbeResolveLabel(v, addrOutputRow);
136230        addrOutputRow = sqlite3VdbeCurrentAddr(v);
136231        sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
136232        VdbeCoverage(v);
136233        VdbeComment((v, "Groupby result generator entry point"));
136234        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
136235        finalizeAggFunctions(pParse, &sAggInfo);
136236        sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
136237        selectInnerLoop(pParse, p, -1, &sSort,
136238                        &sDistinct, pDest,
136239                        addrOutputRow+1, addrSetAbort);
136240        sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
136241        VdbeComment((v, "end groupby result generator"));
136242  
136243        /* Generate a subroutine that will reset the group-by accumulator
136244        */
136245        sqlite3VdbeResolveLabel(v, addrReset);
136246        resetAccumulator(pParse, &sAggInfo);
136247        sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
136248        VdbeComment((v, "indicate accumulator empty"));
136249        sqlite3VdbeAddOp1(v, OP_Return, regReset);
136250       
136251      } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
136252      else {
136253  #ifndef SQLITE_OMIT_BTREECOUNT
136254        Table *pTab;
136255        if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
136256          /* If isSimpleCount() returns a pointer to a Table structure, then
136257          ** the SQL statement is of the form:
136258          **
136259          **   SELECT count(*) FROM <tbl>
136260          **
136261          ** where the Table structure returned represents table <tbl>.
136262          **
136263          ** This statement is so common that it is optimized specially. The
136264          ** OP_Count instruction is executed either on the intkey table that
136265          ** contains the data for table <tbl> or on one of its indexes. It
136266          ** is better to execute the op on an index, as indexes are almost
136267          ** always spread across less pages than their corresponding tables.
136268          */
136269          const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
136270          const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
136271          Index *pIdx;                         /* Iterator variable */
136272          KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
136273          Index *pBest = 0;                    /* Best index found so far */
136274          int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
136275  
136276          sqlite3CodeVerifySchema(pParse, iDb);
136277          sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
136278  
136279          /* Search for the index that has the lowest scan cost.
136280          **
136281          ** (2011-04-15) Do not do a full scan of an unordered index.
136282          **
136283          ** (2013-10-03) Do not count the entries in a partial index.
136284          **
136285          ** In practice the KeyInfo structure will not be used. It is only 
136286          ** passed to keep OP_OpenRead happy.
136287          */
136288          if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
136289          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
136290            if( pIdx->bUnordered==0
136291             && pIdx->szIdxRow<pTab->szTabRow
136292             && pIdx->pPartIdxWhere==0
136293             && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
136294            ){
136295              pBest = pIdx;
136296            }
136297          }
136298          if( pBest ){
136299            iRoot = pBest->tnum;
136300            pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
136301          }
136302  
136303          /* Open a read-only cursor, execute the OP_Count, close the cursor. */
136304          sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
136305          if( pKeyInfo ){
136306            sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
136307          }
136308          sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
136309          sqlite3VdbeAddOp1(v, OP_Close, iCsr);
136310          explainSimpleCount(pParse, pTab, pBest);
136311        }else
136312  #endif /* SQLITE_OMIT_BTREECOUNT */
136313        {
136314          int regAcc = 0;           /* "populate accumulators" flag */
136315  
136316          /* If there are accumulator registers but no min() or max() functions,
136317          ** allocate register regAcc. Register regAcc will contain 0 the first
136318          ** time the inner loop runs, and 1 thereafter. The code generated
136319          ** by updateAccumulator() only updates the accumulator registers if
136320          ** regAcc contains 0.  */
136321          if( sAggInfo.nAccumulator ){
136322            for(i=0; i<sAggInfo.nFunc; i++){
136323              if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
136324            }
136325            if( i==sAggInfo.nFunc ){
136326              regAcc = ++pParse->nMem;
136327              sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
136328            }
136329          }
136330  
136331          /* This case runs if the aggregate has no GROUP BY clause.  The
136332          ** processing is much simpler since there is only a single row
136333          ** of output.
136334          */
136335          assert( p->pGroupBy==0 );
136336          resetAccumulator(pParse, &sAggInfo);
136337  
136338          /* If this query is a candidate for the min/max optimization, then
136339          ** minMaxFlag will have been previously set to either
136340          ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
136341          ** be an appropriate ORDER BY expression for the optimization.
136342          */
136343          assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
136344          assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
136345  
136346          SELECTTRACE(1,pParse,p,("WhereBegin\n"));
136347          pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
136348                                     0, minMaxFlag, 0);
136349          if( pWInfo==0 ){
136350            goto select_end;
136351          }
136352          updateAccumulator(pParse, regAcc, &sAggInfo);
136353          if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
136354          if( sqlite3WhereIsOrdered(pWInfo)>0 ){
136355            sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
136356            VdbeComment((v, "%s() by index",
136357                  (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
136358          }
136359          sqlite3WhereEnd(pWInfo);
136360          finalizeAggFunctions(pParse, &sAggInfo);
136361        }
136362  
136363        sSort.pOrderBy = 0;
136364        sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
136365        selectInnerLoop(pParse, p, -1, 0, 0, 
136366                        pDest, addrEnd, addrEnd);
136367      }
136368      sqlite3VdbeResolveLabel(v, addrEnd);
136369      
136370    } /* endif aggregate query */
136371  
136372    if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
136373      explainTempTable(pParse, "DISTINCT");
136374    }
136375  
136376    /* If there is an ORDER BY clause, then we need to sort the results
136377    ** and send them to the callback one by one.
136378    */
136379    if( sSort.pOrderBy ){
136380      explainTempTable(pParse,
136381                       sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
136382      assert( p->pEList==pEList );
136383      generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
136384    }
136385  
136386    /* Jump here to skip this query
136387    */
136388    sqlite3VdbeResolveLabel(v, iEnd);
136389  
136390    /* The SELECT has been coded. If there is an error in the Parse structure,
136391    ** set the return code to 1. Otherwise 0. */
136392    rc = (pParse->nErr>0);
136393  
136394    /* Control jumps to here if an error is encountered above, or upon
136395    ** successful coding of the SELECT.
136396    */
136397  select_end:
136398    sqlite3ExprListDelete(db, pMinMaxOrderBy);
136399    sqlite3DbFree(db, sAggInfo.aCol);
136400    sqlite3DbFree(db, sAggInfo.aFunc);
136401  #if SELECTTRACE_ENABLED
136402    SELECTTRACE(0x1,pParse,p,("end processing\n"));
136403    if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
136404      sqlite3TreeViewSelect(0, p, 0);
136405    }
136406  #endif
136407    ExplainQueryPlanPop(pParse);
136408    return rc;
136409  }
136410  
136411  /************** End of select.c **********************************************/
136412  /************** Begin file table.c *******************************************/
136413  /*
136414  ** 2001 September 15
136415  **
136416  ** The author disclaims copyright to this source code.  In place of
136417  ** a legal notice, here is a blessing:
136418  **
136419  **    May you do good and not evil.
136420  **    May you find forgiveness for yourself and forgive others.
136421  **    May you share freely, never taking more than you give.
136422  **
136423  *************************************************************************
136424  ** This file contains the sqlite3_get_table() and sqlite3_free_table()
136425  ** interface routines.  These are just wrappers around the main
136426  ** interface routine of sqlite3_exec().
136427  **
136428  ** These routines are in a separate files so that they will not be linked
136429  ** if they are not used.
136430  */
136431  /* #include "sqliteInt.h" */
136432  
136433  #ifndef SQLITE_OMIT_GET_TABLE
136434  
136435  /*
136436  ** This structure is used to pass data from sqlite3_get_table() through
136437  ** to the callback function is uses to build the result.
136438  */
136439  typedef struct TabResult {
136440    char **azResult;   /* Accumulated output */
136441    char *zErrMsg;     /* Error message text, if an error occurs */
136442    u32 nAlloc;        /* Slots allocated for azResult[] */
136443    u32 nRow;          /* Number of rows in the result */
136444    u32 nColumn;       /* Number of columns in the result */
136445    u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
136446    int rc;            /* Return code from sqlite3_exec() */
136447  } TabResult;
136448  
136449  /*
136450  ** This routine is called once for each row in the result table.  Its job
136451  ** is to fill in the TabResult structure appropriately, allocating new
136452  ** memory as necessary.
136453  */
136454  static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
136455    TabResult *p = (TabResult*)pArg;  /* Result accumulator */
136456    int need;                         /* Slots needed in p->azResult[] */
136457    int i;                            /* Loop counter */
136458    char *z;                          /* A single column of result */
136459  
136460    /* Make sure there is enough space in p->azResult to hold everything
136461    ** we need to remember from this invocation of the callback.
136462    */
136463    if( p->nRow==0 && argv!=0 ){
136464      need = nCol*2;
136465    }else{
136466      need = nCol;
136467    }
136468    if( p->nData + need > p->nAlloc ){
136469      char **azNew;
136470      p->nAlloc = p->nAlloc*2 + need;
136471      azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
136472      if( azNew==0 ) goto malloc_failed;
136473      p->azResult = azNew;
136474    }
136475  
136476    /* If this is the first row, then generate an extra row containing
136477    ** the names of all columns.
136478    */
136479    if( p->nRow==0 ){
136480      p->nColumn = nCol;
136481      for(i=0; i<nCol; i++){
136482        z = sqlite3_mprintf("%s", colv[i]);
136483        if( z==0 ) goto malloc_failed;
136484        p->azResult[p->nData++] = z;
136485      }
136486    }else if( (int)p->nColumn!=nCol ){
136487      sqlite3_free(p->zErrMsg);
136488      p->zErrMsg = sqlite3_mprintf(
136489         "sqlite3_get_table() called with two or more incompatible queries"
136490      );
136491      p->rc = SQLITE_ERROR;
136492      return 1;
136493    }
136494  
136495    /* Copy over the row data
136496    */
136497    if( argv!=0 ){
136498      for(i=0; i<nCol; i++){
136499        if( argv[i]==0 ){
136500          z = 0;
136501        }else{
136502          int n = sqlite3Strlen30(argv[i])+1;
136503          z = sqlite3_malloc64( n );
136504          if( z==0 ) goto malloc_failed;
136505          memcpy(z, argv[i], n);
136506        }
136507        p->azResult[p->nData++] = z;
136508      }
136509      p->nRow++;
136510    }
136511    return 0;
136512  
136513  malloc_failed:
136514    p->rc = SQLITE_NOMEM_BKPT;
136515    return 1;
136516  }
136517  
136518  /*
136519  ** Query the database.  But instead of invoking a callback for each row,
136520  ** malloc() for space to hold the result and return the entire results
136521  ** at the conclusion of the call.
136522  **
136523  ** The result that is written to ***pazResult is held in memory obtained
136524  ** from malloc().  But the caller cannot free this memory directly.  
136525  ** Instead, the entire table should be passed to sqlite3_free_table() when
136526  ** the calling procedure is finished using it.
136527  */
136528  SQLITE_API int sqlite3_get_table(
136529    sqlite3 *db,                /* The database on which the SQL executes */
136530    const char *zSql,           /* The SQL to be executed */
136531    char ***pazResult,          /* Write the result table here */
136532    int *pnRow,                 /* Write the number of rows in the result here */
136533    int *pnColumn,              /* Write the number of columns of result here */
136534    char **pzErrMsg             /* Write error messages here */
136535  ){
136536    int rc;
136537    TabResult res;
136538  
136539  #ifdef SQLITE_ENABLE_API_ARMOR
136540    if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
136541  #endif
136542    *pazResult = 0;
136543    if( pnColumn ) *pnColumn = 0;
136544    if( pnRow ) *pnRow = 0;
136545    if( pzErrMsg ) *pzErrMsg = 0;
136546    res.zErrMsg = 0;
136547    res.nRow = 0;
136548    res.nColumn = 0;
136549    res.nData = 1;
136550    res.nAlloc = 20;
136551    res.rc = SQLITE_OK;
136552    res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
136553    if( res.azResult==0 ){
136554       db->errCode = SQLITE_NOMEM;
136555       return SQLITE_NOMEM_BKPT;
136556    }
136557    res.azResult[0] = 0;
136558    rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
136559    assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
136560    res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
136561    if( (rc&0xff)==SQLITE_ABORT ){
136562      sqlite3_free_table(&res.azResult[1]);
136563      if( res.zErrMsg ){
136564        if( pzErrMsg ){
136565          sqlite3_free(*pzErrMsg);
136566          *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
136567        }
136568        sqlite3_free(res.zErrMsg);
136569      }
136570      db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
136571      return res.rc;
136572    }
136573    sqlite3_free(res.zErrMsg);
136574    if( rc!=SQLITE_OK ){
136575      sqlite3_free_table(&res.azResult[1]);
136576      return rc;
136577    }
136578    if( res.nAlloc>res.nData ){
136579      char **azNew;
136580      azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
136581      if( azNew==0 ){
136582        sqlite3_free_table(&res.azResult[1]);
136583        db->errCode = SQLITE_NOMEM;
136584        return SQLITE_NOMEM_BKPT;
136585      }
136586      res.azResult = azNew;
136587    }
136588    *pazResult = &res.azResult[1];
136589    if( pnColumn ) *pnColumn = res.nColumn;
136590    if( pnRow ) *pnRow = res.nRow;
136591    return rc;
136592  }
136593  
136594  /*
136595  ** This routine frees the space the sqlite3_get_table() malloced.
136596  */
136597  SQLITE_API void sqlite3_free_table(
136598    char **azResult            /* Result returned from sqlite3_get_table() */
136599  ){
136600    if( azResult ){
136601      int i, n;
136602      azResult--;
136603      assert( azResult!=0 );
136604      n = SQLITE_PTR_TO_INT(azResult[0]);
136605      for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
136606      sqlite3_free(azResult);
136607    }
136608  }
136609  
136610  #endif /* SQLITE_OMIT_GET_TABLE */
136611  
136612  /************** End of table.c ***********************************************/
136613  /************** Begin file trigger.c *****************************************/
136614  /*
136615  **
136616  ** The author disclaims copyright to this source code.  In place of
136617  ** a legal notice, here is a blessing:
136618  **
136619  **    May you do good and not evil.
136620  **    May you find forgiveness for yourself and forgive others.
136621  **    May you share freely, never taking more than you give.
136622  **
136623  *************************************************************************
136624  ** This file contains the implementation for TRIGGERs
136625  */
136626  /* #include "sqliteInt.h" */
136627  
136628  #ifndef SQLITE_OMIT_TRIGGER
136629  /*
136630  ** Delete a linked list of TriggerStep structures.
136631  */
136632  SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
136633    while( pTriggerStep ){
136634      TriggerStep * pTmp = pTriggerStep;
136635      pTriggerStep = pTriggerStep->pNext;
136636  
136637      sqlite3ExprDelete(db, pTmp->pWhere);
136638      sqlite3ExprListDelete(db, pTmp->pExprList);
136639      sqlite3SelectDelete(db, pTmp->pSelect);
136640      sqlite3IdListDelete(db, pTmp->pIdList);
136641      sqlite3UpsertDelete(db, pTmp->pUpsert);
136642      sqlite3DbFree(db, pTmp->zSpan);
136643  
136644      sqlite3DbFree(db, pTmp);
136645    }
136646  }
136647  
136648  /*
136649  ** Given table pTab, return a list of all the triggers attached to 
136650  ** the table. The list is connected by Trigger.pNext pointers.
136651  **
136652  ** All of the triggers on pTab that are in the same database as pTab
136653  ** are already attached to pTab->pTrigger.  But there might be additional
136654  ** triggers on pTab in the TEMP schema.  This routine prepends all
136655  ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
136656  ** and returns the combined list.
136657  **
136658  ** To state it another way:  This routine returns a list of all triggers
136659  ** that fire off of pTab.  The list will include any TEMP triggers on
136660  ** pTab as well as the triggers lised in pTab->pTrigger.
136661  */
136662  SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
136663    Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
136664    Trigger *pList = 0;                  /* List of triggers to return */
136665  
136666    if( pParse->disableTriggers ){
136667      return 0;
136668    }
136669  
136670    if( pTmpSchema!=pTab->pSchema ){
136671      HashElem *p;
136672      assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
136673      for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
136674        Trigger *pTrig = (Trigger *)sqliteHashData(p);
136675        if( pTrig->pTabSchema==pTab->pSchema
136676         && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
136677        ){
136678          pTrig->pNext = (pList ? pList : pTab->pTrigger);
136679          pList = pTrig;
136680        }
136681      }
136682    }
136683  
136684    return (pList ? pList : pTab->pTrigger);
136685  }
136686  
136687  /*
136688  ** This is called by the parser when it sees a CREATE TRIGGER statement
136689  ** up to the point of the BEGIN before the trigger actions.  A Trigger
136690  ** structure is generated based on the information available and stored
136691  ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
136692  ** sqlite3FinishTrigger() function is called to complete the trigger
136693  ** construction process.
136694  */
136695  SQLITE_PRIVATE void sqlite3BeginTrigger(
136696    Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
136697    Token *pName1,      /* The name of the trigger */
136698    Token *pName2,      /* The name of the trigger */
136699    int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
136700    int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
136701    IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
136702    SrcList *pTableName,/* The name of the table/view the trigger applies to */
136703    Expr *pWhen,        /* WHEN clause */
136704    int isTemp,         /* True if the TEMPORARY keyword is present */
136705    int noErr           /* Suppress errors if the trigger already exists */
136706  ){
136707    Trigger *pTrigger = 0;  /* The new trigger */
136708    Table *pTab;            /* Table that the trigger fires off of */
136709    char *zName = 0;        /* Name of the trigger */
136710    sqlite3 *db = pParse->db;  /* The database connection */
136711    int iDb;                /* The database to store the trigger in */
136712    Token *pName;           /* The unqualified db name */
136713    DbFixer sFix;           /* State vector for the DB fixer */
136714  
136715    assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
136716    assert( pName2!=0 );
136717    assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
136718    assert( op>0 && op<0xff );
136719    if( isTemp ){
136720      /* If TEMP was specified, then the trigger name may not be qualified. */
136721      if( pName2->n>0 ){
136722        sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
136723        goto trigger_cleanup;
136724      }
136725      iDb = 1;
136726      pName = pName1;
136727    }else{
136728      /* Figure out the db that the trigger will be created in */
136729      iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
136730      if( iDb<0 ){
136731        goto trigger_cleanup;
136732      }
136733    }
136734    if( !pTableName || db->mallocFailed ){
136735      goto trigger_cleanup;
136736    }
136737  
136738    /* A long-standing parser bug is that this syntax was allowed:
136739    **
136740    **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
136741    **                                                 ^^^^^^^^
136742    **
136743    ** To maintain backwards compatibility, ignore the database
136744    ** name on pTableName if we are reparsing out of SQLITE_MASTER.
136745    */
136746    if( db->init.busy && iDb!=1 ){
136747      sqlite3DbFree(db, pTableName->a[0].zDatabase);
136748      pTableName->a[0].zDatabase = 0;
136749    }
136750  
136751    /* If the trigger name was unqualified, and the table is a temp table,
136752    ** then set iDb to 1 to create the trigger in the temporary database.
136753    ** If sqlite3SrcListLookup() returns 0, indicating the table does not
136754    ** exist, the error is caught by the block below.
136755    */
136756    pTab = sqlite3SrcListLookup(pParse, pTableName);
136757    if( db->init.busy==0 && pName2->n==0 && pTab
136758          && pTab->pSchema==db->aDb[1].pSchema ){
136759      iDb = 1;
136760    }
136761  
136762    /* Ensure the table name matches database name and that the table exists */
136763    if( db->mallocFailed ) goto trigger_cleanup;
136764    assert( pTableName->nSrc==1 );
136765    sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
136766    if( sqlite3FixSrcList(&sFix, pTableName) ){
136767      goto trigger_cleanup;
136768    }
136769    pTab = sqlite3SrcListLookup(pParse, pTableName);
136770    if( !pTab ){
136771      /* The table does not exist. */
136772      if( db->init.iDb==1 ){
136773        /* Ticket #3810.
136774        ** Normally, whenever a table is dropped, all associated triggers are
136775        ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
136776        ** and the table is dropped by a different database connection, the
136777        ** trigger is not visible to the database connection that does the
136778        ** drop so the trigger cannot be dropped.  This results in an
136779        ** "orphaned trigger" - a trigger whose associated table is missing.
136780        */
136781        db->init.orphanTrigger = 1;
136782      }
136783      goto trigger_cleanup;
136784    }
136785    if( IsVirtual(pTab) ){
136786      sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
136787      goto trigger_cleanup;
136788    }
136789  
136790    /* Check that the trigger name is not reserved and that no trigger of the
136791    ** specified name exists */
136792    zName = sqlite3NameFromToken(db, pName);
136793    if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
136794      goto trigger_cleanup;
136795    }
136796    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
136797    if( !IN_RENAME_OBJECT ){
136798      if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
136799        if( !noErr ){
136800          sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
136801        }else{
136802          assert( !db->init.busy );
136803          sqlite3CodeVerifySchema(pParse, iDb);
136804        }
136805        goto trigger_cleanup;
136806      }
136807    }
136808  
136809    /* Do not create a trigger on a system table */
136810    if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
136811      sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
136812      goto trigger_cleanup;
136813    }
136814  
136815    /* INSTEAD of triggers are only for views and views only support INSTEAD
136816    ** of triggers.
136817    */
136818    if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
136819      sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
136820          (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
136821      goto trigger_cleanup;
136822    }
136823    if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
136824      sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
136825          " trigger on table: %S", pTableName, 0);
136826      goto trigger_cleanup;
136827    }
136828  
136829  #ifndef SQLITE_OMIT_AUTHORIZATION
136830    if( !IN_RENAME_OBJECT ){
136831      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
136832      int code = SQLITE_CREATE_TRIGGER;
136833      const char *zDb = db->aDb[iTabDb].zDbSName;
136834      const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
136835      if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
136836      if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
136837        goto trigger_cleanup;
136838      }
136839      if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
136840        goto trigger_cleanup;
136841      }
136842    }
136843  #endif
136844  
136845    /* INSTEAD OF triggers can only appear on views and BEFORE triggers
136846    ** cannot appear on views.  So we might as well translate every
136847    ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
136848    ** elsewhere.
136849    */
136850    if (tr_tm == TK_INSTEAD){
136851      tr_tm = TK_BEFORE;
136852    }
136853  
136854    /* Build the Trigger object */
136855    pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
136856    if( pTrigger==0 ) goto trigger_cleanup;
136857    pTrigger->zName = zName;
136858    zName = 0;
136859    pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
136860    pTrigger->pSchema = db->aDb[iDb].pSchema;
136861    pTrigger->pTabSchema = pTab->pSchema;
136862    pTrigger->op = (u8)op;
136863    pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
136864    if( IN_RENAME_OBJECT ){
136865      sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
136866      pTrigger->pWhen = pWhen;
136867      pWhen = 0;
136868    }else{
136869      pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
136870    }
136871    pTrigger->pColumns = pColumns;
136872    pColumns = 0;
136873    assert( pParse->pNewTrigger==0 );
136874    pParse->pNewTrigger = pTrigger;
136875  
136876  trigger_cleanup:
136877    sqlite3DbFree(db, zName);
136878    sqlite3SrcListDelete(db, pTableName);
136879    sqlite3IdListDelete(db, pColumns);
136880    sqlite3ExprDelete(db, pWhen);
136881    if( !pParse->pNewTrigger ){
136882      sqlite3DeleteTrigger(db, pTrigger);
136883    }else{
136884      assert( pParse->pNewTrigger==pTrigger );
136885    }
136886  }
136887  
136888  /*
136889  ** This routine is called after all of the trigger actions have been parsed
136890  ** in order to complete the process of building the trigger.
136891  */
136892  SQLITE_PRIVATE void sqlite3FinishTrigger(
136893    Parse *pParse,          /* Parser context */
136894    TriggerStep *pStepList, /* The triggered program */
136895    Token *pAll             /* Token that describes the complete CREATE TRIGGER */
136896  ){
136897    Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
136898    char *zName;                            /* Name of trigger */
136899    sqlite3 *db = pParse->db;               /* The database */
136900    DbFixer sFix;                           /* Fixer object */
136901    int iDb;                                /* Database containing the trigger */
136902    Token nameToken;                        /* Trigger name for error reporting */
136903  
136904    pParse->pNewTrigger = 0;
136905    if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
136906    zName = pTrig->zName;
136907    iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
136908    pTrig->step_list = pStepList;
136909    while( pStepList ){
136910      pStepList->pTrig = pTrig;
136911      pStepList = pStepList->pNext;
136912    }
136913    sqlite3TokenInit(&nameToken, pTrig->zName);
136914    sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
136915    if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
136916     || sqlite3FixExpr(&sFix, pTrig->pWhen) 
136917    ){
136918      goto triggerfinish_cleanup;
136919    }
136920  
136921  #ifndef SQLITE_OMIT_ALTERTABLE
136922    if( IN_RENAME_OBJECT ){
136923      assert( !db->init.busy );
136924      pParse->pNewTrigger = pTrig;
136925      pTrig = 0;
136926    }else
136927  #endif
136928  
136929    /* if we are not initializing,
136930    ** build the sqlite_master entry
136931    */
136932    if( !db->init.busy ){
136933      Vdbe *v;
136934      char *z;
136935  
136936      /* Make an entry in the sqlite_master table */
136937      v = sqlite3GetVdbe(pParse);
136938      if( v==0 ) goto triggerfinish_cleanup;
136939      sqlite3BeginWriteOperation(pParse, 0, iDb);
136940      z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
136941      testcase( z==0 );
136942      sqlite3NestedParse(pParse,
136943         "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
136944         db->aDb[iDb].zDbSName, MASTER_NAME, zName,
136945         pTrig->table, z);
136946      sqlite3DbFree(db, z);
136947      sqlite3ChangeCookie(pParse, iDb);
136948      sqlite3VdbeAddParseSchemaOp(v, iDb,
136949          sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
136950    }
136951  
136952    if( db->init.busy ){
136953      Trigger *pLink = pTrig;
136954      Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
136955      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
136956      pTrig = sqlite3HashInsert(pHash, zName, pTrig);
136957      if( pTrig ){
136958        sqlite3OomFault(db);
136959      }else if( pLink->pSchema==pLink->pTabSchema ){
136960        Table *pTab;
136961        pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
136962        assert( pTab!=0 );
136963        pLink->pNext = pTab->pTrigger;
136964        pTab->pTrigger = pLink;
136965      }
136966    }
136967  
136968  triggerfinish_cleanup:
136969    sqlite3DeleteTrigger(db, pTrig);
136970    assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
136971    sqlite3DeleteTriggerStep(db, pStepList);
136972  }
136973  
136974  /*
136975  ** Duplicate a range of text from an SQL statement, then convert all
136976  ** whitespace characters into ordinary space characters.
136977  */
136978  static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
136979    char *z = sqlite3DbSpanDup(db, zStart, zEnd);
136980    int i;
136981    if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
136982    return z;
136983  }    
136984  
136985  /*
136986  ** Turn a SELECT statement (that the pSelect parameter points to) into
136987  ** a trigger step.  Return a pointer to a TriggerStep structure.
136988  **
136989  ** The parser calls this routine when it finds a SELECT statement in
136990  ** body of a TRIGGER.  
136991  */
136992  SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
136993    sqlite3 *db,                /* Database connection */
136994    Select *pSelect,            /* The SELECT statement */
136995    const char *zStart,         /* Start of SQL text */
136996    const char *zEnd            /* End of SQL text */
136997  ){
136998    TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
136999    if( pTriggerStep==0 ) {
137000      sqlite3SelectDelete(db, pSelect);
137001      return 0;
137002    }
137003    pTriggerStep->op = TK_SELECT;
137004    pTriggerStep->pSelect = pSelect;
137005    pTriggerStep->orconf = OE_Default;
137006    pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
137007    return pTriggerStep;
137008  }
137009  
137010  /*
137011  ** Allocate space to hold a new trigger step.  The allocated space
137012  ** holds both the TriggerStep object and the TriggerStep.target.z string.
137013  **
137014  ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
137015  */
137016  static TriggerStep *triggerStepAllocate(
137017    Parse *pParse,              /* Parser context */
137018    u8 op,                      /* Trigger opcode */
137019    Token *pName,               /* The target name */
137020    const char *zStart,         /* Start of SQL text */
137021    const char *zEnd            /* End of SQL text */
137022  ){
137023    sqlite3 *db = pParse->db;
137024    TriggerStep *pTriggerStep;
137025  
137026    pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
137027    if( pTriggerStep ){
137028      char *z = (char*)&pTriggerStep[1];
137029      memcpy(z, pName->z, pName->n);
137030      sqlite3Dequote(z);
137031      pTriggerStep->zTarget = z;
137032      pTriggerStep->op = op;
137033      pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
137034      if( IN_RENAME_OBJECT ){
137035        sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
137036      }
137037    }
137038    return pTriggerStep;
137039  }
137040  
137041  /*
137042  ** Build a trigger step out of an INSERT statement.  Return a pointer
137043  ** to the new trigger step.
137044  **
137045  ** The parser calls this routine when it sees an INSERT inside the
137046  ** body of a trigger.
137047  */
137048  SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
137049    Parse *pParse,      /* Parser */
137050    Token *pTableName,  /* Name of the table into which we insert */
137051    IdList *pColumn,    /* List of columns in pTableName to insert into */
137052    Select *pSelect,    /* A SELECT statement that supplies values */
137053    u8 orconf,          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
137054    Upsert *pUpsert,    /* ON CONFLICT clauses for upsert */
137055    const char *zStart, /* Start of SQL text */
137056    const char *zEnd    /* End of SQL text */
137057  ){
137058    sqlite3 *db = pParse->db;
137059    TriggerStep *pTriggerStep;
137060  
137061    assert(pSelect != 0 || db->mallocFailed);
137062  
137063    pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
137064    if( pTriggerStep ){
137065      if( IN_RENAME_OBJECT ){
137066        pTriggerStep->pSelect = pSelect;
137067        pSelect = 0;
137068      }else{
137069        pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
137070      }
137071      pTriggerStep->pIdList = pColumn;
137072      pTriggerStep->pUpsert = pUpsert;
137073      pTriggerStep->orconf = orconf;
137074    }else{
137075      testcase( pColumn );
137076      sqlite3IdListDelete(db, pColumn);
137077      testcase( pUpsert );
137078      sqlite3UpsertDelete(db, pUpsert);
137079    }
137080    sqlite3SelectDelete(db, pSelect);
137081  
137082    return pTriggerStep;
137083  }
137084  
137085  /*
137086  ** Construct a trigger step that implements an UPDATE statement and return
137087  ** a pointer to that trigger step.  The parser calls this routine when it
137088  ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
137089  */
137090  SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
137091    Parse *pParse,          /* Parser */
137092    Token *pTableName,   /* Name of the table to be updated */
137093    ExprList *pEList,    /* The SET clause: list of column and new values */
137094    Expr *pWhere,        /* The WHERE clause */
137095    u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
137096    const char *zStart,  /* Start of SQL text */
137097    const char *zEnd     /* End of SQL text */
137098  ){
137099    sqlite3 *db = pParse->db;
137100    TriggerStep *pTriggerStep;
137101  
137102    pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
137103    if( pTriggerStep ){
137104      if( IN_RENAME_OBJECT ){
137105        pTriggerStep->pExprList = pEList;
137106        pTriggerStep->pWhere = pWhere;
137107        pEList = 0;
137108        pWhere = 0;
137109      }else{
137110        pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
137111        pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
137112      }
137113      pTriggerStep->orconf = orconf;
137114    }
137115    sqlite3ExprListDelete(db, pEList);
137116    sqlite3ExprDelete(db, pWhere);
137117    return pTriggerStep;
137118  }
137119  
137120  /*
137121  ** Construct a trigger step that implements a DELETE statement and return
137122  ** a pointer to that trigger step.  The parser calls this routine when it
137123  ** sees a DELETE statement inside the body of a CREATE TRIGGER.
137124  */
137125  SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
137126    Parse *pParse,          /* Parser */
137127    Token *pTableName,      /* The table from which rows are deleted */
137128    Expr *pWhere,           /* The WHERE clause */
137129    const char *zStart,     /* Start of SQL text */
137130    const char *zEnd        /* End of SQL text */
137131  ){
137132    sqlite3 *db = pParse->db;
137133    TriggerStep *pTriggerStep;
137134  
137135    pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
137136    if( pTriggerStep ){
137137      if( IN_RENAME_OBJECT ){
137138        pTriggerStep->pWhere = pWhere;
137139        pWhere = 0;
137140      }else{
137141        pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
137142      }
137143      pTriggerStep->orconf = OE_Default;
137144    }
137145    sqlite3ExprDelete(db, pWhere);
137146    return pTriggerStep;
137147  }
137148  
137149  /* 
137150  ** Recursively delete a Trigger structure
137151  */
137152  SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
137153    if( pTrigger==0 ) return;
137154    sqlite3DeleteTriggerStep(db, pTrigger->step_list);
137155    sqlite3DbFree(db, pTrigger->zName);
137156    sqlite3DbFree(db, pTrigger->table);
137157    sqlite3ExprDelete(db, pTrigger->pWhen);
137158    sqlite3IdListDelete(db, pTrigger->pColumns);
137159    sqlite3DbFree(db, pTrigger);
137160  }
137161  
137162  /*
137163  ** This function is called to drop a trigger from the database schema. 
137164  **
137165  ** This may be called directly from the parser and therefore identifies
137166  ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
137167  ** same job as this routine except it takes a pointer to the trigger
137168  ** instead of the trigger name.
137169  **/
137170  SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
137171    Trigger *pTrigger = 0;
137172    int i;
137173    const char *zDb;
137174    const char *zName;
137175    sqlite3 *db = pParse->db;
137176  
137177    if( db->mallocFailed ) goto drop_trigger_cleanup;
137178    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
137179      goto drop_trigger_cleanup;
137180    }
137181  
137182    assert( pName->nSrc==1 );
137183    zDb = pName->a[0].zDatabase;
137184    zName = pName->a[0].zName;
137185    assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
137186    for(i=OMIT_TEMPDB; i<db->nDb; i++){
137187      int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
137188      if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
137189      assert( sqlite3SchemaMutexHeld(db, j, 0) );
137190      pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
137191      if( pTrigger ) break;
137192    }
137193    if( !pTrigger ){
137194      if( !noErr ){
137195        sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
137196      }else{
137197        sqlite3CodeVerifyNamedSchema(pParse, zDb);
137198      }
137199      pParse->checkSchema = 1;
137200      goto drop_trigger_cleanup;
137201    }
137202    sqlite3DropTriggerPtr(pParse, pTrigger);
137203  
137204  drop_trigger_cleanup:
137205    sqlite3SrcListDelete(db, pName);
137206  }
137207  
137208  /*
137209  ** Return a pointer to the Table structure for the table that a trigger
137210  ** is set on.
137211  */
137212  static Table *tableOfTrigger(Trigger *pTrigger){
137213    return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
137214  }
137215  
137216  
137217  /*
137218  ** Drop a trigger given a pointer to that trigger. 
137219  */
137220  SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
137221    Table   *pTable;
137222    Vdbe *v;
137223    sqlite3 *db = pParse->db;
137224    int iDb;
137225  
137226    iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
137227    assert( iDb>=0 && iDb<db->nDb );
137228    pTable = tableOfTrigger(pTrigger);
137229    assert( pTable );
137230    assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
137231  #ifndef SQLITE_OMIT_AUTHORIZATION
137232    {
137233      int code = SQLITE_DROP_TRIGGER;
137234      const char *zDb = db->aDb[iDb].zDbSName;
137235      const char *zTab = SCHEMA_TABLE(iDb);
137236      if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
137237      if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
137238        sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
137239        return;
137240      }
137241    }
137242  #endif
137243  
137244    /* Generate code to destroy the database record of the trigger.
137245    */
137246    assert( pTable!=0 );
137247    if( (v = sqlite3GetVdbe(pParse))!=0 ){
137248      sqlite3NestedParse(pParse,
137249         "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
137250         db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
137251      );
137252      sqlite3ChangeCookie(pParse, iDb);
137253      sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
137254    }
137255  }
137256  
137257  /*
137258  ** Remove a trigger from the hash tables of the sqlite* pointer.
137259  */
137260  SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
137261    Trigger *pTrigger;
137262    Hash *pHash;
137263  
137264    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
137265    pHash = &(db->aDb[iDb].pSchema->trigHash);
137266    pTrigger = sqlite3HashInsert(pHash, zName, 0);
137267    if( ALWAYS(pTrigger) ){
137268      if( pTrigger->pSchema==pTrigger->pTabSchema ){
137269        Table *pTab = tableOfTrigger(pTrigger);
137270        Trigger **pp;
137271        for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
137272        *pp = (*pp)->pNext;
137273      }
137274      sqlite3DeleteTrigger(db, pTrigger);
137275      db->mDbFlags |= DBFLAG_SchemaChange;
137276    }
137277  }
137278  
137279  /*
137280  ** pEList is the SET clause of an UPDATE statement.  Each entry
137281  ** in pEList is of the format <id>=<expr>.  If any of the entries
137282  ** in pEList have an <id> which matches an identifier in pIdList,
137283  ** then return TRUE.  If pIdList==NULL, then it is considered a
137284  ** wildcard that matches anything.  Likewise if pEList==NULL then
137285  ** it matches anything so always return true.  Return false only
137286  ** if there is no match.
137287  */
137288  static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
137289    int e;
137290    if( pIdList==0 || NEVER(pEList==0) ) return 1;
137291    for(e=0; e<pEList->nExpr; e++){
137292      if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
137293    }
137294    return 0; 
137295  }
137296  
137297  /*
137298  ** Return a list of all triggers on table pTab if there exists at least
137299  ** one trigger that must be fired when an operation of type 'op' is 
137300  ** performed on the table, and, if that operation is an UPDATE, if at
137301  ** least one of the columns in pChanges is being modified.
137302  */
137303  SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
137304    Parse *pParse,          /* Parse context */
137305    Table *pTab,            /* The table the contains the triggers */
137306    int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
137307    ExprList *pChanges,     /* Columns that change in an UPDATE statement */
137308    int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
137309  ){
137310    int mask = 0;
137311    Trigger *pList = 0;
137312    Trigger *p;
137313  
137314    if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
137315      pList = sqlite3TriggerList(pParse, pTab);
137316    }
137317    assert( pList==0 || IsVirtual(pTab)==0 );
137318    for(p=pList; p; p=p->pNext){
137319      if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
137320        mask |= p->tr_tm;
137321      }
137322    }
137323    if( pMask ){
137324      *pMask = mask;
137325    }
137326    return (mask ? pList : 0);
137327  }
137328  
137329  /*
137330  ** Convert the pStep->zTarget string into a SrcList and return a pointer
137331  ** to that SrcList.
137332  **
137333  ** This routine adds a specific database name, if needed, to the target when
137334  ** forming the SrcList.  This prevents a trigger in one database from
137335  ** referring to a target in another database.  An exception is when the
137336  ** trigger is in TEMP in which case it can refer to any other database it
137337  ** wants.
137338  */
137339  static SrcList *targetSrcList(
137340    Parse *pParse,       /* The parsing context */
137341    TriggerStep *pStep   /* The trigger containing the target token */
137342  ){
137343    sqlite3 *db = pParse->db;
137344    int iDb;             /* Index of the database to use */
137345    SrcList *pSrc;       /* SrcList to be returned */
137346  
137347    pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
137348    if( pSrc ){
137349      assert( pSrc->nSrc>0 );
137350      pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
137351      iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
137352      if( iDb==0 || iDb>=2 ){
137353        const char *zDb;
137354        assert( iDb<db->nDb );
137355        zDb = db->aDb[iDb].zDbSName;
137356        pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
137357      }
137358    }
137359    return pSrc;
137360  }
137361  
137362  /*
137363  ** Generate VDBE code for the statements inside the body of a single 
137364  ** trigger.
137365  */
137366  static int codeTriggerProgram(
137367    Parse *pParse,            /* The parser context */
137368    TriggerStep *pStepList,   /* List of statements inside the trigger body */
137369    int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
137370  ){
137371    TriggerStep *pStep;
137372    Vdbe *v = pParse->pVdbe;
137373    sqlite3 *db = pParse->db;
137374  
137375    assert( pParse->pTriggerTab && pParse->pToplevel );
137376    assert( pStepList );
137377    assert( v!=0 );
137378    for(pStep=pStepList; pStep; pStep=pStep->pNext){
137379      /* Figure out the ON CONFLICT policy that will be used for this step
137380      ** of the trigger program. If the statement that caused this trigger
137381      ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
137382      ** the ON CONFLICT policy that was specified as part of the trigger
137383      ** step statement. Example:
137384      **
137385      **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
137386      **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
137387      **   END;
137388      **
137389      **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
137390      **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
137391      */
137392      pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
137393      assert( pParse->okConstFactor==0 );
137394  
137395  #ifndef SQLITE_OMIT_TRACE
137396      if( pStep->zSpan ){
137397        sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
137398                          sqlite3MPrintf(db, "-- %s", pStep->zSpan),
137399                          P4_DYNAMIC);
137400      }
137401  #endif
137402  
137403      switch( pStep->op ){
137404        case TK_UPDATE: {
137405          sqlite3Update(pParse, 
137406            targetSrcList(pParse, pStep),
137407            sqlite3ExprListDup(db, pStep->pExprList, 0), 
137408            sqlite3ExprDup(db, pStep->pWhere, 0), 
137409            pParse->eOrconf, 0, 0, 0
137410          );
137411          break;
137412        }
137413        case TK_INSERT: {
137414          sqlite3Insert(pParse, 
137415            targetSrcList(pParse, pStep),
137416            sqlite3SelectDup(db, pStep->pSelect, 0), 
137417            sqlite3IdListDup(db, pStep->pIdList), 
137418            pParse->eOrconf,
137419            sqlite3UpsertDup(db, pStep->pUpsert)
137420          );
137421          break;
137422        }
137423        case TK_DELETE: {
137424          sqlite3DeleteFrom(pParse, 
137425            targetSrcList(pParse, pStep),
137426            sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
137427          );
137428          break;
137429        }
137430        default: assert( pStep->op==TK_SELECT ); {
137431          SelectDest sDest;
137432          Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
137433          sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
137434          sqlite3Select(pParse, pSelect, &sDest);
137435          sqlite3SelectDelete(db, pSelect);
137436          break;
137437        }
137438      } 
137439      if( pStep->op!=TK_SELECT ){
137440        sqlite3VdbeAddOp0(v, OP_ResetCount);
137441      }
137442    }
137443  
137444    return 0;
137445  }
137446  
137447  #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
137448  /*
137449  ** This function is used to add VdbeComment() annotations to a VDBE
137450  ** program. It is not used in production code, only for debugging.
137451  */
137452  static const char *onErrorText(int onError){
137453    switch( onError ){
137454      case OE_Abort:    return "abort";
137455      case OE_Rollback: return "rollback";
137456      case OE_Fail:     return "fail";
137457      case OE_Replace:  return "replace";
137458      case OE_Ignore:   return "ignore";
137459      case OE_Default:  return "default";
137460    }
137461    return "n/a";
137462  }
137463  #endif
137464  
137465  /*
137466  ** Parse context structure pFrom has just been used to create a sub-vdbe
137467  ** (trigger program). If an error has occurred, transfer error information
137468  ** from pFrom to pTo.
137469  */
137470  static void transferParseError(Parse *pTo, Parse *pFrom){
137471    assert( pFrom->zErrMsg==0 || pFrom->nErr );
137472    assert( pTo->zErrMsg==0 || pTo->nErr );
137473    if( pTo->nErr==0 ){
137474      pTo->zErrMsg = pFrom->zErrMsg;
137475      pTo->nErr = pFrom->nErr;
137476      pTo->rc = pFrom->rc;
137477    }else{
137478      sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
137479    }
137480  }
137481  
137482  /*
137483  ** Create and populate a new TriggerPrg object with a sub-program 
137484  ** implementing trigger pTrigger with ON CONFLICT policy orconf.
137485  */
137486  static TriggerPrg *codeRowTrigger(
137487    Parse *pParse,       /* Current parse context */
137488    Trigger *pTrigger,   /* Trigger to code */
137489    Table *pTab,         /* The table pTrigger is attached to */
137490    int orconf           /* ON CONFLICT policy to code trigger program with */
137491  ){
137492    Parse *pTop = sqlite3ParseToplevel(pParse);
137493    sqlite3 *db = pParse->db;   /* Database handle */
137494    TriggerPrg *pPrg;           /* Value to return */
137495    Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
137496    Vdbe *v;                    /* Temporary VM */
137497    NameContext sNC;            /* Name context for sub-vdbe */
137498    SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
137499    Parse *pSubParse;           /* Parse context for sub-vdbe */
137500    int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
137501  
137502    assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
137503    assert( pTop->pVdbe );
137504  
137505    /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
137506    ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
137507    ** list of the top-level Parse object sooner rather than later.  */
137508    pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
137509    if( !pPrg ) return 0;
137510    pPrg->pNext = pTop->pTriggerPrg;
137511    pTop->pTriggerPrg = pPrg;
137512    pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
137513    if( !pProgram ) return 0;
137514    sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
137515    pPrg->pTrigger = pTrigger;
137516    pPrg->orconf = orconf;
137517    pPrg->aColmask[0] = 0xffffffff;
137518    pPrg->aColmask[1] = 0xffffffff;
137519  
137520    /* Allocate and populate a new Parse context to use for coding the 
137521    ** trigger sub-program.  */
137522    pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
137523    if( !pSubParse ) return 0;
137524    memset(&sNC, 0, sizeof(sNC));
137525    sNC.pParse = pSubParse;
137526    pSubParse->db = db;
137527    pSubParse->pTriggerTab = pTab;
137528    pSubParse->pToplevel = pTop;
137529    pSubParse->zAuthContext = pTrigger->zName;
137530    pSubParse->eTriggerOp = pTrigger->op;
137531    pSubParse->nQueryLoop = pParse->nQueryLoop;
137532    pSubParse->disableVtab = pParse->disableVtab;
137533  
137534    v = sqlite3GetVdbe(pSubParse);
137535    if( v ){
137536      VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
137537        pTrigger->zName, onErrorText(orconf),
137538        (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
137539          (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
137540          (pTrigger->op==TK_INSERT ? "INSERT" : ""),
137541          (pTrigger->op==TK_DELETE ? "DELETE" : ""),
137542        pTab->zName
137543      ));
137544  #ifndef SQLITE_OMIT_TRACE
137545      if( pTrigger->zName ){
137546        sqlite3VdbeChangeP4(v, -1, 
137547          sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
137548        );
137549      }
137550  #endif
137551  
137552      /* If one was specified, code the WHEN clause. If it evaluates to false
137553      ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
137554      ** OP_Halt inserted at the end of the program.  */
137555      if( pTrigger->pWhen ){
137556        pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
137557        if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
137558         && db->mallocFailed==0 
137559        ){
137560          iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
137561          sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
137562        }
137563        sqlite3ExprDelete(db, pWhen);
137564      }
137565  
137566      /* Code the trigger program into the sub-vdbe. */
137567      codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
137568  
137569      /* Insert an OP_Halt at the end of the sub-program. */
137570      if( iEndTrigger ){
137571        sqlite3VdbeResolveLabel(v, iEndTrigger);
137572      }
137573      sqlite3VdbeAddOp0(v, OP_Halt);
137574      VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
137575  
137576      transferParseError(pParse, pSubParse);
137577      if( db->mallocFailed==0 && pParse->nErr==0 ){
137578        pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
137579      }
137580      pProgram->nMem = pSubParse->nMem;
137581      pProgram->nCsr = pSubParse->nTab;
137582      pProgram->token = (void *)pTrigger;
137583      pPrg->aColmask[0] = pSubParse->oldmask;
137584      pPrg->aColmask[1] = pSubParse->newmask;
137585      sqlite3VdbeDelete(v);
137586    }
137587  
137588    assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
137589    assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
137590    sqlite3ParserReset(pSubParse);
137591    sqlite3StackFree(db, pSubParse);
137592  
137593    return pPrg;
137594  }
137595      
137596  /*
137597  ** Return a pointer to a TriggerPrg object containing the sub-program for
137598  ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
137599  ** TriggerPrg object exists, a new object is allocated and populated before
137600  ** being returned.
137601  */
137602  static TriggerPrg *getRowTrigger(
137603    Parse *pParse,       /* Current parse context */
137604    Trigger *pTrigger,   /* Trigger to code */
137605    Table *pTab,         /* The table trigger pTrigger is attached to */
137606    int orconf           /* ON CONFLICT algorithm. */
137607  ){
137608    Parse *pRoot = sqlite3ParseToplevel(pParse);
137609    TriggerPrg *pPrg;
137610  
137611    assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
137612  
137613    /* It may be that this trigger has already been coded (or is in the
137614    ** process of being coded). If this is the case, then an entry with
137615    ** a matching TriggerPrg.pTrigger field will be present somewhere
137616    ** in the Parse.pTriggerPrg list. Search for such an entry.  */
137617    for(pPrg=pRoot->pTriggerPrg; 
137618        pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
137619        pPrg=pPrg->pNext
137620    );
137621  
137622    /* If an existing TriggerPrg could not be located, create a new one. */
137623    if( !pPrg ){
137624      pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
137625    }
137626  
137627    return pPrg;
137628  }
137629  
137630  /*
137631  ** Generate code for the trigger program associated with trigger p on 
137632  ** table pTab. The reg, orconf and ignoreJump parameters passed to this
137633  ** function are the same as those described in the header function for
137634  ** sqlite3CodeRowTrigger()
137635  */
137636  SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
137637    Parse *pParse,       /* Parse context */
137638    Trigger *p,          /* Trigger to code */
137639    Table *pTab,         /* The table to code triggers from */
137640    int reg,             /* Reg array containing OLD.* and NEW.* values */
137641    int orconf,          /* ON CONFLICT policy */
137642    int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
137643  ){
137644    Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
137645    TriggerPrg *pPrg;
137646    pPrg = getRowTrigger(pParse, p, pTab, orconf);
137647    assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
137648  
137649    /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
137650    ** is a pointer to the sub-vdbe containing the trigger program.  */
137651    if( pPrg ){
137652      int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
137653  
137654      sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
137655                        (const char *)pPrg->pProgram, P4_SUBPROGRAM);
137656      VdbeComment(
137657          (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
137658  
137659      /* Set the P5 operand of the OP_Program instruction to non-zero if
137660      ** recursive invocation of this trigger program is disallowed. Recursive
137661      ** invocation is disallowed if (a) the sub-program is really a trigger,
137662      ** not a foreign key action, and (b) the flag to enable recursive triggers
137663      ** is clear.  */
137664      sqlite3VdbeChangeP5(v, (u8)bRecursive);
137665    }
137666  }
137667  
137668  /*
137669  ** This is called to code the required FOR EACH ROW triggers for an operation
137670  ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
137671  ** is given by the op parameter. The tr_tm parameter determines whether the
137672  ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
137673  ** parameter pChanges is passed the list of columns being modified.
137674  **
137675  ** If there are no triggers that fire at the specified time for the specified
137676  ** operation on pTab, this function is a no-op.
137677  **
137678  ** The reg argument is the address of the first in an array of registers 
137679  ** that contain the values substituted for the new.* and old.* references
137680  ** in the trigger program. If N is the number of columns in table pTab
137681  ** (a copy of pTab->nCol), then registers are populated as follows:
137682  **
137683  **   Register       Contains
137684  **   ------------------------------------------------------
137685  **   reg+0          OLD.rowid
137686  **   reg+1          OLD.* value of left-most column of pTab
137687  **   ...            ...
137688  **   reg+N          OLD.* value of right-most column of pTab
137689  **   reg+N+1        NEW.rowid
137690  **   reg+N+2        OLD.* value of left-most column of pTab
137691  **   ...            ...
137692  **   reg+N+N+1      NEW.* value of right-most column of pTab
137693  **
137694  ** For ON DELETE triggers, the registers containing the NEW.* values will
137695  ** never be accessed by the trigger program, so they are not allocated or 
137696  ** populated by the caller (there is no data to populate them with anyway). 
137697  ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
137698  ** are never accessed, and so are not allocated by the caller. So, for an
137699  ** ON INSERT trigger, the value passed to this function as parameter reg
137700  ** is not a readable register, although registers (reg+N) through 
137701  ** (reg+N+N+1) are.
137702  **
137703  ** Parameter orconf is the default conflict resolution algorithm for the
137704  ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
137705  ** is the instruction that control should jump to if a trigger program
137706  ** raises an IGNORE exception.
137707  */
137708  SQLITE_PRIVATE void sqlite3CodeRowTrigger(
137709    Parse *pParse,       /* Parse context */
137710    Trigger *pTrigger,   /* List of triggers on table pTab */
137711    int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
137712    ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
137713    int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
137714    Table *pTab,         /* The table to code triggers from */
137715    int reg,             /* The first in an array of registers (see above) */
137716    int orconf,          /* ON CONFLICT policy */
137717    int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
137718  ){
137719    Trigger *p;          /* Used to iterate through pTrigger list */
137720  
137721    assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
137722    assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
137723    assert( (op==TK_UPDATE)==(pChanges!=0) );
137724  
137725    for(p=pTrigger; p; p=p->pNext){
137726  
137727      /* Sanity checking:  The schema for the trigger and for the table are
137728      ** always defined.  The trigger must be in the same schema as the table
137729      ** or else it must be a TEMP trigger. */
137730      assert( p->pSchema!=0 );
137731      assert( p->pTabSchema!=0 );
137732      assert( p->pSchema==p->pTabSchema 
137733           || p->pSchema==pParse->db->aDb[1].pSchema );
137734  
137735      /* Determine whether we should code this trigger */
137736      if( p->op==op 
137737       && p->tr_tm==tr_tm 
137738       && checkColumnOverlap(p->pColumns, pChanges)
137739      ){
137740        sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
137741      }
137742    }
137743  }
137744  
137745  /*
137746  ** Triggers may access values stored in the old.* or new.* pseudo-table. 
137747  ** This function returns a 32-bit bitmask indicating which columns of the 
137748  ** old.* or new.* tables actually are used by triggers. This information 
137749  ** may be used by the caller, for example, to avoid having to load the entire
137750  ** old.* record into memory when executing an UPDATE or DELETE command.
137751  **
137752  ** Bit 0 of the returned mask is set if the left-most column of the
137753  ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
137754  ** the second leftmost column value is required, and so on. If there
137755  ** are more than 32 columns in the table, and at least one of the columns
137756  ** with an index greater than 32 may be accessed, 0xffffffff is returned.
137757  **
137758  ** It is not possible to determine if the old.rowid or new.rowid column is 
137759  ** accessed by triggers. The caller must always assume that it is.
137760  **
137761  ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
137762  ** applies to the old.* table. If 1, the new.* table.
137763  **
137764  ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
137765  ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
137766  ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
137767  ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
137768  ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
137769  */
137770  SQLITE_PRIVATE u32 sqlite3TriggerColmask(
137771    Parse *pParse,       /* Parse context */
137772    Trigger *pTrigger,   /* List of triggers on table pTab */
137773    ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
137774    int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
137775    int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
137776    Table *pTab,         /* The table to code triggers from */
137777    int orconf           /* Default ON CONFLICT policy for trigger steps */
137778  ){
137779    const int op = pChanges ? TK_UPDATE : TK_DELETE;
137780    u32 mask = 0;
137781    Trigger *p;
137782  
137783    assert( isNew==1 || isNew==0 );
137784    for(p=pTrigger; p; p=p->pNext){
137785      if( p->op==op && (tr_tm&p->tr_tm)
137786       && checkColumnOverlap(p->pColumns,pChanges)
137787      ){
137788        TriggerPrg *pPrg;
137789        pPrg = getRowTrigger(pParse, p, pTab, orconf);
137790        if( pPrg ){
137791          mask |= pPrg->aColmask[isNew];
137792        }
137793      }
137794    }
137795  
137796    return mask;
137797  }
137798  
137799  #endif /* !defined(SQLITE_OMIT_TRIGGER) */
137800  
137801  /************** End of trigger.c *********************************************/
137802  /************** Begin file update.c ******************************************/
137803  /*
137804  ** 2001 September 15
137805  **
137806  ** The author disclaims copyright to this source code.  In place of
137807  ** a legal notice, here is a blessing:
137808  **
137809  **    May you do good and not evil.
137810  **    May you find forgiveness for yourself and forgive others.
137811  **    May you share freely, never taking more than you give.
137812  **
137813  *************************************************************************
137814  ** This file contains C code routines that are called by the parser
137815  ** to handle UPDATE statements.
137816  */
137817  /* #include "sqliteInt.h" */
137818  
137819  #ifndef SQLITE_OMIT_VIRTUALTABLE
137820  /* Forward declaration */
137821  static void updateVirtualTable(
137822    Parse *pParse,       /* The parsing context */
137823    SrcList *pSrc,       /* The virtual table to be modified */
137824    Table *pTab,         /* The virtual table */
137825    ExprList *pChanges,  /* The columns to change in the UPDATE statement */
137826    Expr *pRowidExpr,    /* Expression used to recompute the rowid */
137827    int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
137828    Expr *pWhere,        /* WHERE clause of the UPDATE statement */
137829    int onError          /* ON CONFLICT strategy */
137830  );
137831  #endif /* SQLITE_OMIT_VIRTUALTABLE */
137832  
137833  /*
137834  ** The most recently coded instruction was an OP_Column to retrieve the
137835  ** i-th column of table pTab. This routine sets the P4 parameter of the 
137836  ** OP_Column to the default value, if any.
137837  **
137838  ** The default value of a column is specified by a DEFAULT clause in the 
137839  ** column definition. This was either supplied by the user when the table
137840  ** was created, or added later to the table definition by an ALTER TABLE
137841  ** command. If the latter, then the row-records in the table btree on disk
137842  ** may not contain a value for the column and the default value, taken
137843  ** from the P4 parameter of the OP_Column instruction, is returned instead.
137844  ** If the former, then all row-records are guaranteed to include a value
137845  ** for the column and the P4 value is not required.
137846  **
137847  ** Column definitions created by an ALTER TABLE command may only have 
137848  ** literal default values specified: a number, null or a string. (If a more
137849  ** complicated default expression value was provided, it is evaluated 
137850  ** when the ALTER TABLE is executed and one of the literal values written
137851  ** into the sqlite_master table.)
137852  **
137853  ** Therefore, the P4 parameter is only required if the default value for
137854  ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
137855  ** function is capable of transforming these types of expressions into
137856  ** sqlite3_value objects.
137857  **
137858  ** If parameter iReg is not negative, code an OP_RealAffinity instruction
137859  ** on register iReg. This is used when an equivalent integer value is 
137860  ** stored in place of an 8-byte floating point value in order to save 
137861  ** space.
137862  */
137863  SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
137864    assert( pTab!=0 );
137865    if( !pTab->pSelect ){
137866      sqlite3_value *pValue = 0;
137867      u8 enc = ENC(sqlite3VdbeDb(v));
137868      Column *pCol = &pTab->aCol[i];
137869      VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
137870      assert( i<pTab->nCol );
137871      sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
137872                           pCol->affinity, &pValue);
137873      if( pValue ){
137874        sqlite3VdbeAppendP4(v, pValue, P4_MEM);
137875      }
137876    }
137877  #ifndef SQLITE_OMIT_FLOATING_POINT
137878    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
137879      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
137880    }
137881  #endif
137882  }
137883  
137884  /*
137885  ** Check to see if column iCol of index pIdx references any of the
137886  ** columns defined by aXRef and chngRowid.  Return true if it does
137887  ** and false if not.  This is an optimization.  False-positives are a
137888  ** performance degradation, but false-negatives can result in a corrupt
137889  ** index and incorrect answers.
137890  **
137891  ** aXRef[j] will be non-negative if column j of the original table is
137892  ** being updated.  chngRowid will be true if the rowid of the table is
137893  ** being updated.
137894  */
137895  static int indexColumnIsBeingUpdated(
137896    Index *pIdx,      /* The index to check */
137897    int iCol,         /* Which column of the index to check */
137898    int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
137899    int chngRowid     /* true if the rowid is being updated */
137900  ){
137901    i16 iIdxCol = pIdx->aiColumn[iCol];
137902    assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
137903    if( iIdxCol>=0 ){
137904      return aXRef[iIdxCol]>=0;
137905    }
137906    assert( iIdxCol==XN_EXPR );
137907    assert( pIdx->aColExpr!=0 );
137908    assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
137909    return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
137910                                              aXRef,chngRowid);
137911  }
137912  
137913  /*
137914  ** Check to see if index pIdx is a partial index whose conditional
137915  ** expression might change values due to an UPDATE.  Return true if
137916  ** the index is subject to change and false if the index is guaranteed
137917  ** to be unchanged.  This is an optimization.  False-positives are a
137918  ** performance degradation, but false-negatives can result in a corrupt
137919  ** index and incorrect answers.
137920  **
137921  ** aXRef[j] will be non-negative if column j of the original table is
137922  ** being updated.  chngRowid will be true if the rowid of the table is
137923  ** being updated.
137924  */
137925  static int indexWhereClauseMightChange(
137926    Index *pIdx,      /* The index to check */
137927    int *aXRef,       /* aXRef[j]>=0 if column j is being updated */
137928    int chngRowid     /* true if the rowid is being updated */
137929  ){
137930    if( pIdx->pPartIdxWhere==0 ) return 0;
137931    return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
137932                                              aXRef, chngRowid);
137933  }
137934  
137935  /*
137936  ** Process an UPDATE statement.
137937  **
137938  **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
137939  **          \_______/ \________/     \______/       \________________/
137940  *            onError   pTabList      pChanges             pWhere
137941  */
137942  SQLITE_PRIVATE void sqlite3Update(
137943    Parse *pParse,         /* The parser context */
137944    SrcList *pTabList,     /* The table in which we should change things */
137945    ExprList *pChanges,    /* Things to be changed */
137946    Expr *pWhere,          /* The WHERE clause.  May be null */
137947    int onError,           /* How to handle constraint errors */
137948    ExprList *pOrderBy,    /* ORDER BY clause. May be null */
137949    Expr *pLimit,          /* LIMIT clause. May be null */
137950    Upsert *pUpsert        /* ON CONFLICT clause, or null */
137951  ){
137952    int i, j;              /* Loop counters */
137953    Table *pTab;           /* The table to be updated */
137954    int addrTop = 0;       /* VDBE instruction address of the start of the loop */
137955    WhereInfo *pWInfo;     /* Information about the WHERE clause */
137956    Vdbe *v;               /* The virtual database engine */
137957    Index *pIdx;           /* For looping over indices */
137958    Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
137959    int nIdx;              /* Number of indices that need updating */
137960    int iBaseCur;          /* Base cursor number */
137961    int iDataCur;          /* Cursor for the canonical data btree */
137962    int iIdxCur;           /* Cursor for the first index */
137963    sqlite3 *db;           /* The database structure */
137964    int *aRegIdx = 0;      /* First register in array assigned to each index */
137965    int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
137966                           ** an expression for the i-th column of the table.
137967                           ** aXRef[i]==-1 if the i-th column is not changed. */
137968    u8 *aToOpen;           /* 1 for tables and indices to be opened */
137969    u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
137970    u8 chngRowid;          /* Rowid changed in a normal table */
137971    u8 chngKey;            /* Either chngPk or chngRowid */
137972    Expr *pRowidExpr = 0;  /* Expression defining the new record number */
137973    AuthContext sContext;  /* The authorization context */
137974    NameContext sNC;       /* The name-context to resolve expressions in */
137975    int iDb;               /* Database containing the table being updated */
137976    int eOnePass;          /* ONEPASS_XXX value from where.c */
137977    int hasFK;             /* True if foreign key processing is required */
137978    int labelBreak;        /* Jump here to break out of UPDATE loop */
137979    int labelContinue;     /* Jump here to continue next step of UPDATE loop */
137980    int flags;             /* Flags for sqlite3WhereBegin() */
137981  
137982  #ifndef SQLITE_OMIT_TRIGGER
137983    int isView;            /* True when updating a view (INSTEAD OF trigger) */
137984    Trigger *pTrigger;     /* List of triggers on pTab, if required */
137985    int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
137986  #endif
137987    int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
137988    int iEph = 0;          /* Ephemeral table holding all primary key values */
137989    int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
137990    int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
137991    int addrOpen = 0;      /* Address of OP_OpenEphemeral */
137992    int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
137993    i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
137994    int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
137995  
137996    /* Register Allocations */
137997    int regRowCount = 0;   /* A count of rows changed */
137998    int regOldRowid = 0;   /* The old rowid */
137999    int regNewRowid = 0;   /* The new rowid */
138000    int regNew = 0;        /* Content of the NEW.* table in triggers */
138001    int regOld = 0;        /* Content of OLD.* table in triggers */
138002    int regRowSet = 0;     /* Rowset of rows to be updated */
138003    int regKey = 0;        /* composite PRIMARY KEY value */
138004  
138005    memset(&sContext, 0, sizeof(sContext));
138006    db = pParse->db;
138007    if( pParse->nErr || db->mallocFailed ){
138008      goto update_cleanup;
138009    }
138010    assert( pTabList->nSrc==1 );
138011  
138012    /* Locate the table which we want to update. 
138013    */
138014    pTab = sqlite3SrcListLookup(pParse, pTabList);
138015    if( pTab==0 ) goto update_cleanup;
138016    iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
138017  
138018    /* Figure out if we have any triggers and if the table being
138019    ** updated is a view.
138020    */
138021  #ifndef SQLITE_OMIT_TRIGGER
138022    pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
138023    isView = pTab->pSelect!=0;
138024    assert( pTrigger || tmask==0 );
138025  #else
138026  # define pTrigger 0
138027  # define isView 0
138028  # define tmask 0
138029  #endif
138030  #ifdef SQLITE_OMIT_VIEW
138031  # undef isView
138032  # define isView 0
138033  #endif
138034  
138035  #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
138036    if( !isView ){
138037      pWhere = sqlite3LimitWhere(
138038          pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
138039      );
138040      pOrderBy = 0;
138041      pLimit = 0;
138042    }
138043  #endif
138044  
138045    if( sqlite3ViewGetColumnNames(pParse, pTab) ){
138046      goto update_cleanup;
138047    }
138048    if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
138049      goto update_cleanup;
138050    }
138051  
138052    /* Allocate a cursors for the main database table and for all indices.
138053    ** The index cursors might not be used, but if they are used they
138054    ** need to occur right after the database cursor.  So go ahead and
138055    ** allocate enough space, just in case.
138056    */
138057    iBaseCur = iDataCur = pParse->nTab++;
138058    iIdxCur = iDataCur+1;
138059    pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
138060    testcase( pPk!=0 && pPk!=pTab->pIndex );
138061    for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
138062      if( pPk==pIdx ){
138063        iDataCur = pParse->nTab;
138064      }
138065      pParse->nTab++;
138066    }
138067    if( pUpsert ){
138068      /* On an UPSERT, reuse the same cursors already opened by INSERT */
138069      iDataCur = pUpsert->iDataCur;
138070      iIdxCur = pUpsert->iIdxCur;
138071      pParse->nTab = iBaseCur;
138072    }
138073    pTabList->a[0].iCursor = iDataCur;
138074  
138075    /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
138076    ** Initialize aXRef[] and aToOpen[] to their default values.
138077    */
138078    aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
138079    if( aXRef==0 ) goto update_cleanup;
138080    aRegIdx = aXRef+pTab->nCol;
138081    aToOpen = (u8*)(aRegIdx+nIdx);
138082    memset(aToOpen, 1, nIdx+1);
138083    aToOpen[nIdx+1] = 0;
138084    for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
138085  
138086    /* Initialize the name-context */
138087    memset(&sNC, 0, sizeof(sNC));
138088    sNC.pParse = pParse;
138089    sNC.pSrcList = pTabList;
138090    sNC.uNC.pUpsert = pUpsert;
138091    sNC.ncFlags = NC_UUpsert;
138092  
138093    /* Resolve the column names in all the expressions of the
138094    ** of the UPDATE statement.  Also find the column index
138095    ** for each column to be updated in the pChanges array.  For each
138096    ** column to be updated, make sure we have authorization to change
138097    ** that column.
138098    */
138099    chngRowid = chngPk = 0;
138100    for(i=0; i<pChanges->nExpr; i++){
138101      if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
138102        goto update_cleanup;
138103      }
138104      for(j=0; j<pTab->nCol; j++){
138105        if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
138106          if( j==pTab->iPKey ){
138107            chngRowid = 1;
138108            pRowidExpr = pChanges->a[i].pExpr;
138109          }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
138110            chngPk = 1;
138111          }
138112          aXRef[j] = i;
138113          break;
138114        }
138115      }
138116      if( j>=pTab->nCol ){
138117        if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
138118          j = -1;
138119          chngRowid = 1;
138120          pRowidExpr = pChanges->a[i].pExpr;
138121        }else{
138122          sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
138123          pParse->checkSchema = 1;
138124          goto update_cleanup;
138125        }
138126      }
138127  #ifndef SQLITE_OMIT_AUTHORIZATION
138128      {
138129        int rc;
138130        rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
138131                              j<0 ? "ROWID" : pTab->aCol[j].zName,
138132                              db->aDb[iDb].zDbSName);
138133        if( rc==SQLITE_DENY ){
138134          goto update_cleanup;
138135        }else if( rc==SQLITE_IGNORE ){
138136          aXRef[j] = -1;
138137        }
138138      }
138139  #endif
138140    }
138141    assert( (chngRowid & chngPk)==0 );
138142    assert( chngRowid==0 || chngRowid==1 );
138143    assert( chngPk==0 || chngPk==1 );
138144    chngKey = chngRowid + chngPk;
138145  
138146    /* The SET expressions are not actually used inside the WHERE loop.  
138147    ** So reset the colUsed mask. Unless this is a virtual table. In that
138148    ** case, set all bits of the colUsed mask (to ensure that the virtual
138149    ** table implementation makes all columns available).
138150    */
138151    pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
138152  
138153    hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
138154  
138155    /* There is one entry in the aRegIdx[] array for each index on the table
138156    ** being updated.  Fill in aRegIdx[] with a register number that will hold
138157    ** the key for accessing each index.
138158    */
138159    if( onError==OE_Replace ) bReplace = 1;
138160    for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
138161      int reg;
138162      if( chngKey || hasFK>1 || pIdx==pPk
138163       || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
138164      ){
138165        reg = ++pParse->nMem;
138166        pParse->nMem += pIdx->nColumn;
138167      }else{
138168        reg = 0;
138169        for(i=0; i<pIdx->nKeyCol; i++){
138170          if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
138171            reg = ++pParse->nMem;
138172            pParse->nMem += pIdx->nColumn;
138173            if( onError==OE_Default && pIdx->onError==OE_Replace ){
138174              bReplace = 1;
138175            }
138176            break;
138177          }
138178        }
138179      }
138180      if( reg==0 ) aToOpen[j+1] = 0;
138181      aRegIdx[j] = reg;
138182    }
138183    if( bReplace ){
138184      /* If REPLACE conflict resolution might be invoked, open cursors on all 
138185      ** indexes in case they are needed to delete records.  */
138186      memset(aToOpen, 1, nIdx+1);
138187    }
138188  
138189    /* Begin generating code. */
138190    v = sqlite3GetVdbe(pParse);
138191    if( v==0 ) goto update_cleanup;
138192    if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
138193    sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
138194  
138195    /* Allocate required registers. */
138196    if( !IsVirtual(pTab) ){
138197      regRowSet = ++pParse->nMem;
138198      regOldRowid = regNewRowid = ++pParse->nMem;
138199      if( chngPk || pTrigger || hasFK ){
138200        regOld = pParse->nMem + 1;
138201        pParse->nMem += pTab->nCol;
138202      }
138203      if( chngKey || pTrigger || hasFK ){
138204        regNewRowid = ++pParse->nMem;
138205      }
138206      regNew = pParse->nMem + 1;
138207      pParse->nMem += pTab->nCol;
138208    }
138209  
138210    /* Start the view context. */
138211    if( isView ){
138212      sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
138213    }
138214  
138215    /* If we are trying to update a view, realize that view into
138216    ** an ephemeral table.
138217    */
138218  #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
138219    if( isView ){
138220      sqlite3MaterializeView(pParse, pTab, 
138221          pWhere, pOrderBy, pLimit, iDataCur
138222      );
138223      pOrderBy = 0;
138224      pLimit = 0;
138225    }
138226  #endif
138227  
138228    /* Resolve the column names in all the expressions in the
138229    ** WHERE clause.
138230    */
138231    if( sqlite3ResolveExprNames(&sNC, pWhere) ){
138232      goto update_cleanup;
138233    }
138234  
138235  #ifndef SQLITE_OMIT_VIRTUALTABLE
138236    /* Virtual tables must be handled separately */
138237    if( IsVirtual(pTab) ){
138238      updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
138239                         pWhere, onError);
138240      goto update_cleanup;
138241    }
138242  #endif
138243  
138244    /* Jump to labelBreak to abandon further processing of this UPDATE */
138245    labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
138246  
138247    /* Not an UPSERT.  Normal processing.  Begin by
138248    ** initialize the count of updated rows */
138249    if( (db->flags&SQLITE_CountRows)!=0
138250     && !pParse->pTriggerTab
138251     && !pParse->nested
138252     && pUpsert==0
138253    ){
138254      regRowCount = ++pParse->nMem;
138255      sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
138256    }
138257  
138258    if( HasRowid(pTab) ){
138259      sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
138260    }else{
138261      assert( pPk!=0 );
138262      nPk = pPk->nKeyCol;
138263      iPk = pParse->nMem+1;
138264      pParse->nMem += nPk;
138265      regKey = ++pParse->nMem;
138266      if( pUpsert==0 ){
138267        iEph = pParse->nTab++;
138268          sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
138269        addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
138270        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
138271      }
138272    }
138273    
138274    if( pUpsert ){
138275      /* If this is an UPSERT, then all cursors have already been opened by
138276      ** the outer INSERT and the data cursor should be pointing at the row
138277      ** that is to be updated.  So bypass the code that searches for the
138278      ** row(s) to be updated.
138279      */
138280      pWInfo = 0;
138281      eOnePass = ONEPASS_SINGLE;
138282      sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
138283    }else{
138284      /* Begin the database scan. 
138285      **
138286      ** Do not consider a single-pass strategy for a multi-row update if
138287      ** there are any triggers or foreign keys to process, or rows may
138288      ** be deleted as a result of REPLACE conflict handling. Any of these
138289      ** things might disturb a cursor being used to scan through the table
138290      ** or index, causing a single-pass approach to malfunction.  */
138291      flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
138292      if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
138293        flags |= WHERE_ONEPASS_MULTIROW;
138294      }
138295      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
138296      if( pWInfo==0 ) goto update_cleanup;
138297    
138298      /* A one-pass strategy that might update more than one row may not
138299      ** be used if any column of the index used for the scan is being
138300      ** updated. Otherwise, if there is an index on "b", statements like
138301      ** the following could create an infinite loop:
138302      **
138303      **   UPDATE t1 SET b=b+1 WHERE b>?
138304      **
138305      ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
138306      ** strategy that uses an index for which one or more columns are being
138307      ** updated.  */
138308      eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
138309      if( eOnePass!=ONEPASS_SINGLE ){
138310        sqlite3MultiWrite(pParse);
138311        if( eOnePass==ONEPASS_MULTI ){
138312          int iCur = aiCurOnePass[1];
138313          if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
138314            eOnePass = ONEPASS_OFF;
138315          }
138316          assert( iCur!=iDataCur || !HasRowid(pTab) );
138317        }
138318      }
138319    }
138320  
138321    if( HasRowid(pTab) ){
138322      /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
138323      ** mode, write the rowid into the FIFO. In either of the one-pass modes,
138324      ** leave it in register regOldRowid.  */
138325      sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
138326      if( eOnePass==ONEPASS_OFF ){
138327        sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
138328      }
138329    }else{
138330      /* Read the PK of the current row into an array of registers. In
138331      ** ONEPASS_OFF mode, serialize the array into a record and store it in
138332      ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
138333      ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table 
138334      ** is not required) and leave the PK fields in the array of registers.  */
138335      for(i=0; i<nPk; i++){
138336        assert( pPk->aiColumn[i]>=0 );
138337        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
138338      }
138339      if( eOnePass ){
138340        if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
138341        nKey = nPk;
138342        regKey = iPk;
138343      }else{
138344        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
138345                          sqlite3IndexAffinityStr(db, pPk), nPk);
138346        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
138347      }
138348    }
138349  
138350    if( pUpsert==0 ){
138351      if( eOnePass!=ONEPASS_MULTI ){
138352        sqlite3WhereEnd(pWInfo);
138353      }
138354    
138355      if( !isView ){
138356        int addrOnce = 0;
138357    
138358        /* Open every index that needs updating. */
138359        if( eOnePass!=ONEPASS_OFF ){
138360          if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
138361          if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
138362        }
138363    
138364        if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
138365          addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
138366        }
138367        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
138368                                   aToOpen, 0, 0);
138369        if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
138370      }
138371    
138372      /* Top of the update loop */
138373      if( eOnePass!=ONEPASS_OFF ){
138374        if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
138375          assert( pPk );
138376          sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
138377          VdbeCoverage(v);
138378        }
138379        if( eOnePass!=ONEPASS_SINGLE ){
138380          labelContinue = sqlite3VdbeMakeLabel(pParse);
138381        }
138382        sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
138383        VdbeCoverageIf(v, pPk==0);
138384        VdbeCoverageIf(v, pPk!=0);
138385      }else if( pPk ){
138386        labelContinue = sqlite3VdbeMakeLabel(pParse);
138387        sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
138388        addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
138389        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
138390        VdbeCoverage(v);
138391      }else{
138392        labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
138393                                 regOldRowid);
138394        VdbeCoverage(v);
138395        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
138396        VdbeCoverage(v);
138397      }
138398    }
138399  
138400    /* If the rowid value will change, set register regNewRowid to
138401    ** contain the new value. If the rowid is not being modified,
138402    ** then regNewRowid is the same register as regOldRowid, which is
138403    ** already populated.  */
138404    assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
138405    if( chngRowid ){
138406      sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
138407      sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
138408    }
138409  
138410    /* Compute the old pre-UPDATE content of the row being changed, if that
138411    ** information is needed */
138412    if( chngPk || hasFK || pTrigger ){
138413      u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
138414      oldmask |= sqlite3TriggerColmask(pParse, 
138415          pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
138416      );
138417      for(i=0; i<pTab->nCol; i++){
138418        if( oldmask==0xffffffff
138419         || (i<32 && (oldmask & MASKBIT32(i))!=0)
138420         || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
138421        ){
138422          testcase(  oldmask!=0xffffffff && i==31 );
138423          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
138424        }else{
138425          sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
138426        }
138427      }
138428      if( chngRowid==0 && pPk==0 ){
138429        sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
138430      }
138431    }
138432  
138433    /* Populate the array of registers beginning at regNew with the new
138434    ** row data. This array is used to check constants, create the new
138435    ** table and index records, and as the values for any new.* references
138436    ** made by triggers.
138437    **
138438    ** If there are one or more BEFORE triggers, then do not populate the
138439    ** registers associated with columns that are (a) not modified by
138440    ** this UPDATE statement and (b) not accessed by new.* references. The
138441    ** values for registers not modified by the UPDATE must be reloaded from 
138442    ** the database after the BEFORE triggers are fired anyway (as the trigger 
138443    ** may have modified them). So not loading those that are not going to
138444    ** be used eliminates some redundant opcodes.
138445    */
138446    newmask = sqlite3TriggerColmask(
138447        pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
138448    );
138449    for(i=0; i<pTab->nCol; i++){
138450      if( i==pTab->iPKey ){
138451        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
138452      }else{
138453        j = aXRef[i];
138454        if( j>=0 ){
138455          sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
138456        }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
138457          /* This branch loads the value of a column that will not be changed 
138458          ** into a register. This is done if there are no BEFORE triggers, or
138459          ** if there are one or more BEFORE triggers that use this value via
138460          ** a new.* reference in a trigger program.
138461          */
138462          testcase( i==31 );
138463          testcase( i==32 );
138464          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
138465        }else{
138466          sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
138467        }
138468      }
138469    }
138470  
138471    /* Fire any BEFORE UPDATE triggers. This happens before constraints are
138472    ** verified. One could argue that this is wrong.
138473    */
138474    if( tmask&TRIGGER_BEFORE ){
138475      sqlite3TableAffinity(v, pTab, regNew);
138476      sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
138477          TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
138478  
138479      /* The row-trigger may have deleted the row being updated. In this
138480      ** case, jump to the next row. No updates or AFTER triggers are 
138481      ** required. This behavior - what happens when the row being updated
138482      ** is deleted or renamed by a BEFORE trigger - is left undefined in the
138483      ** documentation.
138484      */
138485      if( pPk ){
138486        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
138487        VdbeCoverage(v);
138488      }else{
138489        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
138490        VdbeCoverage(v);
138491      }
138492  
138493      /* After-BEFORE-trigger-reload-loop:
138494      ** If it did not delete it, the BEFORE trigger may still have modified 
138495      ** some of the columns of the row being updated. Load the values for 
138496      ** all columns not modified by the update statement into their registers
138497      ** in case this has happened. Only unmodified columns are reloaded.
138498      ** The values computed for modified columns use the values before the
138499      ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
138500      ** for an example.
138501      */
138502      for(i=0; i<pTab->nCol; i++){
138503        if( aXRef[i]<0 && i!=pTab->iPKey ){
138504          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
138505        }
138506      }
138507    }
138508  
138509    if( !isView ){
138510      int addr1 = 0;        /* Address of jump instruction */
138511  
138512      /* Do constraint checks. */
138513      assert( regOldRowid>0 );
138514      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
138515          regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
138516          aXRef, 0);
138517  
138518      /* Do FK constraint checks. */
138519      if( hasFK ){
138520        sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
138521      }
138522  
138523      /* Delete the index entries associated with the current record.  */
138524      if( bReplace || chngKey ){
138525        if( pPk ){
138526          addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
138527        }else{
138528          addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
138529        }
138530        VdbeCoverageNeverTaken(v);
138531      }
138532      sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
138533  
138534      /* If changing the rowid value, or if there are foreign key constraints
138535      ** to process, delete the old record. Otherwise, add a noop OP_Delete
138536      ** to invoke the pre-update hook.
138537      **
138538      ** That (regNew==regnewRowid+1) is true is also important for the 
138539      ** pre-update hook. If the caller invokes preupdate_new(), the returned
138540      ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
138541      ** is the column index supplied by the user.
138542      */
138543      assert( regNew==regNewRowid+1 );
138544  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
138545      sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
138546          OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
138547          regNewRowid
138548      );
138549      if( eOnePass==ONEPASS_MULTI ){
138550        assert( hasFK==0 && chngKey==0 );
138551        sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
138552      }
138553      if( !pParse->nested ){
138554        sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
138555      }
138556  #else
138557      if( hasFK>1 || chngKey ){
138558        sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
138559      }
138560  #endif
138561      if( bReplace || chngKey ){
138562        sqlite3VdbeJumpHere(v, addr1);
138563      }
138564  
138565      if( hasFK ){
138566        sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
138567      }
138568    
138569      /* Insert the new index entries and the new record. */
138570      sqlite3CompleteInsertion(
138571          pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, 
138572          OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), 
138573          0, 0
138574      );
138575  
138576      /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
138577      ** handle rows (possibly in other tables) that refer via a foreign key
138578      ** to the row just updated. */ 
138579      if( hasFK ){
138580        sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
138581      }
138582    }
138583  
138584    /* Increment the row counter 
138585    */
138586    if( regRowCount ){
138587      sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
138588    }
138589  
138590    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
138591        TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
138592  
138593    /* Repeat the above with the next record to be updated, until
138594    ** all record selected by the WHERE clause have been updated.
138595    */
138596    if( eOnePass==ONEPASS_SINGLE ){
138597      /* Nothing to do at end-of-loop for a single-pass */
138598    }else if( eOnePass==ONEPASS_MULTI ){
138599      sqlite3VdbeResolveLabel(v, labelContinue);
138600      sqlite3WhereEnd(pWInfo);
138601    }else if( pPk ){
138602      sqlite3VdbeResolveLabel(v, labelContinue);
138603      sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
138604    }else{
138605      sqlite3VdbeGoto(v, labelContinue);
138606    }
138607    sqlite3VdbeResolveLabel(v, labelBreak);
138608  
138609    /* Update the sqlite_sequence table by storing the content of the
138610    ** maximum rowid counter values recorded while inserting into
138611    ** autoincrement tables.
138612    */
138613    if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
138614      sqlite3AutoincrementEnd(pParse);
138615    }
138616  
138617    /*
138618    ** Return the number of rows that were changed, if we are tracking
138619    ** that information.
138620    */
138621    if( regRowCount ){
138622      sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
138623      sqlite3VdbeSetNumCols(v, 1);
138624      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
138625    }
138626  
138627  update_cleanup:
138628    sqlite3AuthContextPop(&sContext);
138629    sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
138630    sqlite3SrcListDelete(db, pTabList);
138631    sqlite3ExprListDelete(db, pChanges);
138632    sqlite3ExprDelete(db, pWhere);
138633  #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 
138634    sqlite3ExprListDelete(db, pOrderBy);
138635    sqlite3ExprDelete(db, pLimit);
138636  #endif
138637    return;
138638  }
138639  /* Make sure "isView" and other macros defined above are undefined. Otherwise
138640  ** they may interfere with compilation of other functions in this file
138641  ** (or in another file, if this file becomes part of the amalgamation).  */
138642  #ifdef isView
138643   #undef isView
138644  #endif
138645  #ifdef pTrigger
138646   #undef pTrigger
138647  #endif
138648  
138649  #ifndef SQLITE_OMIT_VIRTUALTABLE
138650  /*
138651  ** Generate code for an UPDATE of a virtual table.
138652  **
138653  ** There are two possible strategies - the default and the special 
138654  ** "onepass" strategy. Onepass is only used if the virtual table 
138655  ** implementation indicates that pWhere may match at most one row.
138656  **
138657  ** The default strategy is to create an ephemeral table that contains
138658  ** for each row to be changed:
138659  **
138660  **   (A)  The original rowid of that row.
138661  **   (B)  The revised rowid for the row.
138662  **   (C)  The content of every column in the row.
138663  **
138664  ** Then loop through the contents of this ephemeral table executing a
138665  ** VUpdate for each row. When finished, drop the ephemeral table.
138666  **
138667  ** The "onepass" strategy does not use an ephemeral table. Instead, it
138668  ** stores the same values (A, B and C above) in a register array and
138669  ** makes a single invocation of VUpdate.
138670  */
138671  static void updateVirtualTable(
138672    Parse *pParse,       /* The parsing context */
138673    SrcList *pSrc,       /* The virtual table to be modified */
138674    Table *pTab,         /* The virtual table */
138675    ExprList *pChanges,  /* The columns to change in the UPDATE statement */
138676    Expr *pRowid,        /* Expression used to recompute the rowid */
138677    int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
138678    Expr *pWhere,        /* WHERE clause of the UPDATE statement */
138679    int onError          /* ON CONFLICT strategy */
138680  ){
138681    Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
138682    int ephemTab;             /* Table holding the result of the SELECT */
138683    int i;                    /* Loop counter */
138684    sqlite3 *db = pParse->db; /* Database connection */
138685    const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
138686    WhereInfo *pWInfo;
138687    int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
138688    int regArg;                     /* First register in VUpdate arg array */
138689    int regRec;                     /* Register in which to assemble record */
138690    int regRowid;                   /* Register for ephem table rowid */
138691    int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
138692    int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
138693    int eOnePass;                   /* True to use onepass strategy */
138694    int addr;                       /* Address of OP_OpenEphemeral */
138695  
138696    /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
138697    ** create and open the ephemeral table in which the records created from
138698    ** these arguments will be temporarily stored. */
138699    assert( v );
138700    ephemTab = pParse->nTab++;
138701    addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
138702    regArg = pParse->nMem + 1;
138703    pParse->nMem += nArg;
138704    regRec = ++pParse->nMem;
138705    regRowid = ++pParse->nMem;
138706  
138707    /* Start scanning the virtual table */
138708    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
138709    if( pWInfo==0 ) return;
138710  
138711    /* Populate the argument registers. */
138712    for(i=0; i<pTab->nCol; i++){
138713      if( aXRef[i]>=0 ){
138714        sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
138715      }else{
138716        sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
138717        sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
138718      }
138719    }
138720    if( HasRowid(pTab) ){
138721      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
138722      if( pRowid ){
138723        sqlite3ExprCode(pParse, pRowid, regArg+1);
138724      }else{
138725        sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
138726      }
138727    }else{
138728      Index *pPk;   /* PRIMARY KEY index */
138729      i16 iPk;      /* PRIMARY KEY column */
138730      pPk = sqlite3PrimaryKeyIndex(pTab);
138731      assert( pPk!=0 );
138732      assert( pPk->nKeyCol==1 );
138733      iPk = pPk->aiColumn[0];
138734      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
138735      sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
138736    }
138737  
138738    eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
138739  
138740    /* There is no ONEPASS_MULTI on virtual tables */
138741    assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
138742  
138743    if( eOnePass ){
138744      /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
138745      ** above. */
138746      sqlite3VdbeChangeToNoop(v, addr);
138747      sqlite3VdbeAddOp1(v, OP_Close, iCsr);
138748    }else{
138749      /* Create a record from the argument register contents and insert it into
138750      ** the ephemeral table. */
138751      sqlite3MultiWrite(pParse);
138752      sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
138753  #ifdef SQLITE_DEBUG
138754      /* Signal an assert() within OP_MakeRecord that it is allowed to
138755      ** accept no-change records with serial_type 10 */
138756      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
138757  #endif
138758      sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
138759      sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
138760    }
138761  
138762  
138763    if( eOnePass==ONEPASS_OFF ){
138764      /* End the virtual table scan */
138765      sqlite3WhereEnd(pWInfo);
138766  
138767      /* Begin scannning through the ephemeral table. */
138768      addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
138769  
138770      /* Extract arguments from the current row of the ephemeral table and 
138771      ** invoke the VUpdate method.  */
138772      for(i=0; i<nArg; i++){
138773        sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
138774      }
138775    }
138776    sqlite3VtabMakeWritable(pParse, pTab);
138777    sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
138778    sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
138779    sqlite3MayAbort(pParse);
138780  
138781    /* End of the ephemeral table scan. Or, if using the onepass strategy,
138782    ** jump to here if the scan visited zero rows. */
138783    if( eOnePass==ONEPASS_OFF ){
138784      sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
138785      sqlite3VdbeJumpHere(v, addr);
138786      sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
138787    }else{
138788      sqlite3WhereEnd(pWInfo);
138789    }
138790  }
138791  #endif /* SQLITE_OMIT_VIRTUALTABLE */
138792  
138793  /************** End of update.c **********************************************/
138794  /************** Begin file upsert.c ******************************************/
138795  /*
138796  ** 2018-04-12
138797  **
138798  ** The author disclaims copyright to this source code.  In place of
138799  ** a legal notice, here is a blessing:
138800  **
138801  **    May you do good and not evil.
138802  **    May you find forgiveness for yourself and forgive others.
138803  **    May you share freely, never taking more than you give.
138804  **
138805  *************************************************************************
138806  ** This file contains code to implement various aspects of UPSERT
138807  ** processing and handling of the Upsert object.
138808  */
138809  /* #include "sqliteInt.h" */
138810  
138811  #ifndef SQLITE_OMIT_UPSERT
138812  /*
138813  ** Free a list of Upsert objects
138814  */
138815  SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
138816    if( p ){
138817      sqlite3ExprListDelete(db, p->pUpsertTarget);
138818      sqlite3ExprDelete(db, p->pUpsertTargetWhere);
138819      sqlite3ExprListDelete(db, p->pUpsertSet);
138820      sqlite3ExprDelete(db, p->pUpsertWhere);
138821      sqlite3DbFree(db, p);
138822    }
138823  }
138824  
138825  /*
138826  ** Duplicate an Upsert object.
138827  */
138828  SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
138829    if( p==0 ) return 0;
138830    return sqlite3UpsertNew(db,
138831             sqlite3ExprListDup(db, p->pUpsertTarget, 0),
138832             sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
138833             sqlite3ExprListDup(db, p->pUpsertSet, 0),
138834             sqlite3ExprDup(db, p->pUpsertWhere, 0)
138835           );
138836  }
138837  
138838  /*
138839  ** Create a new Upsert object.
138840  */
138841  SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
138842    sqlite3 *db,           /* Determines which memory allocator to use */
138843    ExprList *pTarget,     /* Target argument to ON CONFLICT, or NULL */
138844    Expr *pTargetWhere,    /* Optional WHERE clause on the target */
138845    ExprList *pSet,        /* UPDATE columns, or NULL for a DO NOTHING */
138846    Expr *pWhere           /* WHERE clause for the ON CONFLICT UPDATE */
138847  ){
138848    Upsert *pNew;
138849    pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
138850    if( pNew==0 ){
138851      sqlite3ExprListDelete(db, pTarget);
138852      sqlite3ExprDelete(db, pTargetWhere);
138853      sqlite3ExprListDelete(db, pSet);
138854      sqlite3ExprDelete(db, pWhere);
138855      return 0;
138856    }else{
138857      pNew->pUpsertTarget = pTarget;
138858      pNew->pUpsertTargetWhere = pTargetWhere;
138859      pNew->pUpsertSet = pSet;
138860      pNew->pUpsertWhere = pWhere;
138861      pNew->pUpsertIdx = 0;
138862    }
138863    return pNew;
138864  }
138865  
138866  /*
138867  ** Analyze the ON CONFLICT clause described by pUpsert.  Resolve all
138868  ** symbols in the conflict-target.
138869  **
138870  ** Return SQLITE_OK if everything works, or an error code is something
138871  ** is wrong.
138872  */
138873  SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
138874    Parse *pParse,     /* The parsing context */
138875    SrcList *pTabList, /* Table into which we are inserting */
138876    Upsert *pUpsert    /* The ON CONFLICT clauses */
138877  ){
138878    Table *pTab;            /* That table into which we are inserting */
138879    int rc;                 /* Result code */
138880    int iCursor;            /* Cursor used by pTab */
138881    Index *pIdx;            /* One of the indexes of pTab */
138882    ExprList *pTarget;      /* The conflict-target clause */
138883    Expr *pTerm;            /* One term of the conflict-target clause */
138884    NameContext sNC;        /* Context for resolving symbolic names */
138885    Expr sCol[2];           /* Index column converted into an Expr */
138886  
138887    assert( pTabList->nSrc==1 );
138888    assert( pTabList->a[0].pTab!=0 );
138889    assert( pUpsert!=0 );
138890    assert( pUpsert->pUpsertTarget!=0 );
138891  
138892    /* Resolve all symbolic names in the conflict-target clause, which
138893    ** includes both the list of columns and the optional partial-index
138894    ** WHERE clause.
138895    */
138896    memset(&sNC, 0, sizeof(sNC));
138897    sNC.pParse = pParse;
138898    sNC.pSrcList = pTabList;
138899    rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
138900    if( rc ) return rc;
138901    rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
138902    if( rc ) return rc;
138903  
138904    /* Check to see if the conflict target matches the rowid. */  
138905    pTab = pTabList->a[0].pTab;
138906    pTarget = pUpsert->pUpsertTarget;
138907    iCursor = pTabList->a[0].iCursor;
138908    if( HasRowid(pTab) 
138909     && pTarget->nExpr==1
138910     && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
138911     && pTerm->iColumn==XN_ROWID
138912    ){
138913      /* The conflict-target is the rowid of the primary table */
138914      assert( pUpsert->pUpsertIdx==0 );
138915      return SQLITE_OK;
138916    }
138917  
138918    /* Initialize sCol[0..1] to be an expression parse tree for a
138919    ** single column of an index.  The sCol[0] node will be the TK_COLLATE
138920    ** operator and sCol[1] will be the TK_COLUMN operator.  Code below
138921    ** will populate the specific collation and column number values
138922    ** prior to comparing against the conflict-target expression.
138923    */
138924    memset(sCol, 0, sizeof(sCol));
138925    sCol[0].op = TK_COLLATE;
138926    sCol[0].pLeft = &sCol[1];
138927    sCol[1].op = TK_COLUMN;
138928    sCol[1].iTable = pTabList->a[0].iCursor;
138929  
138930    /* Check for matches against other indexes */
138931    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
138932      int ii, jj, nn;
138933      if( !IsUniqueIndex(pIdx) ) continue;
138934      if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
138935      if( pIdx->pPartIdxWhere ){
138936        if( pUpsert->pUpsertTargetWhere==0 ) continue;
138937        if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
138938                               pIdx->pPartIdxWhere, iCursor)!=0 ){
138939          continue;
138940        }
138941      }
138942      nn = pIdx->nKeyCol;
138943      for(ii=0; ii<nn; ii++){
138944        Expr *pExpr;
138945        sCol[0].u.zToken = (char*)pIdx->azColl[ii];
138946        if( pIdx->aiColumn[ii]==XN_EXPR ){
138947          assert( pIdx->aColExpr!=0 );
138948          assert( pIdx->aColExpr->nExpr>ii );
138949          pExpr = pIdx->aColExpr->a[ii].pExpr;
138950          if( pExpr->op!=TK_COLLATE ){
138951            sCol[0].pLeft = pExpr;
138952            pExpr = &sCol[0];
138953          }
138954        }else{
138955          sCol[0].pLeft = &sCol[1];
138956          sCol[1].iColumn = pIdx->aiColumn[ii];
138957          pExpr = &sCol[0];
138958        }
138959        for(jj=0; jj<nn; jj++){
138960          if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
138961            break;  /* Column ii of the index matches column jj of target */
138962          }
138963        }
138964        if( jj>=nn ){
138965          /* The target contains no match for column jj of the index */
138966          break;
138967        }
138968      }
138969      if( ii<nn ){
138970        /* Column ii of the index did not match any term of the conflict target.
138971        ** Continue the search with the next index. */
138972        continue;
138973      }
138974      pUpsert->pUpsertIdx = pIdx;
138975      return SQLITE_OK;
138976    }
138977    sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
138978                            "PRIMARY KEY or UNIQUE constraint");
138979    return SQLITE_ERROR;
138980  }
138981  
138982  /*
138983  ** Generate bytecode that does an UPDATE as part of an upsert.
138984  **
138985  ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
138986  ** In this case parameter iCur is a cursor open on the table b-tree that
138987  ** currently points to the conflicting table row. Otherwise, if pIdx
138988  ** is not NULL, then pIdx is the constraint that failed and iCur is a
138989  ** cursor points to the conflicting row.
138990  */
138991  SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
138992    Parse *pParse,        /* The parsing and code-generating context */
138993    Upsert *pUpsert,      /* The ON CONFLICT clause for the upsert */
138994    Table *pTab,          /* The table being updated */
138995    Index *pIdx,          /* The UNIQUE constraint that failed */
138996    int iCur              /* Cursor for pIdx (or pTab if pIdx==NULL) */
138997  ){
138998    Vdbe *v = pParse->pVdbe;
138999    sqlite3 *db = pParse->db;
139000    SrcList *pSrc;            /* FROM clause for the UPDATE */
139001    int iDataCur;
139002  
139003    assert( v!=0 );
139004    assert( pUpsert!=0 );
139005    VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
139006    iDataCur = pUpsert->iDataCur;
139007    if( pIdx && iCur!=iDataCur ){
139008      if( HasRowid(pTab) ){
139009        int regRowid = sqlite3GetTempReg(pParse);
139010        sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
139011        sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
139012        VdbeCoverage(v);
139013        sqlite3ReleaseTempReg(pParse, regRowid);
139014      }else{
139015        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
139016        int nPk = pPk->nKeyCol;
139017        int iPk = pParse->nMem+1;
139018        int i;
139019        pParse->nMem += nPk;
139020        for(i=0; i<nPk; i++){
139021          int k;
139022          assert( pPk->aiColumn[i]>=0 );
139023          k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
139024          sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
139025          VdbeComment((v, "%s.%s", pIdx->zName,
139026                      pTab->aCol[pPk->aiColumn[i]].zName));
139027        }
139028        sqlite3VdbeVerifyAbortable(v, OE_Abort);
139029        i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
139030        VdbeCoverage(v);
139031        sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, 
139032              "corrupt database", P4_STATIC);
139033        sqlite3VdbeJumpHere(v, i);
139034      }
139035    }
139036    /* pUpsert does not own pUpsertSrc - the outer INSERT statement does.  So
139037    ** we have to make a copy before passing it down into sqlite3Update() */
139038    pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
139039    sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
139040        pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
139041    pUpsert->pUpsertSet = 0;    /* Will have been deleted by sqlite3Update() */
139042    pUpsert->pUpsertWhere = 0;  /* Will have been deleted by sqlite3Update() */
139043    VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
139044  }
139045  
139046  #endif /* SQLITE_OMIT_UPSERT */
139047  
139048  /************** End of upsert.c **********************************************/
139049  /************** Begin file vacuum.c ******************************************/
139050  /*
139051  ** 2003 April 6
139052  **
139053  ** The author disclaims copyright to this source code.  In place of
139054  ** a legal notice, here is a blessing:
139055  **
139056  **    May you do good and not evil.
139057  **    May you find forgiveness for yourself and forgive others.
139058  **    May you share freely, never taking more than you give.
139059  **
139060  *************************************************************************
139061  ** This file contains code used to implement the VACUUM command.
139062  **
139063  ** Most of the code in this file may be omitted by defining the
139064  ** SQLITE_OMIT_VACUUM macro.
139065  */
139066  /* #include "sqliteInt.h" */
139067  /* #include "vdbeInt.h" */
139068  
139069  #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
139070  
139071  /*
139072  ** Execute zSql on database db.
139073  **
139074  ** If zSql returns rows, then each row will have exactly one
139075  ** column.  (This will only happen if zSql begins with "SELECT".)
139076  ** Take each row of result and call execSql() again recursively.
139077  **
139078  ** The execSqlF() routine does the same thing, except it accepts
139079  ** a format string as its third argument
139080  */
139081  static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
139082    sqlite3_stmt *pStmt;
139083    int rc;
139084  
139085    /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
139086    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
139087    if( rc!=SQLITE_OK ) return rc;
139088    while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
139089      const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
139090      assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
139091      /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
139092      ** or INSERT.  Historically there have been attacks that first
139093      ** corrupt the sqlite_master.sql field with other kinds of statements
139094      ** then run VACUUM to get those statements to execute at inappropriate
139095      ** times. */
139096      if( zSubSql
139097       && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
139098      ){
139099        rc = execSql(db, pzErrMsg, zSubSql);
139100        if( rc!=SQLITE_OK ) break;
139101      }
139102    }
139103    assert( rc!=SQLITE_ROW );
139104    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
139105    if( rc ){
139106      sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
139107    }
139108    (void)sqlite3_finalize(pStmt);
139109    return rc;
139110  }
139111  static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
139112    char *z;
139113    va_list ap;
139114    int rc;
139115    va_start(ap, zSql);
139116    z = sqlite3VMPrintf(db, zSql, ap);
139117    va_end(ap);
139118    if( z==0 ) return SQLITE_NOMEM;
139119    rc = execSql(db, pzErrMsg, z);
139120    sqlite3DbFree(db, z);
139121    return rc;
139122  }
139123  
139124  /*
139125  ** The VACUUM command is used to clean up the database,
139126  ** collapse free space, etc.  It is modelled after the VACUUM command
139127  ** in PostgreSQL.  The VACUUM command works as follows:
139128  **
139129  **   (1)  Create a new transient database file
139130  **   (2)  Copy all content from the database being vacuumed into
139131  **        the new transient database file
139132  **   (3)  Copy content from the transient database back into the
139133  **        original database.
139134  **
139135  ** The transient database requires temporary disk space approximately
139136  ** equal to the size of the original database.  The copy operation of
139137  ** step (3) requires additional temporary disk space approximately equal
139138  ** to the size of the original database for the rollback journal.
139139  ** Hence, temporary disk space that is approximately 2x the size of the
139140  ** original database is required.  Every page of the database is written
139141  ** approximately 3 times:  Once for step (2) and twice for step (3).
139142  ** Two writes per page are required in step (3) because the original
139143  ** database content must be written into the rollback journal prior to
139144  ** overwriting the database with the vacuumed content.
139145  **
139146  ** Only 1x temporary space and only 1x writes would be required if
139147  ** the copy of step (3) were replaced by deleting the original database
139148  ** and renaming the transient database as the original.  But that will
139149  ** not work if other processes are attached to the original database.
139150  ** And a power loss in between deleting the original and renaming the
139151  ** transient would cause the database file to appear to be deleted
139152  ** following reboot.
139153  */
139154  SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
139155    Vdbe *v = sqlite3GetVdbe(pParse);
139156    int iDb = 0;
139157    if( v==0 ) goto build_vacuum_end;
139158    if( pNm ){
139159  #ifndef SQLITE_BUG_COMPATIBLE_20160819
139160      /* Default behavior:  Report an error if the argument to VACUUM is
139161      ** not recognized */
139162      iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
139163      if( iDb<0 ) goto build_vacuum_end;
139164  #else
139165      /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
139166      ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
139167      ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
139168      ** The buggy behavior is required for binary compatibility with some
139169      ** legacy applications. */
139170      iDb = sqlite3FindDb(pParse->db, pNm);
139171      if( iDb<0 ) iDb = 0;
139172  #endif
139173    }
139174    if( iDb!=1 ){
139175      int iIntoReg = 0;
139176      if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
139177        iIntoReg = ++pParse->nMem;
139178        sqlite3ExprCode(pParse, pInto, iIntoReg);
139179      }
139180      sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
139181      sqlite3VdbeUsesBtree(v, iDb);
139182    }
139183  build_vacuum_end:
139184    sqlite3ExprDelete(pParse->db, pInto);
139185    return;
139186  }
139187  
139188  /*
139189  ** This routine implements the OP_Vacuum opcode of the VDBE.
139190  */
139191  SQLITE_PRIVATE int sqlite3RunVacuum(
139192    char **pzErrMsg,        /* Write error message here */
139193    sqlite3 *db,            /* Database connection */
139194    int iDb,                /* Which attached DB to vacuum */
139195    sqlite3_value *pOut     /* Write results here, if not NULL */
139196  ){
139197    int rc = SQLITE_OK;     /* Return code from service routines */
139198    Btree *pMain;           /* The database being vacuumed */
139199    Btree *pTemp;           /* The temporary database we vacuum into */
139200    u32 saved_mDbFlags;     /* Saved value of db->mDbFlags */
139201    u64 saved_flags;        /* Saved value of db->flags */
139202    int saved_nChange;      /* Saved value of db->nChange */
139203    int saved_nTotalChange; /* Saved value of db->nTotalChange */
139204    u8 saved_mTrace;        /* Saved trace settings */
139205    Db *pDb = 0;            /* Database to detach at end of vacuum */
139206    int isMemDb;            /* True if vacuuming a :memory: database */
139207    int nRes;               /* Bytes of reserved space at the end of each page */
139208    int nDb;                /* Number of attached databases */
139209    const char *zDbMain;    /* Schema name of database to vacuum */
139210    const char *zOut;       /* Name of output file */
139211  
139212    if( !db->autoCommit ){
139213      sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
139214      return SQLITE_ERROR;
139215    }
139216    if( db->nVdbeActive>1 ){
139217      sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
139218      return SQLITE_ERROR;
139219    }
139220    if( pOut ){
139221      if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
139222        sqlite3SetString(pzErrMsg, db, "non-text filename");
139223        return SQLITE_ERROR;
139224      }
139225      zOut = (const char*)sqlite3_value_text(pOut);
139226    }else{
139227      zOut = "";
139228    }
139229  
139230    /* Save the current value of the database flags so that it can be 
139231    ** restored before returning. Then set the writable-schema flag, and
139232    ** disable CHECK and foreign key constraints.  */
139233    saved_flags = db->flags;
139234    saved_mDbFlags = db->mDbFlags;
139235    saved_nChange = db->nChange;
139236    saved_nTotalChange = db->nTotalChange;
139237    saved_mTrace = db->mTrace;
139238    db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
139239    db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
139240    db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
139241                     | SQLITE_Defensive | SQLITE_CountRows);
139242    db->mTrace = 0;
139243  
139244    zDbMain = db->aDb[iDb].zDbSName;
139245    pMain = db->aDb[iDb].pBt;
139246    isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
139247  
139248    /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
139249    ** can be set to 'off' for this file, as it is not recovered if a crash
139250    ** occurs anyway. The integrity of the database is maintained by a
139251    ** (possibly synchronous) transaction opened on the main database before
139252    ** sqlite3BtreeCopyFile() is called.
139253    **
139254    ** An optimisation would be to use a non-journaled pager.
139255    ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
139256    ** that actually made the VACUUM run slower.  Very little journalling
139257    ** actually occurs when doing a vacuum since the vacuum_db is initially
139258    ** empty.  Only the journal header is written.  Apparently it takes more
139259    ** time to parse and run the PRAGMA to turn journalling off than it does
139260    ** to write the journal header file.
139261    */
139262    nDb = db->nDb;
139263    rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
139264    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139265    assert( (db->nDb-1)==nDb );
139266    pDb = &db->aDb[nDb];
139267    assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
139268    pTemp = pDb->pBt;
139269    if( pOut ){
139270      sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
139271      i64 sz = 0;
139272      if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
139273        rc = SQLITE_ERROR;
139274        sqlite3SetString(pzErrMsg, db, "output file already exists");
139275        goto end_of_vacuum;
139276      }
139277    }
139278    nRes = sqlite3BtreeGetOptimalReserve(pMain);
139279  
139280    /* A VACUUM cannot change the pagesize of an encrypted database. */
139281  #ifdef SQLITE_HAS_CODEC
139282    if( db->nextPagesize ){
139283      extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
139284      int nKey;
139285      char *zKey;
139286      sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
139287      if( nKey ) db->nextPagesize = 0;
139288    }
139289  #endif
139290  
139291    sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
139292    sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
139293    sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
139294  
139295    /* Begin a transaction and take an exclusive lock on the main database
139296    ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
139297    ** to ensure that we do not try to change the page-size on a WAL database.
139298    */
139299    rc = execSql(db, pzErrMsg, "BEGIN");
139300    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139301    rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
139302    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139303  
139304    /* Do not attempt to change the page size for a WAL database */
139305    if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
139306                                                 ==PAGER_JOURNALMODE_WAL ){
139307      db->nextPagesize = 0;
139308    }
139309  
139310    if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
139311     || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
139312     || NEVER(db->mallocFailed)
139313    ){
139314      rc = SQLITE_NOMEM_BKPT;
139315      goto end_of_vacuum;
139316    }
139317  
139318  #ifndef SQLITE_OMIT_AUTOVACUUM
139319    sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
139320                                             sqlite3BtreeGetAutoVacuum(pMain));
139321  #endif
139322  
139323    /* Query the schema of the main database. Create a mirror schema
139324    ** in the temporary database.
139325    */
139326    db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
139327    rc = execSqlF(db, pzErrMsg,
139328        "SELECT sql FROM \"%w\".sqlite_master"
139329        " WHERE type='table'AND name<>'sqlite_sequence'"
139330        " AND coalesce(rootpage,1)>0",
139331        zDbMain
139332    );
139333    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139334    rc = execSqlF(db, pzErrMsg,
139335        "SELECT sql FROM \"%w\".sqlite_master"
139336        " WHERE type='index'",
139337        zDbMain
139338    );
139339    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139340    db->init.iDb = 0;
139341  
139342    /* Loop through the tables in the main database. For each, do
139343    ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
139344    ** the contents to the temporary database.
139345    */
139346    rc = execSqlF(db, pzErrMsg,
139347        "SELECT'INSERT INTO vacuum_db.'||quote(name)"
139348        "||' SELECT*FROM\"%w\".'||quote(name)"
139349        "FROM vacuum_db.sqlite_master "
139350        "WHERE type='table'AND coalesce(rootpage,1)>0",
139351        zDbMain
139352    );
139353    assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
139354    db->mDbFlags &= ~DBFLAG_Vacuum;
139355    if( rc!=SQLITE_OK ) goto end_of_vacuum;
139356  
139357    /* Copy the triggers, views, and virtual tables from the main database
139358    ** over to the temporary database.  None of these objects has any
139359    ** associated storage, so all we have to do is copy their entries
139360    ** from the SQLITE_MASTER table.
139361    */
139362    rc = execSqlF(db, pzErrMsg,
139363        "INSERT INTO vacuum_db.sqlite_master"
139364        " SELECT*FROM \"%w\".sqlite_master"
139365        " WHERE type IN('view','trigger')"
139366        " OR(type='table'AND rootpage=0)",
139367        zDbMain
139368    );
139369    if( rc ) goto end_of_vacuum;
139370  
139371    /* At this point, there is a write transaction open on both the 
139372    ** vacuum database and the main database. Assuming no error occurs,
139373    ** both transactions are closed by this block - the main database
139374    ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
139375    ** call to sqlite3BtreeCommit().
139376    */
139377    {
139378      u32 meta;
139379      int i;
139380  
139381      /* This array determines which meta meta values are preserved in the
139382      ** vacuum.  Even entries are the meta value number and odd entries
139383      ** are an increment to apply to the meta value after the vacuum.
139384      ** The increment is used to increase the schema cookie so that other
139385      ** connections to the same database will know to reread the schema.
139386      */
139387      static const unsigned char aCopy[] = {
139388         BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
139389         BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
139390         BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
139391         BTREE_USER_VERSION,       0,  /* Preserve the user version */
139392         BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
139393      };
139394  
139395      assert( 1==sqlite3BtreeIsInTrans(pTemp) );
139396      assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );
139397  
139398      /* Copy Btree meta values */
139399      for(i=0; i<ArraySize(aCopy); i+=2){
139400        /* GetMeta() and UpdateMeta() cannot fail in this context because
139401        ** we already have page 1 loaded into cache and marked dirty. */
139402        sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
139403        rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
139404        if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
139405      }
139406  
139407      if( pOut==0 ){
139408        rc = sqlite3BtreeCopyFile(pMain, pTemp);
139409      }
139410      if( rc!=SQLITE_OK ) goto end_of_vacuum;
139411      rc = sqlite3BtreeCommit(pTemp);
139412      if( rc!=SQLITE_OK ) goto end_of_vacuum;
139413  #ifndef SQLITE_OMIT_AUTOVACUUM
139414      if( pOut==0 ){
139415        sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
139416      }
139417  #endif
139418    }
139419  
139420    assert( rc==SQLITE_OK );
139421    if( pOut==0 ){
139422      rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
139423    }
139424  
139425  end_of_vacuum:
139426    /* Restore the original value of db->flags */
139427    db->init.iDb = 0;
139428    db->mDbFlags = saved_mDbFlags;
139429    db->flags = saved_flags;
139430    db->nChange = saved_nChange;
139431    db->nTotalChange = saved_nTotalChange;
139432    db->mTrace = saved_mTrace;
139433    sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
139434  
139435    /* Currently there is an SQL level transaction open on the vacuum
139436    ** database. No locks are held on any other files (since the main file
139437    ** was committed at the btree level). So it safe to end the transaction
139438    ** by manually setting the autoCommit flag to true and detaching the
139439    ** vacuum database. The vacuum_db journal file is deleted when the pager
139440    ** is closed by the DETACH.
139441    */
139442    db->autoCommit = 1;
139443  
139444    if( pDb ){
139445      sqlite3BtreeClose(pDb->pBt);
139446      pDb->pBt = 0;
139447      pDb->pSchema = 0;
139448    }
139449  
139450    /* This both clears the schemas and reduces the size of the db->aDb[]
139451    ** array. */ 
139452    sqlite3ResetAllSchemasOfConnection(db);
139453  
139454    return rc;
139455  }
139456  
139457  #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
139458  
139459  /************** End of vacuum.c **********************************************/
139460  /************** Begin file vtab.c ********************************************/
139461  /*
139462  ** 2006 June 10
139463  **
139464  ** The author disclaims copyright to this source code.  In place of
139465  ** a legal notice, here is a blessing:
139466  **
139467  **    May you do good and not evil.
139468  **    May you find forgiveness for yourself and forgive others.
139469  **    May you share freely, never taking more than you give.
139470  **
139471  *************************************************************************
139472  ** This file contains code used to help implement virtual tables.
139473  */
139474  #ifndef SQLITE_OMIT_VIRTUALTABLE
139475  /* #include "sqliteInt.h" */
139476  
139477  /*
139478  ** Before a virtual table xCreate() or xConnect() method is invoked, the
139479  ** sqlite3.pVtabCtx member variable is set to point to an instance of
139480  ** this struct allocated on the stack. It is used by the implementation of 
139481  ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
139482  ** are invoked only from within xCreate and xConnect methods.
139483  */
139484  struct VtabCtx {
139485    VTable *pVTable;    /* The virtual table being constructed */
139486    Table *pTab;        /* The Table object to which the virtual table belongs */
139487    VtabCtx *pPrior;    /* Parent context (if any) */
139488    int bDeclared;      /* True after sqlite3_declare_vtab() is called */
139489  };
139490  
139491  /*
139492  ** Construct and install a Module object for a virtual table.  When this
139493  ** routine is called, it is guaranteed that all appropriate locks are held
139494  ** and the module is not already part of the connection.
139495  */
139496  SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
139497    sqlite3 *db,                    /* Database in which module is registered */
139498    const char *zName,              /* Name assigned to this module */
139499    const sqlite3_module *pModule,  /* The definition of the module */
139500    void *pAux,                     /* Context pointer for xCreate/xConnect */
139501    void (*xDestroy)(void *)        /* Module destructor function */
139502  ){
139503    Module *pMod;
139504    int nName = sqlite3Strlen30(zName);
139505    pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
139506    if( pMod==0 ){
139507      sqlite3OomFault(db);
139508    }else{
139509      Module *pDel;
139510      char *zCopy = (char *)(&pMod[1]);
139511      memcpy(zCopy, zName, nName+1);
139512      pMod->zName = zCopy;
139513      pMod->pModule = pModule;
139514      pMod->pAux = pAux;
139515      pMod->xDestroy = xDestroy;
139516      pMod->pEpoTab = 0;
139517      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
139518      assert( pDel==0 || pDel==pMod );
139519      if( pDel ){
139520        sqlite3OomFault(db);
139521        sqlite3DbFree(db, pDel);
139522        pMod = 0;
139523      }
139524    }
139525    return pMod;
139526  }
139527  
139528  /*
139529  ** The actual function that does the work of creating a new module.
139530  ** This function implements the sqlite3_create_module() and
139531  ** sqlite3_create_module_v2() interfaces.
139532  */
139533  static int createModule(
139534    sqlite3 *db,                    /* Database in which module is registered */
139535    const char *zName,              /* Name assigned to this module */
139536    const sqlite3_module *pModule,  /* The definition of the module */
139537    void *pAux,                     /* Context pointer for xCreate/xConnect */
139538    void (*xDestroy)(void *)        /* Module destructor function */
139539  ){
139540    int rc = SQLITE_OK;
139541  
139542    sqlite3_mutex_enter(db->mutex);
139543    if( sqlite3HashFind(&db->aModule, zName) ){
139544      rc = SQLITE_MISUSE_BKPT;
139545    }else{
139546      (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
139547    }
139548    rc = sqlite3ApiExit(db, rc);
139549    if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
139550    sqlite3_mutex_leave(db->mutex);
139551    return rc;
139552  }
139553  
139554  
139555  /*
139556  ** External API function used to create a new virtual-table module.
139557  */
139558  SQLITE_API int sqlite3_create_module(
139559    sqlite3 *db,                    /* Database in which module is registered */
139560    const char *zName,              /* Name assigned to this module */
139561    const sqlite3_module *pModule,  /* The definition of the module */
139562    void *pAux                      /* Context pointer for xCreate/xConnect */
139563  ){
139564  #ifdef SQLITE_ENABLE_API_ARMOR
139565    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139566  #endif
139567    return createModule(db, zName, pModule, pAux, 0);
139568  }
139569  
139570  /*
139571  ** External API function used to create a new virtual-table module.
139572  */
139573  SQLITE_API int sqlite3_create_module_v2(
139574    sqlite3 *db,                    /* Database in which module is registered */
139575    const char *zName,              /* Name assigned to this module */
139576    const sqlite3_module *pModule,  /* The definition of the module */
139577    void *pAux,                     /* Context pointer for xCreate/xConnect */
139578    void (*xDestroy)(void *)        /* Module destructor function */
139579  ){
139580  #ifdef SQLITE_ENABLE_API_ARMOR
139581    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139582  #endif
139583    return createModule(db, zName, pModule, pAux, xDestroy);
139584  }
139585  
139586  /*
139587  ** Lock the virtual table so that it cannot be disconnected.
139588  ** Locks nest.  Every lock should have a corresponding unlock.
139589  ** If an unlock is omitted, resources leaks will occur.  
139590  **
139591  ** If a disconnect is attempted while a virtual table is locked,
139592  ** the disconnect is deferred until all locks have been removed.
139593  */
139594  SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
139595    pVTab->nRef++;
139596  }
139597  
139598  
139599  /*
139600  ** pTab is a pointer to a Table structure representing a virtual-table.
139601  ** Return a pointer to the VTable object used by connection db to access 
139602  ** this virtual-table, if one has been created, or NULL otherwise.
139603  */
139604  SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
139605    VTable *pVtab;
139606    assert( IsVirtual(pTab) );
139607    for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
139608    return pVtab;
139609  }
139610  
139611  /*
139612  ** Decrement the ref-count on a virtual table object. When the ref-count
139613  ** reaches zero, call the xDisconnect() method to delete the object.
139614  */
139615  SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
139616    sqlite3 *db = pVTab->db;
139617  
139618    assert( db );
139619    assert( pVTab->nRef>0 );
139620    assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
139621  
139622    pVTab->nRef--;
139623    if( pVTab->nRef==0 ){
139624      sqlite3_vtab *p = pVTab->pVtab;
139625      if( p ){
139626        p->pModule->xDisconnect(p);
139627      }
139628      sqlite3DbFree(db, pVTab);
139629    }
139630  }
139631  
139632  /*
139633  ** Table p is a virtual table. This function moves all elements in the
139634  ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
139635  ** database connections to be disconnected at the next opportunity. 
139636  ** Except, if argument db is not NULL, then the entry associated with
139637  ** connection db is left in the p->pVTable list.
139638  */
139639  static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
139640    VTable *pRet = 0;
139641    VTable *pVTable = p->pVTable;
139642    p->pVTable = 0;
139643  
139644    /* Assert that the mutex (if any) associated with the BtShared database 
139645    ** that contains table p is held by the caller. See header comments 
139646    ** above function sqlite3VtabUnlockList() for an explanation of why
139647    ** this makes it safe to access the sqlite3.pDisconnect list of any
139648    ** database connection that may have an entry in the p->pVTable list.
139649    */
139650    assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
139651  
139652    while( pVTable ){
139653      sqlite3 *db2 = pVTable->db;
139654      VTable *pNext = pVTable->pNext;
139655      assert( db2 );
139656      if( db2==db ){
139657        pRet = pVTable;
139658        p->pVTable = pRet;
139659        pRet->pNext = 0;
139660      }else{
139661        pVTable->pNext = db2->pDisconnect;
139662        db2->pDisconnect = pVTable;
139663      }
139664      pVTable = pNext;
139665    }
139666  
139667    assert( !db || pRet );
139668    return pRet;
139669  }
139670  
139671  /*
139672  ** Table *p is a virtual table. This function removes the VTable object
139673  ** for table *p associated with database connection db from the linked
139674  ** list in p->pVTab. It also decrements the VTable ref count. This is
139675  ** used when closing database connection db to free all of its VTable
139676  ** objects without disturbing the rest of the Schema object (which may
139677  ** be being used by other shared-cache connections).
139678  */
139679  SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
139680    VTable **ppVTab;
139681  
139682    assert( IsVirtual(p) );
139683    assert( sqlite3BtreeHoldsAllMutexes(db) );
139684    assert( sqlite3_mutex_held(db->mutex) );
139685  
139686    for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
139687      if( (*ppVTab)->db==db  ){
139688        VTable *pVTab = *ppVTab;
139689        *ppVTab = pVTab->pNext;
139690        sqlite3VtabUnlock(pVTab);
139691        break;
139692      }
139693    }
139694  }
139695  
139696  
139697  /*
139698  ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
139699  **
139700  ** This function may only be called when the mutexes associated with all
139701  ** shared b-tree databases opened using connection db are held by the 
139702  ** caller. This is done to protect the sqlite3.pDisconnect list. The
139703  ** sqlite3.pDisconnect list is accessed only as follows:
139704  **
139705  **   1) By this function. In this case, all BtShared mutexes and the mutex
139706  **      associated with the database handle itself must be held.
139707  **
139708  **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
139709  **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
139710  **      associated with the database the virtual table is stored in is held
139711  **      or, if the virtual table is stored in a non-sharable database, then
139712  **      the database handle mutex is held.
139713  **
139714  ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
139715  ** by multiple threads. It is thread-safe.
139716  */
139717  SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
139718    VTable *p = db->pDisconnect;
139719    db->pDisconnect = 0;
139720  
139721    assert( sqlite3BtreeHoldsAllMutexes(db) );
139722    assert( sqlite3_mutex_held(db->mutex) );
139723  
139724    if( p ){
139725      sqlite3ExpirePreparedStatements(db, 0);
139726      do {
139727        VTable *pNext = p->pNext;
139728        sqlite3VtabUnlock(p);
139729        p = pNext;
139730      }while( p );
139731    }
139732  }
139733  
139734  /*
139735  ** Clear any and all virtual-table information from the Table record.
139736  ** This routine is called, for example, just before deleting the Table
139737  ** record.
139738  **
139739  ** Since it is a virtual-table, the Table structure contains a pointer
139740  ** to the head of a linked list of VTable structures. Each VTable 
139741  ** structure is associated with a single sqlite3* user of the schema.
139742  ** The reference count of the VTable structure associated with database 
139743  ** connection db is decremented immediately (which may lead to the 
139744  ** structure being xDisconnected and free). Any other VTable structures
139745  ** in the list are moved to the sqlite3.pDisconnect list of the associated 
139746  ** database connection.
139747  */
139748  SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
139749    if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
139750    if( p->azModuleArg ){
139751      int i;
139752      for(i=0; i<p->nModuleArg; i++){
139753        if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
139754      }
139755      sqlite3DbFree(db, p->azModuleArg);
139756    }
139757  }
139758  
139759  /*
139760  ** Add a new module argument to pTable->azModuleArg[].
139761  ** The string is not copied - the pointer is stored.  The
139762  ** string will be freed automatically when the table is
139763  ** deleted.
139764  */
139765  static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
139766    int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
139767    char **azModuleArg;
139768    azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
139769    if( azModuleArg==0 ){
139770      sqlite3DbFree(db, zArg);
139771    }else{
139772      int i = pTable->nModuleArg++;
139773      azModuleArg[i] = zArg;
139774      azModuleArg[i+1] = 0;
139775      pTable->azModuleArg = azModuleArg;
139776    }
139777  }
139778  
139779  /*
139780  ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
139781  ** statement.  The module name has been parsed, but the optional list
139782  ** of parameters that follow the module name are still pending.
139783  */
139784  SQLITE_PRIVATE void sqlite3VtabBeginParse(
139785    Parse *pParse,        /* Parsing context */
139786    Token *pName1,        /* Name of new table, or database name */
139787    Token *pName2,        /* Name of new table or NULL */
139788    Token *pModuleName,   /* Name of the module for the virtual table */
139789    int ifNotExists       /* No error if the table already exists */
139790  ){
139791    Table *pTable;        /* The new virtual table */
139792    sqlite3 *db;          /* Database connection */
139793  
139794    sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
139795    pTable = pParse->pNewTable;
139796    if( pTable==0 ) return;
139797    assert( 0==pTable->pIndex );
139798  
139799    db = pParse->db;
139800  
139801    assert( pTable->nModuleArg==0 );
139802    addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
139803    addModuleArgument(db, pTable, 0);
139804    addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
139805    assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
139806         || (pParse->sNameToken.z==pName1->z && pName2->z==0)
139807    );
139808    pParse->sNameToken.n = (int)(
139809        &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
139810    );
139811  
139812  #ifndef SQLITE_OMIT_AUTHORIZATION
139813    /* Creating a virtual table invokes the authorization callback twice.
139814    ** The first invocation, to obtain permission to INSERT a row into the
139815    ** sqlite_master table, has already been made by sqlite3StartTable().
139816    ** The second call, to obtain permission to create the table, is made now.
139817    */
139818    if( pTable->azModuleArg ){
139819      int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
139820      assert( iDb>=0 ); /* The database the table is being created in */
139821      sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
139822              pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
139823    }
139824  #endif
139825  }
139826  
139827  /*
139828  ** This routine takes the module argument that has been accumulating
139829  ** in pParse->zArg[] and appends it to the list of arguments on the
139830  ** virtual table currently under construction in pParse->pTable.
139831  */
139832  static void addArgumentToVtab(Parse *pParse){
139833    if( pParse->sArg.z && pParse->pNewTable ){
139834      const char *z = (const char*)pParse->sArg.z;
139835      int n = pParse->sArg.n;
139836      sqlite3 *db = pParse->db;
139837      addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
139838    }
139839  }
139840  
139841  /*
139842  ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
139843  ** has been completely parsed.
139844  */
139845  SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
139846    Table *pTab = pParse->pNewTable;  /* The table being constructed */
139847    sqlite3 *db = pParse->db;         /* The database connection */
139848  
139849    if( pTab==0 ) return;
139850    addArgumentToVtab(pParse);
139851    pParse->sArg.z = 0;
139852    if( pTab->nModuleArg<1 ) return;
139853    
139854    /* If the CREATE VIRTUAL TABLE statement is being entered for the
139855    ** first time (in other words if the virtual table is actually being
139856    ** created now instead of just being read out of sqlite_master) then
139857    ** do additional initialization work and store the statement text
139858    ** in the sqlite_master table.
139859    */
139860    if( !db->init.busy ){
139861      char *zStmt;
139862      char *zWhere;
139863      int iDb;
139864      int iReg;
139865      Vdbe *v;
139866  
139867      /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
139868      if( pEnd ){
139869        pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
139870      }
139871      zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
139872  
139873      /* A slot for the record has already been allocated in the 
139874      ** SQLITE_MASTER table.  We just need to update that slot with all
139875      ** the information we've collected.  
139876      **
139877      ** The VM register number pParse->regRowid holds the rowid of an
139878      ** entry in the sqlite_master table tht was created for this vtab
139879      ** by sqlite3StartTable().
139880      */
139881      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
139882      sqlite3NestedParse(pParse,
139883        "UPDATE %Q.%s "
139884           "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
139885         "WHERE rowid=#%d",
139886        db->aDb[iDb].zDbSName, MASTER_NAME,
139887        pTab->zName,
139888        pTab->zName,
139889        zStmt,
139890        pParse->regRowid
139891      );
139892      sqlite3DbFree(db, zStmt);
139893      v = sqlite3GetVdbe(pParse);
139894      sqlite3ChangeCookie(pParse, iDb);
139895  
139896      sqlite3VdbeAddOp0(v, OP_Expire);
139897      zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
139898      sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
139899  
139900      iReg = ++pParse->nMem;
139901      sqlite3VdbeLoadString(v, iReg, pTab->zName);
139902      sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
139903    }
139904  
139905    /* If we are rereading the sqlite_master table create the in-memory
139906    ** record of the table. The xConnect() method is not called until
139907    ** the first time the virtual table is used in an SQL statement. This
139908    ** allows a schema that contains virtual tables to be loaded before
139909    ** the required virtual table implementations are registered.  */
139910    else {
139911      Table *pOld;
139912      Schema *pSchema = pTab->pSchema;
139913      const char *zName = pTab->zName;
139914      assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
139915      pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
139916      if( pOld ){
139917        sqlite3OomFault(db);
139918        assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
139919        return;
139920      }
139921      pParse->pNewTable = 0;
139922    }
139923  }
139924  
139925  /*
139926  ** The parser calls this routine when it sees the first token
139927  ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
139928  */
139929  SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
139930    addArgumentToVtab(pParse);
139931    pParse->sArg.z = 0;
139932    pParse->sArg.n = 0;
139933  }
139934  
139935  /*
139936  ** The parser calls this routine for each token after the first token
139937  ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
139938  */
139939  SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
139940    Token *pArg = &pParse->sArg;
139941    if( pArg->z==0 ){
139942      pArg->z = p->z;
139943      pArg->n = p->n;
139944    }else{
139945      assert(pArg->z <= p->z);
139946      pArg->n = (int)(&p->z[p->n] - pArg->z);
139947    }
139948  }
139949  
139950  /*
139951  ** Invoke a virtual table constructor (either xCreate or xConnect). The
139952  ** pointer to the function to invoke is passed as the fourth parameter
139953  ** to this procedure.
139954  */
139955  static int vtabCallConstructor(
139956    sqlite3 *db, 
139957    Table *pTab,
139958    Module *pMod,
139959    int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
139960    char **pzErr
139961  ){
139962    VtabCtx sCtx;
139963    VTable *pVTable;
139964    int rc;
139965    const char *const*azArg = (const char *const*)pTab->azModuleArg;
139966    int nArg = pTab->nModuleArg;
139967    char *zErr = 0;
139968    char *zModuleName;
139969    int iDb;
139970    VtabCtx *pCtx;
139971  
139972    /* Check that the virtual-table is not already being initialized */
139973    for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
139974      if( pCtx->pTab==pTab ){
139975        *pzErr = sqlite3MPrintf(db, 
139976            "vtable constructor called recursively: %s", pTab->zName
139977        );
139978        return SQLITE_LOCKED;
139979      }
139980    }
139981  
139982    zModuleName = sqlite3DbStrDup(db, pTab->zName);
139983    if( !zModuleName ){
139984      return SQLITE_NOMEM_BKPT;
139985    }
139986  
139987    pVTable = sqlite3MallocZero(sizeof(VTable));
139988    if( !pVTable ){
139989      sqlite3OomFault(db);
139990      sqlite3DbFree(db, zModuleName);
139991      return SQLITE_NOMEM_BKPT;
139992    }
139993    pVTable->db = db;
139994    pVTable->pMod = pMod;
139995  
139996    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
139997    pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
139998  
139999    /* Invoke the virtual table constructor */
140000    assert( &db->pVtabCtx );
140001    assert( xConstruct );
140002    sCtx.pTab = pTab;
140003    sCtx.pVTable = pVTable;
140004    sCtx.pPrior = db->pVtabCtx;
140005    sCtx.bDeclared = 0;
140006    db->pVtabCtx = &sCtx;
140007    rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
140008    db->pVtabCtx = sCtx.pPrior;
140009    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
140010    assert( sCtx.pTab==pTab );
140011  
140012    if( SQLITE_OK!=rc ){
140013      if( zErr==0 ){
140014        *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
140015      }else {
140016        *pzErr = sqlite3MPrintf(db, "%s", zErr);
140017        sqlite3_free(zErr);
140018      }
140019      sqlite3DbFree(db, pVTable);
140020    }else if( ALWAYS(pVTable->pVtab) ){
140021      /* Justification of ALWAYS():  A correct vtab constructor must allocate
140022      ** the sqlite3_vtab object if successful.  */
140023      memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
140024      pVTable->pVtab->pModule = pMod->pModule;
140025      pVTable->nRef = 1;
140026      if( sCtx.bDeclared==0 ){
140027        const char *zFormat = "vtable constructor did not declare schema: %s";
140028        *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
140029        sqlite3VtabUnlock(pVTable);
140030        rc = SQLITE_ERROR;
140031      }else{
140032        int iCol;
140033        u8 oooHidden = 0;
140034        /* If everything went according to plan, link the new VTable structure
140035        ** into the linked list headed by pTab->pVTable. Then loop through the 
140036        ** columns of the table to see if any of them contain the token "hidden".
140037        ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
140038        ** the type string.  */
140039        pVTable->pNext = pTab->pVTable;
140040        pTab->pVTable = pVTable;
140041  
140042        for(iCol=0; iCol<pTab->nCol; iCol++){
140043          char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
140044          int nType;
140045          int i = 0;
140046          nType = sqlite3Strlen30(zType);
140047          for(i=0; i<nType; i++){
140048            if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
140049             && (i==0 || zType[i-1]==' ')
140050             && (zType[i+6]=='\0' || zType[i+6]==' ')
140051            ){
140052              break;
140053            }
140054          }
140055          if( i<nType ){
140056            int j;
140057            int nDel = 6 + (zType[i+6] ? 1 : 0);
140058            for(j=i; (j+nDel)<=nType; j++){
140059              zType[j] = zType[j+nDel];
140060            }
140061            if( zType[i]=='\0' && i>0 ){
140062              assert(zType[i-1]==' ');
140063              zType[i-1] = '\0';
140064            }
140065            pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
140066            oooHidden = TF_OOOHidden;
140067          }else{
140068            pTab->tabFlags |= oooHidden;
140069          }
140070        }
140071      }
140072    }
140073  
140074    sqlite3DbFree(db, zModuleName);
140075    return rc;
140076  }
140077  
140078  /*
140079  ** This function is invoked by the parser to call the xConnect() method
140080  ** of the virtual table pTab. If an error occurs, an error code is returned 
140081  ** and an error left in pParse.
140082  **
140083  ** This call is a no-op if table pTab is not a virtual table.
140084  */
140085  SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
140086    sqlite3 *db = pParse->db;
140087    const char *zMod;
140088    Module *pMod;
140089    int rc;
140090  
140091    assert( pTab );
140092    if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
140093      return SQLITE_OK;
140094    }
140095  
140096    /* Locate the required virtual table module */
140097    zMod = pTab->azModuleArg[0];
140098    pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
140099  
140100    if( !pMod ){
140101      const char *zModule = pTab->azModuleArg[0];
140102      sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
140103      rc = SQLITE_ERROR;
140104    }else{
140105      char *zErr = 0;
140106      rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
140107      if( rc!=SQLITE_OK ){
140108        sqlite3ErrorMsg(pParse, "%s", zErr);
140109        pParse->rc = rc;
140110      }
140111      sqlite3DbFree(db, zErr);
140112    }
140113  
140114    return rc;
140115  }
140116  /*
140117  ** Grow the db->aVTrans[] array so that there is room for at least one
140118  ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
140119  */
140120  static int growVTrans(sqlite3 *db){
140121    const int ARRAY_INCR = 5;
140122  
140123    /* Grow the sqlite3.aVTrans array if required */
140124    if( (db->nVTrans%ARRAY_INCR)==0 ){
140125      VTable **aVTrans;
140126      int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
140127      aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
140128      if( !aVTrans ){
140129        return SQLITE_NOMEM_BKPT;
140130      }
140131      memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
140132      db->aVTrans = aVTrans;
140133    }
140134  
140135    return SQLITE_OK;
140136  }
140137  
140138  /*
140139  ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
140140  ** have already been reserved using growVTrans().
140141  */
140142  static void addToVTrans(sqlite3 *db, VTable *pVTab){
140143    /* Add pVtab to the end of sqlite3.aVTrans */
140144    db->aVTrans[db->nVTrans++] = pVTab;
140145    sqlite3VtabLock(pVTab);
140146  }
140147  
140148  /*
140149  ** This function is invoked by the vdbe to call the xCreate method
140150  ** of the virtual table named zTab in database iDb. 
140151  **
140152  ** If an error occurs, *pzErr is set to point to an English language
140153  ** description of the error and an SQLITE_XXX error code is returned.
140154  ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
140155  */
140156  SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
140157    int rc = SQLITE_OK;
140158    Table *pTab;
140159    Module *pMod;
140160    const char *zMod;
140161  
140162    pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
140163    assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
140164  
140165    /* Locate the required virtual table module */
140166    zMod = pTab->azModuleArg[0];
140167    pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
140168  
140169    /* If the module has been registered and includes a Create method, 
140170    ** invoke it now. If the module has not been registered, return an 
140171    ** error. Otherwise, do nothing.
140172    */
140173    if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
140174      *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
140175      rc = SQLITE_ERROR;
140176    }else{
140177      rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
140178    }
140179  
140180    /* Justification of ALWAYS():  The xConstructor method is required to
140181    ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
140182    if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
140183      rc = growVTrans(db);
140184      if( rc==SQLITE_OK ){
140185        addToVTrans(db, sqlite3GetVTable(db, pTab));
140186      }
140187    }
140188  
140189    return rc;
140190  }
140191  
140192  /*
140193  ** This function is used to set the schema of a virtual table.  It is only
140194  ** valid to call this function from within the xCreate() or xConnect() of a
140195  ** virtual table module.
140196  */
140197  SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
140198    VtabCtx *pCtx;
140199    int rc = SQLITE_OK;
140200    Table *pTab;
140201    char *zErr = 0;
140202    Parse sParse;
140203  
140204  #ifdef SQLITE_ENABLE_API_ARMOR
140205    if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
140206      return SQLITE_MISUSE_BKPT;
140207    }
140208  #endif
140209    sqlite3_mutex_enter(db->mutex);
140210    pCtx = db->pVtabCtx;
140211    if( !pCtx || pCtx->bDeclared ){
140212      sqlite3Error(db, SQLITE_MISUSE);
140213      sqlite3_mutex_leave(db->mutex);
140214      return SQLITE_MISUSE_BKPT;
140215    }
140216    pTab = pCtx->pTab;
140217    assert( IsVirtual(pTab) );
140218  
140219    memset(&sParse, 0, sizeof(sParse));
140220    sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
140221    sParse.db = db;
140222    sParse.nQueryLoop = 1;
140223    if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr) 
140224     && sParse.pNewTable
140225     && !db->mallocFailed
140226     && !sParse.pNewTable->pSelect
140227     && !IsVirtual(sParse.pNewTable)
140228    ){
140229      if( !pTab->aCol ){
140230        Table *pNew = sParse.pNewTable;
140231        Index *pIdx;
140232        pTab->aCol = pNew->aCol;
140233        pTab->nCol = pNew->nCol;
140234        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
140235        pNew->nCol = 0;
140236        pNew->aCol = 0;
140237        assert( pTab->pIndex==0 );
140238        assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
140239        if( !HasRowid(pNew)
140240         && pCtx->pVTable->pMod->pModule->xUpdate!=0
140241         && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
140242        ){
140243          /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
140244          ** or else must have a single-column PRIMARY KEY */
140245          rc = SQLITE_ERROR;
140246        }
140247        pIdx = pNew->pIndex;
140248        if( pIdx ){
140249          assert( pIdx->pNext==0 );
140250          pTab->pIndex = pIdx;
140251          pNew->pIndex = 0;
140252          pIdx->pTable = pTab;
140253        }
140254      }
140255      pCtx->bDeclared = 1;
140256    }else{
140257      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
140258      sqlite3DbFree(db, zErr);
140259      rc = SQLITE_ERROR;
140260    }
140261    sParse.eParseMode = PARSE_MODE_NORMAL;
140262  
140263    if( sParse.pVdbe ){
140264      sqlite3VdbeFinalize(sParse.pVdbe);
140265    }
140266    sqlite3DeleteTable(db, sParse.pNewTable);
140267    sqlite3ParserReset(&sParse);
140268  
140269    assert( (rc&0xff)==rc );
140270    rc = sqlite3ApiExit(db, rc);
140271    sqlite3_mutex_leave(db->mutex);
140272    return rc;
140273  }
140274  
140275  /*
140276  ** This function is invoked by the vdbe to call the xDestroy method
140277  ** of the virtual table named zTab in database iDb. This occurs
140278  ** when a DROP TABLE is mentioned.
140279  **
140280  ** This call is a no-op if zTab is not a virtual table.
140281  */
140282  SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
140283    int rc = SQLITE_OK;
140284    Table *pTab;
140285  
140286    pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
140287    if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
140288      VTable *p;
140289      int (*xDestroy)(sqlite3_vtab *);
140290      for(p=pTab->pVTable; p; p=p->pNext){
140291        assert( p->pVtab );
140292        if( p->pVtab->nRef>0 ){
140293          return SQLITE_LOCKED;
140294        }
140295      }
140296      p = vtabDisconnectAll(db, pTab);
140297      xDestroy = p->pMod->pModule->xDestroy;
140298      assert( xDestroy!=0 );  /* Checked before the virtual table is created */
140299      rc = xDestroy(p->pVtab);
140300      /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
140301      if( rc==SQLITE_OK ){
140302        assert( pTab->pVTable==p && p->pNext==0 );
140303        p->pVtab = 0;
140304        pTab->pVTable = 0;
140305        sqlite3VtabUnlock(p);
140306      }
140307    }
140308  
140309    return rc;
140310  }
140311  
140312  /*
140313  ** This function invokes either the xRollback or xCommit method
140314  ** of each of the virtual tables in the sqlite3.aVTrans array. The method
140315  ** called is identified by the second argument, "offset", which is
140316  ** the offset of the method to call in the sqlite3_module structure.
140317  **
140318  ** The array is cleared after invoking the callbacks. 
140319  */
140320  static void callFinaliser(sqlite3 *db, int offset){
140321    int i;
140322    if( db->aVTrans ){
140323      VTable **aVTrans = db->aVTrans;
140324      db->aVTrans = 0;
140325      for(i=0; i<db->nVTrans; i++){
140326        VTable *pVTab = aVTrans[i];
140327        sqlite3_vtab *p = pVTab->pVtab;
140328        if( p ){
140329          int (*x)(sqlite3_vtab *);
140330          x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
140331          if( x ) x(p);
140332        }
140333        pVTab->iSavepoint = 0;
140334        sqlite3VtabUnlock(pVTab);
140335      }
140336      sqlite3DbFree(db, aVTrans);
140337      db->nVTrans = 0;
140338    }
140339  }
140340  
140341  /*
140342  ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
140343  ** array. Return the error code for the first error that occurs, or
140344  ** SQLITE_OK if all xSync operations are successful.
140345  **
140346  ** If an error message is available, leave it in p->zErrMsg.
140347  */
140348  SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
140349    int i;
140350    int rc = SQLITE_OK;
140351    VTable **aVTrans = db->aVTrans;
140352  
140353    db->aVTrans = 0;
140354    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
140355      int (*x)(sqlite3_vtab *);
140356      sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
140357      if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
140358        rc = x(pVtab);
140359        sqlite3VtabImportErrmsg(p, pVtab);
140360      }
140361    }
140362    db->aVTrans = aVTrans;
140363    return rc;
140364  }
140365  
140366  /*
140367  ** Invoke the xRollback method of all virtual tables in the 
140368  ** sqlite3.aVTrans array. Then clear the array itself.
140369  */
140370  SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
140371    callFinaliser(db, offsetof(sqlite3_module,xRollback));
140372    return SQLITE_OK;
140373  }
140374  
140375  /*
140376  ** Invoke the xCommit method of all virtual tables in the 
140377  ** sqlite3.aVTrans array. Then clear the array itself.
140378  */
140379  SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
140380    callFinaliser(db, offsetof(sqlite3_module,xCommit));
140381    return SQLITE_OK;
140382  }
140383  
140384  /*
140385  ** If the virtual table pVtab supports the transaction interface
140386  ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
140387  ** not currently open, invoke the xBegin method now.
140388  **
140389  ** If the xBegin call is successful, place the sqlite3_vtab pointer
140390  ** in the sqlite3.aVTrans array.
140391  */
140392  SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
140393    int rc = SQLITE_OK;
140394    const sqlite3_module *pModule;
140395  
140396    /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
140397    ** than zero, then this function is being called from within a
140398    ** virtual module xSync() callback. It is illegal to write to 
140399    ** virtual module tables in this case, so return SQLITE_LOCKED.
140400    */
140401    if( sqlite3VtabInSync(db) ){
140402      return SQLITE_LOCKED;
140403    }
140404    if( !pVTab ){
140405      return SQLITE_OK;
140406    } 
140407    pModule = pVTab->pVtab->pModule;
140408  
140409    if( pModule->xBegin ){
140410      int i;
140411  
140412      /* If pVtab is already in the aVTrans array, return early */
140413      for(i=0; i<db->nVTrans; i++){
140414        if( db->aVTrans[i]==pVTab ){
140415          return SQLITE_OK;
140416        }
140417      }
140418  
140419      /* Invoke the xBegin method. If successful, add the vtab to the 
140420      ** sqlite3.aVTrans[] array. */
140421      rc = growVTrans(db);
140422      if( rc==SQLITE_OK ){
140423        rc = pModule->xBegin(pVTab->pVtab);
140424        if( rc==SQLITE_OK ){
140425          int iSvpt = db->nStatement + db->nSavepoint;
140426          addToVTrans(db, pVTab);
140427          if( iSvpt && pModule->xSavepoint ){
140428            pVTab->iSavepoint = iSvpt;
140429            rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
140430          }
140431        }
140432      }
140433    }
140434    return rc;
140435  }
140436  
140437  /*
140438  ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
140439  ** virtual tables that currently have an open transaction. Pass iSavepoint
140440  ** as the second argument to the virtual table method invoked.
140441  **
140442  ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
140443  ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
140444  ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
140445  ** an open transaction is invoked.
140446  **
140447  ** If any virtual table method returns an error code other than SQLITE_OK, 
140448  ** processing is abandoned and the error returned to the caller of this
140449  ** function immediately. If all calls to virtual table methods are successful,
140450  ** SQLITE_OK is returned.
140451  */
140452  SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
140453    int rc = SQLITE_OK;
140454  
140455    assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
140456    assert( iSavepoint>=-1 );
140457    if( db->aVTrans ){
140458      int i;
140459      for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
140460        VTable *pVTab = db->aVTrans[i];
140461        const sqlite3_module *pMod = pVTab->pMod->pModule;
140462        if( pVTab->pVtab && pMod->iVersion>=2 ){
140463          int (*xMethod)(sqlite3_vtab *, int);
140464          sqlite3VtabLock(pVTab);
140465          switch( op ){
140466            case SAVEPOINT_BEGIN:
140467              xMethod = pMod->xSavepoint;
140468              pVTab->iSavepoint = iSavepoint+1;
140469              break;
140470            case SAVEPOINT_ROLLBACK:
140471              xMethod = pMod->xRollbackTo;
140472              break;
140473            default:
140474              xMethod = pMod->xRelease;
140475              break;
140476          }
140477          if( xMethod && pVTab->iSavepoint>iSavepoint ){
140478            rc = xMethod(pVTab->pVtab, iSavepoint);
140479          }
140480          sqlite3VtabUnlock(pVTab);
140481        }
140482      }
140483    }
140484    return rc;
140485  }
140486  
140487  /*
140488  ** The first parameter (pDef) is a function implementation.  The
140489  ** second parameter (pExpr) is the first argument to this function.
140490  ** If pExpr is a column in a virtual table, then let the virtual
140491  ** table implementation have an opportunity to overload the function.
140492  **
140493  ** This routine is used to allow virtual table implementations to
140494  ** overload MATCH, LIKE, GLOB, and REGEXP operators.
140495  **
140496  ** Return either the pDef argument (indicating no change) or a 
140497  ** new FuncDef structure that is marked as ephemeral using the
140498  ** SQLITE_FUNC_EPHEM flag.
140499  */
140500  SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
140501    sqlite3 *db,    /* Database connection for reporting malloc problems */
140502    FuncDef *pDef,  /* Function to possibly overload */
140503    int nArg,       /* Number of arguments to the function */
140504    Expr *pExpr     /* First argument to the function */
140505  ){
140506    Table *pTab;
140507    sqlite3_vtab *pVtab;
140508    sqlite3_module *pMod;
140509    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
140510    void *pArg = 0;
140511    FuncDef *pNew;
140512    int rc = 0;
140513  
140514    /* Check to see the left operand is a column in a virtual table */
140515    if( NEVER(pExpr==0) ) return pDef;
140516    if( pExpr->op!=TK_COLUMN ) return pDef;
140517    pTab = pExpr->y.pTab;
140518    if( pTab==0 ) return pDef;
140519    if( !IsVirtual(pTab) ) return pDef;
140520    pVtab = sqlite3GetVTable(db, pTab)->pVtab;
140521    assert( pVtab!=0 );
140522    assert( pVtab->pModule!=0 );
140523    pMod = (sqlite3_module *)pVtab->pModule;
140524    if( pMod->xFindFunction==0 ) return pDef;
140525   
140526    /* Call the xFindFunction method on the virtual table implementation
140527    ** to see if the implementation wants to overload this function.
140528    **
140529    ** Though undocumented, we have historically always invoked xFindFunction
140530    ** with an all lower-case function name.  Continue in this tradition to
140531    ** avoid any chance of an incompatibility.
140532    */
140533  #ifdef SQLITE_DEBUG
140534    {
140535      int i;
140536      for(i=0; pDef->zName[i]; i++){
140537        unsigned char x = (unsigned char)pDef->zName[i];
140538        assert( x==sqlite3UpperToLower[x] );
140539      }
140540    }
140541  #endif
140542    rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
140543    if( rc==0 ){
140544      return pDef;
140545    }
140546  
140547    /* Create a new ephemeral function definition for the overloaded
140548    ** function */
140549    pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
140550                               + sqlite3Strlen30(pDef->zName) + 1);
140551    if( pNew==0 ){
140552      return pDef;
140553    }
140554    *pNew = *pDef;
140555    pNew->zName = (const char*)&pNew[1];
140556    memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
140557    pNew->xSFunc = xSFunc;
140558    pNew->pUserData = pArg;
140559    pNew->funcFlags |= SQLITE_FUNC_EPHEM;
140560    return pNew;
140561  }
140562  
140563  /*
140564  ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
140565  ** array so that an OP_VBegin will get generated for it.  Add pTab to the
140566  ** array if it is missing.  If pTab is already in the array, this routine
140567  ** is a no-op.
140568  */
140569  SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
140570    Parse *pToplevel = sqlite3ParseToplevel(pParse);
140571    int i, n;
140572    Table **apVtabLock;
140573  
140574    assert( IsVirtual(pTab) );
140575    for(i=0; i<pToplevel->nVtabLock; i++){
140576      if( pTab==pToplevel->apVtabLock[i] ) return;
140577    }
140578    n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
140579    apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
140580    if( apVtabLock ){
140581      pToplevel->apVtabLock = apVtabLock;
140582      pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
140583    }else{
140584      sqlite3OomFault(pToplevel->db);
140585    }
140586  }
140587  
140588  /*
140589  ** Check to see if virtual table module pMod can be have an eponymous
140590  ** virtual table instance.  If it can, create one if one does not already
140591  ** exist. Return non-zero if the eponymous virtual table instance exists
140592  ** when this routine returns, and return zero if it does not exist.
140593  **
140594  ** An eponymous virtual table instance is one that is named after its
140595  ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
140596  ** statement in order to come into existance.  Eponymous virtual table
140597  ** instances always exist.  They cannot be DROP-ed.
140598  **
140599  ** Any virtual table module for which xConnect and xCreate are the same
140600  ** method can have an eponymous virtual table instance.
140601  */
140602  SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
140603    const sqlite3_module *pModule = pMod->pModule;
140604    Table *pTab;
140605    char *zErr = 0;
140606    int rc;
140607    sqlite3 *db = pParse->db;
140608    if( pMod->pEpoTab ) return 1;
140609    if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
140610    pTab = sqlite3DbMallocZero(db, sizeof(Table));
140611    if( pTab==0 ) return 0;
140612    pTab->zName = sqlite3DbStrDup(db, pMod->zName);
140613    if( pTab->zName==0 ){
140614      sqlite3DbFree(db, pTab);
140615      return 0;
140616    }
140617    pMod->pEpoTab = pTab;
140618    pTab->nTabRef = 1;
140619    pTab->pSchema = db->aDb[0].pSchema;
140620    assert( pTab->nModuleArg==0 );
140621    pTab->iPKey = -1;
140622    addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
140623    addModuleArgument(db, pTab, 0);
140624    addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
140625    rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
140626    if( rc ){
140627      sqlite3ErrorMsg(pParse, "%s", zErr);
140628      sqlite3DbFree(db, zErr);
140629      sqlite3VtabEponymousTableClear(db, pMod);
140630      return 0;
140631    }
140632    return 1;
140633  }
140634  
140635  /*
140636  ** Erase the eponymous virtual table instance associated with
140637  ** virtual table module pMod, if it exists.
140638  */
140639  SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
140640    Table *pTab = pMod->pEpoTab;
140641    if( pTab!=0 ){
140642      /* Mark the table as Ephemeral prior to deleting it, so that the
140643      ** sqlite3DeleteTable() routine will know that it is not stored in 
140644      ** the schema. */
140645      pTab->tabFlags |= TF_Ephemeral;
140646      sqlite3DeleteTable(db, pTab);
140647      pMod->pEpoTab = 0;
140648    }
140649  }
140650  
140651  /*
140652  ** Return the ON CONFLICT resolution mode in effect for the virtual
140653  ** table update operation currently in progress.
140654  **
140655  ** The results of this routine are undefined unless it is called from
140656  ** within an xUpdate method.
140657  */
140658  SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
140659    static const unsigned char aMap[] = { 
140660      SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
140661    };
140662  #ifdef SQLITE_ENABLE_API_ARMOR
140663    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
140664  #endif
140665    assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
140666    assert( OE_Ignore==4 && OE_Replace==5 );
140667    assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
140668    return (int)aMap[db->vtabOnConflict-1];
140669  }
140670  
140671  /*
140672  ** Call from within the xCreate() or xConnect() methods to provide 
140673  ** the SQLite core with additional information about the behavior
140674  ** of the virtual table being implemented.
140675  */
140676  SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
140677    va_list ap;
140678    int rc = SQLITE_OK;
140679  
140680  #ifdef SQLITE_ENABLE_API_ARMOR
140681    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
140682  #endif
140683    sqlite3_mutex_enter(db->mutex);
140684    va_start(ap, op);
140685    switch( op ){
140686      case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
140687        VtabCtx *p = db->pVtabCtx;
140688        if( !p ){
140689          rc = SQLITE_MISUSE_BKPT;
140690        }else{
140691          assert( p->pTab==0 || IsVirtual(p->pTab) );
140692          p->pVTable->bConstraint = (u8)va_arg(ap, int);
140693        }
140694        break;
140695      }
140696      default:
140697        rc = SQLITE_MISUSE_BKPT;
140698        break;
140699    }
140700    va_end(ap);
140701  
140702    if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
140703    sqlite3_mutex_leave(db->mutex);
140704    return rc;
140705  }
140706  
140707  #endif /* SQLITE_OMIT_VIRTUALTABLE */
140708  
140709  /************** End of vtab.c ************************************************/
140710  /************** Begin file wherecode.c ***************************************/
140711  /*
140712  ** 2015-06-06
140713  **
140714  ** The author disclaims copyright to this source code.  In place of
140715  ** a legal notice, here is a blessing:
140716  **
140717  **    May you do good and not evil.
140718  **    May you find forgiveness for yourself and forgive others.
140719  **    May you share freely, never taking more than you give.
140720  **
140721  *************************************************************************
140722  ** This module contains C code that generates VDBE code used to process
140723  ** the WHERE clause of SQL statements.
140724  **
140725  ** This file was split off from where.c on 2015-06-06 in order to reduce the
140726  ** size of where.c and make it easier to edit.  This file contains the routines
140727  ** that actually generate the bulk of the WHERE loop code.  The original where.c
140728  ** file retains the code that does query planning and analysis.
140729  */
140730  /* #include "sqliteInt.h" */
140731  /************** Include whereInt.h in the middle of wherecode.c **************/
140732  /************** Begin file whereInt.h ****************************************/
140733  /*
140734  ** 2013-11-12
140735  **
140736  ** The author disclaims copyright to this source code.  In place of
140737  ** a legal notice, here is a blessing:
140738  **
140739  **    May you do good and not evil.
140740  **    May you find forgiveness for yourself and forgive others.
140741  **    May you share freely, never taking more than you give.
140742  **
140743  *************************************************************************
140744  **
140745  ** This file contains structure and macro definitions for the query
140746  ** planner logic in "where.c".  These definitions are broken out into
140747  ** a separate source file for easier editing.
140748  */
140749  
140750  /*
140751  ** Trace output macros
140752  */
140753  #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
140754  /***/ extern int sqlite3WhereTrace;
140755  #endif
140756  #if defined(SQLITE_DEBUG) \
140757      && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
140758  # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
140759  # define WHERETRACE_ENABLED 1
140760  #else
140761  # define WHERETRACE(K,X)
140762  #endif
140763  
140764  /* Forward references
140765  */
140766  typedef struct WhereClause WhereClause;
140767  typedef struct WhereMaskSet WhereMaskSet;
140768  typedef struct WhereOrInfo WhereOrInfo;
140769  typedef struct WhereAndInfo WhereAndInfo;
140770  typedef struct WhereLevel WhereLevel;
140771  typedef struct WhereLoop WhereLoop;
140772  typedef struct WherePath WherePath;
140773  typedef struct WhereTerm WhereTerm;
140774  typedef struct WhereLoopBuilder WhereLoopBuilder;
140775  typedef struct WhereScan WhereScan;
140776  typedef struct WhereOrCost WhereOrCost;
140777  typedef struct WhereOrSet WhereOrSet;
140778  
140779  /*
140780  ** This object contains information needed to implement a single nested
140781  ** loop in WHERE clause.
140782  **
140783  ** Contrast this object with WhereLoop.  This object describes the
140784  ** implementation of the loop.  WhereLoop describes the algorithm.
140785  ** This object contains a pointer to the WhereLoop algorithm as one of
140786  ** its elements.
140787  **
140788  ** The WhereInfo object contains a single instance of this object for
140789  ** each term in the FROM clause (which is to say, for each of the
140790  ** nested loops as implemented).  The order of WhereLevel objects determines
140791  ** the loop nested order, with WhereInfo.a[0] being the outer loop and
140792  ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
140793  */
140794  struct WhereLevel {
140795    int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
140796    int iTabCur;          /* The VDBE cursor used to access the table */
140797    int iIdxCur;          /* The VDBE cursor used to access pIdx */
140798    int addrBrk;          /* Jump here to break out of the loop */
140799    int addrNxt;          /* Jump here to start the next IN combination */
140800    int addrSkip;         /* Jump here for next iteration of skip-scan */
140801    int addrCont;         /* Jump here to continue with the next loop cycle */
140802    int addrFirst;        /* First instruction of interior of the loop */
140803    int addrBody;         /* Beginning of the body of this loop */
140804  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
140805    u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
140806    int addrLikeRep;      /* LIKE range processing address */
140807  #endif
140808    u8 iFrom;             /* Which entry in the FROM clause */
140809    u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
140810    int p1, p2;           /* Operands of the opcode used to ends the loop */
140811    union {               /* Information that depends on pWLoop->wsFlags */
140812      struct {
140813        int nIn;              /* Number of entries in aInLoop[] */
140814        struct InLoop {
140815          int iCur;              /* The VDBE cursor used by this IN operator */
140816          int addrInTop;         /* Top of the IN loop */
140817          int iBase;             /* Base register of multi-key index record */
140818          int nPrefix;           /* Number of prior entires in the key */
140819          u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
140820        } *aInLoop;           /* Information about each nested IN operator */
140821      } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
140822      Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
140823    } u;
140824    struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
140825    Bitmask notReady;          /* FROM entries not usable at this level */
140826  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
140827    int addrVisit;        /* Address at which row is visited */
140828  #endif
140829  };
140830  
140831  /*
140832  ** Each instance of this object represents an algorithm for evaluating one
140833  ** term of a join.  Every term of the FROM clause will have at least
140834  ** one corresponding WhereLoop object (unless INDEXED BY constraints
140835  ** prevent a query solution - which is an error) and many terms of the
140836  ** FROM clause will have multiple WhereLoop objects, each describing a
140837  ** potential way of implementing that FROM-clause term, together with
140838  ** dependencies and cost estimates for using the chosen algorithm.
140839  **
140840  ** Query planning consists of building up a collection of these WhereLoop
140841  ** objects, then computing a particular sequence of WhereLoop objects, with
140842  ** one WhereLoop object per FROM clause term, that satisfy all dependencies
140843  ** and that minimize the overall cost.
140844  */
140845  struct WhereLoop {
140846    Bitmask prereq;       /* Bitmask of other loops that must run first */
140847    Bitmask maskSelf;     /* Bitmask identifying table iTab */
140848  #ifdef SQLITE_DEBUG
140849    char cId;             /* Symbolic ID of this loop for debugging use */
140850  #endif
140851    u8 iTab;              /* Position in FROM clause of table for this loop */
140852    u8 iSortIdx;          /* Sorting index number.  0==None */
140853    LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
140854    LogEst rRun;          /* Cost of running each loop */
140855    LogEst nOut;          /* Estimated number of output rows */
140856    union {
140857      struct {               /* Information for internal btree tables */
140858        u16 nEq;               /* Number of equality constraints */
140859        u16 nBtm;              /* Size of BTM vector */
140860        u16 nTop;              /* Size of TOP vector */
140861        u16 nIdxCol;           /* Index column used for ORDER BY */
140862        Index *pIndex;         /* Index used, or NULL */
140863      } btree;
140864      struct {               /* Information for virtual tables */
140865        int idxNum;            /* Index number */
140866        u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
140867        i8 isOrdered;          /* True if satisfies ORDER BY */
140868        u16 omitMask;          /* Terms that may be omitted */
140869        char *idxStr;          /* Index identifier string */
140870      } vtab;
140871    } u;
140872    u32 wsFlags;          /* WHERE_* flags describing the plan */
140873    u16 nLTerm;           /* Number of entries in aLTerm[] */
140874    u16 nSkip;            /* Number of NULL aLTerm[] entries */
140875    /**** whereLoopXfer() copies fields above ***********************/
140876  # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
140877    u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
140878    WhereTerm **aLTerm;   /* WhereTerms used */
140879    WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
140880    WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
140881  };
140882  
140883  /* This object holds the prerequisites and the cost of running a
140884  ** subquery on one operand of an OR operator in the WHERE clause.
140885  ** See WhereOrSet for additional information 
140886  */
140887  struct WhereOrCost {
140888    Bitmask prereq;     /* Prerequisites */
140889    LogEst rRun;        /* Cost of running this subquery */
140890    LogEst nOut;        /* Number of outputs for this subquery */
140891  };
140892  
140893  /* The WhereOrSet object holds a set of possible WhereOrCosts that
140894  ** correspond to the subquery(s) of OR-clause processing.  Only the
140895  ** best N_OR_COST elements are retained.
140896  */
140897  #define N_OR_COST 3
140898  struct WhereOrSet {
140899    u16 n;                      /* Number of valid a[] entries */
140900    WhereOrCost a[N_OR_COST];   /* Set of best costs */
140901  };
140902  
140903  /*
140904  ** Each instance of this object holds a sequence of WhereLoop objects
140905  ** that implement some or all of a query plan.
140906  **
140907  ** Think of each WhereLoop object as a node in a graph with arcs
140908  ** showing dependencies and costs for travelling between nodes.  (That is
140909  ** not a completely accurate description because WhereLoop costs are a
140910  ** vector, not a scalar, and because dependencies are many-to-one, not
140911  ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
140912  ** Then a WherePath object is a path through the graph that visits some
140913  ** or all of the WhereLoop objects once.
140914  **
140915  ** The "solver" works by creating the N best WherePath objects of length
140916  ** 1.  Then using those as a basis to compute the N best WherePath objects
140917  ** of length 2.  And so forth until the length of WherePaths equals the
140918  ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
140919  ** at the end is the chosen query plan.
140920  */
140921  struct WherePath {
140922    Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
140923    Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
140924    LogEst nRow;          /* Estimated number of rows generated by this path */
140925    LogEst rCost;         /* Total cost of this path */
140926    LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
140927    i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
140928    WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
140929  };
140930  
140931  /*
140932  ** The query generator uses an array of instances of this structure to
140933  ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
140934  ** clause subexpression is separated from the others by AND operators,
140935  ** usually, or sometimes subexpressions separated by OR.
140936  **
140937  ** All WhereTerms are collected into a single WhereClause structure.  
140938  ** The following identity holds:
140939  **
140940  **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
140941  **
140942  ** When a term is of the form:
140943  **
140944  **              X <op> <expr>
140945  **
140946  ** where X is a column name and <op> is one of certain operators,
140947  ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
140948  ** cursor number and column number for X.  WhereTerm.eOperator records
140949  ** the <op> using a bitmask encoding defined by WO_xxx below.  The
140950  ** use of a bitmask encoding for the operator allows us to search
140951  ** quickly for terms that match any of several different operators.
140952  **
140953  ** A WhereTerm might also be two or more subterms connected by OR:
140954  **
140955  **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
140956  **
140957  ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
140958  ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
140959  ** is collected about the OR clause.
140960  **
140961  ** If a term in the WHERE clause does not match either of the two previous
140962  ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
140963  ** to the original subexpression content and wtFlags is set up appropriately
140964  ** but no other fields in the WhereTerm object are meaningful.
140965  **
140966  ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
140967  ** but they do so indirectly.  A single WhereMaskSet structure translates
140968  ** cursor number into bits and the translated bit is stored in the prereq
140969  ** fields.  The translation is used in order to maximize the number of
140970  ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
140971  ** spread out over the non-negative integers.  For example, the cursor
140972  ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
140973  ** translates these sparse cursor numbers into consecutive integers
140974  ** beginning with 0 in order to make the best possible use of the available
140975  ** bits in the Bitmask.  So, in the example above, the cursor numbers
140976  ** would be mapped into integers 0 through 7.
140977  **
140978  ** The number of terms in a join is limited by the number of bits
140979  ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
140980  ** is only able to process joins with 64 or fewer tables.
140981  */
140982  struct WhereTerm {
140983    Expr *pExpr;            /* Pointer to the subexpression that is this term */
140984    WhereClause *pWC;       /* The clause this term is part of */
140985    LogEst truthProb;       /* Probability of truth for this expression */
140986    u16 wtFlags;            /* TERM_xxx bit flags.  See below */
140987    u16 eOperator;          /* A WO_xx value describing <op> */
140988    u8 nChild;              /* Number of children that must disable us */
140989    u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
140990    int iParent;            /* Disable pWC->a[iParent] when this term disabled */
140991    int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
140992    int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
140993    union {
140994      int leftColumn;         /* Column number of X in "X <op> <expr>" */
140995      WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
140996      WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
140997    } u;
140998    Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
140999    Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
141000  };
141001  
141002  /*
141003  ** Allowed values of WhereTerm.wtFlags
141004  */
141005  #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
141006  #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
141007  #define TERM_CODED      0x04   /* This term is already coded */
141008  #define TERM_COPIED     0x08   /* Has a child */
141009  #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
141010  #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
141011  #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
141012  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
141013  #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
141014  #else
141015  #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
141016  #endif
141017  #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
141018  #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
141019  #define TERM_LIKE       0x400  /* The original LIKE operator */
141020  #define TERM_IS         0x800  /* Term.pExpr is an IS operator */
141021  #define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
141022  
141023  /*
141024  ** An instance of the WhereScan object is used as an iterator for locating
141025  ** terms in the WHERE clause that are useful to the query planner.
141026  */
141027  struct WhereScan {
141028    WhereClause *pOrigWC;      /* Original, innermost WhereClause */
141029    WhereClause *pWC;          /* WhereClause currently being scanned */
141030    const char *zCollName;     /* Required collating sequence, if not NULL */
141031    Expr *pIdxExpr;            /* Search for this index expression */
141032    char idxaff;               /* Must match this affinity, if zCollName!=NULL */
141033    unsigned char nEquiv;      /* Number of entries in aEquiv[] */
141034    unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
141035    u32 opMask;                /* Acceptable operators */
141036    int k;                     /* Resume scanning at this->pWC->a[this->k] */
141037    int aiCur[11];             /* Cursors in the equivalence class */
141038    i16 aiColumn[11];          /* Corresponding column number in the eq-class */
141039  };
141040  
141041  /*
141042  ** An instance of the following structure holds all information about a
141043  ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
141044  **
141045  ** Explanation of pOuter:  For a WHERE clause of the form
141046  **
141047  **           a AND ((b AND c) OR (d AND e)) AND f
141048  **
141049  ** There are separate WhereClause objects for the whole clause and for
141050  ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
141051  ** subclauses points to the WhereClause object for the whole clause.
141052  */
141053  struct WhereClause {
141054    WhereInfo *pWInfo;       /* WHERE clause processing context */
141055    WhereClause *pOuter;     /* Outer conjunction */
141056    u8 op;                   /* Split operator.  TK_AND or TK_OR */
141057    u8 hasOr;                /* True if any a[].eOperator is WO_OR */
141058    int nTerm;               /* Number of terms */
141059    int nSlot;               /* Number of entries in a[] */
141060    WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
141061  #if defined(SQLITE_SMALL_STACK)
141062    WhereTerm aStatic[1];    /* Initial static space for a[] */
141063  #else
141064    WhereTerm aStatic[8];    /* Initial static space for a[] */
141065  #endif
141066  };
141067  
141068  /*
141069  ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
141070  ** a dynamically allocated instance of the following structure.
141071  */
141072  struct WhereOrInfo {
141073    WhereClause wc;          /* Decomposition into subterms */
141074    Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
141075  };
141076  
141077  /*
141078  ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
141079  ** a dynamically allocated instance of the following structure.
141080  */
141081  struct WhereAndInfo {
141082    WhereClause wc;          /* The subexpression broken out */
141083  };
141084  
141085  /*
141086  ** An instance of the following structure keeps track of a mapping
141087  ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
141088  **
141089  ** The VDBE cursor numbers are small integers contained in 
141090  ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
141091  ** clause, the cursor numbers might not begin with 0 and they might
141092  ** contain gaps in the numbering sequence.  But we want to make maximum
141093  ** use of the bits in our bitmasks.  This structure provides a mapping
141094  ** from the sparse cursor numbers into consecutive integers beginning
141095  ** with 0.
141096  **
141097  ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
141098  ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
141099  **
141100  ** For example, if the WHERE clause expression used these VDBE
141101  ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
141102  ** would map those cursor numbers into bits 0 through 5.
141103  **
141104  ** Note that the mapping is not necessarily ordered.  In the example
141105  ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
141106  ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
141107  ** does not really matter.  What is important is that sparse cursor
141108  ** numbers all get mapped into bit numbers that begin with 0 and contain
141109  ** no gaps.
141110  */
141111  struct WhereMaskSet {
141112    int bVarSelect;               /* Used by sqlite3WhereExprUsage() */
141113    int n;                        /* Number of assigned cursor values */
141114    int ix[BMS];                  /* Cursor assigned to each bit */
141115  };
141116  
141117  /*
141118  ** Initialize a WhereMaskSet object
141119  */
141120  #define initMaskSet(P)  (P)->n=0
141121  
141122  /*
141123  ** This object is a convenience wrapper holding all information needed
141124  ** to construct WhereLoop objects for a particular query.
141125  */
141126  struct WhereLoopBuilder {
141127    WhereInfo *pWInfo;        /* Information about this WHERE */
141128    WhereClause *pWC;         /* WHERE clause terms */
141129    ExprList *pOrderBy;       /* ORDER BY clause */
141130    WhereLoop *pNew;          /* Template WhereLoop */
141131    WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
141132  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
141133    UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
141134    int nRecValid;            /* Number of valid fields currently in pRec */
141135  #endif
141136    unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
141137    unsigned int iPlanLimit;  /* Search limiter */
141138  };
141139  
141140  /* Allowed values for WhereLoopBuider.bldFlags */
141141  #define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
141142  #define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
141143  
141144  /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
141145  ** index+constraint combinations the query planner will consider for a
141146  ** particular query.  If this parameter is unlimited, then certain
141147  ** pathological queries can spend excess time in the sqlite3WhereBegin()
141148  ** routine.  The limit is high enough that is should not impact real-world
141149  ** queries.
141150  **
141151  ** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit.  The limit is
141152  ** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
141153  ** clause is processed, so that every table in a join is guaranteed to be
141154  ** able to propose a some index+constraint combinations even if the initial
141155  ** baseline limit was exhausted by prior tables of the join.
141156  */
141157  #ifndef SQLITE_QUERY_PLANNER_LIMIT
141158  # define SQLITE_QUERY_PLANNER_LIMIT 20000
141159  #endif
141160  #ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
141161  # define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
141162  #endif
141163  
141164  /*
141165  ** The WHERE clause processing routine has two halves.  The
141166  ** first part does the start of the WHERE loop and the second
141167  ** half does the tail of the WHERE loop.  An instance of
141168  ** this structure is returned by the first half and passed
141169  ** into the second half to give some continuity.
141170  **
141171  ** An instance of this object holds the complete state of the query
141172  ** planner.
141173  */
141174  struct WhereInfo {
141175    Parse *pParse;            /* Parsing and code generating context */
141176    SrcList *pTabList;        /* List of tables in the join */
141177    ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
141178    ExprList *pResultSet;     /* Result set of the query */
141179    Expr *pWhere;             /* The complete WHERE clause */
141180    LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
141181    int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
141182    int iContinue;            /* Jump here to continue with next record */
141183    int iBreak;               /* Jump here to break out of the loop */
141184    int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
141185    u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
141186    u8 nLevel;                /* Number of nested loop */
141187    i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
141188    u8 sorted;                /* True if really sorted (not just grouped) */
141189    u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
141190    u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
141191    u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
141192    u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
141193    int iTop;                 /* The very beginning of the WHERE loop */
141194    WhereLoop *pLoops;        /* List of all WhereLoop objects */
141195    Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
141196    LogEst nRowOut;           /* Estimated number of output rows */
141197    WhereClause sWC;          /* Decomposition of the WHERE clause */
141198    WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
141199    WhereLevel a[1];          /* Information about each nest loop in WHERE */
141200  };
141201  
141202  /*
141203  ** Private interfaces - callable only by other where.c routines.
141204  **
141205  ** where.c:
141206  */
141207  SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
141208  #ifdef WHERETRACE_ENABLED
141209  SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
141210  #endif
141211  SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
141212    WhereClause *pWC,     /* The WHERE clause to be searched */
141213    int iCur,             /* Cursor number of LHS */
141214    int iColumn,          /* Column number of LHS */
141215    Bitmask notReady,     /* RHS must not overlap with this mask */
141216    u32 op,               /* Mask of WO_xx values describing operator */
141217    Index *pIdx           /* Must be compatible with this index, if not NULL */
141218  );
141219  
141220  /* wherecode.c: */
141221  #ifndef SQLITE_OMIT_EXPLAIN
141222  SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
141223    Parse *pParse,                  /* Parse context */
141224    SrcList *pTabList,              /* Table list this loop refers to */
141225    WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
141226    u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
141227  );
141228  #else
141229  # define sqlite3WhereExplainOneScan(u,v,w,x) 0
141230  #endif /* SQLITE_OMIT_EXPLAIN */
141231  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
141232  SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
141233    Vdbe *v,                        /* Vdbe to add scanstatus entry to */
141234    SrcList *pSrclist,              /* FROM clause pLvl reads data from */
141235    WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
141236    int addrExplain                 /* Address of OP_Explain (or 0) */
141237  );
141238  #else
141239  # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
141240  #endif
141241  SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
141242    Parse *pParse,       /* Parsing context */
141243    Vdbe *v,             /* Prepared statement under construction */
141244    WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
141245    int iLevel,          /* Which level of pWInfo->a[] should be coded */
141246    WhereLevel *pLevel,  /* The current level pointer */
141247    Bitmask notReady     /* Which tables are currently available */
141248  );
141249  
141250  /* whereexpr.c: */
141251  SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
141252  SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
141253  SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
141254  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
141255  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
141256  SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
141257  SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
141258  SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
141259  
141260  
141261  
141262  
141263  
141264  /*
141265  ** Bitmasks for the operators on WhereTerm objects.  These are all
141266  ** operators that are of interest to the query planner.  An
141267  ** OR-ed combination of these values can be used when searching for
141268  ** particular WhereTerms within a WhereClause.
141269  **
141270  ** Value constraints:
141271  **     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
141272  **     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
141273  **     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
141274  **     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
141275  **     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
141276  */
141277  #define WO_IN     0x0001
141278  #define WO_EQ     0x0002
141279  #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
141280  #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
141281  #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
141282  #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
141283  #define WO_AUX    0x0040       /* Op useful to virtual tables only */
141284  #define WO_IS     0x0080
141285  #define WO_ISNULL 0x0100
141286  #define WO_OR     0x0200       /* Two or more OR-connected terms */
141287  #define WO_AND    0x0400       /* Two or more AND-connected terms */
141288  #define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
141289  #define WO_NOOP   0x1000       /* This term does not restrict search space */
141290  
141291  #define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
141292  #define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
141293  
141294  /*
141295  ** These are definitions of bits in the WhereLoop.wsFlags field.
141296  ** The particular combination of bits in each WhereLoop help to
141297  ** determine the algorithm that WhereLoop represents.
141298  */
141299  #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
141300  #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
141301  #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
141302  #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
141303  #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
141304  #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
141305  #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
141306  #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
141307  #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
141308  #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
141309  #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
141310  #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
141311  #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
141312  #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
141313  #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
141314  #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
141315  #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
141316  #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
141317  #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
141318  #define WHERE_IN_EARLYOUT  0x00040000  /* Perhaps quit IN loops early */
141319  
141320  /************** End of whereInt.h ********************************************/
141321  /************** Continuing where we left off in wherecode.c ******************/
141322  
141323  #ifndef SQLITE_OMIT_EXPLAIN
141324  
141325  /*
141326  ** Return the name of the i-th column of the pIdx index.
141327  */
141328  static const char *explainIndexColumnName(Index *pIdx, int i){
141329    i = pIdx->aiColumn[i];
141330    if( i==XN_EXPR ) return "<expr>";
141331    if( i==XN_ROWID ) return "rowid";
141332    return pIdx->pTable->aCol[i].zName;
141333  }
141334  
141335  /*
141336  ** This routine is a helper for explainIndexRange() below
141337  **
141338  ** pStr holds the text of an expression that we are building up one term
141339  ** at a time.  This routine adds a new term to the end of the expression.
141340  ** Terms are separated by AND so add the "AND" text for second and subsequent
141341  ** terms only.
141342  */
141343  static void explainAppendTerm(
141344    StrAccum *pStr,             /* The text expression being built */
141345    Index *pIdx,                /* Index to read column names from */
141346    int nTerm,                  /* Number of terms */
141347    int iTerm,                  /* Zero-based index of first term. */
141348    int bAnd,                   /* Non-zero to append " AND " */
141349    const char *zOp             /* Name of the operator */
141350  ){
141351    int i;
141352  
141353    assert( nTerm>=1 );
141354    if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
141355  
141356    if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
141357    for(i=0; i<nTerm; i++){
141358      if( i ) sqlite3_str_append(pStr, ",", 1);
141359      sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
141360    }
141361    if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
141362  
141363    sqlite3_str_append(pStr, zOp, 1);
141364  
141365    if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
141366    for(i=0; i<nTerm; i++){
141367      if( i ) sqlite3_str_append(pStr, ",", 1);
141368      sqlite3_str_append(pStr, "?", 1);
141369    }
141370    if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
141371  }
141372  
141373  /*
141374  ** Argument pLevel describes a strategy for scanning table pTab. This 
141375  ** function appends text to pStr that describes the subset of table
141376  ** rows scanned by the strategy in the form of an SQL expression.
141377  **
141378  ** For example, if the query:
141379  **
141380  **   SELECT * FROM t1 WHERE a=1 AND b>2;
141381  **
141382  ** is run and there is an index on (a, b), then this function returns a
141383  ** string similar to:
141384  **
141385  **   "a=? AND b>?"
141386  */
141387  static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
141388    Index *pIndex = pLoop->u.btree.pIndex;
141389    u16 nEq = pLoop->u.btree.nEq;
141390    u16 nSkip = pLoop->nSkip;
141391    int i, j;
141392  
141393    if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
141394    sqlite3_str_append(pStr, " (", 2);
141395    for(i=0; i<nEq; i++){
141396      const char *z = explainIndexColumnName(pIndex, i);
141397      if( i ) sqlite3_str_append(pStr, " AND ", 5);
141398      sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
141399    }
141400  
141401    j = i;
141402    if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
141403      explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
141404      i = 1;
141405    }
141406    if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
141407      explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
141408    }
141409    sqlite3_str_append(pStr, ")", 1);
141410  }
141411  
141412  /*
141413  ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
141414  ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
141415  ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
141416  ** is added to the output to describe the table scan strategy in pLevel.
141417  **
141418  ** If an OP_Explain opcode is added to the VM, its address is returned.
141419  ** Otherwise, if no OP_Explain is coded, zero is returned.
141420  */
141421  SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
141422    Parse *pParse,                  /* Parse context */
141423    SrcList *pTabList,              /* Table list this loop refers to */
141424    WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
141425    u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
141426  ){
141427    int ret = 0;
141428  #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
141429    if( sqlite3ParseToplevel(pParse)->explain==2 )
141430  #endif
141431    {
141432      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
141433      Vdbe *v = pParse->pVdbe;      /* VM being constructed */
141434      sqlite3 *db = pParse->db;     /* Database handle */
141435      int isSearch;                 /* True for a SEARCH. False for SCAN. */
141436      WhereLoop *pLoop;             /* The controlling WhereLoop object */
141437      u32 flags;                    /* Flags that describe this loop */
141438      char *zMsg;                   /* Text to add to EQP output */
141439      StrAccum str;                 /* EQP output string */
141440      char zBuf[100];               /* Initial space for EQP output string */
141441  
141442      pLoop = pLevel->pWLoop;
141443      flags = pLoop->wsFlags;
141444      if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
141445  
141446      isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
141447              || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
141448              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
141449  
141450      sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
141451      sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
141452      if( pItem->pSelect ){
141453        sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
141454      }else{
141455        sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
141456      }
141457  
141458      if( pItem->zAlias ){
141459        sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
141460      }
141461      if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
141462        const char *zFmt = 0;
141463        Index *pIdx;
141464  
141465        assert( pLoop->u.btree.pIndex!=0 );
141466        pIdx = pLoop->u.btree.pIndex;
141467        assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
141468        if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
141469          if( isSearch ){
141470            zFmt = "PRIMARY KEY";
141471          }
141472        }else if( flags & WHERE_PARTIALIDX ){
141473          zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
141474        }else if( flags & WHERE_AUTO_INDEX ){
141475          zFmt = "AUTOMATIC COVERING INDEX";
141476        }else if( flags & WHERE_IDX_ONLY ){
141477          zFmt = "COVERING INDEX %s";
141478        }else{
141479          zFmt = "INDEX %s";
141480        }
141481        if( zFmt ){
141482          sqlite3_str_append(&str, " USING ", 7);
141483          sqlite3_str_appendf(&str, zFmt, pIdx->zName);
141484          explainIndexRange(&str, pLoop);
141485        }
141486      }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
141487        const char *zRangeOp;
141488        if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
141489          zRangeOp = "=";
141490        }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
141491          zRangeOp = ">? AND rowid<";
141492        }else if( flags&WHERE_BTM_LIMIT ){
141493          zRangeOp = ">";
141494        }else{
141495          assert( flags&WHERE_TOP_LIMIT);
141496          zRangeOp = "<";
141497        }
141498        sqlite3_str_appendf(&str, 
141499            " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
141500      }
141501  #ifndef SQLITE_OMIT_VIRTUALTABLE
141502      else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
141503        sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
141504                    pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
141505      }
141506  #endif
141507  #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
141508      if( pLoop->nOut>=10 ){
141509        sqlite3_str_appendf(&str, " (~%llu rows)",
141510               sqlite3LogEstToInt(pLoop->nOut));
141511      }else{
141512        sqlite3_str_append(&str, " (~1 row)", 9);
141513      }
141514  #endif
141515      zMsg = sqlite3StrAccumFinish(&str);
141516      sqlite3ExplainBreakpoint("",zMsg);
141517      ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
141518                              pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
141519    }
141520    return ret;
141521  }
141522  #endif /* SQLITE_OMIT_EXPLAIN */
141523  
141524  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
141525  /*
141526  ** Configure the VM passed as the first argument with an
141527  ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 
141528  ** implement level pLvl. Argument pSrclist is a pointer to the FROM 
141529  ** clause that the scan reads data from.
141530  **
141531  ** If argument addrExplain is not 0, it must be the address of an 
141532  ** OP_Explain instruction that describes the same loop.
141533  */
141534  SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
141535    Vdbe *v,                        /* Vdbe to add scanstatus entry to */
141536    SrcList *pSrclist,              /* FROM clause pLvl reads data from */
141537    WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
141538    int addrExplain                 /* Address of OP_Explain (or 0) */
141539  ){
141540    const char *zObj = 0;
141541    WhereLoop *pLoop = pLvl->pWLoop;
141542    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
141543      zObj = pLoop->u.btree.pIndex->zName;
141544    }else{
141545      zObj = pSrclist->a[pLvl->iFrom].zName;
141546    }
141547    sqlite3VdbeScanStatus(
141548        v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
141549    );
141550  }
141551  #endif
141552  
141553  
141554  /*
141555  ** Disable a term in the WHERE clause.  Except, do not disable the term
141556  ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
141557  ** or USING clause of that join.
141558  **
141559  ** Consider the term t2.z='ok' in the following queries:
141560  **
141561  **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
141562  **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
141563  **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
141564  **
141565  ** The t2.z='ok' is disabled in the in (2) because it originates
141566  ** in the ON clause.  The term is disabled in (3) because it is not part
141567  ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
141568  **
141569  ** Disabling a term causes that term to not be tested in the inner loop
141570  ** of the join.  Disabling is an optimization.  When terms are satisfied
141571  ** by indices, we disable them to prevent redundant tests in the inner
141572  ** loop.  We would get the correct results if nothing were ever disabled,
141573  ** but joins might run a little slower.  The trick is to disable as much
141574  ** as we can without disabling too much.  If we disabled in (1), we'd get
141575  ** the wrong answer.  See ticket #813.
141576  **
141577  ** If all the children of a term are disabled, then that term is also
141578  ** automatically disabled.  In this way, terms get disabled if derived
141579  ** virtual terms are tested first.  For example:
141580  **
141581  **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
141582  **      \___________/     \______/     \_____/
141583  **         parent          child1       child2
141584  **
141585  ** Only the parent term was in the original WHERE clause.  The child1
141586  ** and child2 terms were added by the LIKE optimization.  If both of
141587  ** the virtual child terms are valid, then testing of the parent can be 
141588  ** skipped.
141589  **
141590  ** Usually the parent term is marked as TERM_CODED.  But if the parent
141591  ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
141592  ** The TERM_LIKECOND marking indicates that the term should be coded inside
141593  ** a conditional such that is only evaluated on the second pass of a
141594  ** LIKE-optimization loop, when scanning BLOBs instead of strings.
141595  */
141596  static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
141597    int nLoop = 0;
141598    assert( pTerm!=0 );
141599    while( (pTerm->wtFlags & TERM_CODED)==0
141600        && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
141601        && (pLevel->notReady & pTerm->prereqAll)==0
141602    ){
141603      if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
141604        pTerm->wtFlags |= TERM_LIKECOND;
141605      }else{
141606        pTerm->wtFlags |= TERM_CODED;
141607      }
141608      if( pTerm->iParent<0 ) break;
141609      pTerm = &pTerm->pWC->a[pTerm->iParent];
141610      assert( pTerm!=0 );
141611      pTerm->nChild--;
141612      if( pTerm->nChild!=0 ) break;
141613      nLoop++;
141614    }
141615  }
141616  
141617  /*
141618  ** Code an OP_Affinity opcode to apply the column affinity string zAff
141619  ** to the n registers starting at base. 
141620  **
141621  ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
141622  ** beginning and end of zAff are ignored.  If all entries in zAff are
141623  ** SQLITE_AFF_BLOB, then no code gets generated.
141624  **
141625  ** This routine makes its own copy of zAff so that the caller is free
141626  ** to modify zAff after this routine returns.
141627  */
141628  static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
141629    Vdbe *v = pParse->pVdbe;
141630    if( zAff==0 ){
141631      assert( pParse->db->mallocFailed );
141632      return;
141633    }
141634    assert( v!=0 );
141635  
141636    /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
141637    ** and end of the affinity string.
141638    */
141639    while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
141640      n--;
141641      base++;
141642      zAff++;
141643    }
141644    while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
141645      n--;
141646    }
141647  
141648    /* Code the OP_Affinity opcode if there is anything left to do. */
141649    if( n>0 ){
141650      sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
141651    }
141652  }
141653  
141654  /*
141655  ** Expression pRight, which is the RHS of a comparison operation, is 
141656  ** either a vector of n elements or, if n==1, a scalar expression.
141657  ** Before the comparison operation, affinity zAff is to be applied
141658  ** to the pRight values. This function modifies characters within the
141659  ** affinity string to SQLITE_AFF_BLOB if either:
141660  **
141661  **   * the comparison will be performed with no affinity, or
141662  **   * the affinity change in zAff is guaranteed not to change the value.
141663  */
141664  static void updateRangeAffinityStr(
141665    Expr *pRight,                   /* RHS of comparison */
141666    int n,                          /* Number of vector elements in comparison */
141667    char *zAff                      /* Affinity string to modify */
141668  ){
141669    int i;
141670    for(i=0; i<n; i++){
141671      Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
141672      if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
141673       || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
141674      ){
141675        zAff[i] = SQLITE_AFF_BLOB;
141676      }
141677    }
141678  }
141679  
141680  
141681  /*
141682  ** pX is an expression of the form:  (vector) IN (SELECT ...)
141683  ** In other words, it is a vector IN operator with a SELECT clause on the
141684  ** LHS.  But not all terms in the vector are indexable and the terms might
141685  ** not be in the correct order for indexing.
141686  **
141687  ** This routine makes a copy of the input pX expression and then adjusts
141688  ** the vector on the LHS with corresponding changes to the SELECT so that
141689  ** the vector contains only index terms and those terms are in the correct
141690  ** order.  The modified IN expression is returned.  The caller is responsible
141691  ** for deleting the returned expression.
141692  **
141693  ** Example:
141694  **
141695  **    CREATE TABLE t1(a,b,c,d,e,f);
141696  **    CREATE INDEX t1x1 ON t1(e,c);
141697  **    SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
141698  **                           \_______________________________________/
141699  **                                     The pX expression
141700  **
141701  ** Since only columns e and c can be used with the index, in that order,
141702  ** the modified IN expression that is returned will be:
141703  **
141704  **        (e,c) IN (SELECT z,x FROM t2)
141705  **
141706  ** The reduced pX is different from the original (obviously) and thus is
141707  ** only used for indexing, to improve performance.  The original unaltered
141708  ** IN expression must also be run on each output row for correctness.
141709  */
141710  static Expr *removeUnindexableInClauseTerms(
141711    Parse *pParse,        /* The parsing context */
141712    int iEq,              /* Look at loop terms starting here */
141713    WhereLoop *pLoop,     /* The current loop */
141714    Expr *pX              /* The IN expression to be reduced */
141715  ){
141716    sqlite3 *db = pParse->db;
141717    Expr *pNew = sqlite3ExprDup(db, pX, 0);
141718    if( db->mallocFailed==0 ){
141719      ExprList *pOrigRhs = pNew->x.pSelect->pEList;  /* Original unmodified RHS */
141720      ExprList *pOrigLhs = pNew->pLeft->x.pList;     /* Original unmodified LHS */
141721      ExprList *pRhs = 0;         /* New RHS after modifications */
141722      ExprList *pLhs = 0;         /* New LHS after mods */
141723      int i;                      /* Loop counter */
141724      Select *pSelect;            /* Pointer to the SELECT on the RHS */
141725  
141726      for(i=iEq; i<pLoop->nLTerm; i++){
141727        if( pLoop->aLTerm[i]->pExpr==pX ){
141728          int iField = pLoop->aLTerm[i]->iField - 1;
141729          if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
141730          pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
141731          pOrigRhs->a[iField].pExpr = 0;
141732          assert( pOrigLhs->a[iField].pExpr!=0 );
141733          pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
141734          pOrigLhs->a[iField].pExpr = 0;
141735        }
141736      }
141737      sqlite3ExprListDelete(db, pOrigRhs);
141738      sqlite3ExprListDelete(db, pOrigLhs);
141739      pNew->pLeft->x.pList = pLhs;
141740      pNew->x.pSelect->pEList = pRhs;
141741      if( pLhs && pLhs->nExpr==1 ){
141742        /* Take care here not to generate a TK_VECTOR containing only a
141743        ** single value. Since the parser never creates such a vector, some
141744        ** of the subroutines do not handle this case.  */
141745        Expr *p = pLhs->a[0].pExpr;
141746        pLhs->a[0].pExpr = 0;
141747        sqlite3ExprDelete(db, pNew->pLeft);
141748        pNew->pLeft = p;
141749      }
141750      pSelect = pNew->x.pSelect;
141751      if( pSelect->pOrderBy ){
141752        /* If the SELECT statement has an ORDER BY clause, zero the 
141753        ** iOrderByCol variables. These are set to non-zero when an 
141754        ** ORDER BY term exactly matches one of the terms of the 
141755        ** result-set. Since the result-set of the SELECT statement may
141756        ** have been modified or reordered, these variables are no longer 
141757        ** set correctly.  Since setting them is just an optimization, 
141758        ** it's easiest just to zero them here.  */
141759        ExprList *pOrderBy = pSelect->pOrderBy;
141760        for(i=0; i<pOrderBy->nExpr; i++){
141761          pOrderBy->a[i].u.x.iOrderByCol = 0;
141762        }
141763      }
141764  
141765  #if 0
141766      printf("For indexing, change the IN expr:\n");
141767      sqlite3TreeViewExpr(0, pX, 0);
141768      printf("Into:\n");
141769      sqlite3TreeViewExpr(0, pNew, 0);
141770  #endif
141771    }
141772    return pNew;
141773  }
141774  
141775  
141776  /*
141777  ** Generate code for a single equality term of the WHERE clause.  An equality
141778  ** term can be either X=expr or X IN (...).   pTerm is the term to be 
141779  ** coded.
141780  **
141781  ** The current value for the constraint is left in a register, the index
141782  ** of which is returned.  An attempt is made store the result in iTarget but
141783  ** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
141784  ** constraint is a TK_EQ or TK_IS, then the current value might be left in
141785  ** some other register and it is the caller's responsibility to compensate.
141786  **
141787  ** For a constraint of the form X=expr, the expression is evaluated in
141788  ** straight-line code.  For constraints of the form X IN (...)
141789  ** this routine sets up a loop that will iterate over all values of X.
141790  */
141791  static int codeEqualityTerm(
141792    Parse *pParse,      /* The parsing context */
141793    WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
141794    WhereLevel *pLevel, /* The level of the FROM clause we are working on */
141795    int iEq,            /* Index of the equality term within this level */
141796    int bRev,           /* True for reverse-order IN operations */
141797    int iTarget         /* Attempt to leave results in this register */
141798  ){
141799    Expr *pX = pTerm->pExpr;
141800    Vdbe *v = pParse->pVdbe;
141801    int iReg;                  /* Register holding results */
141802  
141803    assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
141804    assert( iTarget>0 );
141805    if( pX->op==TK_EQ || pX->op==TK_IS ){
141806      iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
141807    }else if( pX->op==TK_ISNULL ){
141808      iReg = iTarget;
141809      sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
141810  #ifndef SQLITE_OMIT_SUBQUERY
141811    }else{
141812      int eType = IN_INDEX_NOOP;
141813      int iTab;
141814      struct InLoop *pIn;
141815      WhereLoop *pLoop = pLevel->pWLoop;
141816      int i;
141817      int nEq = 0;
141818      int *aiMap = 0;
141819  
141820      if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
141821        && pLoop->u.btree.pIndex!=0
141822        && pLoop->u.btree.pIndex->aSortOrder[iEq]
141823      ){
141824        testcase( iEq==0 );
141825        testcase( bRev );
141826        bRev = !bRev;
141827      }
141828      assert( pX->op==TK_IN );
141829      iReg = iTarget;
141830  
141831      for(i=0; i<iEq; i++){
141832        if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
141833          disableTerm(pLevel, pTerm);
141834          return iTarget;
141835        }
141836      }
141837      for(i=iEq;i<pLoop->nLTerm; i++){
141838        assert( pLoop->aLTerm[i]!=0 );
141839        if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
141840      }
141841  
141842      iTab = 0;
141843      if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
141844        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
141845      }else{
141846        sqlite3 *db = pParse->db;
141847        pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
141848  
141849        if( !db->mallocFailed ){
141850          aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
141851          eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
141852          pTerm->pExpr->iTable = iTab;
141853        }
141854        sqlite3ExprDelete(db, pX);
141855        pX = pTerm->pExpr;
141856      }
141857  
141858      if( eType==IN_INDEX_INDEX_DESC ){
141859        testcase( bRev );
141860        bRev = !bRev;
141861      }
141862      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
141863      VdbeCoverageIf(v, bRev);
141864      VdbeCoverageIf(v, !bRev);
141865      assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
141866  
141867      pLoop->wsFlags |= WHERE_IN_ABLE;
141868      if( pLevel->u.in.nIn==0 ){
141869        pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
141870      }
141871  
141872      i = pLevel->u.in.nIn;
141873      pLevel->u.in.nIn += nEq;
141874      pLevel->u.in.aInLoop =
141875         sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
141876                                sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
141877      pIn = pLevel->u.in.aInLoop;
141878      if( pIn ){
141879        int iMap = 0;               /* Index in aiMap[] */
141880        pIn += i;
141881        for(i=iEq;i<pLoop->nLTerm; i++){
141882          if( pLoop->aLTerm[i]->pExpr==pX ){
141883            int iOut = iReg + i - iEq;
141884            if( eType==IN_INDEX_ROWID ){
141885              pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
141886            }else{
141887              int iCol = aiMap ? aiMap[iMap++] : 0;
141888              pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
141889            }
141890            sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
141891            if( i==iEq ){
141892              pIn->iCur = iTab;
141893              pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
141894              if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
141895                pIn->iBase = iReg - i;
141896                pIn->nPrefix = i;
141897                pLoop->wsFlags |= WHERE_IN_EARLYOUT;
141898              }else{
141899                pIn->nPrefix = 0;
141900              }
141901            }else{
141902              pIn->eEndLoopOp = OP_Noop;
141903            }
141904            pIn++;
141905          }
141906        }
141907      }else{
141908        pLevel->u.in.nIn = 0;
141909      }
141910      sqlite3DbFree(pParse->db, aiMap);
141911  #endif
141912    }
141913    disableTerm(pLevel, pTerm);
141914    return iReg;
141915  }
141916  
141917  /*
141918  ** Generate code that will evaluate all == and IN constraints for an
141919  ** index scan.
141920  **
141921  ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
141922  ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
141923  ** The index has as many as three equality constraints, but in this
141924  ** example, the third "c" value is an inequality.  So only two 
141925  ** constraints are coded.  This routine will generate code to evaluate
141926  ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
141927  ** in consecutive registers and the index of the first register is returned.
141928  **
141929  ** In the example above nEq==2.  But this subroutine works for any value
141930  ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
141931  ** The only thing it does is allocate the pLevel->iMem memory cell and
141932  ** compute the affinity string.
141933  **
141934  ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
141935  ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
141936  ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
141937  ** occurs after the nEq quality constraints.
141938  **
141939  ** This routine allocates a range of nEq+nExtraReg memory cells and returns
141940  ** the index of the first memory cell in that range. The code that
141941  ** calls this routine will use that memory range to store keys for
141942  ** start and termination conditions of the loop.
141943  ** key value of the loop.  If one or more IN operators appear, then
141944  ** this routine allocates an additional nEq memory cells for internal
141945  ** use.
141946  **
141947  ** Before returning, *pzAff is set to point to a buffer containing a
141948  ** copy of the column affinity string of the index allocated using
141949  ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
141950  ** with equality constraints that use BLOB or NONE affinity are set to
141951  ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
141952  **
141953  **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
141954  **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
141955  **
141956  ** In the example above, the index on t1(a) has TEXT affinity. But since
141957  ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
141958  ** no conversion should be attempted before using a t2.b value as part of
141959  ** a key to search the index. Hence the first byte in the returned affinity
141960  ** string in this example would be set to SQLITE_AFF_BLOB.
141961  */
141962  static int codeAllEqualityTerms(
141963    Parse *pParse,        /* Parsing context */
141964    WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
141965    int bRev,             /* Reverse the order of IN operators */
141966    int nExtraReg,        /* Number of extra registers to allocate */
141967    char **pzAff          /* OUT: Set to point to affinity string */
141968  ){
141969    u16 nEq;                      /* The number of == or IN constraints to code */
141970    u16 nSkip;                    /* Number of left-most columns to skip */
141971    Vdbe *v = pParse->pVdbe;      /* The vm under construction */
141972    Index *pIdx;                  /* The index being used for this loop */
141973    WhereTerm *pTerm;             /* A single constraint term */
141974    WhereLoop *pLoop;             /* The WhereLoop object */
141975    int j;                        /* Loop counter */
141976    int regBase;                  /* Base register */
141977    int nReg;                     /* Number of registers to allocate */
141978    char *zAff;                   /* Affinity string to return */
141979  
141980    /* This module is only called on query plans that use an index. */
141981    pLoop = pLevel->pWLoop;
141982    assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
141983    nEq = pLoop->u.btree.nEq;
141984    nSkip = pLoop->nSkip;
141985    pIdx = pLoop->u.btree.pIndex;
141986    assert( pIdx!=0 );
141987  
141988    /* Figure out how many memory cells we will need then allocate them.
141989    */
141990    regBase = pParse->nMem + 1;
141991    nReg = pLoop->u.btree.nEq + nExtraReg;
141992    pParse->nMem += nReg;
141993  
141994    zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
141995    assert( zAff!=0 || pParse->db->mallocFailed );
141996  
141997    if( nSkip ){
141998      int iIdxCur = pLevel->iIdxCur;
141999      sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
142000      VdbeCoverageIf(v, bRev==0);
142001      VdbeCoverageIf(v, bRev!=0);
142002      VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
142003      j = sqlite3VdbeAddOp0(v, OP_Goto);
142004      pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
142005                              iIdxCur, 0, regBase, nSkip);
142006      VdbeCoverageIf(v, bRev==0);
142007      VdbeCoverageIf(v, bRev!=0);
142008      sqlite3VdbeJumpHere(v, j);
142009      for(j=0; j<nSkip; j++){
142010        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
142011        testcase( pIdx->aiColumn[j]==XN_EXPR );
142012        VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
142013      }
142014    }    
142015  
142016    /* Evaluate the equality constraints
142017    */
142018    assert( zAff==0 || (int)strlen(zAff)>=nEq );
142019    for(j=nSkip; j<nEq; j++){
142020      int r1;
142021      pTerm = pLoop->aLTerm[j];
142022      assert( pTerm!=0 );
142023      /* The following testcase is true for indices with redundant columns. 
142024      ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
142025      testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
142026      testcase( pTerm->wtFlags & TERM_VIRTUAL );
142027      r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
142028      if( r1!=regBase+j ){
142029        if( nReg==1 ){
142030          sqlite3ReleaseTempReg(pParse, regBase);
142031          regBase = r1;
142032        }else{
142033          sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
142034        }
142035      }
142036      if( pTerm->eOperator & WO_IN ){
142037        if( pTerm->pExpr->flags & EP_xIsSelect ){
142038          /* No affinity ever needs to be (or should be) applied to a value
142039          ** from the RHS of an "? IN (SELECT ...)" expression. The 
142040          ** sqlite3FindInIndex() routine has already ensured that the 
142041          ** affinity of the comparison has been applied to the value.  */
142042          if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
142043        }
142044      }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
142045        Expr *pRight = pTerm->pExpr->pRight;
142046        if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
142047          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
142048          VdbeCoverage(v);
142049        }
142050        if( zAff ){
142051          if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
142052            zAff[j] = SQLITE_AFF_BLOB;
142053          }
142054          if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
142055            zAff[j] = SQLITE_AFF_BLOB;
142056          }
142057        }
142058      }
142059    }
142060    *pzAff = zAff;
142061    return regBase;
142062  }
142063  
142064  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
142065  /*
142066  ** If the most recently coded instruction is a constant range constraint
142067  ** (a string literal) that originated from the LIKE optimization, then 
142068  ** set P3 and P5 on the OP_String opcode so that the string will be cast
142069  ** to a BLOB at appropriate times.
142070  **
142071  ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
142072  ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
142073  ** scan loop run twice, once for strings and a second time for BLOBs.
142074  ** The OP_String opcodes on the second pass convert the upper and lower
142075  ** bound string constants to blobs.  This routine makes the necessary changes
142076  ** to the OP_String opcodes for that to happen.
142077  **
142078  ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
142079  ** only the one pass through the string space is required, so this routine
142080  ** becomes a no-op.
142081  */
142082  static void whereLikeOptimizationStringFixup(
142083    Vdbe *v,                /* prepared statement under construction */
142084    WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
142085    WhereTerm *pTerm        /* The upper or lower bound just coded */
142086  ){
142087    if( pTerm->wtFlags & TERM_LIKEOPT ){
142088      VdbeOp *pOp;
142089      assert( pLevel->iLikeRepCntr>0 );
142090      pOp = sqlite3VdbeGetOp(v, -1);
142091      assert( pOp!=0 );
142092      assert( pOp->opcode==OP_String8 
142093              || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
142094      pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
142095      pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
142096    }
142097  }
142098  #else
142099  # define whereLikeOptimizationStringFixup(A,B,C)
142100  #endif
142101  
142102  #ifdef SQLITE_ENABLE_CURSOR_HINTS
142103  /*
142104  ** Information is passed from codeCursorHint() down to individual nodes of
142105  ** the expression tree (by sqlite3WalkExpr()) using an instance of this
142106  ** structure.
142107  */
142108  struct CCurHint {
142109    int iTabCur;    /* Cursor for the main table */
142110    int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
142111    Index *pIdx;    /* The index used to access the table */
142112  };
142113  
142114  /*
142115  ** This function is called for every node of an expression that is a candidate
142116  ** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
142117  ** the table CCurHint.iTabCur, verify that the same column can be
142118  ** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
142119  */
142120  static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
142121    struct CCurHint *pHint = pWalker->u.pCCurHint;
142122    assert( pHint->pIdx!=0 );
142123    if( pExpr->op==TK_COLUMN
142124     && pExpr->iTable==pHint->iTabCur
142125     && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
142126    ){
142127      pWalker->eCode = 1;
142128    }
142129    return WRC_Continue;
142130  }
142131  
142132  /*
142133  ** Test whether or not expression pExpr, which was part of a WHERE clause,
142134  ** should be included in the cursor-hint for a table that is on the rhs
142135  ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 
142136  ** expression is not suitable.
142137  **
142138  ** An expression is unsuitable if it might evaluate to non NULL even if
142139  ** a TK_COLUMN node that does affect the value of the expression is set
142140  ** to NULL. For example:
142141  **
142142  **   col IS NULL
142143  **   col IS NOT NULL
142144  **   coalesce(col, 1)
142145  **   CASE WHEN col THEN 0 ELSE 1 END
142146  */
142147  static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
142148    if( pExpr->op==TK_IS 
142149     || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 
142150     || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 
142151    ){
142152      pWalker->eCode = 1;
142153    }else if( pExpr->op==TK_FUNCTION ){
142154      int d1;
142155      char d2[4];
142156      if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
142157        pWalker->eCode = 1;
142158      }
142159    }
142160  
142161    return WRC_Continue;
142162  }
142163  
142164  
142165  /*
142166  ** This function is called on every node of an expression tree used as an
142167  ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
142168  ** that accesses any table other than the one identified by
142169  ** CCurHint.iTabCur, then do the following:
142170  **
142171  **   1) allocate a register and code an OP_Column instruction to read 
142172  **      the specified column into the new register, and
142173  **
142174  **   2) transform the expression node to a TK_REGISTER node that reads 
142175  **      from the newly populated register.
142176  **
142177  ** Also, if the node is a TK_COLUMN that does access the table idenified
142178  ** by pCCurHint.iTabCur, and an index is being used (which we will
142179  ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
142180  ** an access of the index rather than the original table.
142181  */
142182  static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
142183    int rc = WRC_Continue;
142184    struct CCurHint *pHint = pWalker->u.pCCurHint;
142185    if( pExpr->op==TK_COLUMN ){
142186      if( pExpr->iTable!=pHint->iTabCur ){
142187        int reg = ++pWalker->pParse->nMem;   /* Register for column value */
142188        sqlite3ExprCode(pWalker->pParse, pExpr, reg);
142189        pExpr->op = TK_REGISTER;
142190        pExpr->iTable = reg;
142191      }else if( pHint->pIdx!=0 ){
142192        pExpr->iTable = pHint->iIdxCur;
142193        pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
142194        assert( pExpr->iColumn>=0 );
142195      }
142196    }else if( pExpr->op==TK_AGG_FUNCTION ){
142197      /* An aggregate function in the WHERE clause of a query means this must
142198      ** be a correlated sub-query, and expression pExpr is an aggregate from
142199      ** the parent context. Do not walk the function arguments in this case.
142200      **
142201      ** todo: It should be possible to replace this node with a TK_REGISTER
142202      ** expression, as the result of the expression must be stored in a 
142203      ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
142204      rc = WRC_Prune;
142205    }
142206    return rc;
142207  }
142208  
142209  /*
142210  ** Insert an OP_CursorHint instruction if it is appropriate to do so.
142211  */
142212  static void codeCursorHint(
142213    struct SrcList_item *pTabItem,  /* FROM clause item */
142214    WhereInfo *pWInfo,    /* The where clause */
142215    WhereLevel *pLevel,   /* Which loop to provide hints for */
142216    WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
142217  ){
142218    Parse *pParse = pWInfo->pParse;
142219    sqlite3 *db = pParse->db;
142220    Vdbe *v = pParse->pVdbe;
142221    Expr *pExpr = 0;
142222    WhereLoop *pLoop = pLevel->pWLoop;
142223    int iCur;
142224    WhereClause *pWC;
142225    WhereTerm *pTerm;
142226    int i, j;
142227    struct CCurHint sHint;
142228    Walker sWalker;
142229  
142230    if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
142231    iCur = pLevel->iTabCur;
142232    assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
142233    sHint.iTabCur = iCur;
142234    sHint.iIdxCur = pLevel->iIdxCur;
142235    sHint.pIdx = pLoop->u.btree.pIndex;
142236    memset(&sWalker, 0, sizeof(sWalker));
142237    sWalker.pParse = pParse;
142238    sWalker.u.pCCurHint = &sHint;
142239    pWC = &pWInfo->sWC;
142240    for(i=0; i<pWC->nTerm; i++){
142241      pTerm = &pWC->a[i];
142242      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
142243      if( pTerm->prereqAll & pLevel->notReady ) continue;
142244  
142245      /* Any terms specified as part of the ON(...) clause for any LEFT 
142246      ** JOIN for which the current table is not the rhs are omitted
142247      ** from the cursor-hint. 
142248      **
142249      ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 
142250      ** that were specified as part of the WHERE clause must be excluded.
142251      ** This is to address the following:
142252      **
142253      **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
142254      **
142255      ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
142256      ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 
142257      ** pushed down to the cursor, this row is filtered out, causing
142258      ** SQLite to synthesize a row of NULL values. Which does match the
142259      ** WHERE clause, and so the query returns a row. Which is incorrect.
142260      **
142261      ** For the same reason, WHERE terms such as:
142262      **
142263      **   WHERE 1 = (t2.c IS NULL)
142264      **
142265      ** are also excluded. See codeCursorHintIsOrFunction() for details.
142266      */
142267      if( pTabItem->fg.jointype & JT_LEFT ){
142268        Expr *pExpr = pTerm->pExpr;
142269        if( !ExprHasProperty(pExpr, EP_FromJoin) 
142270         || pExpr->iRightJoinTable!=pTabItem->iCursor
142271        ){
142272          sWalker.eCode = 0;
142273          sWalker.xExprCallback = codeCursorHintIsOrFunction;
142274          sqlite3WalkExpr(&sWalker, pTerm->pExpr);
142275          if( sWalker.eCode ) continue;
142276        }
142277      }else{
142278        if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
142279      }
142280  
142281      /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
142282      ** the cursor.  These terms are not needed as hints for a pure range
142283      ** scan (that has no == terms) so omit them. */
142284      if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
142285        for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
142286        if( j<pLoop->nLTerm ) continue;
142287      }
142288  
142289      /* No subqueries or non-deterministic functions allowed */
142290      if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
142291  
142292      /* For an index scan, make sure referenced columns are actually in
142293      ** the index. */
142294      if( sHint.pIdx!=0 ){
142295        sWalker.eCode = 0;
142296        sWalker.xExprCallback = codeCursorHintCheckExpr;
142297        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
142298        if( sWalker.eCode ) continue;
142299      }
142300  
142301      /* If we survive all prior tests, that means this term is worth hinting */
142302      pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
142303    }
142304    if( pExpr!=0 ){
142305      sWalker.xExprCallback = codeCursorHintFixExpr;
142306      sqlite3WalkExpr(&sWalker, pExpr);
142307      sqlite3VdbeAddOp4(v, OP_CursorHint, 
142308                        (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
142309                        (const char*)pExpr, P4_EXPR);
142310    }
142311  }
142312  #else
142313  # define codeCursorHint(A,B,C,D)  /* No-op */
142314  #endif /* SQLITE_ENABLE_CURSOR_HINTS */
142315  
142316  /*
142317  ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
142318  ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
142319  ** function generates code to do a deferred seek of cursor iCur to the 
142320  ** rowid stored in register iRowid.
142321  **
142322  ** Normally, this is just:
142323  **
142324  **   OP_DeferredSeek $iCur $iRowid
142325  **
142326  ** However, if the scan currently being coded is a branch of an OR-loop and
142327  ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
142328  ** is set to iIdxCur and P4 is set to point to an array of integers
142329  ** containing one entry for each column of the table cursor iCur is open 
142330  ** on. For each table column, if the column is the i'th column of the 
142331  ** index, then the corresponding array entry is set to (i+1). If the column
142332  ** does not appear in the index at all, the array entry is set to 0.
142333  */
142334  static void codeDeferredSeek(
142335    WhereInfo *pWInfo,              /* Where clause context */
142336    Index *pIdx,                    /* Index scan is using */
142337    int iCur,                       /* Cursor for IPK b-tree */
142338    int iIdxCur                     /* Index cursor */
142339  ){
142340    Parse *pParse = pWInfo->pParse; /* Parse context */
142341    Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
142342  
142343    assert( iIdxCur>0 );
142344    assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
142345    
142346    sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
142347    if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
142348     && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
142349    ){
142350      int i;
142351      Table *pTab = pIdx->pTable;
142352      int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
142353      if( ai ){
142354        ai[0] = pTab->nCol;
142355        for(i=0; i<pIdx->nColumn-1; i++){
142356          assert( pIdx->aiColumn[i]<pTab->nCol );
142357          if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
142358        }
142359        sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
142360      }
142361    }
142362  }
142363  
142364  /*
142365  ** If the expression passed as the second argument is a vector, generate
142366  ** code to write the first nReg elements of the vector into an array
142367  ** of registers starting with iReg.
142368  **
142369  ** If the expression is not a vector, then nReg must be passed 1. In
142370  ** this case, generate code to evaluate the expression and leave the
142371  ** result in register iReg.
142372  */
142373  static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
142374    assert( nReg>0 );
142375    if( p && sqlite3ExprIsVector(p) ){
142376  #ifndef SQLITE_OMIT_SUBQUERY
142377      if( (p->flags & EP_xIsSelect) ){
142378        Vdbe *v = pParse->pVdbe;
142379        int iSelect;
142380        assert( p->op==TK_SELECT );
142381        iSelect = sqlite3CodeSubselect(pParse, p);
142382        sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
142383      }else
142384  #endif
142385      {
142386        int i;
142387        ExprList *pList = p->x.pList;
142388        assert( nReg<=pList->nExpr );
142389        for(i=0; i<nReg; i++){
142390          sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
142391        }
142392      }
142393    }else{
142394      assert( nReg==1 );
142395      sqlite3ExprCode(pParse, p, iReg);
142396    }
142397  }
142398  
142399  /* An instance of the IdxExprTrans object carries information about a
142400  ** mapping from an expression on table columns into a column in an index
142401  ** down through the Walker.
142402  */
142403  typedef struct IdxExprTrans {
142404    Expr *pIdxExpr;    /* The index expression */
142405    int iTabCur;       /* The cursor of the corresponding table */
142406    int iIdxCur;       /* The cursor for the index */
142407    int iIdxCol;       /* The column for the index */
142408  } IdxExprTrans;
142409  
142410  /* The walker node callback used to transform matching expressions into
142411  ** a reference to an index column for an index on an expression.
142412  **
142413  ** If pExpr matches, then transform it into a reference to the index column
142414  ** that contains the value of pExpr.
142415  */
142416  static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
142417    IdxExprTrans *pX = p->u.pIdxTrans;
142418    if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
142419      pExpr->op = TK_COLUMN;
142420      pExpr->iTable = pX->iIdxCur;
142421      pExpr->iColumn = pX->iIdxCol;
142422      pExpr->y.pTab = 0;
142423      return WRC_Prune;
142424    }else{
142425      return WRC_Continue;
142426    }
142427  }
142428  
142429  /*
142430  ** For an indexes on expression X, locate every instance of expression X
142431  ** in pExpr and change that subexpression into a reference to the appropriate
142432  ** column of the index.
142433  */
142434  static void whereIndexExprTrans(
142435    Index *pIdx,      /* The Index */
142436    int iTabCur,      /* Cursor of the table that is being indexed */
142437    int iIdxCur,      /* Cursor of the index itself */
142438    WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
142439  ){
142440    int iIdxCol;               /* Column number of the index */
142441    ExprList *aColExpr;        /* Expressions that are indexed */
142442    Walker w;
142443    IdxExprTrans x;
142444    aColExpr = pIdx->aColExpr;
142445    if( aColExpr==0 ) return;  /* Not an index on expressions */
142446    memset(&w, 0, sizeof(w));
142447    w.xExprCallback = whereIndexExprTransNode;
142448    w.u.pIdxTrans = &x;
142449    x.iTabCur = iTabCur;
142450    x.iIdxCur = iIdxCur;
142451    for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
142452      if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
142453      assert( aColExpr->a[iIdxCol].pExpr!=0 );
142454      x.iIdxCol = iIdxCol;
142455      x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
142456      sqlite3WalkExpr(&w, pWInfo->pWhere);
142457      sqlite3WalkExprList(&w, pWInfo->pOrderBy);
142458      sqlite3WalkExprList(&w, pWInfo->pResultSet);
142459    }
142460  }
142461  
142462  /*
142463  ** Generate code for the start of the iLevel-th loop in the WHERE clause
142464  ** implementation described by pWInfo.
142465  */
142466  SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
142467    Parse *pParse,       /* Parsing context */
142468    Vdbe *v,             /* Prepared statement under construction */
142469    WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
142470    int iLevel,          /* Which level of pWInfo->a[] should be coded */
142471    WhereLevel *pLevel,  /* The current level pointer */
142472    Bitmask notReady     /* Which tables are currently available */
142473  ){
142474    int j, k;            /* Loop counters */
142475    int iCur;            /* The VDBE cursor for the table */
142476    int addrNxt;         /* Where to jump to continue with the next IN case */
142477    int bRev;            /* True if we need to scan in reverse order */
142478    WhereLoop *pLoop;    /* The WhereLoop object being coded */
142479    WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
142480    WhereTerm *pTerm;               /* A WHERE clause term */
142481    sqlite3 *db;                    /* Database connection */
142482    struct SrcList_item *pTabItem;  /* FROM clause term being coded */
142483    int addrBrk;                    /* Jump here to break out of the loop */
142484    int addrHalt;                   /* addrBrk for the outermost loop */
142485    int addrCont;                   /* Jump here to continue with next cycle */
142486    int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
142487    int iReleaseReg = 0;      /* Temp register to free before returning */
142488    Index *pIdx = 0;          /* Index used by loop (if any) */
142489    int iLoop;                /* Iteration of constraint generator loop */
142490  
142491    pWC = &pWInfo->sWC;
142492    db = pParse->db;
142493    pLoop = pLevel->pWLoop;
142494    pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
142495    iCur = pTabItem->iCursor;
142496    pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
142497    bRev = (pWInfo->revMask>>iLevel)&1;
142498    VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
142499  
142500    /* Create labels for the "break" and "continue" instructions
142501    ** for the current loop.  Jump to addrBrk to break out of a loop.
142502    ** Jump to cont to go immediately to the next iteration of the
142503    ** loop.
142504    **
142505    ** When there is an IN operator, we also have a "addrNxt" label that
142506    ** means to continue with the next IN value combination.  When
142507    ** there are no IN operators in the constraints, the "addrNxt" label
142508    ** is the same as "addrBrk".
142509    */
142510    addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
142511    addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
142512  
142513    /* If this is the right table of a LEFT OUTER JOIN, allocate and
142514    ** initialize a memory cell that records if this table matches any
142515    ** row of the left table of the join.
142516    */
142517    assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
142518         || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
142519    );
142520    if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
142521      pLevel->iLeftJoin = ++pParse->nMem;
142522      sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
142523      VdbeComment((v, "init LEFT JOIN no-match flag"));
142524    }
142525  
142526    /* Compute a safe address to jump to if we discover that the table for
142527    ** this loop is empty and can never contribute content. */
142528    for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
142529    addrHalt = pWInfo->a[j].addrBrk;
142530  
142531    /* Special case of a FROM clause subquery implemented as a co-routine */
142532    if( pTabItem->fg.viaCoroutine ){
142533      int regYield = pTabItem->regReturn;
142534      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
142535      pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
142536      VdbeCoverage(v);
142537      VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
142538      pLevel->op = OP_Goto;
142539    }else
142540  
142541  #ifndef SQLITE_OMIT_VIRTUALTABLE
142542    if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
142543      /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
142544      **          to access the data.
142545      */
142546      int iReg;   /* P3 Value for OP_VFilter */
142547      int addrNotFound;
142548      int nConstraint = pLoop->nLTerm;
142549      int iIn;    /* Counter for IN constraints */
142550  
142551      iReg = sqlite3GetTempRange(pParse, nConstraint+2);
142552      addrNotFound = pLevel->addrBrk;
142553      for(j=0; j<nConstraint; j++){
142554        int iTarget = iReg+j+2;
142555        pTerm = pLoop->aLTerm[j];
142556        if( NEVER(pTerm==0) ) continue;
142557        if( pTerm->eOperator & WO_IN ){
142558          codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
142559          addrNotFound = pLevel->addrNxt;
142560        }else{
142561          Expr *pRight = pTerm->pExpr->pRight;
142562          codeExprOrVector(pParse, pRight, iTarget, 1);
142563        }
142564      }
142565      sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
142566      sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
142567      sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
142568                        pLoop->u.vtab.idxStr,
142569                        pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
142570      VdbeCoverage(v);
142571      pLoop->u.vtab.needFree = 0;
142572      pLevel->p1 = iCur;
142573      pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
142574      pLevel->p2 = sqlite3VdbeCurrentAddr(v);
142575      iIn = pLevel->u.in.nIn;
142576      for(j=nConstraint-1; j>=0; j--){
142577        pTerm = pLoop->aLTerm[j];
142578        if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
142579          disableTerm(pLevel, pTerm);
142580        }else if( (pTerm->eOperator & WO_IN)!=0 ){
142581          Expr *pCompare;  /* The comparison operator */
142582          Expr *pRight;    /* RHS of the comparison */
142583          VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
142584  
142585          /* Reload the constraint value into reg[iReg+j+2].  The same value
142586          ** was loaded into the same register prior to the OP_VFilter, but
142587          ** the xFilter implementation might have changed the datatype or
142588          ** encoding of the value in the register, so it *must* be reloaded. */
142589          assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
142590          if( !db->mallocFailed ){
142591            assert( iIn>0 );
142592            pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
142593            assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
142594            assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
142595            assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
142596            testcase( pOp->opcode==OP_Rowid );
142597            sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
142598          }
142599  
142600          /* Generate code that will continue to the next row if 
142601          ** the IN constraint is not satisfied */
142602          pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
142603          assert( pCompare!=0 || db->mallocFailed );
142604          if( pCompare ){
142605            pCompare->pLeft = pTerm->pExpr->pLeft;
142606            pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
142607            if( pRight ){
142608              pRight->iTable = iReg+j+2;
142609              sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
142610            }
142611            pCompare->pLeft = 0;
142612            sqlite3ExprDelete(db, pCompare);
142613          }
142614        }
142615      }
142616      /* These registers need to be preserved in case there is an IN operator
142617      ** loop.  So we could deallocate the registers here (and potentially
142618      ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
142619      ** simpler and safer to simply not reuse the registers.
142620      **
142621      **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
142622      */
142623    }else
142624  #endif /* SQLITE_OMIT_VIRTUALTABLE */
142625  
142626    if( (pLoop->wsFlags & WHERE_IPK)!=0
142627     && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
142628    ){
142629      /* Case 2:  We can directly reference a single row using an
142630      **          equality comparison against the ROWID field.  Or
142631      **          we reference multiple rows using a "rowid IN (...)"
142632      **          construct.
142633      */
142634      assert( pLoop->u.btree.nEq==1 );
142635      pTerm = pLoop->aLTerm[0];
142636      assert( pTerm!=0 );
142637      assert( pTerm->pExpr!=0 );
142638      testcase( pTerm->wtFlags & TERM_VIRTUAL );
142639      iReleaseReg = ++pParse->nMem;
142640      iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
142641      if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
142642      addrNxt = pLevel->addrNxt;
142643      sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
142644      VdbeCoverage(v);
142645      pLevel->op = OP_Noop;
142646      if( (pTerm->prereqAll & pLevel->notReady)==0 ){
142647        pTerm->wtFlags |= TERM_CODED;
142648      }
142649    }else if( (pLoop->wsFlags & WHERE_IPK)!=0
142650           && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
142651    ){
142652      /* Case 3:  We have an inequality comparison against the ROWID field.
142653      */
142654      int testOp = OP_Noop;
142655      int start;
142656      int memEndValue = 0;
142657      WhereTerm *pStart, *pEnd;
142658  
142659      j = 0;
142660      pStart = pEnd = 0;
142661      if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
142662      if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
142663      assert( pStart!=0 || pEnd!=0 );
142664      if( bRev ){
142665        pTerm = pStart;
142666        pStart = pEnd;
142667        pEnd = pTerm;
142668      }
142669      codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
142670      if( pStart ){
142671        Expr *pX;             /* The expression that defines the start bound */
142672        int r1, rTemp;        /* Registers for holding the start boundary */
142673        int op;               /* Cursor seek operation */
142674  
142675        /* The following constant maps TK_xx codes into corresponding 
142676        ** seek opcodes.  It depends on a particular ordering of TK_xx
142677        */
142678        const u8 aMoveOp[] = {
142679             /* TK_GT */  OP_SeekGT,
142680             /* TK_LE */  OP_SeekLE,
142681             /* TK_LT */  OP_SeekLT,
142682             /* TK_GE */  OP_SeekGE
142683        };
142684        assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
142685        assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
142686        assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
142687  
142688        assert( (pStart->wtFlags & TERM_VNULL)==0 );
142689        testcase( pStart->wtFlags & TERM_VIRTUAL );
142690        pX = pStart->pExpr;
142691        assert( pX!=0 );
142692        testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
142693        if( sqlite3ExprIsVector(pX->pRight) ){
142694          r1 = rTemp = sqlite3GetTempReg(pParse);
142695          codeExprOrVector(pParse, pX->pRight, r1, 1);
142696          testcase( pX->op==TK_GT );
142697          testcase( pX->op==TK_GE );
142698          testcase( pX->op==TK_LT );
142699          testcase( pX->op==TK_LE );
142700          op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
142701          assert( pX->op!=TK_GT || op==OP_SeekGE );
142702          assert( pX->op!=TK_GE || op==OP_SeekGE );
142703          assert( pX->op!=TK_LT || op==OP_SeekLE );
142704          assert( pX->op!=TK_LE || op==OP_SeekLE );
142705        }else{
142706          r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
142707          disableTerm(pLevel, pStart);
142708          op = aMoveOp[(pX->op - TK_GT)];
142709        }
142710        sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
142711        VdbeComment((v, "pk"));
142712        VdbeCoverageIf(v, pX->op==TK_GT);
142713        VdbeCoverageIf(v, pX->op==TK_LE);
142714        VdbeCoverageIf(v, pX->op==TK_LT);
142715        VdbeCoverageIf(v, pX->op==TK_GE);
142716        sqlite3ReleaseTempReg(pParse, rTemp);
142717      }else{
142718        sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
142719        VdbeCoverageIf(v, bRev==0);
142720        VdbeCoverageIf(v, bRev!=0);
142721      }
142722      if( pEnd ){
142723        Expr *pX;
142724        pX = pEnd->pExpr;
142725        assert( pX!=0 );
142726        assert( (pEnd->wtFlags & TERM_VNULL)==0 );
142727        testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
142728        testcase( pEnd->wtFlags & TERM_VIRTUAL );
142729        memEndValue = ++pParse->nMem;
142730        codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
142731        if( 0==sqlite3ExprIsVector(pX->pRight) 
142732         && (pX->op==TK_LT || pX->op==TK_GT) 
142733        ){
142734          testOp = bRev ? OP_Le : OP_Ge;
142735        }else{
142736          testOp = bRev ? OP_Lt : OP_Gt;
142737        }
142738        if( 0==sqlite3ExprIsVector(pX->pRight) ){
142739          disableTerm(pLevel, pEnd);
142740        }
142741      }
142742      start = sqlite3VdbeCurrentAddr(v);
142743      pLevel->op = bRev ? OP_Prev : OP_Next;
142744      pLevel->p1 = iCur;
142745      pLevel->p2 = start;
142746      assert( pLevel->p5==0 );
142747      if( testOp!=OP_Noop ){
142748        iRowidReg = ++pParse->nMem;
142749        sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
142750        sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
142751        VdbeCoverageIf(v, testOp==OP_Le);
142752        VdbeCoverageIf(v, testOp==OP_Lt);
142753        VdbeCoverageIf(v, testOp==OP_Ge);
142754        VdbeCoverageIf(v, testOp==OP_Gt);
142755        sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
142756      }
142757    }else if( pLoop->wsFlags & WHERE_INDEXED ){
142758      /* Case 4: A scan using an index.
142759      **
142760      **         The WHERE clause may contain zero or more equality 
142761      **         terms ("==" or "IN" operators) that refer to the N
142762      **         left-most columns of the index. It may also contain
142763      **         inequality constraints (>, <, >= or <=) on the indexed
142764      **         column that immediately follows the N equalities. Only 
142765      **         the right-most column can be an inequality - the rest must
142766      **         use the "==" and "IN" operators. For example, if the 
142767      **         index is on (x,y,z), then the following clauses are all 
142768      **         optimized:
142769      **
142770      **            x=5
142771      **            x=5 AND y=10
142772      **            x=5 AND y<10
142773      **            x=5 AND y>5 AND y<10
142774      **            x=5 AND y=5 AND z<=10
142775      **
142776      **         The z<10 term of the following cannot be used, only
142777      **         the x=5 term:
142778      **
142779      **            x=5 AND z<10
142780      **
142781      **         N may be zero if there are inequality constraints.
142782      **         If there are no inequality constraints, then N is at
142783      **         least one.
142784      **
142785      **         This case is also used when there are no WHERE clause
142786      **         constraints but an index is selected anyway, in order
142787      **         to force the output order to conform to an ORDER BY.
142788      */  
142789      static const u8 aStartOp[] = {
142790        0,
142791        0,
142792        OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
142793        OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
142794        OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
142795        OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
142796        OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
142797        OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
142798      };
142799      static const u8 aEndOp[] = {
142800        OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
142801        OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
142802        OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
142803        OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
142804      };
142805      u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
142806      u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
142807      u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
142808      int regBase;                 /* Base register holding constraint values */
142809      WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
142810      WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
142811      int startEq;                 /* True if range start uses ==, >= or <= */
142812      int endEq;                   /* True if range end uses ==, >= or <= */
142813      int start_constraints;       /* Start of range is constrained */
142814      int nConstraint;             /* Number of constraint terms */
142815      int iIdxCur;                 /* The VDBE cursor for the index */
142816      int nExtraReg = 0;           /* Number of extra registers needed */
142817      int op;                      /* Instruction opcode */
142818      char *zStartAff;             /* Affinity for start of range constraint */
142819      char *zEndAff = 0;           /* Affinity for end of range constraint */
142820      u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
142821      u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
142822      int omitTable;               /* True if we use the index only */
142823  
142824  
142825      pIdx = pLoop->u.btree.pIndex;
142826      iIdxCur = pLevel->iIdxCur;
142827      assert( nEq>=pLoop->nSkip );
142828  
142829      /* If this loop satisfies a sort order (pOrderBy) request that 
142830      ** was passed to this function to implement a "SELECT min(x) ..." 
142831      ** query, then the caller will only allow the loop to run for
142832      ** a single iteration. This means that the first row returned
142833      ** should not have a NULL value stored in 'x'. If column 'x' is
142834      ** the first one after the nEq equality constraints in the index,
142835      ** this requires some special handling.
142836      */
142837      assert( pWInfo->pOrderBy==0
142838           || pWInfo->pOrderBy->nExpr==1
142839           || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
142840      if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
142841       && pWInfo->nOBSat>0
142842       && (pIdx->nKeyCol>nEq)
142843      ){
142844        assert( pLoop->nSkip==0 );
142845        bSeekPastNull = 1;
142846        nExtraReg = 1;
142847      }
142848  
142849      /* Find any inequality constraint terms for the start and end 
142850      ** of the range. 
142851      */
142852      j = nEq;
142853      if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
142854        pRangeStart = pLoop->aLTerm[j++];
142855        nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
142856        /* Like optimization range constraints always occur in pairs */
142857        assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 
142858                (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
142859      }
142860      if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
142861        pRangeEnd = pLoop->aLTerm[j++];
142862        nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
142863  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
142864        if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
142865          assert( pRangeStart!=0 );                     /* LIKE opt constraints */
142866          assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
142867          pLevel->iLikeRepCntr = (u32)++pParse->nMem;
142868          sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
142869          VdbeComment((v, "LIKE loop counter"));
142870          pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
142871          /* iLikeRepCntr actually stores 2x the counter register number.  The
142872          ** bottom bit indicates whether the search order is ASC or DESC. */
142873          testcase( bRev );
142874          testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
142875          assert( (bRev & ~1)==0 );
142876          pLevel->iLikeRepCntr <<=1;
142877          pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
142878        }
142879  #endif
142880        if( pRangeStart==0 ){
142881          j = pIdx->aiColumn[nEq];
142882          if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
142883            bSeekPastNull = 1;
142884          }
142885        }
142886      }
142887      assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
142888  
142889      /* If we are doing a reverse order scan on an ascending index, or
142890      ** a forward order scan on a descending index, interchange the 
142891      ** start and end terms (pRangeStart and pRangeEnd).
142892      */
142893      if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
142894       || (bRev && pIdx->nKeyCol==nEq)
142895      ){
142896        SWAP(WhereTerm *, pRangeEnd, pRangeStart);
142897        SWAP(u8, bSeekPastNull, bStopAtNull);
142898        SWAP(u8, nBtm, nTop);
142899      }
142900  
142901      /* Generate code to evaluate all constraint terms using == or IN
142902      ** and store the values of those terms in an array of registers
142903      ** starting at regBase.
142904      */
142905      codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
142906      regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
142907      assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
142908      if( zStartAff && nTop ){
142909        zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
142910      }
142911      addrNxt = pLevel->addrNxt;
142912  
142913      testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
142914      testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
142915      testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
142916      testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
142917      startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
142918      endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
142919      start_constraints = pRangeStart || nEq>0;
142920  
142921      /* Seek the index cursor to the start of the range. */
142922      nConstraint = nEq;
142923      if( pRangeStart ){
142924        Expr *pRight = pRangeStart->pExpr->pRight;
142925        codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
142926        whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
142927        if( (pRangeStart->wtFlags & TERM_VNULL)==0
142928         && sqlite3ExprCanBeNull(pRight)
142929        ){
142930          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
142931          VdbeCoverage(v);
142932        }
142933        if( zStartAff ){
142934          updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
142935        }  
142936        nConstraint += nBtm;
142937        testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
142938        if( sqlite3ExprIsVector(pRight)==0 ){
142939          disableTerm(pLevel, pRangeStart);
142940        }else{
142941          startEq = 1;
142942        }
142943        bSeekPastNull = 0;
142944      }else if( bSeekPastNull ){
142945        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
142946        nConstraint++;
142947        startEq = 0;
142948        start_constraints = 1;
142949      }
142950      codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
142951      if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
142952        /* The skip-scan logic inside the call to codeAllEqualityConstraints()
142953        ** above has already left the cursor sitting on the correct row,
142954        ** so no further seeking is needed */
142955      }else{
142956        if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
142957          sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
142958        }
142959        op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
142960        assert( op!=0 );
142961        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
142962        VdbeCoverage(v);
142963        VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
142964        VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
142965        VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
142966        VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
142967        VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
142968        VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
142969      }
142970  
142971      /* Load the value for the inequality constraint at the end of the
142972      ** range (if any).
142973      */
142974      nConstraint = nEq;
142975      if( pRangeEnd ){
142976        Expr *pRight = pRangeEnd->pExpr->pRight;
142977        codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
142978        whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
142979        if( (pRangeEnd->wtFlags & TERM_VNULL)==0
142980         && sqlite3ExprCanBeNull(pRight)
142981        ){
142982          sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
142983          VdbeCoverage(v);
142984        }
142985        if( zEndAff ){
142986          updateRangeAffinityStr(pRight, nTop, zEndAff);
142987          codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
142988        }else{
142989          assert( pParse->db->mallocFailed );
142990        }
142991        nConstraint += nTop;
142992        testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
142993  
142994        if( sqlite3ExprIsVector(pRight)==0 ){
142995          disableTerm(pLevel, pRangeEnd);
142996        }else{
142997          endEq = 1;
142998        }
142999      }else if( bStopAtNull ){
143000        sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
143001        endEq = 0;
143002        nConstraint++;
143003      }
143004      sqlite3DbFree(db, zStartAff);
143005      sqlite3DbFree(db, zEndAff);
143006  
143007      /* Top of the loop body */
143008      pLevel->p2 = sqlite3VdbeCurrentAddr(v);
143009  
143010      /* Check if the index cursor is past the end of the range. */
143011      if( nConstraint ){
143012        op = aEndOp[bRev*2 + endEq];
143013        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
143014        testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
143015        testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
143016        testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
143017        testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
143018      }
143019  
143020      if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
143021        sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
143022      }
143023  
143024      /* Seek the table cursor, if required */
143025      omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
143026             && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
143027      if( omitTable ){
143028        /* pIdx is a covering index.  No need to access the main table. */
143029      }else if( HasRowid(pIdx->pTable) ){
143030        if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
143031            (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) 
143032         && (pWInfo->eOnePass==ONEPASS_SINGLE)
143033        )){
143034          iRowidReg = ++pParse->nMem;
143035          sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
143036          sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
143037          VdbeCoverage(v);
143038        }else{
143039          codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
143040        }
143041      }else if( iCur!=iIdxCur ){
143042        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
143043        iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
143044        for(j=0; j<pPk->nKeyCol; j++){
143045          k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
143046          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
143047        }
143048        sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
143049                             iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
143050      }
143051  
143052      /* If pIdx is an index on one or more expressions, then look through
143053      ** all the expressions in pWInfo and try to transform matching expressions
143054      ** into reference to index columns.
143055      **
143056      ** Do not do this for the RHS of a LEFT JOIN. This is because the 
143057      ** expression may be evaluated after OP_NullRow has been executed on
143058      ** the cursor. In this case it is important to do the full evaluation,
143059      ** as the result of the expression may not be NULL, even if all table
143060      ** column values are.  https://www.sqlite.org/src/info/7fa8049685b50b5a
143061      **
143062      ** Also, do not do this when processing one index an a multi-index
143063      ** OR clause, since the transformation will become invalid once we
143064      ** move forward to the next index.
143065      ** https://sqlite.org/src/info/4e8e4857d32d401f
143066      */
143067      if( pLevel->iLeftJoin==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
143068        whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
143069      }
143070  
143071      /* Record the instruction used to terminate the loop. */
143072      if( pLoop->wsFlags & WHERE_ONEROW ){
143073        pLevel->op = OP_Noop;
143074      }else if( bRev ){
143075        pLevel->op = OP_Prev;
143076      }else{
143077        pLevel->op = OP_Next;
143078      }
143079      pLevel->p1 = iIdxCur;
143080      pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
143081      if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
143082        pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
143083      }else{
143084        assert( pLevel->p5==0 );
143085      }
143086      if( omitTable ) pIdx = 0;
143087    }else
143088  
143089  #ifndef SQLITE_OMIT_OR_OPTIMIZATION
143090    if( pLoop->wsFlags & WHERE_MULTI_OR ){
143091      /* Case 5:  Two or more separately indexed terms connected by OR
143092      **
143093      ** Example:
143094      **
143095      **   CREATE TABLE t1(a,b,c,d);
143096      **   CREATE INDEX i1 ON t1(a);
143097      **   CREATE INDEX i2 ON t1(b);
143098      **   CREATE INDEX i3 ON t1(c);
143099      **
143100      **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
143101      **
143102      ** In the example, there are three indexed terms connected by OR.
143103      ** The top of the loop looks like this:
143104      **
143105      **          Null       1                # Zero the rowset in reg 1
143106      **
143107      ** Then, for each indexed term, the following. The arguments to
143108      ** RowSetTest are such that the rowid of the current row is inserted
143109      ** into the RowSet. If it is already present, control skips the
143110      ** Gosub opcode and jumps straight to the code generated by WhereEnd().
143111      **
143112      **        sqlite3WhereBegin(<term>)
143113      **          RowSetTest                  # Insert rowid into rowset
143114      **          Gosub      2 A
143115      **        sqlite3WhereEnd()
143116      **
143117      ** Following the above, code to terminate the loop. Label A, the target
143118      ** of the Gosub above, jumps to the instruction right after the Goto.
143119      **
143120      **          Null       1                # Zero the rowset in reg 1
143121      **          Goto       B                # The loop is finished.
143122      **
143123      **       A: <loop body>                 # Return data, whatever.
143124      **
143125      **          Return     2                # Jump back to the Gosub
143126      **
143127      **       B: <after the loop>
143128      **
143129      ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
143130      ** use an ephemeral index instead of a RowSet to record the primary
143131      ** keys of the rows we have already seen.
143132      **
143133      */
143134      WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
143135      SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
143136      Index *pCov = 0;             /* Potential covering index (or NULL) */
143137      int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
143138  
143139      int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
143140      int regRowset = 0;                        /* Register for RowSet object */
143141      int regRowid = 0;                         /* Register holding rowid */
143142      int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
143143      int iRetInit;                             /* Address of regReturn init */
143144      int untestedTerms = 0;             /* Some terms not completely tested */
143145      int ii;                            /* Loop counter */
143146      u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
143147      Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
143148      Table *pTab = pTabItem->pTab;
143149  
143150      pTerm = pLoop->aLTerm[0];
143151      assert( pTerm!=0 );
143152      assert( pTerm->eOperator & WO_OR );
143153      assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
143154      pOrWc = &pTerm->u.pOrInfo->wc;
143155      pLevel->op = OP_Return;
143156      pLevel->p1 = regReturn;
143157  
143158      /* Set up a new SrcList in pOrTab containing the table being scanned
143159      ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
143160      ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
143161      */
143162      if( pWInfo->nLevel>1 ){
143163        int nNotReady;                 /* The number of notReady tables */
143164        struct SrcList_item *origSrc;     /* Original list of tables */
143165        nNotReady = pWInfo->nLevel - iLevel - 1;
143166        pOrTab = sqlite3StackAllocRaw(db,
143167                              sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
143168        if( pOrTab==0 ) return notReady;
143169        pOrTab->nAlloc = (u8)(nNotReady + 1);
143170        pOrTab->nSrc = pOrTab->nAlloc;
143171        memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
143172        origSrc = pWInfo->pTabList->a;
143173        for(k=1; k<=nNotReady; k++){
143174          memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
143175        }
143176      }else{
143177        pOrTab = pWInfo->pTabList;
143178      }
143179  
143180      /* Initialize the rowset register to contain NULL. An SQL NULL is 
143181      ** equivalent to an empty rowset.  Or, create an ephemeral index
143182      ** capable of holding primary keys in the case of a WITHOUT ROWID.
143183      **
143184      ** Also initialize regReturn to contain the address of the instruction 
143185      ** immediately following the OP_Return at the bottom of the loop. This
143186      ** is required in a few obscure LEFT JOIN cases where control jumps
143187      ** over the top of the loop into the body of it. In this case the 
143188      ** correct response for the end-of-loop code (the OP_Return) is to 
143189      ** fall through to the next instruction, just as an OP_Next does if
143190      ** called on an uninitialized cursor.
143191      */
143192      if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
143193        if( HasRowid(pTab) ){
143194          regRowset = ++pParse->nMem;
143195          sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
143196        }else{
143197          Index *pPk = sqlite3PrimaryKeyIndex(pTab);
143198          regRowset = pParse->nTab++;
143199          sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
143200          sqlite3VdbeSetP4KeyInfo(pParse, pPk);
143201        }
143202        regRowid = ++pParse->nMem;
143203      }
143204      iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
143205  
143206      /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
143207      ** Then for every term xN, evaluate as the subexpression: xN AND z
143208      ** That way, terms in y that are factored into the disjunction will
143209      ** be picked up by the recursive calls to sqlite3WhereBegin() below.
143210      **
143211      ** Actually, each subexpression is converted to "xN AND w" where w is
143212      ** the "interesting" terms of z - terms that did not originate in the
143213      ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
143214      ** indices.
143215      **
143216      ** This optimization also only applies if the (x1 OR x2 OR ...) term
143217      ** is not contained in the ON clause of a LEFT JOIN.
143218      ** See ticket http://www.sqlite.org/src/info/f2369304e4
143219      */
143220      if( pWC->nTerm>1 ){
143221        int iTerm;
143222        for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
143223          Expr *pExpr = pWC->a[iTerm].pExpr;
143224          if( &pWC->a[iTerm] == pTerm ) continue;
143225          testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
143226          testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
143227          if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
143228          if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
143229          testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
143230          pExpr = sqlite3ExprDup(db, pExpr, 0);
143231          pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
143232        }
143233        if( pAndExpr ){
143234          pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
143235        }
143236      }
143237  
143238      /* Run a separate WHERE clause for each term of the OR clause.  After
143239      ** eliminating duplicates from other WHERE clauses, the action for each
143240      ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
143241      */
143242      wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
143243      ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
143244      for(ii=0; ii<pOrWc->nTerm; ii++){
143245        WhereTerm *pOrTerm = &pOrWc->a[ii];
143246        if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
143247          WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
143248          Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
143249          int jmp1 = 0;                   /* Address of jump operation */
143250          assert( (pTabItem[0].fg.jointype & JT_LEFT)==0 
143251               || ExprHasProperty(pOrExpr, EP_FromJoin) 
143252          );
143253          if( pAndExpr ){
143254            pAndExpr->pLeft = pOrExpr;
143255            pOrExpr = pAndExpr;
143256          }
143257          /* Loop through table entries that match term pOrTerm. */
143258          ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
143259          WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
143260          pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
143261                                        wctrlFlags, iCovCur);
143262          assert( pSubWInfo || pParse->nErr || db->mallocFailed );
143263          if( pSubWInfo ){
143264            WhereLoop *pSubLoop;
143265            int addrExplain = sqlite3WhereExplainOneScan(
143266                pParse, pOrTab, &pSubWInfo->a[0], 0
143267            );
143268            sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
143269  
143270            /* This is the sub-WHERE clause body.  First skip over
143271            ** duplicate rows from prior sub-WHERE clauses, and record the
143272            ** rowid (or PRIMARY KEY) for the current row so that the same
143273            ** row will be skipped in subsequent sub-WHERE clauses.
143274            */
143275            if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
143276              int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
143277              if( HasRowid(pTab) ){
143278                sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
143279                jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
143280                                            regRowid, iSet);
143281                VdbeCoverage(v);
143282              }else{
143283                Index *pPk = sqlite3PrimaryKeyIndex(pTab);
143284                int nPk = pPk->nKeyCol;
143285                int iPk;
143286                int r;
143287  
143288                /* Read the PK into an array of temp registers. */
143289                r = sqlite3GetTempRange(pParse, nPk);
143290                for(iPk=0; iPk<nPk; iPk++){
143291                  int iCol = pPk->aiColumn[iPk];
143292                  sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, r+iPk);
143293                }
143294  
143295                /* Check if the temp table already contains this key. If so,
143296                ** the row has already been included in the result set and
143297                ** can be ignored (by jumping past the Gosub below). Otherwise,
143298                ** insert the key into the temp table and proceed with processing
143299                ** the row.
143300                **
143301                ** Use some of the same optimizations as OP_RowSetTest: If iSet
143302                ** is zero, assume that the key cannot already be present in
143303                ** the temp table. And if iSet is -1, assume that there is no 
143304                ** need to insert the key into the temp table, as it will never 
143305                ** be tested for.  */ 
143306                if( iSet ){
143307                  jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
143308                  VdbeCoverage(v);
143309                }
143310                if( iSet>=0 ){
143311                  sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
143312                  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
143313                                       r, nPk);
143314                  if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
143315                }
143316  
143317                /* Release the array of temp registers */
143318                sqlite3ReleaseTempRange(pParse, r, nPk);
143319              }
143320            }
143321  
143322            /* Invoke the main loop body as a subroutine */
143323            sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
143324  
143325            /* Jump here (skipping the main loop body subroutine) if the
143326            ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
143327            if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
143328  
143329            /* The pSubWInfo->untestedTerms flag means that this OR term
143330            ** contained one or more AND term from a notReady table.  The
143331            ** terms from the notReady table could not be tested and will
143332            ** need to be tested later.
143333            */
143334            if( pSubWInfo->untestedTerms ) untestedTerms = 1;
143335  
143336            /* If all of the OR-connected terms are optimized using the same
143337            ** index, and the index is opened using the same cursor number
143338            ** by each call to sqlite3WhereBegin() made by this loop, it may
143339            ** be possible to use that index as a covering index.
143340            **
143341            ** If the call to sqlite3WhereBegin() above resulted in a scan that
143342            ** uses an index, and this is either the first OR-connected term
143343            ** processed or the index is the same as that used by all previous
143344            ** terms, set pCov to the candidate covering index. Otherwise, set 
143345            ** pCov to NULL to indicate that no candidate covering index will 
143346            ** be available.
143347            */
143348            pSubLoop = pSubWInfo->a[0].pWLoop;
143349            assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
143350            if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
143351             && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
143352             && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
143353            ){
143354              assert( pSubWInfo->a[0].iIdxCur==iCovCur );
143355              pCov = pSubLoop->u.btree.pIndex;
143356            }else{
143357              pCov = 0;
143358            }
143359  
143360            /* Finish the loop through table entries that match term pOrTerm. */
143361            sqlite3WhereEnd(pSubWInfo);
143362            ExplainQueryPlanPop(pParse);
143363          }
143364        }
143365      }
143366      ExplainQueryPlanPop(pParse);
143367      pLevel->u.pCovidx = pCov;
143368      if( pCov ) pLevel->iIdxCur = iCovCur;
143369      if( pAndExpr ){
143370        pAndExpr->pLeft = 0;
143371        sqlite3ExprDelete(db, pAndExpr);
143372      }
143373      sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
143374      sqlite3VdbeGoto(v, pLevel->addrBrk);
143375      sqlite3VdbeResolveLabel(v, iLoopBody);
143376  
143377      if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
143378      if( !untestedTerms ) disableTerm(pLevel, pTerm);
143379    }else
143380  #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
143381  
143382    {
143383      /* Case 6:  There is no usable index.  We must do a complete
143384      **          scan of the entire table.
143385      */
143386      static const u8 aStep[] = { OP_Next, OP_Prev };
143387      static const u8 aStart[] = { OP_Rewind, OP_Last };
143388      assert( bRev==0 || bRev==1 );
143389      if( pTabItem->fg.isRecursive ){
143390        /* Tables marked isRecursive have only a single row that is stored in
143391        ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
143392        pLevel->op = OP_Noop;
143393      }else{
143394        codeCursorHint(pTabItem, pWInfo, pLevel, 0);
143395        pLevel->op = aStep[bRev];
143396        pLevel->p1 = iCur;
143397        pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
143398        VdbeCoverageIf(v, bRev==0);
143399        VdbeCoverageIf(v, bRev!=0);
143400        pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
143401      }
143402    }
143403  
143404  #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
143405    pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
143406  #endif
143407  
143408    /* Insert code to test every subexpression that can be completely
143409    ** computed using the current set of tables.
143410    **
143411    ** This loop may run between one and three times, depending on the
143412    ** constraints to be generated. The value of stack variable iLoop
143413    ** determines the constraints coded by each iteration, as follows:
143414    **
143415    ** iLoop==1: Code only expressions that are entirely covered by pIdx.
143416    ** iLoop==2: Code remaining expressions that do not contain correlated
143417    **           sub-queries.  
143418    ** iLoop==3: Code all remaining expressions.
143419    **
143420    ** An effort is made to skip unnecessary iterations of the loop.
143421    */
143422    iLoop = (pIdx ? 1 : 2);
143423    do{
143424      int iNext = 0;                /* Next value for iLoop */
143425      for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
143426        Expr *pE;
143427        int skipLikeAddr = 0;
143428        testcase( pTerm->wtFlags & TERM_VIRTUAL );
143429        testcase( pTerm->wtFlags & TERM_CODED );
143430        if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
143431        if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
143432          testcase( pWInfo->untestedTerms==0
143433              && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
143434          pWInfo->untestedTerms = 1;
143435          continue;
143436        }
143437        pE = pTerm->pExpr;
143438        assert( pE!=0 );
143439        if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
143440          continue;
143441        }
143442        
143443        if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
143444          iNext = 2;
143445          continue;
143446        }
143447        if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
143448          if( iNext==0 ) iNext = 3;
143449          continue;
143450        }
143451  
143452        if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
143453          /* If the TERM_LIKECOND flag is set, that means that the range search
143454          ** is sufficient to guarantee that the LIKE operator is true, so we
143455          ** can skip the call to the like(A,B) function.  But this only works
143456          ** for strings.  So do not skip the call to the function on the pass
143457          ** that compares BLOBs. */
143458  #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
143459          continue;
143460  #else
143461          u32 x = pLevel->iLikeRepCntr;
143462          if( x>0 ){
143463            skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
143464          }
143465          VdbeCoverage(v);
143466  #endif
143467        }
143468  #ifdef WHERETRACE_ENABLED /* 0xffff */
143469        if( sqlite3WhereTrace ){
143470          VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
143471                           pWC->nTerm-j, pTerm, iLoop));
143472        }
143473  #endif
143474        sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
143475        if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
143476        pTerm->wtFlags |= TERM_CODED;
143477      }
143478      iLoop = iNext;
143479    }while( iLoop>0 );
143480  
143481    /* Insert code to test for implied constraints based on transitivity
143482    ** of the "==" operator.
143483    **
143484    ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
143485    ** and we are coding the t1 loop and the t2 loop has not yet coded,
143486    ** then we cannot use the "t1.a=t2.b" constraint, but we can code
143487    ** the implied "t1.a=123" constraint.
143488    */
143489    for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
143490      Expr *pE, sEAlt;
143491      WhereTerm *pAlt;
143492      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
143493      if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
143494      if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
143495      if( pTerm->leftCursor!=iCur ) continue;
143496      if( pLevel->iLeftJoin ) continue;
143497      pE = pTerm->pExpr;
143498      assert( !ExprHasProperty(pE, EP_FromJoin) );
143499      assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
143500      pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
143501                      WO_EQ|WO_IN|WO_IS, 0);
143502      if( pAlt==0 ) continue;
143503      if( pAlt->wtFlags & (TERM_CODED) ) continue;
143504      if( (pAlt->eOperator & WO_IN) 
143505       && (pAlt->pExpr->flags & EP_xIsSelect)
143506       && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
143507      ){
143508        continue;
143509      }
143510      testcase( pAlt->eOperator & WO_EQ );
143511      testcase( pAlt->eOperator & WO_IS );
143512      testcase( pAlt->eOperator & WO_IN );
143513      VdbeModuleComment((v, "begin transitive constraint"));
143514      sEAlt = *pAlt->pExpr;
143515      sEAlt.pLeft = pE->pLeft;
143516      sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
143517    }
143518  
143519    /* For a LEFT OUTER JOIN, generate code that will record the fact that
143520    ** at least one row of the right table has matched the left table.  
143521    */
143522    if( pLevel->iLeftJoin ){
143523      pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
143524      sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
143525      VdbeComment((v, "record LEFT JOIN hit"));
143526      for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
143527        testcase( pTerm->wtFlags & TERM_VIRTUAL );
143528        testcase( pTerm->wtFlags & TERM_CODED );
143529        if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
143530        if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
143531          assert( pWInfo->untestedTerms );
143532          continue;
143533        }
143534        assert( pTerm->pExpr );
143535        sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
143536        pTerm->wtFlags |= TERM_CODED;
143537      }
143538    }
143539  
143540    return pLevel->notReady;
143541  }
143542  
143543  /************** End of wherecode.c *******************************************/
143544  /************** Begin file whereexpr.c ***************************************/
143545  /*
143546  ** 2015-06-08
143547  **
143548  ** The author disclaims copyright to this source code.  In place of
143549  ** a legal notice, here is a blessing:
143550  **
143551  **    May you do good and not evil.
143552  **    May you find forgiveness for yourself and forgive others.
143553  **    May you share freely, never taking more than you give.
143554  **
143555  *************************************************************************
143556  ** This module contains C code that generates VDBE code used to process
143557  ** the WHERE clause of SQL statements.
143558  **
143559  ** This file was originally part of where.c but was split out to improve
143560  ** readability and editabiliity.  This file contains utility routines for
143561  ** analyzing Expr objects in the WHERE clause.
143562  */
143563  /* #include "sqliteInt.h" */
143564  /* #include "whereInt.h" */
143565  
143566  /* Forward declarations */
143567  static void exprAnalyze(SrcList*, WhereClause*, int);
143568  
143569  /*
143570  ** Deallocate all memory associated with a WhereOrInfo object.
143571  */
143572  static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
143573    sqlite3WhereClauseClear(&p->wc);
143574    sqlite3DbFree(db, p);
143575  }
143576  
143577  /*
143578  ** Deallocate all memory associated with a WhereAndInfo object.
143579  */
143580  static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
143581    sqlite3WhereClauseClear(&p->wc);
143582    sqlite3DbFree(db, p);
143583  }
143584  
143585  /*
143586  ** Add a single new WhereTerm entry to the WhereClause object pWC.
143587  ** The new WhereTerm object is constructed from Expr p and with wtFlags.
143588  ** The index in pWC->a[] of the new WhereTerm is returned on success.
143589  ** 0 is returned if the new WhereTerm could not be added due to a memory
143590  ** allocation error.  The memory allocation failure will be recorded in
143591  ** the db->mallocFailed flag so that higher-level functions can detect it.
143592  **
143593  ** This routine will increase the size of the pWC->a[] array as necessary.
143594  **
143595  ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
143596  ** for freeing the expression p is assumed by the WhereClause object pWC.
143597  ** This is true even if this routine fails to allocate a new WhereTerm.
143598  **
143599  ** WARNING:  This routine might reallocate the space used to store
143600  ** WhereTerms.  All pointers to WhereTerms should be invalidated after
143601  ** calling this routine.  Such pointers may be reinitialized by referencing
143602  ** the pWC->a[] array.
143603  */
143604  static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
143605    WhereTerm *pTerm;
143606    int idx;
143607    testcase( wtFlags & TERM_VIRTUAL );
143608    if( pWC->nTerm>=pWC->nSlot ){
143609      WhereTerm *pOld = pWC->a;
143610      sqlite3 *db = pWC->pWInfo->pParse->db;
143611      pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
143612      if( pWC->a==0 ){
143613        if( wtFlags & TERM_DYNAMIC ){
143614          sqlite3ExprDelete(db, p);
143615        }
143616        pWC->a = pOld;
143617        return 0;
143618      }
143619      memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
143620      if( pOld!=pWC->aStatic ){
143621        sqlite3DbFree(db, pOld);
143622      }
143623      pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
143624    }
143625    pTerm = &pWC->a[idx = pWC->nTerm++];
143626    if( p && ExprHasProperty(p, EP_Unlikely) ){
143627      pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
143628    }else{
143629      pTerm->truthProb = 1;
143630    }
143631    pTerm->pExpr = sqlite3ExprSkipCollate(p);
143632    pTerm->wtFlags = wtFlags;
143633    pTerm->pWC = pWC;
143634    pTerm->iParent = -1;
143635    memset(&pTerm->eOperator, 0,
143636           sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
143637    return idx;
143638  }
143639  
143640  /*
143641  ** Return TRUE if the given operator is one of the operators that is
143642  ** allowed for an indexable WHERE clause term.  The allowed operators are
143643  ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
143644  */
143645  static int allowedOp(int op){
143646    assert( TK_GT>TK_EQ && TK_GT<TK_GE );
143647    assert( TK_LT>TK_EQ && TK_LT<TK_GE );
143648    assert( TK_LE>TK_EQ && TK_LE<TK_GE );
143649    assert( TK_GE==TK_EQ+4 );
143650    return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
143651  }
143652  
143653  /*
143654  ** Commute a comparison operator.  Expressions of the form "X op Y"
143655  ** are converted into "Y op X".
143656  **
143657  ** If left/right precedence rules come into play when determining the
143658  ** collating sequence, then COLLATE operators are adjusted to ensure
143659  ** that the collating sequence does not change.  For example:
143660  ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
143661  ** the left hand side of a comparison overrides any collation sequence 
143662  ** attached to the right. For the same reason the EP_Collate flag
143663  ** is not commuted.
143664  */
143665  static void exprCommute(Parse *pParse, Expr *pExpr){
143666    u16 expRight = (pExpr->pRight->flags & EP_Collate);
143667    u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
143668    assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
143669    if( expRight==expLeft ){
143670      /* Either X and Y both have COLLATE operator or neither do */
143671      if( expRight ){
143672        /* Both X and Y have COLLATE operators.  Make sure X is always
143673        ** used by clearing the EP_Collate flag from Y. */
143674        pExpr->pRight->flags &= ~EP_Collate;
143675      }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
143676        /* Neither X nor Y have COLLATE operators, but X has a non-default
143677        ** collating sequence.  So add the EP_Collate marker on X to cause
143678        ** it to be searched first. */
143679        pExpr->pLeft->flags |= EP_Collate;
143680      }
143681    }
143682    SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
143683    if( pExpr->op>=TK_GT ){
143684      assert( TK_LT==TK_GT+2 );
143685      assert( TK_GE==TK_LE+2 );
143686      assert( TK_GT>TK_EQ );
143687      assert( TK_GT<TK_LE );
143688      assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
143689      pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
143690    }
143691  }
143692  
143693  /*
143694  ** Translate from TK_xx operator to WO_xx bitmask.
143695  */
143696  static u16 operatorMask(int op){
143697    u16 c;
143698    assert( allowedOp(op) );
143699    if( op==TK_IN ){
143700      c = WO_IN;
143701    }else if( op==TK_ISNULL ){
143702      c = WO_ISNULL;
143703    }else if( op==TK_IS ){
143704      c = WO_IS;
143705    }else{
143706      assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
143707      c = (u16)(WO_EQ<<(op-TK_EQ));
143708    }
143709    assert( op!=TK_ISNULL || c==WO_ISNULL );
143710    assert( op!=TK_IN || c==WO_IN );
143711    assert( op!=TK_EQ || c==WO_EQ );
143712    assert( op!=TK_LT || c==WO_LT );
143713    assert( op!=TK_LE || c==WO_LE );
143714    assert( op!=TK_GT || c==WO_GT );
143715    assert( op!=TK_GE || c==WO_GE );
143716    assert( op!=TK_IS || c==WO_IS );
143717    return c;
143718  }
143719  
143720  
143721  #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
143722  /*
143723  ** Check to see if the given expression is a LIKE or GLOB operator that
143724  ** can be optimized using inequality constraints.  Return TRUE if it is
143725  ** so and false if not.
143726  **
143727  ** In order for the operator to be optimizible, the RHS must be a string
143728  ** literal that does not begin with a wildcard.  The LHS must be a column
143729  ** that may only be NULL, a string, or a BLOB, never a number. (This means
143730  ** that virtual tables cannot participate in the LIKE optimization.)  The
143731  ** collating sequence for the column on the LHS must be appropriate for
143732  ** the operator.
143733  */
143734  static int isLikeOrGlob(
143735    Parse *pParse,    /* Parsing and code generating context */
143736    Expr *pExpr,      /* Test this expression */
143737    Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
143738    int *pisComplete, /* True if the only wildcard is % in the last character */
143739    int *pnoCase      /* True if uppercase is equivalent to lowercase */
143740  ){
143741    const u8 *z = 0;           /* String on RHS of LIKE operator */
143742    Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
143743    ExprList *pList;           /* List of operands to the LIKE operator */
143744    u8 c;                      /* One character in z[] */
143745    int cnt;                   /* Number of non-wildcard prefix characters */
143746    u8 wc[4];                  /* Wildcard characters */
143747    sqlite3 *db = pParse->db;  /* Database connection */
143748    sqlite3_value *pVal = 0;
143749    int op;                    /* Opcode of pRight */
143750    int rc;                    /* Result code to return */
143751  
143752    if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
143753      return 0;
143754    }
143755  #ifdef SQLITE_EBCDIC
143756    if( *pnoCase ) return 0;
143757  #endif
143758    pList = pExpr->x.pList;
143759    pLeft = pList->a[1].pExpr;
143760  
143761    pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
143762    op = pRight->op;
143763    if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
143764      Vdbe *pReprepare = pParse->pReprepare;
143765      int iCol = pRight->iColumn;
143766      pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
143767      if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
143768        z = sqlite3_value_text(pVal);
143769      }
143770      sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
143771      assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
143772    }else if( op==TK_STRING ){
143773      z = (u8*)pRight->u.zToken;
143774    }
143775    if( z ){
143776  
143777      /* Count the number of prefix characters prior to the first wildcard */
143778      cnt = 0;
143779      while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
143780        cnt++;
143781        if( c==wc[3] && z[cnt]!=0 ) cnt++;
143782      }
143783  
143784      /* The optimization is possible only if (1) the pattern does not begin
143785      ** with a wildcard and if (2) the non-wildcard prefix does not end with
143786      ** an (illegal 0xff) character, or (3) the pattern does not consist of
143787      ** a single escape character. The second condition is necessary so
143788      ** that we can increment the prefix key to find an upper bound for the
143789      ** range search. The third is because the caller assumes that the pattern
143790      ** consists of at least one character after all escapes have been
143791      ** removed.  */
143792      if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
143793        Expr *pPrefix;
143794  
143795        /* A "complete" match if the pattern ends with "*" or "%" */
143796        *pisComplete = c==wc[0] && z[cnt+1]==0;
143797  
143798        /* Get the pattern prefix.  Remove all escapes from the prefix. */
143799        pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
143800        if( pPrefix ){
143801          int iFrom, iTo;
143802          char *zNew = pPrefix->u.zToken;
143803          zNew[cnt] = 0;
143804          for(iFrom=iTo=0; iFrom<cnt; iFrom++){
143805            if( zNew[iFrom]==wc[3] ) iFrom++;
143806            zNew[iTo++] = zNew[iFrom];
143807          }
143808          zNew[iTo] = 0;
143809  
143810          /* If the RHS begins with a digit or a minus sign, then the LHS must be
143811          ** an ordinary column (not a virtual table column) with TEXT affinity.
143812          ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
143813          ** even though "lhs LIKE rhs" is true.  But if the RHS does not start
143814          ** with a digit or '-', then "lhs LIKE rhs" will always be false if
143815          ** the LHS is numeric and so the optimization still works.
143816          **
143817          ** 2018-09-10 ticket c94369cae9b561b1f996d0054bfab11389f9d033
143818          ** The RHS pattern must not be '/%' because the termination condition
143819          ** will then become "x<'0'" and if the affinity is numeric, will then
143820          ** be converted into "x<0", which is incorrect.
143821          */
143822          if( sqlite3Isdigit(zNew[0])
143823           || zNew[0]=='-'
143824           || (zNew[0]+1=='0' && iTo==1)
143825          ){
143826            if( pLeft->op!=TK_COLUMN 
143827             || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
143828             || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */
143829            ){
143830              sqlite3ExprDelete(db, pPrefix);
143831              sqlite3ValueFree(pVal);
143832              return 0;
143833            }
143834          }
143835        }
143836        *ppPrefix = pPrefix;
143837  
143838        /* If the RHS pattern is a bound parameter, make arrangements to
143839        ** reprepare the statement when that parameter is rebound */
143840        if( op==TK_VARIABLE ){
143841          Vdbe *v = pParse->pVdbe;
143842          sqlite3VdbeSetVarmask(v, pRight->iColumn);
143843          if( *pisComplete && pRight->u.zToken[1] ){
143844            /* If the rhs of the LIKE expression is a variable, and the current
143845            ** value of the variable means there is no need to invoke the LIKE
143846            ** function, then no OP_Variable will be added to the program.
143847            ** This causes problems for the sqlite3_bind_parameter_name()
143848            ** API. To work around them, add a dummy OP_Variable here.
143849            */ 
143850            int r1 = sqlite3GetTempReg(pParse);
143851            sqlite3ExprCodeTarget(pParse, pRight, r1);
143852            sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
143853            sqlite3ReleaseTempReg(pParse, r1);
143854          }
143855        }
143856      }else{
143857        z = 0;
143858      }
143859    }
143860  
143861    rc = (z!=0);
143862    sqlite3ValueFree(pVal);
143863    return rc;
143864  }
143865  #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
143866  
143867  
143868  #ifndef SQLITE_OMIT_VIRTUALTABLE
143869  /*
143870  ** Check to see if the pExpr expression is a form that needs to be passed
143871  ** to the xBestIndex method of virtual tables.  Forms of interest include:
143872  **
143873  **          Expression                   Virtual Table Operator
143874  **          -----------------------      ---------------------------------
143875  **      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
143876  **      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
143877  **      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
143878  **      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
143879  **      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
143880  **      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
143881  **      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
143882  **      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
143883  **      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
143884  **
143885  ** In every case, "column" must be a column of a virtual table.  If there
143886  ** is a match, set *ppLeft to the "column" expression, set *ppRight to the 
143887  ** "expr" expression (even though in forms (6) and (8) the column is on the
143888  ** right and the expression is on the left).  Also set *peOp2 to the
143889  ** appropriate virtual table operator.  The return value is 1 or 2 if there
143890  ** is a match.  The usual return is 1, but if the RHS is also a column
143891  ** of virtual table in forms (5) or (7) then return 2.
143892  **
143893  ** If the expression matches none of the patterns above, return 0.
143894  */
143895  static int isAuxiliaryVtabOperator(
143896    sqlite3 *db,                    /* Parsing context */
143897    Expr *pExpr,                    /* Test this expression */
143898    unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */
143899    Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */
143900    Expr **ppRight                  /* Expression to left of MATCH/op2 */
143901  ){
143902    if( pExpr->op==TK_FUNCTION ){
143903      static const struct Op2 {
143904        const char *zOp;
143905        unsigned char eOp2;
143906      } aOp[] = {
143907        { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
143908        { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
143909        { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
143910        { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
143911      };
143912      ExprList *pList;
143913      Expr *pCol;                     /* Column reference */
143914      int i;
143915  
143916      pList = pExpr->x.pList;
143917      if( pList==0 || pList->nExpr!=2 ){
143918        return 0;
143919      }
143920  
143921      /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
143922      ** virtual table on their second argument, which is the same as
143923      ** the left-hand side operand in their in-fix form.
143924      **
143925      **       vtab_column MATCH expression
143926      **       MATCH(expression,vtab_column)
143927      */
143928      pCol = pList->a[1].pExpr;
143929      if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
143930        for(i=0; i<ArraySize(aOp); i++){
143931          if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
143932            *peOp2 = aOp[i].eOp2;
143933            *ppRight = pList->a[0].pExpr;
143934            *ppLeft = pCol;
143935            return 1;
143936          }
143937        }
143938      }
143939  
143940      /* We can also match against the first column of overloaded
143941      ** functions where xFindFunction returns a value of at least
143942      ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
143943      **
143944      **      OVERLOADED(vtab_column,expression)
143945      **
143946      ** Historically, xFindFunction expected to see lower-case function
143947      ** names.  But for this use case, xFindFunction is expected to deal
143948      ** with function names in an arbitrary case.
143949      */
143950      pCol = pList->a[0].pExpr;
143951      if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
143952        sqlite3_vtab *pVtab;
143953        sqlite3_module *pMod;
143954        void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
143955        void *pNotUsed;
143956        pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
143957        assert( pVtab!=0 );
143958        assert( pVtab->pModule!=0 );
143959        pMod = (sqlite3_module *)pVtab->pModule;
143960        if( pMod->xFindFunction!=0 ){
143961          i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
143962          if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
143963            *peOp2 = i;
143964            *ppRight = pList->a[1].pExpr;
143965            *ppLeft = pCol;
143966            return 1;
143967          }
143968        }
143969      }
143970    }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
143971      int res = 0;
143972      Expr *pLeft = pExpr->pLeft;
143973      Expr *pRight = pExpr->pRight;
143974      if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
143975        res++;
143976      }
143977      if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
143978        res++;
143979        SWAP(Expr*, pLeft, pRight);
143980      }
143981      *ppLeft = pLeft;
143982      *ppRight = pRight;
143983      if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
143984      if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
143985      if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
143986      return res;
143987    }
143988    return 0;
143989  }
143990  #endif /* SQLITE_OMIT_VIRTUALTABLE */
143991  
143992  /*
143993  ** If the pBase expression originated in the ON or USING clause of
143994  ** a join, then transfer the appropriate markings over to derived.
143995  */
143996  static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
143997    if( pDerived ){
143998      pDerived->flags |= pBase->flags & EP_FromJoin;
143999      pDerived->iRightJoinTable = pBase->iRightJoinTable;
144000    }
144001  }
144002  
144003  /*
144004  ** Mark term iChild as being a child of term iParent
144005  */
144006  static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
144007    pWC->a[iChild].iParent = iParent;
144008    pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
144009    pWC->a[iParent].nChild++;
144010  }
144011  
144012  /*
144013  ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
144014  ** a conjunction, then return just pTerm when N==0.  If N is exceeds
144015  ** the number of available subterms, return NULL.
144016  */
144017  static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
144018    if( pTerm->eOperator!=WO_AND ){
144019      return N==0 ? pTerm : 0;
144020    }
144021    if( N<pTerm->u.pAndInfo->wc.nTerm ){
144022      return &pTerm->u.pAndInfo->wc.a[N];
144023    }
144024    return 0;
144025  }
144026  
144027  /*
144028  ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
144029  ** two subterms are in disjunction - they are OR-ed together.
144030  **
144031  ** If these two terms are both of the form:  "A op B" with the same
144032  ** A and B values but different operators and if the operators are
144033  ** compatible (if one is = and the other is <, for example) then
144034  ** add a new virtual AND term to pWC that is the combination of the
144035  ** two.
144036  **
144037  ** Some examples:
144038  **
144039  **    x<y OR x=y    -->     x<=y
144040  **    x=y OR x=y    -->     x=y
144041  **    x<=y OR x<y   -->     x<=y
144042  **
144043  ** The following is NOT generated:
144044  **
144045  **    x<y OR x>y    -->     x!=y     
144046  */
144047  static void whereCombineDisjuncts(
144048    SrcList *pSrc,         /* the FROM clause */
144049    WhereClause *pWC,      /* The complete WHERE clause */
144050    WhereTerm *pOne,       /* First disjunct */
144051    WhereTerm *pTwo        /* Second disjunct */
144052  ){
144053    u16 eOp = pOne->eOperator | pTwo->eOperator;
144054    sqlite3 *db;           /* Database connection (for malloc) */
144055    Expr *pNew;            /* New virtual expression */
144056    int op;                /* Operator for the combined expression */
144057    int idxNew;            /* Index in pWC of the next virtual term */
144058  
144059    if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
144060    if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
144061    if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
144062     && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
144063    assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
144064    assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
144065    if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
144066    if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
144067    /* If we reach this point, it means the two subterms can be combined */
144068    if( (eOp & (eOp-1))!=0 ){
144069      if( eOp & (WO_LT|WO_LE) ){
144070        eOp = WO_LE;
144071      }else{
144072        assert( eOp & (WO_GT|WO_GE) );
144073        eOp = WO_GE;
144074      }
144075    }
144076    db = pWC->pWInfo->pParse->db;
144077    pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
144078    if( pNew==0 ) return;
144079    for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
144080    pNew->op = op;
144081    idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
144082    exprAnalyze(pSrc, pWC, idxNew);
144083  }
144084  
144085  #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
144086  /*
144087  ** Analyze a term that consists of two or more OR-connected
144088  ** subterms.  So in:
144089  **
144090  **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
144091  **                          ^^^^^^^^^^^^^^^^^^^^
144092  **
144093  ** This routine analyzes terms such as the middle term in the above example.
144094  ** A WhereOrTerm object is computed and attached to the term under
144095  ** analysis, regardless of the outcome of the analysis.  Hence:
144096  **
144097  **     WhereTerm.wtFlags   |=  TERM_ORINFO
144098  **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
144099  **
144100  ** The term being analyzed must have two or more of OR-connected subterms.
144101  ** A single subterm might be a set of AND-connected sub-subterms.
144102  ** Examples of terms under analysis:
144103  **
144104  **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
144105  **     (B)     x=expr1 OR expr2=x OR x=expr3
144106  **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
144107  **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
144108  **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
144109  **     (F)     x>A OR (x=A AND y>=B)
144110  **
144111  ** CASE 1:
144112  **
144113  ** If all subterms are of the form T.C=expr for some single column of C and
144114  ** a single table T (as shown in example B above) then create a new virtual
144115  ** term that is an equivalent IN expression.  In other words, if the term
144116  ** being analyzed is:
144117  **
144118  **      x = expr1  OR  expr2 = x  OR  x = expr3
144119  **
144120  ** then create a new virtual term like this:
144121  **
144122  **      x IN (expr1,expr2,expr3)
144123  **
144124  ** CASE 2:
144125  **
144126  ** If there are exactly two disjuncts and one side has x>A and the other side
144127  ** has x=A (for the same x and A) then add a new virtual conjunct term to the
144128  ** WHERE clause of the form "x>=A".  Example:
144129  **
144130  **      x>A OR (x=A AND y>B)    adds:    x>=A
144131  **
144132  ** The added conjunct can sometimes be helpful in query planning.
144133  **
144134  ** CASE 3:
144135  **
144136  ** If all subterms are indexable by a single table T, then set
144137  **
144138  **     WhereTerm.eOperator              =  WO_OR
144139  **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
144140  **
144141  ** A subterm is "indexable" if it is of the form
144142  ** "T.C <op> <expr>" where C is any column of table T and 
144143  ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
144144  ** A subterm is also indexable if it is an AND of two or more
144145  ** subsubterms at least one of which is indexable.  Indexable AND 
144146  ** subterms have their eOperator set to WO_AND and they have
144147  ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
144148  **
144149  ** From another point of view, "indexable" means that the subterm could
144150  ** potentially be used with an index if an appropriate index exists.
144151  ** This analysis does not consider whether or not the index exists; that
144152  ** is decided elsewhere.  This analysis only looks at whether subterms
144153  ** appropriate for indexing exist.
144154  **
144155  ** All examples A through E above satisfy case 3.  But if a term
144156  ** also satisfies case 1 (such as B) we know that the optimizer will
144157  ** always prefer case 1, so in that case we pretend that case 3 is not
144158  ** satisfied.
144159  **
144160  ** It might be the case that multiple tables are indexable.  For example,
144161  ** (E) above is indexable on tables P, Q, and R.
144162  **
144163  ** Terms that satisfy case 3 are candidates for lookup by using
144164  ** separate indices to find rowids for each subterm and composing
144165  ** the union of all rowids using a RowSet object.  This is similar
144166  ** to "bitmap indices" in other database engines.
144167  **
144168  ** OTHERWISE:
144169  **
144170  ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
144171  ** zero.  This term is not useful for search.
144172  */
144173  static void exprAnalyzeOrTerm(
144174    SrcList *pSrc,            /* the FROM clause */
144175    WhereClause *pWC,         /* the complete WHERE clause */
144176    int idxTerm               /* Index of the OR-term to be analyzed */
144177  ){
144178    WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
144179    Parse *pParse = pWInfo->pParse;         /* Parser context */
144180    sqlite3 *db = pParse->db;               /* Database connection */
144181    WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
144182    Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
144183    int i;                                  /* Loop counters */
144184    WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
144185    WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
144186    WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
144187    Bitmask chngToIN;         /* Tables that might satisfy case 1 */
144188    Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
144189  
144190    /*
144191    ** Break the OR clause into its separate subterms.  The subterms are
144192    ** stored in a WhereClause structure containing within the WhereOrInfo
144193    ** object that is attached to the original OR clause term.
144194    */
144195    assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
144196    assert( pExpr->op==TK_OR );
144197    pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
144198    if( pOrInfo==0 ) return;
144199    pTerm->wtFlags |= TERM_ORINFO;
144200    pOrWc = &pOrInfo->wc;
144201    memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
144202    sqlite3WhereClauseInit(pOrWc, pWInfo);
144203    sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
144204    sqlite3WhereExprAnalyze(pSrc, pOrWc);
144205    if( db->mallocFailed ) return;
144206    assert( pOrWc->nTerm>=2 );
144207  
144208    /*
144209    ** Compute the set of tables that might satisfy cases 1 or 3.
144210    */
144211    indexable = ~(Bitmask)0;
144212    chngToIN = ~(Bitmask)0;
144213    for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
144214      if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
144215        WhereAndInfo *pAndInfo;
144216        assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
144217        chngToIN = 0;
144218        pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
144219        if( pAndInfo ){
144220          WhereClause *pAndWC;
144221          WhereTerm *pAndTerm;
144222          int j;
144223          Bitmask b = 0;
144224          pOrTerm->u.pAndInfo = pAndInfo;
144225          pOrTerm->wtFlags |= TERM_ANDINFO;
144226          pOrTerm->eOperator = WO_AND;
144227          pAndWC = &pAndInfo->wc;
144228          memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
144229          sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
144230          sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
144231          sqlite3WhereExprAnalyze(pSrc, pAndWC);
144232          pAndWC->pOuter = pWC;
144233          if( !db->mallocFailed ){
144234            for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
144235              assert( pAndTerm->pExpr );
144236              if( allowedOp(pAndTerm->pExpr->op) 
144237               || pAndTerm->eOperator==WO_AUX
144238              ){
144239                b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
144240              }
144241            }
144242          }
144243          indexable &= b;
144244        }
144245      }else if( pOrTerm->wtFlags & TERM_COPIED ){
144246        /* Skip this term for now.  We revisit it when we process the
144247        ** corresponding TERM_VIRTUAL term */
144248      }else{
144249        Bitmask b;
144250        b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
144251        if( pOrTerm->wtFlags & TERM_VIRTUAL ){
144252          WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
144253          b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
144254        }
144255        indexable &= b;
144256        if( (pOrTerm->eOperator & WO_EQ)==0 ){
144257          chngToIN = 0;
144258        }else{
144259          chngToIN &= b;
144260        }
144261      }
144262    }
144263  
144264    /*
144265    ** Record the set of tables that satisfy case 3.  The set might be
144266    ** empty.
144267    */
144268    pOrInfo->indexable = indexable;
144269    if( indexable ){
144270      pTerm->eOperator = WO_OR;
144271      pWC->hasOr = 1;
144272    }else{
144273      pTerm->eOperator = WO_OR;
144274    }
144275  
144276    /* For a two-way OR, attempt to implementation case 2.
144277    */
144278    if( indexable && pOrWc->nTerm==2 ){
144279      int iOne = 0;
144280      WhereTerm *pOne;
144281      while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
144282        int iTwo = 0;
144283        WhereTerm *pTwo;
144284        while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
144285          whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
144286        }
144287      }
144288    }
144289  
144290    /*
144291    ** chngToIN holds a set of tables that *might* satisfy case 1.  But
144292    ** we have to do some additional checking to see if case 1 really
144293    ** is satisfied.
144294    **
144295    ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
144296    ** that there is no possibility of transforming the OR clause into an
144297    ** IN operator because one or more terms in the OR clause contain
144298    ** something other than == on a column in the single table.  The 1-bit
144299    ** case means that every term of the OR clause is of the form
144300    ** "table.column=expr" for some single table.  The one bit that is set
144301    ** will correspond to the common table.  We still need to check to make
144302    ** sure the same column is used on all terms.  The 2-bit case is when
144303    ** the all terms are of the form "table1.column=table2.column".  It
144304    ** might be possible to form an IN operator with either table1.column
144305    ** or table2.column as the LHS if either is common to every term of
144306    ** the OR clause.
144307    **
144308    ** Note that terms of the form "table.column1=table.column2" (the
144309    ** same table on both sizes of the ==) cannot be optimized.
144310    */
144311    if( chngToIN ){
144312      int okToChngToIN = 0;     /* True if the conversion to IN is valid */
144313      int iColumn = -1;         /* Column index on lhs of IN operator */
144314      int iCursor = -1;         /* Table cursor common to all terms */
144315      int j = 0;                /* Loop counter */
144316  
144317      /* Search for a table and column that appears on one side or the
144318      ** other of the == operator in every subterm.  That table and column
144319      ** will be recorded in iCursor and iColumn.  There might not be any
144320      ** such table and column.  Set okToChngToIN if an appropriate table
144321      ** and column is found but leave okToChngToIN false if not found.
144322      */
144323      for(j=0; j<2 && !okToChngToIN; j++){
144324        Expr *pLeft = 0;
144325        pOrTerm = pOrWc->a;
144326        for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
144327          assert( pOrTerm->eOperator & WO_EQ );
144328          pOrTerm->wtFlags &= ~TERM_OR_OK;
144329          if( pOrTerm->leftCursor==iCursor ){
144330            /* This is the 2-bit case and we are on the second iteration and
144331            ** current term is from the first iteration.  So skip this term. */
144332            assert( j==1 );
144333            continue;
144334          }
144335          if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
144336                                              pOrTerm->leftCursor))==0 ){
144337            /* This term must be of the form t1.a==t2.b where t2 is in the
144338            ** chngToIN set but t1 is not.  This term will be either preceded
144339            ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
144340            ** and use its inversion. */
144341            testcase( pOrTerm->wtFlags & TERM_COPIED );
144342            testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
144343            assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
144344            continue;
144345          }
144346          iColumn = pOrTerm->u.leftColumn;
144347          iCursor = pOrTerm->leftCursor;
144348          pLeft = pOrTerm->pExpr->pLeft;
144349          break;
144350        }
144351        if( i<0 ){
144352          /* No candidate table+column was found.  This can only occur
144353          ** on the second iteration */
144354          assert( j==1 );
144355          assert( IsPowerOfTwo(chngToIN) );
144356          assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
144357          break;
144358        }
144359        testcase( j==1 );
144360  
144361        /* We have found a candidate table and column.  Check to see if that
144362        ** table and column is common to every term in the OR clause */
144363        okToChngToIN = 1;
144364        for(; i>=0 && okToChngToIN; i--, pOrTerm++){
144365          assert( pOrTerm->eOperator & WO_EQ );
144366          if( pOrTerm->leftCursor!=iCursor ){
144367            pOrTerm->wtFlags &= ~TERM_OR_OK;
144368          }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR 
144369                 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
144370          )){
144371            okToChngToIN = 0;
144372          }else{
144373            int affLeft, affRight;
144374            /* If the right-hand side is also a column, then the affinities
144375            ** of both right and left sides must be such that no type
144376            ** conversions are required on the right.  (Ticket #2249)
144377            */
144378            affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
144379            affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
144380            if( affRight!=0 && affRight!=affLeft ){
144381              okToChngToIN = 0;
144382            }else{
144383              pOrTerm->wtFlags |= TERM_OR_OK;
144384            }
144385          }
144386        }
144387      }
144388  
144389      /* At this point, okToChngToIN is true if original pTerm satisfies
144390      ** case 1.  In that case, construct a new virtual term that is 
144391      ** pTerm converted into an IN operator.
144392      */
144393      if( okToChngToIN ){
144394        Expr *pDup;            /* A transient duplicate expression */
144395        ExprList *pList = 0;   /* The RHS of the IN operator */
144396        Expr *pLeft = 0;       /* The LHS of the IN operator */
144397        Expr *pNew;            /* The complete IN operator */
144398  
144399        for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
144400          if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
144401          assert( pOrTerm->eOperator & WO_EQ );
144402          assert( pOrTerm->leftCursor==iCursor );
144403          assert( pOrTerm->u.leftColumn==iColumn );
144404          pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
144405          pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
144406          pLeft = pOrTerm->pExpr->pLeft;
144407        }
144408        assert( pLeft!=0 );
144409        pDup = sqlite3ExprDup(db, pLeft, 0);
144410        pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
144411        if( pNew ){
144412          int idxNew;
144413          transferJoinMarkings(pNew, pExpr);
144414          assert( !ExprHasProperty(pNew, EP_xIsSelect) );
144415          pNew->x.pList = pList;
144416          idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
144417          testcase( idxNew==0 );
144418          exprAnalyze(pSrc, pWC, idxNew);
144419          /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
144420          markTermAsChild(pWC, idxNew, idxTerm);
144421        }else{
144422          sqlite3ExprListDelete(db, pList);
144423        }
144424      }
144425    }
144426  }
144427  #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
144428  
144429  /*
144430  ** We already know that pExpr is a binary operator where both operands are
144431  ** column references.  This routine checks to see if pExpr is an equivalence
144432  ** relation:
144433  **   1.  The SQLITE_Transitive optimization must be enabled
144434  **   2.  Must be either an == or an IS operator
144435  **   3.  Not originating in the ON clause of an OUTER JOIN
144436  **   4.  The affinities of A and B must be compatible
144437  **   5a. Both operands use the same collating sequence OR
144438  **   5b. The overall collating sequence is BINARY
144439  ** If this routine returns TRUE, that means that the RHS can be substituted
144440  ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
144441  ** This is an optimization.  No harm comes from returning 0.  But if 1 is
144442  ** returned when it should not be, then incorrect answers might result.
144443  */
144444  static int termIsEquivalence(Parse *pParse, Expr *pExpr){
144445    char aff1, aff2;
144446    CollSeq *pColl;
144447    if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
144448    if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
144449    if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
144450    aff1 = sqlite3ExprAffinity(pExpr->pLeft);
144451    aff2 = sqlite3ExprAffinity(pExpr->pRight);
144452    if( aff1!=aff2
144453     && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
144454    ){
144455      return 0;
144456    }
144457    pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
144458    if( sqlite3IsBinary(pColl) ) return 1;
144459    return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
144460  }
144461  
144462  /*
144463  ** Recursively walk the expressions of a SELECT statement and generate
144464  ** a bitmask indicating which tables are used in that expression
144465  ** tree.
144466  */
144467  static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
144468    Bitmask mask = 0;
144469    while( pS ){
144470      SrcList *pSrc = pS->pSrc;
144471      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
144472      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
144473      mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
144474      mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
144475      mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
144476      if( ALWAYS(pSrc!=0) ){
144477        int i;
144478        for(i=0; i<pSrc->nSrc; i++){
144479          mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
144480          mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
144481          if( pSrc->a[i].fg.isTabFunc ){
144482            mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
144483          }
144484        }
144485      }
144486      pS = pS->pPrior;
144487    }
144488    return mask;
144489  }
144490  
144491  /*
144492  ** Expression pExpr is one operand of a comparison operator that might
144493  ** be useful for indexing.  This routine checks to see if pExpr appears
144494  ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
144495  ** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
144496  ** number of the table that is indexed and aiCurCol[1] to the column number
144497  ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
144498  ** indexed.
144499  **
144500  ** If pExpr is a TK_COLUMN column reference, then this routine always returns
144501  ** true even if that particular column is not indexed, because the column
144502  ** might be added to an automatic index later.
144503  */
144504  static SQLITE_NOINLINE int exprMightBeIndexed2(
144505    SrcList *pFrom,        /* The FROM clause */
144506    Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
144507    int *aiCurCol,         /* Write the referenced table cursor and column here */
144508    Expr *pExpr            /* An operand of a comparison operator */
144509  ){
144510    Index *pIdx;
144511    int i;
144512    int iCur;
144513    for(i=0; mPrereq>1; i++, mPrereq>>=1){}
144514    iCur = pFrom->a[i].iCursor;
144515    for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
144516      if( pIdx->aColExpr==0 ) continue;
144517      for(i=0; i<pIdx->nKeyCol; i++){
144518        if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
144519        if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
144520          aiCurCol[0] = iCur;
144521          aiCurCol[1] = XN_EXPR;
144522          return 1;
144523        }
144524      }
144525    }
144526    return 0;
144527  }
144528  static int exprMightBeIndexed(
144529    SrcList *pFrom,        /* The FROM clause */
144530    Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
144531    int *aiCurCol,         /* Write the referenced table cursor & column here */
144532    Expr *pExpr,           /* An operand of a comparison operator */
144533    int op                 /* The specific comparison operator */
144534  ){
144535    /* If this expression is a vector to the left or right of a 
144536    ** inequality constraint (>, <, >= or <=), perform the processing 
144537    ** on the first element of the vector.  */
144538    assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
144539    assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
144540    assert( op<=TK_GE );
144541    if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
144542      pExpr = pExpr->x.pList->a[0].pExpr;
144543    }
144544  
144545    if( pExpr->op==TK_COLUMN ){
144546      aiCurCol[0] = pExpr->iTable;
144547      aiCurCol[1] = pExpr->iColumn;
144548      return 1;
144549    }
144550    if( mPrereq==0 ) return 0;                 /* No table references */
144551    if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
144552    return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
144553  }
144554  
144555  /*
144556  ** The input to this routine is an WhereTerm structure with only the
144557  ** "pExpr" field filled in.  The job of this routine is to analyze the
144558  ** subexpression and populate all the other fields of the WhereTerm
144559  ** structure.
144560  **
144561  ** If the expression is of the form "<expr> <op> X" it gets commuted
144562  ** to the standard form of "X <op> <expr>".
144563  **
144564  ** If the expression is of the form "X <op> Y" where both X and Y are
144565  ** columns, then the original expression is unchanged and a new virtual
144566  ** term of the form "Y <op> X" is added to the WHERE clause and
144567  ** analyzed separately.  The original term is marked with TERM_COPIED
144568  ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
144569  ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
144570  ** is a commuted copy of a prior term.)  The original term has nChild=1
144571  ** and the copy has idxParent set to the index of the original term.
144572  */
144573  static void exprAnalyze(
144574    SrcList *pSrc,            /* the FROM clause */
144575    WhereClause *pWC,         /* the WHERE clause */
144576    int idxTerm               /* Index of the term to be analyzed */
144577  ){
144578    WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
144579    WhereTerm *pTerm;                /* The term to be analyzed */
144580    WhereMaskSet *pMaskSet;          /* Set of table index masks */
144581    Expr *pExpr;                     /* The expression to be analyzed */
144582    Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
144583    Bitmask prereqAll;               /* Prerequesites of pExpr */
144584    Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
144585    Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
144586    int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
144587    int noCase = 0;                  /* uppercase equivalent to lowercase */
144588    int op;                          /* Top-level operator.  pExpr->op */
144589    Parse *pParse = pWInfo->pParse;  /* Parsing context */
144590    sqlite3 *db = pParse->db;        /* Database connection */
144591    unsigned char eOp2 = 0;          /* op2 value for LIKE/REGEXP/GLOB */
144592    int nLeft;                       /* Number of elements on left side vector */
144593  
144594    if( db->mallocFailed ){
144595      return;
144596    }
144597    pTerm = &pWC->a[idxTerm];
144598    pMaskSet = &pWInfo->sMaskSet;
144599    pExpr = pTerm->pExpr;
144600    assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
144601    prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
144602    op = pExpr->op;
144603    if( op==TK_IN ){
144604      assert( pExpr->pRight==0 );
144605      if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
144606      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
144607        pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
144608      }else{
144609        pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
144610      }
144611    }else if( op==TK_ISNULL ){
144612      pTerm->prereqRight = 0;
144613    }else{
144614      pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
144615    }
144616    pMaskSet->bVarSelect = 0;
144617    prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
144618    if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
144619    if( ExprHasProperty(pExpr, EP_FromJoin) ){
144620      Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
144621      prereqAll |= x;
144622      extraRight = x-1;  /* ON clause terms may not be used with an index
144623                         ** on left table of a LEFT JOIN.  Ticket #3015 */
144624      if( (prereqAll>>1)>=x ){
144625        sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
144626        return;
144627      }
144628    }
144629    pTerm->prereqAll = prereqAll;
144630    pTerm->leftCursor = -1;
144631    pTerm->iParent = -1;
144632    pTerm->eOperator = 0;
144633    if( allowedOp(op) ){
144634      int aiCurCol[2];
144635      Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
144636      Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
144637      u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
144638  
144639      if( pTerm->iField>0 ){
144640        assert( op==TK_IN );
144641        assert( pLeft->op==TK_VECTOR );
144642        pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
144643      }
144644  
144645      if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
144646        pTerm->leftCursor = aiCurCol[0];
144647        pTerm->u.leftColumn = aiCurCol[1];
144648        pTerm->eOperator = operatorMask(op) & opMask;
144649      }
144650      if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
144651      if( pRight 
144652       && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
144653      ){
144654        WhereTerm *pNew;
144655        Expr *pDup;
144656        u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
144657        assert( pTerm->iField==0 );
144658        if( pTerm->leftCursor>=0 ){
144659          int idxNew;
144660          pDup = sqlite3ExprDup(db, pExpr, 0);
144661          if( db->mallocFailed ){
144662            sqlite3ExprDelete(db, pDup);
144663            return;
144664          }
144665          idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
144666          if( idxNew==0 ) return;
144667          pNew = &pWC->a[idxNew];
144668          markTermAsChild(pWC, idxNew, idxTerm);
144669          if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
144670          pTerm = &pWC->a[idxTerm];
144671          pTerm->wtFlags |= TERM_COPIED;
144672  
144673          if( termIsEquivalence(pParse, pDup) ){
144674            pTerm->eOperator |= WO_EQUIV;
144675            eExtraOp = WO_EQUIV;
144676          }
144677        }else{
144678          pDup = pExpr;
144679          pNew = pTerm;
144680        }
144681        exprCommute(pParse, pDup);
144682        pNew->leftCursor = aiCurCol[0];
144683        pNew->u.leftColumn = aiCurCol[1];
144684        testcase( (prereqLeft | extraRight) != prereqLeft );
144685        pNew->prereqRight = prereqLeft | extraRight;
144686        pNew->prereqAll = prereqAll;
144687        pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
144688      }
144689    }
144690  
144691  #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
144692    /* If a term is the BETWEEN operator, create two new virtual terms
144693    ** that define the range that the BETWEEN implements.  For example:
144694    **
144695    **      a BETWEEN b AND c
144696    **
144697    ** is converted into:
144698    **
144699    **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
144700    **
144701    ** The two new terms are added onto the end of the WhereClause object.
144702    ** The new terms are "dynamic" and are children of the original BETWEEN
144703    ** term.  That means that if the BETWEEN term is coded, the children are
144704    ** skipped.  Or, if the children are satisfied by an index, the original
144705    ** BETWEEN term is skipped.
144706    */
144707    else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
144708      ExprList *pList = pExpr->x.pList;
144709      int i;
144710      static const u8 ops[] = {TK_GE, TK_LE};
144711      assert( pList!=0 );
144712      assert( pList->nExpr==2 );
144713      for(i=0; i<2; i++){
144714        Expr *pNewExpr;
144715        int idxNew;
144716        pNewExpr = sqlite3PExpr(pParse, ops[i], 
144717                               sqlite3ExprDup(db, pExpr->pLeft, 0),
144718                               sqlite3ExprDup(db, pList->a[i].pExpr, 0));
144719        transferJoinMarkings(pNewExpr, pExpr);
144720        idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
144721        testcase( idxNew==0 );
144722        exprAnalyze(pSrc, pWC, idxNew);
144723        pTerm = &pWC->a[idxTerm];
144724        markTermAsChild(pWC, idxNew, idxTerm);
144725      }
144726    }
144727  #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
144728  
144729  #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
144730    /* Analyze a term that is composed of two or more subterms connected by
144731    ** an OR operator.
144732    */
144733    else if( pExpr->op==TK_OR ){
144734      assert( pWC->op==TK_AND );
144735      exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
144736      pTerm = &pWC->a[idxTerm];
144737    }
144738  #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
144739  
144740  #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
144741    /* Add constraints to reduce the search space on a LIKE or GLOB
144742    ** operator.
144743    **
144744    ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
144745    **
144746    **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
144747    **
144748    ** The last character of the prefix "abc" is incremented to form the
144749    ** termination condition "abd".  If case is not significant (the default
144750    ** for LIKE) then the lower-bound is made all uppercase and the upper-
144751    ** bound is made all lowercase so that the bounds also work when comparing
144752    ** BLOBs.
144753    */
144754    if( pWC->op==TK_AND 
144755     && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
144756    ){
144757      Expr *pLeft;       /* LHS of LIKE/GLOB operator */
144758      Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
144759      Expr *pNewExpr1;
144760      Expr *pNewExpr2;
144761      int idxNew1;
144762      int idxNew2;
144763      const char *zCollSeqName;     /* Name of collating sequence */
144764      const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
144765  
144766      pLeft = pExpr->x.pList->a[1].pExpr;
144767      pStr2 = sqlite3ExprDup(db, pStr1, 0);
144768  
144769      /* Convert the lower bound to upper-case and the upper bound to
144770      ** lower-case (upper-case is less than lower-case in ASCII) so that
144771      ** the range constraints also work for BLOBs
144772      */
144773      if( noCase && !pParse->db->mallocFailed ){
144774        int i;
144775        char c;
144776        pTerm->wtFlags |= TERM_LIKE;
144777        for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
144778          pStr1->u.zToken[i] = sqlite3Toupper(c);
144779          pStr2->u.zToken[i] = sqlite3Tolower(c);
144780        }
144781      }
144782  
144783      if( !db->mallocFailed ){
144784        u8 c, *pC;       /* Last character before the first wildcard */
144785        pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
144786        c = *pC;
144787        if( noCase ){
144788          /* The point is to increment the last character before the first
144789          ** wildcard.  But if we increment '@', that will push it into the
144790          ** alphabetic range where case conversions will mess up the 
144791          ** inequality.  To avoid this, make sure to also run the full
144792          ** LIKE on all candidate expressions by clearing the isComplete flag
144793          */
144794          if( c=='A'-1 ) isComplete = 0;
144795          c = sqlite3UpperToLower[c];
144796        }
144797        *pC = c + 1;
144798      }
144799      zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
144800      pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
144801      pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
144802             sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
144803             pStr1);
144804      transferJoinMarkings(pNewExpr1, pExpr);
144805      idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
144806      testcase( idxNew1==0 );
144807      exprAnalyze(pSrc, pWC, idxNew1);
144808      pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
144809      pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
144810             sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
144811             pStr2);
144812      transferJoinMarkings(pNewExpr2, pExpr);
144813      idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
144814      testcase( idxNew2==0 );
144815      exprAnalyze(pSrc, pWC, idxNew2);
144816      pTerm = &pWC->a[idxTerm];
144817      if( isComplete ){
144818        markTermAsChild(pWC, idxNew1, idxTerm);
144819        markTermAsChild(pWC, idxNew2, idxTerm);
144820      }
144821    }
144822  #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
144823  
144824  #ifndef SQLITE_OMIT_VIRTUALTABLE
144825    /* Add a WO_AUX auxiliary term to the constraint set if the
144826    ** current expression is of the form "column OP expr" where OP
144827    ** is an operator that gets passed into virtual tables but which is
144828    ** not normally optimized for ordinary tables.  In other words, OP
144829    ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
144830    ** This information is used by the xBestIndex methods of
144831    ** virtual tables.  The native query optimizer does not attempt
144832    ** to do anything with MATCH functions.
144833    */
144834    if( pWC->op==TK_AND ){
144835      Expr *pRight = 0, *pLeft = 0;
144836      int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
144837      while( res-- > 0 ){
144838        int idxNew;
144839        WhereTerm *pNewTerm;
144840        Bitmask prereqColumn, prereqExpr;
144841  
144842        prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
144843        prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
144844        if( (prereqExpr & prereqColumn)==0 ){
144845          Expr *pNewExpr;
144846          pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
144847              0, sqlite3ExprDup(db, pRight, 0));
144848          if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
144849            ExprSetProperty(pNewExpr, EP_FromJoin);
144850          }
144851          idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
144852          testcase( idxNew==0 );
144853          pNewTerm = &pWC->a[idxNew];
144854          pNewTerm->prereqRight = prereqExpr;
144855          pNewTerm->leftCursor = pLeft->iTable;
144856          pNewTerm->u.leftColumn = pLeft->iColumn;
144857          pNewTerm->eOperator = WO_AUX;
144858          pNewTerm->eMatchOp = eOp2;
144859          markTermAsChild(pWC, idxNew, idxTerm);
144860          pTerm = &pWC->a[idxTerm];
144861          pTerm->wtFlags |= TERM_COPIED;
144862          pNewTerm->prereqAll = pTerm->prereqAll;
144863        }
144864        SWAP(Expr*, pLeft, pRight);
144865      }
144866    }
144867  #endif /* SQLITE_OMIT_VIRTUALTABLE */
144868  
144869    /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
144870    ** new terms for each component comparison - "a = ?" and "b = ?".  The
144871    ** new terms completely replace the original vector comparison, which is
144872    ** no longer used.
144873    **
144874    ** This is only required if at least one side of the comparison operation
144875    ** is not a sub-select.  */
144876    if( pWC->op==TK_AND 
144877    && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
144878    && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
144879    && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
144880    && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 
144881      || (pExpr->pRight->flags & EP_xIsSelect)==0)
144882    ){
144883      int i;
144884      for(i=0; i<nLeft; i++){
144885        int idxNew;
144886        Expr *pNew;
144887        Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
144888        Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
144889  
144890        pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
144891        transferJoinMarkings(pNew, pExpr);
144892        idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
144893        exprAnalyze(pSrc, pWC, idxNew);
144894      }
144895      pTerm = &pWC->a[idxTerm];
144896      pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
144897      pTerm->eOperator = 0;
144898    }
144899  
144900    /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
144901    ** a virtual term for each vector component. The expression object
144902    ** used by each such virtual term is pExpr (the full vector IN(...) 
144903    ** expression). The WhereTerm.iField variable identifies the index within
144904    ** the vector on the LHS that the virtual term represents.
144905    **
144906    ** This only works if the RHS is a simple SELECT, not a compound
144907    */
144908    if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
144909     && pExpr->pLeft->op==TK_VECTOR
144910     && pExpr->x.pSelect->pPrior==0
144911    ){
144912      int i;
144913      for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
144914        int idxNew;
144915        idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
144916        pWC->a[idxNew].iField = i+1;
144917        exprAnalyze(pSrc, pWC, idxNew);
144918        markTermAsChild(pWC, idxNew, idxTerm);
144919      }
144920    }
144921  
144922  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
144923    /* When sqlite_stat3 histogram data is available an operator of the
144924    ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
144925    ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
144926    ** virtual term of that form.
144927    **
144928    ** Note that the virtual term must be tagged with TERM_VNULL.
144929    */
144930    if( pExpr->op==TK_NOTNULL
144931     && pExpr->pLeft->op==TK_COLUMN
144932     && pExpr->pLeft->iColumn>=0
144933     && !ExprHasProperty(pExpr, EP_FromJoin)
144934     && OptimizationEnabled(db, SQLITE_Stat34)
144935    ){
144936      Expr *pNewExpr;
144937      Expr *pLeft = pExpr->pLeft;
144938      int idxNew;
144939      WhereTerm *pNewTerm;
144940  
144941      pNewExpr = sqlite3PExpr(pParse, TK_GT,
144942                              sqlite3ExprDup(db, pLeft, 0),
144943                              sqlite3ExprAlloc(db, TK_NULL, 0, 0));
144944  
144945      idxNew = whereClauseInsert(pWC, pNewExpr,
144946                                TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
144947      if( idxNew ){
144948        pNewTerm = &pWC->a[idxNew];
144949        pNewTerm->prereqRight = 0;
144950        pNewTerm->leftCursor = pLeft->iTable;
144951        pNewTerm->u.leftColumn = pLeft->iColumn;
144952        pNewTerm->eOperator = WO_GT;
144953        markTermAsChild(pWC, idxNew, idxTerm);
144954        pTerm = &pWC->a[idxTerm];
144955        pTerm->wtFlags |= TERM_COPIED;
144956        pNewTerm->prereqAll = pTerm->prereqAll;
144957      }
144958    }
144959  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
144960  
144961    /* Prevent ON clause terms of a LEFT JOIN from being used to drive
144962    ** an index for tables to the left of the join.
144963    */
144964    testcase( pTerm!=&pWC->a[idxTerm] );
144965    pTerm = &pWC->a[idxTerm];
144966    pTerm->prereqRight |= extraRight;
144967  }
144968  
144969  /***************************************************************************
144970  ** Routines with file scope above.  Interface to the rest of the where.c
144971  ** subsystem follows.
144972  ***************************************************************************/
144973  
144974  /*
144975  ** This routine identifies subexpressions in the WHERE clause where
144976  ** each subexpression is separated by the AND operator or some other
144977  ** operator specified in the op parameter.  The WhereClause structure
144978  ** is filled with pointers to subexpressions.  For example:
144979  **
144980  **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
144981  **           \________/     \_______________/     \________________/
144982  **            slot[0]            slot[1]               slot[2]
144983  **
144984  ** The original WHERE clause in pExpr is unaltered.  All this routine
144985  ** does is make slot[] entries point to substructure within pExpr.
144986  **
144987  ** In the previous sentence and in the diagram, "slot[]" refers to
144988  ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
144989  ** all terms of the WHERE clause.
144990  */
144991  SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
144992    Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
144993    pWC->op = op;
144994    if( pE2==0 ) return;
144995    if( pE2->op!=op ){
144996      whereClauseInsert(pWC, pExpr, 0);
144997    }else{
144998      sqlite3WhereSplit(pWC, pE2->pLeft, op);
144999      sqlite3WhereSplit(pWC, pE2->pRight, op);
145000    }
145001  }
145002  
145003  /*
145004  ** Initialize a preallocated WhereClause structure.
145005  */
145006  SQLITE_PRIVATE void sqlite3WhereClauseInit(
145007    WhereClause *pWC,        /* The WhereClause to be initialized */
145008    WhereInfo *pWInfo        /* The WHERE processing context */
145009  ){
145010    pWC->pWInfo = pWInfo;
145011    pWC->hasOr = 0;
145012    pWC->pOuter = 0;
145013    pWC->nTerm = 0;
145014    pWC->nSlot = ArraySize(pWC->aStatic);
145015    pWC->a = pWC->aStatic;
145016  }
145017  
145018  /*
145019  ** Deallocate a WhereClause structure.  The WhereClause structure
145020  ** itself is not freed.  This routine is the inverse of
145021  ** sqlite3WhereClauseInit().
145022  */
145023  SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
145024    int i;
145025    WhereTerm *a;
145026    sqlite3 *db = pWC->pWInfo->pParse->db;
145027    for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
145028      if( a->wtFlags & TERM_DYNAMIC ){
145029        sqlite3ExprDelete(db, a->pExpr);
145030      }
145031      if( a->wtFlags & TERM_ORINFO ){
145032        whereOrInfoDelete(db, a->u.pOrInfo);
145033      }else if( a->wtFlags & TERM_ANDINFO ){
145034        whereAndInfoDelete(db, a->u.pAndInfo);
145035      }
145036    }
145037    if( pWC->a!=pWC->aStatic ){
145038      sqlite3DbFree(db, pWC->a);
145039    }
145040  }
145041  
145042  
145043  /*
145044  ** These routines walk (recursively) an expression tree and generate
145045  ** a bitmask indicating which tables are used in that expression
145046  ** tree.
145047  */
145048  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
145049    Bitmask mask;
145050    if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
145051      return sqlite3WhereGetMask(pMaskSet, p->iTable);
145052    }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
145053      assert( p->op!=TK_IF_NULL_ROW );
145054      return 0;
145055    }
145056    mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
145057    if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
145058    if( p->pRight ){
145059      mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
145060      assert( p->x.pList==0 );
145061    }else if( ExprHasProperty(p, EP_xIsSelect) ){
145062      if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
145063      mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
145064    }else if( p->x.pList ){
145065      mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
145066    }
145067    return mask;
145068  }
145069  SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
145070    return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
145071  }
145072  SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
145073    int i;
145074    Bitmask mask = 0;
145075    if( pList ){
145076      for(i=0; i<pList->nExpr; i++){
145077        mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
145078      }
145079    }
145080    return mask;
145081  }
145082  
145083  
145084  /*
145085  ** Call exprAnalyze on all terms in a WHERE clause.  
145086  **
145087  ** Note that exprAnalyze() might add new virtual terms onto the
145088  ** end of the WHERE clause.  We do not want to analyze these new
145089  ** virtual terms, so start analyzing at the end and work forward
145090  ** so that the added virtual terms are never processed.
145091  */
145092  SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
145093    SrcList *pTabList,       /* the FROM clause */
145094    WhereClause *pWC         /* the WHERE clause to be analyzed */
145095  ){
145096    int i;
145097    for(i=pWC->nTerm-1; i>=0; i--){
145098      exprAnalyze(pTabList, pWC, i);
145099    }
145100  }
145101  
145102  /*
145103  ** For table-valued-functions, transform the function arguments into
145104  ** new WHERE clause terms.  
145105  **
145106  ** Each function argument translates into an equality constraint against
145107  ** a HIDDEN column in the table.
145108  */
145109  SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
145110    Parse *pParse,                    /* Parsing context */
145111    struct SrcList_item *pItem,       /* The FROM clause term to process */
145112    WhereClause *pWC                  /* Xfer function arguments to here */
145113  ){
145114    Table *pTab;
145115    int j, k;
145116    ExprList *pArgs;
145117    Expr *pColRef;
145118    Expr *pTerm;
145119    if( pItem->fg.isTabFunc==0 ) return;
145120    pTab = pItem->pTab;
145121    assert( pTab!=0 );
145122    pArgs = pItem->u1.pFuncArg;
145123    if( pArgs==0 ) return;
145124    for(j=k=0; j<pArgs->nExpr; j++){
145125      Expr *pRhs;
145126      while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
145127      if( k>=pTab->nCol ){
145128        sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
145129                        pTab->zName, j);
145130        return;
145131      }
145132      pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
145133      if( pColRef==0 ) return;
145134      pColRef->iTable = pItem->iCursor;
145135      pColRef->iColumn = k++;
145136      pColRef->y.pTab = pTab;
145137      pRhs = sqlite3PExpr(pParse, TK_UPLUS, 
145138          sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
145139      pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
145140      whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
145141    }
145142  }
145143  
145144  /************** End of whereexpr.c *******************************************/
145145  /************** Begin file where.c *******************************************/
145146  /*
145147  ** 2001 September 15
145148  **
145149  ** The author disclaims copyright to this source code.  In place of
145150  ** a legal notice, here is a blessing:
145151  **
145152  **    May you do good and not evil.
145153  **    May you find forgiveness for yourself and forgive others.
145154  **    May you share freely, never taking more than you give.
145155  **
145156  *************************************************************************
145157  ** This module contains C code that generates VDBE code used to process
145158  ** the WHERE clause of SQL statements.  This module is responsible for
145159  ** generating the code that loops through a table looking for applicable
145160  ** rows.  Indices are selected and used to speed the search when doing
145161  ** so is applicable.  Because this module is responsible for selecting
145162  ** indices, you might also think of this module as the "query optimizer".
145163  */
145164  /* #include "sqliteInt.h" */
145165  /* #include "whereInt.h" */
145166  
145167  /*
145168  ** Extra information appended to the end of sqlite3_index_info but not
145169  ** visible to the xBestIndex function, at least not directly.  The
145170  ** sqlite3_vtab_collation() interface knows how to reach it, however.
145171  **
145172  ** This object is not an API and can be changed from one release to the
145173  ** next.  As long as allocateIndexInfo() and sqlite3_vtab_collation()
145174  ** agree on the structure, all will be well.
145175  */
145176  typedef struct HiddenIndexInfo HiddenIndexInfo;
145177  struct HiddenIndexInfo {
145178    WhereClause *pWC;   /* The Where clause being analyzed */
145179    Parse *pParse;      /* The parsing context */
145180  };
145181  
145182  /* Forward declaration of methods */
145183  static int whereLoopResize(sqlite3*, WhereLoop*, int);
145184  
145185  /* Test variable that can be set to enable WHERE tracing */
145186  #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
145187  /***/ int sqlite3WhereTrace = 0;
145188  #endif
145189  
145190  
145191  /*
145192  ** Return the estimated number of output rows from a WHERE clause
145193  */
145194  SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
145195    return pWInfo->nRowOut;
145196  }
145197  
145198  /*
145199  ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
145200  ** WHERE clause returns outputs for DISTINCT processing.
145201  */
145202  SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
145203    return pWInfo->eDistinct;
145204  }
145205  
145206  /*
145207  ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
145208  ** Return FALSE if the output needs to be sorted.
145209  */
145210  SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
145211    return pWInfo->nOBSat;
145212  }
145213  
145214  /*
145215  ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
145216  ** to emit rows in increasing order, and if the last row emitted by the
145217  ** inner-most loop did not fit within the sorter, then we can skip all
145218  ** subsequent rows for the current iteration of the inner loop (because they
145219  ** will not fit in the sorter either) and continue with the second inner
145220  ** loop - the loop immediately outside the inner-most.
145221  **
145222  ** When a row does not fit in the sorter (because the sorter already
145223  ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
145224  ** label returned by this function.
145225  **
145226  ** If the ORDER BY LIMIT optimization applies, the jump destination should
145227  ** be the continuation for the second-inner-most loop.  If the ORDER BY
145228  ** LIMIT optimization does not apply, then the jump destination should
145229  ** be the continuation for the inner-most loop.
145230  **
145231  ** It is always safe for this routine to return the continuation of the
145232  ** inner-most loop, in the sense that a correct answer will result.  
145233  ** Returning the continuation the second inner loop is an optimization
145234  ** that might make the code run a little faster, but should not change
145235  ** the final answer.
145236  */
145237  SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
145238    WhereLevel *pInner;
145239    if( !pWInfo->bOrderedInnerLoop ){
145240      /* The ORDER BY LIMIT optimization does not apply.  Jump to the 
145241      ** continuation of the inner-most loop. */
145242      return pWInfo->iContinue;
145243    }
145244    pInner = &pWInfo->a[pWInfo->nLevel-1];
145245    assert( pInner->addrNxt!=0 );
145246    return pInner->addrNxt;
145247  }
145248  
145249  /*
145250  ** Return the VDBE address or label to jump to in order to continue
145251  ** immediately with the next row of a WHERE clause.
145252  */
145253  SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
145254    assert( pWInfo->iContinue!=0 );
145255    return pWInfo->iContinue;
145256  }
145257  
145258  /*
145259  ** Return the VDBE address or label to jump to in order to break
145260  ** out of a WHERE loop.
145261  */
145262  SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
145263    return pWInfo->iBreak;
145264  }
145265  
145266  /*
145267  ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
145268  ** operate directly on the rowis returned by a WHERE clause.  Return
145269  ** ONEPASS_SINGLE (1) if the statement can operation directly because only
145270  ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
145271  ** optimization can be used on multiple 
145272  **
145273  ** If the ONEPASS optimization is used (if this routine returns true)
145274  ** then also write the indices of open cursors used by ONEPASS
145275  ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
145276  ** table and iaCur[1] gets the cursor used by an auxiliary index.
145277  ** Either value may be -1, indicating that cursor is not used.
145278  ** Any cursors returned will have been opened for writing.
145279  **
145280  ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
145281  ** unable to use the ONEPASS optimization.
145282  */
145283  SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
145284    memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
145285  #ifdef WHERETRACE_ENABLED
145286    if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
145287      sqlite3DebugPrintf("%s cursors: %d %d\n",
145288           pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
145289           aiCur[0], aiCur[1]);
145290    }
145291  #endif
145292    return pWInfo->eOnePass;
145293  }
145294  
145295  /*
145296  ** Move the content of pSrc into pDest
145297  */
145298  static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
145299    pDest->n = pSrc->n;
145300    memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
145301  }
145302  
145303  /*
145304  ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
145305  **
145306  ** The new entry might overwrite an existing entry, or it might be
145307  ** appended, or it might be discarded.  Do whatever is the right thing
145308  ** so that pSet keeps the N_OR_COST best entries seen so far.
145309  */
145310  static int whereOrInsert(
145311    WhereOrSet *pSet,      /* The WhereOrSet to be updated */
145312    Bitmask prereq,        /* Prerequisites of the new entry */
145313    LogEst rRun,           /* Run-cost of the new entry */
145314    LogEst nOut            /* Number of outputs for the new entry */
145315  ){
145316    u16 i;
145317    WhereOrCost *p;
145318    for(i=pSet->n, p=pSet->a; i>0; i--, p++){
145319      if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
145320        goto whereOrInsert_done;
145321      }
145322      if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
145323        return 0;
145324      }
145325    }
145326    if( pSet->n<N_OR_COST ){
145327      p = &pSet->a[pSet->n++];
145328      p->nOut = nOut;
145329    }else{
145330      p = pSet->a;
145331      for(i=1; i<pSet->n; i++){
145332        if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
145333      }
145334      if( p->rRun<=rRun ) return 0;
145335    }
145336  whereOrInsert_done:
145337    p->prereq = prereq;
145338    p->rRun = rRun;
145339    if( p->nOut>nOut ) p->nOut = nOut;
145340    return 1;
145341  }
145342  
145343  /*
145344  ** Return the bitmask for the given cursor number.  Return 0 if
145345  ** iCursor is not in the set.
145346  */
145347  SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
145348    int i;
145349    assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
145350    for(i=0; i<pMaskSet->n; i++){
145351      if( pMaskSet->ix[i]==iCursor ){
145352        return MASKBIT(i);
145353      }
145354    }
145355    return 0;
145356  }
145357  
145358  /*
145359  ** Create a new mask for cursor iCursor.
145360  **
145361  ** There is one cursor per table in the FROM clause.  The number of
145362  ** tables in the FROM clause is limited by a test early in the
145363  ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
145364  ** array will never overflow.
145365  */
145366  static void createMask(WhereMaskSet *pMaskSet, int iCursor){
145367    assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
145368    pMaskSet->ix[pMaskSet->n++] = iCursor;
145369  }
145370  
145371  /*
145372  ** Advance to the next WhereTerm that matches according to the criteria
145373  ** established when the pScan object was initialized by whereScanInit().
145374  ** Return NULL if there are no more matching WhereTerms.
145375  */
145376  static WhereTerm *whereScanNext(WhereScan *pScan){
145377    int iCur;            /* The cursor on the LHS of the term */
145378    i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
145379    Expr *pX;            /* An expression being tested */
145380    WhereClause *pWC;    /* Shorthand for pScan->pWC */
145381    WhereTerm *pTerm;    /* The term being tested */
145382    int k = pScan->k;    /* Where to start scanning */
145383  
145384    assert( pScan->iEquiv<=pScan->nEquiv );
145385    pWC = pScan->pWC;
145386    while(1){
145387      iColumn = pScan->aiColumn[pScan->iEquiv-1];
145388      iCur = pScan->aiCur[pScan->iEquiv-1];
145389      assert( pWC!=0 );
145390      do{
145391        for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
145392          if( pTerm->leftCursor==iCur
145393           && pTerm->u.leftColumn==iColumn
145394           && (iColumn!=XN_EXPR
145395               || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
145396                                         pScan->pIdxExpr,iCur)==0)
145397           && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
145398          ){
145399            if( (pTerm->eOperator & WO_EQUIV)!=0
145400             && pScan->nEquiv<ArraySize(pScan->aiCur)
145401             && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
145402            ){
145403              int j;
145404              for(j=0; j<pScan->nEquiv; j++){
145405                if( pScan->aiCur[j]==pX->iTable
145406                 && pScan->aiColumn[j]==pX->iColumn ){
145407                    break;
145408                }
145409              }
145410              if( j==pScan->nEquiv ){
145411                pScan->aiCur[j] = pX->iTable;
145412                pScan->aiColumn[j] = pX->iColumn;
145413                pScan->nEquiv++;
145414              }
145415            }
145416            if( (pTerm->eOperator & pScan->opMask)!=0 ){
145417              /* Verify the affinity and collating sequence match */
145418              if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
145419                CollSeq *pColl;
145420                Parse *pParse = pWC->pWInfo->pParse;
145421                pX = pTerm->pExpr;
145422                if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
145423                  continue;
145424                }
145425                assert(pX->pLeft);
145426                pColl = sqlite3BinaryCompareCollSeq(pParse,
145427                                                    pX->pLeft, pX->pRight);
145428                if( pColl==0 ) pColl = pParse->db->pDfltColl;
145429                if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
145430                  continue;
145431                }
145432              }
145433              if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
145434               && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
145435               && pX->iTable==pScan->aiCur[0]
145436               && pX->iColumn==pScan->aiColumn[0]
145437              ){
145438                testcase( pTerm->eOperator & WO_IS );
145439                continue;
145440              }
145441              pScan->pWC = pWC;
145442              pScan->k = k+1;
145443              return pTerm;
145444            }
145445          }
145446        }
145447        pWC = pWC->pOuter;
145448        k = 0;
145449      }while( pWC!=0 );
145450      if( pScan->iEquiv>=pScan->nEquiv ) break;
145451      pWC = pScan->pOrigWC;
145452      k = 0;
145453      pScan->iEquiv++;
145454    }
145455    return 0;
145456  }
145457  
145458  /*
145459  ** This is whereScanInit() for the case of an index on an expression.
145460  ** It is factored out into a separate tail-recursion subroutine so that
145461  ** the normal whereScanInit() routine, which is a high-runner, does not
145462  ** need to push registers onto the stack as part of its prologue.
145463  */
145464  static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
145465    pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
145466    return whereScanNext(pScan);
145467  }
145468  
145469  /*
145470  ** Initialize a WHERE clause scanner object.  Return a pointer to the
145471  ** first match.  Return NULL if there are no matches.
145472  **
145473  ** The scanner will be searching the WHERE clause pWC.  It will look
145474  ** for terms of the form "X <op> <expr>" where X is column iColumn of table
145475  ** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
145476  ** must be one of the indexes of table iCur.
145477  **
145478  ** The <op> must be one of the operators described by opMask.
145479  **
145480  ** If the search is for X and the WHERE clause contains terms of the
145481  ** form X=Y then this routine might also return terms of the form
145482  ** "Y <op> <expr>".  The number of levels of transitivity is limited,
145483  ** but is enough to handle most commonly occurring SQL statements.
145484  **
145485  ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
145486  ** index pIdx.
145487  */
145488  static WhereTerm *whereScanInit(
145489    WhereScan *pScan,       /* The WhereScan object being initialized */
145490    WhereClause *pWC,       /* The WHERE clause to be scanned */
145491    int iCur,               /* Cursor to scan for */
145492    int iColumn,            /* Column to scan for */
145493    u32 opMask,             /* Operator(s) to scan for */
145494    Index *pIdx             /* Must be compatible with this index */
145495  ){
145496    pScan->pOrigWC = pWC;
145497    pScan->pWC = pWC;
145498    pScan->pIdxExpr = 0;
145499    pScan->idxaff = 0;
145500    pScan->zCollName = 0;
145501    pScan->opMask = opMask;
145502    pScan->k = 0;
145503    pScan->aiCur[0] = iCur;
145504    pScan->nEquiv = 1;
145505    pScan->iEquiv = 1;
145506    if( pIdx ){
145507      int j = iColumn;
145508      iColumn = pIdx->aiColumn[j];
145509      if( iColumn==XN_EXPR ){
145510        pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
145511        pScan->zCollName = pIdx->azColl[j];
145512        pScan->aiColumn[0] = XN_EXPR;
145513        return whereScanInitIndexExpr(pScan);
145514      }else if( iColumn==pIdx->pTable->iPKey ){
145515        iColumn = XN_ROWID;
145516      }else if( iColumn>=0 ){
145517        pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
145518        pScan->zCollName = pIdx->azColl[j];
145519      }
145520    }else if( iColumn==XN_EXPR ){
145521      return 0;
145522    }
145523    pScan->aiColumn[0] = iColumn;
145524    return whereScanNext(pScan);
145525  }
145526  
145527  /*
145528  ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
145529  ** where X is a reference to the iColumn of table iCur or of index pIdx
145530  ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
145531  ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
145532  **
145533  ** If pIdx!=0 then it must be one of the indexes of table iCur.  
145534  ** Search for terms matching the iColumn-th column of pIdx
145535  ** rather than the iColumn-th column of table iCur.
145536  **
145537  ** The term returned might by Y=<expr> if there is another constraint in
145538  ** the WHERE clause that specifies that X=Y.  Any such constraints will be
145539  ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
145540  ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
145541  ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
145542  ** other equivalent values.  Hence a search for X will return <expr> if X=A1
145543  ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
145544  **
145545  ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
145546  ** then try for the one with no dependencies on <expr> - in other words where
145547  ** <expr> is a constant expression of some kind.  Only return entries of
145548  ** the form "X <op> Y" where Y is a column in another table if no terms of
145549  ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
145550  ** exist, try to return a term that does not use WO_EQUIV.
145551  */
145552  SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
145553    WhereClause *pWC,     /* The WHERE clause to be searched */
145554    int iCur,             /* Cursor number of LHS */
145555    int iColumn,          /* Column number of LHS */
145556    Bitmask notReady,     /* RHS must not overlap with this mask */
145557    u32 op,               /* Mask of WO_xx values describing operator */
145558    Index *pIdx           /* Must be compatible with this index, if not NULL */
145559  ){
145560    WhereTerm *pResult = 0;
145561    WhereTerm *p;
145562    WhereScan scan;
145563  
145564    p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
145565    op &= WO_EQ|WO_IS;
145566    while( p ){
145567      if( (p->prereqRight & notReady)==0 ){
145568        if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
145569          testcase( p->eOperator & WO_IS );
145570          return p;
145571        }
145572        if( pResult==0 ) pResult = p;
145573      }
145574      p = whereScanNext(&scan);
145575    }
145576    return pResult;
145577  }
145578  
145579  /*
145580  ** This function searches pList for an entry that matches the iCol-th column
145581  ** of index pIdx.
145582  **
145583  ** If such an expression is found, its index in pList->a[] is returned. If
145584  ** no expression is found, -1 is returned.
145585  */
145586  static int findIndexCol(
145587    Parse *pParse,                  /* Parse context */
145588    ExprList *pList,                /* Expression list to search */
145589    int iBase,                      /* Cursor for table associated with pIdx */
145590    Index *pIdx,                    /* Index to match column of */
145591    int iCol                        /* Column of index to match */
145592  ){
145593    int i;
145594    const char *zColl = pIdx->azColl[iCol];
145595  
145596    for(i=0; i<pList->nExpr; i++){
145597      Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
145598      if( p->op==TK_COLUMN
145599       && p->iColumn==pIdx->aiColumn[iCol]
145600       && p->iTable==iBase
145601      ){
145602        CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
145603        if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
145604          return i;
145605        }
145606      }
145607    }
145608  
145609    return -1;
145610  }
145611  
145612  /*
145613  ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
145614  */
145615  static int indexColumnNotNull(Index *pIdx, int iCol){
145616    int j;
145617    assert( pIdx!=0 );
145618    assert( iCol>=0 && iCol<pIdx->nColumn );
145619    j = pIdx->aiColumn[iCol];
145620    if( j>=0 ){
145621      return pIdx->pTable->aCol[j].notNull;
145622    }else if( j==(-1) ){
145623      return 1;
145624    }else{
145625      assert( j==(-2) );
145626      return 0;  /* Assume an indexed expression can always yield a NULL */
145627  
145628    }
145629  }
145630  
145631  /*
145632  ** Return true if the DISTINCT expression-list passed as the third argument
145633  ** is redundant.
145634  **
145635  ** A DISTINCT list is redundant if any subset of the columns in the
145636  ** DISTINCT list are collectively unique and individually non-null.
145637  */
145638  static int isDistinctRedundant(
145639    Parse *pParse,            /* Parsing context */
145640    SrcList *pTabList,        /* The FROM clause */
145641    WhereClause *pWC,         /* The WHERE clause */
145642    ExprList *pDistinct       /* The result set that needs to be DISTINCT */
145643  ){
145644    Table *pTab;
145645    Index *pIdx;
145646    int i;                          
145647    int iBase;
145648  
145649    /* If there is more than one table or sub-select in the FROM clause of
145650    ** this query, then it will not be possible to show that the DISTINCT 
145651    ** clause is redundant. */
145652    if( pTabList->nSrc!=1 ) return 0;
145653    iBase = pTabList->a[0].iCursor;
145654    pTab = pTabList->a[0].pTab;
145655  
145656    /* If any of the expressions is an IPK column on table iBase, then return 
145657    ** true. Note: The (p->iTable==iBase) part of this test may be false if the
145658    ** current SELECT is a correlated sub-query.
145659    */
145660    for(i=0; i<pDistinct->nExpr; i++){
145661      Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
145662      if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
145663    }
145664  
145665    /* Loop through all indices on the table, checking each to see if it makes
145666    ** the DISTINCT qualifier redundant. It does so if:
145667    **
145668    **   1. The index is itself UNIQUE, and
145669    **
145670    **   2. All of the columns in the index are either part of the pDistinct
145671    **      list, or else the WHERE clause contains a term of the form "col=X",
145672    **      where X is a constant value. The collation sequences of the
145673    **      comparison and select-list expressions must match those of the index.
145674    **
145675    **   3. All of those index columns for which the WHERE clause does not
145676    **      contain a "col=X" term are subject to a NOT NULL constraint.
145677    */
145678    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
145679      if( !IsUniqueIndex(pIdx) ) continue;
145680      for(i=0; i<pIdx->nKeyCol; i++){
145681        if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
145682          if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
145683          if( indexColumnNotNull(pIdx, i)==0 ) break;
145684        }
145685      }
145686      if( i==pIdx->nKeyCol ){
145687        /* This index implies that the DISTINCT qualifier is redundant. */
145688        return 1;
145689      }
145690    }
145691  
145692    return 0;
145693  }
145694  
145695  
145696  /*
145697  ** Estimate the logarithm of the input value to base 2.
145698  */
145699  static LogEst estLog(LogEst N){
145700    return N<=10 ? 0 : sqlite3LogEst(N) - 33;
145701  }
145702  
145703  /*
145704  ** Convert OP_Column opcodes to OP_Copy in previously generated code.
145705  **
145706  ** This routine runs over generated VDBE code and translates OP_Column
145707  ** opcodes into OP_Copy when the table is being accessed via co-routine 
145708  ** instead of via table lookup.
145709  **
145710  ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
145711  ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
145712  ** then each OP_Rowid is transformed into an instruction to increment the
145713  ** value stored in its output register.
145714  */
145715  static void translateColumnToCopy(
145716    Parse *pParse,      /* Parsing context */
145717    int iStart,         /* Translate from this opcode to the end */
145718    int iTabCur,        /* OP_Column/OP_Rowid references to this table */
145719    int iRegister,      /* The first column is in this register */
145720    int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
145721  ){
145722    Vdbe *v = pParse->pVdbe;
145723    VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
145724    int iEnd = sqlite3VdbeCurrentAddr(v);
145725    if( pParse->db->mallocFailed ) return;
145726    for(; iStart<iEnd; iStart++, pOp++){
145727      if( pOp->p1!=iTabCur ) continue;
145728      if( pOp->opcode==OP_Column ){
145729        pOp->opcode = OP_Copy;
145730        pOp->p1 = pOp->p2 + iRegister;
145731        pOp->p2 = pOp->p3;
145732        pOp->p3 = 0;
145733      }else if( pOp->opcode==OP_Rowid ){
145734        if( bIncrRowid ){
145735          /* Increment the value stored in the P2 operand of the OP_Rowid. */
145736          pOp->opcode = OP_AddImm;
145737          pOp->p1 = pOp->p2;
145738          pOp->p2 = 1;
145739        }else{
145740          pOp->opcode = OP_Null;
145741          pOp->p1 = 0;
145742          pOp->p3 = 0;
145743        }
145744      }
145745    }
145746  }
145747  
145748  /*
145749  ** Two routines for printing the content of an sqlite3_index_info
145750  ** structure.  Used for testing and debugging only.  If neither
145751  ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
145752  ** are no-ops.
145753  */
145754  #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
145755  static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
145756    int i;
145757    if( !sqlite3WhereTrace ) return;
145758    for(i=0; i<p->nConstraint; i++){
145759      sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
145760         i,
145761         p->aConstraint[i].iColumn,
145762         p->aConstraint[i].iTermOffset,
145763         p->aConstraint[i].op,
145764         p->aConstraint[i].usable);
145765    }
145766    for(i=0; i<p->nOrderBy; i++){
145767      sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
145768         i,
145769         p->aOrderBy[i].iColumn,
145770         p->aOrderBy[i].desc);
145771    }
145772  }
145773  static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
145774    int i;
145775    if( !sqlite3WhereTrace ) return;
145776    for(i=0; i<p->nConstraint; i++){
145777      sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
145778         i,
145779         p->aConstraintUsage[i].argvIndex,
145780         p->aConstraintUsage[i].omit);
145781    }
145782    sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
145783    sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
145784    sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
145785    sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
145786    sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
145787  }
145788  #else
145789  #define TRACE_IDX_INPUTS(A)
145790  #define TRACE_IDX_OUTPUTS(A)
145791  #endif
145792  
145793  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
145794  /*
145795  ** Return TRUE if the WHERE clause term pTerm is of a form where it
145796  ** could be used with an index to access pSrc, assuming an appropriate
145797  ** index existed.
145798  */
145799  static int termCanDriveIndex(
145800    WhereTerm *pTerm,              /* WHERE clause term to check */
145801    struct SrcList_item *pSrc,     /* Table we are trying to access */
145802    Bitmask notReady               /* Tables in outer loops of the join */
145803  ){
145804    char aff;
145805    if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
145806    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
145807    if( (pSrc->fg.jointype & JT_LEFT) 
145808     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
145809     && (pTerm->eOperator & WO_IS)
145810    ){
145811      /* Cannot use an IS term from the WHERE clause as an index driver for
145812      ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
145813      ** the ON clause.  */
145814      return 0;
145815    }
145816    if( (pTerm->prereqRight & notReady)!=0 ) return 0;
145817    if( pTerm->u.leftColumn<0 ) return 0;
145818    aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
145819    if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
145820    testcase( pTerm->pExpr->op==TK_IS );
145821    return 1;
145822  }
145823  #endif
145824  
145825  
145826  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
145827  /*
145828  ** Generate code to construct the Index object for an automatic index
145829  ** and to set up the WhereLevel object pLevel so that the code generator
145830  ** makes use of the automatic index.
145831  */
145832  static void constructAutomaticIndex(
145833    Parse *pParse,              /* The parsing context */
145834    WhereClause *pWC,           /* The WHERE clause */
145835    struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
145836    Bitmask notReady,           /* Mask of cursors that are not available */
145837    WhereLevel *pLevel          /* Write new index here */
145838  ){
145839    int nKeyCol;                /* Number of columns in the constructed index */
145840    WhereTerm *pTerm;           /* A single term of the WHERE clause */
145841    WhereTerm *pWCEnd;          /* End of pWC->a[] */
145842    Index *pIdx;                /* Object describing the transient index */
145843    Vdbe *v;                    /* Prepared statement under construction */
145844    int addrInit;               /* Address of the initialization bypass jump */
145845    Table *pTable;              /* The table being indexed */
145846    int addrTop;                /* Top of the index fill loop */
145847    int regRecord;              /* Register holding an index record */
145848    int n;                      /* Column counter */
145849    int i;                      /* Loop counter */
145850    int mxBitCol;               /* Maximum column in pSrc->colUsed */
145851    CollSeq *pColl;             /* Collating sequence to on a column */
145852    WhereLoop *pLoop;           /* The Loop object */
145853    char *zNotUsed;             /* Extra space on the end of pIdx */
145854    Bitmask idxCols;            /* Bitmap of columns used for indexing */
145855    Bitmask extraCols;          /* Bitmap of additional columns */
145856    u8 sentWarning = 0;         /* True if a warnning has been issued */
145857    Expr *pPartial = 0;         /* Partial Index Expression */
145858    int iContinue = 0;          /* Jump here to skip excluded rows */
145859    struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
145860    int addrCounter = 0;        /* Address where integer counter is initialized */
145861    int regBase;                /* Array of registers where record is assembled */
145862  
145863    /* Generate code to skip over the creation and initialization of the
145864    ** transient index on 2nd and subsequent iterations of the loop. */
145865    v = pParse->pVdbe;
145866    assert( v!=0 );
145867    addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
145868  
145869    /* Count the number of columns that will be added to the index
145870    ** and used to match WHERE clause constraints */
145871    nKeyCol = 0;
145872    pTable = pSrc->pTab;
145873    pWCEnd = &pWC->a[pWC->nTerm];
145874    pLoop = pLevel->pWLoop;
145875    idxCols = 0;
145876    for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
145877      Expr *pExpr = pTerm->pExpr;
145878      assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
145879           || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
145880           || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
145881      if( pLoop->prereq==0
145882       && (pTerm->wtFlags & TERM_VIRTUAL)==0
145883       && !ExprHasProperty(pExpr, EP_FromJoin)
145884       && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
145885        pPartial = sqlite3ExprAnd(pParse->db, pPartial,
145886                                  sqlite3ExprDup(pParse->db, pExpr, 0));
145887      }
145888      if( termCanDriveIndex(pTerm, pSrc, notReady) ){
145889        int iCol = pTerm->u.leftColumn;
145890        Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
145891        testcase( iCol==BMS );
145892        testcase( iCol==BMS-1 );
145893        if( !sentWarning ){
145894          sqlite3_log(SQLITE_WARNING_AUTOINDEX,
145895              "automatic index on %s(%s)", pTable->zName,
145896              pTable->aCol[iCol].zName);
145897          sentWarning = 1;
145898        }
145899        if( (idxCols & cMask)==0 ){
145900          if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
145901            goto end_auto_index_create;
145902          }
145903          pLoop->aLTerm[nKeyCol++] = pTerm;
145904          idxCols |= cMask;
145905        }
145906      }
145907    }
145908    assert( nKeyCol>0 );
145909    pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
145910    pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
145911                       | WHERE_AUTO_INDEX;
145912  
145913    /* Count the number of additional columns needed to create a
145914    ** covering index.  A "covering index" is an index that contains all
145915    ** columns that are needed by the query.  With a covering index, the
145916    ** original table never needs to be accessed.  Automatic indices must
145917    ** be a covering index because the index will not be updated if the
145918    ** original table changes and the index and table cannot both be used
145919    ** if they go out of sync.
145920    */
145921    extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
145922    mxBitCol = MIN(BMS-1,pTable->nCol);
145923    testcase( pTable->nCol==BMS-1 );
145924    testcase( pTable->nCol==BMS-2 );
145925    for(i=0; i<mxBitCol; i++){
145926      if( extraCols & MASKBIT(i) ) nKeyCol++;
145927    }
145928    if( pSrc->colUsed & MASKBIT(BMS-1) ){
145929      nKeyCol += pTable->nCol - BMS + 1;
145930    }
145931  
145932    /* Construct the Index object to describe this index */
145933    pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
145934    if( pIdx==0 ) goto end_auto_index_create;
145935    pLoop->u.btree.pIndex = pIdx;
145936    pIdx->zName = "auto-index";
145937    pIdx->pTable = pTable;
145938    n = 0;
145939    idxCols = 0;
145940    for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
145941      if( termCanDriveIndex(pTerm, pSrc, notReady) ){
145942        int iCol = pTerm->u.leftColumn;
145943        Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
145944        testcase( iCol==BMS-1 );
145945        testcase( iCol==BMS );
145946        if( (idxCols & cMask)==0 ){
145947          Expr *pX = pTerm->pExpr;
145948          idxCols |= cMask;
145949          pIdx->aiColumn[n] = pTerm->u.leftColumn;
145950          pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
145951          pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
145952          n++;
145953        }
145954      }
145955    }
145956    assert( (u32)n==pLoop->u.btree.nEq );
145957  
145958    /* Add additional columns needed to make the automatic index into
145959    ** a covering index */
145960    for(i=0; i<mxBitCol; i++){
145961      if( extraCols & MASKBIT(i) ){
145962        pIdx->aiColumn[n] = i;
145963        pIdx->azColl[n] = sqlite3StrBINARY;
145964        n++;
145965      }
145966    }
145967    if( pSrc->colUsed & MASKBIT(BMS-1) ){
145968      for(i=BMS-1; i<pTable->nCol; i++){
145969        pIdx->aiColumn[n] = i;
145970        pIdx->azColl[n] = sqlite3StrBINARY;
145971        n++;
145972      }
145973    }
145974    assert( n==nKeyCol );
145975    pIdx->aiColumn[n] = XN_ROWID;
145976    pIdx->azColl[n] = sqlite3StrBINARY;
145977  
145978    /* Create the automatic index */
145979    assert( pLevel->iIdxCur>=0 );
145980    pLevel->iIdxCur = pParse->nTab++;
145981    sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
145982    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
145983    VdbeComment((v, "for %s", pTable->zName));
145984  
145985    /* Fill the automatic index with content */
145986    pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
145987    if( pTabItem->fg.viaCoroutine ){
145988      int regYield = pTabItem->regReturn;
145989      addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
145990      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
145991      addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
145992      VdbeCoverage(v);
145993      VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
145994    }else{
145995      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
145996    }
145997    if( pPartial ){
145998      iContinue = sqlite3VdbeMakeLabel(pParse);
145999      sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
146000      pLoop->wsFlags |= WHERE_PARTIALIDX;
146001    }
146002    regRecord = sqlite3GetTempReg(pParse);
146003    regBase = sqlite3GenerateIndexKey(
146004        pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
146005    );
146006    sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
146007    sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
146008    if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
146009    if( pTabItem->fg.viaCoroutine ){
146010      sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
146011      testcase( pParse->db->mallocFailed );
146012      translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
146013                            pTabItem->regResult, 1);
146014      sqlite3VdbeGoto(v, addrTop);
146015      pTabItem->fg.viaCoroutine = 0;
146016    }else{
146017      sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
146018    }
146019    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
146020    sqlite3VdbeJumpHere(v, addrTop);
146021    sqlite3ReleaseTempReg(pParse, regRecord);
146022    
146023    /* Jump here when skipping the initialization */
146024    sqlite3VdbeJumpHere(v, addrInit);
146025  
146026  end_auto_index_create:
146027    sqlite3ExprDelete(pParse->db, pPartial);
146028  }
146029  #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
146030  
146031  #ifndef SQLITE_OMIT_VIRTUALTABLE
146032  /*
146033  ** Allocate and populate an sqlite3_index_info structure. It is the 
146034  ** responsibility of the caller to eventually release the structure
146035  ** by passing the pointer returned by this function to sqlite3_free().
146036  */
146037  static sqlite3_index_info *allocateIndexInfo(
146038    Parse *pParse,                  /* The parsing context */
146039    WhereClause *pWC,               /* The WHERE clause being analyzed */
146040    Bitmask mUnusable,              /* Ignore terms with these prereqs */
146041    struct SrcList_item *pSrc,      /* The FROM clause term that is the vtab */
146042    ExprList *pOrderBy,             /* The ORDER BY clause */
146043    u16 *pmNoOmit                   /* Mask of terms not to omit */
146044  ){
146045    int i, j;
146046    int nTerm;
146047    struct sqlite3_index_constraint *pIdxCons;
146048    struct sqlite3_index_orderby *pIdxOrderBy;
146049    struct sqlite3_index_constraint_usage *pUsage;
146050    struct HiddenIndexInfo *pHidden;
146051    WhereTerm *pTerm;
146052    int nOrderBy;
146053    sqlite3_index_info *pIdxInfo;
146054    u16 mNoOmit = 0;
146055  
146056    /* Count the number of possible WHERE clause constraints referring
146057    ** to this virtual table */
146058    for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
146059      if( pTerm->leftCursor != pSrc->iCursor ) continue;
146060      if( pTerm->prereqRight & mUnusable ) continue;
146061      assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
146062      testcase( pTerm->eOperator & WO_IN );
146063      testcase( pTerm->eOperator & WO_ISNULL );
146064      testcase( pTerm->eOperator & WO_IS );
146065      testcase( pTerm->eOperator & WO_ALL );
146066      if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
146067      if( pTerm->wtFlags & TERM_VNULL ) continue;
146068      assert( pTerm->u.leftColumn>=(-1) );
146069      nTerm++;
146070    }
146071  
146072    /* If the ORDER BY clause contains only columns in the current 
146073    ** virtual table then allocate space for the aOrderBy part of
146074    ** the sqlite3_index_info structure.
146075    */
146076    nOrderBy = 0;
146077    if( pOrderBy ){
146078      int n = pOrderBy->nExpr;
146079      for(i=0; i<n; i++){
146080        Expr *pExpr = pOrderBy->a[i].pExpr;
146081        if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
146082      }
146083      if( i==n){
146084        nOrderBy = n;
146085      }
146086    }
146087  
146088    /* Allocate the sqlite3_index_info structure
146089    */
146090    pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
146091                             + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
146092                             + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
146093    if( pIdxInfo==0 ){
146094      sqlite3ErrorMsg(pParse, "out of memory");
146095      return 0;
146096    }
146097  
146098    /* Initialize the structure.  The sqlite3_index_info structure contains
146099    ** many fields that are declared "const" to prevent xBestIndex from
146100    ** changing them.  We have to do some funky casting in order to
146101    ** initialize those fields.
146102    */
146103    pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
146104    pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
146105    pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
146106    pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
146107    *(int*)&pIdxInfo->nConstraint = nTerm;
146108    *(int*)&pIdxInfo->nOrderBy = nOrderBy;
146109    *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
146110    *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
146111    *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
146112                                                                     pUsage;
146113  
146114    pHidden->pWC = pWC;
146115    pHidden->pParse = pParse;
146116    for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
146117      u16 op;
146118      if( pTerm->leftCursor != pSrc->iCursor ) continue;
146119      if( pTerm->prereqRight & mUnusable ) continue;
146120      assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
146121      testcase( pTerm->eOperator & WO_IN );
146122      testcase( pTerm->eOperator & WO_IS );
146123      testcase( pTerm->eOperator & WO_ISNULL );
146124      testcase( pTerm->eOperator & WO_ALL );
146125      if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
146126      if( pTerm->wtFlags & TERM_VNULL ) continue;
146127      if( (pSrc->fg.jointype & JT_LEFT)!=0
146128       && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
146129       && (pTerm->eOperator & (WO_IS|WO_ISNULL))
146130      ){
146131        /* An "IS" term in the WHERE clause where the virtual table is the rhs
146132        ** of a LEFT JOIN. Do not pass this term to the virtual table
146133        ** implementation, as this can lead to incorrect results from SQL such
146134        ** as:
146135        **
146136        **   "LEFT JOIN vtab WHERE vtab.col IS NULL"  */
146137        testcase( pTerm->eOperator & WO_ISNULL );
146138        testcase( pTerm->eOperator & WO_IS );
146139        continue;
146140      }
146141      assert( pTerm->u.leftColumn>=(-1) );
146142      pIdxCons[j].iColumn = pTerm->u.leftColumn;
146143      pIdxCons[j].iTermOffset = i;
146144      op = pTerm->eOperator & WO_ALL;
146145      if( op==WO_IN ) op = WO_EQ;
146146      if( op==WO_AUX ){
146147        pIdxCons[j].op = pTerm->eMatchOp;
146148      }else if( op & (WO_ISNULL|WO_IS) ){
146149        if( op==WO_ISNULL ){
146150          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
146151        }else{
146152          pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
146153        }
146154      }else{
146155        pIdxCons[j].op = (u8)op;
146156        /* The direct assignment in the previous line is possible only because
146157        ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
146158        ** following asserts verify this fact. */
146159        assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
146160        assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
146161        assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
146162        assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
146163        assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
146164        assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
146165  
146166        if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
146167         && sqlite3ExprIsVector(pTerm->pExpr->pRight) 
146168        ){
146169          if( i<16 ) mNoOmit |= (1 << i);
146170          if( op==WO_LT ) pIdxCons[j].op = WO_LE;
146171          if( op==WO_GT ) pIdxCons[j].op = WO_GE;
146172        }
146173      }
146174  
146175      j++;
146176    }
146177    for(i=0; i<nOrderBy; i++){
146178      Expr *pExpr = pOrderBy->a[i].pExpr;
146179      pIdxOrderBy[i].iColumn = pExpr->iColumn;
146180      pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
146181    }
146182  
146183    *pmNoOmit = mNoOmit;
146184    return pIdxInfo;
146185  }
146186  
146187  /*
146188  ** The table object reference passed as the second argument to this function
146189  ** must represent a virtual table. This function invokes the xBestIndex()
146190  ** method of the virtual table with the sqlite3_index_info object that
146191  ** comes in as the 3rd argument to this function.
146192  **
146193  ** If an error occurs, pParse is populated with an error message and an
146194  ** appropriate error code is returned.  A return of SQLITE_CONSTRAINT from
146195  ** xBestIndex is not considered an error.  SQLITE_CONSTRAINT indicates that
146196  ** the current configuration of "unusable" flags in sqlite3_index_info can
146197  ** not result in a valid plan.
146198  **
146199  ** Whether or not an error is returned, it is the responsibility of the
146200  ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
146201  ** that this is required.
146202  */
146203  static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
146204    sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
146205    int rc;
146206  
146207    TRACE_IDX_INPUTS(p);
146208    rc = pVtab->pModule->xBestIndex(pVtab, p);
146209    TRACE_IDX_OUTPUTS(p);
146210  
146211    if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
146212      if( rc==SQLITE_NOMEM ){
146213        sqlite3OomFault(pParse->db);
146214      }else if( !pVtab->zErrMsg ){
146215        sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
146216      }else{
146217        sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
146218      }
146219    }
146220    sqlite3_free(pVtab->zErrMsg);
146221    pVtab->zErrMsg = 0;
146222    return rc;
146223  }
146224  #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
146225  
146226  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146227  /*
146228  ** Estimate the location of a particular key among all keys in an
146229  ** index.  Store the results in aStat as follows:
146230  **
146231  **    aStat[0]      Est. number of rows less than pRec
146232  **    aStat[1]      Est. number of rows equal to pRec
146233  **
146234  ** Return the index of the sample that is the smallest sample that
146235  ** is greater than or equal to pRec. Note that this index is not an index
146236  ** into the aSample[] array - it is an index into a virtual set of samples
146237  ** based on the contents of aSample[] and the number of fields in record 
146238  ** pRec. 
146239  */
146240  static int whereKeyStats(
146241    Parse *pParse,              /* Database connection */
146242    Index *pIdx,                /* Index to consider domain of */
146243    UnpackedRecord *pRec,       /* Vector of values to consider */
146244    int roundUp,                /* Round up if true.  Round down if false */
146245    tRowcnt *aStat              /* OUT: stats written here */
146246  ){
146247    IndexSample *aSample = pIdx->aSample;
146248    int iCol;                   /* Index of required stats in anEq[] etc. */
146249    int i;                      /* Index of first sample >= pRec */
146250    int iSample;                /* Smallest sample larger than or equal to pRec */
146251    int iMin = 0;               /* Smallest sample not yet tested */
146252    int iTest;                  /* Next sample to test */
146253    int res;                    /* Result of comparison operation */
146254    int nField;                 /* Number of fields in pRec */
146255    tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
146256  
146257  #ifndef SQLITE_DEBUG
146258    UNUSED_PARAMETER( pParse );
146259  #endif
146260    assert( pRec!=0 );
146261    assert( pIdx->nSample>0 );
146262    assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
146263  
146264    /* Do a binary search to find the first sample greater than or equal
146265    ** to pRec. If pRec contains a single field, the set of samples to search
146266    ** is simply the aSample[] array. If the samples in aSample[] contain more
146267    ** than one fields, all fields following the first are ignored.
146268    **
146269    ** If pRec contains N fields, where N is more than one, then as well as the
146270    ** samples in aSample[] (truncated to N fields), the search also has to
146271    ** consider prefixes of those samples. For example, if the set of samples
146272    ** in aSample is:
146273    **
146274    **     aSample[0] = (a, 5) 
146275    **     aSample[1] = (a, 10) 
146276    **     aSample[2] = (b, 5) 
146277    **     aSample[3] = (c, 100) 
146278    **     aSample[4] = (c, 105)
146279    **
146280    ** Then the search space should ideally be the samples above and the 
146281    ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 
146282    ** the code actually searches this set:
146283    **
146284    **     0: (a) 
146285    **     1: (a, 5) 
146286    **     2: (a, 10) 
146287    **     3: (a, 10) 
146288    **     4: (b) 
146289    **     5: (b, 5) 
146290    **     6: (c) 
146291    **     7: (c, 100) 
146292    **     8: (c, 105)
146293    **     9: (c, 105)
146294    **
146295    ** For each sample in the aSample[] array, N samples are present in the
146296    ** effective sample array. In the above, samples 0 and 1 are based on 
146297    ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
146298    **
146299    ** Often, sample i of each block of N effective samples has (i+1) fields.
146300    ** Except, each sample may be extended to ensure that it is greater than or
146301    ** equal to the previous sample in the array. For example, in the above, 
146302    ** sample 2 is the first sample of a block of N samples, so at first it 
146303    ** appears that it should be 1 field in size. However, that would make it 
146304    ** smaller than sample 1, so the binary search would not work. As a result, 
146305    ** it is extended to two fields. The duplicates that this creates do not 
146306    ** cause any problems.
146307    */
146308    nField = pRec->nField;
146309    iCol = 0;
146310    iSample = pIdx->nSample * nField;
146311    do{
146312      int iSamp;                    /* Index in aSample[] of test sample */
146313      int n;                        /* Number of fields in test sample */
146314  
146315      iTest = (iMin+iSample)/2;
146316      iSamp = iTest / nField;
146317      if( iSamp>0 ){
146318        /* The proposed effective sample is a prefix of sample aSample[iSamp].
146319        ** Specifically, the shortest prefix of at least (1 + iTest%nField) 
146320        ** fields that is greater than the previous effective sample.  */
146321        for(n=(iTest % nField) + 1; n<nField; n++){
146322          if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
146323        }
146324      }else{
146325        n = iTest + 1;
146326      }
146327  
146328      pRec->nField = n;
146329      res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
146330      if( res<0 ){
146331        iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
146332        iMin = iTest+1;
146333      }else if( res==0 && n<nField ){
146334        iLower = aSample[iSamp].anLt[n-1];
146335        iMin = iTest+1;
146336        res = -1;
146337      }else{
146338        iSample = iTest;
146339        iCol = n-1;
146340      }
146341    }while( res && iMin<iSample );
146342    i = iSample / nField;
146343  
146344  #ifdef SQLITE_DEBUG
146345    /* The following assert statements check that the binary search code
146346    ** above found the right answer. This block serves no purpose other
146347    ** than to invoke the asserts.  */
146348    if( pParse->db->mallocFailed==0 ){
146349      if( res==0 ){
146350        /* If (res==0) is true, then pRec must be equal to sample i. */
146351        assert( i<pIdx->nSample );
146352        assert( iCol==nField-1 );
146353        pRec->nField = nField;
146354        assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 
146355             || pParse->db->mallocFailed 
146356        );
146357      }else{
146358        /* Unless i==pIdx->nSample, indicating that pRec is larger than
146359        ** all samples in the aSample[] array, pRec must be smaller than the
146360        ** (iCol+1) field prefix of sample i.  */
146361        assert( i<=pIdx->nSample && i>=0 );
146362        pRec->nField = iCol+1;
146363        assert( i==pIdx->nSample 
146364             || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
146365             || pParse->db->mallocFailed );
146366  
146367        /* if i==0 and iCol==0, then record pRec is smaller than all samples
146368        ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
146369        ** be greater than or equal to the (iCol) field prefix of sample i.
146370        ** If (i>0), then pRec must also be greater than sample (i-1).  */
146371        if( iCol>0 ){
146372          pRec->nField = iCol;
146373          assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
146374               || pParse->db->mallocFailed );
146375        }
146376        if( i>0 ){
146377          pRec->nField = nField;
146378          assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
146379               || pParse->db->mallocFailed );
146380        }
146381      }
146382    }
146383  #endif /* ifdef SQLITE_DEBUG */
146384  
146385    if( res==0 ){
146386      /* Record pRec is equal to sample i */
146387      assert( iCol==nField-1 );
146388      aStat[0] = aSample[i].anLt[iCol];
146389      aStat[1] = aSample[i].anEq[iCol];
146390    }else{
146391      /* At this point, the (iCol+1) field prefix of aSample[i] is the first 
146392      ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
146393      ** is larger than all samples in the array. */
146394      tRowcnt iUpper, iGap;
146395      if( i>=pIdx->nSample ){
146396        iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
146397      }else{
146398        iUpper = aSample[i].anLt[iCol];
146399      }
146400  
146401      if( iLower>=iUpper ){
146402        iGap = 0;
146403      }else{
146404        iGap = iUpper - iLower;
146405      }
146406      if( roundUp ){
146407        iGap = (iGap*2)/3;
146408      }else{
146409        iGap = iGap/3;
146410      }
146411      aStat[0] = iLower + iGap;
146412      aStat[1] = pIdx->aAvgEq[nField-1];
146413    }
146414  
146415    /* Restore the pRec->nField value before returning.  */
146416    pRec->nField = nField;
146417    return i;
146418  }
146419  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
146420  
146421  /*
146422  ** If it is not NULL, pTerm is a term that provides an upper or lower
146423  ** bound on a range scan. Without considering pTerm, it is estimated 
146424  ** that the scan will visit nNew rows. This function returns the number
146425  ** estimated to be visited after taking pTerm into account.
146426  **
146427  ** If the user explicitly specified a likelihood() value for this term,
146428  ** then the return value is the likelihood multiplied by the number of
146429  ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
146430  ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
146431  */
146432  static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
146433    LogEst nRet = nNew;
146434    if( pTerm ){
146435      if( pTerm->truthProb<=0 ){
146436        nRet += pTerm->truthProb;
146437      }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
146438        nRet -= 20;        assert( 20==sqlite3LogEst(4) );
146439      }
146440    }
146441    return nRet;
146442  }
146443  
146444  
146445  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146446  /*
146447  ** Return the affinity for a single column of an index.
146448  */
146449  SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
146450    assert( iCol>=0 && iCol<pIdx->nColumn );
146451    if( !pIdx->zColAff ){
146452      if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
146453    }
146454    return pIdx->zColAff[iCol];
146455  }
146456  #endif
146457  
146458  
146459  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146460  /* 
146461  ** This function is called to estimate the number of rows visited by a
146462  ** range-scan on a skip-scan index. For example:
146463  **
146464  **   CREATE INDEX i1 ON t1(a, b, c);
146465  **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
146466  **
146467  ** Value pLoop->nOut is currently set to the estimated number of rows 
146468  ** visited for scanning (a=? AND b=?). This function reduces that estimate 
146469  ** by some factor to account for the (c BETWEEN ? AND ?) expression based
146470  ** on the stat4 data for the index. this scan will be peformed multiple 
146471  ** times (once for each (a,b) combination that matches a=?) is dealt with 
146472  ** by the caller.
146473  **
146474  ** It does this by scanning through all stat4 samples, comparing values
146475  ** extracted from pLower and pUpper with the corresponding column in each
146476  ** sample. If L and U are the number of samples found to be less than or
146477  ** equal to the values extracted from pLower and pUpper respectively, and
146478  ** N is the total number of samples, the pLoop->nOut value is adjusted
146479  ** as follows:
146480  **
146481  **   nOut = nOut * ( min(U - L, 1) / N )
146482  **
146483  ** If pLower is NULL, or a value cannot be extracted from the term, L is
146484  ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
146485  ** U is set to N.
146486  **
146487  ** Normally, this function sets *pbDone to 1 before returning. However,
146488  ** if no value can be extracted from either pLower or pUpper (and so the
146489  ** estimate of the number of rows delivered remains unchanged), *pbDone
146490  ** is left as is.
146491  **
146492  ** If an error occurs, an SQLite error code is returned. Otherwise, 
146493  ** SQLITE_OK.
146494  */
146495  static int whereRangeSkipScanEst(
146496    Parse *pParse,       /* Parsing & code generating context */
146497    WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
146498    WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
146499    WhereLoop *pLoop,    /* Update the .nOut value of this loop */
146500    int *pbDone          /* Set to true if at least one expr. value extracted */
146501  ){
146502    Index *p = pLoop->u.btree.pIndex;
146503    int nEq = pLoop->u.btree.nEq;
146504    sqlite3 *db = pParse->db;
146505    int nLower = -1;
146506    int nUpper = p->nSample+1;
146507    int rc = SQLITE_OK;
146508    u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
146509    CollSeq *pColl;
146510    
146511    sqlite3_value *p1 = 0;          /* Value extracted from pLower */
146512    sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
146513    sqlite3_value *pVal = 0;        /* Value extracted from record */
146514  
146515    pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
146516    if( pLower ){
146517      rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
146518      nLower = 0;
146519    }
146520    if( pUpper && rc==SQLITE_OK ){
146521      rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
146522      nUpper = p2 ? 0 : p->nSample;
146523    }
146524  
146525    if( p1 || p2 ){
146526      int i;
146527      int nDiff;
146528      for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
146529        rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
146530        if( rc==SQLITE_OK && p1 ){
146531          int res = sqlite3MemCompare(p1, pVal, pColl);
146532          if( res>=0 ) nLower++;
146533        }
146534        if( rc==SQLITE_OK && p2 ){
146535          int res = sqlite3MemCompare(p2, pVal, pColl);
146536          if( res>=0 ) nUpper++;
146537        }
146538      }
146539      nDiff = (nUpper - nLower);
146540      if( nDiff<=0 ) nDiff = 1;
146541  
146542      /* If there is both an upper and lower bound specified, and the 
146543      ** comparisons indicate that they are close together, use the fallback
146544      ** method (assume that the scan visits 1/64 of the rows) for estimating
146545      ** the number of rows visited. Otherwise, estimate the number of rows
146546      ** using the method described in the header comment for this function. */
146547      if( nDiff!=1 || pUpper==0 || pLower==0 ){
146548        int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
146549        pLoop->nOut -= nAdjust;
146550        *pbDone = 1;
146551        WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
146552                             nLower, nUpper, nAdjust*-1, pLoop->nOut));
146553      }
146554  
146555    }else{
146556      assert( *pbDone==0 );
146557    }
146558  
146559    sqlite3ValueFree(p1);
146560    sqlite3ValueFree(p2);
146561    sqlite3ValueFree(pVal);
146562  
146563    return rc;
146564  }
146565  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
146566  
146567  /*
146568  ** This function is used to estimate the number of rows that will be visited
146569  ** by scanning an index for a range of values. The range may have an upper
146570  ** bound, a lower bound, or both. The WHERE clause terms that set the upper
146571  ** and lower bounds are represented by pLower and pUpper respectively. For
146572  ** example, assuming that index p is on t1(a):
146573  **
146574  **   ... FROM t1 WHERE a > ? AND a < ? ...
146575  **                    |_____|   |_____|
146576  **                       |         |
146577  **                     pLower    pUpper
146578  **
146579  ** If either of the upper or lower bound is not present, then NULL is passed in
146580  ** place of the corresponding WhereTerm.
146581  **
146582  ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
146583  ** column subject to the range constraint. Or, equivalently, the number of
146584  ** equality constraints optimized by the proposed index scan. For example,
146585  ** assuming index p is on t1(a, b), and the SQL query is:
146586  **
146587  **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
146588  **
146589  ** then nEq is set to 1 (as the range restricted column, b, is the second 
146590  ** left-most column of the index). Or, if the query is:
146591  **
146592  **   ... FROM t1 WHERE a > ? AND a < ? ...
146593  **
146594  ** then nEq is set to 0.
146595  **
146596  ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
146597  ** number of rows that the index scan is expected to visit without 
146598  ** considering the range constraints. If nEq is 0, then *pnOut is the number of 
146599  ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
146600  ** to account for the range constraints pLower and pUpper.
146601  ** 
146602  ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
146603  ** used, a single range inequality reduces the search space by a factor of 4. 
146604  ** and a pair of constraints (x>? AND x<?) reduces the expected number of
146605  ** rows visited by a factor of 64.
146606  */
146607  static int whereRangeScanEst(
146608    Parse *pParse,       /* Parsing & code generating context */
146609    WhereLoopBuilder *pBuilder,
146610    WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
146611    WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
146612    WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
146613  ){
146614    int rc = SQLITE_OK;
146615    int nOut = pLoop->nOut;
146616    LogEst nNew;
146617  
146618  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146619    Index *p = pLoop->u.btree.pIndex;
146620    int nEq = pLoop->u.btree.nEq;
146621  
146622    if( p->nSample>0 && nEq<p->nSampleCol
146623     && OptimizationEnabled(pParse->db, SQLITE_Stat34)
146624    ){
146625      if( nEq==pBuilder->nRecValid ){
146626        UnpackedRecord *pRec = pBuilder->pRec;
146627        tRowcnt a[2];
146628        int nBtm = pLoop->u.btree.nBtm;
146629        int nTop = pLoop->u.btree.nTop;
146630  
146631        /* Variable iLower will be set to the estimate of the number of rows in 
146632        ** the index that are less than the lower bound of the range query. The
146633        ** lower bound being the concatenation of $P and $L, where $P is the
146634        ** key-prefix formed by the nEq values matched against the nEq left-most
146635        ** columns of the index, and $L is the value in pLower.
146636        **
146637        ** Or, if pLower is NULL or $L cannot be extracted from it (because it
146638        ** is not a simple variable or literal value), the lower bound of the
146639        ** range is $P. Due to a quirk in the way whereKeyStats() works, even
146640        ** if $L is available, whereKeyStats() is called for both ($P) and 
146641        ** ($P:$L) and the larger of the two returned values is used.
146642        **
146643        ** Similarly, iUpper is to be set to the estimate of the number of rows
146644        ** less than the upper bound of the range query. Where the upper bound
146645        ** is either ($P) or ($P:$U). Again, even if $U is available, both values
146646        ** of iUpper are requested of whereKeyStats() and the smaller used.
146647        **
146648        ** The number of rows between the two bounds is then just iUpper-iLower.
146649        */
146650        tRowcnt iLower;     /* Rows less than the lower bound */
146651        tRowcnt iUpper;     /* Rows less than the upper bound */
146652        int iLwrIdx = -2;   /* aSample[] for the lower bound */
146653        int iUprIdx = -1;   /* aSample[] for the upper bound */
146654  
146655        if( pRec ){
146656          testcase( pRec->nField!=pBuilder->nRecValid );
146657          pRec->nField = pBuilder->nRecValid;
146658        }
146659        /* Determine iLower and iUpper using ($P) only. */
146660        if( nEq==0 ){
146661          iLower = 0;
146662          iUpper = p->nRowEst0;
146663        }else{
146664          /* Note: this call could be optimized away - since the same values must 
146665          ** have been requested when testing key $P in whereEqualScanEst().  */
146666          whereKeyStats(pParse, p, pRec, 0, a);
146667          iLower = a[0];
146668          iUpper = a[0] + a[1];
146669        }
146670  
146671        assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
146672        assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
146673        assert( p->aSortOrder!=0 );
146674        if( p->aSortOrder[nEq] ){
146675          /* The roles of pLower and pUpper are swapped for a DESC index */
146676          SWAP(WhereTerm*, pLower, pUpper);
146677          SWAP(int, nBtm, nTop);
146678        }
146679  
146680        /* If possible, improve on the iLower estimate using ($P:$L). */
146681        if( pLower ){
146682          int n;                    /* Values extracted from pExpr */
146683          Expr *pExpr = pLower->pExpr->pRight;
146684          rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
146685          if( rc==SQLITE_OK && n ){
146686            tRowcnt iNew;
146687            u16 mask = WO_GT|WO_LE;
146688            if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
146689            iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
146690            iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
146691            if( iNew>iLower ) iLower = iNew;
146692            nOut--;
146693            pLower = 0;
146694          }
146695        }
146696  
146697        /* If possible, improve on the iUpper estimate using ($P:$U). */
146698        if( pUpper ){
146699          int n;                    /* Values extracted from pExpr */
146700          Expr *pExpr = pUpper->pExpr->pRight;
146701          rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
146702          if( rc==SQLITE_OK && n ){
146703            tRowcnt iNew;
146704            u16 mask = WO_GT|WO_LE;
146705            if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
146706            iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
146707            iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
146708            if( iNew<iUpper ) iUpper = iNew;
146709            nOut--;
146710            pUpper = 0;
146711          }
146712        }
146713  
146714        pBuilder->pRec = pRec;
146715        if( rc==SQLITE_OK ){
146716          if( iUpper>iLower ){
146717            nNew = sqlite3LogEst(iUpper - iLower);
146718            /* TUNING:  If both iUpper and iLower are derived from the same
146719            ** sample, then assume they are 4x more selective.  This brings
146720            ** the estimated selectivity more in line with what it would be
146721            ** if estimated without the use of STAT3/4 tables. */
146722            if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
146723          }else{
146724            nNew = 10;        assert( 10==sqlite3LogEst(2) );
146725          }
146726          if( nNew<nOut ){
146727            nOut = nNew;
146728          }
146729          WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
146730                             (u32)iLower, (u32)iUpper, nOut));
146731        }
146732      }else{
146733        int bDone = 0;
146734        rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
146735        if( bDone ) return rc;
146736      }
146737    }
146738  #else
146739    UNUSED_PARAMETER(pParse);
146740    UNUSED_PARAMETER(pBuilder);
146741    assert( pLower || pUpper );
146742  #endif
146743    assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
146744    nNew = whereRangeAdjust(pLower, nOut);
146745    nNew = whereRangeAdjust(pUpper, nNew);
146746  
146747    /* TUNING: If there is both an upper and lower limit and neither limit
146748    ** has an application-defined likelihood(), assume the range is
146749    ** reduced by an additional 75%. This means that, by default, an open-ended
146750    ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
146751    ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
146752    ** match 1/64 of the index. */ 
146753    if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
146754      nNew -= 20;
146755    }
146756  
146757    nOut -= (pLower!=0) + (pUpper!=0);
146758    if( nNew<10 ) nNew = 10;
146759    if( nNew<nOut ) nOut = nNew;
146760  #if defined(WHERETRACE_ENABLED)
146761    if( pLoop->nOut>nOut ){
146762      WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
146763                      pLoop->nOut, nOut));
146764    }
146765  #endif
146766    pLoop->nOut = (LogEst)nOut;
146767    return rc;
146768  }
146769  
146770  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146771  /*
146772  ** Estimate the number of rows that will be returned based on
146773  ** an equality constraint x=VALUE and where that VALUE occurs in
146774  ** the histogram data.  This only works when x is the left-most
146775  ** column of an index and sqlite_stat3 histogram data is available
146776  ** for that index.  When pExpr==NULL that means the constraint is
146777  ** "x IS NULL" instead of "x=VALUE".
146778  **
146779  ** Write the estimated row count into *pnRow and return SQLITE_OK. 
146780  ** If unable to make an estimate, leave *pnRow unchanged and return
146781  ** non-zero.
146782  **
146783  ** This routine can fail if it is unable to load a collating sequence
146784  ** required for string comparison, or if unable to allocate memory
146785  ** for a UTF conversion required for comparison.  The error is stored
146786  ** in the pParse structure.
146787  */
146788  static int whereEqualScanEst(
146789    Parse *pParse,       /* Parsing & code generating context */
146790    WhereLoopBuilder *pBuilder,
146791    Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
146792    tRowcnt *pnRow       /* Write the revised row estimate here */
146793  ){
146794    Index *p = pBuilder->pNew->u.btree.pIndex;
146795    int nEq = pBuilder->pNew->u.btree.nEq;
146796    UnpackedRecord *pRec = pBuilder->pRec;
146797    int rc;                   /* Subfunction return code */
146798    tRowcnt a[2];             /* Statistics */
146799    int bOk;
146800  
146801    assert( nEq>=1 );
146802    assert( nEq<=p->nColumn );
146803    assert( p->aSample!=0 );
146804    assert( p->nSample>0 );
146805    assert( pBuilder->nRecValid<nEq );
146806  
146807    /* If values are not available for all fields of the index to the left
146808    ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
146809    if( pBuilder->nRecValid<(nEq-1) ){
146810      return SQLITE_NOTFOUND;
146811    }
146812  
146813    /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
146814    ** below would return the same value.  */
146815    if( nEq>=p->nColumn ){
146816      *pnRow = 1;
146817      return SQLITE_OK;
146818    }
146819  
146820    rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
146821    pBuilder->pRec = pRec;
146822    if( rc!=SQLITE_OK ) return rc;
146823    if( bOk==0 ) return SQLITE_NOTFOUND;
146824    pBuilder->nRecValid = nEq;
146825  
146826    whereKeyStats(pParse, p, pRec, 0, a);
146827    WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
146828                     p->zName, nEq-1, (int)a[1]));
146829    *pnRow = a[1];
146830    
146831    return rc;
146832  }
146833  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
146834  
146835  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
146836  /*
146837  ** Estimate the number of rows that will be returned based on
146838  ** an IN constraint where the right-hand side of the IN operator
146839  ** is a list of values.  Example:
146840  **
146841  **        WHERE x IN (1,2,3,4)
146842  **
146843  ** Write the estimated row count into *pnRow and return SQLITE_OK. 
146844  ** If unable to make an estimate, leave *pnRow unchanged and return
146845  ** non-zero.
146846  **
146847  ** This routine can fail if it is unable to load a collating sequence
146848  ** required for string comparison, or if unable to allocate memory
146849  ** for a UTF conversion required for comparison.  The error is stored
146850  ** in the pParse structure.
146851  */
146852  static int whereInScanEst(
146853    Parse *pParse,       /* Parsing & code generating context */
146854    WhereLoopBuilder *pBuilder,
146855    ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
146856    tRowcnt *pnRow       /* Write the revised row estimate here */
146857  ){
146858    Index *p = pBuilder->pNew->u.btree.pIndex;
146859    i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
146860    int nRecValid = pBuilder->nRecValid;
146861    int rc = SQLITE_OK;     /* Subfunction return code */
146862    tRowcnt nEst;           /* Number of rows for a single term */
146863    tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
146864    int i;                  /* Loop counter */
146865  
146866    assert( p->aSample!=0 );
146867    for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
146868      nEst = nRow0;
146869      rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
146870      nRowEst += nEst;
146871      pBuilder->nRecValid = nRecValid;
146872    }
146873  
146874    if( rc==SQLITE_OK ){
146875      if( nRowEst > nRow0 ) nRowEst = nRow0;
146876      *pnRow = nRowEst;
146877      WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
146878    }
146879    assert( pBuilder->nRecValid==nRecValid );
146880    return rc;
146881  }
146882  #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
146883  
146884  
146885  #ifdef WHERETRACE_ENABLED
146886  /*
146887  ** Print the content of a WhereTerm object
146888  */
146889  static void whereTermPrint(WhereTerm *pTerm, int iTerm){
146890    if( pTerm==0 ){
146891      sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
146892    }else{
146893      char zType[4];
146894      char zLeft[50];
146895      memcpy(zType, "...", 4);
146896      if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
146897      if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
146898      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
146899      if( pTerm->eOperator & WO_SINGLE ){
146900        sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
146901                         pTerm->leftCursor, pTerm->u.leftColumn);
146902      }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
146903        sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", 
146904                         pTerm->u.pOrInfo->indexable);
146905      }else{
146906        sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
146907      }
146908      sqlite3DebugPrintf(
146909         "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
146910         iTerm, pTerm, zType, zLeft, pTerm->truthProb,
146911         pTerm->eOperator, pTerm->wtFlags);
146912      if( pTerm->iField ){
146913        sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
146914      }else{
146915        sqlite3DebugPrintf("\n");
146916      }
146917      sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
146918    }
146919  }
146920  #endif
146921  
146922  #ifdef WHERETRACE_ENABLED
146923  /*
146924  ** Show the complete content of a WhereClause
146925  */
146926  SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
146927    int i;
146928    for(i=0; i<pWC->nTerm; i++){
146929      whereTermPrint(&pWC->a[i], i);
146930    }
146931  }
146932  #endif
146933  
146934  #ifdef WHERETRACE_ENABLED
146935  /*
146936  ** Print a WhereLoop object for debugging purposes
146937  */
146938  static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
146939    WhereInfo *pWInfo = pWC->pWInfo;
146940    int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
146941    struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
146942    Table *pTab = pItem->pTab;
146943    Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
146944    sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
146945                       p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
146946    sqlite3DebugPrintf(" %12s",
146947                       pItem->zAlias ? pItem->zAlias : pTab->zName);
146948    if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
146949      const char *zName;
146950      if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
146951        if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
146952          int i = sqlite3Strlen30(zName) - 1;
146953          while( zName[i]!='_' ) i--;
146954          zName += i;
146955        }
146956        sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
146957      }else{
146958        sqlite3DebugPrintf("%20s","");
146959      }
146960    }else{
146961      char *z;
146962      if( p->u.vtab.idxStr ){
146963        z = sqlite3_mprintf("(%d,\"%s\",%x)",
146964                  p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
146965      }else{
146966        z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
146967      }
146968      sqlite3DebugPrintf(" %-19s", z);
146969      sqlite3_free(z);
146970    }
146971    if( p->wsFlags & WHERE_SKIPSCAN ){
146972      sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
146973    }else{
146974      sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
146975    }
146976    sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
146977    if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
146978      int i;
146979      for(i=0; i<p->nLTerm; i++){
146980        whereTermPrint(p->aLTerm[i], i);
146981      }
146982    }
146983  }
146984  #endif
146985  
146986  /*
146987  ** Convert bulk memory into a valid WhereLoop that can be passed
146988  ** to whereLoopClear harmlessly.
146989  */
146990  static void whereLoopInit(WhereLoop *p){
146991    p->aLTerm = p->aLTermSpace;
146992    p->nLTerm = 0;
146993    p->nLSlot = ArraySize(p->aLTermSpace);
146994    p->wsFlags = 0;
146995  }
146996  
146997  /*
146998  ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
146999  */
147000  static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
147001    if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
147002      if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
147003        sqlite3_free(p->u.vtab.idxStr);
147004        p->u.vtab.needFree = 0;
147005        p->u.vtab.idxStr = 0;
147006      }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
147007        sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
147008        sqlite3DbFreeNN(db, p->u.btree.pIndex);
147009        p->u.btree.pIndex = 0;
147010      }
147011    }
147012  }
147013  
147014  /*
147015  ** Deallocate internal memory used by a WhereLoop object
147016  */
147017  static void whereLoopClear(sqlite3 *db, WhereLoop *p){
147018    if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
147019    whereLoopClearUnion(db, p);
147020    whereLoopInit(p);
147021  }
147022  
147023  /*
147024  ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
147025  */
147026  static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
147027    WhereTerm **paNew;
147028    if( p->nLSlot>=n ) return SQLITE_OK;
147029    n = (n+7)&~7;
147030    paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
147031    if( paNew==0 ) return SQLITE_NOMEM_BKPT;
147032    memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
147033    if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
147034    p->aLTerm = paNew;
147035    p->nLSlot = n;
147036    return SQLITE_OK;
147037  }
147038  
147039  /*
147040  ** Transfer content from the second pLoop into the first.
147041  */
147042  static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
147043    whereLoopClearUnion(db, pTo);
147044    if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
147045      memset(&pTo->u, 0, sizeof(pTo->u));
147046      return SQLITE_NOMEM_BKPT;
147047    }
147048    memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
147049    memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
147050    if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
147051      pFrom->u.vtab.needFree = 0;
147052    }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
147053      pFrom->u.btree.pIndex = 0;
147054    }
147055    return SQLITE_OK;
147056  }
147057  
147058  /*
147059  ** Delete a WhereLoop object
147060  */
147061  static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
147062    whereLoopClear(db, p);
147063    sqlite3DbFreeNN(db, p);
147064  }
147065  
147066  /*
147067  ** Free a WhereInfo structure
147068  */
147069  static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
147070    int i;
147071    assert( pWInfo!=0 );
147072    for(i=0; i<pWInfo->nLevel; i++){
147073      WhereLevel *pLevel = &pWInfo->a[i];
147074      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
147075        sqlite3DbFree(db, pLevel->u.in.aInLoop);
147076      }
147077    }
147078    sqlite3WhereClauseClear(&pWInfo->sWC);
147079    while( pWInfo->pLoops ){
147080      WhereLoop *p = pWInfo->pLoops;
147081      pWInfo->pLoops = p->pNextLoop;
147082      whereLoopDelete(db, p);
147083    }
147084    sqlite3DbFreeNN(db, pWInfo);
147085  }
147086  
147087  /*
147088  ** Return TRUE if all of the following are true:
147089  **
147090  **   (1)  X has the same or lower cost that Y
147091  **   (2)  X uses fewer WHERE clause terms than Y
147092  **   (3)  Every WHERE clause term used by X is also used by Y
147093  **   (4)  X skips at least as many columns as Y
147094  **   (5)  If X is a covering index, than Y is too
147095  **
147096  ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
147097  ** If X is a proper subset of Y then Y is a better choice and ought
147098  ** to have a lower cost.  This routine returns TRUE when that cost 
147099  ** relationship is inverted and needs to be adjusted.  Constraint (4)
147100  ** was added because if X uses skip-scan less than Y it still might
147101  ** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)
147102  ** was added because a covering index probably deserves to have a lower cost
147103  ** than a non-covering index even if it is a proper subset.
147104  */
147105  static int whereLoopCheaperProperSubset(
147106    const WhereLoop *pX,       /* First WhereLoop to compare */
147107    const WhereLoop *pY        /* Compare against this WhereLoop */
147108  ){
147109    int i, j;
147110    if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
147111      return 0; /* X is not a subset of Y */
147112    }
147113    if( pY->nSkip > pX->nSkip ) return 0;
147114    if( pX->rRun >= pY->rRun ){
147115      if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
147116      if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
147117    }
147118    for(i=pX->nLTerm-1; i>=0; i--){
147119      if( pX->aLTerm[i]==0 ) continue;
147120      for(j=pY->nLTerm-1; j>=0; j--){
147121        if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
147122      }
147123      if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
147124    }
147125    if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 
147126     && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
147127      return 0;  /* Constraint (5) */
147128    }
147129    return 1;  /* All conditions meet */
147130  }
147131  
147132  /*
147133  ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
147134  ** that:
147135  **
147136  **   (1) pTemplate costs less than any other WhereLoops that are a proper
147137  **       subset of pTemplate
147138  **
147139  **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
147140  **       is a proper subset.
147141  **
147142  ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
147143  ** WHERE clause terms than Y and that every WHERE clause term used by X is
147144  ** also used by Y.
147145  */
147146  static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
147147    if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
147148    for(; p; p=p->pNextLoop){
147149      if( p->iTab!=pTemplate->iTab ) continue;
147150      if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
147151      if( whereLoopCheaperProperSubset(p, pTemplate) ){
147152        /* Adjust pTemplate cost downward so that it is cheaper than its 
147153        ** subset p. */
147154        WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
147155                         pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
147156        pTemplate->rRun = p->rRun;
147157        pTemplate->nOut = p->nOut - 1;
147158      }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
147159        /* Adjust pTemplate cost upward so that it is costlier than p since
147160        ** pTemplate is a proper subset of p */
147161        WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
147162                         pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
147163        pTemplate->rRun = p->rRun;
147164        pTemplate->nOut = p->nOut + 1;
147165      }
147166    }
147167  }
147168  
147169  /*
147170  ** Search the list of WhereLoops in *ppPrev looking for one that can be
147171  ** replaced by pTemplate.
147172  **
147173  ** Return NULL if pTemplate does not belong on the WhereLoop list.
147174  ** In other words if pTemplate ought to be dropped from further consideration.
147175  **
147176  ** If pX is a WhereLoop that pTemplate can replace, then return the
147177  ** link that points to pX.
147178  **
147179  ** If pTemplate cannot replace any existing element of the list but needs
147180  ** to be added to the list as a new entry, then return a pointer to the
147181  ** tail of the list.
147182  */
147183  static WhereLoop **whereLoopFindLesser(
147184    WhereLoop **ppPrev,
147185    const WhereLoop *pTemplate
147186  ){
147187    WhereLoop *p;
147188    for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
147189      if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
147190        /* If either the iTab or iSortIdx values for two WhereLoop are different
147191        ** then those WhereLoops need to be considered separately.  Neither is
147192        ** a candidate to replace the other. */
147193        continue;
147194      }
147195      /* In the current implementation, the rSetup value is either zero
147196      ** or the cost of building an automatic index (NlogN) and the NlogN
147197      ** is the same for compatible WhereLoops. */
147198      assert( p->rSetup==0 || pTemplate->rSetup==0 
147199                   || p->rSetup==pTemplate->rSetup );
147200  
147201      /* whereLoopAddBtree() always generates and inserts the automatic index
147202      ** case first.  Hence compatible candidate WhereLoops never have a larger
147203      ** rSetup. Call this SETUP-INVARIANT */
147204      assert( p->rSetup>=pTemplate->rSetup );
147205  
147206      /* Any loop using an appliation-defined index (or PRIMARY KEY or
147207      ** UNIQUE constraint) with one or more == constraints is better
147208      ** than an automatic index. Unless it is a skip-scan. */
147209      if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
147210       && (pTemplate->nSkip)==0
147211       && (pTemplate->wsFlags & WHERE_INDEXED)!=0
147212       && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
147213       && (p->prereq & pTemplate->prereq)==pTemplate->prereq
147214      ){
147215        break;
147216      }
147217  
147218      /* If existing WhereLoop p is better than pTemplate, pTemplate can be
147219      ** discarded.  WhereLoop p is better if:
147220      **   (1)  p has no more dependencies than pTemplate, and
147221      **   (2)  p has an equal or lower cost than pTemplate
147222      */
147223      if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
147224       && p->rSetup<=pTemplate->rSetup                  /* (2a) */
147225       && p->rRun<=pTemplate->rRun                      /* (2b) */
147226       && p->nOut<=pTemplate->nOut                      /* (2c) */
147227      ){
147228        return 0;  /* Discard pTemplate */
147229      }
147230  
147231      /* If pTemplate is always better than p, then cause p to be overwritten
147232      ** with pTemplate.  pTemplate is better than p if:
147233      **   (1)  pTemplate has no more dependences than p, and
147234      **   (2)  pTemplate has an equal or lower cost than p.
147235      */
147236      if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
147237       && p->rRun>=pTemplate->rRun                             /* (2a) */
147238       && p->nOut>=pTemplate->nOut                             /* (2b) */
147239      ){
147240        assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
147241        break;   /* Cause p to be overwritten by pTemplate */
147242      }
147243    }
147244    return ppPrev;
147245  }
147246  
147247  /*
147248  ** Insert or replace a WhereLoop entry using the template supplied.
147249  **
147250  ** An existing WhereLoop entry might be overwritten if the new template
147251  ** is better and has fewer dependencies.  Or the template will be ignored
147252  ** and no insert will occur if an existing WhereLoop is faster and has
147253  ** fewer dependencies than the template.  Otherwise a new WhereLoop is
147254  ** added based on the template.
147255  **
147256  ** If pBuilder->pOrSet is not NULL then we care about only the
147257  ** prerequisites and rRun and nOut costs of the N best loops.  That
147258  ** information is gathered in the pBuilder->pOrSet object.  This special
147259  ** processing mode is used only for OR clause processing.
147260  **
147261  ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
147262  ** still might overwrite similar loops with the new template if the
147263  ** new template is better.  Loops may be overwritten if the following 
147264  ** conditions are met:
147265  **
147266  **    (1)  They have the same iTab.
147267  **    (2)  They have the same iSortIdx.
147268  **    (3)  The template has same or fewer dependencies than the current loop
147269  **    (4)  The template has the same or lower cost than the current loop
147270  */
147271  static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
147272    WhereLoop **ppPrev, *p;
147273    WhereInfo *pWInfo = pBuilder->pWInfo;
147274    sqlite3 *db = pWInfo->pParse->db;
147275    int rc;
147276  
147277    /* Stop the search once we hit the query planner search limit */
147278    if( pBuilder->iPlanLimit==0 ){
147279      WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
147280      if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
147281      return SQLITE_DONE;
147282    }
147283    pBuilder->iPlanLimit--;
147284  
147285    /* If pBuilder->pOrSet is defined, then only keep track of the costs
147286    ** and prereqs.
147287    */
147288    if( pBuilder->pOrSet!=0 ){
147289      if( pTemplate->nLTerm ){
147290  #if WHERETRACE_ENABLED
147291        u16 n = pBuilder->pOrSet->n;
147292        int x =
147293  #endif
147294        whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
147295                                      pTemplate->nOut);
147296  #if WHERETRACE_ENABLED /* 0x8 */
147297        if( sqlite3WhereTrace & 0x8 ){
147298          sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
147299          whereLoopPrint(pTemplate, pBuilder->pWC);
147300        }
147301  #endif
147302      }
147303      return SQLITE_OK;
147304    }
147305  
147306    /* Look for an existing WhereLoop to replace with pTemplate
147307    */
147308    whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
147309    ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
147310  
147311    if( ppPrev==0 ){
147312      /* There already exists a WhereLoop on the list that is better
147313      ** than pTemplate, so just ignore pTemplate */
147314  #if WHERETRACE_ENABLED /* 0x8 */
147315      if( sqlite3WhereTrace & 0x8 ){
147316        sqlite3DebugPrintf("   skip: ");
147317        whereLoopPrint(pTemplate, pBuilder->pWC);
147318      }
147319  #endif
147320      return SQLITE_OK;  
147321    }else{
147322      p = *ppPrev;
147323    }
147324  
147325    /* If we reach this point it means that either p[] should be overwritten
147326    ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
147327    ** WhereLoop and insert it.
147328    */
147329  #if WHERETRACE_ENABLED /* 0x8 */
147330    if( sqlite3WhereTrace & 0x8 ){
147331      if( p!=0 ){
147332        sqlite3DebugPrintf("replace: ");
147333        whereLoopPrint(p, pBuilder->pWC);
147334        sqlite3DebugPrintf("   with: ");
147335      }else{
147336        sqlite3DebugPrintf("    add: ");
147337      }
147338      whereLoopPrint(pTemplate, pBuilder->pWC);
147339    }
147340  #endif
147341    if( p==0 ){
147342      /* Allocate a new WhereLoop to add to the end of the list */
147343      *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
147344      if( p==0 ) return SQLITE_NOMEM_BKPT;
147345      whereLoopInit(p);
147346      p->pNextLoop = 0;
147347    }else{
147348      /* We will be overwriting WhereLoop p[].  But before we do, first
147349      ** go through the rest of the list and delete any other entries besides
147350      ** p[] that are also supplated by pTemplate */
147351      WhereLoop **ppTail = &p->pNextLoop;
147352      WhereLoop *pToDel;
147353      while( *ppTail ){
147354        ppTail = whereLoopFindLesser(ppTail, pTemplate);
147355        if( ppTail==0 ) break;
147356        pToDel = *ppTail;
147357        if( pToDel==0 ) break;
147358        *ppTail = pToDel->pNextLoop;
147359  #if WHERETRACE_ENABLED /* 0x8 */
147360        if( sqlite3WhereTrace & 0x8 ){
147361          sqlite3DebugPrintf(" delete: ");
147362          whereLoopPrint(pToDel, pBuilder->pWC);
147363        }
147364  #endif
147365        whereLoopDelete(db, pToDel);
147366      }
147367    }
147368    rc = whereLoopXfer(db, p, pTemplate);
147369    if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
147370      Index *pIndex = p->u.btree.pIndex;
147371      if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
147372        p->u.btree.pIndex = 0;
147373      }
147374    }
147375    return rc;
147376  }
147377  
147378  /*
147379  ** Adjust the WhereLoop.nOut value downward to account for terms of the
147380  ** WHERE clause that reference the loop but which are not used by an
147381  ** index.
147382  *
147383  ** For every WHERE clause term that is not used by the index
147384  ** and which has a truth probability assigned by one of the likelihood(),
147385  ** likely(), or unlikely() SQL functions, reduce the estimated number
147386  ** of output rows by the probability specified.
147387  **
147388  ** TUNING:  For every WHERE clause term that is not used by the index
147389  ** and which does not have an assigned truth probability, heuristics
147390  ** described below are used to try to estimate the truth probability.
147391  ** TODO --> Perhaps this is something that could be improved by better
147392  ** table statistics.
147393  **
147394  ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
147395  ** value corresponds to -1 in LogEst notation, so this means decrement
147396  ** the WhereLoop.nOut field for every such WHERE clause term.
147397  **
147398  ** Heuristic 2:  If there exists one or more WHERE clause terms of the
147399  ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
147400  ** final output row estimate is no greater than 1/4 of the total number
147401  ** of rows in the table.  In other words, assume that x==EXPR will filter
147402  ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
147403  ** "x" column is boolean or else -1 or 0 or 1 is a common default value
147404  ** on the "x" column and so in that case only cap the output row estimate
147405  ** at 1/2 instead of 1/4.
147406  */
147407  static void whereLoopOutputAdjust(
147408    WhereClause *pWC,      /* The WHERE clause */
147409    WhereLoop *pLoop,      /* The loop to adjust downward */
147410    LogEst nRow            /* Number of rows in the entire table */
147411  ){
147412    WhereTerm *pTerm, *pX;
147413    Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
147414    int i, j, k;
147415    LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
147416  
147417    assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
147418    for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
147419      if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
147420      if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
147421      if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
147422      for(j=pLoop->nLTerm-1; j>=0; j--){
147423        pX = pLoop->aLTerm[j];
147424        if( pX==0 ) continue;
147425        if( pX==pTerm ) break;
147426        if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
147427      }
147428      if( j<0 ){
147429        if( pTerm->truthProb<=0 ){
147430          /* If a truth probability is specified using the likelihood() hints,
147431          ** then use the probability provided by the application. */
147432          pLoop->nOut += pTerm->truthProb;
147433        }else{
147434          /* In the absence of explicit truth probabilities, use heuristics to
147435          ** guess a reasonable truth probability. */
147436          pLoop->nOut--;
147437          if( pTerm->eOperator&(WO_EQ|WO_IS) ){
147438            Expr *pRight = pTerm->pExpr->pRight;
147439            testcase( pTerm->pExpr->op==TK_IS );
147440            if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
147441              k = 10;
147442            }else{
147443              k = 20;
147444            }
147445            if( iReduce<k ) iReduce = k;
147446          }
147447        }
147448      }
147449    }
147450    if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
147451  }
147452  
147453  /* 
147454  ** Term pTerm is a vector range comparison operation. The first comparison
147455  ** in the vector can be optimized using column nEq of the index. This
147456  ** function returns the total number of vector elements that can be used
147457  ** as part of the range comparison.
147458  **
147459  ** For example, if the query is:
147460  **
147461  **   WHERE a = ? AND (b, c, d) > (?, ?, ?)
147462  **
147463  ** and the index:
147464  **
147465  **   CREATE INDEX ... ON (a, b, c, d, e)
147466  **
147467  ** then this function would be invoked with nEq=1. The value returned in
147468  ** this case is 3.
147469  */
147470  static int whereRangeVectorLen(
147471    Parse *pParse,       /* Parsing context */
147472    int iCur,            /* Cursor open on pIdx */
147473    Index *pIdx,         /* The index to be used for a inequality constraint */
147474    int nEq,             /* Number of prior equality constraints on same index */
147475    WhereTerm *pTerm     /* The vector inequality constraint */
147476  ){
147477    int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
147478    int i;
147479  
147480    nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
147481    for(i=1; i<nCmp; i++){
147482      /* Test if comparison i of pTerm is compatible with column (i+nEq) 
147483      ** of the index. If not, exit the loop.  */
147484      char aff;                     /* Comparison affinity */
147485      char idxaff = 0;              /* Indexed columns affinity */
147486      CollSeq *pColl;               /* Comparison collation sequence */
147487      Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
147488      Expr *pRhs = pTerm->pExpr->pRight;
147489      if( pRhs->flags & EP_xIsSelect ){
147490        pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
147491      }else{
147492        pRhs = pRhs->x.pList->a[i].pExpr;
147493      }
147494  
147495      /* Check that the LHS of the comparison is a column reference to
147496      ** the right column of the right source table. And that the sort
147497      ** order of the index column is the same as the sort order of the
147498      ** leftmost index column.  */
147499      if( pLhs->op!=TK_COLUMN 
147500       || pLhs->iTable!=iCur 
147501       || pLhs->iColumn!=pIdx->aiColumn[i+nEq] 
147502       || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
147503      ){
147504        break;
147505      }
147506  
147507      testcase( pLhs->iColumn==XN_ROWID );
147508      aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
147509      idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
147510      if( aff!=idxaff ) break;
147511  
147512      pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
147513      if( pColl==0 ) break;
147514      if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
147515    }
147516    return i;
147517  }
147518  
147519  /*
147520  ** Adjust the cost C by the costMult facter T.  This only occurs if
147521  ** compiled with -DSQLITE_ENABLE_COSTMULT
147522  */
147523  #ifdef SQLITE_ENABLE_COSTMULT
147524  # define ApplyCostMultiplier(C,T)  C += T
147525  #else
147526  # define ApplyCostMultiplier(C,T)
147527  #endif
147528  
147529  /*
147530  ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 
147531  ** index pIndex. Try to match one more.
147532  **
147533  ** When this function is called, pBuilder->pNew->nOut contains the 
147534  ** number of rows expected to be visited by filtering using the nEq 
147535  ** terms only. If it is modified, this value is restored before this 
147536  ** function returns.
147537  **
147538  ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is 
147539  ** a fake index used for the INTEGER PRIMARY KEY.
147540  */
147541  static int whereLoopAddBtreeIndex(
147542    WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
147543    struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
147544    Index *pProbe,                  /* An index on pSrc */
147545    LogEst nInMul                   /* log(Number of iterations due to IN) */
147546  ){
147547    WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
147548    Parse *pParse = pWInfo->pParse;        /* Parsing context */
147549    sqlite3 *db = pParse->db;       /* Database connection malloc context */
147550    WhereLoop *pNew;                /* Template WhereLoop under construction */
147551    WhereTerm *pTerm;               /* A WhereTerm under consideration */
147552    int opMask;                     /* Valid operators for constraints */
147553    WhereScan scan;                 /* Iterator for WHERE terms */
147554    Bitmask saved_prereq;           /* Original value of pNew->prereq */
147555    u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
147556    u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
147557    u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
147558    u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
147559    u16 saved_nSkip;                /* Original value of pNew->nSkip */
147560    u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
147561    LogEst saved_nOut;              /* Original value of pNew->nOut */
147562    int rc = SQLITE_OK;             /* Return code */
147563    LogEst rSize;                   /* Number of rows in the table */
147564    LogEst rLogSize;                /* Logarithm of table size */
147565    WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
147566  
147567    pNew = pBuilder->pNew;
147568    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
147569    WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
147570                       pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
147571  
147572    assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
147573    assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
147574    if( pNew->wsFlags & WHERE_BTM_LIMIT ){
147575      opMask = WO_LT|WO_LE;
147576    }else{
147577      assert( pNew->u.btree.nBtm==0 );
147578      opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
147579    }
147580    if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
147581  
147582    assert( pNew->u.btree.nEq<pProbe->nColumn );
147583  
147584    saved_nEq = pNew->u.btree.nEq;
147585    saved_nBtm = pNew->u.btree.nBtm;
147586    saved_nTop = pNew->u.btree.nTop;
147587    saved_nSkip = pNew->nSkip;
147588    saved_nLTerm = pNew->nLTerm;
147589    saved_wsFlags = pNew->wsFlags;
147590    saved_prereq = pNew->prereq;
147591    saved_nOut = pNew->nOut;
147592    pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
147593                          opMask, pProbe);
147594    pNew->rSetup = 0;
147595    rSize = pProbe->aiRowLogEst[0];
147596    rLogSize = estLog(rSize);
147597    for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
147598      u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
147599      LogEst rCostIdx;
147600      LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
147601      int nIn = 0;
147602  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
147603      int nRecValid = pBuilder->nRecValid;
147604  #endif
147605      if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
147606       && indexColumnNotNull(pProbe, saved_nEq)
147607      ){
147608        continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
147609      }
147610      if( pTerm->prereqRight & pNew->maskSelf ) continue;
147611  
147612      /* Do not allow the upper bound of a LIKE optimization range constraint
147613      ** to mix with a lower range bound from some other source */
147614      if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
147615  
147616      /* Do not allow constraints from the WHERE clause to be used by the
147617      ** right table of a LEFT JOIN.  Only constraints in the ON clause are
147618      ** allowed */
147619      if( (pSrc->fg.jointype & JT_LEFT)!=0
147620       && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
147621      ){
147622        continue;
147623      }
147624  
147625      if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
147626        pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
147627      }else{
147628        pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
147629      }
147630      pNew->wsFlags = saved_wsFlags;
147631      pNew->u.btree.nEq = saved_nEq;
147632      pNew->u.btree.nBtm = saved_nBtm;
147633      pNew->u.btree.nTop = saved_nTop;
147634      pNew->nLTerm = saved_nLTerm;
147635      if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
147636      pNew->aLTerm[pNew->nLTerm++] = pTerm;
147637      pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
147638  
147639      assert( nInMul==0
147640          || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 
147641          || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 
147642          || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 
147643      );
147644  
147645      if( eOp & WO_IN ){
147646        Expr *pExpr = pTerm->pExpr;
147647        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
147648          /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
147649          int i;
147650          nIn = 46;  assert( 46==sqlite3LogEst(25) );
147651  
147652          /* The expression may actually be of the form (x, y) IN (SELECT...).
147653          ** In this case there is a separate term for each of (x) and (y).
147654          ** However, the nIn multiplier should only be applied once, not once
147655          ** for each such term. The following loop checks that pTerm is the
147656          ** first such term in use, and sets nIn back to 0 if it is not. */
147657          for(i=0; i<pNew->nLTerm-1; i++){
147658            if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
147659          }
147660        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
147661          /* "x IN (value, value, ...)" */
147662          nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
147663          assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
147664                            ** changes "x IN (?)" into "x=?". */
147665        }
147666        if( pProbe->hasStat1 ){
147667          LogEst M, logK, safetyMargin;
147668          /* Let:
147669          **   N = the total number of rows in the table
147670          **   K = the number of entries on the RHS of the IN operator
147671          **   M = the number of rows in the table that match terms to the 
147672          **       to the left in the same index.  If the IN operator is on
147673          **       the left-most index column, M==N.
147674          **
147675          ** Given the definitions above, it is better to omit the IN operator
147676          ** from the index lookup and instead do a scan of the M elements,
147677          ** testing each scanned row against the IN operator separately, if:
147678          **
147679          **        M*log(K) < K*log(N)
147680          **
147681          ** Our estimates for M, K, and N might be inaccurate, so we build in
147682          ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
147683          ** with the index, as using an index has better worst-case behavior.
147684          ** If we do not have real sqlite_stat1 data, always prefer to use
147685          ** the index.
147686          */
147687          M = pProbe->aiRowLogEst[saved_nEq];
147688          logK = estLog(nIn);
147689          safetyMargin = 10;  /* TUNING: extra weight for indexed IN */
147690          if( M + logK + safetyMargin < nIn + rLogSize ){
147691            WHERETRACE(0x40,
147692              ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
147693               saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
147694            continue;
147695          }else{
147696            WHERETRACE(0x40,
147697              ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
147698               saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
147699          }
147700        }
147701        pNew->wsFlags |= WHERE_COLUMN_IN;
147702      }else if( eOp & (WO_EQ|WO_IS) ){
147703        int iCol = pProbe->aiColumn[saved_nEq];
147704        pNew->wsFlags |= WHERE_COLUMN_EQ;
147705        assert( saved_nEq==pNew->u.btree.nEq );
147706        if( iCol==XN_ROWID 
147707         || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
147708        ){
147709          if( iCol==XN_ROWID || pProbe->uniqNotNull 
147710           || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) 
147711          ){
147712            pNew->wsFlags |= WHERE_ONEROW;
147713          }else{
147714            pNew->wsFlags |= WHERE_UNQ_WANTED;
147715          }
147716        }
147717      }else if( eOp & WO_ISNULL ){
147718        pNew->wsFlags |= WHERE_COLUMN_NULL;
147719      }else if( eOp & (WO_GT|WO_GE) ){
147720        testcase( eOp & WO_GT );
147721        testcase( eOp & WO_GE );
147722        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
147723        pNew->u.btree.nBtm = whereRangeVectorLen(
147724            pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
147725        );
147726        pBtm = pTerm;
147727        pTop = 0;
147728        if( pTerm->wtFlags & TERM_LIKEOPT ){
147729          /* Range contraints that come from the LIKE optimization are
147730          ** always used in pairs. */
147731          pTop = &pTerm[1];
147732          assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
147733          assert( pTop->wtFlags & TERM_LIKEOPT );
147734          assert( pTop->eOperator==WO_LT );
147735          if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
147736          pNew->aLTerm[pNew->nLTerm++] = pTop;
147737          pNew->wsFlags |= WHERE_TOP_LIMIT;
147738          pNew->u.btree.nTop = 1;
147739        }
147740      }else{
147741        assert( eOp & (WO_LT|WO_LE) );
147742        testcase( eOp & WO_LT );
147743        testcase( eOp & WO_LE );
147744        pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
147745        pNew->u.btree.nTop = whereRangeVectorLen(
147746            pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
147747        );
147748        pTop = pTerm;
147749        pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
147750                       pNew->aLTerm[pNew->nLTerm-2] : 0;
147751      }
147752  
147753      /* At this point pNew->nOut is set to the number of rows expected to
147754      ** be visited by the index scan before considering term pTerm, or the
147755      ** values of nIn and nInMul. In other words, assuming that all 
147756      ** "x IN(...)" terms are replaced with "x = ?". This block updates
147757      ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
147758      assert( pNew->nOut==saved_nOut );
147759      if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
147760        /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
147761        ** data, using some other estimate.  */
147762        whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
147763      }else{
147764        int nEq = ++pNew->u.btree.nEq;
147765        assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
147766  
147767        assert( pNew->nOut==saved_nOut );
147768        if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
147769          assert( (eOp & WO_IN) || nIn==0 );
147770          testcase( eOp & WO_IN );
147771          pNew->nOut += pTerm->truthProb;
147772          pNew->nOut -= nIn;
147773        }else{
147774  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
147775          tRowcnt nOut = 0;
147776          if( nInMul==0 
147777           && pProbe->nSample 
147778           && pNew->u.btree.nEq<=pProbe->nSampleCol
147779           && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
147780           && OptimizationEnabled(db, SQLITE_Stat34)
147781          ){
147782            Expr *pExpr = pTerm->pExpr;
147783            if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
147784              testcase( eOp & WO_EQ );
147785              testcase( eOp & WO_IS );
147786              testcase( eOp & WO_ISNULL );
147787              rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
147788            }else{
147789              rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
147790            }
147791            if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
147792            if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
147793            if( nOut ){
147794              pNew->nOut = sqlite3LogEst(nOut);
147795              if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
147796              pNew->nOut -= nIn;
147797            }
147798          }
147799          if( nOut==0 )
147800  #endif
147801          {
147802            pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
147803            if( eOp & WO_ISNULL ){
147804              /* TUNING: If there is no likelihood() value, assume that a 
147805              ** "col IS NULL" expression matches twice as many rows 
147806              ** as (col=?). */
147807              pNew->nOut += 10;
147808            }
147809          }
147810        }
147811      }
147812  
147813      /* Set rCostIdx to the cost of visiting selected rows in index. Add
147814      ** it to pNew->rRun, which is currently set to the cost of the index
147815      ** seek only. Then, if this is a non-covering index, add the cost of
147816      ** visiting the rows in the main table.  */
147817      rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
147818      pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
147819      if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
147820        pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
147821      }
147822      ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
147823  
147824      nOutUnadjusted = pNew->nOut;
147825      pNew->rRun += nInMul + nIn;
147826      pNew->nOut += nInMul + nIn;
147827      whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
147828      rc = whereLoopInsert(pBuilder, pNew);
147829  
147830      if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
147831        pNew->nOut = saved_nOut;
147832      }else{
147833        pNew->nOut = nOutUnadjusted;
147834      }
147835  
147836      if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
147837       && pNew->u.btree.nEq<pProbe->nColumn
147838      ){
147839        whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
147840      }
147841      pNew->nOut = saved_nOut;
147842  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
147843      pBuilder->nRecValid = nRecValid;
147844  #endif
147845    }
147846    pNew->prereq = saved_prereq;
147847    pNew->u.btree.nEq = saved_nEq;
147848    pNew->u.btree.nBtm = saved_nBtm;
147849    pNew->u.btree.nTop = saved_nTop;
147850    pNew->nSkip = saved_nSkip;
147851    pNew->wsFlags = saved_wsFlags;
147852    pNew->nOut = saved_nOut;
147853    pNew->nLTerm = saved_nLTerm;
147854  
147855    /* Consider using a skip-scan if there are no WHERE clause constraints
147856    ** available for the left-most terms of the index, and if the average
147857    ** number of repeats in the left-most terms is at least 18. 
147858    **
147859    ** The magic number 18 is selected on the basis that scanning 17 rows
147860    ** is almost always quicker than an index seek (even though if the index
147861    ** contains fewer than 2^17 rows we assume otherwise in other parts of
147862    ** the code). And, even if it is not, it should not be too much slower. 
147863    ** On the other hand, the extra seeks could end up being significantly
147864    ** more expensive.  */
147865    assert( 42==sqlite3LogEst(18) );
147866    if( saved_nEq==saved_nSkip
147867     && saved_nEq+1<pProbe->nKeyCol
147868     && pProbe->noSkipScan==0
147869     && OptimizationEnabled(db, SQLITE_SkipScan)
147870     && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
147871     && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
147872    ){
147873      LogEst nIter;
147874      pNew->u.btree.nEq++;
147875      pNew->nSkip++;
147876      pNew->aLTerm[pNew->nLTerm++] = 0;
147877      pNew->wsFlags |= WHERE_SKIPSCAN;
147878      nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
147879      pNew->nOut -= nIter;
147880      /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
147881      ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
147882      nIter += 5;
147883      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
147884      pNew->nOut = saved_nOut;
147885      pNew->u.btree.nEq = saved_nEq;
147886      pNew->nSkip = saved_nSkip;
147887      pNew->wsFlags = saved_wsFlags;
147888    }
147889  
147890    WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
147891                        pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
147892    return rc;
147893  }
147894  
147895  /*
147896  ** Return True if it is possible that pIndex might be useful in
147897  ** implementing the ORDER BY clause in pBuilder.
147898  **
147899  ** Return False if pBuilder does not contain an ORDER BY clause or
147900  ** if there is no way for pIndex to be useful in implementing that
147901  ** ORDER BY clause.
147902  */
147903  static int indexMightHelpWithOrderBy(
147904    WhereLoopBuilder *pBuilder,
147905    Index *pIndex,
147906    int iCursor
147907  ){
147908    ExprList *pOB;
147909    ExprList *aColExpr;
147910    int ii, jj;
147911  
147912    if( pIndex->bUnordered ) return 0;
147913    if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
147914    for(ii=0; ii<pOB->nExpr; ii++){
147915      Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
147916      if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
147917        if( pExpr->iColumn<0 ) return 1;
147918        for(jj=0; jj<pIndex->nKeyCol; jj++){
147919          if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
147920        }
147921      }else if( (aColExpr = pIndex->aColExpr)!=0 ){
147922        for(jj=0; jj<pIndex->nKeyCol; jj++){
147923          if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
147924          if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
147925            return 1;
147926          }
147927        }
147928      }
147929    }
147930    return 0;
147931  }
147932  
147933  /* Check to see if a partial index with pPartIndexWhere can be used
147934  ** in the current query.  Return true if it can be and false if not.
147935  */
147936  static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
147937    int i;
147938    WhereTerm *pTerm;
147939    Parse *pParse = pWC->pWInfo->pParse;
147940    while( pWhere->op==TK_AND ){
147941      if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
147942      pWhere = pWhere->pRight;
147943    }
147944    if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
147945    for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
147946      Expr *pExpr = pTerm->pExpr;
147947      if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
147948       && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) 
147949      ){
147950        return 1;
147951      }
147952    }
147953    return 0;
147954  }
147955  
147956  /*
147957  ** Add all WhereLoop objects for a single table of the join where the table
147958  ** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
147959  ** a b-tree table, not a virtual table.
147960  **
147961  ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
147962  ** are calculated as follows:
147963  **
147964  ** For a full scan, assuming the table (or index) contains nRow rows:
147965  **
147966  **     cost = nRow * 3.0                    // full-table scan
147967  **     cost = nRow * K                      // scan of covering index
147968  **     cost = nRow * (K+3.0)                // scan of non-covering index
147969  **
147970  ** where K is a value between 1.1 and 3.0 set based on the relative 
147971  ** estimated average size of the index and table records.
147972  **
147973  ** For an index scan, where nVisit is the number of index rows visited
147974  ** by the scan, and nSeek is the number of seek operations required on 
147975  ** the index b-tree:
147976  **
147977  **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
147978  **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
147979  **
147980  ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 
147981  ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 
147982  ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
147983  **
147984  ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
147985  ** of uncertainty.  For this reason, scoring is designed to pick plans that
147986  ** "do the least harm" if the estimates are inaccurate.  For example, a
147987  ** log(nRow) factor is omitted from a non-covering index scan in order to
147988  ** bias the scoring in favor of using an index, since the worst-case
147989  ** performance of using an index is far better than the worst-case performance
147990  ** of a full table scan.
147991  */
147992  static int whereLoopAddBtree(
147993    WhereLoopBuilder *pBuilder, /* WHERE clause information */
147994    Bitmask mPrereq             /* Extra prerequesites for using this table */
147995  ){
147996    WhereInfo *pWInfo;          /* WHERE analysis context */
147997    Index *pProbe;              /* An index we are evaluating */
147998    Index sPk;                  /* A fake index object for the primary key */
147999    LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
148000    i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
148001    SrcList *pTabList;          /* The FROM clause */
148002    struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
148003    WhereLoop *pNew;            /* Template WhereLoop object */
148004    int rc = SQLITE_OK;         /* Return code */
148005    int iSortIdx = 1;           /* Index number */
148006    int b;                      /* A boolean value */
148007    LogEst rSize;               /* number of rows in the table */
148008    LogEst rLogSize;            /* Logarithm of the number of rows in the table */
148009    WhereClause *pWC;           /* The parsed WHERE clause */
148010    Table *pTab;                /* Table being queried */
148011    
148012    pNew = pBuilder->pNew;
148013    pWInfo = pBuilder->pWInfo;
148014    pTabList = pWInfo->pTabList;
148015    pSrc = pTabList->a + pNew->iTab;
148016    pTab = pSrc->pTab;
148017    pWC = pBuilder->pWC;
148018    assert( !IsVirtual(pSrc->pTab) );
148019  
148020    if( pSrc->pIBIndex ){
148021      /* An INDEXED BY clause specifies a particular index to use */
148022      pProbe = pSrc->pIBIndex;
148023    }else if( !HasRowid(pTab) ){
148024      pProbe = pTab->pIndex;
148025    }else{
148026      /* There is no INDEXED BY clause.  Create a fake Index object in local
148027      ** variable sPk to represent the rowid primary key index.  Make this
148028      ** fake index the first in a chain of Index objects with all of the real
148029      ** indices to follow */
148030      Index *pFirst;                  /* First of real indices on the table */
148031      memset(&sPk, 0, sizeof(Index));
148032      sPk.nKeyCol = 1;
148033      sPk.nColumn = 1;
148034      sPk.aiColumn = &aiColumnPk;
148035      sPk.aiRowLogEst = aiRowEstPk;
148036      sPk.onError = OE_Replace;
148037      sPk.pTable = pTab;
148038      sPk.szIdxRow = pTab->szTabRow;
148039      sPk.idxType = SQLITE_IDXTYPE_IPK;
148040      aiRowEstPk[0] = pTab->nRowLogEst;
148041      aiRowEstPk[1] = 0;
148042      pFirst = pSrc->pTab->pIndex;
148043      if( pSrc->fg.notIndexed==0 ){
148044        /* The real indices of the table are only considered if the
148045        ** NOT INDEXED qualifier is omitted from the FROM clause */
148046        sPk.pNext = pFirst;
148047      }
148048      pProbe = &sPk;
148049    }
148050    rSize = pTab->nRowLogEst;
148051    rLogSize = estLog(rSize);
148052  
148053  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
148054    /* Automatic indexes */
148055    if( !pBuilder->pOrSet      /* Not part of an OR optimization */
148056     && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
148057     && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
148058     && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
148059     && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
148060     && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
148061     && !pSrc->fg.isCorrelated /* Not a correlated subquery */
148062     && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
148063    ){
148064      /* Generate auto-index WhereLoops */
148065      WhereTerm *pTerm;
148066      WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
148067      for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
148068        if( pTerm->prereqRight & pNew->maskSelf ) continue;
148069        if( termCanDriveIndex(pTerm, pSrc, 0) ){
148070          pNew->u.btree.nEq = 1;
148071          pNew->nSkip = 0;
148072          pNew->u.btree.pIndex = 0;
148073          pNew->nLTerm = 1;
148074          pNew->aLTerm[0] = pTerm;
148075          /* TUNING: One-time cost for computing the automatic index is
148076          ** estimated to be X*N*log2(N) where N is the number of rows in
148077          ** the table being indexed and where X is 7 (LogEst=28) for normal
148078          ** tables or 0.5 (LogEst=-10) for views and subqueries.  The value
148079          ** of X is smaller for views and subqueries so that the query planner
148080          ** will be more aggressive about generating automatic indexes for
148081          ** those objects, since there is no opportunity to add schema
148082          ** indexes on subqueries and views. */
148083          pNew->rSetup = rLogSize + rSize;
148084          if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
148085            pNew->rSetup += 28;
148086          }else{
148087            pNew->rSetup -= 10;
148088          }
148089          ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
148090          if( pNew->rSetup<0 ) pNew->rSetup = 0;
148091          /* TUNING: Each index lookup yields 20 rows in the table.  This
148092          ** is more than the usual guess of 10 rows, since we have no way
148093          ** of knowing how selective the index will ultimately be.  It would
148094          ** not be unreasonable to make this value much larger. */
148095          pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
148096          pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
148097          pNew->wsFlags = WHERE_AUTO_INDEX;
148098          pNew->prereq = mPrereq | pTerm->prereqRight;
148099          rc = whereLoopInsert(pBuilder, pNew);
148100        }
148101      }
148102    }
148103  #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
148104  
148105    /* Loop over all indices. If there was an INDEXED BY clause, then only 
148106    ** consider index pProbe.  */
148107    for(; rc==SQLITE_OK && pProbe; 
148108        pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
148109    ){
148110      if( pProbe->pPartIdxWhere!=0
148111       && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
148112        testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
148113        continue;  /* Partial index inappropriate for this query */
148114      }
148115      if( pProbe->bNoQuery ) continue;
148116      rSize = pProbe->aiRowLogEst[0];
148117      pNew->u.btree.nEq = 0;
148118      pNew->u.btree.nBtm = 0;
148119      pNew->u.btree.nTop = 0;
148120      pNew->nSkip = 0;
148121      pNew->nLTerm = 0;
148122      pNew->iSortIdx = 0;
148123      pNew->rSetup = 0;
148124      pNew->prereq = mPrereq;
148125      pNew->nOut = rSize;
148126      pNew->u.btree.pIndex = pProbe;
148127      b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
148128      /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
148129      assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
148130      if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
148131        /* Integer primary key index */
148132        pNew->wsFlags = WHERE_IPK;
148133  
148134        /* Full table scan */
148135        pNew->iSortIdx = b ? iSortIdx : 0;
148136        /* TUNING: Cost of full table scan is (N*3.0). */
148137        pNew->rRun = rSize + 16;
148138        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
148139        whereLoopOutputAdjust(pWC, pNew, rSize);
148140        rc = whereLoopInsert(pBuilder, pNew);
148141        pNew->nOut = rSize;
148142        if( rc ) break;
148143      }else{
148144        Bitmask m;
148145        if( pProbe->isCovering ){
148146          pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
148147          m = 0;
148148        }else{
148149          m = pSrc->colUsed & pProbe->colNotIdxed;
148150          pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
148151        }
148152  
148153        /* Full scan via index */
148154        if( b
148155         || !HasRowid(pTab)
148156         || pProbe->pPartIdxWhere!=0
148157         || ( m==0
148158           && pProbe->bUnordered==0
148159           && (pProbe->szIdxRow<pTab->szTabRow)
148160           && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
148161           && sqlite3GlobalConfig.bUseCis
148162           && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
148163            )
148164        ){
148165          pNew->iSortIdx = b ? iSortIdx : 0;
148166  
148167          /* The cost of visiting the index rows is N*K, where K is
148168          ** between 1.1 and 3.0, depending on the relative sizes of the
148169          ** index and table rows. */
148170          pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
148171          if( m!=0 ){
148172            /* If this is a non-covering index scan, add in the cost of
148173            ** doing table lookups.  The cost will be 3x the number of
148174            ** lookups.  Take into account WHERE clause terms that can be
148175            ** satisfied using just the index, and that do not require a
148176            ** table lookup. */
148177            LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
148178            int ii;
148179            int iCur = pSrc->iCursor;
148180            WhereClause *pWC2 = &pWInfo->sWC;
148181            for(ii=0; ii<pWC2->nTerm; ii++){
148182              WhereTerm *pTerm = &pWC2->a[ii];
148183              if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
148184                break;
148185              }
148186              /* pTerm can be evaluated using just the index.  So reduce
148187              ** the expected number of table lookups accordingly */
148188              if( pTerm->truthProb<=0 ){
148189                nLookup += pTerm->truthProb;
148190              }else{
148191                nLookup--;
148192                if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
148193              }
148194            }
148195            
148196            pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
148197          }
148198          ApplyCostMultiplier(pNew->rRun, pTab->costMult);
148199          whereLoopOutputAdjust(pWC, pNew, rSize);
148200          rc = whereLoopInsert(pBuilder, pNew);
148201          pNew->nOut = rSize;
148202          if( rc ) break;
148203        }
148204      }
148205  
148206      pBuilder->bldFlags = 0;
148207      rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
148208      if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
148209        /* If a non-unique index is used, or if a prefix of the key for
148210        ** unique index is used (making the index functionally non-unique)
148211        ** then the sqlite_stat1 data becomes important for scoring the
148212        ** plan */
148213        pTab->tabFlags |= TF_StatsUsed;
148214      }
148215  #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
148216      sqlite3Stat4ProbeFree(pBuilder->pRec);
148217      pBuilder->nRecValid = 0;
148218      pBuilder->pRec = 0;
148219  #endif
148220    }
148221    return rc;
148222  }
148223  
148224  #ifndef SQLITE_OMIT_VIRTUALTABLE
148225  
148226  /*
148227  ** Argument pIdxInfo is already populated with all constraints that may
148228  ** be used by the virtual table identified by pBuilder->pNew->iTab. This
148229  ** function marks a subset of those constraints usable, invokes the
148230  ** xBestIndex method and adds the returned plan to pBuilder.
148231  **
148232  ** A constraint is marked usable if:
148233  **
148234  **   * Argument mUsable indicates that its prerequisites are available, and
148235  **
148236  **   * It is not one of the operators specified in the mExclude mask passed
148237  **     as the fourth argument (which in practice is either WO_IN or 0).
148238  **
148239  ** Argument mPrereq is a mask of tables that must be scanned before the
148240  ** virtual table in question. These are added to the plans prerequisites
148241  ** before it is added to pBuilder.
148242  **
148243  ** Output parameter *pbIn is set to true if the plan added to pBuilder
148244  ** uses one or more WO_IN terms, or false otherwise.
148245  */
148246  static int whereLoopAddVirtualOne(
148247    WhereLoopBuilder *pBuilder,
148248    Bitmask mPrereq,                /* Mask of tables that must be used. */
148249    Bitmask mUsable,                /* Mask of usable tables */
148250    u16 mExclude,                   /* Exclude terms using these operators */
148251    sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
148252    u16 mNoOmit,                    /* Do not omit these constraints */
148253    int *pbIn                       /* OUT: True if plan uses an IN(...) op */
148254  ){
148255    WhereClause *pWC = pBuilder->pWC;
148256    struct sqlite3_index_constraint *pIdxCons;
148257    struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
148258    int i;
148259    int mxTerm;
148260    int rc = SQLITE_OK;
148261    WhereLoop *pNew = pBuilder->pNew;
148262    Parse *pParse = pBuilder->pWInfo->pParse;
148263    struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
148264    int nConstraint = pIdxInfo->nConstraint;
148265  
148266    assert( (mUsable & mPrereq)==mPrereq );
148267    *pbIn = 0;
148268    pNew->prereq = mPrereq;
148269  
148270    /* Set the usable flag on the subset of constraints identified by 
148271    ** arguments mUsable and mExclude. */
148272    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
148273    for(i=0; i<nConstraint; i++, pIdxCons++){
148274      WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
148275      pIdxCons->usable = 0;
148276      if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 
148277       && (pTerm->eOperator & mExclude)==0
148278      ){
148279        pIdxCons->usable = 1;
148280      }
148281    }
148282  
148283    /* Initialize the output fields of the sqlite3_index_info structure */
148284    memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
148285    assert( pIdxInfo->needToFreeIdxStr==0 );
148286    pIdxInfo->idxStr = 0;
148287    pIdxInfo->idxNum = 0;
148288    pIdxInfo->orderByConsumed = 0;
148289    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
148290    pIdxInfo->estimatedRows = 25;
148291    pIdxInfo->idxFlags = 0;
148292    pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
148293  
148294    /* Invoke the virtual table xBestIndex() method */
148295    rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
148296    if( rc ){
148297      if( rc==SQLITE_CONSTRAINT ){
148298        /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
148299        ** that the particular combination of parameters provided is unusable.
148300        ** Make no entries in the loop table.
148301        */
148302        WHERETRACE(0xffff, ("  ^^^^--- non-viable plan rejected!\n"));
148303        return SQLITE_OK;
148304      }
148305      return rc;
148306    }
148307  
148308    mxTerm = -1;
148309    assert( pNew->nLSlot>=nConstraint );
148310    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
148311    pNew->u.vtab.omitMask = 0;
148312    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
148313    for(i=0; i<nConstraint; i++, pIdxCons++){
148314      int iTerm;
148315      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
148316        WhereTerm *pTerm;
148317        int j = pIdxCons->iTermOffset;
148318        if( iTerm>=nConstraint
148319         || j<0
148320         || j>=pWC->nTerm
148321         || pNew->aLTerm[iTerm]!=0
148322         || pIdxCons->usable==0
148323        ){
148324          sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
148325          testcase( pIdxInfo->needToFreeIdxStr );
148326          return SQLITE_ERROR;
148327        }
148328        testcase( iTerm==nConstraint-1 );
148329        testcase( j==0 );
148330        testcase( j==pWC->nTerm-1 );
148331        pTerm = &pWC->a[j];
148332        pNew->prereq |= pTerm->prereqRight;
148333        assert( iTerm<pNew->nLSlot );
148334        pNew->aLTerm[iTerm] = pTerm;
148335        if( iTerm>mxTerm ) mxTerm = iTerm;
148336        testcase( iTerm==15 );
148337        testcase( iTerm==16 );
148338        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
148339        if( (pTerm->eOperator & WO_IN)!=0 ){
148340          /* A virtual table that is constrained by an IN clause may not
148341          ** consume the ORDER BY clause because (1) the order of IN terms
148342          ** is not necessarily related to the order of output terms and
148343          ** (2) Multiple outputs from a single IN value will not merge
148344          ** together.  */
148345          pIdxInfo->orderByConsumed = 0;
148346          pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
148347          *pbIn = 1; assert( (mExclude & WO_IN)==0 );
148348        }
148349      }
148350    }
148351    pNew->u.vtab.omitMask &= ~mNoOmit;
148352  
148353    pNew->nLTerm = mxTerm+1;
148354    for(i=0; i<=mxTerm; i++){
148355      if( pNew->aLTerm[i]==0 ){
148356        /* The non-zero argvIdx values must be contiguous.  Raise an
148357        ** error if they are not */
148358        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
148359        testcase( pIdxInfo->needToFreeIdxStr );
148360        return SQLITE_ERROR;
148361      }
148362    }
148363    assert( pNew->nLTerm<=pNew->nLSlot );
148364    pNew->u.vtab.idxNum = pIdxInfo->idxNum;
148365    pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
148366    pIdxInfo->needToFreeIdxStr = 0;
148367    pNew->u.vtab.idxStr = pIdxInfo->idxStr;
148368    pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
148369        pIdxInfo->nOrderBy : 0);
148370    pNew->rSetup = 0;
148371    pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
148372    pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
148373  
148374    /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
148375    ** that the scan will visit at most one row. Clear it otherwise. */
148376    if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
148377      pNew->wsFlags |= WHERE_ONEROW;
148378    }else{
148379      pNew->wsFlags &= ~WHERE_ONEROW;
148380    }
148381    rc = whereLoopInsert(pBuilder, pNew);
148382    if( pNew->u.vtab.needFree ){
148383      sqlite3_free(pNew->u.vtab.idxStr);
148384      pNew->u.vtab.needFree = 0;
148385    }
148386    WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
148387                        *pbIn, (sqlite3_uint64)mPrereq,
148388                        (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
148389  
148390    return rc;
148391  }
148392  
148393  /*
148394  ** If this function is invoked from within an xBestIndex() callback, it
148395  ** returns a pointer to a buffer containing the name of the collation
148396  ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
148397  ** array. Or, if iCons is out of range or there is no active xBestIndex
148398  ** call, return NULL.
148399  */
148400  SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
148401    HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
148402    const char *zRet = 0;
148403    if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
148404      CollSeq *pC = 0;
148405      int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
148406      Expr *pX = pHidden->pWC->a[iTerm].pExpr;
148407      if( pX->pLeft ){
148408        pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
148409      }
148410      zRet = (pC ? pC->zName : sqlite3StrBINARY);
148411    }
148412    return zRet;
148413  }
148414  
148415  /*
148416  ** Add all WhereLoop objects for a table of the join identified by
148417  ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
148418  **
148419  ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
148420  ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
148421  ** entries that occur before the virtual table in the FROM clause and are
148422  ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
148423  ** mUnusable mask contains all FROM clause entries that occur after the
148424  ** virtual table and are separated from it by at least one LEFT or 
148425  ** CROSS JOIN. 
148426  **
148427  ** For example, if the query were:
148428  **
148429  **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
148430  **
148431  ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
148432  **
148433  ** All the tables in mPrereq must be scanned before the current virtual 
148434  ** table. So any terms for which all prerequisites are satisfied by 
148435  ** mPrereq may be specified as "usable" in all calls to xBestIndex. 
148436  ** Conversely, all tables in mUnusable must be scanned after the current
148437  ** virtual table, so any terms for which the prerequisites overlap with
148438  ** mUnusable should always be configured as "not-usable" for xBestIndex.
148439  */
148440  static int whereLoopAddVirtual(
148441    WhereLoopBuilder *pBuilder,  /* WHERE clause information */
148442    Bitmask mPrereq,             /* Tables that must be scanned before this one */
148443    Bitmask mUnusable            /* Tables that must be scanned after this one */
148444  ){
148445    int rc = SQLITE_OK;          /* Return code */
148446    WhereInfo *pWInfo;           /* WHERE analysis context */
148447    Parse *pParse;               /* The parsing context */
148448    WhereClause *pWC;            /* The WHERE clause */
148449    struct SrcList_item *pSrc;   /* The FROM clause term to search */
148450    sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
148451    int nConstraint;             /* Number of constraints in p */
148452    int bIn;                     /* True if plan uses IN(...) operator */
148453    WhereLoop *pNew;
148454    Bitmask mBest;               /* Tables used by best possible plan */
148455    u16 mNoOmit;
148456  
148457    assert( (mPrereq & mUnusable)==0 );
148458    pWInfo = pBuilder->pWInfo;
148459    pParse = pWInfo->pParse;
148460    pWC = pBuilder->pWC;
148461    pNew = pBuilder->pNew;
148462    pSrc = &pWInfo->pTabList->a[pNew->iTab];
148463    assert( IsVirtual(pSrc->pTab) );
148464    p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, 
148465        &mNoOmit);
148466    if( p==0 ) return SQLITE_NOMEM_BKPT;
148467    pNew->rSetup = 0;
148468    pNew->wsFlags = WHERE_VIRTUALTABLE;
148469    pNew->nLTerm = 0;
148470    pNew->u.vtab.needFree = 0;
148471    nConstraint = p->nConstraint;
148472    if( whereLoopResize(pParse->db, pNew, nConstraint) ){
148473      sqlite3DbFree(pParse->db, p);
148474      return SQLITE_NOMEM_BKPT;
148475    }
148476  
148477    /* First call xBestIndex() with all constraints usable. */
148478    WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
148479    WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
148480    rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
148481  
148482    /* If the call to xBestIndex() with all terms enabled produced a plan
148483    ** that does not require any source tables (IOW: a plan with mBest==0),
148484    ** then there is no point in making any further calls to xBestIndex() 
148485    ** since they will all return the same result (if the xBestIndex()
148486    ** implementation is sane). */
148487    if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
148488      int seenZero = 0;             /* True if a plan with no prereqs seen */
148489      int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
148490      Bitmask mPrev = 0;
148491      Bitmask mBestNoIn = 0;
148492  
148493      /* If the plan produced by the earlier call uses an IN(...) term, call
148494      ** xBestIndex again, this time with IN(...) terms disabled. */
148495      if( bIn ){
148496        WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
148497        rc = whereLoopAddVirtualOne(
148498            pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
148499        assert( bIn==0 );
148500        mBestNoIn = pNew->prereq & ~mPrereq;
148501        if( mBestNoIn==0 ){
148502          seenZero = 1;
148503          seenZeroNoIN = 1;
148504        }
148505      }
148506  
148507      /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 
148508      ** in the set of terms that apply to the current virtual table.  */
148509      while( rc==SQLITE_OK ){
148510        int i;
148511        Bitmask mNext = ALLBITS;
148512        assert( mNext>0 );
148513        for(i=0; i<nConstraint; i++){
148514          Bitmask mThis = (
148515              pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
148516          );
148517          if( mThis>mPrev && mThis<mNext ) mNext = mThis;
148518        }
148519        mPrev = mNext;
148520        if( mNext==ALLBITS ) break;
148521        if( mNext==mBest || mNext==mBestNoIn ) continue;
148522        WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
148523                         (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
148524        rc = whereLoopAddVirtualOne(
148525            pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
148526        if( pNew->prereq==mPrereq ){
148527          seenZero = 1;
148528          if( bIn==0 ) seenZeroNoIN = 1;
148529        }
148530      }
148531  
148532      /* If the calls to xBestIndex() in the above loop did not find a plan
148533      ** that requires no source tables at all (i.e. one guaranteed to be
148534      ** usable), make a call here with all source tables disabled */
148535      if( rc==SQLITE_OK && seenZero==0 ){
148536        WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
148537        rc = whereLoopAddVirtualOne(
148538            pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
148539        if( bIn==0 ) seenZeroNoIN = 1;
148540      }
148541  
148542      /* If the calls to xBestIndex() have so far failed to find a plan
148543      ** that requires no source tables at all and does not use an IN(...)
148544      ** operator, make a final call to obtain one here.  */
148545      if( rc==SQLITE_OK && seenZeroNoIN==0 ){
148546        WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
148547        rc = whereLoopAddVirtualOne(
148548            pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
148549      }
148550    }
148551  
148552    if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
148553    sqlite3DbFreeNN(pParse->db, p);
148554    WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
148555    return rc;
148556  }
148557  #endif /* SQLITE_OMIT_VIRTUALTABLE */
148558  
148559  /*
148560  ** Add WhereLoop entries to handle OR terms.  This works for either
148561  ** btrees or virtual tables.
148562  */
148563  static int whereLoopAddOr(
148564    WhereLoopBuilder *pBuilder, 
148565    Bitmask mPrereq, 
148566    Bitmask mUnusable
148567  ){
148568    WhereInfo *pWInfo = pBuilder->pWInfo;
148569    WhereClause *pWC;
148570    WhereLoop *pNew;
148571    WhereTerm *pTerm, *pWCEnd;
148572    int rc = SQLITE_OK;
148573    int iCur;
148574    WhereClause tempWC;
148575    WhereLoopBuilder sSubBuild;
148576    WhereOrSet sSum, sCur;
148577    struct SrcList_item *pItem;
148578    
148579    pWC = pBuilder->pWC;
148580    pWCEnd = pWC->a + pWC->nTerm;
148581    pNew = pBuilder->pNew;
148582    memset(&sSum, 0, sizeof(sSum));
148583    pItem = pWInfo->pTabList->a + pNew->iTab;
148584    iCur = pItem->iCursor;
148585  
148586    for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
148587      if( (pTerm->eOperator & WO_OR)!=0
148588       && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
148589      ){
148590        WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
148591        WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
148592        WhereTerm *pOrTerm;
148593        int once = 1;
148594        int i, j;
148595      
148596        sSubBuild = *pBuilder;
148597        sSubBuild.pOrderBy = 0;
148598        sSubBuild.pOrSet = &sCur;
148599  
148600        WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
148601        for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
148602          if( (pOrTerm->eOperator & WO_AND)!=0 ){
148603            sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
148604          }else if( pOrTerm->leftCursor==iCur ){
148605            tempWC.pWInfo = pWC->pWInfo;
148606            tempWC.pOuter = pWC;
148607            tempWC.op = TK_AND;
148608            tempWC.nTerm = 1;
148609            tempWC.a = pOrTerm;
148610            sSubBuild.pWC = &tempWC;
148611          }else{
148612            continue;
148613          }
148614          sCur.n = 0;
148615  #ifdef WHERETRACE_ENABLED
148616          WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 
148617                     (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
148618          if( sqlite3WhereTrace & 0x400 ){
148619            sqlite3WhereClausePrint(sSubBuild.pWC);
148620          }
148621  #endif
148622  #ifndef SQLITE_OMIT_VIRTUALTABLE
148623          if( IsVirtual(pItem->pTab) ){
148624            rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
148625          }else
148626  #endif
148627          {
148628            rc = whereLoopAddBtree(&sSubBuild, mPrereq);
148629          }
148630          if( rc==SQLITE_OK ){
148631            rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
148632          }
148633          assert( rc==SQLITE_OK || sCur.n==0 );
148634          if( sCur.n==0 ){
148635            sSum.n = 0;
148636            break;
148637          }else if( once ){
148638            whereOrMove(&sSum, &sCur);
148639            once = 0;
148640          }else{
148641            WhereOrSet sPrev;
148642            whereOrMove(&sPrev, &sSum);
148643            sSum.n = 0;
148644            for(i=0; i<sPrev.n; i++){
148645              for(j=0; j<sCur.n; j++){
148646                whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
148647                              sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
148648                              sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
148649              }
148650            }
148651          }
148652        }
148653        pNew->nLTerm = 1;
148654        pNew->aLTerm[0] = pTerm;
148655        pNew->wsFlags = WHERE_MULTI_OR;
148656        pNew->rSetup = 0;
148657        pNew->iSortIdx = 0;
148658        memset(&pNew->u, 0, sizeof(pNew->u));
148659        for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
148660          /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
148661          ** of all sub-scans required by the OR-scan. However, due to rounding
148662          ** errors, it may be that the cost of the OR-scan is equal to its
148663          ** most expensive sub-scan. Add the smallest possible penalty 
148664          ** (equivalent to multiplying the cost by 1.07) to ensure that 
148665          ** this does not happen. Otherwise, for WHERE clauses such as the
148666          ** following where there is an index on "y":
148667          **
148668          **     WHERE likelihood(x=?, 0.99) OR y=?
148669          **
148670          ** the planner may elect to "OR" together a full-table scan and an
148671          ** index lookup. And other similarly odd results.  */
148672          pNew->rRun = sSum.a[i].rRun + 1;
148673          pNew->nOut = sSum.a[i].nOut;
148674          pNew->prereq = sSum.a[i].prereq;
148675          rc = whereLoopInsert(pBuilder, pNew);
148676        }
148677        WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
148678      }
148679    }
148680    return rc;
148681  }
148682  
148683  /*
148684  ** Add all WhereLoop objects for all tables 
148685  */
148686  static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
148687    WhereInfo *pWInfo = pBuilder->pWInfo;
148688    Bitmask mPrereq = 0;
148689    Bitmask mPrior = 0;
148690    int iTab;
148691    SrcList *pTabList = pWInfo->pTabList;
148692    struct SrcList_item *pItem;
148693    struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
148694    sqlite3 *db = pWInfo->pParse->db;
148695    int rc = SQLITE_OK;
148696    WhereLoop *pNew;
148697    u8 priorJointype = 0;
148698  
148699    /* Loop over the tables in the join, from left to right */
148700    pNew = pBuilder->pNew;
148701    whereLoopInit(pNew);
148702    pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
148703    for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
148704      Bitmask mUnusable = 0;
148705      pNew->iTab = iTab;
148706      pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
148707      pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
148708      if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
148709        /* This condition is true when pItem is the FROM clause term on the
148710        ** right-hand-side of a LEFT or CROSS JOIN.  */
148711        mPrereq = mPrior;
148712      }
148713      priorJointype = pItem->fg.jointype;
148714  #ifndef SQLITE_OMIT_VIRTUALTABLE
148715      if( IsVirtual(pItem->pTab) ){
148716        struct SrcList_item *p;
148717        for(p=&pItem[1]; p<pEnd; p++){
148718          if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
148719            mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
148720          }
148721        }
148722        rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
148723      }else
148724  #endif /* SQLITE_OMIT_VIRTUALTABLE */
148725      {
148726        rc = whereLoopAddBtree(pBuilder, mPrereq);
148727      }
148728      if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
148729        rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
148730      }
148731      mPrior |= pNew->maskSelf;
148732      if( rc || db->mallocFailed ){
148733        if( rc==SQLITE_DONE ){
148734          /* We hit the query planner search limit set by iPlanLimit */
148735          sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
148736          rc = SQLITE_OK;
148737        }else{
148738          break;
148739        }
148740      }
148741    }
148742  
148743    whereLoopClear(db, pNew);
148744    return rc;
148745  }
148746  
148747  /*
148748  ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
148749  ** parameters) to see if it outputs rows in the requested ORDER BY
148750  ** (or GROUP BY) without requiring a separate sort operation.  Return N:
148751  ** 
148752  **   N>0:   N terms of the ORDER BY clause are satisfied
148753  **   N==0:  No terms of the ORDER BY clause are satisfied
148754  **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   
148755  **
148756  ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
148757  ** strict.  With GROUP BY and DISTINCT the only requirement is that
148758  ** equivalent rows appear immediately adjacent to one another.  GROUP BY
148759  ** and DISTINCT do not require rows to appear in any particular order as long
148760  ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
148761  ** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
148762  ** pOrderBy terms must be matched in strict left-to-right order.
148763  */
148764  static i8 wherePathSatisfiesOrderBy(
148765    WhereInfo *pWInfo,    /* The WHERE clause */
148766    ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
148767    WherePath *pPath,     /* The WherePath to check */
148768    u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
148769    u16 nLoop,            /* Number of entries in pPath->aLoop[] */
148770    WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
148771    Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
148772  ){
148773    u8 revSet;            /* True if rev is known */
148774    u8 rev;               /* Composite sort order */
148775    u8 revIdx;            /* Index sort order */
148776    u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
148777    u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
148778    u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
148779    u16 eqOpMask;         /* Allowed equality operators */
148780    u16 nKeyCol;          /* Number of key columns in pIndex */
148781    u16 nColumn;          /* Total number of ordered columns in the index */
148782    u16 nOrderBy;         /* Number terms in the ORDER BY clause */
148783    int iLoop;            /* Index of WhereLoop in pPath being processed */
148784    int i, j;             /* Loop counters */
148785    int iCur;             /* Cursor number for current WhereLoop */
148786    int iColumn;          /* A column number within table iCur */
148787    WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
148788    WhereTerm *pTerm;     /* A single term of the WHERE clause */
148789    Expr *pOBExpr;        /* An expression from the ORDER BY clause */
148790    CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
148791    Index *pIndex;        /* The index associated with pLoop */
148792    sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
148793    Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
148794    Bitmask obDone;       /* Mask of all ORDER BY terms */
148795    Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
148796    Bitmask ready;              /* Mask of inner loops */
148797  
148798    /*
148799    ** We say the WhereLoop is "one-row" if it generates no more than one
148800    ** row of output.  A WhereLoop is one-row if all of the following are true:
148801    **  (a) All index columns match with WHERE_COLUMN_EQ.
148802    **  (b) The index is unique
148803    ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
148804    ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
148805    **
148806    ** We say the WhereLoop is "order-distinct" if the set of columns from
148807    ** that WhereLoop that are in the ORDER BY clause are different for every
148808    ** row of the WhereLoop.  Every one-row WhereLoop is automatically
148809    ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
148810    ** is not order-distinct. To be order-distinct is not quite the same as being
148811    ** UNIQUE since a UNIQUE column or index can have multiple rows that 
148812    ** are NULL and NULL values are equivalent for the purpose of order-distinct.
148813    ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
148814    **
148815    ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
148816    ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
148817    ** automatically order-distinct.
148818    */
148819  
148820    assert( pOrderBy!=0 );
148821    if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
148822  
148823    nOrderBy = pOrderBy->nExpr;
148824    testcase( nOrderBy==BMS-1 );
148825    if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
148826    isOrderDistinct = 1;
148827    obDone = MASKBIT(nOrderBy)-1;
148828    orderDistinctMask = 0;
148829    ready = 0;
148830    eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
148831    if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
148832    for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
148833      if( iLoop>0 ) ready |= pLoop->maskSelf;
148834      if( iLoop<nLoop ){
148835        pLoop = pPath->aLoop[iLoop];
148836        if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
148837      }else{
148838        pLoop = pLast;
148839      }
148840      if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
148841        if( pLoop->u.vtab.isOrdered ) obSat = obDone;
148842        break;
148843      }else{
148844        pLoop->u.btree.nIdxCol = 0;
148845      }
148846      iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
148847  
148848      /* Mark off any ORDER BY term X that is a column in the table of
148849      ** the current loop for which there is term in the WHERE
148850      ** clause of the form X IS NULL or X=? that reference only outer
148851      ** loops.
148852      */
148853      for(i=0; i<nOrderBy; i++){
148854        if( MASKBIT(i) & obSat ) continue;
148855        pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
148856        if( pOBExpr->op!=TK_COLUMN ) continue;
148857        if( pOBExpr->iTable!=iCur ) continue;
148858        pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
148859                         ~ready, eqOpMask, 0);
148860        if( pTerm==0 ) continue;
148861        if( pTerm->eOperator==WO_IN ){
148862          /* IN terms are only valid for sorting in the ORDER BY LIMIT 
148863          ** optimization, and then only if they are actually used
148864          ** by the query plan */
148865          assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
148866          for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
148867          if( j>=pLoop->nLTerm ) continue;
148868        }
148869        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
148870          if( sqlite3ExprCollSeqMatch(pWInfo->pParse, 
148871                    pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
148872            continue;
148873          }
148874          testcase( pTerm->pExpr->op==TK_IS );
148875        }
148876        obSat |= MASKBIT(i);
148877      }
148878  
148879      if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
148880        if( pLoop->wsFlags & WHERE_IPK ){
148881          pIndex = 0;
148882          nKeyCol = 0;
148883          nColumn = 1;
148884        }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
148885          return 0;
148886        }else{
148887          nKeyCol = pIndex->nKeyCol;
148888          nColumn = pIndex->nColumn;
148889          assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
148890          assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
148891                            || !HasRowid(pIndex->pTable));
148892          isOrderDistinct = IsUniqueIndex(pIndex);
148893        }
148894  
148895        /* Loop through all columns of the index and deal with the ones
148896        ** that are not constrained by == or IN.
148897        */
148898        rev = revSet = 0;
148899        distinctColumns = 0;
148900        for(j=0; j<nColumn; j++){
148901          u8 bOnce = 1; /* True to run the ORDER BY search loop */
148902  
148903          assert( j>=pLoop->u.btree.nEq 
148904              || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
148905          );
148906          if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
148907            u16 eOp = pLoop->aLTerm[j]->eOperator;
148908  
148909            /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
148910            ** doing WHERE_ORDERBY_LIMIT processing). 
148911            **
148912            ** If the current term is a column of an ((?,?) IN (SELECT...)) 
148913            ** expression for which the SELECT returns more than one column,
148914            ** check that it is the only column used by this loop. Otherwise,
148915            ** if it is one of two or more, none of the columns can be
148916            ** considered to match an ORDER BY term.  */
148917            if( (eOp & eqOpMask)!=0 ){
148918              if( eOp & WO_ISNULL ){
148919                testcase( isOrderDistinct );
148920                isOrderDistinct = 0;
148921              }
148922              continue;  
148923            }else if( ALWAYS(eOp & WO_IN) ){
148924              /* ALWAYS() justification: eOp is an equality operator due to the
148925              ** j<pLoop->u.btree.nEq constraint above.  Any equality other
148926              ** than WO_IN is captured by the previous "if".  So this one
148927              ** always has to be WO_IN. */
148928              Expr *pX = pLoop->aLTerm[j]->pExpr;
148929              for(i=j+1; i<pLoop->u.btree.nEq; i++){
148930                if( pLoop->aLTerm[i]->pExpr==pX ){
148931                  assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
148932                  bOnce = 0;
148933                  break;
148934                }
148935              }
148936            }
148937          }
148938  
148939          /* Get the column number in the table (iColumn) and sort order
148940          ** (revIdx) for the j-th column of the index.
148941          */
148942          if( pIndex ){
148943            iColumn = pIndex->aiColumn[j];
148944            revIdx = pIndex->aSortOrder[j];
148945            if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
148946          }else{
148947            iColumn = XN_ROWID;
148948            revIdx = 0;
148949          }
148950  
148951          /* An unconstrained column that might be NULL means that this
148952          ** WhereLoop is not well-ordered
148953          */
148954          if( isOrderDistinct
148955           && iColumn>=0
148956           && j>=pLoop->u.btree.nEq
148957           && pIndex->pTable->aCol[iColumn].notNull==0
148958          ){
148959            isOrderDistinct = 0;
148960          }
148961  
148962          /* Find the ORDER BY term that corresponds to the j-th column
148963          ** of the index and mark that ORDER BY term off 
148964          */
148965          isMatch = 0;
148966          for(i=0; bOnce && i<nOrderBy; i++){
148967            if( MASKBIT(i) & obSat ) continue;
148968            pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
148969            testcase( wctrlFlags & WHERE_GROUPBY );
148970            testcase( wctrlFlags & WHERE_DISTINCTBY );
148971            if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
148972            if( iColumn>=XN_ROWID ){
148973              if( pOBExpr->op!=TK_COLUMN ) continue;
148974              if( pOBExpr->iTable!=iCur ) continue;
148975              if( pOBExpr->iColumn!=iColumn ) continue;
148976            }else{
148977              Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
148978              if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
148979                continue;
148980              }
148981            }
148982            if( iColumn!=XN_ROWID ){
148983              pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
148984              if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
148985            }
148986            pLoop->u.btree.nIdxCol = j+1;
148987            isMatch = 1;
148988            break;
148989          }
148990          if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
148991            /* Make sure the sort order is compatible in an ORDER BY clause.
148992            ** Sort order is irrelevant for a GROUP BY clause. */
148993            if( revSet ){
148994              if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
148995            }else{
148996              rev = revIdx ^ pOrderBy->a[i].sortOrder;
148997              if( rev ) *pRevMask |= MASKBIT(iLoop);
148998              revSet = 1;
148999            }
149000          }
149001          if( isMatch ){
149002            if( iColumn==XN_ROWID ){
149003              testcase( distinctColumns==0 );
149004              distinctColumns = 1;
149005            }
149006            obSat |= MASKBIT(i);
149007          }else{
149008            /* No match found */
149009            if( j==0 || j<nKeyCol ){
149010              testcase( isOrderDistinct!=0 );
149011              isOrderDistinct = 0;
149012            }
149013            break;
149014          }
149015        } /* end Loop over all index columns */
149016        if( distinctColumns ){
149017          testcase( isOrderDistinct==0 );
149018          isOrderDistinct = 1;
149019        }
149020      } /* end-if not one-row */
149021  
149022      /* Mark off any other ORDER BY terms that reference pLoop */
149023      if( isOrderDistinct ){
149024        orderDistinctMask |= pLoop->maskSelf;
149025        for(i=0; i<nOrderBy; i++){
149026          Expr *p;
149027          Bitmask mTerm;
149028          if( MASKBIT(i) & obSat ) continue;
149029          p = pOrderBy->a[i].pExpr;
149030          mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
149031          if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
149032          if( (mTerm&~orderDistinctMask)==0 ){
149033            obSat |= MASKBIT(i);
149034          }
149035        }
149036      }
149037    } /* End the loop over all WhereLoops from outer-most down to inner-most */
149038    if( obSat==obDone ) return (i8)nOrderBy;
149039    if( !isOrderDistinct ){
149040      for(i=nOrderBy-1; i>0; i--){
149041        Bitmask m = MASKBIT(i) - 1;
149042        if( (obSat&m)==m ) return i;
149043      }
149044      return 0;
149045    }
149046    return -1;
149047  }
149048  
149049  
149050  /*
149051  ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
149052  ** the planner assumes that the specified pOrderBy list is actually a GROUP
149053  ** BY clause - and so any order that groups rows as required satisfies the
149054  ** request.
149055  **
149056  ** Normally, in this case it is not possible for the caller to determine
149057  ** whether or not the rows are really being delivered in sorted order, or
149058  ** just in some other order that provides the required grouping. However,
149059  ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
149060  ** this function may be called on the returned WhereInfo object. It returns
149061  ** true if the rows really will be sorted in the specified order, or false
149062  ** otherwise.
149063  **
149064  ** For example, assuming:
149065  **
149066  **   CREATE INDEX i1 ON t1(x, Y);
149067  **
149068  ** then
149069  **
149070  **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
149071  **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
149072  */
149073  SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
149074    assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
149075    assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
149076    return pWInfo->sorted;
149077  }
149078  
149079  #ifdef WHERETRACE_ENABLED
149080  /* For debugging use only: */
149081  static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
149082    static char zName[65];
149083    int i;
149084    for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
149085    if( pLast ) zName[i++] = pLast->cId;
149086    zName[i] = 0;
149087    return zName;
149088  }
149089  #endif
149090  
149091  /*
149092  ** Return the cost of sorting nRow rows, assuming that the keys have 
149093  ** nOrderby columns and that the first nSorted columns are already in
149094  ** order.
149095  */
149096  static LogEst whereSortingCost(
149097    WhereInfo *pWInfo,
149098    LogEst nRow,
149099    int nOrderBy,
149100    int nSorted
149101  ){
149102    /* TUNING: Estimated cost of a full external sort, where N is 
149103    ** the number of rows to sort is:
149104    **
149105    **   cost = (3.0 * N * log(N)).
149106    ** 
149107    ** Or, if the order-by clause has X terms but only the last Y 
149108    ** terms are out of order, then block-sorting will reduce the 
149109    ** sorting cost to:
149110    **
149111    **   cost = (3.0 * N * log(N)) * (Y/X)
149112    **
149113    ** The (Y/X) term is implemented using stack variable rScale
149114    ** below.  */
149115    LogEst rScale, rSortCost;
149116    assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
149117    rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
149118    rSortCost = nRow + rScale + 16;
149119  
149120    /* Multiple by log(M) where M is the number of output rows.
149121    ** Use the LIMIT for M if it is smaller */
149122    if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
149123      nRow = pWInfo->iLimit;
149124    }
149125    rSortCost += estLog(nRow);
149126    return rSortCost;
149127  }
149128  
149129  /*
149130  ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
149131  ** attempts to find the lowest cost path that visits each WhereLoop
149132  ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
149133  **
149134  ** Assume that the total number of output rows that will need to be sorted
149135  ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
149136  ** costs if nRowEst==0.
149137  **
149138  ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
149139  ** error occurs.
149140  */
149141  static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
149142    int mxChoice;             /* Maximum number of simultaneous paths tracked */
149143    int nLoop;                /* Number of terms in the join */
149144    Parse *pParse;            /* Parsing context */
149145    sqlite3 *db;              /* The database connection */
149146    int iLoop;                /* Loop counter over the terms of the join */
149147    int ii, jj;               /* Loop counters */
149148    int mxI = 0;              /* Index of next entry to replace */
149149    int nOrderBy;             /* Number of ORDER BY clause terms */
149150    LogEst mxCost = 0;        /* Maximum cost of a set of paths */
149151    LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
149152    int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
149153    WherePath *aFrom;         /* All nFrom paths at the previous level */
149154    WherePath *aTo;           /* The nTo best paths at the current level */
149155    WherePath *pFrom;         /* An element of aFrom[] that we are working on */
149156    WherePath *pTo;           /* An element of aTo[] that we are working on */
149157    WhereLoop *pWLoop;        /* One of the WhereLoop objects */
149158    WhereLoop **pX;           /* Used to divy up the pSpace memory */
149159    LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
149160    char *pSpace;             /* Temporary memory used by this routine */
149161    int nSpace;               /* Bytes of space allocated at pSpace */
149162  
149163    pParse = pWInfo->pParse;
149164    db = pParse->db;
149165    nLoop = pWInfo->nLevel;
149166    /* TUNING: For simple queries, only the best path is tracked.
149167    ** For 2-way joins, the 5 best paths are followed.
149168    ** For joins of 3 or more tables, track the 10 best paths */
149169    mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
149170    assert( nLoop<=pWInfo->pTabList->nSrc );
149171    WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
149172  
149173    /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
149174    ** case the purpose of this call is to estimate the number of rows returned
149175    ** by the overall query. Once this estimate has been obtained, the caller
149176    ** will invoke this function a second time, passing the estimate as the
149177    ** nRowEst parameter.  */
149178    if( pWInfo->pOrderBy==0 || nRowEst==0 ){
149179      nOrderBy = 0;
149180    }else{
149181      nOrderBy = pWInfo->pOrderBy->nExpr;
149182    }
149183  
149184    /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
149185    nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
149186    nSpace += sizeof(LogEst) * nOrderBy;
149187    pSpace = sqlite3DbMallocRawNN(db, nSpace);
149188    if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
149189    aTo = (WherePath*)pSpace;
149190    aFrom = aTo+mxChoice;
149191    memset(aFrom, 0, sizeof(aFrom[0]));
149192    pX = (WhereLoop**)(aFrom+mxChoice);
149193    for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
149194      pFrom->aLoop = pX;
149195    }
149196    if( nOrderBy ){
149197      /* If there is an ORDER BY clause and it is not being ignored, set up
149198      ** space for the aSortCost[] array. Each element of the aSortCost array
149199      ** is either zero - meaning it has not yet been initialized - or the
149200      ** cost of sorting nRowEst rows of data where the first X terms of
149201      ** the ORDER BY clause are already in order, where X is the array 
149202      ** index.  */
149203      aSortCost = (LogEst*)pX;
149204      memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
149205    }
149206    assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
149207    assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
149208  
149209    /* Seed the search with a single WherePath containing zero WhereLoops.
149210    **
149211    ** TUNING: Do not let the number of iterations go above 28.  If the cost
149212    ** of computing an automatic index is not paid back within the first 28
149213    ** rows, then do not use the automatic index. */
149214    aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
149215    nFrom = 1;
149216    assert( aFrom[0].isOrdered==0 );
149217    if( nOrderBy ){
149218      /* If nLoop is zero, then there are no FROM terms in the query. Since
149219      ** in this case the query may return a maximum of one row, the results
149220      ** are already in the requested order. Set isOrdered to nOrderBy to
149221      ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
149222      ** -1, indicating that the result set may or may not be ordered, 
149223      ** depending on the loops added to the current plan.  */
149224      aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
149225    }
149226  
149227    /* Compute successively longer WherePaths using the previous generation
149228    ** of WherePaths as the basis for the next.  Keep track of the mxChoice
149229    ** best paths at each generation */
149230    for(iLoop=0; iLoop<nLoop; iLoop++){
149231      nTo = 0;
149232      for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
149233        for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
149234          LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
149235          LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
149236          LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
149237          i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
149238          Bitmask maskNew;                  /* Mask of src visited by (..) */
149239          Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
149240  
149241          if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
149242          if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
149243          if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
149244            /* Do not use an automatic index if the this loop is expected
149245            ** to run less than 1.25 times.  It is tempting to also exclude
149246            ** automatic index usage on an outer loop, but sometimes an automatic
149247            ** index is useful in the outer loop of a correlated subquery. */
149248            assert( 10==sqlite3LogEst(2) );
149249            continue;
149250          }
149251  
149252          /* At this point, pWLoop is a candidate to be the next loop. 
149253          ** Compute its cost */
149254          rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
149255          rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
149256          nOut = pFrom->nRow + pWLoop->nOut;
149257          maskNew = pFrom->maskLoop | pWLoop->maskSelf;
149258          if( isOrdered<0 ){
149259            isOrdered = wherePathSatisfiesOrderBy(pWInfo,
149260                         pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
149261                         iLoop, pWLoop, &revMask);
149262          }else{
149263            revMask = pFrom->revLoop;
149264          }
149265          if( isOrdered>=0 && isOrdered<nOrderBy ){
149266            if( aSortCost[isOrdered]==0 ){
149267              aSortCost[isOrdered] = whereSortingCost(
149268                  pWInfo, nRowEst, nOrderBy, isOrdered
149269              );
149270            }
149271            /* TUNING:  Add a small extra penalty (5) to sorting as an
149272            ** extra encouragment to the query planner to select a plan
149273            ** where the rows emerge in the correct order without any sorting
149274            ** required. */
149275            rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
149276  
149277            WHERETRACE(0x002,
149278                ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
149279                 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
149280                 rUnsorted, rCost));
149281          }else{
149282            rCost = rUnsorted;
149283            rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
149284          }
149285  
149286          /* Check to see if pWLoop should be added to the set of
149287          ** mxChoice best-so-far paths.
149288          **
149289          ** First look for an existing path among best-so-far paths
149290          ** that covers the same set of loops and has the same isOrdered
149291          ** setting as the current path candidate.
149292          **
149293          ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
149294          ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
149295          ** of legal values for isOrdered, -1..64.
149296          */
149297          for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
149298            if( pTo->maskLoop==maskNew
149299             && ((pTo->isOrdered^isOrdered)&0x80)==0
149300            ){
149301              testcase( jj==nTo-1 );
149302              break;
149303            }
149304          }
149305          if( jj>=nTo ){
149306            /* None of the existing best-so-far paths match the candidate. */
149307            if( nTo>=mxChoice
149308             && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
149309            ){
149310              /* The current candidate is no better than any of the mxChoice
149311              ** paths currently in the best-so-far buffer.  So discard
149312              ** this candidate as not viable. */
149313  #ifdef WHERETRACE_ENABLED /* 0x4 */
149314              if( sqlite3WhereTrace&0x4 ){
149315                sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
149316                    wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
149317                    isOrdered>=0 ? isOrdered+'0' : '?');
149318              }
149319  #endif
149320              continue;
149321            }
149322            /* If we reach this points it means that the new candidate path
149323            ** needs to be added to the set of best-so-far paths. */
149324            if( nTo<mxChoice ){
149325              /* Increase the size of the aTo set by one */
149326              jj = nTo++;
149327            }else{
149328              /* New path replaces the prior worst to keep count below mxChoice */
149329              jj = mxI;
149330            }
149331            pTo = &aTo[jj];
149332  #ifdef WHERETRACE_ENABLED /* 0x4 */
149333            if( sqlite3WhereTrace&0x4 ){
149334              sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
149335                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
149336                  isOrdered>=0 ? isOrdered+'0' : '?');
149337            }
149338  #endif
149339          }else{
149340            /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
149341            ** same set of loops and has the same isOrdered setting as the
149342            ** candidate path.  Check to see if the candidate should replace
149343            ** pTo or if the candidate should be skipped.
149344            ** 
149345            ** The conditional is an expanded vector comparison equivalent to:
149346            **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
149347            */
149348            if( pTo->rCost<rCost 
149349             || (pTo->rCost==rCost
149350                 && (pTo->nRow<nOut
149351                     || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
149352                    )
149353                )
149354            ){
149355  #ifdef WHERETRACE_ENABLED /* 0x4 */
149356              if( sqlite3WhereTrace&0x4 ){
149357                sqlite3DebugPrintf(
149358                    "Skip   %s cost=%-3d,%3d,%3d order=%c",
149359                    wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
149360                    isOrdered>=0 ? isOrdered+'0' : '?');
149361                sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
149362                    wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
149363                    pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
149364              }
149365  #endif
149366              /* Discard the candidate path from further consideration */
149367              testcase( pTo->rCost==rCost );
149368              continue;
149369            }
149370            testcase( pTo->rCost==rCost+1 );
149371            /* Control reaches here if the candidate path is better than the
149372            ** pTo path.  Replace pTo with the candidate. */
149373  #ifdef WHERETRACE_ENABLED /* 0x4 */
149374            if( sqlite3WhereTrace&0x4 ){
149375              sqlite3DebugPrintf(
149376                  "Update %s cost=%-3d,%3d,%3d order=%c",
149377                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
149378                  isOrdered>=0 ? isOrdered+'0' : '?');
149379              sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
149380                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
149381                  pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
149382            }
149383  #endif
149384          }
149385          /* pWLoop is a winner.  Add it to the set of best so far */
149386          pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
149387          pTo->revLoop = revMask;
149388          pTo->nRow = nOut;
149389          pTo->rCost = rCost;
149390          pTo->rUnsorted = rUnsorted;
149391          pTo->isOrdered = isOrdered;
149392          memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
149393          pTo->aLoop[iLoop] = pWLoop;
149394          if( nTo>=mxChoice ){
149395            mxI = 0;
149396            mxCost = aTo[0].rCost;
149397            mxUnsorted = aTo[0].nRow;
149398            for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
149399              if( pTo->rCost>mxCost 
149400               || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
149401              ){
149402                mxCost = pTo->rCost;
149403                mxUnsorted = pTo->rUnsorted;
149404                mxI = jj;
149405              }
149406            }
149407          }
149408        }
149409      }
149410  
149411  #ifdef WHERETRACE_ENABLED  /* >=2 */
149412      if( sqlite3WhereTrace & 0x02 ){
149413        sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
149414        for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
149415          sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
149416             wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
149417             pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
149418          if( pTo->isOrdered>0 ){
149419            sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
149420          }else{
149421            sqlite3DebugPrintf("\n");
149422          }
149423        }
149424      }
149425  #endif
149426  
149427      /* Swap the roles of aFrom and aTo for the next generation */
149428      pFrom = aTo;
149429      aTo = aFrom;
149430      aFrom = pFrom;
149431      nFrom = nTo;
149432    }
149433  
149434    if( nFrom==0 ){
149435      sqlite3ErrorMsg(pParse, "no query solution");
149436      sqlite3DbFreeNN(db, pSpace);
149437      return SQLITE_ERROR;
149438    }
149439    
149440    /* Find the lowest cost path.  pFrom will be left pointing to that path */
149441    pFrom = aFrom;
149442    for(ii=1; ii<nFrom; ii++){
149443      if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
149444    }
149445    assert( pWInfo->nLevel==nLoop );
149446    /* Load the lowest cost path into pWInfo */
149447    for(iLoop=0; iLoop<nLoop; iLoop++){
149448      WhereLevel *pLevel = pWInfo->a + iLoop;
149449      pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
149450      pLevel->iFrom = pWLoop->iTab;
149451      pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
149452    }
149453    if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
149454     && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
149455     && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
149456     && nRowEst
149457    ){
149458      Bitmask notUsed;
149459      int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
149460                   WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
149461      if( rc==pWInfo->pResultSet->nExpr ){
149462        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
149463      }
149464    }
149465    pWInfo->bOrderedInnerLoop = 0;
149466    if( pWInfo->pOrderBy ){
149467      if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
149468        if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
149469          pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
149470        }
149471      }else{
149472        pWInfo->nOBSat = pFrom->isOrdered;
149473        pWInfo->revMask = pFrom->revLoop;
149474        if( pWInfo->nOBSat<=0 ){
149475          pWInfo->nOBSat = 0;
149476          if( nLoop>0 ){
149477            u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
149478            if( (wsFlags & WHERE_ONEROW)==0 
149479             && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
149480            ){
149481              Bitmask m = 0;
149482              int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
149483                        WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
149484              testcase( wsFlags & WHERE_IPK );
149485              testcase( wsFlags & WHERE_COLUMN_IN );
149486              if( rc==pWInfo->pOrderBy->nExpr ){
149487                pWInfo->bOrderedInnerLoop = 1;
149488                pWInfo->revMask = m;
149489              }
149490            }
149491          }
149492        }
149493      }
149494      if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
149495          && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
149496      ){
149497        Bitmask revMask = 0;
149498        int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 
149499            pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
149500        );
149501        assert( pWInfo->sorted==0 );
149502        if( nOrder==pWInfo->pOrderBy->nExpr ){
149503          pWInfo->sorted = 1;
149504          pWInfo->revMask = revMask;
149505        }
149506      }
149507    }
149508  
149509  
149510    pWInfo->nRowOut = pFrom->nRow;
149511  
149512    /* Free temporary memory and return success */
149513    sqlite3DbFreeNN(db, pSpace);
149514    return SQLITE_OK;
149515  }
149516  
149517  /*
149518  ** Most queries use only a single table (they are not joins) and have
149519  ** simple == constraints against indexed fields.  This routine attempts
149520  ** to plan those simple cases using much less ceremony than the
149521  ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
149522  ** times for the common case.
149523  **
149524  ** Return non-zero on success, if this query can be handled by this
149525  ** no-frills query planner.  Return zero if this query needs the 
149526  ** general-purpose query planner.
149527  */
149528  static int whereShortCut(WhereLoopBuilder *pBuilder){
149529    WhereInfo *pWInfo;
149530    struct SrcList_item *pItem;
149531    WhereClause *pWC;
149532    WhereTerm *pTerm;
149533    WhereLoop *pLoop;
149534    int iCur;
149535    int j;
149536    Table *pTab;
149537    Index *pIdx;
149538  
149539    pWInfo = pBuilder->pWInfo;
149540    if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
149541    assert( pWInfo->pTabList->nSrc>=1 );
149542    pItem = pWInfo->pTabList->a;
149543    pTab = pItem->pTab;
149544    if( IsVirtual(pTab) ) return 0;
149545    if( pItem->fg.isIndexedBy ) return 0;
149546    iCur = pItem->iCursor;
149547    pWC = &pWInfo->sWC;
149548    pLoop = pBuilder->pNew;
149549    pLoop->wsFlags = 0;
149550    pLoop->nSkip = 0;
149551    pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
149552    if( pTerm ){
149553      testcase( pTerm->eOperator & WO_IS );
149554      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
149555      pLoop->aLTerm[0] = pTerm;
149556      pLoop->nLTerm = 1;
149557      pLoop->u.btree.nEq = 1;
149558      /* TUNING: Cost of a rowid lookup is 10 */
149559      pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
149560    }else{
149561      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
149562        int opMask;
149563        assert( pLoop->aLTermSpace==pLoop->aLTerm );
149564        if( !IsUniqueIndex(pIdx)
149565         || pIdx->pPartIdxWhere!=0 
149566         || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
149567        ) continue;
149568        opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
149569        for(j=0; j<pIdx->nKeyCol; j++){
149570          pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
149571          if( pTerm==0 ) break;
149572          testcase( pTerm->eOperator & WO_IS );
149573          pLoop->aLTerm[j] = pTerm;
149574        }
149575        if( j!=pIdx->nKeyCol ) continue;
149576        pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
149577        if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
149578          pLoop->wsFlags |= WHERE_IDX_ONLY;
149579        }
149580        pLoop->nLTerm = j;
149581        pLoop->u.btree.nEq = j;
149582        pLoop->u.btree.pIndex = pIdx;
149583        /* TUNING: Cost of a unique index lookup is 15 */
149584        pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
149585        break;
149586      }
149587    }
149588    if( pLoop->wsFlags ){
149589      pLoop->nOut = (LogEst)1;
149590      pWInfo->a[0].pWLoop = pLoop;
149591      assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
149592      pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
149593      pWInfo->a[0].iTabCur = iCur;
149594      pWInfo->nRowOut = 1;
149595      if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
149596      if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
149597        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
149598      }
149599  #ifdef SQLITE_DEBUG
149600      pLoop->cId = '0';
149601  #endif
149602      return 1;
149603    }
149604    return 0;
149605  }
149606  
149607  /*
149608  ** Helper function for exprIsDeterministic().
149609  */
149610  static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
149611    if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
149612      pWalker->eCode = 0;
149613      return WRC_Abort;
149614    }
149615    return WRC_Continue;
149616  }
149617  
149618  /*
149619  ** Return true if the expression contains no non-deterministic SQL 
149620  ** functions. Do not consider non-deterministic SQL functions that are 
149621  ** part of sub-select statements.
149622  */
149623  static int exprIsDeterministic(Expr *p){
149624    Walker w;
149625    memset(&w, 0, sizeof(w));
149626    w.eCode = 1;
149627    w.xExprCallback = exprNodeIsDeterministic;
149628    w.xSelectCallback = sqlite3SelectWalkFail;
149629    sqlite3WalkExpr(&w, p);
149630    return w.eCode;
149631  }
149632  
149633  /*
149634  ** Generate the beginning of the loop used for WHERE clause processing.
149635  ** The return value is a pointer to an opaque structure that contains
149636  ** information needed to terminate the loop.  Later, the calling routine
149637  ** should invoke sqlite3WhereEnd() with the return value of this function
149638  ** in order to complete the WHERE clause processing.
149639  **
149640  ** If an error occurs, this routine returns NULL.
149641  **
149642  ** The basic idea is to do a nested loop, one loop for each table in
149643  ** the FROM clause of a select.  (INSERT and UPDATE statements are the
149644  ** same as a SELECT with only a single table in the FROM clause.)  For
149645  ** example, if the SQL is this:
149646  **
149647  **       SELECT * FROM t1, t2, t3 WHERE ...;
149648  **
149649  ** Then the code generated is conceptually like the following:
149650  **
149651  **      foreach row1 in t1 do       \    Code generated
149652  **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
149653  **          foreach row3 in t3 do   /
149654  **            ...
149655  **          end                     \    Code generated
149656  **        end                        |-- by sqlite3WhereEnd()
149657  **      end                         /
149658  **
149659  ** Note that the loops might not be nested in the order in which they
149660  ** appear in the FROM clause if a different order is better able to make
149661  ** use of indices.  Note also that when the IN operator appears in
149662  ** the WHERE clause, it might result in additional nested loops for
149663  ** scanning through all values on the right-hand side of the IN.
149664  **
149665  ** There are Btree cursors associated with each table.  t1 uses cursor
149666  ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
149667  ** And so forth.  This routine generates code to open those VDBE cursors
149668  ** and sqlite3WhereEnd() generates the code to close them.
149669  **
149670  ** The code that sqlite3WhereBegin() generates leaves the cursors named
149671  ** in pTabList pointing at their appropriate entries.  The [...] code
149672  ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
149673  ** data from the various tables of the loop.
149674  **
149675  ** If the WHERE clause is empty, the foreach loops must each scan their
149676  ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
149677  ** the tables have indices and there are terms in the WHERE clause that
149678  ** refer to those indices, a complete table scan can be avoided and the
149679  ** code will run much faster.  Most of the work of this routine is checking
149680  ** to see if there are indices that can be used to speed up the loop.
149681  **
149682  ** Terms of the WHERE clause are also used to limit which rows actually
149683  ** make it to the "..." in the middle of the loop.  After each "foreach",
149684  ** terms of the WHERE clause that use only terms in that loop and outer
149685  ** loops are evaluated and if false a jump is made around all subsequent
149686  ** inner loops (or around the "..." if the test occurs within the inner-
149687  ** most loop)
149688  **
149689  ** OUTER JOINS
149690  **
149691  ** An outer join of tables t1 and t2 is conceptally coded as follows:
149692  **
149693  **    foreach row1 in t1 do
149694  **      flag = 0
149695  **      foreach row2 in t2 do
149696  **        start:
149697  **          ...
149698  **          flag = 1
149699  **      end
149700  **      if flag==0 then
149701  **        move the row2 cursor to a null row
149702  **        goto start
149703  **      fi
149704  **    end
149705  **
149706  ** ORDER BY CLAUSE PROCESSING
149707  **
149708  ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
149709  ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
149710  ** if there is one.  If there is no ORDER BY clause or if this routine
149711  ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
149712  **
149713  ** The iIdxCur parameter is the cursor number of an index.  If 
149714  ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
149715  ** to use for OR clause processing.  The WHERE clause should use this
149716  ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
149717  ** the first cursor in an array of cursors for all indices.  iIdxCur should
149718  ** be used to compute the appropriate cursor depending on which index is
149719  ** used.
149720  */
149721  SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
149722    Parse *pParse,          /* The parser context */
149723    SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
149724    Expr *pWhere,           /* The WHERE clause */
149725    ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
149726    ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
149727    u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
149728    int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
149729                            ** If WHERE_USE_LIMIT, then the limit amount */
149730  ){
149731    int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
149732    int nTabList;              /* Number of elements in pTabList */
149733    WhereInfo *pWInfo;         /* Will become the return value of this function */
149734    Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
149735    Bitmask notReady;          /* Cursors that are not yet positioned */
149736    WhereLoopBuilder sWLB;     /* The WhereLoop builder */
149737    WhereMaskSet *pMaskSet;    /* The expression mask set */
149738    WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
149739    WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
149740    int ii;                    /* Loop counter */
149741    sqlite3 *db;               /* Database connection */
149742    int rc;                    /* Return code */
149743    u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
149744  
149745    assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
149746          (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
149747       && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 
149748    ));
149749  
149750    /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
149751    assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
149752              || (wctrlFlags & WHERE_USE_LIMIT)==0 );
149753  
149754    /* Variable initialization */
149755    db = pParse->db;
149756    memset(&sWLB, 0, sizeof(sWLB));
149757  
149758    /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
149759    testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
149760    if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
149761    sWLB.pOrderBy = pOrderBy;
149762  
149763    /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
149764    ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
149765    if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
149766      wctrlFlags &= ~WHERE_WANT_DISTINCT;
149767    }
149768  
149769    /* The number of tables in the FROM clause is limited by the number of
149770    ** bits in a Bitmask 
149771    */
149772    testcase( pTabList->nSrc==BMS );
149773    if( pTabList->nSrc>BMS ){
149774      sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
149775      return 0;
149776    }
149777  
149778    /* This function normally generates a nested loop for all tables in 
149779    ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
149780    ** only generate code for the first table in pTabList and assume that
149781    ** any cursors associated with subsequent tables are uninitialized.
149782    */
149783    nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
149784  
149785    /* Allocate and initialize the WhereInfo structure that will become the
149786    ** return value. A single allocation is used to store the WhereInfo
149787    ** struct, the contents of WhereInfo.a[], the WhereClause structure
149788    ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
149789    ** field (type Bitmask) it must be aligned on an 8-byte boundary on
149790    ** some architectures. Hence the ROUND8() below.
149791    */
149792    nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
149793    pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
149794    if( db->mallocFailed ){
149795      sqlite3DbFree(db, pWInfo);
149796      pWInfo = 0;
149797      goto whereBeginError;
149798    }
149799    pWInfo->pParse = pParse;
149800    pWInfo->pTabList = pTabList;
149801    pWInfo->pOrderBy = pOrderBy;
149802    pWInfo->pWhere = pWhere;
149803    pWInfo->pResultSet = pResultSet;
149804    pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
149805    pWInfo->nLevel = nTabList;
149806    pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
149807    pWInfo->wctrlFlags = wctrlFlags;
149808    pWInfo->iLimit = iAuxArg;
149809    pWInfo->savedNQueryLoop = pParse->nQueryLoop;
149810    memset(&pWInfo->nOBSat, 0, 
149811           offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
149812    memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
149813    assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
149814    pMaskSet = &pWInfo->sMaskSet;
149815    sWLB.pWInfo = pWInfo;
149816    sWLB.pWC = &pWInfo->sWC;
149817    sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
149818    assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
149819    whereLoopInit(sWLB.pNew);
149820  #ifdef SQLITE_DEBUG
149821    sWLB.pNew->cId = '*';
149822  #endif
149823  
149824    /* Split the WHERE clause into separate subexpressions where each
149825    ** subexpression is separated by an AND operator.
149826    */
149827    initMaskSet(pMaskSet);
149828    sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
149829    sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
149830      
149831    /* Special case: No FROM clause
149832    */
149833    if( nTabList==0 ){
149834      if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
149835      if( wctrlFlags & WHERE_WANT_DISTINCT ){
149836        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
149837      }
149838      ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
149839    }else{
149840      /* Assign a bit from the bitmask to every term in the FROM clause.
149841      **
149842      ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
149843      **
149844      ** The rule of the previous sentence ensures thta if X is the bitmask for
149845      ** a table T, then X-1 is the bitmask for all other tables to the left of T.
149846      ** Knowing the bitmask for all tables to the left of a left join is
149847      ** important.  Ticket #3015.
149848      **
149849      ** Note that bitmasks are created for all pTabList->nSrc tables in
149850      ** pTabList, not just the first nTabList tables.  nTabList is normally
149851      ** equal to pTabList->nSrc but might be shortened to 1 if the
149852      ** WHERE_OR_SUBCLAUSE flag is set.
149853      */
149854      ii = 0;
149855      do{
149856        createMask(pMaskSet, pTabList->a[ii].iCursor);
149857        sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
149858      }while( (++ii)<pTabList->nSrc );
149859    #ifdef SQLITE_DEBUG
149860      {
149861        Bitmask mx = 0;
149862        for(ii=0; ii<pTabList->nSrc; ii++){
149863          Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
149864          assert( m>=mx );
149865          mx = m;
149866        }
149867      }
149868    #endif
149869    }
149870    
149871    /* Analyze all of the subexpressions. */
149872    sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
149873    if( db->mallocFailed ) goto whereBeginError;
149874  
149875    /* Special case: WHERE terms that do not refer to any tables in the join
149876    ** (constant expressions). Evaluate each such term, and jump over all the
149877    ** generated code if the result is not true.  
149878    **
149879    ** Do not do this if the expression contains non-deterministic functions
149880    ** that are not within a sub-select. This is not strictly required, but
149881    ** preserves SQLite's legacy behaviour in the following two cases:
149882    **
149883    **   FROM ... WHERE random()>0;           -- eval random() once per row
149884    **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
149885    */
149886    for(ii=0; ii<sWLB.pWC->nTerm; ii++){
149887      WhereTerm *pT = &sWLB.pWC->a[ii];
149888      if( pT->wtFlags & TERM_VIRTUAL ) continue;
149889      if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
149890        sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
149891        pT->wtFlags |= TERM_CODED;
149892      }
149893    }
149894  
149895    if( wctrlFlags & WHERE_WANT_DISTINCT ){
149896      if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
149897        /* The DISTINCT marking is pointless.  Ignore it. */
149898        pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
149899      }else if( pOrderBy==0 ){
149900        /* Try to ORDER BY the result set to make distinct processing easier */
149901        pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
149902        pWInfo->pOrderBy = pResultSet;
149903      }
149904    }
149905  
149906    /* Construct the WhereLoop objects */
149907  #if defined(WHERETRACE_ENABLED)
149908    if( sqlite3WhereTrace & 0xffff ){
149909      sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
149910      if( wctrlFlags & WHERE_USE_LIMIT ){
149911        sqlite3DebugPrintf(", limit: %d", iAuxArg);
149912      }
149913      sqlite3DebugPrintf(")\n");
149914    }
149915    if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
149916      sqlite3WhereClausePrint(sWLB.pWC);
149917    }
149918  #endif
149919  
149920    if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
149921      rc = whereLoopAddAll(&sWLB);
149922      if( rc ) goto whereBeginError;
149923    
149924  #ifdef WHERETRACE_ENABLED
149925      if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
149926        WhereLoop *p;
149927        int i;
149928        static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
149929                                               "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
149930        for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
149931          p->cId = zLabel[i%(sizeof(zLabel)-1)];
149932          whereLoopPrint(p, sWLB.pWC);
149933        }
149934      }
149935  #endif
149936    
149937      wherePathSolver(pWInfo, 0);
149938      if( db->mallocFailed ) goto whereBeginError;
149939      if( pWInfo->pOrderBy ){
149940         wherePathSolver(pWInfo, pWInfo->nRowOut+1);
149941         if( db->mallocFailed ) goto whereBeginError;
149942      }
149943    }
149944    if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
149945       pWInfo->revMask = ALLBITS;
149946    }
149947    if( pParse->nErr || NEVER(db->mallocFailed) ){
149948      goto whereBeginError;
149949    }
149950  #ifdef WHERETRACE_ENABLED
149951    if( sqlite3WhereTrace ){
149952      sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
149953      if( pWInfo->nOBSat>0 ){
149954        sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
149955      }
149956      switch( pWInfo->eDistinct ){
149957        case WHERE_DISTINCT_UNIQUE: {
149958          sqlite3DebugPrintf("  DISTINCT=unique");
149959          break;
149960        }
149961        case WHERE_DISTINCT_ORDERED: {
149962          sqlite3DebugPrintf("  DISTINCT=ordered");
149963          break;
149964        }
149965        case WHERE_DISTINCT_UNORDERED: {
149966          sqlite3DebugPrintf("  DISTINCT=unordered");
149967          break;
149968        }
149969      }
149970      sqlite3DebugPrintf("\n");
149971      for(ii=0; ii<pWInfo->nLevel; ii++){
149972        whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
149973      }
149974    }
149975  #endif
149976  
149977    /* Attempt to omit tables from the join that do not affect the result.
149978    ** For a table to not affect the result, the following must be true:
149979    **
149980    **   1) The query must not be an aggregate.
149981    **   2) The table must be the RHS of a LEFT JOIN.
149982    **   3) Either the query must be DISTINCT, or else the ON or USING clause
149983    **      must contain a constraint that limits the scan of the table to 
149984    **      at most a single row.
149985    **   4) The table must not be referenced by any part of the query apart
149986    **      from its own USING or ON clause.
149987    **
149988    ** For example, given:
149989    **
149990    **     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
149991    **     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
149992    **     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
149993    **
149994    ** then table t2 can be omitted from the following:
149995    **
149996    **     SELECT v1, v3 FROM t1 
149997    **       LEFT JOIN t2 USING (t1.ipk=t2.ipk)
149998    **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
149999    **
150000    ** or from:
150001    **
150002    **     SELECT DISTINCT v1, v3 FROM t1 
150003    **       LEFT JOIN t2
150004    **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
150005    */
150006    notReady = ~(Bitmask)0;
150007    if( pWInfo->nLevel>=2
150008     && pResultSet!=0               /* guarantees condition (1) above */
150009     && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
150010    ){
150011      int i;
150012      Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
150013      if( sWLB.pOrderBy ){
150014        tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
150015      }
150016      for(i=pWInfo->nLevel-1; i>=1; i--){
150017        WhereTerm *pTerm, *pEnd;
150018        struct SrcList_item *pItem;
150019        pLoop = pWInfo->a[i].pWLoop;
150020        pItem = &pWInfo->pTabList->a[pLoop->iTab];
150021        if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
150022        if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
150023         && (pLoop->wsFlags & WHERE_ONEROW)==0
150024        ){
150025          continue;
150026        }
150027        if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
150028        pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
150029        for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
150030          if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
150031            if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
150032             || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
150033            ){
150034              break;
150035            }
150036          }
150037        }
150038        if( pTerm<pEnd ) continue;
150039        WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
150040        notReady &= ~pLoop->maskSelf;
150041        for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
150042          if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
150043            pTerm->wtFlags |= TERM_CODED;
150044          }
150045        }
150046        if( i!=pWInfo->nLevel-1 ){
150047          int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
150048          memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
150049        }
150050        pWInfo->nLevel--;
150051        nTabList--;
150052      }
150053    }
150054    WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
150055    pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
150056  
150057    /* If the caller is an UPDATE or DELETE statement that is requesting
150058    ** to use a one-pass algorithm, determine if this is appropriate.
150059    **
150060    ** A one-pass approach can be used if the caller has requested one
150061    ** and either (a) the scan visits at most one row or (b) each
150062    ** of the following are true:
150063    **
150064    **   * the caller has indicated that a one-pass approach can be used
150065    **     with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
150066    **   * the table is not a virtual table, and
150067    **   * either the scan does not use the OR optimization or the caller
150068    **     is a DELETE operation (WHERE_DUPLICATES_OK is only specified
150069    **     for DELETE).
150070    **
150071    ** The last qualification is because an UPDATE statement uses
150072    ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
150073    ** use a one-pass approach, and this is not set accurately for scans
150074    ** that use the OR optimization.
150075    */
150076    assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
150077    if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
150078      int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
150079      int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
150080      assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
150081      if( bOnerow || (
150082          0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
150083       && !IsVirtual(pTabList->a[0].pTab)
150084       && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
150085      )){
150086        pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
150087        if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
150088          if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
150089            bFordelete = OPFLAG_FORDELETE;
150090          }
150091          pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
150092        }
150093      }
150094    }
150095  
150096    /* Open all tables in the pTabList and any indices selected for
150097    ** searching those tables.
150098    */
150099    for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
150100      Table *pTab;     /* Table to open */
150101      int iDb;         /* Index of database containing table/index */
150102      struct SrcList_item *pTabItem;
150103  
150104      pTabItem = &pTabList->a[pLevel->iFrom];
150105      pTab = pTabItem->pTab;
150106      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
150107      pLoop = pLevel->pWLoop;
150108      if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
150109        /* Do nothing */
150110      }else
150111  #ifndef SQLITE_OMIT_VIRTUALTABLE
150112      if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
150113        const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
150114        int iCur = pTabItem->iCursor;
150115        sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
150116      }else if( IsVirtual(pTab) ){
150117        /* noop */
150118      }else
150119  #endif
150120      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
150121           && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
150122        int op = OP_OpenRead;
150123        if( pWInfo->eOnePass!=ONEPASS_OFF ){
150124          op = OP_OpenWrite;
150125          pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
150126        };
150127        sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
150128        assert( pTabItem->iCursor==pLevel->iTabCur );
150129        testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
150130        testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
150131        if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
150132          Bitmask b = pTabItem->colUsed;
150133          int n = 0;
150134          for(; b; b=b>>1, n++){}
150135          sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
150136          assert( n<=pTab->nCol );
150137        }
150138  #ifdef SQLITE_ENABLE_CURSOR_HINTS
150139        if( pLoop->u.btree.pIndex!=0 ){
150140          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
150141        }else
150142  #endif
150143        {
150144          sqlite3VdbeChangeP5(v, bFordelete);
150145        }
150146  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
150147        sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
150148                              (const u8*)&pTabItem->colUsed, P4_INT64);
150149  #endif
150150      }else{
150151        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
150152      }
150153      if( pLoop->wsFlags & WHERE_INDEXED ){
150154        Index *pIx = pLoop->u.btree.pIndex;
150155        int iIndexCur;
150156        int op = OP_OpenRead;
150157        /* iAuxArg is always set to a positive value if ONEPASS is possible */
150158        assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
150159        if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
150160         && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
150161        ){
150162          /* This is one term of an OR-optimization using the PRIMARY KEY of a
150163          ** WITHOUT ROWID table.  No need for a separate index */
150164          iIndexCur = pLevel->iTabCur;
150165          op = 0;
150166        }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
150167          Index *pJ = pTabItem->pTab->pIndex;
150168          iIndexCur = iAuxArg;
150169          assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
150170          while( ALWAYS(pJ) && pJ!=pIx ){
150171            iIndexCur++;
150172            pJ = pJ->pNext;
150173          }
150174          op = OP_OpenWrite;
150175          pWInfo->aiCurOnePass[1] = iIndexCur;
150176        }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
150177          iIndexCur = iAuxArg;
150178          op = OP_ReopenIdx;
150179        }else{
150180          iIndexCur = pParse->nTab++;
150181        }
150182        pLevel->iIdxCur = iIndexCur;
150183        assert( pIx->pSchema==pTab->pSchema );
150184        assert( iIndexCur>=0 );
150185        if( op ){
150186          sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
150187          sqlite3VdbeSetP4KeyInfo(pParse, pIx);
150188          if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
150189           && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
150190           && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
150191           && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
150192          ){
150193            sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
150194          }
150195          VdbeComment((v, "%s", pIx->zName));
150196  #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
150197          {
150198            u64 colUsed = 0;
150199            int ii, jj;
150200            for(ii=0; ii<pIx->nColumn; ii++){
150201              jj = pIx->aiColumn[ii];
150202              if( jj<0 ) continue;
150203              if( jj>63 ) jj = 63;
150204              if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
150205              colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
150206            }
150207            sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
150208                                  (u8*)&colUsed, P4_INT64);
150209          }
150210  #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
150211        }
150212      }
150213      if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
150214    }
150215    pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
150216    if( db->mallocFailed ) goto whereBeginError;
150217  
150218    /* Generate the code to do the search.  Each iteration of the for
150219    ** loop below generates code for a single nested loop of the VM
150220    ** program.
150221    */
150222    for(ii=0; ii<nTabList; ii++){
150223      int addrExplain;
150224      int wsFlags;
150225      pLevel = &pWInfo->a[ii];
150226      wsFlags = pLevel->pWLoop->wsFlags;
150227  #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
150228      if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
150229        constructAutomaticIndex(pParse, &pWInfo->sWC,
150230                  &pTabList->a[pLevel->iFrom], notReady, pLevel);
150231        if( db->mallocFailed ) goto whereBeginError;
150232      }
150233  #endif
150234      addrExplain = sqlite3WhereExplainOneScan(
150235          pParse, pTabList, pLevel, wctrlFlags
150236      );
150237      pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
150238      notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
150239      pWInfo->iContinue = pLevel->addrCont;
150240      if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
150241        sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
150242      }
150243    }
150244  
150245    /* Done. */
150246    VdbeModuleComment((v, "Begin WHERE-core"));
150247    return pWInfo;
150248  
150249    /* Jump here if malloc fails */
150250  whereBeginError:
150251    if( pWInfo ){
150252      pParse->nQueryLoop = pWInfo->savedNQueryLoop;
150253      whereInfoFree(db, pWInfo);
150254    }
150255    return 0;
150256  }
150257  
150258  /*
150259  ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
150260  ** index rather than the main table.  In SQLITE_DEBUG mode, we want
150261  ** to trace those changes if PRAGMA vdbe_addoptrace=on.  This routine
150262  ** does that.
150263  */
150264  #ifndef SQLITE_DEBUG
150265  # define OpcodeRewriteTrace(D,K,P) /* no-op */
150266  #else
150267  # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
150268    static void sqlite3WhereOpcodeRewriteTrace(
150269      sqlite3 *db,
150270      int pc,
150271      VdbeOp *pOp
150272    ){
150273      if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
150274      sqlite3VdbePrintOp(0, pc, pOp);
150275    }
150276  #endif
150277  
150278  /*
150279  ** Generate the end of the WHERE loop.  See comments on 
150280  ** sqlite3WhereBegin() for additional information.
150281  */
150282  SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
150283    Parse *pParse = pWInfo->pParse;
150284    Vdbe *v = pParse->pVdbe;
150285    int i;
150286    WhereLevel *pLevel;
150287    WhereLoop *pLoop;
150288    SrcList *pTabList = pWInfo->pTabList;
150289    sqlite3 *db = pParse->db;
150290  
150291    /* Generate loop termination code.
150292    */
150293    VdbeModuleComment((v, "End WHERE-core"));
150294    for(i=pWInfo->nLevel-1; i>=0; i--){
150295      int addr;
150296      pLevel = &pWInfo->a[i];
150297      pLoop = pLevel->pWLoop;
150298      if( pLevel->op!=OP_Noop ){
150299  #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
150300        int addrSeek = 0;
150301        Index *pIdx;
150302        int n;
150303        if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
150304         && i==pWInfo->nLevel-1  /* Ticket [ef9318757b152e3] 2017-10-21 */
150305         && (pLoop->wsFlags & WHERE_INDEXED)!=0
150306         && (pIdx = pLoop->u.btree.pIndex)->hasStat1
150307         && (n = pLoop->u.btree.nIdxCol)>0
150308         && pIdx->aiRowLogEst[n]>=36
150309        ){
150310          int r1 = pParse->nMem+1;
150311          int j, op;
150312          for(j=0; j<n; j++){
150313            sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
150314          }
150315          pParse->nMem += n+1;
150316          op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
150317          addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
150318          VdbeCoverageIf(v, op==OP_SeekLT);
150319          VdbeCoverageIf(v, op==OP_SeekGT);
150320          sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
150321        }
150322  #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
150323        /* The common case: Advance to the next row */
150324        sqlite3VdbeResolveLabel(v, pLevel->addrCont);
150325        sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
150326        sqlite3VdbeChangeP5(v, pLevel->p5);
150327        VdbeCoverage(v);
150328        VdbeCoverageIf(v, pLevel->op==OP_Next);
150329        VdbeCoverageIf(v, pLevel->op==OP_Prev);
150330        VdbeCoverageIf(v, pLevel->op==OP_VNext);
150331  #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
150332        if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
150333  #endif
150334      }else{
150335        sqlite3VdbeResolveLabel(v, pLevel->addrCont);
150336      }
150337      if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
150338        struct InLoop *pIn;
150339        int j;
150340        sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
150341        for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
150342          sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
150343          if( pIn->eEndLoopOp!=OP_Noop ){
150344            if( pIn->nPrefix ){
150345              assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
150346              sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
150347                                sqlite3VdbeCurrentAddr(v)+2,
150348                                pIn->iBase, pIn->nPrefix);
150349              VdbeCoverage(v);
150350            }
150351            sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
150352            VdbeCoverage(v);
150353            VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
150354            VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
150355          }
150356          sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
150357        }
150358      }
150359      sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
150360      if( pLevel->addrSkip ){
150361        sqlite3VdbeGoto(v, pLevel->addrSkip);
150362        VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
150363        sqlite3VdbeJumpHere(v, pLevel->addrSkip);
150364        sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
150365      }
150366  #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
150367      if( pLevel->addrLikeRep ){
150368        sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
150369                          pLevel->addrLikeRep);
150370        VdbeCoverage(v);
150371      }
150372  #endif
150373      if( pLevel->iLeftJoin ){
150374        int ws = pLoop->wsFlags;
150375        addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
150376        assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
150377        if( (ws & WHERE_IDX_ONLY)==0 ){
150378          assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
150379          sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
150380        }
150381        if( (ws & WHERE_INDEXED) 
150382         || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) 
150383        ){
150384          sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
150385        }
150386        if( pLevel->op==OP_Return ){
150387          sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
150388        }else{
150389          sqlite3VdbeGoto(v, pLevel->addrFirst);
150390        }
150391        sqlite3VdbeJumpHere(v, addr);
150392      }
150393      VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
150394                       pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
150395    }
150396  
150397    /* The "break" point is here, just past the end of the outer loop.
150398    ** Set it.
150399    */
150400    sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
150401  
150402    assert( pWInfo->nLevel<=pTabList->nSrc );
150403    for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
150404      int k, last;
150405      VdbeOp *pOp;
150406      Index *pIdx = 0;
150407      struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
150408      Table *pTab = pTabItem->pTab;
150409      assert( pTab!=0 );
150410      pLoop = pLevel->pWLoop;
150411  
150412      /* For a co-routine, change all OP_Column references to the table of
150413      ** the co-routine into OP_Copy of result contained in a register.
150414      ** OP_Rowid becomes OP_Null.
150415      */
150416      if( pTabItem->fg.viaCoroutine ){
150417        testcase( pParse->db->mallocFailed );
150418        translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
150419                              pTabItem->regResult, 0);
150420        continue;
150421      }
150422  
150423  #ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE
150424      /* Close all of the cursors that were opened by sqlite3WhereBegin.
150425      ** Except, do not close cursors that will be reused by the OR optimization
150426      ** (WHERE_OR_SUBCLAUSE).  And do not close the OP_OpenWrite cursors
150427      ** created for the ONEPASS optimization.
150428      */
150429      if( (pTab->tabFlags & TF_Ephemeral)==0
150430       && pTab->pSelect==0
150431       && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
150432      ){
150433        int ws = pLoop->wsFlags;
150434        if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
150435          sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
150436        }
150437        if( (ws & WHERE_INDEXED)!=0
150438         && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 
150439         && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
150440        ){
150441          sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
150442        }
150443      }
150444  #endif
150445  
150446      /* If this scan uses an index, make VDBE code substitutions to read data
150447      ** from the index instead of from the table where possible.  In some cases
150448      ** this optimization prevents the table from ever being read, which can
150449      ** yield a significant performance boost.
150450      ** 
150451      ** Calls to the code generator in between sqlite3WhereBegin and
150452      ** sqlite3WhereEnd will have created code that references the table
150453      ** directly.  This loop scans all that code looking for opcodes
150454      ** that reference the table and converts them into opcodes that
150455      ** reference the index.
150456      */
150457      if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
150458        pIdx = pLoop->u.btree.pIndex;
150459      }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
150460        pIdx = pLevel->u.pCovidx;
150461      }
150462      if( pIdx
150463       && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
150464       && !db->mallocFailed
150465      ){
150466        last = sqlite3VdbeCurrentAddr(v);
150467        k = pLevel->addrBody;
150468  #ifdef SQLITE_DEBUG
150469        if( db->flags & SQLITE_VdbeAddopTrace ){
150470          printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
150471        }
150472  #endif
150473        pOp = sqlite3VdbeGetOp(v, k);
150474        for(; k<last; k++, pOp++){
150475          if( pOp->p1!=pLevel->iTabCur ) continue;
150476          if( pOp->opcode==OP_Column
150477  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
150478           || pOp->opcode==OP_Offset
150479  #endif
150480          ){
150481            int x = pOp->p2;
150482            assert( pIdx->pTable==pTab );
150483            if( !HasRowid(pTab) ){
150484              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
150485              x = pPk->aiColumn[x];
150486              assert( x>=0 );
150487            }
150488            x = sqlite3ColumnOfIndex(pIdx, x);
150489            if( x>=0 ){
150490              pOp->p2 = x;
150491              pOp->p1 = pLevel->iIdxCur;
150492              OpcodeRewriteTrace(db, k, pOp);
150493            }
150494            assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 
150495                || pWInfo->eOnePass );
150496          }else if( pOp->opcode==OP_Rowid ){
150497            pOp->p1 = pLevel->iIdxCur;
150498            pOp->opcode = OP_IdxRowid;
150499            OpcodeRewriteTrace(db, k, pOp);
150500          }else if( pOp->opcode==OP_IfNullRow ){
150501            pOp->p1 = pLevel->iIdxCur;
150502            OpcodeRewriteTrace(db, k, pOp);
150503          }
150504        }
150505  #ifdef SQLITE_DEBUG
150506        if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
150507  #endif
150508      }
150509    }
150510  
150511    /* Final cleanup
150512    */
150513    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
150514    whereInfoFree(db, pWInfo);
150515    return;
150516  }
150517  
150518  /************** End of where.c ***********************************************/
150519  /************** Begin file window.c ******************************************/
150520  /*
150521  ** 2018 May 08
150522  **
150523  ** The author disclaims copyright to this source code.  In place of
150524  ** a legal notice, here is a blessing:
150525  **
150526  **    May you do good and not evil.
150527  **    May you find forgiveness for yourself and forgive others.
150528  **    May you share freely, never taking more than you give.
150529  **
150530  *************************************************************************
150531  */
150532  /* #include "sqliteInt.h" */
150533  
150534  #ifndef SQLITE_OMIT_WINDOWFUNC
150535  
150536  /*
150537  ** SELECT REWRITING
150538  **
150539  **   Any SELECT statement that contains one or more window functions in
150540  **   either the select list or ORDER BY clause (the only two places window
150541  **   functions may be used) is transformed by function sqlite3WindowRewrite()
150542  **   in order to support window function processing. For example, with the
150543  **   schema:
150544  **
150545  **     CREATE TABLE t1(a, b, c, d, e, f, g);
150546  **
150547  **   the statement:
150548  **
150549  **     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
150550  **
150551  **   is transformed to:
150552  **
150553  **     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
150554  **         SELECT a, e, c, d, b FROM t1 ORDER BY c, d
150555  **     ) ORDER BY e;
150556  **
150557  **   The flattening optimization is disabled when processing this transformed
150558  **   SELECT statement. This allows the implementation of the window function
150559  **   (in this case max()) to process rows sorted in order of (c, d), which
150560  **   makes things easier for obvious reasons. More generally:
150561  **
150562  **     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to 
150563  **       the sub-query.
150564  **
150565  **     * ORDER BY, LIMIT and OFFSET remain part of the parent query.
150566  **
150567  **     * Terminals from each of the expression trees that make up the 
150568  **       select-list and ORDER BY expressions in the parent query are
150569  **       selected by the sub-query. For the purposes of the transformation,
150570  **       terminals are column references and aggregate functions.
150571  **
150572  **   If there is more than one window function in the SELECT that uses
150573  **   the same window declaration (the OVER bit), then a single scan may
150574  **   be used to process more than one window function. For example:
150575  **
150576  **     SELECT max(b) OVER (PARTITION BY c ORDER BY d), 
150577  **            min(e) OVER (PARTITION BY c ORDER BY d) 
150578  **     FROM t1;
150579  **
150580  **   is transformed in the same way as the example above. However:
150581  **
150582  **     SELECT max(b) OVER (PARTITION BY c ORDER BY d), 
150583  **            min(e) OVER (PARTITION BY a ORDER BY b) 
150584  **     FROM t1;
150585  **
150586  **   Must be transformed to:
150587  **
150588  **     SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
150589  **         SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
150590  **           SELECT a, e, c, d, b FROM t1 ORDER BY a, b
150591  **         ) ORDER BY c, d
150592  **     ) ORDER BY e;
150593  **
150594  **   so that both min() and max() may process rows in the order defined by
150595  **   their respective window declarations.
150596  **
150597  ** INTERFACE WITH SELECT.C
150598  **
150599  **   When processing the rewritten SELECT statement, code in select.c calls
150600  **   sqlite3WhereBegin() to begin iterating through the results of the
150601  **   sub-query, which is always implemented as a co-routine. It then calls
150602  **   sqlite3WindowCodeStep() to process rows and finish the scan by calling
150603  **   sqlite3WhereEnd().
150604  **
150605  **   sqlite3WindowCodeStep() generates VM code so that, for each row returned
150606  **   by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
150607  **   When the sub-routine is invoked:
150608  **
150609  **     * The results of all window-functions for the row are stored
150610  **       in the associated Window.regResult registers.
150611  **
150612  **     * The required terminal values are stored in the current row of
150613  **       temp table Window.iEphCsr.
150614  **
150615  **   In some cases, depending on the window frame and the specific window
150616  **   functions invoked, sqlite3WindowCodeStep() caches each entire partition
150617  **   in a temp table before returning any rows. In other cases it does not.
150618  **   This detail is encapsulated within this file, the code generated by
150619  **   select.c is the same in either case.
150620  **
150621  ** BUILT-IN WINDOW FUNCTIONS
150622  **
150623  **   This implementation features the following built-in window functions:
150624  **
150625  **     row_number()
150626  **     rank()
150627  **     dense_rank()
150628  **     percent_rank()
150629  **     cume_dist()
150630  **     ntile(N)
150631  **     lead(expr [, offset [, default]])
150632  **     lag(expr [, offset [, default]])
150633  **     first_value(expr)
150634  **     last_value(expr)
150635  **     nth_value(expr, N)
150636  **   
150637  **   These are the same built-in window functions supported by Postgres. 
150638  **   Although the behaviour of aggregate window functions (functions that
150639  **   can be used as either aggregates or window funtions) allows them to
150640  **   be implemented using an API, built-in window functions are much more
150641  **   esoteric. Additionally, some window functions (e.g. nth_value()) 
150642  **   may only be implemented by caching the entire partition in memory.
150643  **   As such, some built-in window functions use the same API as aggregate
150644  **   window functions and some are implemented directly using VDBE 
150645  **   instructions. Additionally, for those functions that use the API, the
150646  **   window frame is sometimes modified before the SELECT statement is
150647  **   rewritten. For example, regardless of the specified window frame, the
150648  **   row_number() function always uses:
150649  **
150650  **     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
150651  **
150652  **   See sqlite3WindowUpdate() for details.
150653  **
150654  **   As well as some of the built-in window functions, aggregate window
150655  **   functions min() and max() are implemented using VDBE instructions if
150656  **   the start of the window frame is declared as anything other than 
150657  **   UNBOUNDED PRECEDING.
150658  */
150659  
150660  /*
150661  ** Implementation of built-in window function row_number(). Assumes that the
150662  ** window frame has been coerced to:
150663  **
150664  **   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
150665  */
150666  static void row_numberStepFunc(
150667    sqlite3_context *pCtx, 
150668    int nArg,
150669    sqlite3_value **apArg
150670  ){
150671    i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150672    if( p ) (*p)++;
150673    UNUSED_PARAMETER(nArg);
150674    UNUSED_PARAMETER(apArg);
150675  }
150676  static void row_numberValueFunc(sqlite3_context *pCtx){
150677    i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150678    sqlite3_result_int64(pCtx, (p ? *p : 0));
150679  }
150680  
150681  /*
150682  ** Context object type used by rank(), dense_rank(), percent_rank() and
150683  ** cume_dist().
150684  */
150685  struct CallCount {
150686    i64 nValue;
150687    i64 nStep;
150688    i64 nTotal;
150689  };
150690  
150691  /*
150692  ** Implementation of built-in window function dense_rank(). Assumes that
150693  ** the window frame has been set to:
150694  **
150695  **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
150696  */
150697  static void dense_rankStepFunc(
150698    sqlite3_context *pCtx, 
150699    int nArg,
150700    sqlite3_value **apArg
150701  ){
150702    struct CallCount *p;
150703    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150704    if( p ) p->nStep = 1;
150705    UNUSED_PARAMETER(nArg);
150706    UNUSED_PARAMETER(apArg);
150707  }
150708  static void dense_rankValueFunc(sqlite3_context *pCtx){
150709    struct CallCount *p;
150710    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150711    if( p ){
150712      if( p->nStep ){
150713        p->nValue++;
150714        p->nStep = 0;
150715      }
150716      sqlite3_result_int64(pCtx, p->nValue);
150717    }
150718  }
150719  
150720  /*
150721  ** Implementation of built-in window function rank(). Assumes that
150722  ** the window frame has been set to:
150723  **
150724  **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
150725  */
150726  static void rankStepFunc(
150727    sqlite3_context *pCtx, 
150728    int nArg,
150729    sqlite3_value **apArg
150730  ){
150731    struct CallCount *p;
150732    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150733    if( p ){
150734      p->nStep++;
150735      if( p->nValue==0 ){
150736        p->nValue = p->nStep;
150737      }
150738    }
150739    UNUSED_PARAMETER(nArg);
150740    UNUSED_PARAMETER(apArg);
150741  }
150742  static void rankValueFunc(sqlite3_context *pCtx){
150743    struct CallCount *p;
150744    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150745    if( p ){
150746      sqlite3_result_int64(pCtx, p->nValue);
150747      p->nValue = 0;
150748    }
150749  }
150750  
150751  /*
150752  ** Implementation of built-in window function percent_rank(). Assumes that
150753  ** the window frame has been set to:
150754  **
150755  **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
150756  */
150757  static void percent_rankStepFunc(
150758    sqlite3_context *pCtx, 
150759    int nArg,
150760    sqlite3_value **apArg
150761  ){
150762    struct CallCount *p;
150763    UNUSED_PARAMETER(nArg); assert( nArg==1 );
150764  
150765    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150766    if( p ){
150767      if( p->nTotal==0 ){
150768        p->nTotal = sqlite3_value_int64(apArg[0]);
150769      }
150770      p->nStep++;
150771      if( p->nValue==0 ){
150772        p->nValue = p->nStep;
150773      }
150774    }
150775  }
150776  static void percent_rankValueFunc(sqlite3_context *pCtx){
150777    struct CallCount *p;
150778    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150779    if( p ){
150780      if( p->nTotal>1 ){
150781        double r = (double)(p->nValue-1) / (double)(p->nTotal-1);
150782        sqlite3_result_double(pCtx, r);
150783      }else{
150784        sqlite3_result_double(pCtx, 0.0);
150785      }
150786      p->nValue = 0;
150787    }
150788  }
150789  
150790  /*
150791  ** Implementation of built-in window function cume_dist(). Assumes that
150792  ** the window frame has been set to:
150793  **
150794  **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
150795  */
150796  static void cume_distStepFunc(
150797    sqlite3_context *pCtx, 
150798    int nArg,
150799    sqlite3_value **apArg
150800  ){
150801    struct CallCount *p;
150802    assert( nArg==1 ); UNUSED_PARAMETER(nArg);
150803  
150804    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150805    if( p ){
150806      if( p->nTotal==0 ){
150807        p->nTotal = sqlite3_value_int64(apArg[0]);
150808      }
150809      p->nStep++;
150810    }
150811  }
150812  static void cume_distValueFunc(sqlite3_context *pCtx){
150813    struct CallCount *p;
150814    p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150815    if( p && p->nTotal ){
150816      double r = (double)(p->nStep) / (double)(p->nTotal);
150817      sqlite3_result_double(pCtx, r);
150818    }
150819  }
150820  
150821  /*
150822  ** Context object for ntile() window function.
150823  */
150824  struct NtileCtx {
150825    i64 nTotal;                     /* Total rows in partition */
150826    i64 nParam;                     /* Parameter passed to ntile(N) */
150827    i64 iRow;                       /* Current row */
150828  };
150829  
150830  /*
150831  ** Implementation of ntile(). This assumes that the window frame has
150832  ** been coerced to:
150833  **
150834  **   ROWS UNBOUNDED PRECEDING AND CURRENT ROW
150835  */
150836  static void ntileStepFunc(
150837    sqlite3_context *pCtx, 
150838    int nArg,
150839    sqlite3_value **apArg
150840  ){
150841    struct NtileCtx *p;
150842    assert( nArg==2 ); UNUSED_PARAMETER(nArg);
150843    p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150844    if( p ){
150845      if( p->nTotal==0 ){
150846        p->nParam = sqlite3_value_int64(apArg[0]);
150847        p->nTotal = sqlite3_value_int64(apArg[1]);
150848        if( p->nParam<=0 ){
150849          sqlite3_result_error(
150850              pCtx, "argument of ntile must be a positive integer", -1
150851          );
150852        }
150853      }
150854      p->iRow++;
150855    }
150856  }
150857  static void ntileValueFunc(sqlite3_context *pCtx){
150858    struct NtileCtx *p;
150859    p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150860    if( p && p->nParam>0 ){
150861      int nSize = (p->nTotal / p->nParam);
150862      if( nSize==0 ){
150863        sqlite3_result_int64(pCtx, p->iRow);
150864      }else{
150865        i64 nLarge = p->nTotal - p->nParam*nSize;
150866        i64 iSmall = nLarge*(nSize+1);
150867        i64 iRow = p->iRow-1;
150868  
150869        assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
150870  
150871        if( iRow<iSmall ){
150872          sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
150873        }else{
150874          sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
150875        }
150876      }
150877    }
150878  }
150879  
150880  /*
150881  ** Context object for last_value() window function.
150882  */
150883  struct LastValueCtx {
150884    sqlite3_value *pVal;
150885    int nVal;
150886  };
150887  
150888  /*
150889  ** Implementation of last_value().
150890  */
150891  static void last_valueStepFunc(
150892    sqlite3_context *pCtx, 
150893    int nArg,
150894    sqlite3_value **apArg
150895  ){
150896    struct LastValueCtx *p;
150897    UNUSED_PARAMETER(nArg);
150898    p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150899    if( p ){
150900      sqlite3_value_free(p->pVal);
150901      p->pVal = sqlite3_value_dup(apArg[0]);
150902      if( p->pVal==0 ){
150903        sqlite3_result_error_nomem(pCtx);
150904      }else{
150905        p->nVal++;
150906      }
150907    }
150908  }
150909  static void last_valueInvFunc(
150910    sqlite3_context *pCtx, 
150911    int nArg,
150912    sqlite3_value **apArg
150913  ){
150914    struct LastValueCtx *p;
150915    UNUSED_PARAMETER(nArg);
150916    UNUSED_PARAMETER(apArg);
150917    p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150918    if( ALWAYS(p) ){
150919      p->nVal--;
150920      if( p->nVal==0 ){
150921        sqlite3_value_free(p->pVal);
150922        p->pVal = 0;
150923      }
150924    }
150925  }
150926  static void last_valueValueFunc(sqlite3_context *pCtx){
150927    struct LastValueCtx *p;
150928    p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150929    if( p && p->pVal ){
150930      sqlite3_result_value(pCtx, p->pVal);
150931    }
150932  }
150933  static void last_valueFinalizeFunc(sqlite3_context *pCtx){
150934    struct LastValueCtx *p;
150935    p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
150936    if( p && p->pVal ){
150937      sqlite3_result_value(pCtx, p->pVal);
150938      sqlite3_value_free(p->pVal);
150939      p->pVal = 0;
150940    }
150941  }
150942  
150943  /*
150944  ** Static names for the built-in window function names.  These static
150945  ** names are used, rather than string literals, so that FuncDef objects
150946  ** can be associated with a particular window function by direct
150947  ** comparison of the zName pointer.  Example:
150948  **
150949  **       if( pFuncDef->zName==row_valueName ){ ... }
150950  */
150951  static const char row_numberName[] =   "row_number";
150952  static const char dense_rankName[] =   "dense_rank";
150953  static const char rankName[] =         "rank";
150954  static const char percent_rankName[] = "percent_rank";
150955  static const char cume_distName[] =    "cume_dist";
150956  static const char ntileName[] =        "ntile";
150957  static const char last_valueName[] =   "last_value";
150958  static const char nth_valueName[] =    "nth_value";
150959  static const char first_valueName[] =  "first_value";
150960  static const char leadName[] =         "lead";
150961  static const char lagName[] =          "lag";
150962  
150963  /*
150964  ** No-op implementations of xStep() and xFinalize().  Used as place-holders
150965  ** for built-in window functions that never call those interfaces.
150966  **
150967  ** The noopValueFunc() is called but is expected to do nothing.  The
150968  ** noopStepFunc() is never called, and so it is marked with NO_TEST to
150969  ** let the test coverage routine know not to expect this function to be
150970  ** invoked.
150971  */
150972  static void noopStepFunc(    /*NO_TEST*/
150973    sqlite3_context *p,        /*NO_TEST*/
150974    int n,                     /*NO_TEST*/
150975    sqlite3_value **a          /*NO_TEST*/
150976  ){                           /*NO_TEST*/
150977    UNUSED_PARAMETER(p);       /*NO_TEST*/
150978    UNUSED_PARAMETER(n);       /*NO_TEST*/
150979    UNUSED_PARAMETER(a);       /*NO_TEST*/
150980    assert(0);                 /*NO_TEST*/
150981  }                            /*NO_TEST*/
150982  static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
150983  
150984  /* Window functions that use all window interfaces: xStep, xFinal,
150985  ** xValue, and xInverse */
150986  #define WINDOWFUNCALL(name,nArg,extra) {                                   \
150987    nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
150988    name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \
150989    name ## InvFunc, name ## Name, {0}                                       \
150990  }
150991  
150992  /* Window functions that are implemented using bytecode and thus have
150993  ** no-op routines for their methods */
150994  #define WINDOWFUNCNOOP(name,nArg,extra) {                                  \
150995    nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
150996    noopStepFunc, noopValueFunc, noopValueFunc,                              \
150997    noopStepFunc, name ## Name, {0}                                          \
150998  }
150999  
151000  /* Window functions that use all window interfaces: xStep, the
151001  ** same routine for xFinalize and xValue and which never call
151002  ** xInverse. */
151003  #define WINDOWFUNCX(name,nArg,extra) {                                     \
151004    nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
151005    name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \
151006    noopStepFunc, name ## Name, {0}                                          \
151007  }
151008  
151009  
151010  /*
151011  ** Register those built-in window functions that are not also aggregates.
151012  */
151013  SQLITE_PRIVATE void sqlite3WindowFunctions(void){
151014    static FuncDef aWindowFuncs[] = {
151015      WINDOWFUNCX(row_number, 0, 0),
151016      WINDOWFUNCX(dense_rank, 0, 0),
151017      WINDOWFUNCX(rank, 0, 0),
151018      WINDOWFUNCX(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
151019      WINDOWFUNCX(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
151020      WINDOWFUNCX(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
151021      WINDOWFUNCALL(last_value, 1, 0),
151022      WINDOWFUNCNOOP(nth_value, 2, 0),
151023      WINDOWFUNCNOOP(first_value, 1, 0),
151024      WINDOWFUNCNOOP(lead, 1, 0),
151025      WINDOWFUNCNOOP(lead, 2, 0),
151026      WINDOWFUNCNOOP(lead, 3, 0),
151027      WINDOWFUNCNOOP(lag, 1, 0),
151028      WINDOWFUNCNOOP(lag, 2, 0),
151029      WINDOWFUNCNOOP(lag, 3, 0),
151030    };
151031    sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
151032  }
151033  
151034  /*
151035  ** This function is called immediately after resolving the function name
151036  ** for a window function within a SELECT statement. Argument pList is a
151037  ** linked list of WINDOW definitions for the current SELECT statement.
151038  ** Argument pFunc is the function definition just resolved and pWin
151039  ** is the Window object representing the associated OVER clause. This
151040  ** function updates the contents of pWin as follows:
151041  **
151042  **   * If the OVER clause refered to a named window (as in "max(x) OVER win"),
151043  **     search list pList for a matching WINDOW definition, and update pWin
151044  **     accordingly. If no such WINDOW clause can be found, leave an error
151045  **     in pParse.
151046  **
151047  **   * If the function is a built-in window function that requires the
151048  **     window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
151049  **     of this file), pWin is updated here.
151050  */
151051  SQLITE_PRIVATE void sqlite3WindowUpdate(
151052    Parse *pParse, 
151053    Window *pList,                  /* List of named windows for this SELECT */
151054    Window *pWin,                   /* Window frame to update */
151055    FuncDef *pFunc                  /* Window function definition */
151056  ){
151057    if( pWin->zName && pWin->eType==0 ){
151058      Window *p;
151059      for(p=pList; p; p=p->pNextWin){
151060        if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break;
151061      }
151062      if( p==0 ){
151063        sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName);
151064        return;
151065      }
151066      pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
151067      pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
151068      pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
151069      pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
151070      pWin->eStart = p->eStart;
151071      pWin->eEnd = p->eEnd;
151072      pWin->eType = p->eType;
151073    }
151074    if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
151075      sqlite3 *db = pParse->db;
151076      if( pWin->pFilter ){
151077        sqlite3ErrorMsg(pParse, 
151078            "FILTER clause may only be used with aggregate window functions"
151079        );
151080      }else
151081      if( pFunc->zName==row_numberName || pFunc->zName==ntileName ){
151082        sqlite3ExprDelete(db, pWin->pStart);
151083        sqlite3ExprDelete(db, pWin->pEnd);
151084        pWin->pStart = pWin->pEnd = 0;
151085        pWin->eType = TK_ROWS;
151086        pWin->eStart = TK_UNBOUNDED;
151087        pWin->eEnd = TK_CURRENT;
151088      }else
151089  
151090      if( pFunc->zName==dense_rankName || pFunc->zName==rankName
151091       || pFunc->zName==percent_rankName || pFunc->zName==cume_distName
151092      ){
151093        sqlite3ExprDelete(db, pWin->pStart);
151094        sqlite3ExprDelete(db, pWin->pEnd);
151095        pWin->pStart = pWin->pEnd = 0;
151096        pWin->eType = TK_RANGE;
151097        pWin->eStart = TK_UNBOUNDED;
151098        pWin->eEnd = TK_CURRENT;
151099      }
151100    }
151101    pWin->pFunc = pFunc;
151102  }
151103  
151104  /*
151105  ** Context object passed through sqlite3WalkExprList() to
151106  ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
151107  */
151108  typedef struct WindowRewrite WindowRewrite;
151109  struct WindowRewrite {
151110    Window *pWin;
151111    SrcList *pSrc;
151112    ExprList *pSub;
151113    Select *pSubSelect;             /* Current sub-select, if any */
151114  };
151115  
151116  /*
151117  ** Callback function used by selectWindowRewriteEList(). If necessary,
151118  ** this function appends to the output expression-list and updates 
151119  ** expression (*ppExpr) in place.
151120  */
151121  static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
151122    struct WindowRewrite *p = pWalker->u.pRewrite;
151123    Parse *pParse = pWalker->pParse;
151124  
151125    /* If this function is being called from within a scalar sub-select
151126    ** that used by the SELECT statement being processed, only process
151127    ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
151128    ** not process aggregates or window functions at all, as they belong
151129    ** to the scalar sub-select.  */
151130    if( p->pSubSelect ){
151131      if( pExpr->op!=TK_COLUMN ){
151132        return WRC_Continue;
151133      }else{
151134        int nSrc = p->pSrc->nSrc;
151135        int i;
151136        for(i=0; i<nSrc; i++){
151137          if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
151138        }
151139        if( i==nSrc ) return WRC_Continue;
151140      }
151141    }
151142  
151143    switch( pExpr->op ){
151144  
151145      case TK_FUNCTION:
151146        if( !ExprHasProperty(pExpr, EP_WinFunc) ){
151147          break;
151148        }else{
151149          Window *pWin;
151150          for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
151151            if( pExpr->y.pWin==pWin ){
151152              assert( pWin->pOwner==pExpr );
151153              return WRC_Prune;
151154            }
151155          }
151156        }
151157        /* Fall through.  */
151158  
151159      case TK_AGG_FUNCTION:
151160      case TK_COLUMN: {
151161        Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
151162        p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
151163        if( p->pSub ){
151164          assert( ExprHasProperty(pExpr, EP_Static)==0 );
151165          ExprSetProperty(pExpr, EP_Static);
151166          sqlite3ExprDelete(pParse->db, pExpr);
151167          ExprClearProperty(pExpr, EP_Static);
151168          memset(pExpr, 0, sizeof(Expr));
151169  
151170          pExpr->op = TK_COLUMN;
151171          pExpr->iColumn = p->pSub->nExpr-1;
151172          pExpr->iTable = p->pWin->iEphCsr;
151173        }
151174  
151175        break;
151176      }
151177  
151178      default: /* no-op */
151179        break;
151180    }
151181  
151182    return WRC_Continue;
151183  }
151184  static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
151185    struct WindowRewrite *p = pWalker->u.pRewrite;
151186    Select *pSave = p->pSubSelect;
151187    if( pSave==pSelect ){
151188      return WRC_Continue;
151189    }else{
151190      p->pSubSelect = pSelect;
151191      sqlite3WalkSelect(pWalker, pSelect);
151192      p->pSubSelect = pSave;
151193    }
151194    return WRC_Prune;
151195  }
151196  
151197  
151198  /*
151199  ** Iterate through each expression in expression-list pEList. For each:
151200  **
151201  **   * TK_COLUMN,
151202  **   * aggregate function, or
151203  **   * window function with a Window object that is not a member of the 
151204  **     Window list passed as the second argument (pWin).
151205  **
151206  ** Append the node to output expression-list (*ppSub). And replace it
151207  ** with a TK_COLUMN that reads the (N-1)th element of table 
151208  ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
151209  ** appending the new one.
151210  */
151211  static void selectWindowRewriteEList(
151212    Parse *pParse, 
151213    Window *pWin,
151214    SrcList *pSrc,
151215    ExprList *pEList,               /* Rewrite expressions in this list */
151216    ExprList **ppSub                /* IN/OUT: Sub-select expression-list */
151217  ){
151218    Walker sWalker;
151219    WindowRewrite sRewrite;
151220  
151221    memset(&sWalker, 0, sizeof(Walker));
151222    memset(&sRewrite, 0, sizeof(WindowRewrite));
151223  
151224    sRewrite.pSub = *ppSub;
151225    sRewrite.pWin = pWin;
151226    sRewrite.pSrc = pSrc;
151227  
151228    sWalker.pParse = pParse;
151229    sWalker.xExprCallback = selectWindowRewriteExprCb;
151230    sWalker.xSelectCallback = selectWindowRewriteSelectCb;
151231    sWalker.u.pRewrite = &sRewrite;
151232  
151233    (void)sqlite3WalkExprList(&sWalker, pEList);
151234  
151235    *ppSub = sRewrite.pSub;
151236  }
151237  
151238  /*
151239  ** Append a copy of each expression in expression-list pAppend to
151240  ** expression list pList. Return a pointer to the result list.
151241  */
151242  static ExprList *exprListAppendList(
151243    Parse *pParse,          /* Parsing context */
151244    ExprList *pList,        /* List to which to append. Might be NULL */
151245    ExprList *pAppend       /* List of values to append. Might be NULL */
151246  ){
151247    if( pAppend ){
151248      int i;
151249      int nInit = pList ? pList->nExpr : 0;
151250      for(i=0; i<pAppend->nExpr; i++){
151251        Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
151252        pList = sqlite3ExprListAppend(pParse, pList, pDup);
151253        if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
151254      }
151255    }
151256    return pList;
151257  }
151258  
151259  /*
151260  ** If the SELECT statement passed as the second argument does not invoke
151261  ** any SQL window functions, this function is a no-op. Otherwise, it 
151262  ** rewrites the SELECT statement so that window function xStep functions
151263  ** are invoked in the correct order as described under "SELECT REWRITING"
151264  ** at the top of this file.
151265  */
151266  SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
151267    int rc = SQLITE_OK;
151268    if( p->pWin && p->pPrior==0 ){
151269      Vdbe *v = sqlite3GetVdbe(pParse);
151270      sqlite3 *db = pParse->db;
151271      Select *pSub = 0;             /* The subquery */
151272      SrcList *pSrc = p->pSrc;
151273      Expr *pWhere = p->pWhere;
151274      ExprList *pGroupBy = p->pGroupBy;
151275      Expr *pHaving = p->pHaving;
151276      ExprList *pSort = 0;
151277  
151278      ExprList *pSublist = 0;       /* Expression list for sub-query */
151279      Window *pMWin = p->pWin;      /* Master window object */
151280      Window *pWin;                 /* Window object iterator */
151281  
151282      p->pSrc = 0;
151283      p->pWhere = 0;
151284      p->pGroupBy = 0;
151285      p->pHaving = 0;
151286  
151287      /* Create the ORDER BY clause for the sub-select. This is the concatenation
151288      ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
151289      ** redundant, remove the ORDER BY from the parent SELECT.  */
151290      pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
151291      pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
151292      if( pSort && p->pOrderBy ){
151293        if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
151294          sqlite3ExprListDelete(db, p->pOrderBy);
151295          p->pOrderBy = 0;
151296        }
151297      }
151298  
151299      /* Assign a cursor number for the ephemeral table used to buffer rows.
151300      ** The OpenEphemeral instruction is coded later, after it is known how
151301      ** many columns the table will have.  */
151302      pMWin->iEphCsr = pParse->nTab++;
151303  
151304      selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
151305      selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
151306      pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
151307  
151308      /* Append the PARTITION BY and ORDER BY expressions to the to the 
151309      ** sub-select expression list. They are required to figure out where 
151310      ** boundaries for partitions and sets of peer rows lie.  */
151311      pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
151312      pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
151313  
151314      /* Append the arguments passed to each window function to the
151315      ** sub-select expression list. Also allocate two registers for each
151316      ** window function - one for the accumulator, another for interim
151317      ** results.  */
151318      for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151319        pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
151320        pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
151321        if( pWin->pFilter ){
151322          Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
151323          pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
151324        }
151325        pWin->regAccum = ++pParse->nMem;
151326        pWin->regResult = ++pParse->nMem;
151327        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
151328      }
151329  
151330      /* If there is no ORDER BY or PARTITION BY clause, and the window
151331      ** function accepts zero arguments, and there are no other columns
151332      ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
151333      ** that pSublist is still NULL here. Add a constant expression here to 
151334      ** keep everything legal in this case. 
151335      */
151336      if( pSublist==0 ){
151337        pSublist = sqlite3ExprListAppend(pParse, 0, 
151338            sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
151339        );
151340      }
151341  
151342      pSub = sqlite3SelectNew(
151343          pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
151344      );
151345      p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
151346      if( p->pSrc ){
151347        p->pSrc->a[0].pSelect = pSub;
151348        sqlite3SrcListAssignCursors(pParse, p->pSrc);
151349        if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
151350          rc = SQLITE_NOMEM;
151351        }else{
151352          pSub->selFlags |= SF_Expanded;
151353          p->selFlags &= ~SF_Aggregate;
151354          sqlite3SelectPrep(pParse, pSub, 0);
151355        }
151356  
151357        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
151358      }else{
151359        sqlite3SelectDelete(db, pSub);
151360      }
151361      if( db->mallocFailed ) rc = SQLITE_NOMEM;
151362    }
151363  
151364    return rc;
151365  }
151366  
151367  /*
151368  ** Free the Window object passed as the second argument.
151369  */
151370  SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
151371    if( p ){
151372      sqlite3ExprDelete(db, p->pFilter);
151373      sqlite3ExprListDelete(db, p->pPartition);
151374      sqlite3ExprListDelete(db, p->pOrderBy);
151375      sqlite3ExprDelete(db, p->pEnd);
151376      sqlite3ExprDelete(db, p->pStart);
151377      sqlite3DbFree(db, p->zName);
151378      sqlite3DbFree(db, p);
151379    }
151380  }
151381  
151382  /*
151383  ** Free the linked list of Window objects starting at the second argument.
151384  */
151385  SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
151386    while( p ){
151387      Window *pNext = p->pNextWin;
151388      sqlite3WindowDelete(db, p);
151389      p = pNext;
151390    }
151391  }
151392  
151393  /*
151394  ** The argument expression is an PRECEDING or FOLLOWING offset.  The
151395  ** value should be a non-negative integer.  If the value is not a
151396  ** constant, change it to NULL.  The fact that it is then a non-negative
151397  ** integer will be caught later.  But it is important not to leave
151398  ** variable values in the expression tree.
151399  */
151400  static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
151401    if( 0==sqlite3ExprIsConstant(pExpr) ){
151402      if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
151403      sqlite3ExprDelete(pParse->db, pExpr);
151404      pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
151405    }
151406    return pExpr;
151407  }
151408  
151409  /*
151410  ** Allocate and return a new Window object describing a Window Definition.
151411  */
151412  SQLITE_PRIVATE Window *sqlite3WindowAlloc(
151413    Parse *pParse,    /* Parsing context */
151414    int eType,        /* Frame type. TK_RANGE or TK_ROWS */
151415    int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
151416    Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */
151417    int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
151418    Expr *pEnd        /* End window size if TK_FOLLOWING or PRECEDING */
151419  ){
151420    Window *pWin = 0;
151421  
151422    /* Parser assures the following: */
151423    assert( eType==TK_RANGE || eType==TK_ROWS );
151424    assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
151425             || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
151426    assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
151427             || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
151428    assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
151429    assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
151430  
151431  
151432    /* If a frame is declared "RANGE" (not "ROWS"), then it may not use
151433    ** either "<expr> PRECEDING" or "<expr> FOLLOWING".
151434    */
151435    if( eType==TK_RANGE && (pStart!=0 || pEnd!=0) ){
151436      sqlite3ErrorMsg(pParse, "RANGE must use only UNBOUNDED or CURRENT ROW");
151437      goto windowAllocErr;
151438    }
151439  
151440    /* Additionally, the
151441    ** starting boundary type may not occur earlier in the following list than
151442    ** the ending boundary type:
151443    **
151444    **   UNBOUNDED PRECEDING
151445    **   <expr> PRECEDING
151446    **   CURRENT ROW
151447    **   <expr> FOLLOWING
151448    **   UNBOUNDED FOLLOWING
151449    **
151450    ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
151451    ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
151452    ** frame boundary.
151453    */
151454    if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
151455     || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
151456    ){
151457      sqlite3ErrorMsg(pParse, "unsupported frame delimiter for ROWS");
151458      goto windowAllocErr;
151459    }
151460  
151461    pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
151462    if( pWin==0 ) goto windowAllocErr;
151463    pWin->eType = eType;
151464    pWin->eStart = eStart;
151465    pWin->eEnd = eEnd;
151466    pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
151467    pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
151468    return pWin;
151469  
151470  windowAllocErr:
151471    sqlite3ExprDelete(pParse->db, pEnd);
151472    sqlite3ExprDelete(pParse->db, pStart);
151473    return 0;
151474  }
151475  
151476  /*
151477  ** Attach window object pWin to expression p.
151478  */
151479  SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
151480    if( p ){
151481      assert( p->op==TK_FUNCTION );
151482      /* This routine is only called for the parser.  If pWin was not
151483      ** allocated due to an OOM, then the parser would fail before ever
151484      ** invoking this routine */
151485      if( ALWAYS(pWin) ){
151486        p->y.pWin = pWin;
151487        ExprSetProperty(p, EP_WinFunc);
151488        pWin->pOwner = p;
151489        if( p->flags & EP_Distinct ){
151490          sqlite3ErrorMsg(pParse,
151491             "DISTINCT is not supported for window functions");
151492        }
151493      }
151494    }else{
151495      sqlite3WindowDelete(pParse->db, pWin);
151496    }
151497  }
151498  
151499  /*
151500  ** Return 0 if the two window objects are identical, or non-zero otherwise.
151501  ** Identical window objects can be processed in a single scan.
151502  */
151503  SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
151504    if( p1->eType!=p2->eType ) return 1;
151505    if( p1->eStart!=p2->eStart ) return 1;
151506    if( p1->eEnd!=p2->eEnd ) return 1;
151507    if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
151508    if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
151509    if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
151510    if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
151511    return 0;
151512  }
151513  
151514  
151515  /*
151516  ** This is called by code in select.c before it calls sqlite3WhereBegin()
151517  ** to begin iterating through the sub-query results. It is used to allocate
151518  ** and initialize registers and cursors used by sqlite3WindowCodeStep().
151519  */
151520  SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
151521    Window *pWin;
151522    Vdbe *v = sqlite3GetVdbe(pParse);
151523    int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
151524    nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
151525    if( nPart ){
151526      pMWin->regPart = pParse->nMem+1;
151527      pParse->nMem += nPart;
151528      sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
151529    }
151530  
151531    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151532      FuncDef *p = pWin->pFunc;
151533      if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
151534        /* The inline versions of min() and max() require a single ephemeral
151535        ** table and 3 registers. The registers are used as follows:
151536        **
151537        **   regApp+0: slot to copy min()/max() argument to for MakeRecord
151538        **   regApp+1: integer value used to ensure keys are unique
151539        **   regApp+2: output of MakeRecord
151540        */
151541        ExprList *pList = pWin->pOwner->x.pList;
151542        KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
151543        pWin->csrApp = pParse->nTab++;
151544        pWin->regApp = pParse->nMem+1;
151545        pParse->nMem += 3;
151546        if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
151547          assert( pKeyInfo->aSortOrder[0]==0 );
151548          pKeyInfo->aSortOrder[0] = 1;
151549        }
151550        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
151551        sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
151552        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
151553      }
151554      else if( p->zName==nth_valueName || p->zName==first_valueName ){
151555        /* Allocate two registers at pWin->regApp. These will be used to
151556        ** store the start and end index of the current frame.  */
151557        assert( pMWin->iEphCsr );
151558        pWin->regApp = pParse->nMem+1;
151559        pWin->csrApp = pParse->nTab++;
151560        pParse->nMem += 2;
151561        sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
151562      }
151563      else if( p->zName==leadName || p->zName==lagName ){
151564        assert( pMWin->iEphCsr );
151565        pWin->csrApp = pParse->nTab++;
151566        sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
151567      }
151568    }
151569  }
151570  
151571  /*
151572  ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
151573  ** value of the second argument to nth_value() (eCond==2) has just been
151574  ** evaluated and the result left in register reg. This function generates VM
151575  ** code to check that the value is a non-negative integer and throws an
151576  ** exception if it is not.
151577  */
151578  static void windowCheckIntValue(Parse *pParse, int reg, int eCond){
151579    static const char *azErr[] = {
151580      "frame starting offset must be a non-negative integer",
151581      "frame ending offset must be a non-negative integer",
151582      "second argument to nth_value must be a positive integer"
151583    };
151584    static int aOp[] = { OP_Ge, OP_Ge, OP_Gt };
151585    Vdbe *v = sqlite3GetVdbe(pParse);
151586    int regZero = sqlite3GetTempReg(pParse);
151587    assert( eCond==0 || eCond==1 || eCond==2 );
151588    sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
151589    sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
151590    VdbeCoverageIf(v, eCond==0);
151591    VdbeCoverageIf(v, eCond==1);
151592    VdbeCoverageIf(v, eCond==2);
151593    sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
151594    VdbeCoverageNeverNullIf(v, eCond==0);
151595    VdbeCoverageNeverNullIf(v, eCond==1);
151596    VdbeCoverageNeverNullIf(v, eCond==2);
151597    sqlite3MayAbort(pParse);
151598    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
151599    sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
151600    sqlite3ReleaseTempReg(pParse, regZero);
151601  }
151602  
151603  /*
151604  ** Return the number of arguments passed to the window-function associated
151605  ** with the object passed as the only argument to this function.
151606  */
151607  static int windowArgCount(Window *pWin){
151608    ExprList *pList = pWin->pOwner->x.pList;
151609    return (pList ? pList->nExpr : 0);
151610  }
151611  
151612  /*
151613  ** Generate VM code to invoke either xStep() (if bInverse is 0) or 
151614  ** xInverse (if bInverse is non-zero) for each window function in the 
151615  ** linked list starting at pMWin. Or, for built-in window functions
151616  ** that do not use the standard function API, generate the required
151617  ** inline VM code.
151618  **
151619  ** If argument csr is greater than or equal to 0, then argument reg is
151620  ** the first register in an array of registers guaranteed to be large
151621  ** enough to hold the array of arguments for each function. In this case
151622  ** the arguments are extracted from the current row of csr into the
151623  ** array of registers before invoking OP_AggStep or OP_AggInverse
151624  **
151625  ** Or, if csr is less than zero, then the array of registers at reg is
151626  ** already populated with all columns from the current row of the sub-query.
151627  **
151628  ** If argument regPartSize is non-zero, then it is a register containing the
151629  ** number of rows in the current partition.
151630  */
151631  static void windowAggStep(
151632    Parse *pParse, 
151633    Window *pMWin,                  /* Linked list of window functions */
151634    int csr,                        /* Read arguments from this cursor */
151635    int bInverse,                   /* True to invoke xInverse instead of xStep */
151636    int reg,                        /* Array of registers */
151637    int regPartSize                 /* Register containing size of partition */
151638  ){
151639    Vdbe *v = sqlite3GetVdbe(pParse);
151640    Window *pWin;
151641    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151642      int flags = pWin->pFunc->funcFlags;
151643      int regArg;
151644      int nArg = windowArgCount(pWin);
151645  
151646      if( csr>=0 ){
151647        int i;
151648        for(i=0; i<nArg; i++){
151649          sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
151650        }
151651        regArg = reg;
151652        if( flags & SQLITE_FUNC_WINDOW_SIZE ){
151653          if( nArg==0 ){
151654            regArg = regPartSize;
151655          }else{
151656            sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg);
151657          }
151658          nArg++;
151659        }
151660      }else{
151661        assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) );
151662        regArg = reg + pWin->iArgCol;
151663      }
151664  
151665      if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 
151666        && pWin->eStart!=TK_UNBOUNDED 
151667      ){
151668        int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
151669        VdbeCoverage(v);
151670        if( bInverse==0 ){
151671          sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
151672          sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
151673          sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
151674          sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
151675        }else{
151676          sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
151677          VdbeCoverageNeverTaken(v);
151678          sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
151679          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
151680        }
151681        sqlite3VdbeJumpHere(v, addrIsNull);
151682      }else if( pWin->regApp ){
151683        assert( pWin->pFunc->zName==nth_valueName
151684             || pWin->pFunc->zName==first_valueName
151685        );
151686        assert( bInverse==0 || bInverse==1 );
151687        sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
151688      }else if( pWin->pFunc->zName==leadName
151689             || pWin->pFunc->zName==lagName
151690      ){
151691        /* no-op */
151692      }else{
151693        int addrIf = 0;
151694        if( pWin->pFilter ){
151695          int regTmp;
151696          assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
151697          assert( nArg || pWin->pOwner->x.pList==0 );
151698          if( csr>0 ){
151699            regTmp = sqlite3GetTempReg(pParse);
151700            sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
151701          }else{
151702            regTmp = regArg + nArg;
151703          }
151704          addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
151705          VdbeCoverage(v);
151706          if( csr>0 ){
151707            sqlite3ReleaseTempReg(pParse, regTmp);
151708          }
151709        }
151710        if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
151711          CollSeq *pColl;
151712          assert( nArg>0 );
151713          pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
151714          sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
151715        }
151716        sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, 
151717                          bInverse, regArg, pWin->regAccum);
151718        sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
151719        sqlite3VdbeChangeP5(v, (u8)nArg);
151720        if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
151721      }
151722    }
151723  }
151724  
151725  /*
151726  ** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
151727  ** (bFinal==1) for each window function in the linked list starting at
151728  ** pMWin. Or, for built-in window-functions that do not use the standard
151729  ** API, generate the equivalent VM code.
151730  */
151731  static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
151732    Vdbe *v = sqlite3GetVdbe(pParse);
151733    Window *pWin;
151734  
151735    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151736      if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 
151737       && pWin->eStart!=TK_UNBOUNDED 
151738      ){
151739        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
151740        sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
151741        VdbeCoverage(v);
151742        sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
151743        sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
151744        if( bFinal ){
151745          sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
151746        }
151747      }else if( pWin->regApp ){
151748      }else{
151749        if( bFinal ){
151750          sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
151751          sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
151752          sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
151753          sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
151754        }else{
151755          sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
151756                               pWin->regResult);
151757          sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
151758        }
151759      }
151760    }
151761  }
151762  
151763  /*
151764  ** This function generates VM code to invoke the sub-routine at address
151765  ** lblFlushPart once for each partition with the entire partition cached in
151766  ** the Window.iEphCsr temp table.
151767  */
151768  static void windowPartitionCache(
151769    Parse *pParse,
151770    Select *p,                      /* The rewritten SELECT statement */
151771    WhereInfo *pWInfo,              /* WhereInfo to call WhereEnd() on */
151772    int regFlushPart,               /* Register to use with Gosub lblFlushPart */
151773    int lblFlushPart,               /* Subroutine to Gosub to */
151774    int *pRegSize                   /* OUT: Register containing partition size */
151775  ){
151776    Window *pMWin = p->pWin;
151777    Vdbe *v = sqlite3GetVdbe(pParse);
151778    int iSubCsr = p->pSrc->a[0].iCursor;
151779    int nSub = p->pSrc->a[0].pTab->nCol;
151780    int k;
151781  
151782    int reg = pParse->nMem+1;
151783    int regRecord = reg+nSub;
151784    int regRowid = regRecord+1;
151785  
151786    *pRegSize = regRowid;
151787    pParse->nMem += nSub + 2;
151788  
151789    /* Load the column values for the row returned by the sub-select
151790    ** into an array of registers starting at reg. */
151791    for(k=0; k<nSub; k++){
151792      sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
151793    }
151794    sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord);
151795  
151796    /* Check if this is the start of a new partition. If so, call the
151797    ** flush_partition sub-routine.  */
151798    if( pMWin->pPartition ){
151799      int addr;
151800      ExprList *pPart = pMWin->pPartition;
151801      int nPart = pPart->nExpr;
151802      int regNewPart = reg + pMWin->nBufferCol;
151803      KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
151804  
151805      addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
151806      sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
151807      sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
151808      VdbeCoverageEqNe(v);
151809      sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
151810      sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
151811      VdbeComment((v, "call flush_partition"));
151812    }
151813  
151814    /* Buffer the current row in the ephemeral table. */
151815    sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
151816    sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
151817  
151818    /* End of the input loop */
151819    sqlite3WhereEnd(pWInfo);
151820  
151821    /* Invoke "flush_partition" to deal with the final (or only) partition */
151822    sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
151823    VdbeComment((v, "call flush_partition"));
151824  }
151825  
151826  /*
151827  ** Invoke the sub-routine at regGosub (generated by code in select.c) to
151828  ** return the current row of Window.iEphCsr. If all window functions are
151829  ** aggregate window functions that use the standard API, a single
151830  ** OP_Gosub instruction is all that this routine generates. Extra VM code
151831  ** for per-row processing is only generated for the following built-in window
151832  ** functions:
151833  **
151834  **   nth_value()
151835  **   first_value()
151836  **   lag()
151837  **   lead()
151838  */
151839  static void windowReturnOneRow(
151840    Parse *pParse,
151841    Window *pMWin,
151842    int regGosub,
151843    int addrGosub
151844  ){
151845    Vdbe *v = sqlite3GetVdbe(pParse);
151846    Window *pWin;
151847    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151848      FuncDef *pFunc = pWin->pFunc;
151849      if( pFunc->zName==nth_valueName
151850       || pFunc->zName==first_valueName
151851      ){
151852        int csr = pWin->csrApp;
151853        int lbl = sqlite3VdbeMakeLabel(pParse);
151854        int tmpReg = sqlite3GetTempReg(pParse);
151855        sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
151856  
151857        if( pFunc->zName==nth_valueName ){
151858          sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
151859          windowCheckIntValue(pParse, tmpReg, 2);
151860        }else{
151861          sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
151862        }
151863        sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
151864        sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
151865        VdbeCoverageNeverNull(v);
151866        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
151867        VdbeCoverageNeverTaken(v);
151868        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
151869        sqlite3VdbeResolveLabel(v, lbl);
151870        sqlite3ReleaseTempReg(pParse, tmpReg);
151871      }
151872      else if( pFunc->zName==leadName || pFunc->zName==lagName ){
151873        int nArg = pWin->pOwner->x.pList->nExpr;
151874        int iEph = pMWin->iEphCsr;
151875        int csr = pWin->csrApp;
151876        int lbl = sqlite3VdbeMakeLabel(pParse);
151877        int tmpReg = sqlite3GetTempReg(pParse);
151878  
151879        if( nArg<3 ){
151880          sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
151881        }else{
151882          sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
151883        }
151884        sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
151885        if( nArg<2 ){
151886          int val = (pFunc->zName==leadName ? 1 : -1);
151887          sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
151888        }else{
151889          int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
151890          int tmpReg2 = sqlite3GetTempReg(pParse);
151891          sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
151892          sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
151893          sqlite3ReleaseTempReg(pParse, tmpReg2);
151894        }
151895  
151896        sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
151897        VdbeCoverage(v);
151898        sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
151899        sqlite3VdbeResolveLabel(v, lbl);
151900        sqlite3ReleaseTempReg(pParse, tmpReg);
151901      }
151902    }
151903    sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
151904  }
151905  
151906  /*
151907  ** Invoke the code generated by windowReturnOneRow() and, optionally, the
151908  ** xInverse() function for each window function, for one or more rows
151909  ** from the Window.iEphCsr temp table. This routine generates VM code
151910  ** similar to:
151911  **
151912  **   while( regCtr>0 ){
151913  **     regCtr--;
151914  **     windowReturnOneRow()
151915  **     if( bInverse ){
151916  **       AggInverse
151917  **     }
151918  **     Next (Window.iEphCsr)
151919  **   }
151920  */
151921  static void windowReturnRows(
151922    Parse *pParse,
151923    Window *pMWin,                  /* List of window functions */
151924    int regCtr,                     /* Register containing number of rows */
151925    int regGosub,                   /* Register for Gosub addrGosub */
151926    int addrGosub,                  /* Address of sub-routine for ReturnOneRow */
151927    int regInvArg,                  /* Array of registers for xInverse args */
151928    int regInvSize                  /* Register containing size of partition */
151929  ){
151930    int addr;
151931    Vdbe *v = sqlite3GetVdbe(pParse);
151932    windowAggFinal(pParse, pMWin, 0);
151933    addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1);
151934    VdbeCoverage(v);
151935    sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
151936    windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
151937    if( regInvArg ){
151938      windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize);
151939    }
151940    sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr);
151941    VdbeCoverage(v);
151942    sqlite3VdbeJumpHere(v, addr+1);   /* The OP_Goto */
151943  }
151944  
151945  /*
151946  ** Generate code to set the accumulator register for each window function
151947  ** in the linked list passed as the second argument to NULL. And perform
151948  ** any equivalent initialization required by any built-in window functions
151949  ** in the list.
151950  */
151951  static int windowInitAccum(Parse *pParse, Window *pMWin){
151952    Vdbe *v = sqlite3GetVdbe(pParse);
151953    int regArg;
151954    int nArg = 0;
151955    Window *pWin;
151956    for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
151957      FuncDef *pFunc = pWin->pFunc;
151958      sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
151959      nArg = MAX(nArg, windowArgCount(pWin));
151960      if( pFunc->zName==nth_valueName
151961       || pFunc->zName==first_valueName
151962      ){
151963        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
151964        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
151965      }
151966  
151967      if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
151968        assert( pWin->eStart!=TK_UNBOUNDED );
151969        sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
151970        sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
151971      }
151972    }
151973    regArg = pParse->nMem+1;
151974    pParse->nMem += nArg;
151975    return regArg;
151976  }
151977  
151978  
151979  /*
151980  ** This function does the work of sqlite3WindowCodeStep() for all "ROWS"
151981  ** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT
151982  ** ROW". Pseudo-code for each follows.
151983  **
151984  ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
151985  **
151986  **     ...
151987  **       if( new partition ){
151988  **         Gosub flush_partition
151989  **       }
151990  **       Insert (record in eph-table)
151991  **     sqlite3WhereEnd()
151992  **     Gosub flush_partition
151993  **  
151994  **   flush_partition:
151995  **     Once {
151996  **       OpenDup (iEphCsr -> csrStart)
151997  **       OpenDup (iEphCsr -> csrEnd)
151998  **     }
151999  **     regStart = <expr1>                // PRECEDING expression
152000  **     regEnd = <expr2>                  // FOLLOWING expression
152001  **     if( regStart<0 || regEnd<0 ){ error! }
152002  **     Rewind (csr,csrStart,csrEnd)      // if EOF goto flush_partition_done
152003  **       Next(csrEnd)                    // if EOF skip Aggstep
152004  **       Aggstep (csrEnd)
152005  **       if( (regEnd--)<=0 ){
152006  **         AggFinal (xValue)
152007  **         Gosub addrGosub
152008  **         Next(csr)                // if EOF goto flush_partition_done
152009  **         if( (regStart--)<=0 ){
152010  **           AggInverse (csrStart)
152011  **           Next(csrStart)
152012  **         }
152013  **       }
152014  **   flush_partition_done:
152015  **     ResetSorter (csr)
152016  **     Return
152017  **
152018  ** ROWS BETWEEN <expr> PRECEDING    AND CURRENT ROW
152019  ** ROWS BETWEEN CURRENT ROW         AND <expr> FOLLOWING
152020  ** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING
152021  **
152022  **   These are similar to the above. For "CURRENT ROW", intialize the
152023  **   register to 0. For "UNBOUNDED PRECEDING" to infinity.
152024  **
152025  ** ROWS BETWEEN <expr> PRECEDING    AND UNBOUNDED FOLLOWING
152026  ** ROWS BETWEEN CURRENT ROW         AND UNBOUNDED FOLLOWING
152027  **
152028  **     Rewind (csr,csrStart,csrEnd)    // if EOF goto flush_partition_done
152029  **     while( 1 ){
152030  **       Next(csrEnd)                  // Exit while(1) at EOF
152031  **       Aggstep (csrEnd)
152032  **     }
152033  **     while( 1 ){
152034  **       AggFinal (xValue)
152035  **       Gosub addrGosub
152036  **       Next(csr)                     // if EOF goto flush_partition_done
152037  **       if( (regStart--)<=0 ){
152038  **         AggInverse (csrStart)
152039  **         Next(csrStart)
152040  **       }
152041  **     }
152042  **
152043  **   For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if() 
152044  **   condition is always true (as if regStart were initialized to 0).
152045  **
152046  ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
152047  ** 
152048  **   This is the only RANGE case handled by this routine. It modifies the
152049  **   second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to
152050  **   be:
152051  **
152052  **     while( 1 ){
152053  **       AggFinal (xValue)
152054  **       while( 1 ){
152055  **         regPeer++
152056  **         Gosub addrGosub
152057  **         Next(csr)                     // if EOF goto flush_partition_done
152058  **         if( new peer ) break;
152059  **       }
152060  **       while( (regPeer--)>0 ){
152061  **         AggInverse (csrStart)
152062  **         Next(csrStart)
152063  **       }
152064  **     }
152065  **
152066  ** ROWS BETWEEN <expr> FOLLOWING    AND <expr> FOLLOWING
152067  **
152068  **   regEnd = regEnd - regStart
152069  **   Rewind (csr,csrStart,csrEnd)   // if EOF goto flush_partition_done
152070  **     Aggstep (csrEnd)
152071  **     Next(csrEnd)                 // if EOF fall-through
152072  **     if( (regEnd--)<=0 ){
152073  **       if( (regStart--)<=0 ){
152074  **         AggFinal (xValue)
152075  **         Gosub addrGosub
152076  **         Next(csr)              // if EOF goto flush_partition_done
152077  **       }
152078  **       AggInverse (csrStart)
152079  **       Next (csrStart)
152080  **     }
152081  **
152082  ** ROWS BETWEEN <expr> PRECEDING    AND <expr> PRECEDING
152083  **
152084  **   Replace the bit after "Rewind" in the above with:
152085  **
152086  **     if( (regEnd--)<=0 ){
152087  **       AggStep (csrEnd)
152088  **       Next (csrEnd)
152089  **     }
152090  **     AggFinal (xValue)
152091  **     Gosub addrGosub
152092  **     Next(csr)                  // if EOF goto flush_partition_done
152093  **     if( (regStart--)<=0 ){
152094  **       AggInverse (csr2)
152095  **       Next (csr2)
152096  **     }
152097  **
152098  */
152099  static void windowCodeRowExprStep(
152100    Parse *pParse, 
152101    Select *p,
152102    WhereInfo *pWInfo,
152103    int regGosub, 
152104    int addrGosub
152105  ){
152106    Window *pMWin = p->pWin;
152107    Vdbe *v = sqlite3GetVdbe(pParse);
152108    int regFlushPart;               /* Register for "Gosub flush_partition" */
152109    int lblFlushPart;               /* Label for "Gosub flush_partition" */
152110    int lblFlushDone;               /* Label for "Gosub flush_partition_done" */
152111  
152112    int regArg;
152113    int addr;
152114    int csrStart = pParse->nTab++;
152115    int csrEnd = pParse->nTab++;
152116    int regStart;                    /* Value of <expr> PRECEDING */
152117    int regEnd;                      /* Value of <expr> FOLLOWING */
152118    int addrGoto;
152119    int addrTop;
152120    int addrIfPos1 = 0;
152121    int addrIfPos2 = 0;
152122    int regSize = 0;
152123  
152124    assert( pMWin->eStart==TK_PRECEDING 
152125         || pMWin->eStart==TK_CURRENT 
152126         || pMWin->eStart==TK_FOLLOWING 
152127         || pMWin->eStart==TK_UNBOUNDED 
152128    );
152129    assert( pMWin->eEnd==TK_FOLLOWING 
152130         || pMWin->eEnd==TK_CURRENT 
152131         || pMWin->eEnd==TK_UNBOUNDED 
152132         || pMWin->eEnd==TK_PRECEDING 
152133    );
152134  
152135    /* Allocate register and label for the "flush_partition" sub-routine. */
152136    regFlushPart = ++pParse->nMem;
152137    lblFlushPart = sqlite3VdbeMakeLabel(pParse);
152138    lblFlushDone = sqlite3VdbeMakeLabel(pParse);
152139  
152140    regStart = ++pParse->nMem;
152141    regEnd = ++pParse->nMem;
152142  
152143    windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
152144  
152145    addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
152146  
152147    /* Start of "flush_partition" */
152148    sqlite3VdbeResolveLabel(v, lblFlushPart);
152149    sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3);
152150    VdbeCoverage(v);
152151    VdbeComment((v, "Flush_partition subroutine"));
152152    sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr);
152153    sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr);
152154  
152155    /* If either regStart or regEnd are not non-negative integers, throw 
152156    ** an exception.  */
152157    if( pMWin->pStart ){
152158      sqlite3ExprCode(pParse, pMWin->pStart, regStart);
152159      windowCheckIntValue(pParse, regStart, 0);
152160    }
152161    if( pMWin->pEnd ){
152162      sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
152163      windowCheckIntValue(pParse, regEnd, 1);
152164    }
152165  
152166    /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do:
152167    **
152168    **   if( regEnd<regStart ){
152169    **     // The frame always consists of 0 rows
152170    **     regStart = regSize;
152171    **   }
152172    **   regEnd = regEnd - regStart;
152173    */
152174    if( pMWin->pEnd && pMWin->eStart==TK_FOLLOWING ){
152175      assert( pMWin->pStart!=0 );
152176      assert( pMWin->eEnd==TK_FOLLOWING );
152177      sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd);
152178      VdbeCoverageNeverNull(v);
152179      sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
152180      sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);
152181    }
152182  
152183    if( pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){
152184      assert( pMWin->pEnd!=0 );
152185      assert( pMWin->eStart==TK_PRECEDING );
152186      sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd);
152187      VdbeCoverageNeverNull(v);
152188      sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
152189      sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd);
152190    }
152191  
152192    /* Initialize the accumulator register for each window function to NULL */
152193    regArg = windowInitAccum(pParse, pMWin);
152194  
152195    sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone);
152196    VdbeCoverage(v);
152197    sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone);
152198    VdbeCoverageNeverTaken(v);
152199    sqlite3VdbeChangeP5(v, 1);
152200    sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone);
152201    VdbeCoverageNeverTaken(v);
152202    sqlite3VdbeChangeP5(v, 1);
152203  
152204    /* Invoke AggStep function for each window function using the row that
152205    ** csrEnd currently points to. Or, if csrEnd is already at EOF,
152206    ** do nothing.  */
152207    addrTop = sqlite3VdbeCurrentAddr(v);
152208    if( pMWin->eEnd==TK_PRECEDING ){
152209      addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
152210      VdbeCoverage(v);
152211    }
152212    sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2);
152213    VdbeCoverage(v);
152214    addr = sqlite3VdbeAddOp0(v, OP_Goto);
152215    windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize);
152216    if( pMWin->eEnd==TK_UNBOUNDED ){
152217      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
152218      sqlite3VdbeJumpHere(v, addr);
152219      addrTop = sqlite3VdbeCurrentAddr(v);
152220    }else{
152221      sqlite3VdbeJumpHere(v, addr);
152222      if( pMWin->eEnd==TK_PRECEDING ){
152223        sqlite3VdbeJumpHere(v, addrIfPos1);
152224      }
152225    }
152226  
152227    if( pMWin->eEnd==TK_FOLLOWING ){
152228      addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
152229      VdbeCoverage(v);
152230    }
152231    if( pMWin->eStart==TK_FOLLOWING ){
152232      addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1);
152233      VdbeCoverage(v);
152234    }
152235    windowAggFinal(pParse, pMWin, 0);
152236    windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
152237    sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2);
152238    VdbeCoverage(v);
152239    sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone);
152240    if( pMWin->eStart==TK_FOLLOWING ){
152241      sqlite3VdbeJumpHere(v, addrIfPos2);
152242    }
152243  
152244    if( pMWin->eStart==TK_CURRENT 
152245     || pMWin->eStart==TK_PRECEDING 
152246     || pMWin->eStart==TK_FOLLOWING 
152247    ){
152248      int lblSkipInverse = sqlite3VdbeMakeLabel(pParse);;
152249      if( pMWin->eStart==TK_PRECEDING ){
152250        sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1);
152251        VdbeCoverage(v);
152252      }
152253      if( pMWin->eStart==TK_FOLLOWING ){
152254        sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2);
152255        VdbeCoverage(v);
152256        sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse);
152257      }else{
152258        sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1);
152259        VdbeCoverageAlwaysTaken(v);
152260      }
152261      windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize);
152262      sqlite3VdbeResolveLabel(v, lblSkipInverse);
152263    }
152264    if( pMWin->eEnd==TK_FOLLOWING ){
152265      sqlite3VdbeJumpHere(v, addrIfPos1);
152266    }
152267    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
152268  
152269    /* flush_partition_done: */
152270    sqlite3VdbeResolveLabel(v, lblFlushDone);
152271    sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
152272    sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
152273    VdbeComment((v, "end flush_partition subroutine"));
152274  
152275    /* Jump to here to skip over flush_partition */
152276    sqlite3VdbeJumpHere(v, addrGoto);
152277  }
152278  
152279  /*
152280  ** This function does the work of sqlite3WindowCodeStep() for cases that
152281  ** would normally be handled by windowCodeDefaultStep() when there are
152282  ** one or more built-in window-functions that require the entire partition
152283  ** to be cached in a temp table before any rows can be returned. Additionally.
152284  ** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by
152285  ** this function.
152286  **
152287  ** Pseudo-code corresponding to the VM code generated by this function
152288  ** for each type of window follows.
152289  **
152290  ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152291  **
152292  **   flush_partition:
152293  **     Once {
152294  **       OpenDup (iEphCsr -> csrLead)
152295  **     }
152296  **     Integer ctr 0
152297  **     foreach row (csrLead){
152298  **       if( new peer ){
152299  **         AggFinal (xValue)
152300  **         for(i=0; i<ctr; i++){
152301  **           Gosub addrGosub
152302  **           Next iEphCsr
152303  **         }
152304  **         Integer ctr 0
152305  **       }
152306  **       AggStep (csrLead)
152307  **       Incr ctr
152308  **     }
152309  **
152310  **     AggFinal (xFinalize)
152311  **     for(i=0; i<ctr; i++){
152312  **       Gosub addrGosub
152313  **       Next iEphCsr
152314  **     }
152315  **
152316  **     ResetSorter (csr)
152317  **     Return
152318  **
152319  ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152320  **
152321  **   As above, except that the "if( new peer )" branch is always taken.
152322  **
152323  ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW 
152324  **
152325  **   As above, except that each of the for() loops becomes:
152326  **
152327  **         for(i=0; i<ctr; i++){
152328  **           Gosub addrGosub
152329  **           AggInverse (iEphCsr)
152330  **           Next iEphCsr
152331  **         }
152332  **
152333  ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
152334  **
152335  **   flush_partition:
152336  **     Once {
152337  **       OpenDup (iEphCsr -> csrLead)
152338  **     }
152339  **     foreach row (csrLead) {
152340  **       AggStep (csrLead)
152341  **     }
152342  **     foreach row (iEphCsr) {
152343  **       Gosub addrGosub
152344  **     }
152345  ** 
152346  ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
152347  **
152348  **   flush_partition:
152349  **     Once {
152350  **       OpenDup (iEphCsr -> csrLead)
152351  **     }
152352  **     foreach row (csrLead){
152353  **       AggStep (csrLead)
152354  **     }
152355  **     Rewind (csrLead)
152356  **     Integer ctr 0
152357  **     foreach row (csrLead){
152358  **       if( new peer ){
152359  **         AggFinal (xValue)
152360  **         for(i=0; i<ctr; i++){
152361  **           Gosub addrGosub
152362  **           AggInverse (iEphCsr)
152363  **           Next iEphCsr
152364  **         }
152365  **         Integer ctr 0
152366  **       }
152367  **       Incr ctr
152368  **     }
152369  **
152370  **     AggFinal (xFinalize)
152371  **     for(i=0; i<ctr; i++){
152372  **       Gosub addrGosub
152373  **       Next iEphCsr
152374  **     }
152375  **
152376  **     ResetSorter (csr)
152377  **     Return
152378  */
152379  static void windowCodeCacheStep(
152380    Parse *pParse, 
152381    Select *p,
152382    WhereInfo *pWInfo,
152383    int regGosub, 
152384    int addrGosub
152385  ){
152386    Window *pMWin = p->pWin;
152387    Vdbe *v = sqlite3GetVdbe(pParse);
152388    int k;
152389    int addr;
152390    ExprList *pPart = pMWin->pPartition;
152391    ExprList *pOrderBy = pMWin->pOrderBy;
152392    int nPeer = pOrderBy ? pOrderBy->nExpr : 0;
152393    int regNewPeer;
152394  
152395    int addrGoto;                   /* Address of Goto used to jump flush_par.. */
152396    int addrNext;                   /* Jump here for next iteration of loop */
152397    int regFlushPart;
152398    int lblFlushPart;
152399    int csrLead;
152400    int regCtr;
152401    int regArg;                     /* Register array to martial function args */
152402    int regSize;
152403    int lblEmpty;
152404    int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT 
152405            && pMWin->eEnd==TK_UNBOUNDED;
152406  
152407    assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT) 
152408         || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED) 
152409         || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT) 
152410         || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED) 
152411    );
152412  
152413    lblEmpty = sqlite3VdbeMakeLabel(pParse);
152414    regNewPeer = pParse->nMem+1;
152415    pParse->nMem += nPeer;
152416  
152417    /* Allocate register and label for the "flush_partition" sub-routine. */
152418    regFlushPart = ++pParse->nMem;
152419    lblFlushPart = sqlite3VdbeMakeLabel(pParse);
152420  
152421    csrLead = pParse->nTab++;
152422    regCtr = ++pParse->nMem;
152423  
152424    windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
152425    addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
152426  
152427    /* Start of "flush_partition" */
152428    sqlite3VdbeResolveLabel(v, lblFlushPart);
152429    sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2);
152430    VdbeCoverage(v);
152431    sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr);
152432  
152433    /* Initialize the accumulator register for each window function to NULL */
152434    regArg = windowInitAccum(pParse, pMWin);
152435  
152436    sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr);
152437    sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
152438    VdbeCoverage(v);
152439    sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty);
152440    VdbeCoverageNeverTaken(v);
152441  
152442    if( bReverse ){
152443      int addr2 = sqlite3VdbeCurrentAddr(v);
152444      windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
152445      sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr2);
152446      VdbeCoverage(v);
152447      sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
152448      VdbeCoverageNeverTaken(v);
152449    }
152450    addrNext = sqlite3VdbeCurrentAddr(v);
152451  
152452    if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){
152453      int bCurrent = (pMWin->eStart==TK_CURRENT);
152454      int addrJump = 0;             /* Address of OP_Jump below */
152455      if( pMWin->eType==TK_RANGE ){
152456        int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
152457        int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0);
152458        KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
152459        for(k=0; k<nPeer; k++){
152460          sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k);
152461        }
152462        addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
152463        sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
152464        addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
152465        VdbeCoverage(v);
152466        sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1);
152467      }
152468  
152469      windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 
152470          (bCurrent ? regArg : 0), (bCurrent ? regSize : 0)
152471      );
152472      if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
152473    }
152474  
152475    if( bReverse==0 ){
152476      windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
152477    }
152478    sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1);
152479    sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext);
152480    VdbeCoverage(v);
152481  
152482    windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0);
152483  
152484    sqlite3VdbeResolveLabel(v, lblEmpty);
152485    sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
152486    sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
152487  
152488    /* Jump to here to skip over flush_partition */
152489    sqlite3VdbeJumpHere(v, addrGoto);
152490  }
152491  
152492  
152493  /*
152494  ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152495  **
152496  **   ...
152497  **     if( new partition ){
152498  **       AggFinal (xFinalize)
152499  **       Gosub addrGosub
152500  **       ResetSorter eph-table
152501  **     }
152502  **     else if( new peer ){
152503  **       AggFinal (xValue)
152504  **       Gosub addrGosub
152505  **       ResetSorter eph-table
152506  **     }
152507  **     AggStep
152508  **     Insert (record into eph-table)
152509  **   sqlite3WhereEnd()
152510  **   AggFinal (xFinalize)
152511  **   Gosub addrGosub
152512  **
152513  ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
152514  **
152515  **   As above, except take no action for a "new peer". Invoke
152516  **   the sub-routine once only for each partition.
152517  **
152518  ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
152519  **
152520  **   As above, except that the "new peer" condition is handled in the
152521  **   same way as "new partition" (so there is no "else if" block).
152522  **
152523  ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152524  ** 
152525  **   As above, except assume every row is a "new peer".
152526  */
152527  static void windowCodeDefaultStep(
152528    Parse *pParse, 
152529    Select *p,
152530    WhereInfo *pWInfo,
152531    int regGosub, 
152532    int addrGosub
152533  ){
152534    Window *pMWin = p->pWin;
152535    Vdbe *v = sqlite3GetVdbe(pParse);
152536    int k;
152537    int iSubCsr = p->pSrc->a[0].iCursor;
152538    int nSub = p->pSrc->a[0].pTab->nCol;
152539    int reg = pParse->nMem+1;
152540    int regRecord = reg+nSub;
152541    int regRowid = regRecord+1;
152542    int addr;
152543    ExprList *pPart = pMWin->pPartition;
152544    ExprList *pOrderBy = pMWin->pOrderBy;
152545  
152546    assert( pMWin->eType==TK_RANGE 
152547        || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
152548    );
152549  
152550    assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
152551         || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
152552         || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
152553         || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy)
152554    );
152555  
152556    if( pMWin->eEnd==TK_UNBOUNDED ){
152557      pOrderBy = 0;
152558    }
152559  
152560    pParse->nMem += nSub + 2;
152561  
152562    /* Load the individual column values of the row returned by
152563    ** the sub-select into an array of registers. */
152564    for(k=0; k<nSub; k++){
152565      sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
152566    }
152567  
152568    /* Check if this is the start of a new partition or peer group. */
152569    if( pPart || pOrderBy ){
152570      int nPart = (pPart ? pPart->nExpr : 0);
152571      int addrGoto = 0;
152572      int addrJump = 0;
152573      int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
152574  
152575      if( pPart ){
152576        int regNewPart = reg + pMWin->nBufferCol;
152577        KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
152578        addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
152579        sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
152580        addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
152581        VdbeCoverageEqNe(v);
152582        windowAggFinal(pParse, pMWin, 1);
152583        if( pOrderBy ){
152584          addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
152585        }
152586      }
152587  
152588      if( pOrderBy ){
152589        int regNewPeer = reg + pMWin->nBufferCol + nPart;
152590        int regPeer = pMWin->regPart + nPart;
152591  
152592        if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
152593        if( pMWin->eType==TK_RANGE ){
152594          KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
152595          addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
152596          sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
152597          addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
152598          VdbeCoverage(v);
152599        }else{
152600          addrJump = 0;
152601        }
152602        windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT);
152603        if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
152604      }
152605  
152606      sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
152607      VdbeCoverage(v);
152608      sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
152609      sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
152610      VdbeCoverage(v);
152611  
152612      sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
152613      sqlite3VdbeAddOp3(
152614          v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1
152615      );
152616  
152617      if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
152618    }
152619  
152620    /* Invoke step function for window functions */
152621    windowAggStep(pParse, pMWin, -1, 0, reg, 0);
152622  
152623    /* Buffer the current row in the ephemeral table. */
152624    if( pMWin->nBufferCol>0 ){
152625      sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord);
152626    }else{
152627      sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord);
152628      sqlite3VdbeAppendP4(v, (void*)"", 0);
152629    }
152630    sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
152631    sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
152632  
152633    /* End the database scan loop. */
152634    sqlite3WhereEnd(pWInfo);
152635  
152636    windowAggFinal(pParse, pMWin, 1);
152637    sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
152638    VdbeCoverage(v);
152639    sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
152640    sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
152641    VdbeCoverage(v);
152642  }
152643  
152644  /*
152645  ** Allocate and return a duplicate of the Window object indicated by the
152646  ** third argument. Set the Window.pOwner field of the new object to
152647  ** pOwner.
152648  */
152649  SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
152650    Window *pNew = 0;
152651    if( ALWAYS(p) ){
152652      pNew = sqlite3DbMallocZero(db, sizeof(Window));
152653      if( pNew ){
152654        pNew->zName = sqlite3DbStrDup(db, p->zName);
152655        pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
152656        pNew->pFunc = p->pFunc;
152657        pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
152658        pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
152659        pNew->eType = p->eType;
152660        pNew->eEnd = p->eEnd;
152661        pNew->eStart = p->eStart;
152662        pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
152663        pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
152664        pNew->pOwner = pOwner;
152665      }
152666    }
152667    return pNew;
152668  }
152669  
152670  /*
152671  ** Return a copy of the linked list of Window objects passed as the
152672  ** second argument.
152673  */
152674  SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
152675    Window *pWin;
152676    Window *pRet = 0;
152677    Window **pp = &pRet;
152678  
152679    for(pWin=p; pWin; pWin=pWin->pNextWin){
152680      *pp = sqlite3WindowDup(db, 0, pWin);
152681      if( *pp==0 ) break;
152682      pp = &((*pp)->pNextWin);
152683    }
152684  
152685    return pRet;
152686  }
152687  
152688  /*
152689  ** sqlite3WhereBegin() has already been called for the SELECT statement 
152690  ** passed as the second argument when this function is invoked. It generates
152691  ** code to populate the Window.regResult register for each window function and
152692  ** invoke the sub-routine at instruction addrGosub once for each row.
152693  ** This function calls sqlite3WhereEnd() before returning. 
152694  */
152695  SQLITE_PRIVATE void sqlite3WindowCodeStep(
152696    Parse *pParse,                  /* Parse context */
152697    Select *p,                      /* Rewritten SELECT statement */
152698    WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */
152699    int regGosub,                   /* Register for OP_Gosub */
152700    int addrGosub                   /* OP_Gosub here to return each row */
152701  ){
152702    Window *pMWin = p->pWin;
152703  
152704    /* There are three different functions that may be used to do the work
152705    ** of this one, depending on the window frame and the specific built-in
152706    ** window functions used (if any).
152707    **
152708    ** windowCodeRowExprStep() handles all "ROWS" window frames, except for:
152709    **
152710    **   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152711    **
152712    ** The exception is because windowCodeRowExprStep() implements all window
152713    ** frame types by caching the entire partition in a temp table, and
152714    ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to
152715    ** implement without such a cache.
152716    **
152717    ** windowCodeCacheStep() is used for:
152718    **
152719    **   RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
152720    **
152721    ** It is also used for anything not handled by windowCodeRowExprStep() 
152722    ** that invokes a built-in window function that requires the entire 
152723    ** partition to be cached in a temp table before any rows are returned
152724    ** (e.g. nth_value() or percent_rank()).
152725    **
152726    ** Finally, assuming there is no built-in window function that requires
152727    ** the partition to be cached, windowCodeDefaultStep() is used for:
152728    **
152729    **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
152730    **   RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
152731    **   RANGE BETWEEN CURRENT ROW AND CURRENT ROW 
152732    **   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152733    **
152734    ** windowCodeDefaultStep() is the only one of the three functions that
152735    ** does not cache each partition in a temp table before beginning to
152736    ** return rows.
152737    */
152738    if( pMWin->eType==TK_ROWS 
152739     && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy)
152740    ){
152741      VdbeModuleComment((pParse->pVdbe, "Begin RowExprStep()"));
152742      windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub);
152743    }else{
152744      Window *pWin;
152745      int bCache = 0;               /* True to use CacheStep() */
152746  
152747      if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){
152748        bCache = 1;
152749      }else{
152750        for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
152751          FuncDef *pFunc = pWin->pFunc;
152752          if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE)
152753           || (pFunc->zName==nth_valueName)
152754           || (pFunc->zName==first_valueName)
152755           || (pFunc->zName==leadName)
152756           || (pFunc->zName==lagName)
152757          ){
152758            bCache = 1;
152759            break;
152760          }
152761        }
152762      }
152763  
152764      /* Otherwise, call windowCodeDefaultStep().  */
152765      if( bCache ){
152766        VdbeModuleComment((pParse->pVdbe, "Begin CacheStep()"));
152767        windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub);
152768      }else{
152769        VdbeModuleComment((pParse->pVdbe, "Begin DefaultStep()"));
152770        windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub);
152771      }
152772    }
152773  }
152774  
152775  #endif /* SQLITE_OMIT_WINDOWFUNC */
152776  
152777  /************** End of window.c **********************************************/
152778  /************** Begin file parse.c *******************************************/
152779  /*
152780  ** 2000-05-29
152781  **
152782  ** The author disclaims copyright to this source code.  In place of
152783  ** a legal notice, here is a blessing:
152784  **
152785  **    May you do good and not evil.
152786  **    May you find forgiveness for yourself and forgive others.
152787  **    May you share freely, never taking more than you give.
152788  **
152789  *************************************************************************
152790  ** Driver template for the LEMON parser generator.
152791  **
152792  ** The "lemon" program processes an LALR(1) input grammar file, then uses
152793  ** this template to construct a parser.  The "lemon" program inserts text
152794  ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
152795  ** interstitial "-" characters) contained in this template is changed into
152796  ** the value of the %name directive from the grammar.  Otherwise, the content
152797  ** of this template is copied straight through into the generate parser
152798  ** source file.
152799  **
152800  ** The following is the concatenation of all %include directives from the
152801  ** input grammar file:
152802  */
152803  /* #include <stdio.h> */
152804  /* #include <assert.h> */
152805  /************ Begin %include sections from the grammar ************************/
152806  
152807  /* #include "sqliteInt.h" */
152808  
152809  /*
152810  ** Disable all error recovery processing in the parser push-down
152811  ** automaton.
152812  */
152813  #define YYNOERRORRECOVERY 1
152814  
152815  /*
152816  ** Make yytestcase() the same as testcase()
152817  */
152818  #define yytestcase(X) testcase(X)
152819  
152820  /*
152821  ** Indicate that sqlite3ParserFree() will never be called with a null
152822  ** pointer.
152823  */
152824  #define YYPARSEFREENEVERNULL 1
152825  
152826  /*
152827  ** In the amalgamation, the parse.c file generated by lemon and the
152828  ** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
152829  ** has access to the the size of the yyParser object and so the parser
152830  ** engine can be allocated from stack.  In that case, only the
152831  ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
152832  ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
152833  ** omitted.
152834  */
152835  #ifdef SQLITE_AMALGAMATION
152836  # define sqlite3Parser_ENGINEALWAYSONSTACK 1
152837  #endif
152838  
152839  /*
152840  ** Alternative datatype for the argument to the malloc() routine passed
152841  ** into sqlite3ParserAlloc().  The default is size_t.
152842  */
152843  #define YYMALLOCARGTYPE  u64
152844  
152845  /*
152846  ** An instance of the following structure describes the event of a
152847  ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
152848  ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
152849  **
152850  **      UPDATE ON (a,b,c)
152851  **
152852  ** Then the "b" IdList records the list "a,b,c".
152853  */
152854  struct TrigEvent { int a; IdList * b; };
152855  
152856  struct FrameBound     { int eType; Expr *pExpr; };
152857  
152858  /*
152859  ** Disable lookaside memory allocation for objects that might be
152860  ** shared across database connections.
152861  */
152862  static void disableLookaside(Parse *pParse){
152863    pParse->disableLookaside++;
152864    pParse->db->lookaside.bDisable++;
152865  }
152866  
152867  
152868    /*
152869    ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
152870    ** all elements in the list.  And make sure list length does not exceed
152871    ** SQLITE_LIMIT_COMPOUND_SELECT.
152872    */
152873    static void parserDoubleLinkSelect(Parse *pParse, Select *p){
152874      if( p->pPrior ){
152875        Select *pNext = 0, *pLoop;
152876        int mxSelect, cnt = 0;
152877        for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
152878          pLoop->pNext = pNext;
152879          pLoop->selFlags |= SF_Compound;
152880        }
152881        if( (p->selFlags & SF_MultiValue)==0 && 
152882          (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
152883          cnt>mxSelect
152884        ){
152885          sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
152886        }
152887      }
152888    }
152889  
152890  
152891    /* Construct a new Expr object from a single identifier.  Use the
152892    ** new Expr to populate pOut.  Set the span of pOut to be the identifier
152893    ** that created the expression.
152894    */
152895    static Expr *tokenExpr(Parse *pParse, int op, Token t){
152896      Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
152897      if( p ){
152898        /* memset(p, 0, sizeof(Expr)); */
152899        p->op = (u8)op;
152900        p->affinity = 0;
152901        p->flags = EP_Leaf;
152902        p->iAgg = -1;
152903        p->pLeft = p->pRight = 0;
152904        p->x.pList = 0;
152905        p->pAggInfo = 0;
152906        p->y.pTab = 0;
152907        p->op2 = 0;
152908        p->iTable = 0;
152909        p->iColumn = 0;
152910        p->u.zToken = (char*)&p[1];
152911        memcpy(p->u.zToken, t.z, t.n);
152912        p->u.zToken[t.n] = 0;
152913        if( sqlite3Isquote(p->u.zToken[0]) ){
152914          sqlite3DequoteExpr(p);
152915        }
152916  #if SQLITE_MAX_EXPR_DEPTH>0
152917        p->nHeight = 1;
152918  #endif  
152919        if( IN_RENAME_OBJECT ){
152920          return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
152921        }
152922      }
152923      return p;
152924    }
152925  
152926  
152927    /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
152928    ** unary TK_ISNULL or TK_NOTNULL expression. */
152929    static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
152930      sqlite3 *db = pParse->db;
152931      if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
152932        pA->op = (u8)op;
152933        sqlite3ExprDelete(db, pA->pRight);
152934        pA->pRight = 0;
152935      }
152936    }
152937  
152938    /* Add a single new term to an ExprList that is used to store a
152939    ** list of identifiers.  Report an error if the ID list contains
152940    ** a COLLATE clause or an ASC or DESC keyword, except ignore the
152941    ** error while parsing a legacy schema.
152942    */
152943    static ExprList *parserAddExprIdListTerm(
152944      Parse *pParse,
152945      ExprList *pPrior,
152946      Token *pIdToken,
152947      int hasCollate,
152948      int sortOrder
152949    ){
152950      ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
152951      if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
152952          && pParse->db->init.busy==0
152953      ){
152954        sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
152955                           pIdToken->n, pIdToken->z);
152956      }
152957      sqlite3ExprListSetName(pParse, p, pIdToken, 1);
152958      return p;
152959    }
152960  /**************** End of %include directives **********************************/
152961  /* These constants specify the various numeric values for terminal symbols
152962  ** in a format understandable to "makeheaders".  This section is blank unless
152963  ** "lemon" is run with the "-m" command-line option.
152964  ***************** Begin makeheaders token definitions *************************/
152965  /**************** End makeheaders token definitions ***************************/
152966  
152967  /* The next sections is a series of control #defines.
152968  ** various aspects of the generated parser.
152969  **    YYCODETYPE         is the data type used to store the integer codes
152970  **                       that represent terminal and non-terminal symbols.
152971  **                       "unsigned char" is used if there are fewer than
152972  **                       256 symbols.  Larger types otherwise.
152973  **    YYNOCODE           is a number of type YYCODETYPE that is not used for
152974  **                       any terminal or nonterminal symbol.
152975  **    YYFALLBACK         If defined, this indicates that one or more tokens
152976  **                       (also known as: "terminal symbols") have fall-back
152977  **                       values which should be used if the original symbol
152978  **                       would not parse.  This permits keywords to sometimes
152979  **                       be used as identifiers, for example.
152980  **    YYACTIONTYPE       is the data type used for "action codes" - numbers
152981  **                       that indicate what to do in response to the next
152982  **                       token.
152983  **    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
152984  **                       symbols.  Background: A "minor type" is a semantic
152985  **                       value associated with a terminal or non-terminal
152986  **                       symbols.  For example, for an "ID" terminal symbol,
152987  **                       the minor type might be the name of the identifier.
152988  **                       Each non-terminal can have a different minor type.
152989  **                       Terminal symbols all have the same minor type, though.
152990  **                       This macros defines the minor type for terminal 
152991  **                       symbols.
152992  **    YYMINORTYPE        is the data type used for all minor types.
152993  **                       This is typically a union of many types, one of
152994  **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
152995  **                       for terminal symbols is called "yy0".
152996  **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
152997  **                       zero the stack is dynamically sized using realloc()
152998  **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
152999  **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
153000  **    sqlite3ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter
153001  **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
153002  **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
153003  **    sqlite3ParserCTX_*         As sqlite3ParserARG_ except for %extra_context
153004  **    YYERRORSYMBOL      is the code number of the error symbol.  If not
153005  **                       defined, then do no error processing.
153006  **    YYNSTATE           the combined number of states.
153007  **    YYNRULE            the number of rules in the grammar
153008  **    YYNTOKEN           Number of terminal symbols
153009  **    YY_MAX_SHIFT       Maximum value for shift actions
153010  **    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
153011  **    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
153012  **    YY_ERROR_ACTION    The yy_action[] code for syntax error
153013  **    YY_ACCEPT_ACTION   The yy_action[] code for accept
153014  **    YY_NO_ACTION       The yy_action[] code for no-op
153015  **    YY_MIN_REDUCE      Minimum value for reduce actions
153016  **    YY_MAX_REDUCE      Maximum value for reduce actions
153017  */
153018  #ifndef INTERFACE
153019  # define INTERFACE 1
153020  #endif
153021  /************* Begin control #defines *****************************************/
153022  #define YYCODETYPE unsigned short int
153023  #define YYNOCODE 278
153024  #define YYACTIONTYPE unsigned short int
153025  #define YYWILDCARD 91
153026  #define sqlite3ParserTOKENTYPE Token
153027  typedef union {
153028    int yyinit;
153029    sqlite3ParserTOKENTYPE yy0;
153030    ExprList* yy42;
153031    int yy96;
153032    TriggerStep* yy119;
153033    Window* yy147;
153034    SrcList* yy167;
153035    Upsert* yy266;
153036    struct FrameBound yy317;
153037    IdList* yy336;
153038    struct TrigEvent yy350;
153039    struct {int value; int mask;} yy367;
153040    Select* yy423;
153041    const char* yy464;
153042    Expr* yy490;
153043    With* yy499;
153044  } YYMINORTYPE;
153045  #ifndef YYSTACKDEPTH
153046  #define YYSTACKDEPTH 100
153047  #endif
153048  #define sqlite3ParserARG_SDECL
153049  #define sqlite3ParserARG_PDECL
153050  #define sqlite3ParserARG_PARAM
153051  #define sqlite3ParserARG_FETCH
153052  #define sqlite3ParserARG_STORE
153053  #define sqlite3ParserCTX_SDECL Parse *pParse;
153054  #define sqlite3ParserCTX_PDECL ,Parse *pParse
153055  #define sqlite3ParserCTX_PARAM ,pParse
153056  #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
153057  #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
153058  #define YYFALLBACK 1
153059  #define YYNSTATE             524
153060  #define YYNRULE              369
153061  #define YYNTOKEN             155
153062  #define YY_MAX_SHIFT         523
153063  #define YY_MIN_SHIFTREDUCE   760
153064  #define YY_MAX_SHIFTREDUCE   1128
153065  #define YY_ERROR_ACTION      1129
153066  #define YY_ACCEPT_ACTION     1130
153067  #define YY_NO_ACTION         1131
153068  #define YY_MIN_REDUCE        1132
153069  #define YY_MAX_REDUCE        1500
153070  /************* End control #defines *******************************************/
153071  #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
153072  
153073  /* Define the yytestcase() macro to be a no-op if is not already defined
153074  ** otherwise.
153075  **
153076  ** Applications can choose to define yytestcase() in the %include section
153077  ** to a macro that can assist in verifying code coverage.  For production
153078  ** code the yytestcase() macro should be turned off.  But it is useful
153079  ** for testing.
153080  */
153081  #ifndef yytestcase
153082  # define yytestcase(X)
153083  #endif
153084  
153085  
153086  /* Next are the tables used to determine what action to take based on the
153087  ** current state and lookahead token.  These tables are used to implement
153088  ** functions that take a state number and lookahead value and return an
153089  ** action integer.  
153090  **
153091  ** Suppose the action integer is N.  Then the action is determined as
153092  ** follows
153093  **
153094  **   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
153095  **                                      token onto the stack and goto state N.
153096  **
153097  **   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
153098  **     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
153099  **
153100  **   N == YY_ERROR_ACTION               A syntax error has occurred.
153101  **
153102  **   N == YY_ACCEPT_ACTION              The parser accepts its input.
153103  **
153104  **   N == YY_NO_ACTION                  No such action.  Denotes unused
153105  **                                      slots in the yy_action[] table.
153106  **
153107  **   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
153108  **     and YY_MAX_REDUCE
153109  **
153110  ** The action table is constructed as a single large table named yy_action[].
153111  ** Given state S and lookahead X, the action is computed as either:
153112  **
153113  **    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
153114  **    (B)   N = yy_default[S]
153115  **
153116  ** The (A) formula is preferred.  The B formula is used instead if
153117  ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
153118  **
153119  ** The formulas above are for computing the action when the lookahead is
153120  ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
153121  ** a reduce action) then the yy_reduce_ofst[] array is used in place of
153122  ** the yy_shift_ofst[] array.
153123  **
153124  ** The following are the tables generated in this section:
153125  **
153126  **  yy_action[]        A single table containing all actions.
153127  **  yy_lookahead[]     A table containing the lookahead for each entry in
153128  **                     yy_action.  Used to detect hash collisions.
153129  **  yy_shift_ofst[]    For each state, the offset into yy_action for
153130  **                     shifting terminals.
153131  **  yy_reduce_ofst[]   For each state, the offset into yy_action for
153132  **                     shifting non-terminals after a reduce.
153133  **  yy_default[]       Default action for each state.
153134  **
153135  *********** Begin parsing tables **********************************************/
153136  #define YY_ACTTAB_COUNT (2009)
153137  static const YYACTIONTYPE yy_action[] = {
153138   /*     0 */   377,  518,  371,  107,  104,  200, 1293,  518, 1130,    1,
153139   /*    10 */     1,  523,    2, 1134,  518, 1203, 1203, 1262,  277,  373,
153140   /*    20 */   129,  495,   37,   37, 1397, 1201, 1201, 1211,   65,   65,
153141   /*    30 */   480,  891,  107,  104,  200,   37,   37, 1043, 1494,  892,
153142   /*    40 */   346, 1494,  342,  114,  115,  105, 1106, 1106,  957,  960,
153143   /*    50 */   950,  950,  112,  112,  113,  113,  113,  113,  285,  254,
153144   /*    60 */   254,  518,  254,  254,  500,  518,  495,  518,  107,  104,
153145   /*    70 */   200, 1085,  515,  481,  386,  515, 1464,  442,  501,  230,
153146   /*    80 */   197,  439,   37,   37, 1172,  210,   65,   65,   65,   65,
153147   /*    90 */   254,  254,  111,  111,  111,  111,  110,  110,  109,  109,
153148   /*   100 */   109,  108,  404,  515,  404,  155, 1041,  431,  401,  400,
153149   /*   110 */   254,  254,  373, 1431, 1427,  408, 1110, 1085, 1086, 1087,
153150   /*   120 */   284, 1112,  500,  515,  500,  368, 1433, 1421, 1428, 1111,
153151   /*   130 */  1261,  499,  373,  502,  108,  404,  114,  115,  105, 1106,
153152   /*   140 */  1106,  957,  960,  950,  950,  112,  112,  113,  113,  113,
153153   /*   150 */   113,  276,  509, 1113,  369, 1113,  114,  115,  105, 1106,
153154   /*   160 */  1106,  957,  960,  950,  950,  112,  112,  113,  113,  113,
153155   /*   170 */   113,  496, 1420, 1431,  493, 1468, 1065,  260, 1063,  433,
153156   /*   180 */    74,  107,  104,  200,  498,  111,  111,  111,  111,  110,
153157   /*   190 */   110,  109,  109,  109,  108,  404,  373,  113,  113,  113,
153158   /*   200 */   113,  106,  131,   91, 1361,  111,  111,  111,  111,  110,
153159   /*   210 */   110,  109,  109,  109,  108,  404,  113,  113,  113,  113,
153160   /*   220 */   114,  115,  105, 1106, 1106,  957,  960,  950,  950,  112,
153161   /*   230 */   112,  113,  113,  113,  113,  111,  111,  111,  111,  110,
153162   /*   240 */   110,  109,  109,  109,  108,  404,  116,  110,  110,  109,
153163   /*   250 */   109,  109,  108,  404,  111,  111,  111,  111,  110,  110,
153164   /*   260 */   109,  109,  109,  108,  404,  917,  512,  512,  512,  111,
153165   /*   270 */   111,  111,  111,  110,  110,  109,  109,  109,  108,  404,
153166   /*   280 */   517, 1198, 1177,  181,  109,  109,  109,  108,  404,  373,
153167   /*   290 */  1198,  402,  402,  402,   75,  360,  111,  111,  111,  111,
153168   /*   300 */   110,  110,  109,  109,  109,  108,  404,  382,  299,  419,
153169   /*   310 */   287,  170,  518,  114,  115,  105, 1106, 1106,  957,  960,
153170   /*   320 */   950,  950,  112,  112,  113,  113,  113,  113, 1444,  523,
153171   /*   330 */     2, 1134,  518,   13,   13,  337,  277, 1085,  129,  226,
153172   /*   340 */   937, 1058, 1000,  471,  917, 1211,  453,  384, 1085,  395,
153173   /*   350 */   162, 1057,  155,   45,   45,  416,  928,  401,  400,  479,
153174   /*   360 */   927,   12,  111,  111,  111,  111,  110,  110,  109,  109,
153175   /*   370 */   109,  108,  404,  226,  286,  254,  254,  254,  254,  518,
153176   /*   380 */    16,   16,  373, 1085, 1086, 1087,  314,  299,  515,  472,
153177   /*   390 */   515,  927,  927,  929, 1085, 1086, 1087,  378,  276,  509,
153178   /*   400 */    65,   65, 1113,  210, 1113, 1085,  114,  115,  105, 1106,
153179   /*   410 */  1106,  957,  960,  950,  950,  112,  112,  113,  113,  113,
153180   /*   420 */   113, 1448,  222, 1134, 1089,  461,  458,  457,  277,  180,
153181   /*   430 */   129,  378,  392,  408,  423,  456,  500, 1211,  240,  257,
153182   /*   440 */   324,  464,  319,  463,  227,  470,   12,  317,  424,  300,
153183   /*   450 */   317, 1085, 1086, 1087,  485,  111,  111,  111,  111,  110,
153184   /*   460 */   110,  109,  109,  109,  108,  404,  181,  118, 1085,  254,
153185   /*   470 */   254, 1089,  518,   90,  351,  373,  518, 1181,  365,  798,
153186   /*   480 */  1440,  339,  515,  248,  248,   77,  325,  133, 1085,  249,
153187   /*   490 */   424,  300,  794,   49,   49,  210,  515,   65,   65,  114,
153188   /*   500 */   115,  105, 1106, 1106,  957,  960,  950,  950,  112,  112,
153189   /*   510 */   113,  113,  113,  113, 1085, 1086, 1087,  222, 1085,  438,
153190   /*   520 */   461,  458,  457,  937,  787,  408,  171,  857,  362, 1021,
153191   /*   530 */   456,  136,  198,  486, 1085, 1086, 1087,  448,  794,  928,
153192   /*   540 */     5,  193,  192,  927, 1022,  107,  104,  200,  111,  111,
153193   /*   550 */   111,  111,  110,  110,  109,  109,  109,  108,  404, 1023,
153194   /*   560 */   254,  254,  803, 1085, 1085, 1086, 1087,  437,  373, 1085,
153195   /*   570 */   344,  787,  791,  515,  927,  927,  929, 1085, 1408, 1396,
153196   /*   580 */   832, 1085,  176,    3,  852, 1085,  518, 1439,  429,  851,
153197   /*   590 */   833,  518,  114,  115,  105, 1106, 1106,  957,  960,  950,
153198   /*   600 */   950,  112,  112,  113,  113,  113,  113,   13,   13, 1085,
153199   /*   610 */  1086, 1087,   13,   13,  518, 1085, 1086, 1087, 1496,  358,
153200   /*   620 */  1085,  389, 1234, 1085, 1086, 1087,  391, 1085, 1086, 1087,
153201   /*   630 */   448, 1085, 1086, 1087,  518,   65,   65,  947,  947,  958,
153202   /*   640 */   961,  111,  111,  111,  111,  110,  110,  109,  109,  109,
153203   /*   650 */   108,  404,  518,  382,  878,   13,   13,  518,  877,  518,
153204   /*   660 */   263,  373,  518,  431,  448, 1070, 1085, 1086, 1087,  267,
153205   /*   670 */   448,  488, 1360,   64,   64,  431,  812,  155,   50,   50,
153206   /*   680 */    65,   65,  518,   65,   65,  114,  115,  105, 1106, 1106,
153207   /*   690 */   957,  960,  950,  950,  112,  112,  113,  113,  113,  113,
153208   /*   700 */   518,  951,  382,   13,   13,  415,  411,  462,  414, 1085,
153209   /*   710 */  1366,  777, 1210,  292,  297,  813,  399,  497,  181,  403,
153210   /*   720 */   261,   15,   15,  276,  509,  414,  413, 1366, 1368,  410,
153211   /*   730 */   372,  345, 1209,  264,  111,  111,  111,  111,  110,  110,
153212   /*   740 */   109,  109,  109,  108,  404,  265,  254,  254,  229, 1405,
153213   /*   750 */   268, 1215,  268, 1103,  373, 1085, 1086, 1087,  938,  515,
153214   /*   760 */   393,  409,  876,  515,  254,  254, 1152,  482,  473,  262,
153215   /*   770 */   422,  476,  325,  503,  289,  518,  291,  515,  114,  115,
153216   /*   780 */   105, 1106, 1106,  957,  960,  950,  950,  112,  112,  113,
153217   /*   790 */   113,  113,  113,  414, 1021, 1366,   39,   39,  254,  254,
153218   /*   800 */   254,  254,  980,  254,  254,  254,  254,  255,  255, 1022,
153219   /*   810 */   279,  515,  516,  515,  846,  846,  515,  138,  515,  518,
153220   /*   820 */   515, 1043, 1495,  251, 1023, 1495,  876,  111,  111,  111,
153221   /*   830 */   111,  110,  110,  109,  109,  109,  108,  404,  518, 1353,
153222   /*   840 */    51,   51,  518,  199,  518,  506,  290,  373,  518,  276,
153223   /*   850 */   509,  922,    9,  483,  233, 1005, 1005,  445,  189,   52,
153224   /*   860 */    52,  325,  280,   53,   53,   54,   54,  373,  876,   55,
153225   /*   870 */    55,  114,  115,  105, 1106, 1106,  957,  960,  950,  950,
153226   /*   880 */   112,  112,  113,  113,  113,  113,   97,  518,   95, 1104,
153227   /*   890 */  1041,  114,  115,  105, 1106, 1106,  957,  960,  950,  950,
153228   /*   900 */   112,  112,  113,  113,  113,  113,  135,  199,   56,   56,
153229   /*   910 */   765,  766,  767,  225,  224,  223,  518,  283,  437,  233,
153230   /*   920 */   111,  111,  111,  111,  110,  110,  109,  109,  109,  108,
153231   /*   930 */   404, 1002,  876,  326,  518, 1002, 1104,   40,   40,  518,
153232   /*   940 */   111,  111,  111,  111,  110,  110,  109,  109,  109,  108,
153233   /*   950 */   404,  518,  448,  518, 1104,   41,   41,  518,   17,  518,
153234   /*   960 */    43,   43, 1155,  379,  518,  448,  518,  443,  518,  390,
153235   /*   970 */   518,  194,   44,   44,   57,   57, 1247,  518,   58,   58,
153236   /*   980 */    59,   59,  518,  466,  326,   14,   14,   60,   60,  120,
153237   /*   990 */   120,   61,   61,  449, 1206,   93,  518,  425,   46,   46,
153238   /*  1000 */   518, 1104,  518,   62,   62,  518,  437,  305,  518,  852,
153239   /*  1010 */   518,  298,  518, 1246,  851,  373,  518,   63,   63, 1293,
153240   /*  1020 */   397,   47,   47,  142,  142, 1467,  143,  143,  821,   70,
153241   /*  1030 */    70,   48,   48,   66,   66,  373,  518,  121,  121,  114,
153242   /*  1040 */   115,  105, 1106, 1106,  957,  960,  950,  950,  112,  112,
153243   /*  1050 */   113,  113,  113,  113,  518,  418,  518,   67,   67,  114,
153244   /*  1060 */   115,  105, 1106, 1106,  957,  960,  950,  950,  112,  112,
153245   /*  1070 */   113,  113,  113,  113,  312,  122,  122,  123,  123, 1293,
153246   /*  1080 */   518,  357, 1126,   88,  518,  435,  325,  387,  111,  111,
153247   /*  1090 */   111,  111,  110,  110,  109,  109,  109,  108,  404,  266,
153248   /*  1100 */   518,  119,  119,  518, 1293,  141,  141,  518,  111,  111,
153249   /*  1110 */   111,  111,  110,  110,  109,  109,  109,  108,  404,  518,
153250   /*  1120 */   801,  140,  140,  518,  127,  127,  511,  379,  126,  126,
153251   /*  1130 */   518,  137,  518, 1308,  518,  307,  518,  310,  518,  203,
153252   /*  1140 */   124,  124, 1307,   96,  125,  125,  207,  388, 1441,  468,
153253   /*  1150 */  1127,   69,   69,   71,   71,   68,   68,   38,   38,   42,
153254   /*  1160 */    42,  357, 1042,  373, 1293,  276,  509,  801,  185,  469,
153255   /*  1170 */   494,  436,  444,    6,  380,  156,  253,  197,  469,  134,
153256   /*  1180 */   426,   33, 1038,  373, 1121,  359, 1411,  114,  115,  105,
153257   /*  1190 */  1106, 1106,  957,  960,  950,  950,  112,  112,  113,  113,
153258   /*  1200 */   113,  113,  914,  296,   27,  293,   90,  114,  103,  105,
153259   /*  1210 */  1106, 1106,  957,  960,  950,  950,  112,  112,  113,  113,
153260   /*  1220 */   113,  113,  919,  275,  430,  232,  891,  232,  432,  256,
153261   /*  1230 */  1127,  232,  398,  370,  892,   28,  111,  111,  111,  111,
153262   /*  1240 */   110,  110,  109,  109,  109,  108,  404,  301,  454, 1385,
153263   /*  1250 */    90,  228,  209,  987,  811,  810,  111,  111,  111,  111,
153264   /*  1260 */   110,  110,  109,  109,  109,  108,  404,  315,  818,  819,
153265   /*  1270 */    90,  323,  983,  931,  885,  228,  373,  232,  999,  849,
153266   /*  1280 */   999,  322,  102,  998, 1384,  998,  785,  850,  440,  132,
153267   /*  1290 */   102,  302, 1243,  306,  309,  311,  373,  313, 1194, 1180,
153268   /*  1300 */   987,  115,  105, 1106, 1106,  957,  960,  950,  950,  112,
153269   /*  1310 */   112,  113,  113,  113,  113, 1178, 1179,  318,  327,  328,
153270   /*  1320 */   931, 1255,  105, 1106, 1106,  957,  960,  950,  950,  112,
153271   /*  1330 */   112,  113,  113,  113,  113, 1292, 1230, 1457,  273, 1241,
153272   /*  1340 */   504,  505, 1298,  100,  510,  246,    4, 1161, 1154,  111,
153273   /*  1350 */   111,  111,  111,  110,  110,  109,  109,  109,  108,  404,
153274   /*  1360 */   513, 1143,  187, 1142,  202, 1144, 1451,  356, 1227,  111,
153275   /*  1370 */   111,  111,  111,  110,  110,  109,  109,  109,  108,  404,
153276   /*  1380 */    11, 1277,  330,  405,  332,  334,  191, 1285,  364,  195,
153277   /*  1390 */   295,  417,  288,  100,  510,  507,    4,  434,  459,  321,
153278   /*  1400 */  1177,  349, 1357, 1356,  336,  155,  190, 1454, 1121,  158,
153279   /*  1410 */   513,  508,  235, 1404,  937, 1402, 1118,  381,   77,  428,
153280   /*  1420 */    98,   98,    8, 1282,  168,   30,  152,   99,  160,  405,
153281   /*  1430 */   520,  519,   88,  405,  927, 1362, 1274,  420,  163,   73,
153282   /*  1440 */   164,   76,  165,  166,  421,  507,  452,  212,  361,  363,
153283   /*  1450 */   427,  276,  509,   31, 1288,  172,  491,  441,  216, 1351,
153284   /*  1460 */    82,  490,  447, 1373,  937,  927,  927,  929,  930,   24,
153285   /*  1470 */    98,   98,  304,  247,  218,  177,  308,   99,  219,  405,
153286   /*  1480 */   520,  519,  450, 1145,  927,  220,  366, 1197,  100,  510,
153287   /*  1490 */   465,    4, 1188, 1196, 1195,  394,  803, 1169, 1187,  367,
153288   /*  1500 */  1168,  396,  484,  320, 1167,  513, 1466,   87,  475,  100,
153289   /*  1510 */   510,  271,    4,  272,  478,  927,  927,  929,  930,   24,
153290   /*  1520 */  1443, 1074,  407, 1238, 1239,  258,  513,  329,  405,  331,
153291   /*  1530 */   355,  355,  354,  243,  352,  234,  489,  774,  498,  184,
153292   /*  1540 */   507,  338, 1422,  339,  117, 1220,   10,  341,  333,  405,
153293   /*  1550 */   204,  491,  282, 1219, 1237, 1236,  492,  335,  343,  937,
153294   /*  1560 */   281,  507,   94, 1337,  186,   98,   98,  347,   89,  487,
153295   /*  1570 */   348,  241,   99,   29,  405,  520,  519,  274, 1151,  927,
153296   /*  1580 */   937,  521, 1080,  245,  242,  244,   98,   98,  856,  522,
153297   /*  1590 */   206, 1140, 1135,   99,  144,  405,  520,  519,  147,  375,
153298   /*  1600 */   927,  149,  376,  157, 1389, 1390, 1388, 1387,  205,  145,
153299   /*  1610 */   927,  927,  929,  930,   24,  146,  130,  761, 1165, 1164,
153300   /*  1620 */    72,  100,  510, 1162,    4,  269,  406,  188,  278,  201,
153301   /*  1630 */   259,  927,  927,  929,  930,   24,  128,  911,  513,  997,
153302   /*  1640 */   995,  159,  374,  208,  148,  161,  835,  276,  509,  211,
153303   /*  1650 */   294, 1011,  915,  167,  150,  383,  169,   78,  385,   79,
153304   /*  1660 */    80,  405,   81,  151, 1014,  213,  214, 1010,  139,   18,
153305   /*  1670 */   412,  215,  303,  507,  232, 1115, 1003,  446,  173,  217,
153306   /*  1680 */   174,   32,  776,  451,  491,  322,  221,  175,  814,  490,
153307   /*  1690 */    83,  455,  937,   19,  460,  316,   20,   84,   98,   98,
153308   /*  1700 */   270,  182,   85,  467,  153,   99,  154,  405,  520,  519,
153309   /*  1710 */  1074,  407,  927,  183,  258,  963, 1046,   86,   34,  355,
153310   /*  1720 */   355,  354,  243,  352,  474, 1047,  774,   35,  477,  196,
153311   /*  1730 */   250,  100,  510,  252,    4,  884,  178,  231, 1060,  204,
153312   /*  1740 */    21,  282,  102,  927,  927,  929,  930,   24,  513,  281,
153313   /*  1750 */   879,   22, 1064, 1062, 1051,    7,  340,   23,  978,  179,
153314   /*  1760 */    90,   92,  510,  964,    4,  236,  962,  966, 1020, 1019,
153315   /*  1770 */   237,  405,  967,   25,   36,  514,  932,  786,  513,  206,
153316   /*  1780 */   101,   26,  845,  507,  238,  239, 1459,  147,  350, 1458,
153317   /*  1790 */   149,  353, 1075, 1131, 1131, 1131, 1131,  205, 1131, 1131,
153318   /*  1800 */  1131,  405,  937, 1131, 1131, 1131, 1131, 1131,   98,   98,
153319   /*  1810 */  1131, 1131, 1131,  507, 1131,   99, 1131,  405,  520,  519,
153320   /*  1820 */  1131, 1131,  927, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153321   /*  1830 */  1131,  374,  937, 1131, 1131, 1131,  276,  509,   98,   98,
153322   /*  1840 */  1131, 1131, 1131, 1131, 1131,   99, 1131,  405,  520,  519,
153323   /*  1850 */  1131, 1131,  927,  927,  927,  929,  930,   24, 1131,  412,
153324   /*  1860 */  1131, 1131, 1131,  258, 1131, 1131, 1131, 1131,  355,  355,
153325   /*  1870 */   354,  243,  352, 1131, 1131,  774, 1131, 1131, 1131, 1131,
153326   /*  1880 */  1131, 1131, 1131,  927,  927,  929,  930,   24,  204, 1131,
153327   /*  1890 */   282, 1131, 1131, 1131, 1131, 1131, 1131, 1131,  281, 1131,
153328   /*  1900 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153329   /*  1910 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153330   /*  1920 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,  206, 1131,
153331   /*  1930 */  1131, 1131, 1131, 1131, 1131, 1131,  147, 1131, 1131,  149,
153332   /*  1940 */  1131, 1131, 1131, 1131, 1131, 1131,  205, 1131, 1131, 1131,
153333   /*  1950 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153334   /*  1960 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153335   /*  1970 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153336   /*  1980 */   374, 1131, 1131, 1131, 1131,  276,  509, 1131, 1131, 1131,
153337   /*  1990 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,
153338   /*  2000 */  1131, 1131, 1131, 1131, 1131, 1131, 1131, 1131,  412,
153339  };
153340  static const YYCODETYPE yy_lookahead[] = {
153341   /*     0 */   168,  163,  184,  238,  239,  240,  163,  163,  155,  156,
153342   /*    10 */   157,  158,  159,  160,  163,  202,  203,  187,  165,   19,
153343   /*    20 */   167,  163,  184,  185,  259,  202,  203,  174,  184,  185,
153344   /*    30 */   174,   31,  238,  239,  240,  184,  185,   22,   23,   39,
153345   /*    40 */   216,   26,  218,   43,   44,   45,   46,   47,   48,   49,
153346   /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  174,  206,
153347   /*    60 */   207,  163,  206,  207,  220,  163,  163,  163,  238,  239,
153348   /*    70 */   240,   59,  219,  229,  231,  219,  183,  245,  174,  223,
153349   /*    80 */   224,  249,  184,  185,  191,  232,  184,  185,  184,  185,
153350   /*    90 */   206,  207,   92,   93,   94,   95,   96,   97,   98,   99,
153351   /*   100 */   100,  101,  102,  219,  102,   81,   91,  163,   96,   97,
153352   /*   110 */   206,  207,   19,  275,  276,  262,  104,  105,  106,  107,
153353   /*   120 */   163,  109,  220,  219,  220,  184,  275,  269,  277,  117,
153354   /*   130 */   187,  229,   19,  229,  101,  102,   43,   44,   45,   46,
153355   /*   140 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
153356   /*   150 */    57,  127,  128,  141,  184,  143,   43,   44,   45,   46,
153357   /*   160 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
153358   /*   170 */    57,  268,  269,  275,  276,  197,   83,  233,   85,  163,
153359   /*   180 */    67,  238,  239,  240,  134,   92,   93,   94,   95,   96,
153360   /*   190 */    97,   98,   99,  100,  101,  102,   19,   54,   55,   56,
153361   /*   200 */    57,   58,  152,   26,  247,   92,   93,   94,   95,   96,
153362   /*   210 */    97,   98,   99,  100,  101,  102,   54,   55,   56,   57,
153363   /*   220 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
153364   /*   230 */    53,   54,   55,   56,   57,   92,   93,   94,   95,   96,
153365   /*   240 */    97,   98,   99,  100,  101,  102,   69,   96,   97,   98,
153366   /*   250 */    99,  100,  101,  102,   92,   93,   94,   95,   96,   97,
153367   /*   260 */    98,   99,  100,  101,  102,   73,  179,  180,  181,   92,
153368   /*   270 */    93,   94,   95,   96,   97,   98,   99,  100,  101,  102,
153369   /*   280 */   163,  191,  192,  163,   98,   99,  100,  101,  102,   19,
153370   /*   290 */   200,  179,  180,  181,   24,  175,   92,   93,   94,   95,
153371   /*   300 */    96,   97,   98,   99,  100,  101,  102,  163,  116,  117,
153372   /*   310 */   118,   22,  163,   43,   44,   45,   46,   47,   48,   49,
153373   /*   320 */    50,   51,   52,   53,   54,   55,   56,   57,  157,  158,
153374   /*   330 */   159,  160,  163,  184,  185,  163,  165,   59,  167,   46,
153375   /*   340 */    90,   76,   11,  174,   73,  174,   19,  198,   59,   19,
153376   /*   350 */    72,   86,   81,  184,  185,  234,  106,   96,   97,  163,
153377   /*   360 */   110,  182,   92,   93,   94,   95,   96,   97,   98,   99,
153378   /*   370 */   100,  101,  102,   46,  230,  206,  207,  206,  207,  163,
153379   /*   380 */   184,  185,   19,  105,  106,  107,   23,  116,  219,  220,
153380   /*   390 */   219,  141,  142,  143,  105,  106,  107,  104,  127,  128,
153381   /*   400 */   184,  185,  141,  232,  143,   59,   43,   44,   45,   46,
153382   /*   410 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
153383   /*   420 */    57,  158,  108,  160,   59,  111,  112,  113,  165,  250,
153384   /*   430 */   167,  104,  102,  262,  255,  121,  220,  174,  108,  109,
153385   /*   440 */   110,  111,  112,  113,  114,  229,  182,  120,  117,  118,
153386   /*   450 */   120,  105,  106,  107,  163,   92,   93,   94,   95,   96,
153387   /*   460 */    97,   98,   99,  100,  101,  102,  163,   22,   59,  206,
153388   /*   470 */   207,  106,  163,   26,  171,   19,  163,  193,  175,   23,
153389   /*   480 */   163,   22,  219,  206,  207,  139,  163,   22,   59,  182,
153390   /*   490 */   117,  118,   59,  184,  185,  232,  219,  184,  185,   43,
153391   /*   500 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
153392   /*   510 */    54,   55,   56,   57,  105,  106,  107,  108,   59,  255,
153393   /*   520 */   111,  112,  113,   90,   59,  262,   22,   98,  174,   12,
153394   /*   530 */   121,  208,  163,  220,  105,  106,  107,  163,  105,  106,
153395   /*   540 */    22,   96,   97,  110,   27,  238,  239,  240,   92,   93,
153396   /*   550 */    94,   95,   96,   97,   98,   99,  100,  101,  102,   42,
153397   /*   560 */   206,  207,  115,   59,  105,  106,  107,  163,   19,   59,
153398   /*   570 */   163,  106,   23,  219,  141,  142,  143,   59,  163,  205,
153399   /*   580 */    63,   59,   72,   22,  124,   59,  163,  270,  234,  129,
153400   /*   590 */    73,  163,   43,   44,   45,   46,   47,   48,   49,   50,
153401   /*   600 */    51,   52,   53,   54,   55,   56,   57,  184,  185,  105,
153402   /*   610 */   106,  107,  184,  185,  163,  105,  106,  107,  265,  266,
153403   /*   620 */    59,  198,  225,  105,  106,  107,  198,  105,  106,  107,
153404   /*   630 */   163,  105,  106,  107,  163,  184,  185,   46,   47,   48,
153405   /*   640 */    49,   92,   93,   94,   95,   96,   97,   98,   99,  100,
153406   /*   650 */   101,  102,  163,  163,  132,  184,  185,  163,  132,  163,
153407   /*   660 */   256,   19,  163,  163,  163,   23,  105,  106,  107,  198,
153408   /*   670 */   163,  220,  205,  184,  185,  163,   35,   81,  184,  185,
153409   /*   680 */   184,  185,  163,  184,  185,   43,   44,   45,   46,   47,
153410   /*   690 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
153411   /*   700 */   163,  110,  163,  184,  185,  109,  205,   66,  163,   59,
153412   /*   710 */   163,   21,  205,   16,  174,   74,  220,  198,  163,  220,
153413   /*   720 */   230,  184,  185,  127,  128,  180,  181,  180,  181,  163,
153414   /*   730 */   175,  242,  174,  233,   92,   93,   94,   95,   96,   97,
153415   /*   740 */    98,   99,  100,  101,  102,  233,  206,  207,   26,  163,
153416   /*   750 */   195,  207,  197,   26,   19,  105,  106,  107,   23,  219,
153417   /*   760 */   119,  260,   26,  219,  206,  207,  174,   19,  174,  230,
153418   /*   770 */    80,  174,  163,  174,   77,  163,   79,  219,   43,   44,
153419   /*   780 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
153420   /*   790 */    55,   56,   57,  248,   12,  248,  184,  185,  206,  207,
153421   /*   800 */   206,  207,  112,  206,  207,  206,  207,  206,  207,   27,
153422   /*   810 */   163,  219,  123,  219,  125,  126,  219,  208,  219,  163,
153423   /*   820 */   219,   22,   23,   23,   42,   26,   26,   92,   93,   94,
153424   /*   830 */    95,   96,   97,   98,   99,  100,  101,  102,  163,  149,
153425   /*   840 */   184,  185,  163,  107,  163,   63,  149,   19,  163,  127,
153426   /*   850 */   128,   23,   22,  105,   24,  116,  117,  118,  131,  184,
153427   /*   860 */   185,  163,  163,  184,  185,  184,  185,   19,  132,  184,
153428   /*   870 */   185,   43,   44,   45,   46,   47,   48,   49,   50,   51,
153429   /*   880 */    52,   53,   54,   55,   56,   57,  146,  163,  148,   59,
153430   /*   890 */    91,   43,   44,   45,   46,   47,   48,   49,   50,   51,
153431   /*   900 */    52,   53,   54,   55,   56,   57,  208,  107,  184,  185,
153432   /*   910 */     7,    8,    9,  116,  117,  118,  163,  163,  163,   24,
153433   /*   920 */    92,   93,   94,   95,   96,   97,   98,   99,  100,  101,
153434   /*   930 */   102,   29,  132,  163,  163,   33,  106,  184,  185,  163,
153435   /*   940 */    92,   93,   94,   95,   96,   97,   98,   99,  100,  101,
153436   /*   950 */   102,  163,  163,  163,   59,  184,  185,  163,   22,  163,
153437   /*   960 */   184,  185,  177,  178,  163,  163,  163,   65,  163,  199,
153438   /*   970 */   163,   26,  184,  185,  184,  185,  163,  163,  184,  185,
153439   /*   980 */   184,  185,  163,   98,  163,  184,  185,  184,  185,  184,
153440   /*   990 */   185,  184,  185,  252,  205,  147,  163,   61,  184,  185,
153441   /*  1000 */   163,  106,  163,  184,  185,  163,  163,  205,  163,  124,
153442   /*  1010 */   163,  256,  163,  163,  129,   19,  163,  184,  185,  163,
153443   /*  1020 */   199,  184,  185,  184,  185,   23,  184,  185,   26,  184,
153444   /*  1030 */   185,  184,  185,  184,  185,   19,  163,  184,  185,   43,
153445   /*  1040 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
153446   /*  1050 */    54,   55,   56,   57,  163,  163,  163,  184,  185,   43,
153447   /*  1060 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
153448   /*  1070 */    54,   55,   56,   57,   16,  184,  185,  184,  185,  163,
153449   /*  1080 */   163,   22,   23,  138,  163,   19,  163,  231,   92,   93,
153450   /*  1090 */    94,   95,   96,   97,   98,   99,  100,  101,  102,  256,
153451   /*  1100 */   163,  184,  185,  163,  163,  184,  185,  163,   92,   93,
153452   /*  1110 */    94,   95,   96,   97,   98,   99,  100,  101,  102,  163,
153453   /*  1120 */    59,  184,  185,  163,  184,  185,  177,  178,  184,  185,
153454   /*  1130 */   163,  208,  163,  237,  163,   77,  163,   79,  163,   15,
153455   /*  1140 */   184,  185,  237,  147,  184,  185,   24,  231,  153,  154,
153456   /*  1150 */    91,  184,  185,  184,  185,  184,  185,  184,  185,  184,
153457   /*  1160 */   185,   22,   23,   19,  163,  127,  128,  106,   24,  273,
153458   /*  1170 */   271,  105,  231,  274,  263,  264,  223,  224,  273,   22,
153459   /*  1180 */   118,   24,   23,   19,   60,   26,  163,   43,   44,   45,
153460   /*  1190 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
153461   /*  1200 */    56,   57,  140,   23,   22,  163,   26,   43,   44,   45,
153462   /*  1210 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
153463   /*  1220 */    56,   57,   23,  211,   23,   26,   31,   26,   23,   22,
153464   /*  1230 */    91,   26,  231,  221,   39,   53,   92,   93,   94,   95,
153465   /*  1240 */    96,   97,   98,   99,  100,  101,  102,   23,   23,  163,
153466   /*  1250 */    26,   26,  130,   59,  109,  110,   92,   93,   94,   95,
153467   /*  1260 */    96,   97,   98,   99,  100,  101,  102,   23,    7,    8,
153468   /*  1270 */    26,  110,   23,   59,   23,   26,   19,   26,  141,   23,
153469   /*  1280 */   143,  120,   26,  141,  163,  143,   23,   23,  163,   26,
153470   /*  1290 */    26,  163,  163,  163,  163,  163,   19,  163,  163,  193,
153471   /*  1300 */   106,   44,   45,   46,   47,   48,   49,   50,   51,   52,
153472   /*  1310 */    53,   54,   55,   56,   57,  163,  193,  163,  163,  163,
153473   /*  1320 */   106,  163,   45,   46,   47,   48,   49,   50,   51,   52,
153474   /*  1330 */    53,   54,   55,   56,   57,  163,  163,  130,  222,  163,
153475   /*  1340 */   163,  203,  163,   19,   20,  251,   22,  163,  163,   92,
153476   /*  1350 */    93,   94,   95,   96,   97,   98,   99,  100,  101,  102,
153477   /*  1360 */    36,  163,  209,  163,  261,  163,  163,  161,  222,   92,
153478   /*  1370 */    93,   94,   95,   96,   97,   98,   99,  100,  101,  102,
153479   /*  1380 */   210,  213,  222,   59,  222,  222,  182,  213,  213,  196,
153480   /*  1390 */   257,  226,  226,   19,   20,   71,   22,  257,  188,  187,
153481   /*  1400 */   192,  212,  187,  187,  226,   81,  210,  166,   60,  261,
153482   /*  1410 */    36,  244,  130,  170,   90,  170,   38,  170,  139,  104,
153483   /*  1420 */    96,   97,   48,  236,   22,  235,   43,  103,  201,  105,
153484   /*  1430 */   106,  107,  138,   59,  110,  247,  213,   18,  204,  258,
153485   /*  1440 */   204,  258,  204,  204,  170,   71,   18,  169,  213,  236,
153486   /*  1450 */   213,  127,  128,  235,  201,  201,   82,  170,  169,  213,
153487   /*  1460 */   146,   87,   62,  254,   90,  141,  142,  143,  144,  145,
153488   /*  1470 */    96,   97,  253,  170,  169,   22,  170,  103,  169,  105,
153489   /*  1480 */   106,  107,  189,  170,  110,  169,  189,  186,   19,   20,
153490   /*  1490 */   104,   22,  194,  186,  186,   64,  115,  186,  194,  189,
153491   /*  1500 */   188,  102,  133,  186,  186,   36,  186,  104,  189,   19,
153492   /*  1510 */    20,  246,   22,  246,  189,  141,  142,  143,  144,  145,
153493   /*  1520 */     0,    1,    2,  228,  228,    5,   36,  227,   59,  227,
153494   /*  1530 */    10,   11,   12,   13,   14,  170,   84,   17,  134,  216,
153495   /*  1540 */    71,  272,  270,   22,  137,  217,   22,  216,  227,   59,
153496   /*  1550 */    30,   82,   32,  217,  228,  228,   87,  227,  170,   90,
153497   /*  1560 */    40,   71,  146,  241,  215,   96,   97,  214,  136,  135,
153498   /*  1570 */   213,   25,  103,   26,  105,  106,  107,  243,  173,  110,
153499   /*  1580 */    90,  172,   13,    6,  164,  164,   96,   97,   98,  162,
153500   /*  1590 */    70,  162,  162,  103,  176,  105,  106,  107,   78,  267,
153501   /*  1600 */   110,   81,  267,  264,  182,  182,  182,  182,   88,  176,
153502   /*  1610 */   141,  142,  143,  144,  145,  176,  190,    4,  182,  182,
153503   /*  1620 */   182,   19,   20,  182,   22,  190,    3,   22,  151,   15,
153504   /*  1630 */    89,  141,  142,  143,  144,  145,   16,  128,   36,   23,
153505   /*  1640 */    23,  139,  122,   24,  119,  131,   20,  127,  128,  133,
153506   /*  1650 */    16,    1,  140,  131,  119,   61,  139,   53,   37,   53,
153507   /*  1660 */    53,   59,   53,  119,  105,   34,  130,    1,    5,   22,
153508   /*  1670 */   150,  104,  149,   71,   26,   75,   68,   41,   68,  130,
153509   /*  1680 */   104,   24,   20,   19,   82,  120,  114,   22,   28,   87,
153510   /*  1690 */    22,   67,   90,   22,   67,   23,   22,   22,   96,   97,
153511   /*  1700 */    67,   23,  138,   22,   37,  103,  153,  105,  106,  107,
153512   /*  1710 */     1,    2,  110,   23,    5,   23,   23,   26,   22,   10,
153513   /*  1720 */    11,   12,   13,   14,   24,   23,   17,   22,   24,  130,
153514   /*  1730 */    23,   19,   20,   23,   22,  105,   22,   34,   85,   30,
153515   /*  1740 */    34,   32,   26,  141,  142,  143,  144,  145,   36,   40,
153516   /*  1750 */   132,   34,   75,   83,   23,   44,   24,   34,   23,   26,
153517   /*  1760 */    26,   19,   20,   23,   22,   26,   23,   23,   23,   23,
153518   /*  1770 */    22,   59,   11,   22,   22,   26,   23,   23,   36,   70,
153519   /*  1780 */    22,   22,  124,   71,  130,  130,  130,   78,   23,  130,
153520   /*  1790 */    81,   15,    1,  278,  278,  278,  278,   88,  278,  278,
153521   /*  1800 */   278,   59,   90,  278,  278,  278,  278,  278,   96,   97,
153522   /*  1810 */   278,  278,  278,   71,  278,  103,  278,  105,  106,  107,
153523   /*  1820 */   278,  278,  110,  278,  278,  278,  278,  278,  278,  278,
153524   /*  1830 */   278,  122,   90,  278,  278,  278,  127,  128,   96,   97,
153525   /*  1840 */   278,  278,  278,  278,  278,  103,  278,  105,  106,  107,
153526   /*  1850 */   278,  278,  110,  141,  142,  143,  144,  145,  278,  150,
153527   /*  1860 */   278,  278,  278,    5,  278,  278,  278,  278,   10,   11,
153528   /*  1870 */    12,   13,   14,  278,  278,   17,  278,  278,  278,  278,
153529   /*  1880 */   278,  278,  278,  141,  142,  143,  144,  145,   30,  278,
153530   /*  1890 */    32,  278,  278,  278,  278,  278,  278,  278,   40,  278,
153531   /*  1900 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153532   /*  1910 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153533   /*  1920 */   278,  278,  278,  278,  278,  278,  278,  278,   70,  278,
153534   /*  1930 */   278,  278,  278,  278,  278,  278,   78,  278,  278,   81,
153535   /*  1940 */   278,  278,  278,  278,  278,  278,   88,  278,  278,  278,
153536   /*  1950 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153537   /*  1960 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153538   /*  1970 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153539   /*  1980 */   122,  278,  278,  278,  278,  127,  128,  278,  278,  278,
153540   /*  1990 */   278,  278,  278,  278,  278,  278,  278,  278,  278,  278,
153541   /*  2000 */   278,  278,  278,  278,  278,  278,  278,  278,  150,  278,
153542   /*  2010 */   278,  278,  278,  278,  278,  278,  278,  278,  278,
153543  };
153544  #define YY_SHIFT_COUNT    (523)
153545  #define YY_SHIFT_MIN      (0)
153546  #define YY_SHIFT_MAX      (1858)
153547  static const unsigned short int yy_shift_ofst[] = {
153548   /*     0 */  1709, 1520, 1858, 1324, 1324,   24, 1374, 1469, 1602, 1712,
153549   /*    10 */  1712, 1712,  271,    0,    0,  113, 1016, 1712, 1712, 1712,
153550   /*    20 */  1712, 1712, 1712, 1712, 1712, 1712, 1712,   12,   12,  409,
153551   /*    30 */   596,   24,   24,   24,   24,   24,   24,   93,  177,  270,
153552   /*    40 */   363,  456,  549,  642,  735,  828,  848,  996, 1144, 1016,
153553   /*    50 */  1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016, 1016,
153554   /*    60 */  1016, 1016, 1016, 1016, 1016, 1016, 1016, 1164, 1016, 1257,
153555   /*    70 */  1277, 1277, 1490, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
153556   /*    80 */  1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
153557   /*    90 */  1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,
153558   /*   100 */  1712, 1712, 1712, 1712, 1712, 1742, 1712, 1712, 1712, 1712,
153559   /*   110 */  1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712, 1712,  143,
153560   /*   120 */   162,  162,  162,  162,  162,  204,  151,  186,  650,  690,
153561   /*   130 */   327,  650,  261,  261,  650,  722,  722,  722,  722,  373,
153562   /*   140 */    33,    2, 2009, 2009,  330,  330,  330,  346,  289,  278,
153563   /*   150 */   289,  289,  517,  517,  459,  510,   15,  799,  650,  650,
153564   /*   160 */   650,  650,  650,  650,  650,  650,  650,  650,  650,  650,
153565   /*   170 */   650,  650,  650,  650,  650,  650,  650,  650,  650,  650,
153566   /*   180 */   331,  365,  995,  995,  265,  365,   50, 1038, 2009, 2009,
153567   /*   190 */  2009,  433,  250,  250,  504,  314,  429,  518,  522,  526,
153568   /*   200 */   561,  650,  650,  650,  650,  650,  650,  650,  650,  650,
153569   /*   210 */   192,  650,  650,  650,  650,  650,  650,  650,  650,  650,
153570   /*   220 */   650,  650,  650,  641,  641,  641,  650,  650,  650,  650,
153571   /*   230 */   800,  650,  650,  650,  830,  650,  650,  782,  650,  650,
153572   /*   240 */   650,  650,  650,  650,  650,  650,  739,  902,  689,  895,
153573   /*   250 */   895,  895,  895,  736,  689,  689,  885,  445,  903, 1124,
153574   /*   260 */   945,  748,  748, 1066,  945,  945, 1066,  447, 1002,  293,
153575   /*   270 */  1195, 1195, 1195,  748,  740,  727,  460, 1157, 1348, 1282,
153576   /*   280 */  1282, 1378, 1378, 1282, 1279, 1315, 1402, 1383, 1294, 1419,
153577   /*   290 */  1419, 1419, 1419, 1282, 1428, 1294, 1294, 1315, 1402, 1383,
153578   /*   300 */  1383, 1294, 1282, 1428, 1314, 1400, 1282, 1428, 1453, 1282,
153579   /*   310 */  1428, 1282, 1428, 1453, 1386, 1386, 1386, 1431, 1453, 1386,
153580   /*   320 */  1381, 1386, 1431, 1386, 1386, 1453, 1399, 1399, 1453, 1369,
153581   /*   330 */  1403, 1369, 1403, 1369, 1403, 1369, 1403, 1282, 1404, 1452,
153582   /*   340 */  1521, 1407, 1404, 1524, 1282, 1416, 1407, 1432, 1434, 1294,
153583   /*   350 */  1546, 1547, 1569, 1569, 1577, 1577, 1577, 2009, 2009, 2009,
153584   /*   360 */  2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
153585   /*   370 */  2009, 2009, 2009,  591,  697, 1059, 1139, 1058,  797,  465,
153586   /*   380 */  1159, 1182, 1122, 1062, 1180,  936, 1199, 1201, 1205, 1224,
153587   /*   390 */  1225, 1244, 1061, 1145, 1261, 1161, 1194, 1249, 1251, 1256,
153588   /*   400 */  1137, 1142, 1263, 1264, 1214, 1207, 1613, 1623, 1605, 1477,
153589   /*   410 */  1614, 1541, 1620, 1616, 1617, 1509, 1502, 1525, 1619, 1514,
153590   /*   420 */  1626, 1516, 1634, 1650, 1522, 1512, 1535, 1594, 1621, 1517,
153591   /*   430 */  1604, 1606, 1607, 1609, 1544, 1559, 1631, 1536, 1666, 1663,
153592   /*   440 */  1647, 1567, 1523, 1608, 1648, 1610, 1600, 1636, 1549, 1576,
153593   /*   450 */  1657, 1662, 1664, 1565, 1572, 1665, 1624, 1668, 1671, 1672,
153594   /*   460 */  1674, 1627, 1660, 1675, 1633, 1667, 1678, 1564, 1681, 1553,
153595   /*   470 */  1690, 1692, 1691, 1693, 1696, 1700, 1702, 1705, 1704, 1599,
153596   /*   480 */  1707, 1710, 1630, 1703, 1714, 1618, 1716, 1706, 1716, 1717,
153597   /*   490 */  1653, 1677, 1670, 1711, 1731, 1732, 1733, 1734, 1723, 1735,
153598   /*   500 */  1716, 1740, 1743, 1744, 1745, 1739, 1746, 1748, 1761, 1751,
153599   /*   510 */  1752, 1753, 1754, 1758, 1759, 1749, 1658, 1654, 1655, 1656,
153600   /*   520 */  1659, 1765, 1776, 1791,
153601  };
153602  #define YY_REDUCE_COUNT (372)
153603  #define YY_REDUCE_MIN   (-235)
153604  #define YY_REDUCE_MAX   (1441)
153605  static const short yy_reduce_ofst[] = {
153606   /*     0 */  -147,  171,  263,  -96,  169, -144, -162, -149, -102, -156,
153607   /*    10 */   -98,  216,  354, -170,  -57, -235,  307,  149,  423,  428,
153608   /*    20 */   471,  313,  451,  519,  489,  496,  499,  545,  547,  555,
153609   /*    30 */  -116,  540,  558,  592,  594,  597,  599, -206, -206, -206,
153610   /*    40 */  -206, -206, -206, -206, -206, -206, -206, -206, -206, -206,
153611   /*    50 */  -206, -206, -206, -206, -206, -206, -206, -206, -206, -206,
153612   /*    60 */  -206, -206, -206, -206, -206, -206, -206, -206, -206, -206,
153613   /*    70 */  -206, -206,  196,  309,  494,  537,  612,  656,  675,  679,
153614   /*    80 */   681,  685,  724,  753,  771,  776,  788,  790,  794,  796,
153615   /*    90 */   801,  803,  805,  807,  814,  819,  833,  837,  839,  842,
153616   /*   100 */   845,  847,  849,  853,  873,  891,  893,  917,  921,  937,
153617   /*   110 */   940,  944,  956,  960,  967,  969,  971,  973,  975, -206,
153618   /*   120 */  -206, -206, -206, -206, -206, -206, -206, -206,  501, -168,
153619   /*   130 */    90,  -97,   87,  112,  303,  277,  601,  277,  601,  179,
153620   /*   140 */  -206, -206, -206, -206, -107, -107, -107,  -43,  -56,  323,
153621   /*   150 */   500,  512, -187, -177,  317,  609,  353,  353,  120,  144,
153622   /*   160 */   490,  539,  698,  374,  467,  507,  789,  404, -157,  755,
153623   /*   170 */   856,  916,  843,  941,  802,  770,  923,  821, 1001, -142,
153624   /*   180 */   264,  785,  896,  905,  899,  949, -176,  544,  911,  953,
153625   /*   190 */  1012, -182,  -59,  -30,   16,  -22,  117,  172,  291,  369,
153626   /*   200 */   407,  415,  566,  586,  647,  699,  754,  813,  850,  892,
153627   /*   210 */   121, 1023, 1042, 1086, 1121, 1125, 1128, 1129, 1130, 1131,
153628   /*   220 */  1132, 1134, 1135,  284, 1106, 1123, 1152, 1154, 1155, 1156,
153629   /*   230 */   397, 1158, 1172, 1173, 1116, 1176, 1177, 1138, 1179,  117,
153630   /*   240 */  1184, 1185, 1198, 1200, 1202, 1203,  741, 1094, 1153, 1146,
153631   /*   250 */  1160, 1162, 1163,  397, 1153, 1153, 1170, 1204, 1206, 1103,
153632   /*   260 */  1168, 1165, 1166, 1133, 1174, 1175, 1140, 1210, 1193, 1208,
153633   /*   270 */  1212, 1215, 1216, 1178, 1167, 1189, 1196, 1241, 1148, 1243,
153634   /*   280 */  1245, 1181, 1183, 1247, 1188, 1187, 1190, 1227, 1223, 1234,
153635   /*   290 */  1236, 1238, 1239, 1274, 1278, 1235, 1237, 1213, 1218, 1253,
153636   /*   300 */  1254, 1246, 1287, 1289, 1209, 1219, 1303, 1305, 1293, 1306,
153637   /*   310 */  1309, 1313, 1316, 1297, 1301, 1307, 1308, 1298, 1310, 1311,
153638   /*   320 */  1312, 1317, 1304, 1318, 1320, 1319, 1265, 1267, 1325, 1295,
153639   /*   330 */  1300, 1296, 1302, 1326, 1321, 1327, 1330, 1365, 1323, 1269,
153640   /*   340 */  1272, 1328, 1331, 1322, 1388, 1334, 1336, 1349, 1353, 1357,
153641   /*   350 */  1405, 1409, 1420, 1421, 1427, 1429, 1430, 1332, 1335, 1339,
153642   /*   360 */  1418, 1422, 1423, 1424, 1425, 1433, 1426, 1435, 1436, 1437,
153643   /*   370 */  1438, 1441, 1439,
153644  };
153645  static const YYACTIONTYPE yy_default[] = {
153646   /*     0 */  1500, 1500, 1500, 1346, 1129, 1235, 1129, 1129, 1129, 1346,
153647   /*    10 */  1346, 1346, 1129, 1265, 1265, 1399, 1160, 1129, 1129, 1129,
153648   /*    20 */  1129, 1129, 1129, 1129, 1345, 1129, 1129, 1129, 1129, 1129,
153649   /*    30 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1271, 1129,
153650   /*    40 */  1129, 1129, 1129, 1129, 1347, 1348, 1129, 1129, 1129, 1398,
153651   /*    50 */  1400, 1363, 1281, 1280, 1279, 1278, 1381, 1252, 1276, 1269,
153652   /*    60 */  1273, 1341, 1342, 1340, 1344, 1348, 1347, 1129, 1272, 1312,
153653   /*    70 */  1326, 1311, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153654   /*    80 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153655   /*    90 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153656   /*   100 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153657   /*   110 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1320,
153658   /*   120 */  1325, 1331, 1324, 1321, 1314, 1313, 1315, 1316, 1129, 1150,
153659   /*   130 */  1199, 1129, 1129, 1129, 1129, 1417, 1416, 1129, 1129, 1160,
153660   /*   140 */  1317, 1318, 1328, 1327, 1406, 1456, 1455, 1364, 1129, 1129,
153661   /*   150 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153662   /*   160 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153663   /*   170 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153664   /*   180 */  1160, 1156, 1306, 1305, 1426, 1156, 1259, 1129, 1412, 1235,
153665   /*   190 */  1226, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153666   /*   200 */  1129, 1129, 1129, 1129, 1403, 1401, 1129, 1129, 1129, 1129,
153667   /*   210 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153668   /*   220 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153669   /*   230 */  1129, 1129, 1129, 1129, 1231, 1129, 1129, 1129, 1129, 1129,
153670   /*   240 */  1129, 1129, 1129, 1129, 1129, 1450, 1129, 1376, 1213, 1231,
153671   /*   250 */  1231, 1231, 1231, 1233, 1214, 1212, 1225, 1160, 1136, 1492,
153672   /*   260 */  1275, 1254, 1254, 1489, 1275, 1275, 1489, 1174, 1470, 1171,
153673   /*   270 */  1265, 1265, 1265, 1254, 1343, 1232, 1225, 1129, 1492, 1240,
153674   /*   280 */  1240, 1491, 1491, 1240, 1364, 1284, 1290, 1202, 1275, 1208,
153675   /*   290 */  1208, 1208, 1208, 1240, 1147, 1275, 1275, 1284, 1290, 1202,
153676   /*   300 */  1202, 1275, 1240, 1147, 1380, 1486, 1240, 1147, 1354, 1240,
153677   /*   310 */  1147, 1240, 1147, 1354, 1200, 1200, 1200, 1189, 1354, 1200,
153678   /*   320 */  1174, 1200, 1189, 1200, 1200, 1354, 1358, 1358, 1354, 1258,
153679   /*   330 */  1253, 1258, 1253, 1258, 1253, 1258, 1253, 1240, 1259, 1425,
153680   /*   340 */  1129, 1270, 1259, 1349, 1240, 1129, 1270, 1268, 1266, 1275,
153681   /*   350 */  1153, 1192, 1453, 1453, 1449, 1449, 1449, 1497, 1497, 1412,
153682   /*   360 */  1465, 1160, 1160, 1160, 1160, 1465, 1176, 1176, 1160, 1160,
153683   /*   370 */  1160, 1160, 1465, 1129, 1129, 1129, 1129, 1129, 1129, 1460,
153684   /*   380 */  1129, 1365, 1244, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153685   /*   390 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153686   /*   400 */  1129, 1129, 1129, 1129, 1129, 1295, 1129, 1132, 1409, 1129,
153687   /*   410 */  1129, 1407, 1129, 1129, 1129, 1129, 1129, 1129, 1245, 1129,
153688   /*   420 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153689   /*   430 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1488, 1129, 1129,
153690   /*   440 */  1129, 1129, 1129, 1129, 1379, 1378, 1129, 1129, 1242, 1129,
153691   /*   450 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153692   /*   460 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153693   /*   470 */  1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153694   /*   480 */  1129, 1129, 1129, 1129, 1129, 1129, 1267, 1129, 1424, 1129,
153695   /*   490 */  1129, 1129, 1129, 1129, 1129, 1129, 1438, 1260, 1129, 1129,
153696   /*   500 */  1479, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129, 1129,
153697   /*   510 */  1129, 1129, 1129, 1129, 1129, 1474, 1216, 1297, 1129, 1296,
153698   /*   520 */  1300, 1129, 1141, 1129,
153699  };
153700  /********** End of lemon-generated parsing tables *****************************/
153701  
153702  /* The next table maps tokens (terminal symbols) into fallback tokens.  
153703  ** If a construct like the following:
153704  ** 
153705  **      %fallback ID X Y Z.
153706  **
153707  ** appears in the grammar, then ID becomes a fallback token for X, Y,
153708  ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
153709  ** but it does not parse, the type of the token is changed to ID and
153710  ** the parse is retried before an error is thrown.
153711  **
153712  ** This feature can be used, for example, to cause some keywords in a language
153713  ** to revert to identifiers if they keyword does not apply in the context where
153714  ** it appears.
153715  */
153716  #ifdef YYFALLBACK
153717  static const YYCODETYPE yyFallback[] = {
153718      0,  /*          $ => nothing */
153719      0,  /*       SEMI => nothing */
153720     59,  /*    EXPLAIN => ID */
153721     59,  /*      QUERY => ID */
153722     59,  /*       PLAN => ID */
153723     59,  /*      BEGIN => ID */
153724      0,  /* TRANSACTION => nothing */
153725     59,  /*   DEFERRED => ID */
153726     59,  /*  IMMEDIATE => ID */
153727     59,  /*  EXCLUSIVE => ID */
153728      0,  /*     COMMIT => nothing */
153729     59,  /*        END => ID */
153730     59,  /*   ROLLBACK => ID */
153731     59,  /*  SAVEPOINT => ID */
153732     59,  /*    RELEASE => ID */
153733      0,  /*         TO => nothing */
153734      0,  /*      TABLE => nothing */
153735      0,  /*     CREATE => nothing */
153736     59,  /*         IF => ID */
153737      0,  /*        NOT => nothing */
153738      0,  /*     EXISTS => nothing */
153739     59,  /*       TEMP => ID */
153740      0,  /*         LP => nothing */
153741      0,  /*         RP => nothing */
153742      0,  /*         AS => nothing */
153743     59,  /*    WITHOUT => ID */
153744      0,  /*      COMMA => nothing */
153745     59,  /*      ABORT => ID */
153746     59,  /*     ACTION => ID */
153747     59,  /*      AFTER => ID */
153748     59,  /*    ANALYZE => ID */
153749     59,  /*        ASC => ID */
153750     59,  /*     ATTACH => ID */
153751     59,  /*     BEFORE => ID */
153752     59,  /*         BY => ID */
153753     59,  /*    CASCADE => ID */
153754     59,  /*       CAST => ID */
153755     59,  /*   CONFLICT => ID */
153756     59,  /*   DATABASE => ID */
153757     59,  /*       DESC => ID */
153758     59,  /*     DETACH => ID */
153759     59,  /*       EACH => ID */
153760     59,  /*       FAIL => ID */
153761      0,  /*         OR => nothing */
153762      0,  /*        AND => nothing */
153763      0,  /*         IS => nothing */
153764     59,  /*      MATCH => ID */
153765     59,  /*    LIKE_KW => ID */
153766      0,  /*    BETWEEN => nothing */
153767      0,  /*         IN => nothing */
153768      0,  /*     ISNULL => nothing */
153769      0,  /*    NOTNULL => nothing */
153770      0,  /*         NE => nothing */
153771      0,  /*         EQ => nothing */
153772      0,  /*         GT => nothing */
153773      0,  /*         LE => nothing */
153774      0,  /*         LT => nothing */
153775      0,  /*         GE => nothing */
153776      0,  /*     ESCAPE => nothing */
153777      0,  /*         ID => nothing */
153778     59,  /*   COLUMNKW => ID */
153779     59,  /*         DO => ID */
153780     59,  /*        FOR => ID */
153781     59,  /*     IGNORE => ID */
153782     59,  /*  INITIALLY => ID */
153783     59,  /*    INSTEAD => ID */
153784     59,  /*         NO => ID */
153785     59,  /*        KEY => ID */
153786     59,  /*         OF => ID */
153787     59,  /*     OFFSET => ID */
153788     59,  /*     PRAGMA => ID */
153789     59,  /*      RAISE => ID */
153790     59,  /*  RECURSIVE => ID */
153791     59,  /*    REPLACE => ID */
153792     59,  /*   RESTRICT => ID */
153793     59,  /*        ROW => ID */
153794     59,  /*       ROWS => ID */
153795     59,  /*    TRIGGER => ID */
153796     59,  /*     VACUUM => ID */
153797     59,  /*       VIEW => ID */
153798     59,  /*    VIRTUAL => ID */
153799     59,  /*       WITH => ID */
153800     59,  /*    CURRENT => ID */
153801     59,  /*  FOLLOWING => ID */
153802     59,  /*  PARTITION => ID */
153803     59,  /*  PRECEDING => ID */
153804     59,  /*      RANGE => ID */
153805     59,  /*  UNBOUNDED => ID */
153806     59,  /*    REINDEX => ID */
153807     59,  /*     RENAME => ID */
153808     59,  /*   CTIME_KW => ID */
153809  };
153810  #endif /* YYFALLBACK */
153811  
153812  /* The following structure represents a single element of the
153813  ** parser's stack.  Information stored includes:
153814  **
153815  **   +  The state number for the parser at this level of the stack.
153816  **
153817  **   +  The value of the token stored at this level of the stack.
153818  **      (In other words, the "major" token.)
153819  **
153820  **   +  The semantic value stored at this level of the stack.  This is
153821  **      the information used by the action routines in the grammar.
153822  **      It is sometimes called the "minor" token.
153823  **
153824  ** After the "shift" half of a SHIFTREDUCE action, the stateno field
153825  ** actually contains the reduce action for the second half of the
153826  ** SHIFTREDUCE.
153827  */
153828  struct yyStackEntry {
153829    YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
153830    YYCODETYPE major;      /* The major token value.  This is the code
153831                           ** number for the token at this stack level */
153832    YYMINORTYPE minor;     /* The user-supplied minor token value.  This
153833                           ** is the value of the token  */
153834  };
153835  typedef struct yyStackEntry yyStackEntry;
153836  
153837  /* The state of the parser is completely contained in an instance of
153838  ** the following structure */
153839  struct yyParser {
153840    yyStackEntry *yytos;          /* Pointer to top element of the stack */
153841  #ifdef YYTRACKMAXSTACKDEPTH
153842    int yyhwm;                    /* High-water mark of the stack */
153843  #endif
153844  #ifndef YYNOERRORRECOVERY
153845    int yyerrcnt;                 /* Shifts left before out of the error */
153846  #endif
153847    sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
153848    sqlite3ParserCTX_SDECL                /* A place to hold %extra_context */
153849  #if YYSTACKDEPTH<=0
153850    int yystksz;                  /* Current side of the stack */
153851    yyStackEntry *yystack;        /* The parser's stack */
153852    yyStackEntry yystk0;          /* First stack entry */
153853  #else
153854    yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
153855    yyStackEntry *yystackEnd;            /* Last entry in the stack */
153856  #endif
153857  };
153858  typedef struct yyParser yyParser;
153859  
153860  #ifndef NDEBUG
153861  /* #include <stdio.h> */
153862  static FILE *yyTraceFILE = 0;
153863  static char *yyTracePrompt = 0;
153864  #endif /* NDEBUG */
153865  
153866  #ifndef NDEBUG
153867  /* 
153868  ** Turn parser tracing on by giving a stream to which to write the trace
153869  ** and a prompt to preface each trace message.  Tracing is turned off
153870  ** by making either argument NULL 
153871  **
153872  ** Inputs:
153873  ** <ul>
153874  ** <li> A FILE* to which trace output should be written.
153875  **      If NULL, then tracing is turned off.
153876  ** <li> A prefix string written at the beginning of every
153877  **      line of trace output.  If NULL, then tracing is
153878  **      turned off.
153879  ** </ul>
153880  **
153881  ** Outputs:
153882  ** None.
153883  */
153884  SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
153885    yyTraceFILE = TraceFILE;
153886    yyTracePrompt = zTracePrompt;
153887    if( yyTraceFILE==0 ) yyTracePrompt = 0;
153888    else if( yyTracePrompt==0 ) yyTraceFILE = 0;
153889  }
153890  #endif /* NDEBUG */
153891  
153892  #if defined(YYCOVERAGE) || !defined(NDEBUG)
153893  /* For tracing shifts, the names of all terminals and nonterminals
153894  ** are required.  The following table supplies these names */
153895  static const char *const yyTokenName[] = { 
153896    /*    0 */ "$",
153897    /*    1 */ "SEMI",
153898    /*    2 */ "EXPLAIN",
153899    /*    3 */ "QUERY",
153900    /*    4 */ "PLAN",
153901    /*    5 */ "BEGIN",
153902    /*    6 */ "TRANSACTION",
153903    /*    7 */ "DEFERRED",
153904    /*    8 */ "IMMEDIATE",
153905    /*    9 */ "EXCLUSIVE",
153906    /*   10 */ "COMMIT",
153907    /*   11 */ "END",
153908    /*   12 */ "ROLLBACK",
153909    /*   13 */ "SAVEPOINT",
153910    /*   14 */ "RELEASE",
153911    /*   15 */ "TO",
153912    /*   16 */ "TABLE",
153913    /*   17 */ "CREATE",
153914    /*   18 */ "IF",
153915    /*   19 */ "NOT",
153916    /*   20 */ "EXISTS",
153917    /*   21 */ "TEMP",
153918    /*   22 */ "LP",
153919    /*   23 */ "RP",
153920    /*   24 */ "AS",
153921    /*   25 */ "WITHOUT",
153922    /*   26 */ "COMMA",
153923    /*   27 */ "ABORT",
153924    /*   28 */ "ACTION",
153925    /*   29 */ "AFTER",
153926    /*   30 */ "ANALYZE",
153927    /*   31 */ "ASC",
153928    /*   32 */ "ATTACH",
153929    /*   33 */ "BEFORE",
153930    /*   34 */ "BY",
153931    /*   35 */ "CASCADE",
153932    /*   36 */ "CAST",
153933    /*   37 */ "CONFLICT",
153934    /*   38 */ "DATABASE",
153935    /*   39 */ "DESC",
153936    /*   40 */ "DETACH",
153937    /*   41 */ "EACH",
153938    /*   42 */ "FAIL",
153939    /*   43 */ "OR",
153940    /*   44 */ "AND",
153941    /*   45 */ "IS",
153942    /*   46 */ "MATCH",
153943    /*   47 */ "LIKE_KW",
153944    /*   48 */ "BETWEEN",
153945    /*   49 */ "IN",
153946    /*   50 */ "ISNULL",
153947    /*   51 */ "NOTNULL",
153948    /*   52 */ "NE",
153949    /*   53 */ "EQ",
153950    /*   54 */ "GT",
153951    /*   55 */ "LE",
153952    /*   56 */ "LT",
153953    /*   57 */ "GE",
153954    /*   58 */ "ESCAPE",
153955    /*   59 */ "ID",
153956    /*   60 */ "COLUMNKW",
153957    /*   61 */ "DO",
153958    /*   62 */ "FOR",
153959    /*   63 */ "IGNORE",
153960    /*   64 */ "INITIALLY",
153961    /*   65 */ "INSTEAD",
153962    /*   66 */ "NO",
153963    /*   67 */ "KEY",
153964    /*   68 */ "OF",
153965    /*   69 */ "OFFSET",
153966    /*   70 */ "PRAGMA",
153967    /*   71 */ "RAISE",
153968    /*   72 */ "RECURSIVE",
153969    /*   73 */ "REPLACE",
153970    /*   74 */ "RESTRICT",
153971    /*   75 */ "ROW",
153972    /*   76 */ "ROWS",
153973    /*   77 */ "TRIGGER",
153974    /*   78 */ "VACUUM",
153975    /*   79 */ "VIEW",
153976    /*   80 */ "VIRTUAL",
153977    /*   81 */ "WITH",
153978    /*   82 */ "CURRENT",
153979    /*   83 */ "FOLLOWING",
153980    /*   84 */ "PARTITION",
153981    /*   85 */ "PRECEDING",
153982    /*   86 */ "RANGE",
153983    /*   87 */ "UNBOUNDED",
153984    /*   88 */ "REINDEX",
153985    /*   89 */ "RENAME",
153986    /*   90 */ "CTIME_KW",
153987    /*   91 */ "ANY",
153988    /*   92 */ "BITAND",
153989    /*   93 */ "BITOR",
153990    /*   94 */ "LSHIFT",
153991    /*   95 */ "RSHIFT",
153992    /*   96 */ "PLUS",
153993    /*   97 */ "MINUS",
153994    /*   98 */ "STAR",
153995    /*   99 */ "SLASH",
153996    /*  100 */ "REM",
153997    /*  101 */ "CONCAT",
153998    /*  102 */ "COLLATE",
153999    /*  103 */ "BITNOT",
154000    /*  104 */ "ON",
154001    /*  105 */ "INDEXED",
154002    /*  106 */ "STRING",
154003    /*  107 */ "JOIN_KW",
154004    /*  108 */ "CONSTRAINT",
154005    /*  109 */ "DEFAULT",
154006    /*  110 */ "NULL",
154007    /*  111 */ "PRIMARY",
154008    /*  112 */ "UNIQUE",
154009    /*  113 */ "CHECK",
154010    /*  114 */ "REFERENCES",
154011    /*  115 */ "AUTOINCR",
154012    /*  116 */ "INSERT",
154013    /*  117 */ "DELETE",
154014    /*  118 */ "UPDATE",
154015    /*  119 */ "SET",
154016    /*  120 */ "DEFERRABLE",
154017    /*  121 */ "FOREIGN",
154018    /*  122 */ "DROP",
154019    /*  123 */ "UNION",
154020    /*  124 */ "ALL",
154021    /*  125 */ "EXCEPT",
154022    /*  126 */ "INTERSECT",
154023    /*  127 */ "SELECT",
154024    /*  128 */ "VALUES",
154025    /*  129 */ "DISTINCT",
154026    /*  130 */ "DOT",
154027    /*  131 */ "FROM",
154028    /*  132 */ "JOIN",
154029    /*  133 */ "USING",
154030    /*  134 */ "ORDER",
154031    /*  135 */ "GROUP",
154032    /*  136 */ "HAVING",
154033    /*  137 */ "LIMIT",
154034    /*  138 */ "WHERE",
154035    /*  139 */ "INTO",
154036    /*  140 */ "NOTHING",
154037    /*  141 */ "FLOAT",
154038    /*  142 */ "BLOB",
154039    /*  143 */ "INTEGER",
154040    /*  144 */ "VARIABLE",
154041    /*  145 */ "CASE",
154042    /*  146 */ "WHEN",
154043    /*  147 */ "THEN",
154044    /*  148 */ "ELSE",
154045    /*  149 */ "INDEX",
154046    /*  150 */ "ALTER",
154047    /*  151 */ "ADD",
154048    /*  152 */ "WINDOW",
154049    /*  153 */ "OVER",
154050    /*  154 */ "FILTER",
154051    /*  155 */ "input",
154052    /*  156 */ "cmdlist",
154053    /*  157 */ "ecmd",
154054    /*  158 */ "cmdx",
154055    /*  159 */ "explain",
154056    /*  160 */ "cmd",
154057    /*  161 */ "transtype",
154058    /*  162 */ "trans_opt",
154059    /*  163 */ "nm",
154060    /*  164 */ "savepoint_opt",
154061    /*  165 */ "create_table",
154062    /*  166 */ "create_table_args",
154063    /*  167 */ "createkw",
154064    /*  168 */ "temp",
154065    /*  169 */ "ifnotexists",
154066    /*  170 */ "dbnm",
154067    /*  171 */ "columnlist",
154068    /*  172 */ "conslist_opt",
154069    /*  173 */ "table_options",
154070    /*  174 */ "select",
154071    /*  175 */ "columnname",
154072    /*  176 */ "carglist",
154073    /*  177 */ "typetoken",
154074    /*  178 */ "typename",
154075    /*  179 */ "signed",
154076    /*  180 */ "plus_num",
154077    /*  181 */ "minus_num",
154078    /*  182 */ "scanpt",
154079    /*  183 */ "ccons",
154080    /*  184 */ "term",
154081    /*  185 */ "expr",
154082    /*  186 */ "onconf",
154083    /*  187 */ "sortorder",
154084    /*  188 */ "autoinc",
154085    /*  189 */ "eidlist_opt",
154086    /*  190 */ "refargs",
154087    /*  191 */ "defer_subclause",
154088    /*  192 */ "refarg",
154089    /*  193 */ "refact",
154090    /*  194 */ "init_deferred_pred_opt",
154091    /*  195 */ "conslist",
154092    /*  196 */ "tconscomma",
154093    /*  197 */ "tcons",
154094    /*  198 */ "sortlist",
154095    /*  199 */ "eidlist",
154096    /*  200 */ "defer_subclause_opt",
154097    /*  201 */ "orconf",
154098    /*  202 */ "resolvetype",
154099    /*  203 */ "raisetype",
154100    /*  204 */ "ifexists",
154101    /*  205 */ "fullname",
154102    /*  206 */ "selectnowith",
154103    /*  207 */ "oneselect",
154104    /*  208 */ "wqlist",
154105    /*  209 */ "multiselect_op",
154106    /*  210 */ "distinct",
154107    /*  211 */ "selcollist",
154108    /*  212 */ "from",
154109    /*  213 */ "where_opt",
154110    /*  214 */ "groupby_opt",
154111    /*  215 */ "having_opt",
154112    /*  216 */ "orderby_opt",
154113    /*  217 */ "limit_opt",
154114    /*  218 */ "window_clause",
154115    /*  219 */ "values",
154116    /*  220 */ "nexprlist",
154117    /*  221 */ "sclp",
154118    /*  222 */ "as",
154119    /*  223 */ "seltablist",
154120    /*  224 */ "stl_prefix",
154121    /*  225 */ "joinop",
154122    /*  226 */ "indexed_opt",
154123    /*  227 */ "on_opt",
154124    /*  228 */ "using_opt",
154125    /*  229 */ "exprlist",
154126    /*  230 */ "xfullname",
154127    /*  231 */ "idlist",
154128    /*  232 */ "with",
154129    /*  233 */ "setlist",
154130    /*  234 */ "insert_cmd",
154131    /*  235 */ "idlist_opt",
154132    /*  236 */ "upsert",
154133    /*  237 */ "over_clause",
154134    /*  238 */ "likeop",
154135    /*  239 */ "between_op",
154136    /*  240 */ "in_op",
154137    /*  241 */ "paren_exprlist",
154138    /*  242 */ "case_operand",
154139    /*  243 */ "case_exprlist",
154140    /*  244 */ "case_else",
154141    /*  245 */ "uniqueflag",
154142    /*  246 */ "collate",
154143    /*  247 */ "vinto",
154144    /*  248 */ "nmnum",
154145    /*  249 */ "trigger_decl",
154146    /*  250 */ "trigger_cmd_list",
154147    /*  251 */ "trigger_time",
154148    /*  252 */ "trigger_event",
154149    /*  253 */ "foreach_clause",
154150    /*  254 */ "when_clause",
154151    /*  255 */ "trigger_cmd",
154152    /*  256 */ "trnm",
154153    /*  257 */ "tridxby",
154154    /*  258 */ "database_kw_opt",
154155    /*  259 */ "key_opt",
154156    /*  260 */ "add_column_fullname",
154157    /*  261 */ "kwcolumn_opt",
154158    /*  262 */ "create_vtab",
154159    /*  263 */ "vtabarglist",
154160    /*  264 */ "vtabarg",
154161    /*  265 */ "vtabargtoken",
154162    /*  266 */ "lp",
154163    /*  267 */ "anylist",
154164    /*  268 */ "windowdefn_list",
154165    /*  269 */ "windowdefn",
154166    /*  270 */ "window",
154167    /*  271 */ "frame_opt",
154168    /*  272 */ "part_opt",
154169    /*  273 */ "filter_opt",
154170    /*  274 */ "range_or_rows",
154171    /*  275 */ "frame_bound",
154172    /*  276 */ "frame_bound_s",
154173    /*  277 */ "frame_bound_e",
154174  };
154175  #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
154176  
154177  #ifndef NDEBUG
154178  /* For tracing reduce actions, the names of all rules are required.
154179  */
154180  static const char *const yyRuleName[] = {
154181   /*   0 */ "explain ::= EXPLAIN",
154182   /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
154183   /*   2 */ "cmdx ::= cmd",
154184   /*   3 */ "cmd ::= BEGIN transtype trans_opt",
154185   /*   4 */ "transtype ::=",
154186   /*   5 */ "transtype ::= DEFERRED",
154187   /*   6 */ "transtype ::= IMMEDIATE",
154188   /*   7 */ "transtype ::= EXCLUSIVE",
154189   /*   8 */ "cmd ::= COMMIT|END trans_opt",
154190   /*   9 */ "cmd ::= ROLLBACK trans_opt",
154191   /*  10 */ "cmd ::= SAVEPOINT nm",
154192   /*  11 */ "cmd ::= RELEASE savepoint_opt nm",
154193   /*  12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
154194   /*  13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
154195   /*  14 */ "createkw ::= CREATE",
154196   /*  15 */ "ifnotexists ::=",
154197   /*  16 */ "ifnotexists ::= IF NOT EXISTS",
154198   /*  17 */ "temp ::= TEMP",
154199   /*  18 */ "temp ::=",
154200   /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
154201   /*  20 */ "create_table_args ::= AS select",
154202   /*  21 */ "table_options ::=",
154203   /*  22 */ "table_options ::= WITHOUT nm",
154204   /*  23 */ "columnname ::= nm typetoken",
154205   /*  24 */ "typetoken ::=",
154206   /*  25 */ "typetoken ::= typename LP signed RP",
154207   /*  26 */ "typetoken ::= typename LP signed COMMA signed RP",
154208   /*  27 */ "typename ::= typename ID|STRING",
154209   /*  28 */ "scanpt ::=",
154210   /*  29 */ "ccons ::= CONSTRAINT nm",
154211   /*  30 */ "ccons ::= DEFAULT scanpt term scanpt",
154212   /*  31 */ "ccons ::= DEFAULT LP expr RP",
154213   /*  32 */ "ccons ::= DEFAULT PLUS term scanpt",
154214   /*  33 */ "ccons ::= DEFAULT MINUS term scanpt",
154215   /*  34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
154216   /*  35 */ "ccons ::= NOT NULL onconf",
154217   /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
154218   /*  37 */ "ccons ::= UNIQUE onconf",
154219   /*  38 */ "ccons ::= CHECK LP expr RP",
154220   /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
154221   /*  40 */ "ccons ::= defer_subclause",
154222   /*  41 */ "ccons ::= COLLATE ID|STRING",
154223   /*  42 */ "autoinc ::=",
154224   /*  43 */ "autoinc ::= AUTOINCR",
154225   /*  44 */ "refargs ::=",
154226   /*  45 */ "refargs ::= refargs refarg",
154227   /*  46 */ "refarg ::= MATCH nm",
154228   /*  47 */ "refarg ::= ON INSERT refact",
154229   /*  48 */ "refarg ::= ON DELETE refact",
154230   /*  49 */ "refarg ::= ON UPDATE refact",
154231   /*  50 */ "refact ::= SET NULL",
154232   /*  51 */ "refact ::= SET DEFAULT",
154233   /*  52 */ "refact ::= CASCADE",
154234   /*  53 */ "refact ::= RESTRICT",
154235   /*  54 */ "refact ::= NO ACTION",
154236   /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
154237   /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
154238   /*  57 */ "init_deferred_pred_opt ::=",
154239   /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
154240   /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
154241   /*  60 */ "conslist_opt ::=",
154242   /*  61 */ "tconscomma ::= COMMA",
154243   /*  62 */ "tcons ::= CONSTRAINT nm",
154244   /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
154245   /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
154246   /*  65 */ "tcons ::= CHECK LP expr RP onconf",
154247   /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
154248   /*  67 */ "defer_subclause_opt ::=",
154249   /*  68 */ "onconf ::=",
154250   /*  69 */ "onconf ::= ON CONFLICT resolvetype",
154251   /*  70 */ "orconf ::=",
154252   /*  71 */ "orconf ::= OR resolvetype",
154253   /*  72 */ "resolvetype ::= IGNORE",
154254   /*  73 */ "resolvetype ::= REPLACE",
154255   /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
154256   /*  75 */ "ifexists ::= IF EXISTS",
154257   /*  76 */ "ifexists ::=",
154258   /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
154259   /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
154260   /*  79 */ "cmd ::= select",
154261   /*  80 */ "select ::= WITH wqlist selectnowith",
154262   /*  81 */ "select ::= WITH RECURSIVE wqlist selectnowith",
154263   /*  82 */ "select ::= selectnowith",
154264   /*  83 */ "selectnowith ::= selectnowith multiselect_op oneselect",
154265   /*  84 */ "multiselect_op ::= UNION",
154266   /*  85 */ "multiselect_op ::= UNION ALL",
154267   /*  86 */ "multiselect_op ::= EXCEPT|INTERSECT",
154268   /*  87 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
154269   /*  88 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
154270   /*  89 */ "values ::= VALUES LP nexprlist RP",
154271   /*  90 */ "values ::= values COMMA LP nexprlist RP",
154272   /*  91 */ "distinct ::= DISTINCT",
154273   /*  92 */ "distinct ::= ALL",
154274   /*  93 */ "distinct ::=",
154275   /*  94 */ "sclp ::=",
154276   /*  95 */ "selcollist ::= sclp scanpt expr scanpt as",
154277   /*  96 */ "selcollist ::= sclp scanpt STAR",
154278   /*  97 */ "selcollist ::= sclp scanpt nm DOT STAR",
154279   /*  98 */ "as ::= AS nm",
154280   /*  99 */ "as ::=",
154281   /* 100 */ "from ::=",
154282   /* 101 */ "from ::= FROM seltablist",
154283   /* 102 */ "stl_prefix ::= seltablist joinop",
154284   /* 103 */ "stl_prefix ::=",
154285   /* 104 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
154286   /* 105 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
154287   /* 106 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
154288   /* 107 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
154289   /* 108 */ "dbnm ::=",
154290   /* 109 */ "dbnm ::= DOT nm",
154291   /* 110 */ "fullname ::= nm",
154292   /* 111 */ "fullname ::= nm DOT nm",
154293   /* 112 */ "xfullname ::= nm",
154294   /* 113 */ "xfullname ::= nm DOT nm",
154295   /* 114 */ "xfullname ::= nm DOT nm AS nm",
154296   /* 115 */ "xfullname ::= nm AS nm",
154297   /* 116 */ "joinop ::= COMMA|JOIN",
154298   /* 117 */ "joinop ::= JOIN_KW JOIN",
154299   /* 118 */ "joinop ::= JOIN_KW nm JOIN",
154300   /* 119 */ "joinop ::= JOIN_KW nm nm JOIN",
154301   /* 120 */ "on_opt ::= ON expr",
154302   /* 121 */ "on_opt ::=",
154303   /* 122 */ "indexed_opt ::=",
154304   /* 123 */ "indexed_opt ::= INDEXED BY nm",
154305   /* 124 */ "indexed_opt ::= NOT INDEXED",
154306   /* 125 */ "using_opt ::= USING LP idlist RP",
154307   /* 126 */ "using_opt ::=",
154308   /* 127 */ "orderby_opt ::=",
154309   /* 128 */ "orderby_opt ::= ORDER BY sortlist",
154310   /* 129 */ "sortlist ::= sortlist COMMA expr sortorder",
154311   /* 130 */ "sortlist ::= expr sortorder",
154312   /* 131 */ "sortorder ::= ASC",
154313   /* 132 */ "sortorder ::= DESC",
154314   /* 133 */ "sortorder ::=",
154315   /* 134 */ "groupby_opt ::=",
154316   /* 135 */ "groupby_opt ::= GROUP BY nexprlist",
154317   /* 136 */ "having_opt ::=",
154318   /* 137 */ "having_opt ::= HAVING expr",
154319   /* 138 */ "limit_opt ::=",
154320   /* 139 */ "limit_opt ::= LIMIT expr",
154321   /* 140 */ "limit_opt ::= LIMIT expr OFFSET expr",
154322   /* 141 */ "limit_opt ::= LIMIT expr COMMA expr",
154323   /* 142 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
154324   /* 143 */ "where_opt ::=",
154325   /* 144 */ "where_opt ::= WHERE expr",
154326   /* 145 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
154327   /* 146 */ "setlist ::= setlist COMMA nm EQ expr",
154328   /* 147 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
154329   /* 148 */ "setlist ::= nm EQ expr",
154330   /* 149 */ "setlist ::= LP idlist RP EQ expr",
154331   /* 150 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
154332   /* 151 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
154333   /* 152 */ "upsert ::=",
154334   /* 153 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
154335   /* 154 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
154336   /* 155 */ "upsert ::= ON CONFLICT DO NOTHING",
154337   /* 156 */ "insert_cmd ::= INSERT orconf",
154338   /* 157 */ "insert_cmd ::= REPLACE",
154339   /* 158 */ "idlist_opt ::=",
154340   /* 159 */ "idlist_opt ::= LP idlist RP",
154341   /* 160 */ "idlist ::= idlist COMMA nm",
154342   /* 161 */ "idlist ::= nm",
154343   /* 162 */ "expr ::= LP expr RP",
154344   /* 163 */ "expr ::= ID|INDEXED",
154345   /* 164 */ "expr ::= JOIN_KW",
154346   /* 165 */ "expr ::= nm DOT nm",
154347   /* 166 */ "expr ::= nm DOT nm DOT nm",
154348   /* 167 */ "term ::= NULL|FLOAT|BLOB",
154349   /* 168 */ "term ::= STRING",
154350   /* 169 */ "term ::= INTEGER",
154351   /* 170 */ "expr ::= VARIABLE",
154352   /* 171 */ "expr ::= expr COLLATE ID|STRING",
154353   /* 172 */ "expr ::= CAST LP expr AS typetoken RP",
154354   /* 173 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
154355   /* 174 */ "expr ::= ID|INDEXED LP STAR RP",
154356   /* 175 */ "expr ::= ID|INDEXED LP distinct exprlist RP over_clause",
154357   /* 176 */ "expr ::= ID|INDEXED LP STAR RP over_clause",
154358   /* 177 */ "term ::= CTIME_KW",
154359   /* 178 */ "expr ::= LP nexprlist COMMA expr RP",
154360   /* 179 */ "expr ::= expr AND expr",
154361   /* 180 */ "expr ::= expr OR expr",
154362   /* 181 */ "expr ::= expr LT|GT|GE|LE expr",
154363   /* 182 */ "expr ::= expr EQ|NE expr",
154364   /* 183 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
154365   /* 184 */ "expr ::= expr PLUS|MINUS expr",
154366   /* 185 */ "expr ::= expr STAR|SLASH|REM expr",
154367   /* 186 */ "expr ::= expr CONCAT expr",
154368   /* 187 */ "likeop ::= NOT LIKE_KW|MATCH",
154369   /* 188 */ "expr ::= expr likeop expr",
154370   /* 189 */ "expr ::= expr likeop expr ESCAPE expr",
154371   /* 190 */ "expr ::= expr ISNULL|NOTNULL",
154372   /* 191 */ "expr ::= expr NOT NULL",
154373   /* 192 */ "expr ::= expr IS expr",
154374   /* 193 */ "expr ::= expr IS NOT expr",
154375   /* 194 */ "expr ::= NOT expr",
154376   /* 195 */ "expr ::= BITNOT expr",
154377   /* 196 */ "expr ::= PLUS|MINUS expr",
154378   /* 197 */ "between_op ::= BETWEEN",
154379   /* 198 */ "between_op ::= NOT BETWEEN",
154380   /* 199 */ "expr ::= expr between_op expr AND expr",
154381   /* 200 */ "in_op ::= IN",
154382   /* 201 */ "in_op ::= NOT IN",
154383   /* 202 */ "expr ::= expr in_op LP exprlist RP",
154384   /* 203 */ "expr ::= LP select RP",
154385   /* 204 */ "expr ::= expr in_op LP select RP",
154386   /* 205 */ "expr ::= expr in_op nm dbnm paren_exprlist",
154387   /* 206 */ "expr ::= EXISTS LP select RP",
154388   /* 207 */ "expr ::= CASE case_operand case_exprlist case_else END",
154389   /* 208 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
154390   /* 209 */ "case_exprlist ::= WHEN expr THEN expr",
154391   /* 210 */ "case_else ::= ELSE expr",
154392   /* 211 */ "case_else ::=",
154393   /* 212 */ "case_operand ::= expr",
154394   /* 213 */ "case_operand ::=",
154395   /* 214 */ "exprlist ::=",
154396   /* 215 */ "nexprlist ::= nexprlist COMMA expr",
154397   /* 216 */ "nexprlist ::= expr",
154398   /* 217 */ "paren_exprlist ::=",
154399   /* 218 */ "paren_exprlist ::= LP exprlist RP",
154400   /* 219 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
154401   /* 220 */ "uniqueflag ::= UNIQUE",
154402   /* 221 */ "uniqueflag ::=",
154403   /* 222 */ "eidlist_opt ::=",
154404   /* 223 */ "eidlist_opt ::= LP eidlist RP",
154405   /* 224 */ "eidlist ::= eidlist COMMA nm collate sortorder",
154406   /* 225 */ "eidlist ::= nm collate sortorder",
154407   /* 226 */ "collate ::=",
154408   /* 227 */ "collate ::= COLLATE ID|STRING",
154409   /* 228 */ "cmd ::= DROP INDEX ifexists fullname",
154410   /* 229 */ "cmd ::= VACUUM vinto",
154411   /* 230 */ "cmd ::= VACUUM nm vinto",
154412   /* 231 */ "vinto ::= INTO expr",
154413   /* 232 */ "vinto ::=",
154414   /* 233 */ "cmd ::= PRAGMA nm dbnm",
154415   /* 234 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
154416   /* 235 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
154417   /* 236 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
154418   /* 237 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
154419   /* 238 */ "plus_num ::= PLUS INTEGER|FLOAT",
154420   /* 239 */ "minus_num ::= MINUS INTEGER|FLOAT",
154421   /* 240 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
154422   /* 241 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
154423   /* 242 */ "trigger_time ::= BEFORE|AFTER",
154424   /* 243 */ "trigger_time ::= INSTEAD OF",
154425   /* 244 */ "trigger_time ::=",
154426   /* 245 */ "trigger_event ::= DELETE|INSERT",
154427   /* 246 */ "trigger_event ::= UPDATE",
154428   /* 247 */ "trigger_event ::= UPDATE OF idlist",
154429   /* 248 */ "when_clause ::=",
154430   /* 249 */ "when_clause ::= WHEN expr",
154431   /* 250 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
154432   /* 251 */ "trigger_cmd_list ::= trigger_cmd SEMI",
154433   /* 252 */ "trnm ::= nm DOT nm",
154434   /* 253 */ "tridxby ::= INDEXED BY nm",
154435   /* 254 */ "tridxby ::= NOT INDEXED",
154436   /* 255 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
154437   /* 256 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
154438   /* 257 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
154439   /* 258 */ "trigger_cmd ::= scanpt select scanpt",
154440   /* 259 */ "expr ::= RAISE LP IGNORE RP",
154441   /* 260 */ "expr ::= RAISE LP raisetype COMMA nm RP",
154442   /* 261 */ "raisetype ::= ROLLBACK",
154443   /* 262 */ "raisetype ::= ABORT",
154444   /* 263 */ "raisetype ::= FAIL",
154445   /* 264 */ "cmd ::= DROP TRIGGER ifexists fullname",
154446   /* 265 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
154447   /* 266 */ "cmd ::= DETACH database_kw_opt expr",
154448   /* 267 */ "key_opt ::=",
154449   /* 268 */ "key_opt ::= KEY expr",
154450   /* 269 */ "cmd ::= REINDEX",
154451   /* 270 */ "cmd ::= REINDEX nm dbnm",
154452   /* 271 */ "cmd ::= ANALYZE",
154453   /* 272 */ "cmd ::= ANALYZE nm dbnm",
154454   /* 273 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
154455   /* 274 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
154456   /* 275 */ "add_column_fullname ::= fullname",
154457   /* 276 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
154458   /* 277 */ "cmd ::= create_vtab",
154459   /* 278 */ "cmd ::= create_vtab LP vtabarglist RP",
154460   /* 279 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
154461   /* 280 */ "vtabarg ::=",
154462   /* 281 */ "vtabargtoken ::= ANY",
154463   /* 282 */ "vtabargtoken ::= lp anylist RP",
154464   /* 283 */ "lp ::= LP",
154465   /* 284 */ "with ::= WITH wqlist",
154466   /* 285 */ "with ::= WITH RECURSIVE wqlist",
154467   /* 286 */ "wqlist ::= nm eidlist_opt AS LP select RP",
154468   /* 287 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
154469   /* 288 */ "windowdefn_list ::= windowdefn",
154470   /* 289 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
154471   /* 290 */ "windowdefn ::= nm AS window",
154472   /* 291 */ "window ::= LP part_opt orderby_opt frame_opt RP",
154473   /* 292 */ "part_opt ::= PARTITION BY nexprlist",
154474   /* 293 */ "part_opt ::=",
154475   /* 294 */ "frame_opt ::=",
154476   /* 295 */ "frame_opt ::= range_or_rows frame_bound_s",
154477   /* 296 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e",
154478   /* 297 */ "range_or_rows ::= RANGE",
154479   /* 298 */ "range_or_rows ::= ROWS",
154480   /* 299 */ "frame_bound_s ::= frame_bound",
154481   /* 300 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
154482   /* 301 */ "frame_bound_e ::= frame_bound",
154483   /* 302 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
154484   /* 303 */ "frame_bound ::= expr PRECEDING",
154485   /* 304 */ "frame_bound ::= CURRENT ROW",
154486   /* 305 */ "frame_bound ::= expr FOLLOWING",
154487   /* 306 */ "window_clause ::= WINDOW windowdefn_list",
154488   /* 307 */ "over_clause ::= filter_opt OVER window",
154489   /* 308 */ "over_clause ::= filter_opt OVER nm",
154490   /* 309 */ "filter_opt ::=",
154491   /* 310 */ "filter_opt ::= FILTER LP WHERE expr RP",
154492   /* 311 */ "input ::= cmdlist",
154493   /* 312 */ "cmdlist ::= cmdlist ecmd",
154494   /* 313 */ "cmdlist ::= ecmd",
154495   /* 314 */ "ecmd ::= SEMI",
154496   /* 315 */ "ecmd ::= cmdx SEMI",
154497   /* 316 */ "ecmd ::= explain cmdx",
154498   /* 317 */ "trans_opt ::=",
154499   /* 318 */ "trans_opt ::= TRANSACTION",
154500   /* 319 */ "trans_opt ::= TRANSACTION nm",
154501   /* 320 */ "savepoint_opt ::= SAVEPOINT",
154502   /* 321 */ "savepoint_opt ::=",
154503   /* 322 */ "cmd ::= create_table create_table_args",
154504   /* 323 */ "columnlist ::= columnlist COMMA columnname carglist",
154505   /* 324 */ "columnlist ::= columnname carglist",
154506   /* 325 */ "nm ::= ID|INDEXED",
154507   /* 326 */ "nm ::= STRING",
154508   /* 327 */ "nm ::= JOIN_KW",
154509   /* 328 */ "typetoken ::= typename",
154510   /* 329 */ "typename ::= ID|STRING",
154511   /* 330 */ "signed ::= plus_num",
154512   /* 331 */ "signed ::= minus_num",
154513   /* 332 */ "carglist ::= carglist ccons",
154514   /* 333 */ "carglist ::=",
154515   /* 334 */ "ccons ::= NULL onconf",
154516   /* 335 */ "conslist_opt ::= COMMA conslist",
154517   /* 336 */ "conslist ::= conslist tconscomma tcons",
154518   /* 337 */ "conslist ::= tcons",
154519   /* 338 */ "tconscomma ::=",
154520   /* 339 */ "defer_subclause_opt ::= defer_subclause",
154521   /* 340 */ "resolvetype ::= raisetype",
154522   /* 341 */ "selectnowith ::= oneselect",
154523   /* 342 */ "oneselect ::= values",
154524   /* 343 */ "sclp ::= selcollist COMMA",
154525   /* 344 */ "as ::= ID|STRING",
154526   /* 345 */ "expr ::= term",
154527   /* 346 */ "likeop ::= LIKE_KW|MATCH",
154528   /* 347 */ "exprlist ::= nexprlist",
154529   /* 348 */ "nmnum ::= plus_num",
154530   /* 349 */ "nmnum ::= nm",
154531   /* 350 */ "nmnum ::= ON",
154532   /* 351 */ "nmnum ::= DELETE",
154533   /* 352 */ "nmnum ::= DEFAULT",
154534   /* 353 */ "plus_num ::= INTEGER|FLOAT",
154535   /* 354 */ "foreach_clause ::=",
154536   /* 355 */ "foreach_clause ::= FOR EACH ROW",
154537   /* 356 */ "trnm ::= nm",
154538   /* 357 */ "tridxby ::=",
154539   /* 358 */ "database_kw_opt ::= DATABASE",
154540   /* 359 */ "database_kw_opt ::=",
154541   /* 360 */ "kwcolumn_opt ::=",
154542   /* 361 */ "kwcolumn_opt ::= COLUMNKW",
154543   /* 362 */ "vtabarglist ::= vtabarg",
154544   /* 363 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
154545   /* 364 */ "vtabarg ::= vtabarg vtabargtoken",
154546   /* 365 */ "anylist ::=",
154547   /* 366 */ "anylist ::= anylist LP anylist RP",
154548   /* 367 */ "anylist ::= anylist ANY",
154549   /* 368 */ "with ::=",
154550  };
154551  #endif /* NDEBUG */
154552  
154553  
154554  #if YYSTACKDEPTH<=0
154555  /*
154556  ** Try to increase the size of the parser stack.  Return the number
154557  ** of errors.  Return 0 on success.
154558  */
154559  static int yyGrowStack(yyParser *p){
154560    int newSize;
154561    int idx;
154562    yyStackEntry *pNew;
154563  
154564    newSize = p->yystksz*2 + 100;
154565    idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
154566    if( p->yystack==&p->yystk0 ){
154567      pNew = malloc(newSize*sizeof(pNew[0]));
154568      if( pNew ) pNew[0] = p->yystk0;
154569    }else{
154570      pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
154571    }
154572    if( pNew ){
154573      p->yystack = pNew;
154574      p->yytos = &p->yystack[idx];
154575  #ifndef NDEBUG
154576      if( yyTraceFILE ){
154577        fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
154578                yyTracePrompt, p->yystksz, newSize);
154579      }
154580  #endif
154581      p->yystksz = newSize;
154582    }
154583    return pNew==0; 
154584  }
154585  #endif
154586  
154587  /* Datatype of the argument to the memory allocated passed as the
154588  ** second argument to sqlite3ParserAlloc() below.  This can be changed by
154589  ** putting an appropriate #define in the %include section of the input
154590  ** grammar.
154591  */
154592  #ifndef YYMALLOCARGTYPE
154593  # define YYMALLOCARGTYPE size_t
154594  #endif
154595  
154596  /* Initialize a new parser that has already been allocated.
154597  */
154598  SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
154599    yyParser *yypParser = (yyParser*)yypRawParser;
154600    sqlite3ParserCTX_STORE
154601  #ifdef YYTRACKMAXSTACKDEPTH
154602    yypParser->yyhwm = 0;
154603  #endif
154604  #if YYSTACKDEPTH<=0
154605    yypParser->yytos = NULL;
154606    yypParser->yystack = NULL;
154607    yypParser->yystksz = 0;
154608    if( yyGrowStack(yypParser) ){
154609      yypParser->yystack = &yypParser->yystk0;
154610      yypParser->yystksz = 1;
154611    }
154612  #endif
154613  #ifndef YYNOERRORRECOVERY
154614    yypParser->yyerrcnt = -1;
154615  #endif
154616    yypParser->yytos = yypParser->yystack;
154617    yypParser->yystack[0].stateno = 0;
154618    yypParser->yystack[0].major = 0;
154619  #if YYSTACKDEPTH>0
154620    yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
154621  #endif
154622  }
154623  
154624  #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
154625  /* 
154626  ** This function allocates a new parser.
154627  ** The only argument is a pointer to a function which works like
154628  ** malloc.
154629  **
154630  ** Inputs:
154631  ** A pointer to the function used to allocate memory.
154632  **
154633  ** Outputs:
154634  ** A pointer to a parser.  This pointer is used in subsequent calls
154635  ** to sqlite3Parser and sqlite3ParserFree.
154636  */
154637  SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
154638    yyParser *yypParser;
154639    yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
154640    if( yypParser ){
154641      sqlite3ParserCTX_STORE
154642      sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
154643    }
154644    return (void*)yypParser;
154645  }
154646  #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
154647  
154648  
154649  /* The following function deletes the "minor type" or semantic value
154650  ** associated with a symbol.  The symbol can be either a terminal
154651  ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
154652  ** a pointer to the value to be deleted.  The code used to do the 
154653  ** deletions is derived from the %destructor and/or %token_destructor
154654  ** directives of the input grammar.
154655  */
154656  static void yy_destructor(
154657    yyParser *yypParser,    /* The parser */
154658    YYCODETYPE yymajor,     /* Type code for object to destroy */
154659    YYMINORTYPE *yypminor   /* The object to be destroyed */
154660  ){
154661    sqlite3ParserARG_FETCH
154662    sqlite3ParserCTX_FETCH
154663    switch( yymajor ){
154664      /* Here is inserted the actions which take place when a
154665      ** terminal or non-terminal is destroyed.  This can happen
154666      ** when the symbol is popped from the stack during a
154667      ** reduce or during error processing or when a parser is 
154668      ** being destroyed before it is finished parsing.
154669      **
154670      ** Note: during a reduce, the only symbols destroyed are those
154671      ** which appear on the RHS of the rule, but which are *not* used
154672      ** inside the C code.
154673      */
154674  /********* Begin destructor definitions ***************************************/
154675      case 174: /* select */
154676      case 206: /* selectnowith */
154677      case 207: /* oneselect */
154678      case 219: /* values */
154679  {
154680  sqlite3SelectDelete(pParse->db, (yypminor->yy423));
154681  }
154682        break;
154683      case 184: /* term */
154684      case 185: /* expr */
154685      case 213: /* where_opt */
154686      case 215: /* having_opt */
154687      case 227: /* on_opt */
154688      case 242: /* case_operand */
154689      case 244: /* case_else */
154690      case 247: /* vinto */
154691      case 254: /* when_clause */
154692      case 259: /* key_opt */
154693      case 273: /* filter_opt */
154694  {
154695  sqlite3ExprDelete(pParse->db, (yypminor->yy490));
154696  }
154697        break;
154698      case 189: /* eidlist_opt */
154699      case 198: /* sortlist */
154700      case 199: /* eidlist */
154701      case 211: /* selcollist */
154702      case 214: /* groupby_opt */
154703      case 216: /* orderby_opt */
154704      case 220: /* nexprlist */
154705      case 221: /* sclp */
154706      case 229: /* exprlist */
154707      case 233: /* setlist */
154708      case 241: /* paren_exprlist */
154709      case 243: /* case_exprlist */
154710      case 272: /* part_opt */
154711  {
154712  sqlite3ExprListDelete(pParse->db, (yypminor->yy42));
154713  }
154714        break;
154715      case 205: /* fullname */
154716      case 212: /* from */
154717      case 223: /* seltablist */
154718      case 224: /* stl_prefix */
154719      case 230: /* xfullname */
154720  {
154721  sqlite3SrcListDelete(pParse->db, (yypminor->yy167));
154722  }
154723        break;
154724      case 208: /* wqlist */
154725  {
154726  sqlite3WithDelete(pParse->db, (yypminor->yy499));
154727  }
154728        break;
154729      case 218: /* window_clause */
154730      case 268: /* windowdefn_list */
154731  {
154732  sqlite3WindowListDelete(pParse->db, (yypminor->yy147));
154733  }
154734        break;
154735      case 228: /* using_opt */
154736      case 231: /* idlist */
154737      case 235: /* idlist_opt */
154738  {
154739  sqlite3IdListDelete(pParse->db, (yypminor->yy336));
154740  }
154741        break;
154742      case 237: /* over_clause */
154743      case 269: /* windowdefn */
154744      case 270: /* window */
154745      case 271: /* frame_opt */
154746  {
154747  sqlite3WindowDelete(pParse->db, (yypminor->yy147));
154748  }
154749        break;
154750      case 250: /* trigger_cmd_list */
154751      case 255: /* trigger_cmd */
154752  {
154753  sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy119));
154754  }
154755        break;
154756      case 252: /* trigger_event */
154757  {
154758  sqlite3IdListDelete(pParse->db, (yypminor->yy350).b);
154759  }
154760        break;
154761      case 275: /* frame_bound */
154762      case 276: /* frame_bound_s */
154763      case 277: /* frame_bound_e */
154764  {
154765  sqlite3ExprDelete(pParse->db, (yypminor->yy317).pExpr);
154766  }
154767        break;
154768  /********* End destructor definitions *****************************************/
154769      default:  break;   /* If no destructor action specified: do nothing */
154770    }
154771  }
154772  
154773  /*
154774  ** Pop the parser's stack once.
154775  **
154776  ** If there is a destructor routine associated with the token which
154777  ** is popped from the stack, then call it.
154778  */
154779  static void yy_pop_parser_stack(yyParser *pParser){
154780    yyStackEntry *yytos;
154781    assert( pParser->yytos!=0 );
154782    assert( pParser->yytos > pParser->yystack );
154783    yytos = pParser->yytos--;
154784  #ifndef NDEBUG
154785    if( yyTraceFILE ){
154786      fprintf(yyTraceFILE,"%sPopping %s\n",
154787        yyTracePrompt,
154788        yyTokenName[yytos->major]);
154789    }
154790  #endif
154791    yy_destructor(pParser, yytos->major, &yytos->minor);
154792  }
154793  
154794  /*
154795  ** Clear all secondary memory allocations from the parser
154796  */
154797  SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
154798    yyParser *pParser = (yyParser*)p;
154799    while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
154800  #if YYSTACKDEPTH<=0
154801    if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
154802  #endif
154803  }
154804  
154805  #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
154806  /* 
154807  ** Deallocate and destroy a parser.  Destructors are called for
154808  ** all stack elements before shutting the parser down.
154809  **
154810  ** If the YYPARSEFREENEVERNULL macro exists (for example because it
154811  ** is defined in a %include section of the input grammar) then it is
154812  ** assumed that the input pointer is never NULL.
154813  */
154814  SQLITE_PRIVATE void sqlite3ParserFree(
154815    void *p,                    /* The parser to be deleted */
154816    void (*freeProc)(void*)     /* Function used to reclaim memory */
154817  ){
154818  #ifndef YYPARSEFREENEVERNULL
154819    if( p==0 ) return;
154820  #endif
154821    sqlite3ParserFinalize(p);
154822    (*freeProc)(p);
154823  }
154824  #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
154825  
154826  /*
154827  ** Return the peak depth of the stack for a parser.
154828  */
154829  #ifdef YYTRACKMAXSTACKDEPTH
154830  SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
154831    yyParser *pParser = (yyParser*)p;
154832    return pParser->yyhwm;
154833  }
154834  #endif
154835  
154836  /* This array of booleans keeps track of the parser statement
154837  ** coverage.  The element yycoverage[X][Y] is set when the parser
154838  ** is in state X and has a lookahead token Y.  In a well-tested
154839  ** systems, every element of this matrix should end up being set.
154840  */
154841  #if defined(YYCOVERAGE)
154842  static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
154843  #endif
154844  
154845  /*
154846  ** Write into out a description of every state/lookahead combination that
154847  **
154848  **   (1)  has not been used by the parser, and
154849  **   (2)  is not a syntax error.
154850  **
154851  ** Return the number of missed state/lookahead combinations.
154852  */
154853  #if defined(YYCOVERAGE)
154854  SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
154855    int stateno, iLookAhead, i;
154856    int nMissed = 0;
154857    for(stateno=0; stateno<YYNSTATE; stateno++){
154858      i = yy_shift_ofst[stateno];
154859      for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
154860        if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
154861        if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
154862        if( out ){
154863          fprintf(out,"State %d lookahead %s %s\n", stateno,
154864                  yyTokenName[iLookAhead],
154865                  yycoverage[stateno][iLookAhead] ? "ok" : "missed");
154866        }
154867      }
154868    }
154869    return nMissed;
154870  }
154871  #endif
154872  
154873  /*
154874  ** Find the appropriate action for a parser given the terminal
154875  ** look-ahead token iLookAhead.
154876  */
154877  static YYACTIONTYPE yy_find_shift_action(
154878    YYCODETYPE iLookAhead,    /* The look-ahead token */
154879    YYACTIONTYPE stateno      /* Current state number */
154880  ){
154881    int i;
154882  
154883    if( stateno>YY_MAX_SHIFT ) return stateno;
154884    assert( stateno <= YY_SHIFT_COUNT );
154885  #if defined(YYCOVERAGE)
154886    yycoverage[stateno][iLookAhead] = 1;
154887  #endif
154888    do{
154889      i = yy_shift_ofst[stateno];
154890      assert( i>=0 );
154891      /* assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); */
154892      assert( iLookAhead!=YYNOCODE );
154893      assert( iLookAhead < YYNTOKEN );
154894      i += iLookAhead;
154895      if( i>=YY_NLOOKAHEAD || yy_lookahead[i]!=iLookAhead ){
154896  #ifdef YYFALLBACK
154897        YYCODETYPE iFallback;            /* Fallback token */
154898        if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
154899               && (iFallback = yyFallback[iLookAhead])!=0 ){
154900  #ifndef NDEBUG
154901          if( yyTraceFILE ){
154902            fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
154903               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
154904          }
154905  #endif
154906          assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
154907          iLookAhead = iFallback;
154908          continue;
154909        }
154910  #endif
154911  #ifdef YYWILDCARD
154912        {
154913          int j = i - iLookAhead + YYWILDCARD;
154914          if( 
154915  #if YY_SHIFT_MIN+YYWILDCARD<0
154916            j>=0 &&
154917  #endif
154918  #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
154919            j<YY_ACTTAB_COUNT &&
154920  #endif
154921            j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) &&
154922            yy_lookahead[j]==YYWILDCARD && iLookAhead>0
154923          ){
154924  #ifndef NDEBUG
154925            if( yyTraceFILE ){
154926              fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
154927                 yyTracePrompt, yyTokenName[iLookAhead],
154928                 yyTokenName[YYWILDCARD]);
154929            }
154930  #endif /* NDEBUG */
154931            return yy_action[j];
154932          }
154933        }
154934  #endif /* YYWILDCARD */
154935        return yy_default[stateno];
154936      }else{
154937        return yy_action[i];
154938      }
154939    }while(1);
154940  }
154941  
154942  /*
154943  ** Find the appropriate action for a parser given the non-terminal
154944  ** look-ahead token iLookAhead.
154945  */
154946  static YYACTIONTYPE yy_find_reduce_action(
154947    YYACTIONTYPE stateno,     /* Current state number */
154948    YYCODETYPE iLookAhead     /* The look-ahead token */
154949  ){
154950    int i;
154951  #ifdef YYERRORSYMBOL
154952    if( stateno>YY_REDUCE_COUNT ){
154953      return yy_default[stateno];
154954    }
154955  #else
154956    assert( stateno<=YY_REDUCE_COUNT );
154957  #endif
154958    i = yy_reduce_ofst[stateno];
154959    assert( iLookAhead!=YYNOCODE );
154960    i += iLookAhead;
154961  #ifdef YYERRORSYMBOL
154962    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
154963      return yy_default[stateno];
154964    }
154965  #else
154966    assert( i>=0 && i<YY_ACTTAB_COUNT );
154967    assert( yy_lookahead[i]==iLookAhead );
154968  #endif
154969    return yy_action[i];
154970  }
154971  
154972  /*
154973  ** The following routine is called if the stack overflows.
154974  */
154975  static void yyStackOverflow(yyParser *yypParser){
154976     sqlite3ParserARG_FETCH
154977     sqlite3ParserCTX_FETCH
154978  #ifndef NDEBUG
154979     if( yyTraceFILE ){
154980       fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
154981     }
154982  #endif
154983     while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
154984     /* Here code is inserted which will execute if the parser
154985     ** stack every overflows */
154986  /******** Begin %stack_overflow code ******************************************/
154987  
154988    sqlite3ErrorMsg(pParse, "parser stack overflow");
154989  /******** End %stack_overflow code ********************************************/
154990     sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
154991     sqlite3ParserCTX_STORE
154992  }
154993  
154994  /*
154995  ** Print tracing information for a SHIFT action
154996  */
154997  #ifndef NDEBUG
154998  static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
154999    if( yyTraceFILE ){
155000      if( yyNewState<YYNSTATE ){
155001        fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
155002           yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
155003           yyNewState);
155004      }else{
155005        fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
155006           yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
155007           yyNewState - YY_MIN_REDUCE);
155008      }
155009    }
155010  }
155011  #else
155012  # define yyTraceShift(X,Y,Z)
155013  #endif
155014  
155015  /*
155016  ** Perform a shift action.
155017  */
155018  static void yy_shift(
155019    yyParser *yypParser,          /* The parser to be shifted */
155020    YYACTIONTYPE yyNewState,      /* The new state to shift in */
155021    YYCODETYPE yyMajor,           /* The major token to shift in */
155022    sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
155023  ){
155024    yyStackEntry *yytos;
155025    yypParser->yytos++;
155026  #ifdef YYTRACKMAXSTACKDEPTH
155027    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
155028      yypParser->yyhwm++;
155029      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
155030    }
155031  #endif
155032  #if YYSTACKDEPTH>0 
155033    if( yypParser->yytos>yypParser->yystackEnd ){
155034      yypParser->yytos--;
155035      yyStackOverflow(yypParser);
155036      return;
155037    }
155038  #else
155039    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
155040      if( yyGrowStack(yypParser) ){
155041        yypParser->yytos--;
155042        yyStackOverflow(yypParser);
155043        return;
155044      }
155045    }
155046  #endif
155047    if( yyNewState > YY_MAX_SHIFT ){
155048      yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
155049    }
155050    yytos = yypParser->yytos;
155051    yytos->stateno = yyNewState;
155052    yytos->major = yyMajor;
155053    yytos->minor.yy0 = yyMinor;
155054    yyTraceShift(yypParser, yyNewState, "Shift");
155055  }
155056  
155057  /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
155058  ** of that rule */
155059  static const YYCODETYPE yyRuleInfoLhs[] = {
155060     159,  /* (0) explain ::= EXPLAIN */
155061     159,  /* (1) explain ::= EXPLAIN QUERY PLAN */
155062     158,  /* (2) cmdx ::= cmd */
155063     160,  /* (3) cmd ::= BEGIN transtype trans_opt */
155064     161,  /* (4) transtype ::= */
155065     161,  /* (5) transtype ::= DEFERRED */
155066     161,  /* (6) transtype ::= IMMEDIATE */
155067     161,  /* (7) transtype ::= EXCLUSIVE */
155068     160,  /* (8) cmd ::= COMMIT|END trans_opt */
155069     160,  /* (9) cmd ::= ROLLBACK trans_opt */
155070     160,  /* (10) cmd ::= SAVEPOINT nm */
155071     160,  /* (11) cmd ::= RELEASE savepoint_opt nm */
155072     160,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
155073     165,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
155074     167,  /* (14) createkw ::= CREATE */
155075     169,  /* (15) ifnotexists ::= */
155076     169,  /* (16) ifnotexists ::= IF NOT EXISTS */
155077     168,  /* (17) temp ::= TEMP */
155078     168,  /* (18) temp ::= */
155079     166,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
155080     166,  /* (20) create_table_args ::= AS select */
155081     173,  /* (21) table_options ::= */
155082     173,  /* (22) table_options ::= WITHOUT nm */
155083     175,  /* (23) columnname ::= nm typetoken */
155084     177,  /* (24) typetoken ::= */
155085     177,  /* (25) typetoken ::= typename LP signed RP */
155086     177,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
155087     178,  /* (27) typename ::= typename ID|STRING */
155088     182,  /* (28) scanpt ::= */
155089     183,  /* (29) ccons ::= CONSTRAINT nm */
155090     183,  /* (30) ccons ::= DEFAULT scanpt term scanpt */
155091     183,  /* (31) ccons ::= DEFAULT LP expr RP */
155092     183,  /* (32) ccons ::= DEFAULT PLUS term scanpt */
155093     183,  /* (33) ccons ::= DEFAULT MINUS term scanpt */
155094     183,  /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
155095     183,  /* (35) ccons ::= NOT NULL onconf */
155096     183,  /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
155097     183,  /* (37) ccons ::= UNIQUE onconf */
155098     183,  /* (38) ccons ::= CHECK LP expr RP */
155099     183,  /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
155100     183,  /* (40) ccons ::= defer_subclause */
155101     183,  /* (41) ccons ::= COLLATE ID|STRING */
155102     188,  /* (42) autoinc ::= */
155103     188,  /* (43) autoinc ::= AUTOINCR */
155104     190,  /* (44) refargs ::= */
155105     190,  /* (45) refargs ::= refargs refarg */
155106     192,  /* (46) refarg ::= MATCH nm */
155107     192,  /* (47) refarg ::= ON INSERT refact */
155108     192,  /* (48) refarg ::= ON DELETE refact */
155109     192,  /* (49) refarg ::= ON UPDATE refact */
155110     193,  /* (50) refact ::= SET NULL */
155111     193,  /* (51) refact ::= SET DEFAULT */
155112     193,  /* (52) refact ::= CASCADE */
155113     193,  /* (53) refact ::= RESTRICT */
155114     193,  /* (54) refact ::= NO ACTION */
155115     191,  /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
155116     191,  /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
155117     194,  /* (57) init_deferred_pred_opt ::= */
155118     194,  /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
155119     194,  /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
155120     172,  /* (60) conslist_opt ::= */
155121     196,  /* (61) tconscomma ::= COMMA */
155122     197,  /* (62) tcons ::= CONSTRAINT nm */
155123     197,  /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
155124     197,  /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
155125     197,  /* (65) tcons ::= CHECK LP expr RP onconf */
155126     197,  /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
155127     200,  /* (67) defer_subclause_opt ::= */
155128     186,  /* (68) onconf ::= */
155129     186,  /* (69) onconf ::= ON CONFLICT resolvetype */
155130     201,  /* (70) orconf ::= */
155131     201,  /* (71) orconf ::= OR resolvetype */
155132     202,  /* (72) resolvetype ::= IGNORE */
155133     202,  /* (73) resolvetype ::= REPLACE */
155134     160,  /* (74) cmd ::= DROP TABLE ifexists fullname */
155135     204,  /* (75) ifexists ::= IF EXISTS */
155136     204,  /* (76) ifexists ::= */
155137     160,  /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
155138     160,  /* (78) cmd ::= DROP VIEW ifexists fullname */
155139     160,  /* (79) cmd ::= select */
155140     174,  /* (80) select ::= WITH wqlist selectnowith */
155141     174,  /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
155142     174,  /* (82) select ::= selectnowith */
155143     206,  /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
155144     209,  /* (84) multiselect_op ::= UNION */
155145     209,  /* (85) multiselect_op ::= UNION ALL */
155146     209,  /* (86) multiselect_op ::= EXCEPT|INTERSECT */
155147     207,  /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
155148     207,  /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
155149     219,  /* (89) values ::= VALUES LP nexprlist RP */
155150     219,  /* (90) values ::= values COMMA LP nexprlist RP */
155151     210,  /* (91) distinct ::= DISTINCT */
155152     210,  /* (92) distinct ::= ALL */
155153     210,  /* (93) distinct ::= */
155154     221,  /* (94) sclp ::= */
155155     211,  /* (95) selcollist ::= sclp scanpt expr scanpt as */
155156     211,  /* (96) selcollist ::= sclp scanpt STAR */
155157     211,  /* (97) selcollist ::= sclp scanpt nm DOT STAR */
155158     222,  /* (98) as ::= AS nm */
155159     222,  /* (99) as ::= */
155160     212,  /* (100) from ::= */
155161     212,  /* (101) from ::= FROM seltablist */
155162     224,  /* (102) stl_prefix ::= seltablist joinop */
155163     224,  /* (103) stl_prefix ::= */
155164     223,  /* (104) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
155165     223,  /* (105) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
155166     223,  /* (106) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
155167     223,  /* (107) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
155168     170,  /* (108) dbnm ::= */
155169     170,  /* (109) dbnm ::= DOT nm */
155170     205,  /* (110) fullname ::= nm */
155171     205,  /* (111) fullname ::= nm DOT nm */
155172     230,  /* (112) xfullname ::= nm */
155173     230,  /* (113) xfullname ::= nm DOT nm */
155174     230,  /* (114) xfullname ::= nm DOT nm AS nm */
155175     230,  /* (115) xfullname ::= nm AS nm */
155176     225,  /* (116) joinop ::= COMMA|JOIN */
155177     225,  /* (117) joinop ::= JOIN_KW JOIN */
155178     225,  /* (118) joinop ::= JOIN_KW nm JOIN */
155179     225,  /* (119) joinop ::= JOIN_KW nm nm JOIN */
155180     227,  /* (120) on_opt ::= ON expr */
155181     227,  /* (121) on_opt ::= */
155182     226,  /* (122) indexed_opt ::= */
155183     226,  /* (123) indexed_opt ::= INDEXED BY nm */
155184     226,  /* (124) indexed_opt ::= NOT INDEXED */
155185     228,  /* (125) using_opt ::= USING LP idlist RP */
155186     228,  /* (126) using_opt ::= */
155187     216,  /* (127) orderby_opt ::= */
155188     216,  /* (128) orderby_opt ::= ORDER BY sortlist */
155189     198,  /* (129) sortlist ::= sortlist COMMA expr sortorder */
155190     198,  /* (130) sortlist ::= expr sortorder */
155191     187,  /* (131) sortorder ::= ASC */
155192     187,  /* (132) sortorder ::= DESC */
155193     187,  /* (133) sortorder ::= */
155194     214,  /* (134) groupby_opt ::= */
155195     214,  /* (135) groupby_opt ::= GROUP BY nexprlist */
155196     215,  /* (136) having_opt ::= */
155197     215,  /* (137) having_opt ::= HAVING expr */
155198     217,  /* (138) limit_opt ::= */
155199     217,  /* (139) limit_opt ::= LIMIT expr */
155200     217,  /* (140) limit_opt ::= LIMIT expr OFFSET expr */
155201     217,  /* (141) limit_opt ::= LIMIT expr COMMA expr */
155202     160,  /* (142) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
155203     213,  /* (143) where_opt ::= */
155204     213,  /* (144) where_opt ::= WHERE expr */
155205     160,  /* (145) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
155206     233,  /* (146) setlist ::= setlist COMMA nm EQ expr */
155207     233,  /* (147) setlist ::= setlist COMMA LP idlist RP EQ expr */
155208     233,  /* (148) setlist ::= nm EQ expr */
155209     233,  /* (149) setlist ::= LP idlist RP EQ expr */
155210     160,  /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
155211     160,  /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
155212     236,  /* (152) upsert ::= */
155213     236,  /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
155214     236,  /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
155215     236,  /* (155) upsert ::= ON CONFLICT DO NOTHING */
155216     234,  /* (156) insert_cmd ::= INSERT orconf */
155217     234,  /* (157) insert_cmd ::= REPLACE */
155218     235,  /* (158) idlist_opt ::= */
155219     235,  /* (159) idlist_opt ::= LP idlist RP */
155220     231,  /* (160) idlist ::= idlist COMMA nm */
155221     231,  /* (161) idlist ::= nm */
155222     185,  /* (162) expr ::= LP expr RP */
155223     185,  /* (163) expr ::= ID|INDEXED */
155224     185,  /* (164) expr ::= JOIN_KW */
155225     185,  /* (165) expr ::= nm DOT nm */
155226     185,  /* (166) expr ::= nm DOT nm DOT nm */
155227     184,  /* (167) term ::= NULL|FLOAT|BLOB */
155228     184,  /* (168) term ::= STRING */
155229     184,  /* (169) term ::= INTEGER */
155230     185,  /* (170) expr ::= VARIABLE */
155231     185,  /* (171) expr ::= expr COLLATE ID|STRING */
155232     185,  /* (172) expr ::= CAST LP expr AS typetoken RP */
155233     185,  /* (173) expr ::= ID|INDEXED LP distinct exprlist RP */
155234     185,  /* (174) expr ::= ID|INDEXED LP STAR RP */
155235     185,  /* (175) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
155236     185,  /* (176) expr ::= ID|INDEXED LP STAR RP over_clause */
155237     184,  /* (177) term ::= CTIME_KW */
155238     185,  /* (178) expr ::= LP nexprlist COMMA expr RP */
155239     185,  /* (179) expr ::= expr AND expr */
155240     185,  /* (180) expr ::= expr OR expr */
155241     185,  /* (181) expr ::= expr LT|GT|GE|LE expr */
155242     185,  /* (182) expr ::= expr EQ|NE expr */
155243     185,  /* (183) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
155244     185,  /* (184) expr ::= expr PLUS|MINUS expr */
155245     185,  /* (185) expr ::= expr STAR|SLASH|REM expr */
155246     185,  /* (186) expr ::= expr CONCAT expr */
155247     238,  /* (187) likeop ::= NOT LIKE_KW|MATCH */
155248     185,  /* (188) expr ::= expr likeop expr */
155249     185,  /* (189) expr ::= expr likeop expr ESCAPE expr */
155250     185,  /* (190) expr ::= expr ISNULL|NOTNULL */
155251     185,  /* (191) expr ::= expr NOT NULL */
155252     185,  /* (192) expr ::= expr IS expr */
155253     185,  /* (193) expr ::= expr IS NOT expr */
155254     185,  /* (194) expr ::= NOT expr */
155255     185,  /* (195) expr ::= BITNOT expr */
155256     185,  /* (196) expr ::= PLUS|MINUS expr */
155257     239,  /* (197) between_op ::= BETWEEN */
155258     239,  /* (198) between_op ::= NOT BETWEEN */
155259     185,  /* (199) expr ::= expr between_op expr AND expr */
155260     240,  /* (200) in_op ::= IN */
155261     240,  /* (201) in_op ::= NOT IN */
155262     185,  /* (202) expr ::= expr in_op LP exprlist RP */
155263     185,  /* (203) expr ::= LP select RP */
155264     185,  /* (204) expr ::= expr in_op LP select RP */
155265     185,  /* (205) expr ::= expr in_op nm dbnm paren_exprlist */
155266     185,  /* (206) expr ::= EXISTS LP select RP */
155267     185,  /* (207) expr ::= CASE case_operand case_exprlist case_else END */
155268     243,  /* (208) case_exprlist ::= case_exprlist WHEN expr THEN expr */
155269     243,  /* (209) case_exprlist ::= WHEN expr THEN expr */
155270     244,  /* (210) case_else ::= ELSE expr */
155271     244,  /* (211) case_else ::= */
155272     242,  /* (212) case_operand ::= expr */
155273     242,  /* (213) case_operand ::= */
155274     229,  /* (214) exprlist ::= */
155275     220,  /* (215) nexprlist ::= nexprlist COMMA expr */
155276     220,  /* (216) nexprlist ::= expr */
155277     241,  /* (217) paren_exprlist ::= */
155278     241,  /* (218) paren_exprlist ::= LP exprlist RP */
155279     160,  /* (219) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
155280     245,  /* (220) uniqueflag ::= UNIQUE */
155281     245,  /* (221) uniqueflag ::= */
155282     189,  /* (222) eidlist_opt ::= */
155283     189,  /* (223) eidlist_opt ::= LP eidlist RP */
155284     199,  /* (224) eidlist ::= eidlist COMMA nm collate sortorder */
155285     199,  /* (225) eidlist ::= nm collate sortorder */
155286     246,  /* (226) collate ::= */
155287     246,  /* (227) collate ::= COLLATE ID|STRING */
155288     160,  /* (228) cmd ::= DROP INDEX ifexists fullname */
155289     160,  /* (229) cmd ::= VACUUM vinto */
155290     160,  /* (230) cmd ::= VACUUM nm vinto */
155291     247,  /* (231) vinto ::= INTO expr */
155292     247,  /* (232) vinto ::= */
155293     160,  /* (233) cmd ::= PRAGMA nm dbnm */
155294     160,  /* (234) cmd ::= PRAGMA nm dbnm EQ nmnum */
155295     160,  /* (235) cmd ::= PRAGMA nm dbnm LP nmnum RP */
155296     160,  /* (236) cmd ::= PRAGMA nm dbnm EQ minus_num */
155297     160,  /* (237) cmd ::= PRAGMA nm dbnm LP minus_num RP */
155298     180,  /* (238) plus_num ::= PLUS INTEGER|FLOAT */
155299     181,  /* (239) minus_num ::= MINUS INTEGER|FLOAT */
155300     160,  /* (240) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
155301     249,  /* (241) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
155302     251,  /* (242) trigger_time ::= BEFORE|AFTER */
155303     251,  /* (243) trigger_time ::= INSTEAD OF */
155304     251,  /* (244) trigger_time ::= */
155305     252,  /* (245) trigger_event ::= DELETE|INSERT */
155306     252,  /* (246) trigger_event ::= UPDATE */
155307     252,  /* (247) trigger_event ::= UPDATE OF idlist */
155308     254,  /* (248) when_clause ::= */
155309     254,  /* (249) when_clause ::= WHEN expr */
155310     250,  /* (250) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
155311     250,  /* (251) trigger_cmd_list ::= trigger_cmd SEMI */
155312     256,  /* (252) trnm ::= nm DOT nm */
155313     257,  /* (253) tridxby ::= INDEXED BY nm */
155314     257,  /* (254) tridxby ::= NOT INDEXED */
155315     255,  /* (255) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
155316     255,  /* (256) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
155317     255,  /* (257) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
155318     255,  /* (258) trigger_cmd ::= scanpt select scanpt */
155319     185,  /* (259) expr ::= RAISE LP IGNORE RP */
155320     185,  /* (260) expr ::= RAISE LP raisetype COMMA nm RP */
155321     203,  /* (261) raisetype ::= ROLLBACK */
155322     203,  /* (262) raisetype ::= ABORT */
155323     203,  /* (263) raisetype ::= FAIL */
155324     160,  /* (264) cmd ::= DROP TRIGGER ifexists fullname */
155325     160,  /* (265) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
155326     160,  /* (266) cmd ::= DETACH database_kw_opt expr */
155327     259,  /* (267) key_opt ::= */
155328     259,  /* (268) key_opt ::= KEY expr */
155329     160,  /* (269) cmd ::= REINDEX */
155330     160,  /* (270) cmd ::= REINDEX nm dbnm */
155331     160,  /* (271) cmd ::= ANALYZE */
155332     160,  /* (272) cmd ::= ANALYZE nm dbnm */
155333     160,  /* (273) cmd ::= ALTER TABLE fullname RENAME TO nm */
155334     160,  /* (274) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
155335     260,  /* (275) add_column_fullname ::= fullname */
155336     160,  /* (276) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
155337     160,  /* (277) cmd ::= create_vtab */
155338     160,  /* (278) cmd ::= create_vtab LP vtabarglist RP */
155339     262,  /* (279) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
155340     264,  /* (280) vtabarg ::= */
155341     265,  /* (281) vtabargtoken ::= ANY */
155342     265,  /* (282) vtabargtoken ::= lp anylist RP */
155343     266,  /* (283) lp ::= LP */
155344     232,  /* (284) with ::= WITH wqlist */
155345     232,  /* (285) with ::= WITH RECURSIVE wqlist */
155346     208,  /* (286) wqlist ::= nm eidlist_opt AS LP select RP */
155347     208,  /* (287) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
155348     268,  /* (288) windowdefn_list ::= windowdefn */
155349     268,  /* (289) windowdefn_list ::= windowdefn_list COMMA windowdefn */
155350     269,  /* (290) windowdefn ::= nm AS window */
155351     270,  /* (291) window ::= LP part_opt orderby_opt frame_opt RP */
155352     272,  /* (292) part_opt ::= PARTITION BY nexprlist */
155353     272,  /* (293) part_opt ::= */
155354     271,  /* (294) frame_opt ::= */
155355     271,  /* (295) frame_opt ::= range_or_rows frame_bound_s */
155356     271,  /* (296) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e */
155357     274,  /* (297) range_or_rows ::= RANGE */
155358     274,  /* (298) range_or_rows ::= ROWS */
155359     276,  /* (299) frame_bound_s ::= frame_bound */
155360     276,  /* (300) frame_bound_s ::= UNBOUNDED PRECEDING */
155361     277,  /* (301) frame_bound_e ::= frame_bound */
155362     277,  /* (302) frame_bound_e ::= UNBOUNDED FOLLOWING */
155363     275,  /* (303) frame_bound ::= expr PRECEDING */
155364     275,  /* (304) frame_bound ::= CURRENT ROW */
155365     275,  /* (305) frame_bound ::= expr FOLLOWING */
155366     218,  /* (306) window_clause ::= WINDOW windowdefn_list */
155367     237,  /* (307) over_clause ::= filter_opt OVER window */
155368     237,  /* (308) over_clause ::= filter_opt OVER nm */
155369     273,  /* (309) filter_opt ::= */
155370     273,  /* (310) filter_opt ::= FILTER LP WHERE expr RP */
155371     155,  /* (311) input ::= cmdlist */
155372     156,  /* (312) cmdlist ::= cmdlist ecmd */
155373     156,  /* (313) cmdlist ::= ecmd */
155374     157,  /* (314) ecmd ::= SEMI */
155375     157,  /* (315) ecmd ::= cmdx SEMI */
155376     157,  /* (316) ecmd ::= explain cmdx */
155377     162,  /* (317) trans_opt ::= */
155378     162,  /* (318) trans_opt ::= TRANSACTION */
155379     162,  /* (319) trans_opt ::= TRANSACTION nm */
155380     164,  /* (320) savepoint_opt ::= SAVEPOINT */
155381     164,  /* (321) savepoint_opt ::= */
155382     160,  /* (322) cmd ::= create_table create_table_args */
155383     171,  /* (323) columnlist ::= columnlist COMMA columnname carglist */
155384     171,  /* (324) columnlist ::= columnname carglist */
155385     163,  /* (325) nm ::= ID|INDEXED */
155386     163,  /* (326) nm ::= STRING */
155387     163,  /* (327) nm ::= JOIN_KW */
155388     177,  /* (328) typetoken ::= typename */
155389     178,  /* (329) typename ::= ID|STRING */
155390     179,  /* (330) signed ::= plus_num */
155391     179,  /* (331) signed ::= minus_num */
155392     176,  /* (332) carglist ::= carglist ccons */
155393     176,  /* (333) carglist ::= */
155394     183,  /* (334) ccons ::= NULL onconf */
155395     172,  /* (335) conslist_opt ::= COMMA conslist */
155396     195,  /* (336) conslist ::= conslist tconscomma tcons */
155397     195,  /* (337) conslist ::= tcons */
155398     196,  /* (338) tconscomma ::= */
155399     200,  /* (339) defer_subclause_opt ::= defer_subclause */
155400     202,  /* (340) resolvetype ::= raisetype */
155401     206,  /* (341) selectnowith ::= oneselect */
155402     207,  /* (342) oneselect ::= values */
155403     221,  /* (343) sclp ::= selcollist COMMA */
155404     222,  /* (344) as ::= ID|STRING */
155405     185,  /* (345) expr ::= term */
155406     238,  /* (346) likeop ::= LIKE_KW|MATCH */
155407     229,  /* (347) exprlist ::= nexprlist */
155408     248,  /* (348) nmnum ::= plus_num */
155409     248,  /* (349) nmnum ::= nm */
155410     248,  /* (350) nmnum ::= ON */
155411     248,  /* (351) nmnum ::= DELETE */
155412     248,  /* (352) nmnum ::= DEFAULT */
155413     180,  /* (353) plus_num ::= INTEGER|FLOAT */
155414     253,  /* (354) foreach_clause ::= */
155415     253,  /* (355) foreach_clause ::= FOR EACH ROW */
155416     256,  /* (356) trnm ::= nm */
155417     257,  /* (357) tridxby ::= */
155418     258,  /* (358) database_kw_opt ::= DATABASE */
155419     258,  /* (359) database_kw_opt ::= */
155420     261,  /* (360) kwcolumn_opt ::= */
155421     261,  /* (361) kwcolumn_opt ::= COLUMNKW */
155422     263,  /* (362) vtabarglist ::= vtabarg */
155423     263,  /* (363) vtabarglist ::= vtabarglist COMMA vtabarg */
155424     264,  /* (364) vtabarg ::= vtabarg vtabargtoken */
155425     267,  /* (365) anylist ::= */
155426     267,  /* (366) anylist ::= anylist LP anylist RP */
155427     267,  /* (367) anylist ::= anylist ANY */
155428     232,  /* (368) with ::= */
155429  };
155430  
155431  /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
155432  ** of symbols on the right-hand side of that rule. */
155433  static const signed char yyRuleInfoNRhs[] = {
155434     -1,  /* (0) explain ::= EXPLAIN */
155435     -3,  /* (1) explain ::= EXPLAIN QUERY PLAN */
155436     -1,  /* (2) cmdx ::= cmd */
155437     -3,  /* (3) cmd ::= BEGIN transtype trans_opt */
155438      0,  /* (4) transtype ::= */
155439     -1,  /* (5) transtype ::= DEFERRED */
155440     -1,  /* (6) transtype ::= IMMEDIATE */
155441     -1,  /* (7) transtype ::= EXCLUSIVE */
155442     -2,  /* (8) cmd ::= COMMIT|END trans_opt */
155443     -2,  /* (9) cmd ::= ROLLBACK trans_opt */
155444     -2,  /* (10) cmd ::= SAVEPOINT nm */
155445     -3,  /* (11) cmd ::= RELEASE savepoint_opt nm */
155446     -5,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
155447     -6,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
155448     -1,  /* (14) createkw ::= CREATE */
155449      0,  /* (15) ifnotexists ::= */
155450     -3,  /* (16) ifnotexists ::= IF NOT EXISTS */
155451     -1,  /* (17) temp ::= TEMP */
155452      0,  /* (18) temp ::= */
155453     -5,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
155454     -2,  /* (20) create_table_args ::= AS select */
155455      0,  /* (21) table_options ::= */
155456     -2,  /* (22) table_options ::= WITHOUT nm */
155457     -2,  /* (23) columnname ::= nm typetoken */
155458      0,  /* (24) typetoken ::= */
155459     -4,  /* (25) typetoken ::= typename LP signed RP */
155460     -6,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
155461     -2,  /* (27) typename ::= typename ID|STRING */
155462      0,  /* (28) scanpt ::= */
155463     -2,  /* (29) ccons ::= CONSTRAINT nm */
155464     -4,  /* (30) ccons ::= DEFAULT scanpt term scanpt */
155465     -4,  /* (31) ccons ::= DEFAULT LP expr RP */
155466     -4,  /* (32) ccons ::= DEFAULT PLUS term scanpt */
155467     -4,  /* (33) ccons ::= DEFAULT MINUS term scanpt */
155468     -3,  /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
155469     -3,  /* (35) ccons ::= NOT NULL onconf */
155470     -5,  /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
155471     -2,  /* (37) ccons ::= UNIQUE onconf */
155472     -4,  /* (38) ccons ::= CHECK LP expr RP */
155473     -4,  /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
155474     -1,  /* (40) ccons ::= defer_subclause */
155475     -2,  /* (41) ccons ::= COLLATE ID|STRING */
155476      0,  /* (42) autoinc ::= */
155477     -1,  /* (43) autoinc ::= AUTOINCR */
155478      0,  /* (44) refargs ::= */
155479     -2,  /* (45) refargs ::= refargs refarg */
155480     -2,  /* (46) refarg ::= MATCH nm */
155481     -3,  /* (47) refarg ::= ON INSERT refact */
155482     -3,  /* (48) refarg ::= ON DELETE refact */
155483     -3,  /* (49) refarg ::= ON UPDATE refact */
155484     -2,  /* (50) refact ::= SET NULL */
155485     -2,  /* (51) refact ::= SET DEFAULT */
155486     -1,  /* (52) refact ::= CASCADE */
155487     -1,  /* (53) refact ::= RESTRICT */
155488     -2,  /* (54) refact ::= NO ACTION */
155489     -3,  /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
155490     -2,  /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
155491      0,  /* (57) init_deferred_pred_opt ::= */
155492     -2,  /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
155493     -2,  /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
155494      0,  /* (60) conslist_opt ::= */
155495     -1,  /* (61) tconscomma ::= COMMA */
155496     -2,  /* (62) tcons ::= CONSTRAINT nm */
155497     -7,  /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
155498     -5,  /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
155499     -5,  /* (65) tcons ::= CHECK LP expr RP onconf */
155500    -10,  /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
155501      0,  /* (67) defer_subclause_opt ::= */
155502      0,  /* (68) onconf ::= */
155503     -3,  /* (69) onconf ::= ON CONFLICT resolvetype */
155504      0,  /* (70) orconf ::= */
155505     -2,  /* (71) orconf ::= OR resolvetype */
155506     -1,  /* (72) resolvetype ::= IGNORE */
155507     -1,  /* (73) resolvetype ::= REPLACE */
155508     -4,  /* (74) cmd ::= DROP TABLE ifexists fullname */
155509     -2,  /* (75) ifexists ::= IF EXISTS */
155510      0,  /* (76) ifexists ::= */
155511     -9,  /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
155512     -4,  /* (78) cmd ::= DROP VIEW ifexists fullname */
155513     -1,  /* (79) cmd ::= select */
155514     -3,  /* (80) select ::= WITH wqlist selectnowith */
155515     -4,  /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
155516     -1,  /* (82) select ::= selectnowith */
155517     -3,  /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
155518     -1,  /* (84) multiselect_op ::= UNION */
155519     -2,  /* (85) multiselect_op ::= UNION ALL */
155520     -1,  /* (86) multiselect_op ::= EXCEPT|INTERSECT */
155521     -9,  /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
155522    -10,  /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
155523     -4,  /* (89) values ::= VALUES LP nexprlist RP */
155524     -5,  /* (90) values ::= values COMMA LP nexprlist RP */
155525     -1,  /* (91) distinct ::= DISTINCT */
155526     -1,  /* (92) distinct ::= ALL */
155527      0,  /* (93) distinct ::= */
155528      0,  /* (94) sclp ::= */
155529     -5,  /* (95) selcollist ::= sclp scanpt expr scanpt as */
155530     -3,  /* (96) selcollist ::= sclp scanpt STAR */
155531     -5,  /* (97) selcollist ::= sclp scanpt nm DOT STAR */
155532     -2,  /* (98) as ::= AS nm */
155533      0,  /* (99) as ::= */
155534      0,  /* (100) from ::= */
155535     -2,  /* (101) from ::= FROM seltablist */
155536     -2,  /* (102) stl_prefix ::= seltablist joinop */
155537      0,  /* (103) stl_prefix ::= */
155538     -7,  /* (104) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
155539     -9,  /* (105) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
155540     -7,  /* (106) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
155541     -7,  /* (107) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
155542      0,  /* (108) dbnm ::= */
155543     -2,  /* (109) dbnm ::= DOT nm */
155544     -1,  /* (110) fullname ::= nm */
155545     -3,  /* (111) fullname ::= nm DOT nm */
155546     -1,  /* (112) xfullname ::= nm */
155547     -3,  /* (113) xfullname ::= nm DOT nm */
155548     -5,  /* (114) xfullname ::= nm DOT nm AS nm */
155549     -3,  /* (115) xfullname ::= nm AS nm */
155550     -1,  /* (116) joinop ::= COMMA|JOIN */
155551     -2,  /* (117) joinop ::= JOIN_KW JOIN */
155552     -3,  /* (118) joinop ::= JOIN_KW nm JOIN */
155553     -4,  /* (119) joinop ::= JOIN_KW nm nm JOIN */
155554     -2,  /* (120) on_opt ::= ON expr */
155555      0,  /* (121) on_opt ::= */
155556      0,  /* (122) indexed_opt ::= */
155557     -3,  /* (123) indexed_opt ::= INDEXED BY nm */
155558     -2,  /* (124) indexed_opt ::= NOT INDEXED */
155559     -4,  /* (125) using_opt ::= USING LP idlist RP */
155560      0,  /* (126) using_opt ::= */
155561      0,  /* (127) orderby_opt ::= */
155562     -3,  /* (128) orderby_opt ::= ORDER BY sortlist */
155563     -4,  /* (129) sortlist ::= sortlist COMMA expr sortorder */
155564     -2,  /* (130) sortlist ::= expr sortorder */
155565     -1,  /* (131) sortorder ::= ASC */
155566     -1,  /* (132) sortorder ::= DESC */
155567      0,  /* (133) sortorder ::= */
155568      0,  /* (134) groupby_opt ::= */
155569     -3,  /* (135) groupby_opt ::= GROUP BY nexprlist */
155570      0,  /* (136) having_opt ::= */
155571     -2,  /* (137) having_opt ::= HAVING expr */
155572      0,  /* (138) limit_opt ::= */
155573     -2,  /* (139) limit_opt ::= LIMIT expr */
155574     -4,  /* (140) limit_opt ::= LIMIT expr OFFSET expr */
155575     -4,  /* (141) limit_opt ::= LIMIT expr COMMA expr */
155576     -6,  /* (142) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
155577      0,  /* (143) where_opt ::= */
155578     -2,  /* (144) where_opt ::= WHERE expr */
155579     -8,  /* (145) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
155580     -5,  /* (146) setlist ::= setlist COMMA nm EQ expr */
155581     -7,  /* (147) setlist ::= setlist COMMA LP idlist RP EQ expr */
155582     -3,  /* (148) setlist ::= nm EQ expr */
155583     -5,  /* (149) setlist ::= LP idlist RP EQ expr */
155584     -7,  /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
155585     -7,  /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
155586      0,  /* (152) upsert ::= */
155587    -11,  /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
155588     -8,  /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
155589     -4,  /* (155) upsert ::= ON CONFLICT DO NOTHING */
155590     -2,  /* (156) insert_cmd ::= INSERT orconf */
155591     -1,  /* (157) insert_cmd ::= REPLACE */
155592      0,  /* (158) idlist_opt ::= */
155593     -3,  /* (159) idlist_opt ::= LP idlist RP */
155594     -3,  /* (160) idlist ::= idlist COMMA nm */
155595     -1,  /* (161) idlist ::= nm */
155596     -3,  /* (162) expr ::= LP expr RP */
155597     -1,  /* (163) expr ::= ID|INDEXED */
155598     -1,  /* (164) expr ::= JOIN_KW */
155599     -3,  /* (165) expr ::= nm DOT nm */
155600     -5,  /* (166) expr ::= nm DOT nm DOT nm */
155601     -1,  /* (167) term ::= NULL|FLOAT|BLOB */
155602     -1,  /* (168) term ::= STRING */
155603     -1,  /* (169) term ::= INTEGER */
155604     -1,  /* (170) expr ::= VARIABLE */
155605     -3,  /* (171) expr ::= expr COLLATE ID|STRING */
155606     -6,  /* (172) expr ::= CAST LP expr AS typetoken RP */
155607     -5,  /* (173) expr ::= ID|INDEXED LP distinct exprlist RP */
155608     -4,  /* (174) expr ::= ID|INDEXED LP STAR RP */
155609     -6,  /* (175) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
155610     -5,  /* (176) expr ::= ID|INDEXED LP STAR RP over_clause */
155611     -1,  /* (177) term ::= CTIME_KW */
155612     -5,  /* (178) expr ::= LP nexprlist COMMA expr RP */
155613     -3,  /* (179) expr ::= expr AND expr */
155614     -3,  /* (180) expr ::= expr OR expr */
155615     -3,  /* (181) expr ::= expr LT|GT|GE|LE expr */
155616     -3,  /* (182) expr ::= expr EQ|NE expr */
155617     -3,  /* (183) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
155618     -3,  /* (184) expr ::= expr PLUS|MINUS expr */
155619     -3,  /* (185) expr ::= expr STAR|SLASH|REM expr */
155620     -3,  /* (186) expr ::= expr CONCAT expr */
155621     -2,  /* (187) likeop ::= NOT LIKE_KW|MATCH */
155622     -3,  /* (188) expr ::= expr likeop expr */
155623     -5,  /* (189) expr ::= expr likeop expr ESCAPE expr */
155624     -2,  /* (190) expr ::= expr ISNULL|NOTNULL */
155625     -3,  /* (191) expr ::= expr NOT NULL */
155626     -3,  /* (192) expr ::= expr IS expr */
155627     -4,  /* (193) expr ::= expr IS NOT expr */
155628     -2,  /* (194) expr ::= NOT expr */
155629     -2,  /* (195) expr ::= BITNOT expr */
155630     -2,  /* (196) expr ::= PLUS|MINUS expr */
155631     -1,  /* (197) between_op ::= BETWEEN */
155632     -2,  /* (198) between_op ::= NOT BETWEEN */
155633     -5,  /* (199) expr ::= expr between_op expr AND expr */
155634     -1,  /* (200) in_op ::= IN */
155635     -2,  /* (201) in_op ::= NOT IN */
155636     -5,  /* (202) expr ::= expr in_op LP exprlist RP */
155637     -3,  /* (203) expr ::= LP select RP */
155638     -5,  /* (204) expr ::= expr in_op LP select RP */
155639     -5,  /* (205) expr ::= expr in_op nm dbnm paren_exprlist */
155640     -4,  /* (206) expr ::= EXISTS LP select RP */
155641     -5,  /* (207) expr ::= CASE case_operand case_exprlist case_else END */
155642     -5,  /* (208) case_exprlist ::= case_exprlist WHEN expr THEN expr */
155643     -4,  /* (209) case_exprlist ::= WHEN expr THEN expr */
155644     -2,  /* (210) case_else ::= ELSE expr */
155645      0,  /* (211) case_else ::= */
155646     -1,  /* (212) case_operand ::= expr */
155647      0,  /* (213) case_operand ::= */
155648      0,  /* (214) exprlist ::= */
155649     -3,  /* (215) nexprlist ::= nexprlist COMMA expr */
155650     -1,  /* (216) nexprlist ::= expr */
155651      0,  /* (217) paren_exprlist ::= */
155652     -3,  /* (218) paren_exprlist ::= LP exprlist RP */
155653    -12,  /* (219) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
155654     -1,  /* (220) uniqueflag ::= UNIQUE */
155655      0,  /* (221) uniqueflag ::= */
155656      0,  /* (222) eidlist_opt ::= */
155657     -3,  /* (223) eidlist_opt ::= LP eidlist RP */
155658     -5,  /* (224) eidlist ::= eidlist COMMA nm collate sortorder */
155659     -3,  /* (225) eidlist ::= nm collate sortorder */
155660      0,  /* (226) collate ::= */
155661     -2,  /* (227) collate ::= COLLATE ID|STRING */
155662     -4,  /* (228) cmd ::= DROP INDEX ifexists fullname */
155663     -2,  /* (229) cmd ::= VACUUM vinto */
155664     -3,  /* (230) cmd ::= VACUUM nm vinto */
155665     -2,  /* (231) vinto ::= INTO expr */
155666      0,  /* (232) vinto ::= */
155667     -3,  /* (233) cmd ::= PRAGMA nm dbnm */
155668     -5,  /* (234) cmd ::= PRAGMA nm dbnm EQ nmnum */
155669     -6,  /* (235) cmd ::= PRAGMA nm dbnm LP nmnum RP */
155670     -5,  /* (236) cmd ::= PRAGMA nm dbnm EQ minus_num */
155671     -6,  /* (237) cmd ::= PRAGMA nm dbnm LP minus_num RP */
155672     -2,  /* (238) plus_num ::= PLUS INTEGER|FLOAT */
155673     -2,  /* (239) minus_num ::= MINUS INTEGER|FLOAT */
155674     -5,  /* (240) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
155675    -11,  /* (241) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
155676     -1,  /* (242) trigger_time ::= BEFORE|AFTER */
155677     -2,  /* (243) trigger_time ::= INSTEAD OF */
155678      0,  /* (244) trigger_time ::= */
155679     -1,  /* (245) trigger_event ::= DELETE|INSERT */
155680     -1,  /* (246) trigger_event ::= UPDATE */
155681     -3,  /* (247) trigger_event ::= UPDATE OF idlist */
155682      0,  /* (248) when_clause ::= */
155683     -2,  /* (249) when_clause ::= WHEN expr */
155684     -3,  /* (250) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
155685     -2,  /* (251) trigger_cmd_list ::= trigger_cmd SEMI */
155686     -3,  /* (252) trnm ::= nm DOT nm */
155687     -3,  /* (253) tridxby ::= INDEXED BY nm */
155688     -2,  /* (254) tridxby ::= NOT INDEXED */
155689     -8,  /* (255) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
155690     -8,  /* (256) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
155691     -6,  /* (257) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
155692     -3,  /* (258) trigger_cmd ::= scanpt select scanpt */
155693     -4,  /* (259) expr ::= RAISE LP IGNORE RP */
155694     -6,  /* (260) expr ::= RAISE LP raisetype COMMA nm RP */
155695     -1,  /* (261) raisetype ::= ROLLBACK */
155696     -1,  /* (262) raisetype ::= ABORT */
155697     -1,  /* (263) raisetype ::= FAIL */
155698     -4,  /* (264) cmd ::= DROP TRIGGER ifexists fullname */
155699     -6,  /* (265) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
155700     -3,  /* (266) cmd ::= DETACH database_kw_opt expr */
155701      0,  /* (267) key_opt ::= */
155702     -2,  /* (268) key_opt ::= KEY expr */
155703     -1,  /* (269) cmd ::= REINDEX */
155704     -3,  /* (270) cmd ::= REINDEX nm dbnm */
155705     -1,  /* (271) cmd ::= ANALYZE */
155706     -3,  /* (272) cmd ::= ANALYZE nm dbnm */
155707     -6,  /* (273) cmd ::= ALTER TABLE fullname RENAME TO nm */
155708     -7,  /* (274) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
155709     -1,  /* (275) add_column_fullname ::= fullname */
155710     -8,  /* (276) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
155711     -1,  /* (277) cmd ::= create_vtab */
155712     -4,  /* (278) cmd ::= create_vtab LP vtabarglist RP */
155713     -8,  /* (279) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
155714      0,  /* (280) vtabarg ::= */
155715     -1,  /* (281) vtabargtoken ::= ANY */
155716     -3,  /* (282) vtabargtoken ::= lp anylist RP */
155717     -1,  /* (283) lp ::= LP */
155718     -2,  /* (284) with ::= WITH wqlist */
155719     -3,  /* (285) with ::= WITH RECURSIVE wqlist */
155720     -6,  /* (286) wqlist ::= nm eidlist_opt AS LP select RP */
155721     -8,  /* (287) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
155722     -1,  /* (288) windowdefn_list ::= windowdefn */
155723     -3,  /* (289) windowdefn_list ::= windowdefn_list COMMA windowdefn */
155724     -3,  /* (290) windowdefn ::= nm AS window */
155725     -5,  /* (291) window ::= LP part_opt orderby_opt frame_opt RP */
155726     -3,  /* (292) part_opt ::= PARTITION BY nexprlist */
155727      0,  /* (293) part_opt ::= */
155728      0,  /* (294) frame_opt ::= */
155729     -2,  /* (295) frame_opt ::= range_or_rows frame_bound_s */
155730     -5,  /* (296) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e */
155731     -1,  /* (297) range_or_rows ::= RANGE */
155732     -1,  /* (298) range_or_rows ::= ROWS */
155733     -1,  /* (299) frame_bound_s ::= frame_bound */
155734     -2,  /* (300) frame_bound_s ::= UNBOUNDED PRECEDING */
155735     -1,  /* (301) frame_bound_e ::= frame_bound */
155736     -2,  /* (302) frame_bound_e ::= UNBOUNDED FOLLOWING */
155737     -2,  /* (303) frame_bound ::= expr PRECEDING */
155738     -2,  /* (304) frame_bound ::= CURRENT ROW */
155739     -2,  /* (305) frame_bound ::= expr FOLLOWING */
155740     -2,  /* (306) window_clause ::= WINDOW windowdefn_list */
155741     -3,  /* (307) over_clause ::= filter_opt OVER window */
155742     -3,  /* (308) over_clause ::= filter_opt OVER nm */
155743      0,  /* (309) filter_opt ::= */
155744     -5,  /* (310) filter_opt ::= FILTER LP WHERE expr RP */
155745     -1,  /* (311) input ::= cmdlist */
155746     -2,  /* (312) cmdlist ::= cmdlist ecmd */
155747     -1,  /* (313) cmdlist ::= ecmd */
155748     -1,  /* (314) ecmd ::= SEMI */
155749     -2,  /* (315) ecmd ::= cmdx SEMI */
155750     -2,  /* (316) ecmd ::= explain cmdx */
155751      0,  /* (317) trans_opt ::= */
155752     -1,  /* (318) trans_opt ::= TRANSACTION */
155753     -2,  /* (319) trans_opt ::= TRANSACTION nm */
155754     -1,  /* (320) savepoint_opt ::= SAVEPOINT */
155755      0,  /* (321) savepoint_opt ::= */
155756     -2,  /* (322) cmd ::= create_table create_table_args */
155757     -4,  /* (323) columnlist ::= columnlist COMMA columnname carglist */
155758     -2,  /* (324) columnlist ::= columnname carglist */
155759     -1,  /* (325) nm ::= ID|INDEXED */
155760     -1,  /* (326) nm ::= STRING */
155761     -1,  /* (327) nm ::= JOIN_KW */
155762     -1,  /* (328) typetoken ::= typename */
155763     -1,  /* (329) typename ::= ID|STRING */
155764     -1,  /* (330) signed ::= plus_num */
155765     -1,  /* (331) signed ::= minus_num */
155766     -2,  /* (332) carglist ::= carglist ccons */
155767      0,  /* (333) carglist ::= */
155768     -2,  /* (334) ccons ::= NULL onconf */
155769     -2,  /* (335) conslist_opt ::= COMMA conslist */
155770     -3,  /* (336) conslist ::= conslist tconscomma tcons */
155771     -1,  /* (337) conslist ::= tcons */
155772      0,  /* (338) tconscomma ::= */
155773     -1,  /* (339) defer_subclause_opt ::= defer_subclause */
155774     -1,  /* (340) resolvetype ::= raisetype */
155775     -1,  /* (341) selectnowith ::= oneselect */
155776     -1,  /* (342) oneselect ::= values */
155777     -2,  /* (343) sclp ::= selcollist COMMA */
155778     -1,  /* (344) as ::= ID|STRING */
155779     -1,  /* (345) expr ::= term */
155780     -1,  /* (346) likeop ::= LIKE_KW|MATCH */
155781     -1,  /* (347) exprlist ::= nexprlist */
155782     -1,  /* (348) nmnum ::= plus_num */
155783     -1,  /* (349) nmnum ::= nm */
155784     -1,  /* (350) nmnum ::= ON */
155785     -1,  /* (351) nmnum ::= DELETE */
155786     -1,  /* (352) nmnum ::= DEFAULT */
155787     -1,  /* (353) plus_num ::= INTEGER|FLOAT */
155788      0,  /* (354) foreach_clause ::= */
155789     -3,  /* (355) foreach_clause ::= FOR EACH ROW */
155790     -1,  /* (356) trnm ::= nm */
155791      0,  /* (357) tridxby ::= */
155792     -1,  /* (358) database_kw_opt ::= DATABASE */
155793      0,  /* (359) database_kw_opt ::= */
155794      0,  /* (360) kwcolumn_opt ::= */
155795     -1,  /* (361) kwcolumn_opt ::= COLUMNKW */
155796     -1,  /* (362) vtabarglist ::= vtabarg */
155797     -3,  /* (363) vtabarglist ::= vtabarglist COMMA vtabarg */
155798     -2,  /* (364) vtabarg ::= vtabarg vtabargtoken */
155799      0,  /* (365) anylist ::= */
155800     -4,  /* (366) anylist ::= anylist LP anylist RP */
155801     -2,  /* (367) anylist ::= anylist ANY */
155802      0,  /* (368) with ::= */
155803  };
155804  
155805  static void yy_accept(yyParser*);  /* Forward Declaration */
155806  
155807  /*
155808  ** Perform a reduce action and the shift that must immediately
155809  ** follow the reduce.
155810  **
155811  ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
155812  ** access to the lookahead token (if any).  The yyLookahead will be YYNOCODE
155813  ** if the lookahead token has already been consumed.  As this procedure is
155814  ** only called from one place, optimizing compilers will in-line it, which
155815  ** means that the extra parameters have no performance impact.
155816  */
155817  static YYACTIONTYPE yy_reduce(
155818    yyParser *yypParser,         /* The parser */
155819    unsigned int yyruleno,       /* Number of the rule by which to reduce */
155820    int yyLookahead,             /* Lookahead token, or YYNOCODE if none */
155821    sqlite3ParserTOKENTYPE yyLookaheadToken  /* Value of the lookahead token */
155822    sqlite3ParserCTX_PDECL                   /* %extra_context */
155823  ){
155824    int yygoto;                     /* The next state */
155825    YYACTIONTYPE yyact;             /* The next action */
155826    yyStackEntry *yymsp;            /* The top of the parser's stack */
155827    int yysize;                     /* Amount to pop the stack */
155828    sqlite3ParserARG_FETCH
155829    (void)yyLookahead;
155830    (void)yyLookaheadToken;
155831    yymsp = yypParser->yytos;
155832  #ifndef NDEBUG
155833    if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
155834      yysize = yyRuleInfoNRhs[yyruleno];
155835      if( yysize ){
155836        fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
155837          yyTracePrompt,
155838          yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
155839      }else{
155840        fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
155841          yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
155842      }
155843    }
155844  #endif /* NDEBUG */
155845  
155846    /* Check that the stack is large enough to grow by a single entry
155847    ** if the RHS of the rule is empty.  This ensures that there is room
155848    ** enough on the stack to push the LHS value */
155849    if( yyRuleInfoNRhs[yyruleno]==0 ){
155850  #ifdef YYTRACKMAXSTACKDEPTH
155851      if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
155852        yypParser->yyhwm++;
155853        assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
155854      }
155855  #endif
155856  #if YYSTACKDEPTH>0 
155857      if( yypParser->yytos>=yypParser->yystackEnd ){
155858        yyStackOverflow(yypParser);
155859        /* The call to yyStackOverflow() above pops the stack until it is
155860        ** empty, causing the main parser loop to exit.  So the return value
155861        ** is never used and does not matter. */
155862        return 0;
155863      }
155864  #else
155865      if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
155866        if( yyGrowStack(yypParser) ){
155867          yyStackOverflow(yypParser);
155868          /* The call to yyStackOverflow() above pops the stack until it is
155869          ** empty, causing the main parser loop to exit.  So the return value
155870          ** is never used and does not matter. */
155871          return 0;
155872        }
155873        yymsp = yypParser->yytos;
155874      }
155875  #endif
155876    }
155877  
155878    switch( yyruleno ){
155879    /* Beginning here are the reduction cases.  A typical example
155880    ** follows:
155881    **   case 0:
155882    **  #line <lineno> <grammarfile>
155883    **     { ... }           // User supplied code
155884    **  #line <lineno> <thisfile>
155885    **     break;
155886    */
155887  /********** Begin reduce actions **********************************************/
155888          YYMINORTYPE yylhsminor;
155889        case 0: /* explain ::= EXPLAIN */
155890  { pParse->explain = 1; }
155891          break;
155892        case 1: /* explain ::= EXPLAIN QUERY PLAN */
155893  { pParse->explain = 2; }
155894          break;
155895        case 2: /* cmdx ::= cmd */
155896  { sqlite3FinishCoding(pParse); }
155897          break;
155898        case 3: /* cmd ::= BEGIN transtype trans_opt */
155899  {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy96);}
155900          break;
155901        case 4: /* transtype ::= */
155902  {yymsp[1].minor.yy96 = TK_DEFERRED;}
155903          break;
155904        case 5: /* transtype ::= DEFERRED */
155905        case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
155906        case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
155907  {yymsp[0].minor.yy96 = yymsp[0].major; /*A-overwrites-X*/}
155908          break;
155909        case 8: /* cmd ::= COMMIT|END trans_opt */
155910        case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
155911  {sqlite3EndTransaction(pParse,yymsp[-1].major);}
155912          break;
155913        case 10: /* cmd ::= SAVEPOINT nm */
155914  {
155915    sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
155916  }
155917          break;
155918        case 11: /* cmd ::= RELEASE savepoint_opt nm */
155919  {
155920    sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
155921  }
155922          break;
155923        case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
155924  {
155925    sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
155926  }
155927          break;
155928        case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
155929  {
155930     sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy96,0,0,yymsp[-2].minor.yy96);
155931  }
155932          break;
155933        case 14: /* createkw ::= CREATE */
155934  {disableLookaside(pParse);}
155935          break;
155936        case 15: /* ifnotexists ::= */
155937        case 18: /* temp ::= */ yytestcase(yyruleno==18);
155938        case 21: /* table_options ::= */ yytestcase(yyruleno==21);
155939        case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
155940        case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
155941        case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
155942        case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
155943        case 93: /* distinct ::= */ yytestcase(yyruleno==93);
155944        case 226: /* collate ::= */ yytestcase(yyruleno==226);
155945  {yymsp[1].minor.yy96 = 0;}
155946          break;
155947        case 16: /* ifnotexists ::= IF NOT EXISTS */
155948  {yymsp[-2].minor.yy96 = 1;}
155949          break;
155950        case 17: /* temp ::= TEMP */
155951        case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
155952  {yymsp[0].minor.yy96 = 1;}
155953          break;
155954        case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
155955  {
155956    sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy96,0);
155957  }
155958          break;
155959        case 20: /* create_table_args ::= AS select */
155960  {
155961    sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy423);
155962    sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy423);
155963  }
155964          break;
155965        case 22: /* table_options ::= WITHOUT nm */
155966  {
155967    if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
155968      yymsp[-1].minor.yy96 = TF_WithoutRowid | TF_NoVisibleRowid;
155969    }else{
155970      yymsp[-1].minor.yy96 = 0;
155971      sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
155972    }
155973  }
155974          break;
155975        case 23: /* columnname ::= nm typetoken */
155976  {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
155977          break;
155978        case 24: /* typetoken ::= */
155979        case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
155980        case 99: /* as ::= */ yytestcase(yyruleno==99);
155981  {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
155982          break;
155983        case 25: /* typetoken ::= typename LP signed RP */
155984  {
155985    yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
155986  }
155987          break;
155988        case 26: /* typetoken ::= typename LP signed COMMA signed RP */
155989  {
155990    yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
155991  }
155992          break;
155993        case 27: /* typename ::= typename ID|STRING */
155994  {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
155995          break;
155996        case 28: /* scanpt ::= */
155997  {
155998    assert( yyLookahead!=YYNOCODE );
155999    yymsp[1].minor.yy464 = yyLookaheadToken.z;
156000  }
156001          break;
156002        case 29: /* ccons ::= CONSTRAINT nm */
156003        case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
156004  {pParse->constraintName = yymsp[0].minor.yy0;}
156005          break;
156006        case 30: /* ccons ::= DEFAULT scanpt term scanpt */
156007  {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy490,yymsp[-2].minor.yy464,yymsp[0].minor.yy464);}
156008          break;
156009        case 31: /* ccons ::= DEFAULT LP expr RP */
156010  {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy490,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
156011          break;
156012        case 32: /* ccons ::= DEFAULT PLUS term scanpt */
156013  {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy490,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy464);}
156014          break;
156015        case 33: /* ccons ::= DEFAULT MINUS term scanpt */
156016  {
156017    Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy490, 0);
156018    sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy464);
156019  }
156020          break;
156021        case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
156022  {
156023    Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
156024    if( p ){
156025      sqlite3ExprIdToTrueFalse(p);
156026      testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
156027    }
156028      sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
156029  }
156030          break;
156031        case 35: /* ccons ::= NOT NULL onconf */
156032  {sqlite3AddNotNull(pParse, yymsp[0].minor.yy96);}
156033          break;
156034        case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
156035  {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy96,yymsp[0].minor.yy96,yymsp[-2].minor.yy96);}
156036          break;
156037        case 37: /* ccons ::= UNIQUE onconf */
156038  {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy96,0,0,0,0,
156039                                     SQLITE_IDXTYPE_UNIQUE);}
156040          break;
156041        case 38: /* ccons ::= CHECK LP expr RP */
156042  {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy490);}
156043          break;
156044        case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
156045  {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy42,yymsp[0].minor.yy96);}
156046          break;
156047        case 40: /* ccons ::= defer_subclause */
156048  {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy96);}
156049          break;
156050        case 41: /* ccons ::= COLLATE ID|STRING */
156051  {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
156052          break;
156053        case 44: /* refargs ::= */
156054  { yymsp[1].minor.yy96 = OE_None*0x0101; /* EV: R-19803-45884 */}
156055          break;
156056        case 45: /* refargs ::= refargs refarg */
156057  { yymsp[-1].minor.yy96 = (yymsp[-1].minor.yy96 & ~yymsp[0].minor.yy367.mask) | yymsp[0].minor.yy367.value; }
156058          break;
156059        case 46: /* refarg ::= MATCH nm */
156060  { yymsp[-1].minor.yy367.value = 0;     yymsp[-1].minor.yy367.mask = 0x000000; }
156061          break;
156062        case 47: /* refarg ::= ON INSERT refact */
156063  { yymsp[-2].minor.yy367.value = 0;     yymsp[-2].minor.yy367.mask = 0x000000; }
156064          break;
156065        case 48: /* refarg ::= ON DELETE refact */
156066  { yymsp[-2].minor.yy367.value = yymsp[0].minor.yy96;     yymsp[-2].minor.yy367.mask = 0x0000ff; }
156067          break;
156068        case 49: /* refarg ::= ON UPDATE refact */
156069  { yymsp[-2].minor.yy367.value = yymsp[0].minor.yy96<<8;  yymsp[-2].minor.yy367.mask = 0x00ff00; }
156070          break;
156071        case 50: /* refact ::= SET NULL */
156072  { yymsp[-1].minor.yy96 = OE_SetNull;  /* EV: R-33326-45252 */}
156073          break;
156074        case 51: /* refact ::= SET DEFAULT */
156075  { yymsp[-1].minor.yy96 = OE_SetDflt;  /* EV: R-33326-45252 */}
156076          break;
156077        case 52: /* refact ::= CASCADE */
156078  { yymsp[0].minor.yy96 = OE_Cascade;  /* EV: R-33326-45252 */}
156079          break;
156080        case 53: /* refact ::= RESTRICT */
156081  { yymsp[0].minor.yy96 = OE_Restrict; /* EV: R-33326-45252 */}
156082          break;
156083        case 54: /* refact ::= NO ACTION */
156084  { yymsp[-1].minor.yy96 = OE_None;     /* EV: R-33326-45252 */}
156085          break;
156086        case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
156087  {yymsp[-2].minor.yy96 = 0;}
156088          break;
156089        case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
156090        case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
156091        case 156: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==156);
156092  {yymsp[-1].minor.yy96 = yymsp[0].minor.yy96;}
156093          break;
156094        case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
156095        case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
156096        case 198: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==198);
156097        case 201: /* in_op ::= NOT IN */ yytestcase(yyruleno==201);
156098        case 227: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==227);
156099  {yymsp[-1].minor.yy96 = 1;}
156100          break;
156101        case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
156102  {yymsp[-1].minor.yy96 = 0;}
156103          break;
156104        case 61: /* tconscomma ::= COMMA */
156105  {pParse->constraintName.n = 0;}
156106          break;
156107        case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
156108  {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy42,yymsp[0].minor.yy96,yymsp[-2].minor.yy96,0);}
156109          break;
156110        case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
156111  {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy42,yymsp[0].minor.yy96,0,0,0,0,
156112                                         SQLITE_IDXTYPE_UNIQUE);}
156113          break;
156114        case 65: /* tcons ::= CHECK LP expr RP onconf */
156115  {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy490);}
156116          break;
156117        case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
156118  {
156119      sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy42, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy42, yymsp[-1].minor.yy96);
156120      sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy96);
156121  }
156122          break;
156123        case 68: /* onconf ::= */
156124        case 70: /* orconf ::= */ yytestcase(yyruleno==70);
156125  {yymsp[1].minor.yy96 = OE_Default;}
156126          break;
156127        case 69: /* onconf ::= ON CONFLICT resolvetype */
156128  {yymsp[-2].minor.yy96 = yymsp[0].minor.yy96;}
156129          break;
156130        case 72: /* resolvetype ::= IGNORE */
156131  {yymsp[0].minor.yy96 = OE_Ignore;}
156132          break;
156133        case 73: /* resolvetype ::= REPLACE */
156134        case 157: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==157);
156135  {yymsp[0].minor.yy96 = OE_Replace;}
156136          break;
156137        case 74: /* cmd ::= DROP TABLE ifexists fullname */
156138  {
156139    sqlite3DropTable(pParse, yymsp[0].minor.yy167, 0, yymsp[-1].minor.yy96);
156140  }
156141          break;
156142        case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
156143  {
156144    sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy42, yymsp[0].minor.yy423, yymsp[-7].minor.yy96, yymsp[-5].minor.yy96);
156145  }
156146          break;
156147        case 78: /* cmd ::= DROP VIEW ifexists fullname */
156148  {
156149    sqlite3DropTable(pParse, yymsp[0].minor.yy167, 1, yymsp[-1].minor.yy96);
156150  }
156151          break;
156152        case 79: /* cmd ::= select */
156153  {
156154    SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
156155    sqlite3Select(pParse, yymsp[0].minor.yy423, &dest);
156156    sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy423);
156157  }
156158          break;
156159        case 80: /* select ::= WITH wqlist selectnowith */
156160  {
156161    Select *p = yymsp[0].minor.yy423;
156162    if( p ){
156163      p->pWith = yymsp[-1].minor.yy499;
156164      parserDoubleLinkSelect(pParse, p);
156165    }else{
156166      sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy499);
156167    }
156168    yymsp[-2].minor.yy423 = p;
156169  }
156170          break;
156171        case 81: /* select ::= WITH RECURSIVE wqlist selectnowith */
156172  {
156173    Select *p = yymsp[0].minor.yy423;
156174    if( p ){
156175      p->pWith = yymsp[-1].minor.yy499;
156176      parserDoubleLinkSelect(pParse, p);
156177    }else{
156178      sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy499);
156179    }
156180    yymsp[-3].minor.yy423 = p;
156181  }
156182          break;
156183        case 82: /* select ::= selectnowith */
156184  {
156185    Select *p = yymsp[0].minor.yy423;
156186    if( p ){
156187      parserDoubleLinkSelect(pParse, p);
156188    }
156189    yymsp[0].minor.yy423 = p; /*A-overwrites-X*/
156190  }
156191          break;
156192        case 83: /* selectnowith ::= selectnowith multiselect_op oneselect */
156193  {
156194    Select *pRhs = yymsp[0].minor.yy423;
156195    Select *pLhs = yymsp[-2].minor.yy423;
156196    if( pRhs && pRhs->pPrior ){
156197      SrcList *pFrom;
156198      Token x;
156199      x.n = 0;
156200      parserDoubleLinkSelect(pParse, pRhs);
156201      pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
156202      pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
156203    }
156204    if( pRhs ){
156205      pRhs->op = (u8)yymsp[-1].minor.yy96;
156206      pRhs->pPrior = pLhs;
156207      if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
156208      pRhs->selFlags &= ~SF_MultiValue;
156209      if( yymsp[-1].minor.yy96!=TK_ALL ) pParse->hasCompound = 1;
156210    }else{
156211      sqlite3SelectDelete(pParse->db, pLhs);
156212    }
156213    yymsp[-2].minor.yy423 = pRhs;
156214  }
156215          break;
156216        case 84: /* multiselect_op ::= UNION */
156217        case 86: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==86);
156218  {yymsp[0].minor.yy96 = yymsp[0].major; /*A-overwrites-OP*/}
156219          break;
156220        case 85: /* multiselect_op ::= UNION ALL */
156221  {yymsp[-1].minor.yy96 = TK_ALL;}
156222          break;
156223        case 87: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
156224  {
156225    yymsp[-8].minor.yy423 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy42,yymsp[-5].minor.yy167,yymsp[-4].minor.yy490,yymsp[-3].minor.yy42,yymsp[-2].minor.yy490,yymsp[-1].minor.yy42,yymsp[-7].minor.yy96,yymsp[0].minor.yy490);
156226  }
156227          break;
156228        case 88: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
156229  {
156230    yymsp[-9].minor.yy423 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy42,yymsp[-6].minor.yy167,yymsp[-5].minor.yy490,yymsp[-4].minor.yy42,yymsp[-3].minor.yy490,yymsp[-1].minor.yy42,yymsp[-8].minor.yy96,yymsp[0].minor.yy490);
156231    if( yymsp[-9].minor.yy423 ){
156232      yymsp[-9].minor.yy423->pWinDefn = yymsp[-2].minor.yy147;
156233    }else{
156234      sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy147);
156235    }
156236  }
156237          break;
156238        case 89: /* values ::= VALUES LP nexprlist RP */
156239  {
156240    yymsp[-3].minor.yy423 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy42,0,0,0,0,0,SF_Values,0);
156241  }
156242          break;
156243        case 90: /* values ::= values COMMA LP nexprlist RP */
156244  {
156245    Select *pRight, *pLeft = yymsp[-4].minor.yy423;
156246    pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy42,0,0,0,0,0,SF_Values|SF_MultiValue,0);
156247    if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
156248    if( pRight ){
156249      pRight->op = TK_ALL;
156250      pRight->pPrior = pLeft;
156251      yymsp[-4].minor.yy423 = pRight;
156252    }else{
156253      yymsp[-4].minor.yy423 = pLeft;
156254    }
156255  }
156256          break;
156257        case 91: /* distinct ::= DISTINCT */
156258  {yymsp[0].minor.yy96 = SF_Distinct;}
156259          break;
156260        case 92: /* distinct ::= ALL */
156261  {yymsp[0].minor.yy96 = SF_All;}
156262          break;
156263        case 94: /* sclp ::= */
156264        case 127: /* orderby_opt ::= */ yytestcase(yyruleno==127);
156265        case 134: /* groupby_opt ::= */ yytestcase(yyruleno==134);
156266        case 214: /* exprlist ::= */ yytestcase(yyruleno==214);
156267        case 217: /* paren_exprlist ::= */ yytestcase(yyruleno==217);
156268        case 222: /* eidlist_opt ::= */ yytestcase(yyruleno==222);
156269  {yymsp[1].minor.yy42 = 0;}
156270          break;
156271        case 95: /* selcollist ::= sclp scanpt expr scanpt as */
156272  {
156273     yymsp[-4].minor.yy42 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy42, yymsp[-2].minor.yy490);
156274     if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy42, &yymsp[0].minor.yy0, 1);
156275     sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy42,yymsp[-3].minor.yy464,yymsp[-1].minor.yy464);
156276  }
156277          break;
156278        case 96: /* selcollist ::= sclp scanpt STAR */
156279  {
156280    Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
156281    yymsp[-2].minor.yy42 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy42, p);
156282  }
156283          break;
156284        case 97: /* selcollist ::= sclp scanpt nm DOT STAR */
156285  {
156286    Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
156287    Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
156288    Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
156289    yymsp[-4].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy42, pDot);
156290  }
156291          break;
156292        case 98: /* as ::= AS nm */
156293        case 109: /* dbnm ::= DOT nm */ yytestcase(yyruleno==109);
156294        case 238: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==238);
156295        case 239: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==239);
156296  {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
156297          break;
156298        case 100: /* from ::= */
156299  {yymsp[1].minor.yy167 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy167));}
156300          break;
156301        case 101: /* from ::= FROM seltablist */
156302  {
156303    yymsp[-1].minor.yy167 = yymsp[0].minor.yy167;
156304    sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy167);
156305  }
156306          break;
156307        case 102: /* stl_prefix ::= seltablist joinop */
156308  {
156309     if( ALWAYS(yymsp[-1].minor.yy167 && yymsp[-1].minor.yy167->nSrc>0) ) yymsp[-1].minor.yy167->a[yymsp[-1].minor.yy167->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy96;
156310  }
156311          break;
156312        case 103: /* stl_prefix ::= */
156313  {yymsp[1].minor.yy167 = 0;}
156314          break;
156315        case 104: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
156316  {
156317    yymsp[-6].minor.yy167 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy167,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy490,yymsp[0].minor.yy336);
156318    sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy167, &yymsp[-2].minor.yy0);
156319  }
156320          break;
156321        case 105: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
156322  {
156323    yymsp[-8].minor.yy167 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy167,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy490,yymsp[0].minor.yy336);
156324    sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy167, yymsp[-4].minor.yy42);
156325  }
156326          break;
156327        case 106: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
156328  {
156329      yymsp[-6].minor.yy167 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy167,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy423,yymsp[-1].minor.yy490,yymsp[0].minor.yy336);
156330    }
156331          break;
156332        case 107: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
156333  {
156334      if( yymsp[-6].minor.yy167==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy490==0 && yymsp[0].minor.yy336==0 ){
156335        yymsp[-6].minor.yy167 = yymsp[-4].minor.yy167;
156336      }else if( yymsp[-4].minor.yy167->nSrc==1 ){
156337        yymsp[-6].minor.yy167 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy167,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy490,yymsp[0].minor.yy336);
156338        if( yymsp[-6].minor.yy167 ){
156339          struct SrcList_item *pNew = &yymsp[-6].minor.yy167->a[yymsp[-6].minor.yy167->nSrc-1];
156340          struct SrcList_item *pOld = yymsp[-4].minor.yy167->a;
156341          pNew->zName = pOld->zName;
156342          pNew->zDatabase = pOld->zDatabase;
156343          pNew->pSelect = pOld->pSelect;
156344          if( pOld->fg.isTabFunc ){
156345            pNew->u1.pFuncArg = pOld->u1.pFuncArg;
156346            pOld->u1.pFuncArg = 0;
156347            pOld->fg.isTabFunc = 0;
156348            pNew->fg.isTabFunc = 1;
156349          }
156350          pOld->zName = pOld->zDatabase = 0;
156351          pOld->pSelect = 0;
156352        }
156353        sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy167);
156354      }else{
156355        Select *pSubquery;
156356        sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy167);
156357        pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy167,0,0,0,0,SF_NestedFrom,0);
156358        yymsp[-6].minor.yy167 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy167,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy490,yymsp[0].minor.yy336);
156359      }
156360    }
156361          break;
156362        case 108: /* dbnm ::= */
156363        case 122: /* indexed_opt ::= */ yytestcase(yyruleno==122);
156364  {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
156365          break;
156366        case 110: /* fullname ::= nm */
156367  {
156368    yylhsminor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
156369    if( IN_RENAME_OBJECT && yylhsminor.yy167 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy167->a[0].zName, &yymsp[0].minor.yy0);
156370  }
156371    yymsp[0].minor.yy167 = yylhsminor.yy167;
156372          break;
156373        case 111: /* fullname ::= nm DOT nm */
156374  {
156375    yylhsminor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
156376    if( IN_RENAME_OBJECT && yylhsminor.yy167 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy167->a[0].zName, &yymsp[0].minor.yy0);
156377  }
156378    yymsp[-2].minor.yy167 = yylhsminor.yy167;
156379          break;
156380        case 112: /* xfullname ::= nm */
156381  {yymsp[0].minor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
156382          break;
156383        case 113: /* xfullname ::= nm DOT nm */
156384  {yymsp[-2].minor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
156385          break;
156386        case 114: /* xfullname ::= nm DOT nm AS nm */
156387  {
156388     yymsp[-4].minor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
156389     if( yymsp[-4].minor.yy167 ) yymsp[-4].minor.yy167->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
156390  }
156391          break;
156392        case 115: /* xfullname ::= nm AS nm */
156393  {  
156394     yymsp[-2].minor.yy167 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
156395     if( yymsp[-2].minor.yy167 ) yymsp[-2].minor.yy167->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
156396  }
156397          break;
156398        case 116: /* joinop ::= COMMA|JOIN */
156399  { yymsp[0].minor.yy96 = JT_INNER; }
156400          break;
156401        case 117: /* joinop ::= JOIN_KW JOIN */
156402  {yymsp[-1].minor.yy96 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
156403          break;
156404        case 118: /* joinop ::= JOIN_KW nm JOIN */
156405  {yymsp[-2].minor.yy96 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
156406          break;
156407        case 119: /* joinop ::= JOIN_KW nm nm JOIN */
156408  {yymsp[-3].minor.yy96 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
156409          break;
156410        case 120: /* on_opt ::= ON expr */
156411        case 137: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==137);
156412        case 144: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==144);
156413        case 210: /* case_else ::= ELSE expr */ yytestcase(yyruleno==210);
156414        case 231: /* vinto ::= INTO expr */ yytestcase(yyruleno==231);
156415  {yymsp[-1].minor.yy490 = yymsp[0].minor.yy490;}
156416          break;
156417        case 121: /* on_opt ::= */
156418        case 136: /* having_opt ::= */ yytestcase(yyruleno==136);
156419        case 138: /* limit_opt ::= */ yytestcase(yyruleno==138);
156420        case 143: /* where_opt ::= */ yytestcase(yyruleno==143);
156421        case 211: /* case_else ::= */ yytestcase(yyruleno==211);
156422        case 213: /* case_operand ::= */ yytestcase(yyruleno==213);
156423        case 232: /* vinto ::= */ yytestcase(yyruleno==232);
156424  {yymsp[1].minor.yy490 = 0;}
156425          break;
156426        case 123: /* indexed_opt ::= INDEXED BY nm */
156427  {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
156428          break;
156429        case 124: /* indexed_opt ::= NOT INDEXED */
156430  {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
156431          break;
156432        case 125: /* using_opt ::= USING LP idlist RP */
156433  {yymsp[-3].minor.yy336 = yymsp[-1].minor.yy336;}
156434          break;
156435        case 126: /* using_opt ::= */
156436        case 158: /* idlist_opt ::= */ yytestcase(yyruleno==158);
156437  {yymsp[1].minor.yy336 = 0;}
156438          break;
156439        case 128: /* orderby_opt ::= ORDER BY sortlist */
156440        case 135: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==135);
156441  {yymsp[-2].minor.yy42 = yymsp[0].minor.yy42;}
156442          break;
156443        case 129: /* sortlist ::= sortlist COMMA expr sortorder */
156444  {
156445    yymsp[-3].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy42,yymsp[-1].minor.yy490);
156446    sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy42,yymsp[0].minor.yy96);
156447  }
156448          break;
156449        case 130: /* sortlist ::= expr sortorder */
156450  {
156451    yymsp[-1].minor.yy42 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy490); /*A-overwrites-Y*/
156452    sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy42,yymsp[0].minor.yy96);
156453  }
156454          break;
156455        case 131: /* sortorder ::= ASC */
156456  {yymsp[0].minor.yy96 = SQLITE_SO_ASC;}
156457          break;
156458        case 132: /* sortorder ::= DESC */
156459  {yymsp[0].minor.yy96 = SQLITE_SO_DESC;}
156460          break;
156461        case 133: /* sortorder ::= */
156462  {yymsp[1].minor.yy96 = SQLITE_SO_UNDEFINED;}
156463          break;
156464        case 139: /* limit_opt ::= LIMIT expr */
156465  {yymsp[-1].minor.yy490 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy490,0);}
156466          break;
156467        case 140: /* limit_opt ::= LIMIT expr OFFSET expr */
156468  {yymsp[-3].minor.yy490 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy490,yymsp[0].minor.yy490);}
156469          break;
156470        case 141: /* limit_opt ::= LIMIT expr COMMA expr */
156471  {yymsp[-3].minor.yy490 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy490,yymsp[-2].minor.yy490);}
156472          break;
156473        case 142: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
156474  {
156475    sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy167, &yymsp[-1].minor.yy0);
156476    sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy167,yymsp[0].minor.yy490,0,0);
156477  }
156478          break;
156479        case 145: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
156480  {
156481    sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy167, &yymsp[-3].minor.yy0);
156482    sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy42,"set list"); 
156483    sqlite3Update(pParse,yymsp[-4].minor.yy167,yymsp[-1].minor.yy42,yymsp[0].minor.yy490,yymsp[-5].minor.yy96,0,0,0);
156484  }
156485          break;
156486        case 146: /* setlist ::= setlist COMMA nm EQ expr */
156487  {
156488    yymsp[-4].minor.yy42 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy42, yymsp[0].minor.yy490);
156489    sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy42, &yymsp[-2].minor.yy0, 1);
156490  }
156491          break;
156492        case 147: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
156493  {
156494    yymsp[-6].minor.yy42 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy42, yymsp[-3].minor.yy336, yymsp[0].minor.yy490);
156495  }
156496          break;
156497        case 148: /* setlist ::= nm EQ expr */
156498  {
156499    yylhsminor.yy42 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy490);
156500    sqlite3ExprListSetName(pParse, yylhsminor.yy42, &yymsp[-2].minor.yy0, 1);
156501  }
156502    yymsp[-2].minor.yy42 = yylhsminor.yy42;
156503          break;
156504        case 149: /* setlist ::= LP idlist RP EQ expr */
156505  {
156506    yymsp[-4].minor.yy42 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy336, yymsp[0].minor.yy490);
156507  }
156508          break;
156509        case 150: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
156510  {
156511    sqlite3Insert(pParse, yymsp[-3].minor.yy167, yymsp[-1].minor.yy423, yymsp[-2].minor.yy336, yymsp[-5].minor.yy96, yymsp[0].minor.yy266);
156512  }
156513          break;
156514        case 151: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
156515  {
156516    sqlite3Insert(pParse, yymsp[-3].minor.yy167, 0, yymsp[-2].minor.yy336, yymsp[-5].minor.yy96, 0);
156517  }
156518          break;
156519        case 152: /* upsert ::= */
156520  { yymsp[1].minor.yy266 = 0; }
156521          break;
156522        case 153: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
156523  { yymsp[-10].minor.yy266 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy42,yymsp[-5].minor.yy490,yymsp[-1].minor.yy42,yymsp[0].minor.yy490);}
156524          break;
156525        case 154: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
156526  { yymsp[-7].minor.yy266 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy42,yymsp[-2].minor.yy490,0,0); }
156527          break;
156528        case 155: /* upsert ::= ON CONFLICT DO NOTHING */
156529  { yymsp[-3].minor.yy266 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
156530          break;
156531        case 159: /* idlist_opt ::= LP idlist RP */
156532  {yymsp[-2].minor.yy336 = yymsp[-1].minor.yy336;}
156533          break;
156534        case 160: /* idlist ::= idlist COMMA nm */
156535  {yymsp[-2].minor.yy336 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy336,&yymsp[0].minor.yy0);}
156536          break;
156537        case 161: /* idlist ::= nm */
156538  {yymsp[0].minor.yy336 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
156539          break;
156540        case 162: /* expr ::= LP expr RP */
156541  {yymsp[-2].minor.yy490 = yymsp[-1].minor.yy490;}
156542          break;
156543        case 163: /* expr ::= ID|INDEXED */
156544        case 164: /* expr ::= JOIN_KW */ yytestcase(yyruleno==164);
156545  {yymsp[0].minor.yy490=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
156546          break;
156547        case 165: /* expr ::= nm DOT nm */
156548  {
156549    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
156550    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
156551    if( IN_RENAME_OBJECT ){
156552      sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
156553      sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
156554    }
156555    yylhsminor.yy490 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
156556  }
156557    yymsp[-2].minor.yy490 = yylhsminor.yy490;
156558          break;
156559        case 166: /* expr ::= nm DOT nm DOT nm */
156560  {
156561    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
156562    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
156563    Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
156564    Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
156565    if( IN_RENAME_OBJECT ){
156566      sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
156567      sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
156568    }
156569    yylhsminor.yy490 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
156570  }
156571    yymsp[-4].minor.yy490 = yylhsminor.yy490;
156572          break;
156573        case 167: /* term ::= NULL|FLOAT|BLOB */
156574        case 168: /* term ::= STRING */ yytestcase(yyruleno==168);
156575  {yymsp[0].minor.yy490=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
156576          break;
156577        case 169: /* term ::= INTEGER */
156578  {
156579    yylhsminor.yy490 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
156580  }
156581    yymsp[0].minor.yy490 = yylhsminor.yy490;
156582          break;
156583        case 170: /* expr ::= VARIABLE */
156584  {
156585    if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
156586      u32 n = yymsp[0].minor.yy0.n;
156587      yymsp[0].minor.yy490 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
156588      sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy490, n);
156589    }else{
156590      /* When doing a nested parse, one can include terms in an expression
156591      ** that look like this:   #1 #2 ...  These terms refer to registers
156592      ** in the virtual machine.  #N is the N-th register. */
156593      Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
156594      assert( t.n>=2 );
156595      if( pParse->nested==0 ){
156596        sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
156597        yymsp[0].minor.yy490 = 0;
156598      }else{
156599        yymsp[0].minor.yy490 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
156600        if( yymsp[0].minor.yy490 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy490->iTable);
156601      }
156602    }
156603  }
156604          break;
156605        case 171: /* expr ::= expr COLLATE ID|STRING */
156606  {
156607    yymsp[-2].minor.yy490 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy490, &yymsp[0].minor.yy0, 1);
156608  }
156609          break;
156610        case 172: /* expr ::= CAST LP expr AS typetoken RP */
156611  {
156612    yymsp[-5].minor.yy490 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
156613    sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy490, yymsp[-3].minor.yy490, 0);
156614  }
156615          break;
156616        case 173: /* expr ::= ID|INDEXED LP distinct exprlist RP */
156617  {
156618    yylhsminor.yy490 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy42, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy96);
156619  }
156620    yymsp[-4].minor.yy490 = yylhsminor.yy490;
156621          break;
156622        case 174: /* expr ::= ID|INDEXED LP STAR RP */
156623  {
156624    yylhsminor.yy490 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
156625  }
156626    yymsp[-3].minor.yy490 = yylhsminor.yy490;
156627          break;
156628        case 175: /* expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
156629  {
156630    yylhsminor.yy490 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy42, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy96);
156631    sqlite3WindowAttach(pParse, yylhsminor.yy490, yymsp[0].minor.yy147);
156632  }
156633    yymsp[-5].minor.yy490 = yylhsminor.yy490;
156634          break;
156635        case 176: /* expr ::= ID|INDEXED LP STAR RP over_clause */
156636  {
156637    yylhsminor.yy490 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
156638    sqlite3WindowAttach(pParse, yylhsminor.yy490, yymsp[0].minor.yy147);
156639  }
156640    yymsp[-4].minor.yy490 = yylhsminor.yy490;
156641          break;
156642        case 177: /* term ::= CTIME_KW */
156643  {
156644    yylhsminor.yy490 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
156645  }
156646    yymsp[0].minor.yy490 = yylhsminor.yy490;
156647          break;
156648        case 178: /* expr ::= LP nexprlist COMMA expr RP */
156649  {
156650    ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy42, yymsp[-1].minor.yy490);
156651    yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
156652    if( yymsp[-4].minor.yy490 ){
156653      yymsp[-4].minor.yy490->x.pList = pList;
156654    }else{
156655      sqlite3ExprListDelete(pParse->db, pList);
156656    }
156657  }
156658          break;
156659        case 179: /* expr ::= expr AND expr */
156660        case 180: /* expr ::= expr OR expr */ yytestcase(yyruleno==180);
156661        case 181: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==181);
156662        case 182: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==182);
156663        case 183: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==183);
156664        case 184: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==184);
156665        case 185: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==185);
156666        case 186: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==186);
156667  {yymsp[-2].minor.yy490=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy490,yymsp[0].minor.yy490);}
156668          break;
156669        case 187: /* likeop ::= NOT LIKE_KW|MATCH */
156670  {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
156671          break;
156672        case 188: /* expr ::= expr likeop expr */
156673  {
156674    ExprList *pList;
156675    int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
156676    yymsp[-1].minor.yy0.n &= 0x7fffffff;
156677    pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy490);
156678    pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy490);
156679    yymsp[-2].minor.yy490 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
156680    if( bNot ) yymsp[-2].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy490, 0);
156681    if( yymsp[-2].minor.yy490 ) yymsp[-2].minor.yy490->flags |= EP_InfixFunc;
156682  }
156683          break;
156684        case 189: /* expr ::= expr likeop expr ESCAPE expr */
156685  {
156686    ExprList *pList;
156687    int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
156688    yymsp[-3].minor.yy0.n &= 0x7fffffff;
156689    pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy490);
156690    pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy490);
156691    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy490);
156692    yymsp[-4].minor.yy490 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
156693    if( bNot ) yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy490, 0);
156694    if( yymsp[-4].minor.yy490 ) yymsp[-4].minor.yy490->flags |= EP_InfixFunc;
156695  }
156696          break;
156697        case 190: /* expr ::= expr ISNULL|NOTNULL */
156698  {yymsp[-1].minor.yy490 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy490,0);}
156699          break;
156700        case 191: /* expr ::= expr NOT NULL */
156701  {yymsp[-2].minor.yy490 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy490,0);}
156702          break;
156703        case 192: /* expr ::= expr IS expr */
156704  {
156705    yymsp[-2].minor.yy490 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy490,yymsp[0].minor.yy490);
156706    binaryToUnaryIfNull(pParse, yymsp[0].minor.yy490, yymsp[-2].minor.yy490, TK_ISNULL);
156707  }
156708          break;
156709        case 193: /* expr ::= expr IS NOT expr */
156710  {
156711    yymsp[-3].minor.yy490 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy490,yymsp[0].minor.yy490);
156712    binaryToUnaryIfNull(pParse, yymsp[0].minor.yy490, yymsp[-3].minor.yy490, TK_NOTNULL);
156713  }
156714          break;
156715        case 194: /* expr ::= NOT expr */
156716        case 195: /* expr ::= BITNOT expr */ yytestcase(yyruleno==195);
156717  {yymsp[-1].minor.yy490 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy490, 0);/*A-overwrites-B*/}
156718          break;
156719        case 196: /* expr ::= PLUS|MINUS expr */
156720  {
156721    yymsp[-1].minor.yy490 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy490, 0);
156722    /*A-overwrites-B*/
156723  }
156724          break;
156725        case 197: /* between_op ::= BETWEEN */
156726        case 200: /* in_op ::= IN */ yytestcase(yyruleno==200);
156727  {yymsp[0].minor.yy96 = 0;}
156728          break;
156729        case 199: /* expr ::= expr between_op expr AND expr */
156730  {
156731    ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy490);
156732    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy490);
156733    yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy490, 0);
156734    if( yymsp[-4].minor.yy490 ){
156735      yymsp[-4].minor.yy490->x.pList = pList;
156736    }else{
156737      sqlite3ExprListDelete(pParse->db, pList);
156738    } 
156739    if( yymsp[-3].minor.yy96 ) yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy490, 0);
156740  }
156741          break;
156742        case 202: /* expr ::= expr in_op LP exprlist RP */
156743  {
156744      if( yymsp[-1].minor.yy42==0 ){
156745        /* Expressions of the form
156746        **
156747        **      expr1 IN ()
156748        **      expr1 NOT IN ()
156749        **
156750        ** simplify to constants 0 (false) and 1 (true), respectively,
156751        ** regardless of the value of expr1.
156752        */
156753        if( IN_RENAME_OBJECT==0 ){
156754          sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy490);
156755          yymsp[-4].minor.yy490 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy96],1);
156756        }
156757      }else if( yymsp[-1].minor.yy42->nExpr==1 ){
156758        /* Expressions of the form:
156759        **
156760        **      expr1 IN (?1)
156761        **      expr1 NOT IN (?2)
156762        **
156763        ** with exactly one value on the RHS can be simplified to something
156764        ** like this:
156765        **
156766        **      expr1 == ?1
156767        **      expr1 <> ?2
156768        **
156769        ** But, the RHS of the == or <> is marked with the EP_Generic flag
156770        ** so that it may not contribute to the computation of comparison
156771        ** affinity or the collating sequence to use for comparison.  Otherwise,
156772        ** the semantics would be subtly different from IN or NOT IN.
156773        */
156774        Expr *pRHS = yymsp[-1].minor.yy42->a[0].pExpr;
156775        yymsp[-1].minor.yy42->a[0].pExpr = 0;
156776        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy42);
156777        /* pRHS cannot be NULL because a malloc error would have been detected
156778        ** before now and control would have never reached this point */
156779        if( ALWAYS(pRHS) ){
156780          pRHS->flags &= ~EP_Collate;
156781          pRHS->flags |= EP_Generic;
156782        }
156783        yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, yymsp[-3].minor.yy96 ? TK_NE : TK_EQ, yymsp[-4].minor.yy490, pRHS);
156784      }else{
156785        yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy490, 0);
156786        if( yymsp[-4].minor.yy490 ){
156787          yymsp[-4].minor.yy490->x.pList = yymsp[-1].minor.yy42;
156788          sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy490);
156789        }else{
156790          sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy42);
156791        }
156792        if( yymsp[-3].minor.yy96 ) yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy490, 0);
156793      }
156794    }
156795          break;
156796        case 203: /* expr ::= LP select RP */
156797  {
156798      yymsp[-2].minor.yy490 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
156799      sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy490, yymsp[-1].minor.yy423);
156800    }
156801          break;
156802        case 204: /* expr ::= expr in_op LP select RP */
156803  {
156804      yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy490, 0);
156805      sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy490, yymsp[-1].minor.yy423);
156806      if( yymsp[-3].minor.yy96 ) yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy490, 0);
156807    }
156808          break;
156809        case 205: /* expr ::= expr in_op nm dbnm paren_exprlist */
156810  {
156811      SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
156812      Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
156813      if( yymsp[0].minor.yy42 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy42);
156814      yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy490, 0);
156815      sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy490, pSelect);
156816      if( yymsp[-3].minor.yy96 ) yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy490, 0);
156817    }
156818          break;
156819        case 206: /* expr ::= EXISTS LP select RP */
156820  {
156821      Expr *p;
156822      p = yymsp[-3].minor.yy490 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
156823      sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy423);
156824    }
156825          break;
156826        case 207: /* expr ::= CASE case_operand case_exprlist case_else END */
156827  {
156828    yymsp[-4].minor.yy490 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy490, 0);
156829    if( yymsp[-4].minor.yy490 ){
156830      yymsp[-4].minor.yy490->x.pList = yymsp[-1].minor.yy490 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy42,yymsp[-1].minor.yy490) : yymsp[-2].minor.yy42;
156831      sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy490);
156832    }else{
156833      sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy42);
156834      sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy490);
156835    }
156836  }
156837          break;
156838        case 208: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
156839  {
156840    yymsp[-4].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy42, yymsp[-2].minor.yy490);
156841    yymsp[-4].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy42, yymsp[0].minor.yy490);
156842  }
156843          break;
156844        case 209: /* case_exprlist ::= WHEN expr THEN expr */
156845  {
156846    yymsp[-3].minor.yy42 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy490);
156847    yymsp[-3].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy42, yymsp[0].minor.yy490);
156848  }
156849          break;
156850        case 212: /* case_operand ::= expr */
156851  {yymsp[0].minor.yy490 = yymsp[0].minor.yy490; /*A-overwrites-X*/}
156852          break;
156853        case 215: /* nexprlist ::= nexprlist COMMA expr */
156854  {yymsp[-2].minor.yy42 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy42,yymsp[0].minor.yy490);}
156855          break;
156856        case 216: /* nexprlist ::= expr */
156857  {yymsp[0].minor.yy42 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy490); /*A-overwrites-Y*/}
156858          break;
156859        case 218: /* paren_exprlist ::= LP exprlist RP */
156860        case 223: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==223);
156861  {yymsp[-2].minor.yy42 = yymsp[-1].minor.yy42;}
156862          break;
156863        case 219: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
156864  {
156865    sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
156866                       sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy42, yymsp[-10].minor.yy96,
156867                        &yymsp[-11].minor.yy0, yymsp[0].minor.yy490, SQLITE_SO_ASC, yymsp[-8].minor.yy96, SQLITE_IDXTYPE_APPDEF);
156868    if( IN_RENAME_OBJECT && pParse->pNewIndex ){
156869      sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
156870    }
156871  }
156872          break;
156873        case 220: /* uniqueflag ::= UNIQUE */
156874        case 262: /* raisetype ::= ABORT */ yytestcase(yyruleno==262);
156875  {yymsp[0].minor.yy96 = OE_Abort;}
156876          break;
156877        case 221: /* uniqueflag ::= */
156878  {yymsp[1].minor.yy96 = OE_None;}
156879          break;
156880        case 224: /* eidlist ::= eidlist COMMA nm collate sortorder */
156881  {
156882    yymsp[-4].minor.yy42 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy42, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy96, yymsp[0].minor.yy96);
156883  }
156884          break;
156885        case 225: /* eidlist ::= nm collate sortorder */
156886  {
156887    yymsp[-2].minor.yy42 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy96, yymsp[0].minor.yy96); /*A-overwrites-Y*/
156888  }
156889          break;
156890        case 228: /* cmd ::= DROP INDEX ifexists fullname */
156891  {sqlite3DropIndex(pParse, yymsp[0].minor.yy167, yymsp[-1].minor.yy96);}
156892          break;
156893        case 229: /* cmd ::= VACUUM vinto */
156894  {sqlite3Vacuum(pParse,0,yymsp[0].minor.yy490);}
156895          break;
156896        case 230: /* cmd ::= VACUUM nm vinto */
156897  {sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy490);}
156898          break;
156899        case 233: /* cmd ::= PRAGMA nm dbnm */
156900  {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
156901          break;
156902        case 234: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
156903  {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
156904          break;
156905        case 235: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
156906  {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
156907          break;
156908        case 236: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
156909  {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
156910          break;
156911        case 237: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
156912  {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
156913          break;
156914        case 240: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
156915  {
156916    Token all;
156917    all.z = yymsp[-3].minor.yy0.z;
156918    all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
156919    sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy119, &all);
156920  }
156921          break;
156922        case 241: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
156923  {
156924    sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy96, yymsp[-4].minor.yy350.a, yymsp[-4].minor.yy350.b, yymsp[-2].minor.yy167, yymsp[0].minor.yy490, yymsp[-10].minor.yy96, yymsp[-8].minor.yy96);
156925    yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
156926  }
156927          break;
156928        case 242: /* trigger_time ::= BEFORE|AFTER */
156929  { yymsp[0].minor.yy96 = yymsp[0].major; /*A-overwrites-X*/ }
156930          break;
156931        case 243: /* trigger_time ::= INSTEAD OF */
156932  { yymsp[-1].minor.yy96 = TK_INSTEAD;}
156933          break;
156934        case 244: /* trigger_time ::= */
156935  { yymsp[1].minor.yy96 = TK_BEFORE; }
156936          break;
156937        case 245: /* trigger_event ::= DELETE|INSERT */
156938        case 246: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==246);
156939  {yymsp[0].minor.yy350.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy350.b = 0;}
156940          break;
156941        case 247: /* trigger_event ::= UPDATE OF idlist */
156942  {yymsp[-2].minor.yy350.a = TK_UPDATE; yymsp[-2].minor.yy350.b = yymsp[0].minor.yy336;}
156943          break;
156944        case 248: /* when_clause ::= */
156945        case 267: /* key_opt ::= */ yytestcase(yyruleno==267);
156946        case 309: /* filter_opt ::= */ yytestcase(yyruleno==309);
156947  { yymsp[1].minor.yy490 = 0; }
156948          break;
156949        case 249: /* when_clause ::= WHEN expr */
156950        case 268: /* key_opt ::= KEY expr */ yytestcase(yyruleno==268);
156951  { yymsp[-1].minor.yy490 = yymsp[0].minor.yy490; }
156952          break;
156953        case 250: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
156954  {
156955    assert( yymsp[-2].minor.yy119!=0 );
156956    yymsp[-2].minor.yy119->pLast->pNext = yymsp[-1].minor.yy119;
156957    yymsp[-2].minor.yy119->pLast = yymsp[-1].minor.yy119;
156958  }
156959          break;
156960        case 251: /* trigger_cmd_list ::= trigger_cmd SEMI */
156961  { 
156962    assert( yymsp[-1].minor.yy119!=0 );
156963    yymsp[-1].minor.yy119->pLast = yymsp[-1].minor.yy119;
156964  }
156965          break;
156966        case 252: /* trnm ::= nm DOT nm */
156967  {
156968    yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
156969    sqlite3ErrorMsg(pParse, 
156970          "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
156971          "statements within triggers");
156972  }
156973          break;
156974        case 253: /* tridxby ::= INDEXED BY nm */
156975  {
156976    sqlite3ErrorMsg(pParse,
156977          "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
156978          "within triggers");
156979  }
156980          break;
156981        case 254: /* tridxby ::= NOT INDEXED */
156982  {
156983    sqlite3ErrorMsg(pParse,
156984          "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
156985          "within triggers");
156986  }
156987          break;
156988        case 255: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
156989  {yylhsminor.yy119 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy42, yymsp[-1].minor.yy490, yymsp[-6].minor.yy96, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy464);}
156990    yymsp[-7].minor.yy119 = yylhsminor.yy119;
156991          break;
156992        case 256: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
156993  {
156994     yylhsminor.yy119 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy336,yymsp[-2].minor.yy423,yymsp[-6].minor.yy96,yymsp[-1].minor.yy266,yymsp[-7].minor.yy464,yymsp[0].minor.yy464);/*yylhsminor.yy119-overwrites-yymsp[-6].minor.yy96*/
156995  }
156996    yymsp[-7].minor.yy119 = yylhsminor.yy119;
156997          break;
156998        case 257: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
156999  {yylhsminor.yy119 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy490, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy464);}
157000    yymsp[-5].minor.yy119 = yylhsminor.yy119;
157001          break;
157002        case 258: /* trigger_cmd ::= scanpt select scanpt */
157003  {yylhsminor.yy119 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy423, yymsp[-2].minor.yy464, yymsp[0].minor.yy464); /*yylhsminor.yy119-overwrites-yymsp[-1].minor.yy423*/}
157004    yymsp[-2].minor.yy119 = yylhsminor.yy119;
157005          break;
157006        case 259: /* expr ::= RAISE LP IGNORE RP */
157007  {
157008    yymsp[-3].minor.yy490 = sqlite3PExpr(pParse, TK_RAISE, 0, 0); 
157009    if( yymsp[-3].minor.yy490 ){
157010      yymsp[-3].minor.yy490->affinity = OE_Ignore;
157011    }
157012  }
157013          break;
157014        case 260: /* expr ::= RAISE LP raisetype COMMA nm RP */
157015  {
157016    yymsp[-5].minor.yy490 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); 
157017    if( yymsp[-5].minor.yy490 ) {
157018      yymsp[-5].minor.yy490->affinity = (char)yymsp[-3].minor.yy96;
157019    }
157020  }
157021          break;
157022        case 261: /* raisetype ::= ROLLBACK */
157023  {yymsp[0].minor.yy96 = OE_Rollback;}
157024          break;
157025        case 263: /* raisetype ::= FAIL */
157026  {yymsp[0].minor.yy96 = OE_Fail;}
157027          break;
157028        case 264: /* cmd ::= DROP TRIGGER ifexists fullname */
157029  {
157030    sqlite3DropTrigger(pParse,yymsp[0].minor.yy167,yymsp[-1].minor.yy96);
157031  }
157032          break;
157033        case 265: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
157034  {
157035    sqlite3Attach(pParse, yymsp[-3].minor.yy490, yymsp[-1].minor.yy490, yymsp[0].minor.yy490);
157036  }
157037          break;
157038        case 266: /* cmd ::= DETACH database_kw_opt expr */
157039  {
157040    sqlite3Detach(pParse, yymsp[0].minor.yy490);
157041  }
157042          break;
157043        case 269: /* cmd ::= REINDEX */
157044  {sqlite3Reindex(pParse, 0, 0);}
157045          break;
157046        case 270: /* cmd ::= REINDEX nm dbnm */
157047  {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
157048          break;
157049        case 271: /* cmd ::= ANALYZE */
157050  {sqlite3Analyze(pParse, 0, 0);}
157051          break;
157052        case 272: /* cmd ::= ANALYZE nm dbnm */
157053  {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
157054          break;
157055        case 273: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
157056  {
157057    sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy167,&yymsp[0].minor.yy0);
157058  }
157059          break;
157060        case 274: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
157061  {
157062    yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
157063    sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
157064  }
157065          break;
157066        case 275: /* add_column_fullname ::= fullname */
157067  {
157068    disableLookaside(pParse);
157069    sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy167);
157070  }
157071          break;
157072        case 276: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
157073  {
157074    sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy167, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
157075  }
157076          break;
157077        case 277: /* cmd ::= create_vtab */
157078  {sqlite3VtabFinishParse(pParse,0);}
157079          break;
157080        case 278: /* cmd ::= create_vtab LP vtabarglist RP */
157081  {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
157082          break;
157083        case 279: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
157084  {
157085      sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy96);
157086  }
157087          break;
157088        case 280: /* vtabarg ::= */
157089  {sqlite3VtabArgInit(pParse);}
157090          break;
157091        case 281: /* vtabargtoken ::= ANY */
157092        case 282: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==282);
157093        case 283: /* lp ::= LP */ yytestcase(yyruleno==283);
157094  {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
157095          break;
157096        case 284: /* with ::= WITH wqlist */
157097        case 285: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==285);
157098  { sqlite3WithPush(pParse, yymsp[0].minor.yy499, 1); }
157099          break;
157100        case 286: /* wqlist ::= nm eidlist_opt AS LP select RP */
157101  {
157102    yymsp[-5].minor.yy499 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy42, yymsp[-1].minor.yy423); /*A-overwrites-X*/
157103  }
157104          break;
157105        case 287: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
157106  {
157107    yymsp[-7].minor.yy499 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy499, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy42, yymsp[-1].minor.yy423);
157108  }
157109          break;
157110        case 288: /* windowdefn_list ::= windowdefn */
157111  { yylhsminor.yy147 = yymsp[0].minor.yy147; }
157112    yymsp[0].minor.yy147 = yylhsminor.yy147;
157113          break;
157114        case 289: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
157115  {
157116    assert( yymsp[0].minor.yy147!=0 );
157117    yymsp[0].minor.yy147->pNextWin = yymsp[-2].minor.yy147;
157118    yylhsminor.yy147 = yymsp[0].minor.yy147;
157119  }
157120    yymsp[-2].minor.yy147 = yylhsminor.yy147;
157121          break;
157122        case 290: /* windowdefn ::= nm AS window */
157123  {
157124    if( ALWAYS(yymsp[0].minor.yy147) ){
157125      yymsp[0].minor.yy147->zName = sqlite3DbStrNDup(pParse->db, yymsp[-2].minor.yy0.z, yymsp[-2].minor.yy0.n);
157126    }
157127    yylhsminor.yy147 = yymsp[0].minor.yy147;
157128  }
157129    yymsp[-2].minor.yy147 = yylhsminor.yy147;
157130          break;
157131        case 291: /* window ::= LP part_opt orderby_opt frame_opt RP */
157132  {
157133    yymsp[-4].minor.yy147 = yymsp[-1].minor.yy147;
157134    if( ALWAYS(yymsp[-4].minor.yy147) ){
157135      yymsp[-4].minor.yy147->pPartition = yymsp[-3].minor.yy42;
157136      yymsp[-4].minor.yy147->pOrderBy = yymsp[-2].minor.yy42;
157137    }
157138  }
157139          break;
157140        case 292: /* part_opt ::= PARTITION BY nexprlist */
157141  { yymsp[-2].minor.yy42 = yymsp[0].minor.yy42; }
157142          break;
157143        case 293: /* part_opt ::= */
157144  { yymsp[1].minor.yy42 = 0; }
157145          break;
157146        case 294: /* frame_opt ::= */
157147  { 
157148    yymsp[1].minor.yy147 = sqlite3WindowAlloc(pParse, TK_RANGE, TK_UNBOUNDED, 0, TK_CURRENT, 0);
157149  }
157150          break;
157151        case 295: /* frame_opt ::= range_or_rows frame_bound_s */
157152  { 
157153    yylhsminor.yy147 = sqlite3WindowAlloc(pParse, yymsp[-1].minor.yy96, yymsp[0].minor.yy317.eType, yymsp[0].minor.yy317.pExpr, TK_CURRENT, 0);
157154  }
157155    yymsp[-1].minor.yy147 = yylhsminor.yy147;
157156          break;
157157        case 296: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e */
157158  { 
157159    yylhsminor.yy147 = sqlite3WindowAlloc(pParse, yymsp[-4].minor.yy96, yymsp[-2].minor.yy317.eType, yymsp[-2].minor.yy317.pExpr, yymsp[0].minor.yy317.eType, yymsp[0].minor.yy317.pExpr);
157160  }
157161    yymsp[-4].minor.yy147 = yylhsminor.yy147;
157162          break;
157163        case 297: /* range_or_rows ::= RANGE */
157164  { yymsp[0].minor.yy96 = TK_RANGE; }
157165          break;
157166        case 298: /* range_or_rows ::= ROWS */
157167  { yymsp[0].minor.yy96 = TK_ROWS;  }
157168          break;
157169        case 299: /* frame_bound_s ::= frame_bound */
157170        case 301: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==301);
157171  { yylhsminor.yy317 = yymsp[0].minor.yy317; }
157172    yymsp[0].minor.yy317 = yylhsminor.yy317;
157173          break;
157174        case 300: /* frame_bound_s ::= UNBOUNDED PRECEDING */
157175        case 302: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==302);
157176  {yymsp[-1].minor.yy317.eType = TK_UNBOUNDED; yymsp[-1].minor.yy317.pExpr = 0;}
157177          break;
157178        case 303: /* frame_bound ::= expr PRECEDING */
157179  { yylhsminor.yy317.eType = TK_PRECEDING; yylhsminor.yy317.pExpr = yymsp[-1].minor.yy490; }
157180    yymsp[-1].minor.yy317 = yylhsminor.yy317;
157181          break;
157182        case 304: /* frame_bound ::= CURRENT ROW */
157183  { yymsp[-1].minor.yy317.eType = TK_CURRENT  ; yymsp[-1].minor.yy317.pExpr = 0; }
157184          break;
157185        case 305: /* frame_bound ::= expr FOLLOWING */
157186  { yylhsminor.yy317.eType = TK_FOLLOWING; yylhsminor.yy317.pExpr = yymsp[-1].minor.yy490; }
157187    yymsp[-1].minor.yy317 = yylhsminor.yy317;
157188          break;
157189        case 306: /* window_clause ::= WINDOW windowdefn_list */
157190  { yymsp[-1].minor.yy147 = yymsp[0].minor.yy147; }
157191          break;
157192        case 307: /* over_clause ::= filter_opt OVER window */
157193  {
157194    yylhsminor.yy147 = yymsp[0].minor.yy147;
157195    assert( yylhsminor.yy147!=0 );
157196    yylhsminor.yy147->pFilter = yymsp[-2].minor.yy490;
157197  }
157198    yymsp[-2].minor.yy147 = yylhsminor.yy147;
157199          break;
157200        case 308: /* over_clause ::= filter_opt OVER nm */
157201  {
157202    yylhsminor.yy147 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
157203    if( yylhsminor.yy147 ){
157204      yylhsminor.yy147->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
157205      yylhsminor.yy147->pFilter = yymsp[-2].minor.yy490;
157206    }else{
157207      sqlite3ExprDelete(pParse->db, yymsp[-2].minor.yy490);
157208    }
157209  }
157210    yymsp[-2].minor.yy147 = yylhsminor.yy147;
157211          break;
157212        case 310: /* filter_opt ::= FILTER LP WHERE expr RP */
157213  { yymsp[-4].minor.yy490 = yymsp[-1].minor.yy490; }
157214          break;
157215        default:
157216        /* (311) input ::= cmdlist */ yytestcase(yyruleno==311);
157217        /* (312) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==312);
157218        /* (313) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=313);
157219        /* (314) ecmd ::= SEMI */ yytestcase(yyruleno==314);
157220        /* (315) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==315);
157221        /* (316) ecmd ::= explain cmdx */ yytestcase(yyruleno==316);
157222        /* (317) trans_opt ::= */ yytestcase(yyruleno==317);
157223        /* (318) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==318);
157224        /* (319) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==319);
157225        /* (320) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==320);
157226        /* (321) savepoint_opt ::= */ yytestcase(yyruleno==321);
157227        /* (322) cmd ::= create_table create_table_args */ yytestcase(yyruleno==322);
157228        /* (323) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==323);
157229        /* (324) columnlist ::= columnname carglist */ yytestcase(yyruleno==324);
157230        /* (325) nm ::= ID|INDEXED */ yytestcase(yyruleno==325);
157231        /* (326) nm ::= STRING */ yytestcase(yyruleno==326);
157232        /* (327) nm ::= JOIN_KW */ yytestcase(yyruleno==327);
157233        /* (328) typetoken ::= typename */ yytestcase(yyruleno==328);
157234        /* (329) typename ::= ID|STRING */ yytestcase(yyruleno==329);
157235        /* (330) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=330);
157236        /* (331) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=331);
157237        /* (332) carglist ::= carglist ccons */ yytestcase(yyruleno==332);
157238        /* (333) carglist ::= */ yytestcase(yyruleno==333);
157239        /* (334) ccons ::= NULL onconf */ yytestcase(yyruleno==334);
157240        /* (335) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==335);
157241        /* (336) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==336);
157242        /* (337) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=337);
157243        /* (338) tconscomma ::= */ yytestcase(yyruleno==338);
157244        /* (339) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=339);
157245        /* (340) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=340);
157246        /* (341) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=341);
157247        /* (342) oneselect ::= values */ yytestcase(yyruleno==342);
157248        /* (343) sclp ::= selcollist COMMA */ yytestcase(yyruleno==343);
157249        /* (344) as ::= ID|STRING */ yytestcase(yyruleno==344);
157250        /* (345) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=345);
157251        /* (346) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==346);
157252        /* (347) exprlist ::= nexprlist */ yytestcase(yyruleno==347);
157253        /* (348) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=348);
157254        /* (349) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=349);
157255        /* (350) nmnum ::= ON */ yytestcase(yyruleno==350);
157256        /* (351) nmnum ::= DELETE */ yytestcase(yyruleno==351);
157257        /* (352) nmnum ::= DEFAULT */ yytestcase(yyruleno==352);
157258        /* (353) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==353);
157259        /* (354) foreach_clause ::= */ yytestcase(yyruleno==354);
157260        /* (355) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==355);
157261        /* (356) trnm ::= nm */ yytestcase(yyruleno==356);
157262        /* (357) tridxby ::= */ yytestcase(yyruleno==357);
157263        /* (358) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==358);
157264        /* (359) database_kw_opt ::= */ yytestcase(yyruleno==359);
157265        /* (360) kwcolumn_opt ::= */ yytestcase(yyruleno==360);
157266        /* (361) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==361);
157267        /* (362) vtabarglist ::= vtabarg */ yytestcase(yyruleno==362);
157268        /* (363) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==363);
157269        /* (364) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==364);
157270        /* (365) anylist ::= */ yytestcase(yyruleno==365);
157271        /* (366) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==366);
157272        /* (367) anylist ::= anylist ANY */ yytestcase(yyruleno==367);
157273        /* (368) with ::= */ yytestcase(yyruleno==368);
157274          break;
157275  /********** End reduce actions ************************************************/
157276    };
157277    assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
157278    yygoto = yyRuleInfoLhs[yyruleno];
157279    yysize = yyRuleInfoNRhs[yyruleno];
157280    yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
157281  
157282    /* There are no SHIFTREDUCE actions on nonterminals because the table
157283    ** generator has simplified them to pure REDUCE actions. */
157284    assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
157285  
157286    /* It is not possible for a REDUCE to be followed by an error */
157287    assert( yyact!=YY_ERROR_ACTION );
157288  
157289    yymsp += yysize+1;
157290    yypParser->yytos = yymsp;
157291    yymsp->stateno = (YYACTIONTYPE)yyact;
157292    yymsp->major = (YYCODETYPE)yygoto;
157293    yyTraceShift(yypParser, yyact, "... then shift");
157294    return yyact;
157295  }
157296  
157297  /*
157298  ** The following code executes when the parse fails
157299  */
157300  #ifndef YYNOERRORRECOVERY
157301  static void yy_parse_failed(
157302    yyParser *yypParser           /* The parser */
157303  ){
157304    sqlite3ParserARG_FETCH
157305    sqlite3ParserCTX_FETCH
157306  #ifndef NDEBUG
157307    if( yyTraceFILE ){
157308      fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
157309    }
157310  #endif
157311    while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
157312    /* Here code is inserted which will be executed whenever the
157313    ** parser fails */
157314  /************ Begin %parse_failure code ***************************************/
157315  /************ End %parse_failure code *****************************************/
157316    sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
157317    sqlite3ParserCTX_STORE
157318  }
157319  #endif /* YYNOERRORRECOVERY */
157320  
157321  /*
157322  ** The following code executes when a syntax error first occurs.
157323  */
157324  static void yy_syntax_error(
157325    yyParser *yypParser,           /* The parser */
157326    int yymajor,                   /* The major type of the error token */
157327    sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
157328  ){
157329    sqlite3ParserARG_FETCH
157330    sqlite3ParserCTX_FETCH
157331  #define TOKEN yyminor
157332  /************ Begin %syntax_error code ****************************************/
157333  
157334    UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
157335    if( TOKEN.z[0] ){
157336      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
157337    }else{
157338      sqlite3ErrorMsg(pParse, "incomplete input");
157339    }
157340  /************ End %syntax_error code ******************************************/
157341    sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
157342    sqlite3ParserCTX_STORE
157343  }
157344  
157345  /*
157346  ** The following is executed when the parser accepts
157347  */
157348  static void yy_accept(
157349    yyParser *yypParser           /* The parser */
157350  ){
157351    sqlite3ParserARG_FETCH
157352    sqlite3ParserCTX_FETCH
157353  #ifndef NDEBUG
157354    if( yyTraceFILE ){
157355      fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
157356    }
157357  #endif
157358  #ifndef YYNOERRORRECOVERY
157359    yypParser->yyerrcnt = -1;
157360  #endif
157361    assert( yypParser->yytos==yypParser->yystack );
157362    /* Here code is inserted which will be executed whenever the
157363    ** parser accepts */
157364  /*********** Begin %parse_accept code *****************************************/
157365  /*********** End %parse_accept code *******************************************/
157366    sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
157367    sqlite3ParserCTX_STORE
157368  }
157369  
157370  /* The main parser program.
157371  ** The first argument is a pointer to a structure obtained from
157372  ** "sqlite3ParserAlloc" which describes the current state of the parser.
157373  ** The second argument is the major token number.  The third is
157374  ** the minor token.  The fourth optional argument is whatever the
157375  ** user wants (and specified in the grammar) and is available for
157376  ** use by the action routines.
157377  **
157378  ** Inputs:
157379  ** <ul>
157380  ** <li> A pointer to the parser (an opaque structure.)
157381  ** <li> The major token number.
157382  ** <li> The minor token number.
157383  ** <li> An option argument of a grammar-specified type.
157384  ** </ul>
157385  **
157386  ** Outputs:
157387  ** None.
157388  */
157389  SQLITE_PRIVATE void sqlite3Parser(
157390    void *yyp,                   /* The parser */
157391    int yymajor,                 /* The major token code number */
157392    sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
157393    sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
157394  ){
157395    YYMINORTYPE yyminorunion;
157396    YYACTIONTYPE yyact;   /* The parser action. */
157397  #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
157398    int yyendofinput;     /* True if we are at the end of input */
157399  #endif
157400  #ifdef YYERRORSYMBOL
157401    int yyerrorhit = 0;   /* True if yymajor has invoked an error */
157402  #endif
157403    yyParser *yypParser = (yyParser*)yyp;  /* The parser */
157404    sqlite3ParserCTX_FETCH
157405    sqlite3ParserARG_STORE
157406  
157407    assert( yypParser->yytos!=0 );
157408  #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
157409    yyendofinput = (yymajor==0);
157410  #endif
157411  
157412    yyact = yypParser->yytos->stateno;
157413  #ifndef NDEBUG
157414    if( yyTraceFILE ){
157415      if( yyact < YY_MIN_REDUCE ){
157416        fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
157417                yyTracePrompt,yyTokenName[yymajor],yyact);
157418      }else{
157419        fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
157420                yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
157421      }
157422    }
157423  #endif
157424  
157425    do{
157426      assert( yyact==yypParser->yytos->stateno );
157427      yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
157428      if( yyact >= YY_MIN_REDUCE ){
157429        yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
157430                          yyminor sqlite3ParserCTX_PARAM);
157431      }else if( yyact <= YY_MAX_SHIFTREDUCE ){
157432        yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
157433  #ifndef YYNOERRORRECOVERY
157434        yypParser->yyerrcnt--;
157435  #endif
157436        break;
157437      }else if( yyact==YY_ACCEPT_ACTION ){
157438        yypParser->yytos--;
157439        yy_accept(yypParser);
157440        return;
157441      }else{
157442        assert( yyact == YY_ERROR_ACTION );
157443        yyminorunion.yy0 = yyminor;
157444  #ifdef YYERRORSYMBOL
157445        int yymx;
157446  #endif
157447  #ifndef NDEBUG
157448        if( yyTraceFILE ){
157449          fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
157450        }
157451  #endif
157452  #ifdef YYERRORSYMBOL
157453        /* A syntax error has occurred.
157454        ** The response to an error depends upon whether or not the
157455        ** grammar defines an error token "ERROR".  
157456        **
157457        ** This is what we do if the grammar does define ERROR:
157458        **
157459        **  * Call the %syntax_error function.
157460        **
157461        **  * Begin popping the stack until we enter a state where
157462        **    it is legal to shift the error symbol, then shift
157463        **    the error symbol.
157464        **
157465        **  * Set the error count to three.
157466        **
157467        **  * Begin accepting and shifting new tokens.  No new error
157468        **    processing will occur until three tokens have been
157469        **    shifted successfully.
157470        **
157471        */
157472        if( yypParser->yyerrcnt<0 ){
157473          yy_syntax_error(yypParser,yymajor,yyminor);
157474        }
157475        yymx = yypParser->yytos->major;
157476        if( yymx==YYERRORSYMBOL || yyerrorhit ){
157477  #ifndef NDEBUG
157478          if( yyTraceFILE ){
157479            fprintf(yyTraceFILE,"%sDiscard input token %s\n",
157480               yyTracePrompt,yyTokenName[yymajor]);
157481          }
157482  #endif
157483          yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
157484          yymajor = YYNOCODE;
157485        }else{
157486          while( yypParser->yytos >= yypParser->yystack
157487              && (yyact = yy_find_reduce_action(
157488                          yypParser->yytos->stateno,
157489                          YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
157490          ){
157491            yy_pop_parser_stack(yypParser);
157492          }
157493          if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
157494            yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
157495            yy_parse_failed(yypParser);
157496  #ifndef YYNOERRORRECOVERY
157497            yypParser->yyerrcnt = -1;
157498  #endif
157499            yymajor = YYNOCODE;
157500          }else if( yymx!=YYERRORSYMBOL ){
157501            yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
157502          }
157503        }
157504        yypParser->yyerrcnt = 3;
157505        yyerrorhit = 1;
157506        if( yymajor==YYNOCODE ) break;
157507        yyact = yypParser->yytos->stateno;
157508  #elif defined(YYNOERRORRECOVERY)
157509        /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
157510        ** do any kind of error recovery.  Instead, simply invoke the syntax
157511        ** error routine and continue going as if nothing had happened.
157512        **
157513        ** Applications can set this macro (for example inside %include) if
157514        ** they intend to abandon the parse upon the first syntax error seen.
157515        */
157516        yy_syntax_error(yypParser,yymajor, yyminor);
157517        yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
157518        break;
157519  #else  /* YYERRORSYMBOL is not defined */
157520        /* This is what we do if the grammar does not define ERROR:
157521        **
157522        **  * Report an error message, and throw away the input token.
157523        **
157524        **  * If the input token is $, then fail the parse.
157525        **
157526        ** As before, subsequent error messages are suppressed until
157527        ** three input tokens have been successfully shifted.
157528        */
157529        if( yypParser->yyerrcnt<=0 ){
157530          yy_syntax_error(yypParser,yymajor, yyminor);
157531        }
157532        yypParser->yyerrcnt = 3;
157533        yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
157534        if( yyendofinput ){
157535          yy_parse_failed(yypParser);
157536  #ifndef YYNOERRORRECOVERY
157537          yypParser->yyerrcnt = -1;
157538  #endif
157539        }
157540        break;
157541  #endif
157542      }
157543    }while( yypParser->yytos>yypParser->yystack );
157544  #ifndef NDEBUG
157545    if( yyTraceFILE ){
157546      yyStackEntry *i;
157547      char cDiv = '[';
157548      fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
157549      for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
157550        fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
157551        cDiv = ' ';
157552      }
157553      fprintf(yyTraceFILE,"]\n");
157554    }
157555  #endif
157556    return;
157557  }
157558  
157559  /*
157560  ** Return the fallback token corresponding to canonical token iToken, or
157561  ** 0 if iToken has no fallback.
157562  */
157563  SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
157564  #ifdef YYFALLBACK
157565    if( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ){
157566      return yyFallback[iToken];
157567    }
157568  #else
157569    (void)iToken;
157570  #endif
157571    return 0;
157572  }
157573  
157574  /************** End of parse.c ***********************************************/
157575  /************** Begin file tokenize.c ****************************************/
157576  /*
157577  ** 2001 September 15
157578  **
157579  ** The author disclaims copyright to this source code.  In place of
157580  ** a legal notice, here is a blessing:
157581  **
157582  **    May you do good and not evil.
157583  **    May you find forgiveness for yourself and forgive others.
157584  **    May you share freely, never taking more than you give.
157585  **
157586  *************************************************************************
157587  ** An tokenizer for SQL
157588  **
157589  ** This file contains C code that splits an SQL input string up into
157590  ** individual tokens and sends those tokens one-by-one over to the
157591  ** parser for analysis.
157592  */
157593  /* #include "sqliteInt.h" */
157594  /* #include <stdlib.h> */
157595  
157596  /* Character classes for tokenizing
157597  **
157598  ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
157599  ** using a lookup table, whereas a switch() directly on c uses a binary search.
157600  ** The lookup table is much faster.  To maximize speed, and to ensure that
157601  ** a lookup table is used, all of the classes need to be small integers and
157602  ** all of them need to be used within the switch.
157603  */
157604  #define CC_X          0    /* The letter 'x', or start of BLOB literal */
157605  #define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
157606  #define CC_ID         2    /* unicode characters usable in IDs */
157607  #define CC_DIGIT      3    /* Digits */
157608  #define CC_DOLLAR     4    /* '$' */
157609  #define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
157610  #define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
157611  #define CC_SPACE      7    /* Space characters */
157612  #define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
157613  #define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
157614  #define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
157615  #define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
157616  #define CC_LT        12    /* '<'.  Part of < or <= or <> */
157617  #define CC_GT        13    /* '>'.  Part of > or >= */
157618  #define CC_EQ        14    /* '='.  Part of = or == */
157619  #define CC_BANG      15    /* '!'.  Part of != */
157620  #define CC_SLASH     16    /* '/'.  / or c-style comment */
157621  #define CC_LP        17    /* '(' */
157622  #define CC_RP        18    /* ')' */
157623  #define CC_SEMI      19    /* ';' */
157624  #define CC_PLUS      20    /* '+' */
157625  #define CC_STAR      21    /* '*' */
157626  #define CC_PERCENT   22    /* '%' */
157627  #define CC_COMMA     23    /* ',' */
157628  #define CC_AND       24    /* '&' */
157629  #define CC_TILDA     25    /* '~' */
157630  #define CC_DOT       26    /* '.' */
157631  #define CC_ILLEGAL   27    /* Illegal character */
157632  #define CC_NUL       28    /* 0x00 */
157633  
157634  static const unsigned char aiClass[] = {
157635  #ifdef SQLITE_ASCII
157636  /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
157637  /* 0x */   28, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
157638  /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
157639  /* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
157640  /* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
157641  /* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
157642  /* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
157643  /* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
157644  /* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
157645  /* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157646  /* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157647  /* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157648  /* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157649  /* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157650  /* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157651  /* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
157652  /* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
157653  #endif
157654  #ifdef SQLITE_EBCDIC
157655  /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
157656  /* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
157657  /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
157658  /* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
157659  /* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
157660  /* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
157661  /* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
157662  /* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,
157663  /* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
157664  /* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
157665  /* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
157666  /* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
157667  /* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
157668  /* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
157669  /* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
157670  /* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
157671  /* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
157672  #endif
157673  };
157674  
157675  /*
157676  ** The charMap() macro maps alphabetic characters (only) into their
157677  ** lower-case ASCII equivalent.  On ASCII machines, this is just
157678  ** an upper-to-lower case map.  On EBCDIC machines we also need
157679  ** to adjust the encoding.  The mapping is only valid for alphabetics
157680  ** which are the only characters for which this feature is used. 
157681  **
157682  ** Used by keywordhash.h
157683  */
157684  #ifdef SQLITE_ASCII
157685  # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
157686  #endif
157687  #ifdef SQLITE_EBCDIC
157688  # define charMap(X) ebcdicToAscii[(unsigned char)X]
157689  const unsigned char ebcdicToAscii[] = {
157690  /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
157691     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
157692     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
157693     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
157694     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
157695     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
157696     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
157697     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
157698     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
157699     0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
157700     0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
157701     0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
157702     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
157703     0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
157704     0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
157705     0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
157706     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
157707  };
157708  #endif
157709  
157710  /*
157711  ** The sqlite3KeywordCode function looks up an identifier to determine if
157712  ** it is a keyword.  If it is a keyword, the token code of that keyword is 
157713  ** returned.  If the input is not a keyword, TK_ID is returned.
157714  **
157715  ** The implementation of this routine was generated by a program,
157716  ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
157717  ** The output of the mkkeywordhash.c program is written into a file
157718  ** named keywordhash.h and then included into this source file by
157719  ** the #include below.
157720  */
157721  /************** Include keywordhash.h in the middle of tokenize.c ************/
157722  /************** Begin file keywordhash.h *************************************/
157723  /***** This file contains automatically generated code ******
157724  **
157725  ** The code in this file has been automatically generated by
157726  **
157727  **   sqlite/tool/mkkeywordhash.c
157728  **
157729  ** The code in this file implements a function that determines whether
157730  ** or not a given identifier is really an SQL keyword.  The same thing
157731  ** might be implemented more directly using a hand-written hash table.
157732  ** But by using this automatically generated code, the size of the code
157733  ** is substantially reduced.  This is important for embedded applications
157734  ** on platforms with limited memory.
157735  */
157736  /* Hash score: 208 */
157737  /* zKWText[] encodes 923 bytes of keyword text in 614 bytes */
157738  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
157739  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
157740  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
157741  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERANGEBETWEEN      */
157742  /*   OTHINGLOBYCASCADELETECASECOLLATECREATECURRENT_DATEDETACH           */
157743  /*   IMMEDIATEJOINSERTLIKEMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMIT     */
157744  /*   WHENOTNULLWHERECURSIVEAFTERENAMEANDEFAULTAUTOINCREMENTCAST         */
157745  /*   COLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMPARTITIONDEFERRED         */
157746  /*   ISTINCTDROPRECEDINGFAILFILTEREPLACEFOLLOWINGFROMFULLIFISNULL       */
157747  /*   ORDERESTRICTOVERIGHTROLLBACKROWSUNBOUNDEDUNIONUSINGVACUUMVIEW      */
157748  /*   INDOWINITIALLYPRIMARY                                              */
157749  static const char zKWText[613] = {
157750    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
157751    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
157752    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
157753    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
157754    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
157755    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
157756    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
157757    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
157758    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
157759    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
157760    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
157761    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
157762    'T','E','B','E','G','I','N','N','E','R','A','N','G','E','B','E','T','W',
157763    'E','E','N','O','T','H','I','N','G','L','O','B','Y','C','A','S','C','A',
157764    'D','E','L','E','T','E','C','A','S','E','C','O','L','L','A','T','E','C',
157765    'R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E','D',
157766    'E','T','A','C','H','I','M','M','E','D','I','A','T','E','J','O','I','N',
157767    'S','E','R','T','L','I','K','E','M','A','T','C','H','P','L','A','N','A',
157768    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
157769    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','O',
157770    'T','N','U','L','L','W','H','E','R','E','C','U','R','S','I','V','E','A',
157771    'F','T','E','R','E','N','A','M','E','A','N','D','E','F','A','U','L','T',
157772    'A','U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C',
157773    'O','L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C',
157774    'T','C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E',
157775    'S','T','A','M','P','A','R','T','I','T','I','O','N','D','E','F','E','R',
157776    'R','E','D','I','S','T','I','N','C','T','D','R','O','P','R','E','C','E',
157777    'D','I','N','G','F','A','I','L','F','I','L','T','E','R','E','P','L','A',
157778    'C','E','F','O','L','L','O','W','I','N','G','F','R','O','M','F','U','L',
157779    'L','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T','R',
157780    'I','C','T','O','V','E','R','I','G','H','T','R','O','L','L','B','A','C',
157781    'K','R','O','W','S','U','N','B','O','U','N','D','E','D','U','N','I','O',
157782    'N','U','S','I','N','G','V','A','C','U','U','M','V','I','E','W','I','N',
157783    'D','O','W','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R',
157784    'Y',
157785  };
157786  /* aKWHash[i] is the hash value for the i-th keyword */
157787  static const unsigned char aKWHash[127] = {
157788      74, 109, 124,  72, 106,  45,   0,   0,  81,   0,  76,  61,   0,
157789      42,  12,  77,  15,   0, 123,  84,  54, 118, 125,  19,   0,   0,
157790     130,   0, 128, 121,   0,  22,  96,   0,   9,   0,   0, 115,  69,
157791       0,  67,   6,   0,  48,  93, 136,   0, 126, 104,   0,   0,  44,
157792       0, 107,  24,   0,  17,   0, 131,  53,  23,   0,   5,  62, 132,
157793      99,   0,   0, 135, 110,  60, 134,  57, 113,  55,   0,  94,   0,
157794     103,  26,   0, 102,   0,   0,   0,  98,  95, 100, 105, 117,  14,
157795      39, 116,   0,  80,   0, 133, 114,  92,  59,   0, 129,  79, 119,
157796      86,  46,  83,   0,   0,  97,  40, 122, 120,   0, 127,   0,   0,
157797      29,   0,  89,  87,  88,   0,  20,  85, 111,  56,
157798  };
157799  /* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
157800  ** then the i-th keyword has no more hash collisions.  Otherwise,
157801  ** the next keyword with the same hash is aKWHash[i]-1. */
157802  static const unsigned char aKWNext[136] = {
157803       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
157804       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
157805       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
157806       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
157807       0,  43,   3,  47,   0,   0,  32,   0,   0,   0,   0,   0,   0,
157808       0,   1,  64,   0,   0,  65,   0,  41,   0,  38,   0,   0,   0,
157809       0,   0,  49,  75,   0,   0,  30,   0,  58,   0,   0,   0,  31,
157810      63,  16,  34,  10,   0,   0,   0,   0,   0,   0,   0,  11,  70,
157811      91,   0,   0,   8,   0, 108,   0, 101,  28,  52,  68,   0, 112,
157812       0,  73,  51,   0,  90,  27,  37,   0,  71,  36,  82,   0,  35,
157813      66,  25,  18,   0,   0,  78,
157814  };
157815  /* aKWLen[i] is the length (in bytes) of the i-th keyword */
157816  static const unsigned char aKWLen[136] = {
157817       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
157818       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
157819      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
157820       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
157821       6,   6,   5,   6,   5,   5,   5,   7,   7,   4,   2,   7,   3,
157822       6,   4,   7,   6,  12,   6,   9,   4,   6,   4,   5,   4,   7,
157823       6,   5,   6,   7,   5,   4,   7,   3,   2,   4,   5,   9,   5,
157824       6,   3,   7,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,
157825       7,   9,   8,   8,   2,   4,   9,   4,   6,   7,   9,   4,   4,
157826       2,   6,   5,   8,   4,   5,   8,   4,   3,   9,   5,   5,   6,
157827       4,   6,   2,   9,   3,   7,
157828  };
157829  /* aKWOffset[i] is the index into zKWText[] of the start of
157830  ** the text for the i-th keyword. */
157831  static const unsigned short int aKWOffset[136] = {
157832       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
157833      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
157834      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
157835     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
157836     199, 204, 209, 212, 218, 221, 225, 230, 236, 242, 245, 247, 248,
157837     252, 258, 262, 269, 275, 287, 293, 302, 304, 310, 314, 319, 321,
157838     328, 333, 338, 344, 350, 355, 358, 358, 358, 361, 365, 368, 377,
157839     381, 387, 389, 396, 398, 400, 409, 413, 419, 425, 433, 438, 438,
157840     438, 454, 463, 470, 471, 478, 481, 490, 494, 499, 506, 515, 519,
157841     523, 525, 531, 535, 543, 546, 551, 559, 559, 563, 572, 577, 582,
157842     588, 591, 594, 597, 602, 606,
157843  };
157844  /* aKWCode[i] is the parser symbol code for the i-th keyword */
157845  static const unsigned char aKWCode[136] = {
157846    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
157847    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
157848    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
157849    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
157850    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
157851    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
157852    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
157853    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
157854    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
157855    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
157856    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,      
157857    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RANGE,      TK_BETWEEN,    
157858    TK_NOTHING,    TK_LIKE_KW,    TK_BY,         TK_CASCADE,    TK_ASC,        
157859    TK_DELETE,     TK_CASE,       TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   
157860    TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_LIKE_KW,    
157861    TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      
157862    TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       TK_NOTNULL,    
157863    TK_NOT,        TK_NO,         TK_NULL,       TK_WHERE,      TK_RECURSIVE,  
157864    TK_AFTER,      TK_RENAME,     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   
157865    TK_TO,         TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     
157866    TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_CURRENT,    
157867    TK_PARTITION,  TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       
157868    TK_PRECEDING,  TK_FAIL,       TK_FILTER,     TK_REPLACE,    TK_FOLLOWING,  
157869    TK_FROM,       TK_JOIN_KW,    TK_IF,         TK_ISNULL,     TK_ORDER,      
157870    TK_RESTRICT,   TK_OVER,       TK_JOIN_KW,    TK_ROLLBACK,   TK_ROWS,       
157871    TK_ROW,        TK_UNBOUNDED,  TK_UNION,      TK_USING,      TK_VACUUM,     
157872    TK_VIEW,       TK_WINDOW,     TK_DO,         TK_INITIALLY,  TK_ALL,        
157873    TK_PRIMARY,    
157874  };
157875  /* Check to see if z[0..n-1] is a keyword. If it is, write the
157876  ** parser symbol code for that keyword into *pType.  Always
157877  ** return the integer n (the length of the token). */
157878  static int keywordCode(const char *z, int n, int *pType){
157879    int i, j;
157880    const char *zKW;
157881    if( n>=2 ){
157882      i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
157883      for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
157884        if( aKWLen[i]!=n ) continue;
157885        j = 0;
157886        zKW = &zKWText[aKWOffset[i]];
157887  #ifdef SQLITE_ASCII
157888        while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
157889  #endif
157890  #ifdef SQLITE_EBCDIC
157891        while( j<n && toupper(z[j])==zKW[j] ){ j++; }
157892  #endif
157893        if( j<n ) continue;
157894        testcase( i==0 ); /* REINDEX */
157895        testcase( i==1 ); /* INDEXED */
157896        testcase( i==2 ); /* INDEX */
157897        testcase( i==3 ); /* DESC */
157898        testcase( i==4 ); /* ESCAPE */
157899        testcase( i==5 ); /* EACH */
157900        testcase( i==6 ); /* CHECK */
157901        testcase( i==7 ); /* KEY */
157902        testcase( i==8 ); /* BEFORE */
157903        testcase( i==9 ); /* FOREIGN */
157904        testcase( i==10 ); /* FOR */
157905        testcase( i==11 ); /* IGNORE */
157906        testcase( i==12 ); /* REGEXP */
157907        testcase( i==13 ); /* EXPLAIN */
157908        testcase( i==14 ); /* INSTEAD */
157909        testcase( i==15 ); /* ADD */
157910        testcase( i==16 ); /* DATABASE */
157911        testcase( i==17 ); /* AS */
157912        testcase( i==18 ); /* SELECT */
157913        testcase( i==19 ); /* TABLE */
157914        testcase( i==20 ); /* LEFT */
157915        testcase( i==21 ); /* THEN */
157916        testcase( i==22 ); /* END */
157917        testcase( i==23 ); /* DEFERRABLE */
157918        testcase( i==24 ); /* ELSE */
157919        testcase( i==25 ); /* EXCEPT */
157920        testcase( i==26 ); /* TRANSACTION */
157921        testcase( i==27 ); /* ACTION */
157922        testcase( i==28 ); /* ON */
157923        testcase( i==29 ); /* NATURAL */
157924        testcase( i==30 ); /* ALTER */
157925        testcase( i==31 ); /* RAISE */
157926        testcase( i==32 ); /* EXCLUSIVE */
157927        testcase( i==33 ); /* EXISTS */
157928        testcase( i==34 ); /* SAVEPOINT */
157929        testcase( i==35 ); /* INTERSECT */
157930        testcase( i==36 ); /* TRIGGER */
157931        testcase( i==37 ); /* REFERENCES */
157932        testcase( i==38 ); /* CONSTRAINT */
157933        testcase( i==39 ); /* INTO */
157934        testcase( i==40 ); /* OFFSET */
157935        testcase( i==41 ); /* OF */
157936        testcase( i==42 ); /* SET */
157937        testcase( i==43 ); /* TEMPORARY */
157938        testcase( i==44 ); /* TEMP */
157939        testcase( i==45 ); /* OR */
157940        testcase( i==46 ); /* UNIQUE */
157941        testcase( i==47 ); /* QUERY */
157942        testcase( i==48 ); /* WITHOUT */
157943        testcase( i==49 ); /* WITH */
157944        testcase( i==50 ); /* OUTER */
157945        testcase( i==51 ); /* RELEASE */
157946        testcase( i==52 ); /* ATTACH */
157947        testcase( i==53 ); /* HAVING */
157948        testcase( i==54 ); /* GROUP */
157949        testcase( i==55 ); /* UPDATE */
157950        testcase( i==56 ); /* BEGIN */
157951        testcase( i==57 ); /* INNER */
157952        testcase( i==58 ); /* RANGE */
157953        testcase( i==59 ); /* BETWEEN */
157954        testcase( i==60 ); /* NOTHING */
157955        testcase( i==61 ); /* GLOB */
157956        testcase( i==62 ); /* BY */
157957        testcase( i==63 ); /* CASCADE */
157958        testcase( i==64 ); /* ASC */
157959        testcase( i==65 ); /* DELETE */
157960        testcase( i==66 ); /* CASE */
157961        testcase( i==67 ); /* COLLATE */
157962        testcase( i==68 ); /* CREATE */
157963        testcase( i==69 ); /* CURRENT_DATE */
157964        testcase( i==70 ); /* DETACH */
157965        testcase( i==71 ); /* IMMEDIATE */
157966        testcase( i==72 ); /* JOIN */
157967        testcase( i==73 ); /* INSERT */
157968        testcase( i==74 ); /* LIKE */
157969        testcase( i==75 ); /* MATCH */
157970        testcase( i==76 ); /* PLAN */
157971        testcase( i==77 ); /* ANALYZE */
157972        testcase( i==78 ); /* PRAGMA */
157973        testcase( i==79 ); /* ABORT */
157974        testcase( i==80 ); /* VALUES */
157975        testcase( i==81 ); /* VIRTUAL */
157976        testcase( i==82 ); /* LIMIT */
157977        testcase( i==83 ); /* WHEN */
157978        testcase( i==84 ); /* NOTNULL */
157979        testcase( i==85 ); /* NOT */
157980        testcase( i==86 ); /* NO */
157981        testcase( i==87 ); /* NULL */
157982        testcase( i==88 ); /* WHERE */
157983        testcase( i==89 ); /* RECURSIVE */
157984        testcase( i==90 ); /* AFTER */
157985        testcase( i==91 ); /* RENAME */
157986        testcase( i==92 ); /* AND */
157987        testcase( i==93 ); /* DEFAULT */
157988        testcase( i==94 ); /* AUTOINCREMENT */
157989        testcase( i==95 ); /* TO */
157990        testcase( i==96 ); /* IN */
157991        testcase( i==97 ); /* CAST */
157992        testcase( i==98 ); /* COLUMN */
157993        testcase( i==99 ); /* COMMIT */
157994        testcase( i==100 ); /* CONFLICT */
157995        testcase( i==101 ); /* CROSS */
157996        testcase( i==102 ); /* CURRENT_TIMESTAMP */
157997        testcase( i==103 ); /* CURRENT_TIME */
157998        testcase( i==104 ); /* CURRENT */
157999        testcase( i==105 ); /* PARTITION */
158000        testcase( i==106 ); /* DEFERRED */
158001        testcase( i==107 ); /* DISTINCT */
158002        testcase( i==108 ); /* IS */
158003        testcase( i==109 ); /* DROP */
158004        testcase( i==110 ); /* PRECEDING */
158005        testcase( i==111 ); /* FAIL */
158006        testcase( i==112 ); /* FILTER */
158007        testcase( i==113 ); /* REPLACE */
158008        testcase( i==114 ); /* FOLLOWING */
158009        testcase( i==115 ); /* FROM */
158010        testcase( i==116 ); /* FULL */
158011        testcase( i==117 ); /* IF */
158012        testcase( i==118 ); /* ISNULL */
158013        testcase( i==119 ); /* ORDER */
158014        testcase( i==120 ); /* RESTRICT */
158015        testcase( i==121 ); /* OVER */
158016        testcase( i==122 ); /* RIGHT */
158017        testcase( i==123 ); /* ROLLBACK */
158018        testcase( i==124 ); /* ROWS */
158019        testcase( i==125 ); /* ROW */
158020        testcase( i==126 ); /* UNBOUNDED */
158021        testcase( i==127 ); /* UNION */
158022        testcase( i==128 ); /* USING */
158023        testcase( i==129 ); /* VACUUM */
158024        testcase( i==130 ); /* VIEW */
158025        testcase( i==131 ); /* WINDOW */
158026        testcase( i==132 ); /* DO */
158027        testcase( i==133 ); /* INITIALLY */
158028        testcase( i==134 ); /* ALL */
158029        testcase( i==135 ); /* PRIMARY */
158030        *pType = aKWCode[i];
158031        break;
158032      }
158033    }
158034    return n;
158035  }
158036  SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
158037    int id = TK_ID;
158038    keywordCode((char*)z, n, &id);
158039    return id;
158040  }
158041  #define SQLITE_N_KEYWORD 136
158042  SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
158043    if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
158044    *pzName = zKWText + aKWOffset[i];
158045    *pnName = aKWLen[i];
158046    return SQLITE_OK;
158047  }
158048  SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
158049  SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
158050    return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
158051  }
158052  
158053  /************** End of keywordhash.h *****************************************/
158054  /************** Continuing where we left off in tokenize.c *******************/
158055  
158056  
158057  /*
158058  ** If X is a character that can be used in an identifier then
158059  ** IdChar(X) will be true.  Otherwise it is false.
158060  **
158061  ** For ASCII, any character with the high-order bit set is
158062  ** allowed in an identifier.  For 7-bit characters, 
158063  ** sqlite3IsIdChar[X] must be 1.
158064  **
158065  ** For EBCDIC, the rules are more complex but have the same
158066  ** end result.
158067  **
158068  ** Ticket #1066.  the SQL standard does not allow '$' in the
158069  ** middle of identifiers.  But many SQL implementations do. 
158070  ** SQLite will allow '$' in identifiers for compatibility.
158071  ** But the feature is undocumented.
158072  */
158073  #ifdef SQLITE_ASCII
158074  #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
158075  #endif
158076  #ifdef SQLITE_EBCDIC
158077  SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
158078  /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
158079      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
158080      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
158081      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
158082      0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
158083      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
158084      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
158085      1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
158086      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
158087      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
158088      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
158089      0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
158090      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
158091  };
158092  #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
158093  #endif
158094  
158095  /* Make the IdChar function accessible from ctime.c and alter.c */
158096  SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
158097  
158098  #ifndef SQLITE_OMIT_WINDOWFUNC
158099  /*
158100  ** Return the id of the next token in string (*pz). Before returning, set
158101  ** (*pz) to point to the byte following the parsed token.
158102  */
158103  static int getToken(const unsigned char **pz){
158104    const unsigned char *z = *pz;
158105    int t;                          /* Token type to return */
158106    do {
158107      z += sqlite3GetToken(z, &t);
158108    }while( t==TK_SPACE );
158109    if( t==TK_ID 
158110     || t==TK_STRING 
158111     || t==TK_JOIN_KW 
158112     || t==TK_WINDOW 
158113     || t==TK_OVER 
158114     || sqlite3ParserFallback(t)==TK_ID 
158115    ){
158116      t = TK_ID;
158117    }
158118    *pz = z;
158119    return t;
158120  }
158121  
158122  /*
158123  ** The following three functions are called immediately after the tokenizer
158124  ** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
158125  ** whether the token should be treated as a keyword or an SQL identifier.
158126  ** This cannot be handled by the usual lemon %fallback method, due to
158127  ** the ambiguity in some constructions. e.g.
158128  **
158129  **   SELECT sum(x) OVER ...
158130  **
158131  ** In the above, "OVER" might be a keyword, or it might be an alias for the 
158132  ** sum(x) expression. If a "%fallback ID OVER" directive were added to 
158133  ** grammar, then SQLite would always treat "OVER" as an alias, making it
158134  ** impossible to call a window-function without a FILTER clause.
158135  **
158136  ** WINDOW is treated as a keyword if:
158137  **
158138  **   * the following token is an identifier, or a keyword that can fallback
158139  **     to being an identifier, and
158140  **   * the token after than one is TK_AS.
158141  **
158142  ** OVER is a keyword if:
158143  **
158144  **   * the previous token was TK_RP, and
158145  **   * the next token is either TK_LP or an identifier.
158146  **
158147  ** FILTER is a keyword if:
158148  **
158149  **   * the previous token was TK_RP, and
158150  **   * the next token is TK_LP.
158151  */
158152  static int analyzeWindowKeyword(const unsigned char *z){
158153    int t;
158154    t = getToken(&z);
158155    if( t!=TK_ID ) return TK_ID;
158156    t = getToken(&z);
158157    if( t!=TK_AS ) return TK_ID;
158158    return TK_WINDOW;
158159  }
158160  static int analyzeOverKeyword(const unsigned char *z, int lastToken){
158161    if( lastToken==TK_RP ){
158162      int t = getToken(&z);
158163      if( t==TK_LP || t==TK_ID ) return TK_OVER;
158164    }
158165    return TK_ID;
158166  }
158167  static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
158168    if( lastToken==TK_RP && getToken(&z)==TK_LP ){
158169      return TK_FILTER;
158170    }
158171    return TK_ID;
158172  }
158173  #endif /* SQLITE_OMIT_WINDOWFUNC */
158174  
158175  /*
158176  ** Return the length (in bytes) of the token that begins at z[0]. 
158177  ** Store the token type in *tokenType before returning.
158178  */
158179  SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
158180    int i, c;
158181    switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
158182                            ** of the token. See the comment on the CC_ defines
158183                            ** above. */
158184      case CC_SPACE: {
158185        testcase( z[0]==' ' );
158186        testcase( z[0]=='\t' );
158187        testcase( z[0]=='\n' );
158188        testcase( z[0]=='\f' );
158189        testcase( z[0]=='\r' );
158190        for(i=1; sqlite3Isspace(z[i]); i++){}
158191        *tokenType = TK_SPACE;
158192        return i;
158193      }
158194      case CC_MINUS: {
158195        if( z[1]=='-' ){
158196          for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
158197          *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
158198          return i;
158199        }
158200        *tokenType = TK_MINUS;
158201        return 1;
158202      }
158203      case CC_LP: {
158204        *tokenType = TK_LP;
158205        return 1;
158206      }
158207      case CC_RP: {
158208        *tokenType = TK_RP;
158209        return 1;
158210      }
158211      case CC_SEMI: {
158212        *tokenType = TK_SEMI;
158213        return 1;
158214      }
158215      case CC_PLUS: {
158216        *tokenType = TK_PLUS;
158217        return 1;
158218      }
158219      case CC_STAR: {
158220        *tokenType = TK_STAR;
158221        return 1;
158222      }
158223      case CC_SLASH: {
158224        if( z[1]!='*' || z[2]==0 ){
158225          *tokenType = TK_SLASH;
158226          return 1;
158227        }
158228        for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
158229        if( c ) i++;
158230        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
158231        return i;
158232      }
158233      case CC_PERCENT: {
158234        *tokenType = TK_REM;
158235        return 1;
158236      }
158237      case CC_EQ: {
158238        *tokenType = TK_EQ;
158239        return 1 + (z[1]=='=');
158240      }
158241      case CC_LT: {
158242        if( (c=z[1])=='=' ){
158243          *tokenType = TK_LE;
158244          return 2;
158245        }else if( c=='>' ){
158246          *tokenType = TK_NE;
158247          return 2;
158248        }else if( c=='<' ){
158249          *tokenType = TK_LSHIFT;
158250          return 2;
158251        }else{
158252          *tokenType = TK_LT;
158253          return 1;
158254        }
158255      }
158256      case CC_GT: {
158257        if( (c=z[1])=='=' ){
158258          *tokenType = TK_GE;
158259          return 2;
158260        }else if( c=='>' ){
158261          *tokenType = TK_RSHIFT;
158262          return 2;
158263        }else{
158264          *tokenType = TK_GT;
158265          return 1;
158266        }
158267      }
158268      case CC_BANG: {
158269        if( z[1]!='=' ){
158270          *tokenType = TK_ILLEGAL;
158271          return 1;
158272        }else{
158273          *tokenType = TK_NE;
158274          return 2;
158275        }
158276      }
158277      case CC_PIPE: {
158278        if( z[1]!='|' ){
158279          *tokenType = TK_BITOR;
158280          return 1;
158281        }else{
158282          *tokenType = TK_CONCAT;
158283          return 2;
158284        }
158285      }
158286      case CC_COMMA: {
158287        *tokenType = TK_COMMA;
158288        return 1;
158289      }
158290      case CC_AND: {
158291        *tokenType = TK_BITAND;
158292        return 1;
158293      }
158294      case CC_TILDA: {
158295        *tokenType = TK_BITNOT;
158296        return 1;
158297      }
158298      case CC_QUOTE: {
158299        int delim = z[0];
158300        testcase( delim=='`' );
158301        testcase( delim=='\'' );
158302        testcase( delim=='"' );
158303        for(i=1; (c=z[i])!=0; i++){
158304          if( c==delim ){
158305            if( z[i+1]==delim ){
158306              i++;
158307            }else{
158308              break;
158309            }
158310          }
158311        }
158312        if( c=='\'' ){
158313          *tokenType = TK_STRING;
158314          return i+1;
158315        }else if( c!=0 ){
158316          *tokenType = TK_ID;
158317          return i+1;
158318        }else{
158319          *tokenType = TK_ILLEGAL;
158320          return i;
158321        }
158322      }
158323      case CC_DOT: {
158324  #ifndef SQLITE_OMIT_FLOATING_POINT
158325        if( !sqlite3Isdigit(z[1]) )
158326  #endif
158327        {
158328          *tokenType = TK_DOT;
158329          return 1;
158330        }
158331        /* If the next character is a digit, this is a floating point
158332        ** number that begins with ".".  Fall thru into the next case */
158333      }
158334      case CC_DIGIT: {
158335        testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
158336        testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
158337        testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
158338        testcase( z[0]=='9' );
158339        *tokenType = TK_INTEGER;
158340  #ifndef SQLITE_OMIT_HEX_INTEGER
158341        if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
158342          for(i=3; sqlite3Isxdigit(z[i]); i++){}
158343          return i;
158344        }
158345  #endif
158346        for(i=0; sqlite3Isdigit(z[i]); i++){}
158347  #ifndef SQLITE_OMIT_FLOATING_POINT
158348        if( z[i]=='.' ){
158349          i++;
158350          while( sqlite3Isdigit(z[i]) ){ i++; }
158351          *tokenType = TK_FLOAT;
158352        }
158353        if( (z[i]=='e' || z[i]=='E') &&
158354             ( sqlite3Isdigit(z[i+1]) 
158355              || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
158356             )
158357        ){
158358          i += 2;
158359          while( sqlite3Isdigit(z[i]) ){ i++; }
158360          *tokenType = TK_FLOAT;
158361        }
158362  #endif
158363        while( IdChar(z[i]) ){
158364          *tokenType = TK_ILLEGAL;
158365          i++;
158366        }
158367        return i;
158368      }
158369      case CC_QUOTE2: {
158370        for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
158371        *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
158372        return i;
158373      }
158374      case CC_VARNUM: {
158375        *tokenType = TK_VARIABLE;
158376        for(i=1; sqlite3Isdigit(z[i]); i++){}
158377        return i;
158378      }
158379      case CC_DOLLAR:
158380      case CC_VARALPHA: {
158381        int n = 0;
158382        testcase( z[0]=='$' );  testcase( z[0]=='@' );
158383        testcase( z[0]==':' );  testcase( z[0]=='#' );
158384        *tokenType = TK_VARIABLE;
158385        for(i=1; (c=z[i])!=0; i++){
158386          if( IdChar(c) ){
158387            n++;
158388  #ifndef SQLITE_OMIT_TCL_VARIABLE
158389          }else if( c=='(' && n>0 ){
158390            do{
158391              i++;
158392            }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
158393            if( c==')' ){
158394              i++;
158395            }else{
158396              *tokenType = TK_ILLEGAL;
158397            }
158398            break;
158399          }else if( c==':' && z[i+1]==':' ){
158400            i++;
158401  #endif
158402          }else{
158403            break;
158404          }
158405        }
158406        if( n==0 ) *tokenType = TK_ILLEGAL;
158407        return i;
158408      }
158409      case CC_KYWD: {
158410        for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
158411        if( IdChar(z[i]) ){
158412          /* This token started out using characters that can appear in keywords,
158413          ** but z[i] is a character not allowed within keywords, so this must
158414          ** be an identifier instead */
158415          i++;
158416          break;
158417        }
158418        *tokenType = TK_ID;
158419        return keywordCode((char*)z, i, tokenType);
158420      }
158421      case CC_X: {
158422  #ifndef SQLITE_OMIT_BLOB_LITERAL
158423        testcase( z[0]=='x' ); testcase( z[0]=='X' );
158424        if( z[1]=='\'' ){
158425          *tokenType = TK_BLOB;
158426          for(i=2; sqlite3Isxdigit(z[i]); i++){}
158427          if( z[i]!='\'' || i%2 ){
158428            *tokenType = TK_ILLEGAL;
158429            while( z[i] && z[i]!='\'' ){ i++; }
158430          }
158431          if( z[i] ) i++;
158432          return i;
158433        }
158434  #endif
158435        /* If it is not a BLOB literal, then it must be an ID, since no
158436        ** SQL keywords start with the letter 'x'.  Fall through */
158437      }
158438      case CC_ID: {
158439        i = 1;
158440        break;
158441      }
158442      case CC_NUL: {
158443        *tokenType = TK_ILLEGAL;
158444        return 0;
158445      }
158446      default: {
158447        *tokenType = TK_ILLEGAL;
158448        return 1;
158449      }
158450    }
158451    while( IdChar(z[i]) ){ i++; }
158452    *tokenType = TK_ID;
158453    return i;
158454  }
158455  
158456  /*
158457  ** Run the parser on the given SQL string.  The parser structure is
158458  ** passed in.  An SQLITE_ status code is returned.  If an error occurs
158459  ** then an and attempt is made to write an error message into 
158460  ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
158461  ** error message.
158462  */
158463  SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
158464    int nErr = 0;                   /* Number of errors encountered */
158465    void *pEngine;                  /* The LEMON-generated LALR(1) parser */
158466    int n = 0;                      /* Length of the next token token */
158467    int tokenType;                  /* type of the next token */
158468    int lastTokenParsed = -1;       /* type of the previous token */
158469    sqlite3 *db = pParse->db;       /* The database connection */
158470    int mxSqlLen;                   /* Max length of an SQL string */
158471    const char *zCurSql;            /* The current SQL command being parsed */
158472  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
158473    yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
158474  #endif
158475  
158476    assert( zSql!=0 );
158477    mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
158478    if( db->nVdbeActive==0 ){
158479      db->u1.isInterrupted = 0;
158480    }
158481    pParse->rc = SQLITE_OK;
158482    pParse->zTail = zSql;
158483    zCurSql = zSql;
158484    assert( pzErrMsg!=0 );
158485  #ifdef SQLITE_DEBUG
158486    if( db->flags & SQLITE_ParserTrace ){
158487      printf("parser: [[[%s]]]\n", zSql);
158488      sqlite3ParserTrace(stdout, "parser: ");
158489    }else{
158490      sqlite3ParserTrace(0, 0);
158491    }
158492  #endif
158493  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
158494    pEngine = &sEngine;
158495    sqlite3ParserInit(pEngine, pParse);
158496  #else
158497    pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
158498    if( pEngine==0 ){
158499      sqlite3OomFault(db);
158500      return SQLITE_NOMEM_BKPT;
158501    }
158502  #endif
158503    assert( pParse->pNewTable==0 );
158504    assert( pParse->pNewTrigger==0 );
158505    assert( pParse->nVar==0 );
158506    assert( pParse->pVList==0 );
158507  
158508  //! here instead of the code bellow it could detect the special pragma commands and
158509  //  allocate a new string inside quotes. then release it at the vm disposal.
158510  //  PRAGMA branch=master.3  ->  PRAGMA branch="master.3"
158511  //  PRAGMA new_branch=test at master.10  ->  PRAGMA new_branch="test at master.10"
158512  //  the experimental code is in the "sqlite3-3 - new pragma parsing.c" file.
158513  
158514    /*
158515    ** Implement pragma commands with special syntax:
158516    **  PRAGMA branch=<name>.<commit>  |  =<name>
158517    **  PRAGMA new_branch=<name> at <source>.<commit>
158518    */
158519    if( (zSql[0]=='p' || zSql[0]=='P') && (zSql[1]=='r' || zSql[1]=='R') &&
158520        (zSql[2]=='a' || zSql[2]=='A') && (zSql[3]=='g' || zSql[3]=='G') &&
158521        (zSql[4]=='m' || zSql[4]=='M') && (zSql[5]=='a' || zSql[5]=='A') &&
158522        (zSql[6]==' ')
158523      ){
158524      char *zSqlCopy, *zDb=0, *zCmd, *zArg, *zNext, *p;
158525      BRANCHTRACE("pragma command: %s", (char*)zSql + 7);
158526      //split_token_chr(t, ';', &tNext);
158527      //split_token_chr(t, '=', &tArg);
158528      //split_token_chr(t, '.', &tCmd);
158529      /* create a copy because we will modify it */
158530      zSqlCopy = sqlite3_strdup((char*)zSql);
158531      if( !zSqlCopy ) { db->mallocFailed = 1; goto loc_parse_done; }
158532      /* parse the typed command */
158533      p = zSqlCopy + 7;
158534      while( *p==' ' ) p++;
158535      zNext = stripchr(p, ';'); if( zNext==0 ) zNext=zSqlCopy+strlen(zSqlCopy);
158536      zArg = stripchr(p, '=');
158537      if( zArg==0 ){
158538        zArg = stripchr(p, '(');
158539        if( zArg ){
158540          char *zEnd = zArg + strlen(zArg) - 1;
158541          while( zEnd>=zArg && sqlite3Isspace(*zEnd) ){ *zEnd='\0'; zEnd--; }
158542          if( zEnd>=zArg && *zEnd==')' ) *zEnd='\0';
158543        }
158544      }
158545      if( zArg==0 ) zArg = stripchr(p, ' ');
158546      zCmd = stripchr(p, '.');
158547      if( !zCmd ){
158548        zCmd = p;
158549        zDb = "main";
158550      } else {
158551        zDb = p;
158552      }
158553      if( zArg ){
158554        while( *zArg==' ' ) zArg++;
158555        p = zArg + strlen(zArg) - 1;
158556        while( p>=zArg && sqlite3Isspace(*p) ){ *p='\0'; p--; }
158557      }
158558      /* check the pragma command */
158559      if( sqlite3_stricmp(zCmd,"branch")==0 || sqlite3_stricmp(zCmd,"new_branch")==0 ||
158560          sqlite3_stricmp(zCmd,"rename_branch")==0 || sqlite3_stricmp(zCmd,"branch_diff")==0 || 
158561          sqlite3_stricmp(zCmd,"branch_merge")==0 || sqlite3_stricmp(zCmd,"branch_rebase")==0 ||
158562          sqlite3_stricmp(zCmd,"branch_truncate")==0 || sqlite3_stricmp(zCmd,"branch_log")==0 ||
158563          sqlite3_stricmp(zCmd,"discard_commits")==0 ){
158564        Token tkDb, tkCmd, tkArg;
158565        BRANCHTRACE("processing special pragma command: %s", zCmd);
158566        #define TOKEN_SET(t,s) { t.z=s; if(s) t.n=strlen(s); else t.n=0; }
158567        TOKEN_SET(tkDb, zDb);
158568        TOKEN_SET(tkCmd, zCmd);
158569        TOKEN_SET(tkArg, zArg);
158570        sqlite3Pragma(pParse, &tkDb, &tkCmd, &tkArg, 0);
158571        pParse->zTail = &zSql[zNext-zSqlCopy];
158572        sqlite3_free(zSqlCopy);
158573        sqlite3FinishCoding(pParse);
158574        goto loc_parse_done;
158575      }
158576      sqlite3_free(zSqlCopy);
158577    }
158578  
158579    while( 1 ){
158580      n = sqlite3GetToken((u8*)zSql, &tokenType);
158581      mxSqlLen -= n;
158582      if( mxSqlLen<0 ){
158583        pParse->rc = SQLITE_TOOBIG;
158584        break;
158585      }
158586  #ifndef SQLITE_OMIT_WINDOWFUNC
158587      if( tokenType>=TK_WINDOW ){
158588        assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
158589             || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW 
158590        );
158591  #else
158592      if( tokenType>=TK_SPACE ){
158593        assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
158594  #endif /* SQLITE_OMIT_WINDOWFUNC */
158595        if( db->u1.isInterrupted ){
158596          pParse->rc = SQLITE_INTERRUPT;
158597          break;
158598        }
158599        if( tokenType==TK_SPACE ){
158600          zSql += n;
158601          continue;
158602        }
158603        if( zSql[0]==0 ){
158604          /* Upon reaching the end of input, call the parser two more times
158605          ** with tokens TK_SEMI and 0, in that order. */
158606          if( lastTokenParsed==TK_SEMI ){
158607            tokenType = 0;
158608          }else if( lastTokenParsed==0 ){
158609            break;
158610          }else{
158611            tokenType = TK_SEMI;
158612          }
158613          n = 0;
158614  #ifndef SQLITE_OMIT_WINDOWFUNC
158615        }else if( tokenType==TK_WINDOW ){
158616          assert( n==6 );
158617          tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
158618        }else if( tokenType==TK_OVER ){
158619          assert( n==4 );
158620          tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
158621        }else if( tokenType==TK_FILTER ){
158622          assert( n==6 );
158623          tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
158624  #endif /* SQLITE_OMIT_WINDOWFUNC */
158625        }else{
158626          sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
158627          break;
158628        }
158629      }
158630      pParse->sLastToken.z = zSql;
158631      pParse->sLastToken.n = n;
158632      sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
158633      lastTokenParsed = tokenType;
158634      zSql += n;
158635      if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
158636    }
158637    pParse->zTail = zSql;
158638    assert( nErr==0 );
158639  
158640  loc_parse_done:
158641  
158642  #ifdef YYTRACKMAXSTACKDEPTH
158643    sqlite3_mutex_enter(sqlite3MallocMutex());
158644    sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
158645        sqlite3ParserStackPeak(pEngine)
158646    );
158647    sqlite3_mutex_leave(sqlite3MallocMutex());
158648  #endif /* YYDEBUG */
158649  #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
158650    sqlite3ParserFinalize(pEngine);
158651  #else
158652    sqlite3ParserFree(pEngine, sqlite3_free);
158653  #endif
158654    if( db->mallocFailed ){
158655      pParse->rc = SQLITE_NOMEM_BKPT;
158656    }
158657    if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
158658      pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
158659    }
158660    assert( pzErrMsg!=0 );
158661    if( pParse->zErrMsg ){
158662      *pzErrMsg = pParse->zErrMsg;
158663      sqlite3_log(pParse->rc, "%s in \"%s\"", 
158664                  *pzErrMsg, zCurSql);
158665      pParse->zErrMsg = 0;
158666      nErr++;
158667    }
158668    if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
158669      sqlite3VdbeDelete(pParse->pVdbe);
158670      pParse->pVdbe = 0;
158671    }
158672  #ifndef SQLITE_OMIT_SHARED_CACHE
158673    if( pParse->nested==0 ){
158674      sqlite3DbFree(db, pParse->aTableLock);
158675      pParse->aTableLock = 0;
158676      pParse->nTableLock = 0;
158677    }
158678  #endif
158679  #ifndef SQLITE_OMIT_VIRTUALTABLE
158680    sqlite3_free(pParse->apVtabLock);
158681  #endif
158682  
158683    if( !IN_SPECIAL_PARSE ){
158684      /* If the pParse->declareVtab flag is set, do not delete any table 
158685      ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
158686      ** will take responsibility for freeing the Table structure.
158687      */
158688      sqlite3DeleteTable(db, pParse->pNewTable);
158689    }
158690    if( !IN_RENAME_OBJECT ){
158691      sqlite3DeleteTrigger(db, pParse->pNewTrigger);
158692    }
158693  
158694    if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
158695    sqlite3DbFree(db, pParse->pVList);
158696    while( pParse->pAinc ){
158697      AutoincInfo *p = pParse->pAinc;
158698      pParse->pAinc = p->pNext;
158699      sqlite3DbFreeNN(db, p);
158700    }
158701    while( pParse->pZombieTab ){
158702      Table *p = pParse->pZombieTab;
158703      pParse->pZombieTab = p->pNextZombie;
158704      sqlite3DeleteTable(db, p);
158705    }
158706    assert( nErr==0 || pParse->rc!=SQLITE_OK );
158707    return nErr;
158708  }
158709  
158710  
158711  #ifdef SQLITE_ENABLE_NORMALIZE
158712  /*
158713  ** Insert a single space character into pStr if the current string
158714  ** ends with an identifier
158715  */
158716  static void addSpaceSeparator(sqlite3_str *pStr){
158717    if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
158718      sqlite3_str_append(pStr, " ", 1);
158719    }
158720  }
158721  
158722  /*
158723  ** Compute a normalization of the SQL given by zSql[0..nSql-1].  Return
158724  ** the normalization in space obtained from sqlite3DbMalloc().  Or return
158725  ** NULL if anything goes wrong or if zSql is NULL.
158726  */
158727  SQLITE_PRIVATE char *sqlite3Normalize(
158728    Vdbe *pVdbe,       /* VM being reprepared */
158729    const char *zSql   /* The original SQL string */
158730  ){
158731    sqlite3 *db;       /* The database connection */
158732    int i;             /* Next unread byte of zSql[] */
158733    int n;             /* length of current token */
158734    int tokenType;     /* type of current token */
158735    int prevType = 0;  /* Previous non-whitespace token */
158736    int nParen;        /* Number of nested levels of parentheses */
158737    int iStartIN;      /* Start of RHS of IN operator in z[] */
158738    int nParenAtIN;    /* Value of nParent at start of RHS of IN operator */
158739    int j;             /* Bytes of normalized SQL generated so far */
158740    sqlite3_str *pStr; /* The normalized SQL string under construction */
158741  
158742    db = sqlite3VdbeDb(pVdbe);
158743    tokenType = -1;
158744    nParen = iStartIN = nParenAtIN = 0;
158745    pStr = sqlite3_str_new(db);
158746    assert( pStr!=0 );  /* sqlite3_str_new() never returns NULL */
158747    for(i=0; zSql[i] && pStr->accError==0; i+=n){
158748      if( tokenType!=TK_SPACE ){
158749        prevType = tokenType;
158750      }
158751      n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
158752      if( NEVER(n<=0) ) break;
158753      switch( tokenType ){
158754        case TK_SPACE: {
158755          break;
158756        }
158757        case TK_NULL: {
158758          if( prevType==TK_IS || prevType==TK_NOT ){
158759            sqlite3_str_append(pStr, " NULL", 5);
158760            break;
158761          }
158762          /* Fall through */
158763        }
158764        case TK_STRING:
158765        case TK_INTEGER:
158766        case TK_FLOAT:
158767        case TK_VARIABLE:
158768        case TK_BLOB: {
158769          sqlite3_str_append(pStr, "?", 1);
158770          break;
158771        }
158772        case TK_LP: {
158773          nParen++;
158774          if( prevType==TK_IN ){
158775            iStartIN = pStr->nChar;
158776            nParenAtIN = nParen;
158777          }
158778          sqlite3_str_append(pStr, "(", 1);
158779          break;
158780        }
158781        case TK_RP: {
158782          if( iStartIN>0 && nParen==nParenAtIN ){
158783            assert( pStr->nChar>=iStartIN );
158784            pStr->nChar = iStartIN+1;
158785            sqlite3_str_append(pStr, "?,?,?", 5);
158786            iStartIN = 0;
158787          }
158788          nParen--;
158789          sqlite3_str_append(pStr, ")", 1);
158790          break;
158791        }
158792        case TK_ID: {
158793          iStartIN = 0;
158794          j = pStr->nChar;
158795          if( sqlite3Isquote(zSql[i]) ){
158796            char *zId = sqlite3DbStrNDup(db, zSql+i, n);
158797            int nId;
158798            int eType = 0;
158799            if( zId==0 ) break;
158800            sqlite3Dequote(zId);
158801            if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
158802              sqlite3_str_append(pStr, "?", 1);
158803              sqlite3DbFree(db, zId);
158804              break;
158805            }
158806            nId = sqlite3Strlen30(zId);
158807            if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
158808              addSpaceSeparator(pStr);
158809              sqlite3_str_append(pStr, zId, nId);
158810            }else{
158811              sqlite3_str_appendf(pStr, "\"%w\"", zId);
158812            }
158813            sqlite3DbFree(db, zId);
158814          }else{
158815            addSpaceSeparator(pStr);
158816            sqlite3_str_append(pStr, zSql+i, n);
158817          }
158818          while( j<pStr->nChar ){
158819            pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
158820            j++;
158821          }
158822          break;
158823        }
158824        case TK_SELECT: {
158825          iStartIN = 0;
158826          /* fall through */
158827        }
158828        default: {
158829          if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
158830          j = pStr->nChar;
158831          sqlite3_str_append(pStr, zSql+i, n);
158832          while( j<pStr->nChar ){
158833            pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
158834            j++;
158835          }
158836          break;
158837        }
158838      }
158839    }
158840    if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
158841    return sqlite3_str_finish(pStr);
158842  }
158843  #endif /* SQLITE_ENABLE_NORMALIZE */
158844  
158845  /************** End of tokenize.c ********************************************/
158846  /************** Begin file complete.c ****************************************/
158847  /*
158848  ** 2001 September 15
158849  **
158850  ** The author disclaims copyright to this source code.  In place of
158851  ** a legal notice, here is a blessing:
158852  **
158853  **    May you do good and not evil.
158854  **    May you find forgiveness for yourself and forgive others.
158855  **    May you share freely, never taking more than you give.
158856  **
158857  *************************************************************************
158858  ** An tokenizer for SQL
158859  **
158860  ** This file contains C code that implements the sqlite3_complete() API.
158861  ** This code used to be part of the tokenizer.c source file.  But by
158862  ** separating it out, the code will be automatically omitted from
158863  ** static links that do not use it.
158864  */
158865  /* #include "sqliteInt.h" */
158866  #ifndef SQLITE_OMIT_COMPLETE
158867  
158868  /*
158869  ** This is defined in tokenize.c.  We just have to import the definition.
158870  */
158871  #ifndef SQLITE_AMALGAMATION
158872  #ifdef SQLITE_ASCII
158873  #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
158874  #endif
158875  #ifdef SQLITE_EBCDIC
158876  SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
158877  #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
158878  #endif
158879  #endif /* SQLITE_AMALGAMATION */
158880  
158881  
158882  /*
158883  ** Token types used by the sqlite3_complete() routine.  See the header
158884  ** comments on that procedure for additional information.
158885  */
158886  #define tkSEMI    0
158887  #define tkWS      1
158888  #define tkOTHER   2
158889  #ifndef SQLITE_OMIT_TRIGGER
158890  #define tkEXPLAIN 3
158891  #define tkCREATE  4
158892  #define tkTEMP    5
158893  #define tkTRIGGER 6
158894  #define tkEND     7
158895  #endif
158896  
158897  /*
158898  ** Return TRUE if the given SQL string ends in a semicolon.
158899  **
158900  ** Special handling is require for CREATE TRIGGER statements.
158901  ** Whenever the CREATE TRIGGER keywords are seen, the statement
158902  ** must end with ";END;".
158903  **
158904  ** This implementation uses a state machine with 8 states:
158905  **
158906  **   (0) INVALID   We have not yet seen a non-whitespace character.
158907  **
158908  **   (1) START     At the beginning or end of an SQL statement.  This routine
158909  **                 returns 1 if it ends in the START state and 0 if it ends
158910  **                 in any other state.
158911  **
158912  **   (2) NORMAL    We are in the middle of statement which ends with a single
158913  **                 semicolon.
158914  **
158915  **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
158916  **                 a statement.
158917  **
158918  **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
158919  **                 statement, possibly preceded by EXPLAIN and/or followed by
158920  **                 TEMP or TEMPORARY
158921  **
158922  **   (5) TRIGGER   We are in the middle of a trigger definition that must be
158923  **                 ended by a semicolon, the keyword END, and another semicolon.
158924  **
158925  **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
158926  **                 the end of a trigger definition.
158927  **
158928  **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
158929  **                 of a trigger definition.
158930  **
158931  ** Transitions between states above are determined by tokens extracted
158932  ** from the input.  The following tokens are significant:
158933  **
158934  **   (0) tkSEMI      A semicolon.
158935  **   (1) tkWS        Whitespace.
158936  **   (2) tkOTHER     Any other SQL token.
158937  **   (3) tkEXPLAIN   The "explain" keyword.
158938  **   (4) tkCREATE    The "create" keyword.
158939  **   (5) tkTEMP      The "temp" or "temporary" keyword.
158940  **   (6) tkTRIGGER   The "trigger" keyword.
158941  **   (7) tkEND       The "end" keyword.
158942  **
158943  ** Whitespace never causes a state transition and is always ignored.
158944  ** This means that a SQL string of all whitespace is invalid.
158945  **
158946  ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
158947  ** to recognize the end of a trigger can be omitted.  All we have to do
158948  ** is look for a semicolon that is not part of an string or comment.
158949  */
158950  SQLITE_API int sqlite3_complete(const char *zSql){
158951    u8 state = 0;   /* Current state, using numbers defined in header comment */
158952    u8 token;       /* Value of the next token */
158953  
158954  #ifndef SQLITE_OMIT_TRIGGER
158955    /* A complex statement machine used to detect the end of a CREATE TRIGGER
158956    ** statement.  This is the normal case.
158957    */
158958    static const u8 trans[8][8] = {
158959                       /* Token:                                                */
158960       /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
158961       /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
158962       /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
158963       /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
158964       /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
158965       /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
158966       /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
158967       /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
158968       /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
158969    };
158970  #else
158971    /* If triggers are not supported by this compile then the statement machine
158972    ** used to detect the end of a statement is much simpler
158973    */
158974    static const u8 trans[3][3] = {
158975                       /* Token:           */
158976       /* State:       **  SEMI  WS  OTHER */
158977       /* 0 INVALID: */ {    1,  0,     2, },
158978       /* 1   START: */ {    1,  1,     2, },
158979       /* 2  NORMAL: */ {    1,  2,     2, },
158980    };
158981  #endif /* SQLITE_OMIT_TRIGGER */
158982  
158983  #ifdef SQLITE_ENABLE_API_ARMOR
158984    if( zSql==0 ){
158985      (void)SQLITE_MISUSE_BKPT;
158986      return 0;
158987    }
158988  #endif
158989  
158990    while( *zSql ){
158991      switch( *zSql ){
158992        case ';': {  /* A semicolon */
158993          token = tkSEMI;
158994          break;
158995        }
158996        case ' ':
158997        case '\r':
158998        case '\t':
158999        case '\n':
159000        case '\f': {  /* White space is ignored */
159001          token = tkWS;
159002          break;
159003        }
159004        case '/': {   /* C-style comments */
159005          if( zSql[1]!='*' ){
159006            token = tkOTHER;
159007            break;
159008          }
159009          zSql += 2;
159010          while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
159011          if( zSql[0]==0 ) return 0;
159012          zSql++;
159013          token = tkWS;
159014          break;
159015        }
159016        case '-': {   /* SQL-style comments from "--" to end of line */
159017          if( zSql[1]!='-' ){
159018            token = tkOTHER;
159019            break;
159020          }
159021          while( *zSql && *zSql!='\n' ){ zSql++; }
159022          if( *zSql==0 ) return state==1;
159023          token = tkWS;
159024          break;
159025        }
159026        case '[': {   /* Microsoft-style identifiers in [...] */
159027          zSql++;
159028          while( *zSql && *zSql!=']' ){ zSql++; }
159029          if( *zSql==0 ) return 0;
159030          token = tkOTHER;
159031          break;
159032        }
159033        case '`':     /* Grave-accent quoted symbols used by MySQL */
159034        case '"':     /* single- and double-quoted strings */
159035        case '\'': {
159036          int c = *zSql;
159037          zSql++;
159038          while( *zSql && *zSql!=c ){ zSql++; }
159039          if( *zSql==0 ) return 0;
159040          token = tkOTHER;
159041          break;
159042        }
159043        default: {
159044  #ifdef SQLITE_EBCDIC
159045          unsigned char c;
159046  #endif
159047          if( IdChar((u8)*zSql) ){
159048            /* Keywords and unquoted identifiers */
159049            int nId;
159050            for(nId=1; IdChar(zSql[nId]); nId++){}
159051  #ifdef SQLITE_OMIT_TRIGGER
159052            token = tkOTHER;
159053  #else
159054            switch( *zSql ){
159055              case 'c': case 'C': {
159056                if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
159057                  token = tkCREATE;
159058                }else{
159059                  token = tkOTHER;
159060                }
159061                break;
159062              }
159063              case 't': case 'T': {
159064                if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
159065                  token = tkTRIGGER;
159066                }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
159067                  token = tkTEMP;
159068                }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
159069                  token = tkTEMP;
159070                }else{
159071                  token = tkOTHER;
159072                }
159073                break;
159074              }
159075              case 'e':  case 'E': {
159076                if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
159077                  token = tkEND;
159078                }else
159079  #ifndef SQLITE_OMIT_EXPLAIN
159080                if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
159081                  token = tkEXPLAIN;
159082                }else
159083  #endif
159084                {
159085                  token = tkOTHER;
159086                }
159087                break;
159088              }
159089              default: {
159090                token = tkOTHER;
159091                break;
159092              }
159093            }
159094  #endif /* SQLITE_OMIT_TRIGGER */
159095            zSql += nId-1;
159096          }else{
159097            /* Operators and special symbols */
159098            token = tkOTHER;
159099          }
159100          break;
159101        }
159102      }
159103      state = trans[state][token];
159104      zSql++;
159105    }
159106    return state==1;
159107  }
159108  
159109  #ifndef SQLITE_OMIT_UTF16
159110  /*
159111  ** This routine is the same as the sqlite3_complete() routine described
159112  ** above, except that the parameter is required to be UTF-16 encoded, not
159113  ** UTF-8.
159114  */
159115  SQLITE_API int sqlite3_complete16(const void *zSql){
159116    sqlite3_value *pVal;
159117    char const *zSql8;
159118    int rc;
159119  
159120  #ifndef SQLITE_OMIT_AUTOINIT
159121    rc = sqlite3_initialize();
159122    if( rc ) return rc;
159123  #endif
159124    pVal = sqlite3ValueNew(0);
159125    sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
159126    zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
159127    if( zSql8 ){
159128      rc = sqlite3_complete(zSql8);
159129    }else{
159130      rc = SQLITE_NOMEM_BKPT;
159131    }
159132    sqlite3ValueFree(pVal);
159133    return rc & 0xff;
159134  }
159135  #endif /* SQLITE_OMIT_UTF16 */
159136  #endif /* SQLITE_OMIT_COMPLETE */
159137  
159138  /************** End of complete.c ********************************************/
159139  /************** Begin file main.c ********************************************/
159140  /*
159141  ** 2001 September 15
159142  **
159143  ** The author disclaims copyright to this source code.  In place of
159144  ** a legal notice, here is a blessing:
159145  **
159146  **    May you do good and not evil.
159147  **    May you find forgiveness for yourself and forgive others.
159148  **    May you share freely, never taking more than you give.
159149  **
159150  *************************************************************************
159151  ** Main file for the SQLite library.  The routines in this file
159152  ** implement the programmer interface to the library.  Routines in
159153  ** other files are for internal use by SQLite and should not be
159154  ** accessed by users of the library.
159155  */
159156  /* #include "sqliteInt.h" */
159157  
159158  #ifdef SQLITE_ENABLE_FTS3
159159  /************** Include fts3.h in the middle of main.c ***********************/
159160  /************** Begin file fts3.h ********************************************/
159161  /*
159162  ** 2006 Oct 10
159163  **
159164  ** The author disclaims copyright to this source code.  In place of
159165  ** a legal notice, here is a blessing:
159166  **
159167  **    May you do good and not evil.
159168  **    May you find forgiveness for yourself and forgive others.
159169  **    May you share freely, never taking more than you give.
159170  **
159171  ******************************************************************************
159172  **
159173  ** This header file is used by programs that want to link against the
159174  ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
159175  */
159176  /* #include "sqlite3.h" */
159177  
159178  #if 0
159179  extern "C" {
159180  #endif  /* __cplusplus */
159181  
159182  SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
159183  
159184  #if 0
159185  }  /* extern "C" */
159186  #endif  /* __cplusplus */
159187  
159188  /************** End of fts3.h ************************************************/
159189  /************** Continuing where we left off in main.c ***********************/
159190  #endif
159191  #ifdef SQLITE_ENABLE_RTREE
159192  /************** Include rtree.h in the middle of main.c **********************/
159193  /************** Begin file rtree.h *******************************************/
159194  /*
159195  ** 2008 May 26
159196  **
159197  ** The author disclaims copyright to this source code.  In place of
159198  ** a legal notice, here is a blessing:
159199  **
159200  **    May you do good and not evil.
159201  **    May you find forgiveness for yourself and forgive others.
159202  **    May you share freely, never taking more than you give.
159203  **
159204  ******************************************************************************
159205  **
159206  ** This header file is used by programs that want to link against the
159207  ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
159208  */
159209  /* #include "sqlite3.h" */
159210  
159211  #ifdef SQLITE_OMIT_VIRTUALTABLE
159212  # undef SQLITE_ENABLE_RTREE
159213  #endif
159214  
159215  #if 0
159216  extern "C" {
159217  #endif  /* __cplusplus */
159218  
159219  SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
159220  
159221  #if 0
159222  }  /* extern "C" */
159223  #endif  /* __cplusplus */
159224  
159225  /************** End of rtree.h ***********************************************/
159226  /************** Continuing where we left off in main.c ***********************/
159227  #endif
159228  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
159229  /************** Include sqliteicu.h in the middle of main.c ******************/
159230  /************** Begin file sqliteicu.h ***************************************/
159231  /*
159232  ** 2008 May 26
159233  **
159234  ** The author disclaims copyright to this source code.  In place of
159235  ** a legal notice, here is a blessing:
159236  **
159237  **    May you do good and not evil.
159238  **    May you find forgiveness for yourself and forgive others.
159239  **    May you share freely, never taking more than you give.
159240  **
159241  ******************************************************************************
159242  **
159243  ** This header file is used by programs that want to link against the
159244  ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
159245  */
159246  /* #include "sqlite3.h" */
159247  
159248  #if 0
159249  extern "C" {
159250  #endif  /* __cplusplus */
159251  
159252  SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
159253  
159254  #if 0
159255  }  /* extern "C" */
159256  #endif  /* __cplusplus */
159257  
159258  
159259  /************** End of sqliteicu.h *******************************************/
159260  /************** Continuing where we left off in main.c ***********************/
159261  #endif
159262  #ifdef SQLITE_ENABLE_JSON1
159263  SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
159264  #endif
159265  #ifdef SQLITE_ENABLE_STMTVTAB
159266  SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
159267  #endif
159268  #ifdef SQLITE_ENABLE_FTS5
159269  SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
159270  #endif
159271  
159272  #ifndef SQLITE_AMALGAMATION
159273  /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
159274  ** contains the text of SQLITE_VERSION macro. 
159275  */
159276  SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
159277  #endif
159278  
159279  /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
159280  ** a pointer to the to the sqlite3_version[] string constant. 
159281  */
159282  SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
159283  
159284  /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
159285  ** pointer to a string constant whose value is the same as the
159286  ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
159287  ** an edited copy of the amalgamation, then the last four characters of
159288  ** the hash might be different from SQLITE_SOURCE_ID.
159289  */
159290  /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
159291  
159292  /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
159293  ** returns an integer equal to SQLITE_VERSION_NUMBER.
159294  */
159295  SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
159296  
159297  /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
159298  ** zero if and only if SQLite was compiled with mutexing code omitted due to
159299  ** the SQLITE_THREADSAFE compile-time option being set to 0.
159300  */
159301  SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
159302  
159303  /*
159304  ** When compiling the test fixture or with debugging enabled (on Win32),
159305  ** this variable being set to non-zero will cause OSTRACE macros to emit
159306  ** extra diagnostic information.
159307  */
159308  #ifdef SQLITE_HAVE_OS_TRACE
159309  # ifndef SQLITE_DEBUG_OS_TRACE
159310  #   define SQLITE_DEBUG_OS_TRACE 0
159311  # endif
159312    int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
159313  #endif
159314  
159315  #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
159316  /*
159317  ** If the following function pointer is not NULL and if
159318  ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
159319  ** I/O active are written using this function.  These messages
159320  ** are intended for debugging activity only.
159321  */
159322  SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
159323  #endif
159324  
159325  /*
159326  ** If the following global variable points to a string which is the
159327  ** name of a directory, then that directory will be used to store
159328  ** temporary files.
159329  **
159330  ** See also the "PRAGMA temp_store_directory" SQL command.
159331  */
159332  SQLITE_API char *sqlite3_temp_directory = 0;
159333  
159334  /*
159335  ** If the following global variable points to a string which is the
159336  ** name of a directory, then that directory will be used to store
159337  ** all database files specified with a relative pathname.
159338  **
159339  ** See also the "PRAGMA data_store_directory" SQL command.
159340  */
159341  SQLITE_API char *sqlite3_data_directory = 0;
159342  
159343  /************** Include nullvfs.c in the middle of main.c ********************/
159344  /************** Begin file nullvfs.c *****************************************/
159345  /*
159346  ** 2010 April 7
159347  **
159348  ** The author disclaims copyright to this source code.  In place of
159349  ** a legal notice, here is a blessing:
159350  **
159351  **    May you do good and not evil.
159352  **    May you find forgiveness for yourself and forgive others.
159353  **    May you share freely, never taking more than you give.
159354  **
159355  ******************************************************************************
159356  **
159357  ** Implements a Null VFS. Useful when storing data outside of normal SQLite
159358  ** files.
159359  */
159360  
159361  /*
159362  ** The maximum pathname length supported by this VFS.
159363  */
159364  #if SQLITE_OS_WIN
159365  #ifdef SQLITE_WIN32_HAS_WIDE
159366  #define NULLVFS_MAXPATHNAME SQLITE_WINNT_MAX_PATH_BYTES
159367  #else
159368  #define NULLVFS_MAXPATHNAME SQLITE_WIN32_MAX_PATH_BYTES
159369  #endif
159370  #else
159371  #define NULLVFS_MAXPATHNAME MAX_PATHNAME
159372  #endif
159373  
159374  /*
159375  ** When using this VFS, the sqlite3_file* handles that SQLite uses are
159376  ** actually pointers to instances of type NullFile.
159377  */
159378  typedef struct NullFile NullFile;
159379  struct NullFile {
159380    sqlite3_file base;              /* Base class. Must be first. */
159381    int lock;
159382  };
159383  
159384  static int nullDirectWrite(
159385    NullFile *p,                    /* File handle */
159386    const void *zBuf,               /* Buffer containing data to write */
159387    int iAmt,                       /* Size of data to write in bytes */
159388    sqlite_int64 iOfst              /* File offset to write to */
159389  ){
159390    BRANCHTRACE("nullDirectWrite");
159391    return SQLITE_OK;
159392  }
159393  
159394  static int nullClose(sqlite3_file *pFile){
159395    BRANCHTRACE("nullClose");
159396    return SQLITE_OK;
159397  }
159398  
159399  /*
159400  ** Read data from a file.
159401  */
159402  static int nullRead(
159403    sqlite3_file *pFile,
159404    void *zBuf,
159405    int iAmt,
159406    sqlite_int64 iOfst
159407  ){
159408    BRANCHTRACE("nullRead %d bytes at offset %lld", iAmt, iOfst);
159409    return SQLITE_IOERR_SHORT_READ;
159410  }
159411  
159412  /*
159413  ** Write data to a crash-file.
159414  */
159415  static int nullWrite(
159416    sqlite3_file *pFile,
159417    const void *zBuf,
159418    int iAmt,
159419    sqlite_int64 iOfst
159420  ){
159421    NullFile *p = (NullFile*)pFile;
159422    BRANCHTRACE("nullWrite %d bytes at offset %lld", iAmt, iOfst);
159423    return nullDirectWrite(p,zBuf,iAmt,iOfst);
159424  }
159425  
159426  /*
159427  ** Truncate a file. This is a no-op for this VFS (see header comments at
159428  ** the top of the file).
159429  */
159430  static int nullTruncate(sqlite3_file *pFile, sqlite_int64 size){
159431    BRANCHTRACE("nullTruncate - size: %lld bytes", size);
159432    return SQLITE_OK;
159433  }
159434  
159435  /*
159436  ** Sync the contents of the file to the persistent media.
159437  */
159438  static int nullSync(sqlite3_file *pFile, int flags){
159439    BRANCHTRACE("nullSync");
159440    return SQLITE_OK;
159441  }
159442  
159443  /*
159444  ** Write the size of the file in bytes to *pSize.
159445  */
159446  static int nullFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
159447    // NullFile *p = (NullFile*)pFile;
159448    // *pSize = p->size;
159449    BRANCHTRACE("nullFileSize");
159450    *pSize = SQLITE_DEFAULT_PAGE_SIZE;
159451    return SQLITE_OK;
159452  }
159453  
159454  static int nullLock(sqlite3_file *pFile, int eLock){
159455    NullFile *p = (NullFile*)pFile;
159456    BRANCHTRACE("nullLock");
159457    if (p->lock < eLock)
159458      p->lock = eLock;
159459    return SQLITE_OK;
159460  }
159461  static int nullUnlock(sqlite3_file *pFile, int eLock){
159462    NullFile *p = (NullFile*)pFile;
159463    BRANCHTRACE("nullUnlock");
159464    if (p->lock > eLock)
159465      p->lock = eLock;
159466    return SQLITE_OK;
159467  }
159468  static int nullCheckReservedLock(sqlite3_file *pFile, int *pResOut){
159469    BRANCHTRACE("nullCheckReservedLock");
159470    *pResOut = 0;
159471    return SQLITE_OK;
159472  }
159473  
159474  static int nullFileControl(sqlite3_file *pFile, int op, void *pArg){
159475    // if( op==SQLITE_FCNTL_SIZE_HINT ){
159476    //     printf("SIZEHINT %lld\n",*(i64*)pArg);
159477    // }
159478    NullFile *p = (NullFile*)pFile;
159479    BRANCHTRACE("nullFileControl op=%d", op);
159480    switch( op ){
159481    case SQLITE_FCNTL_WAL_BLOCK: {
159482      return SQLITE_OK;
159483    }
159484    case SQLITE_FCNTL_LOCKSTATE: {
159485      *(int*)pArg = p->lock;
159486      return SQLITE_OK;
159487    }
159488    case SQLITE_FCNTL_LAST_ERRNO: {
159489      *(int*)pArg = 0;
159490      return SQLITE_OK;
159491    }
159492    case SQLITE_FCNTL_CHUNK_SIZE: {
159493      return SQLITE_OK;
159494    }
159495    case SQLITE_FCNTL_SIZE_HINT: {
159496      return SQLITE_OK;
159497    }
159498    case SQLITE_FCNTL_PERSIST_WAL: {
159499      return SQLITE_OK;
159500    }
159501    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
159502      return SQLITE_OK;
159503    }
159504    case SQLITE_FCNTL_VFSNAME: {
159505      *(char**)pArg = "null";
159506      return SQLITE_OK;
159507    }
159508    case SQLITE_FCNTL_TEMPFILENAME: {
159509      *(char**)pArg = "123";
159510      return SQLITE_OK;
159511    }
159512    case SQLITE_FCNTL_HAS_MOVED: {
159513      *(int*)pArg = 0;
159514      return SQLITE_OK;
159515    }
159516  #if SQLITE_MAX_MMAP_SIZE>0
159517    case SQLITE_FCNTL_MMAP_SIZE: {
159518      return SQLITE_OK;
159519    }
159520  #endif
159521  #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
159522    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
159523    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
159524      return SQLITE_OK;
159525    }
159526  #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
159527  }
159528  return SQLITE_NOTFOUND;
159529  }
159530  
159531  #ifdef UNUSED_FUNCTION
159532  
159533  static int nullSectorSize(sqlite3_file *pFile){
159534    BRANCHTRACE("nullSectorSize");
159535    return SQLITE_DEFAULT_SECTOR_SIZE;
159536  }
159537  static int nullDeviceCharacteristics(sqlite3_file *pFile){
159538    BRANCHTRACE("nullDeviceCharacteristics");
159539    return 0;
159540  }
159541  
159542  #endif
159543  
159544  static int nullShmMap(
159545    sqlite3_file *fd,               /* Handle open on database file */
159546    int iRegion,                    /* Region to retrieve */
159547    int szRegion,                   /* Size of regions */
159548    int bExtend,                    /* True to extend file if necessary */
159549    void volatile **pp              /* OUT: Mapped memory */
159550  ){ return SQLITE_OK; }
159551  
159552  static int nullShmLock(
159553    sqlite3_file *fd,          /* Database file holding the shared memory */
159554    int ofst,                  /* First lock to acquire or release */
159555    int n,                     /* Number of locks to acquire or release */
159556    int flags                  /* What to do with the lock */
159557  ){ return SQLITE_OK; }
159558  
159559  static void nullShmBarrier(
159560    sqlite3_file *fd                /* Database file holding the shared memory */
159561  ){}
159562  
159563  static int nullShmUnmap(
159564    sqlite3_file *fd,               /* The underlying database file */
159565    int deleteFlag                  /* Delete shared-memory if true */
159566  ){ return SQLITE_OK;}
159567  
159568  // static void nullUnmapfile(unixFile *pFd){}
159569  
159570  static int nullFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){return SQLITE_OK; }
159571  
159572  static int nullUnfetch(sqlite3_file *fd, i64 iOff, void *p){return SQLITE_OK; }
159573  
159574  
159575  static int nullOpen(
159576    sqlite3_vfs *pVfs,              /* VFS */
159577    const char *zName,              /* File to open, or 0 for a temp file */
159578    sqlite3_file *pFile,            /* Pointer to NullFile struct to populate */
159579    int flags,                      /* Input SQLITE_OPEN_XXX flags */
159580    int *pOutFlags                  /* Output SQLITE_OPEN_XXX flags (or NULL) */
159581  ){
159582    int openflags = 0;
159583    static const sqlite3_io_methods nullio = {
159584      3,                            /* iVersion */
159585      nullClose,                    /* xClose */
159586      nullRead,                     /* xRead */
159587      nullWrite,                    /* xWrite */
159588      nullTruncate,                 /* xTruncate */
159589      nullSync,                     /* xSync */
159590      nullFileSize,                 /* xFileSize */
159591      nullLock,                     /* xLock */
159592      nullUnlock,                   /* xUnlock */
159593      nullCheckReservedLock,        /* xCheckReservedLock */
159594      nullFileControl,              /* xFileControl */
159595      //nullSectorSize,             /* xSectorSize */
159596      //nullDeviceCharacteristics,  /* xDeviceCharacteristics */
159597  #if SQLITE_OS_WIN
159598      winSectorSize,                /* xSectorSize */
159599      winDeviceCharacteristics,     /* xDeviceCharacteristics */
159600  #else
159601      unixSectorSize,               /* xSectorSize */
159602      unixDeviceCharacteristics,    /* xDeviceCharacteristics */
159603  #endif
159604      nullShmMap,                   /* xShmMap */
159605      nullShmLock,                  /* xShmLock */
159606      nullShmBarrier,               /* xShmBarrier */
159607      nullShmUnmap,                 /* xShmUnmap */
159608      nullFetch,                    /* xFetch */
159609      nullUnfetch                   /* xUnfetch */
159610    };
159611    int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
159612    int isCreate     = (flags & SQLITE_OPEN_CREATE);
159613    int isReadonly   = (flags & SQLITE_OPEN_READONLY);
159614    int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
159615  
159616    NullFile *p = (NullFile*)pFile; /* Populate this structure */
159617  
159618    BRANCHTRACE("nullOpen VFS=%s file=%s", pVfs->zName, zName);
159619  
159620    memset(p, 0, sizeof(NullFile));
159621  
159622  #if SQLITE_OS_WIN
159623    openflags = flags;
159624  #else
159625    if( isReadonly )  openflags |= O_RDONLY;
159626    if( isReadWrite ) openflags |= O_RDWR;
159627    if( isCreate )    openflags |= O_CREAT;
159628    #ifdef O_NOFOLLOW
159629    if( isExclusive ) openflags |= (O_EXCL|O_NOFOLLOW);
159630    #else
159631    if( isExclusive ) openflags |= (O_EXCL);
159632    #endif
159633  
159634    #ifdef O_LARGEFILE
159635    openflags |= (O_LARGEFILE|O_BINARY);
159636    #else
159637    openflags |= (O_BINARY);
159638    #endif
159639  #endif
159640  
159641    if( pOutFlags ){
159642      *pOutFlags = openflags;
159643    }
159644    p->base.pMethods = &nullio;
159645    return SQLITE_OK;
159646  }
159647  
159648  /*
159649  ** Delete the file identified by argument zPath. If the dirSync parameter
159650  ** is non-zero, then ensure the file-system modification to delete the
159651  ** file has been synced to disk before returning.
159652  */
159653  static int nullDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
159654    BRANCHTRACE("nullDelete path=%s", zPath);
159655    return SQLITE_OK;
159656  }
159657  
159658  #ifndef F_OK
159659  # define F_OK 0
159660  #endif
159661  #ifndef R_OK
159662  # define R_OK 4
159663  #endif
159664  #ifndef W_OK
159665  # define W_OK 2
159666  #endif
159667  
159668  #ifdef UNUSED_FUNCTION
159669  
159670  /*
159671  ** Query the file-system to see if the named file exists, is readable or
159672  ** is both readable and writable.
159673  */
159674  static int nullAccess(
159675    sqlite3_vfs *pVfs,
159676    const char *zPath,
159677    int flags,
159678    int *pResOut
159679  ){
159680    BRANCHTRACE("nullAccess path=%s", zPath);
159681    *pResOut = 0;  // R_OK | W_OK;
159682    return SQLITE_OK;
159683  }
159684  
159685  #endif
159686  
159687  /*
159688  ** This function returns a pointer to the VFS implemented in this file.
159689  ** To make the VFS available to SQLite:
159690  **
159691  **   sqlite3_vfs_register(sqlite3_nullvfs(), 0);
159692  */
159693  sqlite3_vfs *sqlite3_nullvfs(void){
159694    static sqlite3_vfs nullvfs = {
159695      3,                    /* iVersion */
159696      sizeof(NullFile),     /* szOsFile */
159697      NULLVFS_MAXPATHNAME,  /* mxPathname */
159698      0,                    /* pNext */
159699      "null",               /* zName */
159700      0,                    /* pAppData */
159701      nullOpen,             /* xOpen */
159702      nullDelete,           /* xDelete */
159703    #if SQLITE_OS_WIN
159704      winAccess,            /* xAccess */
159705      winFullPathname,      /* xFullPathname */
159706      winDlOpen,            /* xDlOpen */
159707      winDlError,           /* xDlError */
159708      winDlSym,             /* xDlSym */
159709      winDlClose,           /* xDlClose */
159710      winRandomness,        /* xRandomness */
159711      winSleep,             /* xSleep */
159712      winCurrentTime,       /* xCurrentTime */
159713      winGetLastError,      /* xGetLastError */
159714      winCurrentTimeInt64,  /* xCurrentTimeInt64 */
159715      winSetSystemCall,     /* xSetSystemCall */
159716      winGetSystemCall,     /* xGetSystemCall */
159717      winNextSystemCall,    /* xNextSystemCall */
159718    #else
159719      unixAccess,           /* xAccess */
159720      unixFullPathname,     /* xFullPathname */
159721      unixDlOpen,           /* xDlOpen */
159722      unixDlError,          /* xDlError */
159723      unixDlSym,            /* xDlSym */
159724      unixDlClose,          /* xDlClose */
159725      unixRandomness,       /* xRandomness */
159726      unixSleep,            /* xSleep */
159727      unixCurrentTime,      /* xCurrentTime */
159728      unixGetLastError,     /* xGetLastError */
159729      unixCurrentTimeInt64, /* xCurrentTimeInt64 */
159730      unixSetSystemCall,    /* xSetSystemCall */
159731      unixGetSystemCall,    /* xGetSystemCall */
159732      unixNextSystemCall,   /* xNextSystemCall */
159733    #endif
159734    };
159735    return &nullvfs;
159736  }
159737  
159738  //#endif /* !defined(SQLITE_TEST) || SQLITE_OS_UNIX */
159739  /************** End of nullvfs.h *********************************************/
159740  /************** Continuing where we left off in main.c ***********************/
159741  
159742  /*
159743  ** Initialize SQLite.  
159744  **
159745  ** This routine must be called to initialize the memory allocation,
159746  ** VFS, and mutex subsystems prior to doing any serious work with
159747  ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
159748  ** this routine will be called automatically by key routines such as
159749  ** sqlite3_open().  
159750  **
159751  ** This routine is a no-op except on its very first call for the process,
159752  ** or for the first call after a call to sqlite3_shutdown.
159753  **
159754  ** The first thread to call this routine runs the initialization to
159755  ** completion.  If subsequent threads call this routine before the first
159756  ** thread has finished the initialization process, then the subsequent
159757  ** threads must block until the first thread finishes with the initialization.
159758  **
159759  ** The first thread might call this routine recursively.  Recursive
159760  ** calls to this routine should not block, of course.  Otherwise the
159761  ** initialization process would never complete.
159762  **
159763  ** Let X be the first thread to enter this routine.  Let Y be some other
159764  ** thread.  Then while the initial invocation of this routine by X is
159765  ** incomplete, it is required that:
159766  **
159767  **    *  Calls to this routine from Y must block until the outer-most
159768  **       call by X completes.
159769  **
159770  **    *  Recursive calls to this routine from thread X return immediately
159771  **       without blocking.
159772  */
159773  SQLITE_API int sqlite3_initialize(void){
159774    MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
159775    int rc;                                      /* Result code */
159776  #ifdef SQLITE_EXTRA_INIT
159777    int bRunExtraInit = 0;                       /* Extra initialization needed */
159778  #endif
159779  
159780  #ifdef SQLITE_OMIT_WSD
159781    rc = sqlite3_wsd_init(4096, 24);
159782    if( rc!=SQLITE_OK ){
159783      return rc;
159784    }
159785  #endif
159786  
159787    /* If the following assert() fails on some obscure processor/compiler
159788    ** combination, the work-around is to set the correct pointer
159789    ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
159790    assert( SQLITE_PTRSIZE==sizeof(char*) );
159791  
159792    /* If SQLite is already completely initialized, then this call
159793    ** to sqlite3_initialize() should be a no-op.  But the initialization
159794    ** must be complete.  So isInit must not be set until the very end
159795    ** of this routine.
159796    */
159797    if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
159798  
159799    /* Make sure the mutex subsystem is initialized.  If unable to 
159800    ** initialize the mutex subsystem, return early with the error.
159801    ** If the system is so sick that we are unable to allocate a mutex,
159802    ** there is not much SQLite is going to be able to do.
159803    **
159804    ** The mutex subsystem must take care of serializing its own
159805    ** initialization.
159806    */
159807    rc = sqlite3MutexInit();
159808    if( rc ) return rc;
159809  
159810    /* Initialize the malloc() system and the recursive pInitMutex mutex.
159811    ** This operation is protected by the STATIC_MASTER mutex.  Note that
159812    ** MutexAlloc() is called for a static mutex prior to initializing the
159813    ** malloc subsystem - this implies that the allocation of a static
159814    ** mutex must not require support from the malloc subsystem.
159815    */
159816    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
159817    sqlite3_mutex_enter(pMaster);
159818    sqlite3GlobalConfig.isMutexInit = 1;
159819    if( !sqlite3GlobalConfig.isMallocInit ){
159820      rc = sqlite3MallocInit();
159821    }
159822    if( rc==SQLITE_OK ){
159823      sqlite3GlobalConfig.isMallocInit = 1;
159824      if( !sqlite3GlobalConfig.pInitMutex ){
159825        sqlite3GlobalConfig.pInitMutex =
159826             sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
159827        if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
159828          rc = SQLITE_NOMEM_BKPT;
159829        }
159830      }
159831    }
159832    if( rc==SQLITE_OK ){
159833      sqlite3GlobalConfig.nRefInitMutex++;
159834    }
159835    sqlite3_mutex_leave(pMaster);
159836  
159837    /* If rc is not SQLITE_OK at this point, then either the malloc
159838    ** subsystem could not be initialized or the system failed to allocate
159839    ** the pInitMutex mutex. Return an error in either case.  */
159840    if( rc!=SQLITE_OK ){
159841      return rc;
159842    }
159843  
159844    /* Do the rest of the initialization under the recursive mutex so
159845    ** that we will be able to handle recursive calls into
159846    ** sqlite3_initialize().  The recursive calls normally come through
159847    ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
159848    ** recursive calls might also be possible.
159849    **
159850    ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
159851    ** to the xInit method, so the xInit method need not be threadsafe.
159852    **
159853    ** The following mutex is what serializes access to the appdef pcache xInit
159854    ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
159855    ** call to sqlite3PcacheInitialize().
159856    */
159857    sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
159858    if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
159859      sqlite3GlobalConfig.inProgress = 1;
159860  #ifdef SQLITE_ENABLE_SQLLOG
159861      {
159862        extern void sqlite3_init_sqllog(void);
159863        sqlite3_init_sqllog();
159864      }
159865  #endif
159866      memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
159867      sqlite3RegisterBuiltinFunctions();
159868      if( sqlite3GlobalConfig.isPCacheInit==0 ){
159869        rc = sqlite3PcacheInitialize();
159870      }
159871      if( rc==SQLITE_OK ){
159872        sqlite3GlobalConfig.isPCacheInit = 1;
159873        rc = sqlite3OsInit();
159874      }
159875  #ifdef SQLITE_ENABLE_DESERIALIZE
159876      if( rc==SQLITE_OK ){
159877        rc = sqlite3MemdbInit();
159878      }
159879  #endif
159880      if( rc==SQLITE_OK ){
159881        sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
159882            sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
159883        sqlite3GlobalConfig.isInit = 1;
159884  #ifdef SQLITE_EXTRA_INIT
159885        bRunExtraInit = 1;
159886  #endif
159887      }
159888      sqlite3GlobalConfig.inProgress = 0;
159889    }
159890    sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
159891  
159892    /* Go back under the static mutex and clean up the recursive
159893    ** mutex to prevent a resource leak.
159894    */
159895    sqlite3_mutex_enter(pMaster);
159896    sqlite3GlobalConfig.nRefInitMutex--;
159897    if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
159898      assert( sqlite3GlobalConfig.nRefInitMutex==0 );
159899      sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
159900      sqlite3GlobalConfig.pInitMutex = 0;
159901    }
159902    sqlite3_mutex_leave(pMaster);
159903  
159904    /* The following is just a sanity check to make sure SQLite has
159905    ** been compiled correctly.  It is important to run this code, but
159906    ** we don't want to run it too often and soak up CPU cycles for no
159907    ** reason.  So we run it once during initialization.
159908    */
159909  #ifndef NDEBUG
159910  #ifndef SQLITE_OMIT_FLOATING_POINT
159911    /* This section of code's only "output" is via assert() statements. */
159912    if( rc==SQLITE_OK ){
159913      u64 x = (((u64)1)<<63)-1;
159914      double y;
159915      assert(sizeof(x)==8);
159916      assert(sizeof(x)==sizeof(y));
159917      memcpy(&y, &x, 8);
159918      assert( sqlite3IsNaN(y) );
159919    }
159920  #endif
159921  #endif
159922  
159923    /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
159924    ** compile-time option.
159925    */
159926  #ifdef SQLITE_EXTRA_INIT
159927    if( bRunExtraInit ){
159928      int SQLITE_EXTRA_INIT(const char*);
159929      rc = SQLITE_EXTRA_INIT(0);
159930    }
159931  #endif
159932  
159933    return rc;
159934  }
159935  
159936  /*
159937  ** Undo the effects of sqlite3_initialize().  Must not be called while
159938  ** there are outstanding database connections or memory allocations or
159939  ** while any part of SQLite is otherwise in use in any thread.  This
159940  ** routine is not threadsafe.  But it is safe to invoke this routine
159941  ** on when SQLite is already shut down.  If SQLite is already shut down
159942  ** when this routine is invoked, then this routine is a harmless no-op.
159943  */
159944  SQLITE_API int sqlite3_shutdown(void){
159945  #ifdef SQLITE_OMIT_WSD
159946    int rc = sqlite3_wsd_init(4096, 24);
159947    if( rc!=SQLITE_OK ){
159948      return rc;
159949    }
159950  #endif
159951  
159952    if( sqlite3GlobalConfig.isInit ){
159953  #ifdef SQLITE_EXTRA_SHUTDOWN
159954      void SQLITE_EXTRA_SHUTDOWN(void);
159955      SQLITE_EXTRA_SHUTDOWN();
159956  #endif
159957      sqlite3_os_end();
159958      sqlite3_reset_auto_extension();
159959      sqlite3GlobalConfig.isInit = 0;
159960    }
159961    if( sqlite3GlobalConfig.isPCacheInit ){
159962      sqlite3PcacheShutdown();
159963      sqlite3GlobalConfig.isPCacheInit = 0;
159964    }
159965    if( sqlite3GlobalConfig.isMallocInit ){
159966      sqlite3MallocEnd();
159967      sqlite3GlobalConfig.isMallocInit = 0;
159968  
159969  #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
159970      /* The heap subsystem has now been shutdown and these values are supposed
159971      ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
159972      ** which would rely on that heap subsystem; therefore, make sure these
159973      ** values cannot refer to heap memory that was just invalidated when the
159974      ** heap subsystem was shutdown.  This is only done if the current call to
159975      ** this function resulted in the heap subsystem actually being shutdown.
159976      */
159977      sqlite3_data_directory = 0;
159978      sqlite3_temp_directory = 0;
159979  #endif
159980    }
159981    if( sqlite3GlobalConfig.isMutexInit ){
159982      sqlite3MutexEnd();
159983      sqlite3GlobalConfig.isMutexInit = 0;
159984    }
159985  
159986    return SQLITE_OK;
159987  }
159988  
159989  /*
159990  ** This API allows applications to modify the global configuration of
159991  ** the SQLite library at run-time.
159992  **
159993  ** This routine should only be called when there are no outstanding
159994  ** database connections or memory allocations.  This routine is not
159995  ** threadsafe.  Failure to heed these warnings can lead to unpredictable
159996  ** behavior.
159997  */
159998  SQLITE_API int sqlite3_config(int op, ...){
159999    va_list ap;
160000    int rc = SQLITE_OK;
160001  
160002    /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
160003    ** the SQLite library is in use. */
160004    if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
160005  
160006    va_start(ap, op);
160007    switch( op ){
160008  
160009      /* Mutex configuration options are only available in a threadsafe
160010      ** compile.
160011      */
160012  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
160013      case SQLITE_CONFIG_SINGLETHREAD: {
160014        /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
160015        ** Single-thread. */
160016        sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
160017        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
160018        break;
160019      }
160020  #endif
160021  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
160022      case SQLITE_CONFIG_MULTITHREAD: {
160023        /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
160024        ** Multi-thread. */
160025        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
160026        sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
160027        break;
160028      }
160029  #endif
160030  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
160031      case SQLITE_CONFIG_SERIALIZED: {
160032        /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
160033        ** Serialized. */
160034        sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
160035        sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
160036        break;
160037      }
160038  #endif
160039  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
160040      case SQLITE_CONFIG_MUTEX: {
160041        /* Specify an alternative mutex implementation */
160042        sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
160043        break;
160044      }
160045  #endif
160046  #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
160047      case SQLITE_CONFIG_GETMUTEX: {
160048        /* Retrieve the current mutex implementation */
160049        *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
160050        break;
160051      }
160052  #endif
160053  
160054      case SQLITE_CONFIG_MALLOC: {
160055        /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
160056        ** single argument which is a pointer to an instance of the
160057        ** sqlite3_mem_methods structure. The argument specifies alternative
160058        ** low-level memory allocation routines to be used in place of the memory
160059        ** allocation routines built into SQLite. */
160060        sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
160061        break;
160062      }
160063      case SQLITE_CONFIG_GETMALLOC: {
160064        /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
160065        ** single argument which is a pointer to an instance of the
160066        ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
160067        ** filled with the currently defined memory allocation routines. */
160068        if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
160069        *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
160070        break;
160071      }
160072      case SQLITE_CONFIG_MEMSTATUS: {
160073        /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
160074        ** single argument of type int, interpreted as a boolean, which enables
160075        ** or disables the collection of memory allocation statistics. */
160076        sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
160077        break;
160078      }
160079      case SQLITE_CONFIG_SMALL_MALLOC: {
160080        sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
160081        break;
160082      }
160083      case SQLITE_CONFIG_PAGECACHE: {
160084        /* EVIDENCE-OF: R-18761-36601 There are three arguments to
160085        ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
160086        ** the size of each page cache line (sz), and the number of cache lines
160087        ** (N). */
160088        sqlite3GlobalConfig.pPage = va_arg(ap, void*);
160089        sqlite3GlobalConfig.szPage = va_arg(ap, int);
160090        sqlite3GlobalConfig.nPage = va_arg(ap, int);
160091        break;
160092      }
160093      case SQLITE_CONFIG_PCACHE_HDRSZ: {
160094        /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
160095        ** a single parameter which is a pointer to an integer and writes into
160096        ** that integer the number of extra bytes per page required for each page
160097        ** in SQLITE_CONFIG_PAGECACHE. */
160098        *va_arg(ap, int*) = 
160099            sqlite3HeaderSizeBtree() +
160100            sqlite3HeaderSizePcache() +
160101            sqlite3HeaderSizePcache1();
160102        break;
160103      }
160104  
160105      case SQLITE_CONFIG_PCACHE: {
160106        /* no-op */
160107        break;
160108      }
160109      case SQLITE_CONFIG_GETPCACHE: {
160110        /* now an error */
160111        rc = SQLITE_ERROR;
160112        break;
160113      }
160114  
160115      case SQLITE_CONFIG_PCACHE2: {
160116        /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
160117        ** single argument which is a pointer to an sqlite3_pcache_methods2
160118        ** object. This object specifies the interface to a custom page cache
160119        ** implementation. */
160120        sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
160121        break;
160122      }
160123      case SQLITE_CONFIG_GETPCACHE2: {
160124        /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
160125        ** single argument which is a pointer to an sqlite3_pcache_methods2
160126        ** object. SQLite copies of the current page cache implementation into
160127        ** that object. */
160128        if( sqlite3GlobalConfig.pcache2.xInit==0 ){
160129          sqlite3PCacheSetDefault();
160130        }
160131        *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
160132        break;
160133      }
160134  
160135  /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
160136  ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
160137  ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
160138  #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
160139      case SQLITE_CONFIG_HEAP: {
160140        /* EVIDENCE-OF: R-19854-42126 There are three arguments to
160141        ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
160142        ** number of bytes in the memory buffer, and the minimum allocation size.
160143        */
160144        sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
160145        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
160146        sqlite3GlobalConfig.mnReq = va_arg(ap, int);
160147  
160148        if( sqlite3GlobalConfig.mnReq<1 ){
160149          sqlite3GlobalConfig.mnReq = 1;
160150        }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
160151          /* cap min request size at 2^12 */
160152          sqlite3GlobalConfig.mnReq = (1<<12);
160153        }
160154  
160155        if( sqlite3GlobalConfig.pHeap==0 ){
160156          /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
160157          ** is NULL, then SQLite reverts to using its default memory allocator
160158          ** (the system malloc() implementation), undoing any prior invocation of
160159          ** SQLITE_CONFIG_MALLOC.
160160          **
160161          ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
160162          ** revert to its default implementation when sqlite3_initialize() is run
160163          */
160164          memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
160165        }else{
160166          /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
160167          ** alternative memory allocator is engaged to handle all of SQLites
160168          ** memory allocation needs. */
160169  #ifdef SQLITE_ENABLE_MEMSYS3
160170          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
160171  #endif
160172  #ifdef SQLITE_ENABLE_MEMSYS5
160173          sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
160174  #endif
160175        }
160176        break;
160177      }
160178  #endif
160179  
160180      case SQLITE_CONFIG_LOOKASIDE: {
160181        sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
160182        sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
160183        break;
160184      }
160185      
160186      /* Record a pointer to the logger function and its first argument.
160187      ** The default is NULL.  Logging is disabled if the function pointer is
160188      ** NULL.
160189      */
160190      case SQLITE_CONFIG_LOG: {
160191        /* MSVC is picky about pulling func ptrs from va lists.
160192        ** http://support.microsoft.com/kb/47961
160193        ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
160194        */
160195        typedef void(*LOGFUNC_t)(void*,int,const char*);
160196        sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
160197        sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
160198        break;
160199      }
160200  
160201      /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
160202      ** can be changed at start-time using the
160203      ** sqlite3_config(SQLITE_CONFIG_URI,1) or
160204      ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
160205      */
160206      case SQLITE_CONFIG_URI: {
160207        /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
160208        ** argument of type int. If non-zero, then URI handling is globally
160209        ** enabled. If the parameter is zero, then URI handling is globally
160210        ** disabled. */
160211        sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
160212        break;
160213      }
160214  
160215      case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
160216        /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
160217        ** option takes a single integer argument which is interpreted as a
160218        ** boolean in order to enable or disable the use of covering indices for
160219        ** full table scans in the query optimizer. */
160220        sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
160221        break;
160222      }
160223  
160224  #ifdef SQLITE_ENABLE_SQLLOG
160225      case SQLITE_CONFIG_SQLLOG: {
160226        typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
160227        sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
160228        sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
160229        break;
160230      }
160231  #endif
160232  
160233      case SQLITE_CONFIG_MMAP_SIZE: {
160234        /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
160235        ** integer (sqlite3_int64) values that are the default mmap size limit
160236        ** (the default setting for PRAGMA mmap_size) and the maximum allowed
160237        ** mmap size limit. */
160238        sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
160239        sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
160240        /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
160241        ** negative, then that argument is changed to its compile-time default.
160242        **
160243        ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
160244        ** silently truncated if necessary so that it does not exceed the
160245        ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
160246        ** compile-time option.
160247        */
160248        if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
160249          mxMmap = SQLITE_MAX_MMAP_SIZE;
160250        }
160251        if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
160252        if( szMmap>mxMmap) szMmap = mxMmap;
160253        sqlite3GlobalConfig.mxMmap = mxMmap;
160254        sqlite3GlobalConfig.szMmap = szMmap;
160255        break;
160256      }
160257  
160258  #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
160259      case SQLITE_CONFIG_WIN32_HEAPSIZE: {
160260        /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
160261        ** unsigned integer value that specifies the maximum size of the created
160262        ** heap. */
160263        sqlite3GlobalConfig.nHeap = va_arg(ap, int);
160264        break;
160265      }
160266  #endif
160267  
160268      case SQLITE_CONFIG_PMASZ: {
160269        sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
160270        break;
160271      }
160272  
160273      case SQLITE_CONFIG_STMTJRNL_SPILL: {
160274        sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
160275        break;
160276      }
160277  
160278  #ifdef SQLITE_ENABLE_SORTER_REFERENCES
160279      case SQLITE_CONFIG_SORTERREF_SIZE: {
160280        int iVal = va_arg(ap, int);
160281        if( iVal<0 ){
160282          iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
160283        }
160284        sqlite3GlobalConfig.szSorterRef = (u32)iVal;
160285        break;
160286      }
160287  #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
160288  
160289  #ifdef SQLITE_ENABLE_DESERIALIZE
160290      case SQLITE_CONFIG_MEMDB_MAXSIZE: {
160291        sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
160292        break;
160293      }
160294  #endif /* SQLITE_ENABLE_DESERIALIZE */
160295  
160296      default: {
160297        rc = SQLITE_ERROR;
160298        break;
160299      }
160300    }
160301    va_end(ap);
160302    return rc;
160303  }
160304  
160305  /*
160306  ** Set up the lookaside buffers for a database connection.
160307  ** Return SQLITE_OK on success.  
160308  ** If lookaside is already active, return SQLITE_BUSY.
160309  **
160310  ** The sz parameter is the number of bytes in each lookaside slot.
160311  ** The cnt parameter is the number of slots.  If pStart is NULL the
160312  ** space for the lookaside memory is obtained from sqlite3_malloc().
160313  ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
160314  ** the lookaside memory.
160315  */
160316  static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
160317  #ifndef SQLITE_OMIT_LOOKASIDE
160318    void *pStart;
160319    
160320    if( sqlite3LookasideUsed(db,0)>0 ){
160321      return SQLITE_BUSY;
160322    }
160323    /* Free any existing lookaside buffer for this handle before
160324    ** allocating a new one so we don't have to have space for 
160325    ** both at the same time.
160326    */
160327    if( db->lookaside.bMalloced ){
160328      sqlite3_free(db->lookaside.pStart);
160329    }
160330    /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
160331    ** than a pointer to be useful.
160332    */
160333    sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
160334    if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
160335    if( cnt<0 ) cnt = 0;
160336    if( sz==0 || cnt==0 ){
160337      sz = 0;
160338      pStart = 0;
160339    }else if( pBuf==0 ){
160340      sqlite3BeginBenignMalloc();
160341      pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
160342      sqlite3EndBenignMalloc();
160343      if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
160344    }else{
160345      pStart = pBuf;
160346    }
160347    db->lookaside.pStart = pStart;
160348    db->lookaside.pInit = 0;
160349    db->lookaside.pFree = 0;
160350    db->lookaside.sz = (u16)sz;
160351    if( pStart ){
160352      int i;
160353      LookasideSlot *p;
160354      assert( sz > (int)sizeof(LookasideSlot*) );
160355      db->lookaside.nSlot = cnt;
160356      p = (LookasideSlot*)pStart;
160357      for(i=cnt-1; i>=0; i--){
160358        p->pNext = db->lookaside.pInit;
160359        db->lookaside.pInit = p;
160360        p = (LookasideSlot*)&((u8*)p)[sz];
160361      }
160362      db->lookaside.pEnd = p;
160363      db->lookaside.bDisable = 0;
160364      db->lookaside.bMalloced = pBuf==0 ?1:0;
160365    }else{
160366      db->lookaside.pStart = db;
160367      db->lookaside.pEnd = db;
160368      db->lookaside.bDisable = 1;
160369      db->lookaside.bMalloced = 0;
160370      db->lookaside.nSlot = 0;
160371    }
160372  #endif /* SQLITE_OMIT_LOOKASIDE */
160373    return SQLITE_OK;
160374  }
160375  
160376  /*
160377  ** Return the mutex associated with a database connection.
160378  */
160379  SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
160380  #ifdef SQLITE_ENABLE_API_ARMOR
160381    if( !sqlite3SafetyCheckOk(db) ){
160382      (void)SQLITE_MISUSE_BKPT;
160383      return 0;
160384    }
160385  #endif
160386    return db->mutex;
160387  }
160388  
160389  /*
160390  ** Free up as much memory as we can from the given database
160391  ** connection.
160392  */
160393  SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
160394    int i;
160395  
160396  #ifdef SQLITE_ENABLE_API_ARMOR
160397    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
160398  #endif
160399    sqlite3_mutex_enter(db->mutex);
160400    sqlite3BtreeEnterAll(db);
160401    for(i=0; i<db->nDb; i++){
160402      Btree *pBt = db->aDb[i].pBt;
160403      if( pBt ){
160404        Pager *pPager = sqlite3BtreePager(pBt);
160405        sqlite3PagerShrink(pPager);
160406      }
160407    }
160408    sqlite3BtreeLeaveAll(db);
160409    sqlite3_mutex_leave(db->mutex);
160410    return SQLITE_OK;
160411  }
160412  
160413  /*
160414  ** Flush any dirty pages in the pager-cache for any attached database
160415  ** to disk.
160416  */
160417  SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
160418    int i;
160419    int rc = SQLITE_OK;
160420    int bSeenBusy = 0;
160421  
160422  #ifdef SQLITE_ENABLE_API_ARMOR
160423    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
160424  #endif
160425    sqlite3_mutex_enter(db->mutex);
160426    sqlite3BtreeEnterAll(db);
160427    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
160428      Btree *pBt = db->aDb[i].pBt;
160429      if( pBt && sqlite3BtreeIsInTrans(pBt) ){
160430        Pager *pPager = sqlite3BtreePager(pBt);
160431        rc = sqlite3PagerFlush(pPager);
160432        if( rc==SQLITE_BUSY ){
160433          bSeenBusy = 1;
160434          rc = SQLITE_OK;
160435        }
160436      }
160437    }
160438    sqlite3BtreeLeaveAll(db);
160439    sqlite3_mutex_leave(db->mutex);
160440    return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
160441  }
160442  
160443  /*
160444  ** Configuration settings for an individual database connection
160445  */
160446  SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
160447    va_list ap;
160448    int rc;
160449    va_start(ap, op);
160450    switch( op ){
160451      case SQLITE_DBCONFIG_MAINDBNAME: {
160452        /* IMP: R-06824-28531 */
160453        /* IMP: R-36257-52125 */
160454        db->aDb[0].zDbSName = va_arg(ap,char*);
160455        rc = SQLITE_OK;
160456        break;
160457      }
160458      case SQLITE_DBCONFIG_LOOKASIDE: {
160459        void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
160460        int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
160461        int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
160462        rc = setupLookaside(db, pBuf, sz, cnt);
160463        break;
160464      }
160465      default: {
160466        static const struct {
160467          int op;      /* The opcode */
160468          u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
160469        } aFlagOp[] = {
160470          { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
160471          { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
160472          { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
160473          { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
160474          { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
160475          { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
160476          { SQLITE_DBCONFIG_TRIGGER_EQP,           SQLITE_TriggerEQP     },
160477          { SQLITE_DBCONFIG_RESET_DATABASE,        SQLITE_ResetDatabase  },
160478          { SQLITE_DBCONFIG_DEFENSIVE,             SQLITE_Defensive      },
160479        };
160480        unsigned int i;
160481        rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
160482        for(i=0; i<ArraySize(aFlagOp); i++){
160483          if( aFlagOp[i].op==op ){
160484            int onoff = va_arg(ap, int);
160485            int *pRes = va_arg(ap, int*);
160486            u64 oldFlags = db->flags;
160487            if( onoff>0 ){
160488              db->flags |= aFlagOp[i].mask;
160489            }else if( onoff==0 ){
160490              db->flags &= ~(u64)aFlagOp[i].mask;
160491            }
160492            if( oldFlags!=db->flags ){
160493              sqlite3ExpirePreparedStatements(db, 0);
160494            }
160495            if( pRes ){
160496              *pRes = (db->flags & aFlagOp[i].mask)!=0;
160497            }
160498            rc = SQLITE_OK;
160499            break;
160500          }
160501        }
160502        break;
160503      }
160504    }
160505    va_end(ap);
160506    return rc;
160507  }
160508  
160509  
160510  /*
160511  ** Return true if the buffer z[0..n-1] contains all spaces.
160512  */
160513  static int allSpaces(const char *z, int n){
160514    while( n>0 && z[n-1]==' ' ){ n--; }
160515    return n==0;
160516  }
160517  
160518  /*
160519  ** This is the default collating function named "BINARY" which is always
160520  ** available.
160521  **
160522  ** If the padFlag argument is not NULL then space padding at the end
160523  ** of strings is ignored.  This implements the RTRIM collation.
160524  */
160525  static int binCollFunc(
160526    void *padFlag,
160527    int nKey1, const void *pKey1,
160528    int nKey2, const void *pKey2
160529  ){
160530    int rc, n;
160531    n = nKey1<nKey2 ? nKey1 : nKey2;
160532    /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
160533    ** strings byte by byte using the memcmp() function from the standard C
160534    ** library. */
160535    assert( pKey1 && pKey2 );
160536    rc = memcmp(pKey1, pKey2, n);
160537    if( rc==0 ){
160538      if( padFlag
160539       && allSpaces(((char*)pKey1)+n, nKey1-n)
160540       && allSpaces(((char*)pKey2)+n, nKey2-n)
160541      ){
160542        /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
160543        ** spaces at the end of either string do not change the result. In other
160544        ** words, strings will compare equal to one another as long as they
160545        ** differ only in the number of spaces at the end.
160546        */
160547      }else{
160548        rc = nKey1 - nKey2;
160549      }
160550    }
160551    return rc;
160552  }
160553  
160554  /*
160555  ** Return true if CollSeq is the default built-in BINARY.
160556  */
160557  SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
160558    assert( p==0 || p->xCmp!=binCollFunc || p->pUser!=0
160559              || strcmp(p->zName,"BINARY")==0 );
160560    return p==0 || (p->xCmp==binCollFunc && p->pUser==0);
160561  }
160562  
160563  /*
160564  ** Another built-in collating sequence: NOCASE. 
160565  **
160566  ** This collating sequence is intended to be used for "case independent
160567  ** comparison". SQLite's knowledge of upper and lower case equivalents
160568  ** extends only to the 26 characters used in the English language.
160569  **
160570  ** At the moment there is only a UTF-8 implementation.
160571  */
160572  static int nocaseCollatingFunc(
160573    void *NotUsed,
160574    int nKey1, const void *pKey1,
160575    int nKey2, const void *pKey2
160576  ){
160577    int r = sqlite3StrNICmp(
160578        (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
160579    UNUSED_PARAMETER(NotUsed);
160580    if( 0==r ){
160581      r = nKey1-nKey2;
160582    }
160583    return r;
160584  }
160585  
160586  /*
160587  ** Return the ROWID of the most recent insert
160588  */
160589  SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
160590  #ifdef SQLITE_ENABLE_API_ARMOR
160591    if( !sqlite3SafetyCheckOk(db) ){
160592      (void)SQLITE_MISUSE_BKPT;
160593      return 0;
160594    }
160595  #endif
160596    return db->lastRowid;
160597  }
160598  
160599  /*
160600  ** Set the value returned by the sqlite3_last_insert_rowid() API function.
160601  */
160602  SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
160603  #ifdef SQLITE_ENABLE_API_ARMOR
160604    if( !sqlite3SafetyCheckOk(db) ){
160605      (void)SQLITE_MISUSE_BKPT;
160606      return;
160607    }
160608  #endif
160609    sqlite3_mutex_enter(db->mutex);
160610    db->lastRowid = iRowid;
160611    sqlite3_mutex_leave(db->mutex);
160612  }
160613  
160614  /*
160615  ** Return the number of changes in the most recent call to sqlite3_exec().
160616  */
160617  SQLITE_API int sqlite3_changes(sqlite3 *db){
160618  #ifdef SQLITE_ENABLE_API_ARMOR
160619    if( !sqlite3SafetyCheckOk(db) ){
160620      (void)SQLITE_MISUSE_BKPT;
160621      return 0;
160622    }
160623  #endif
160624    return db->nChange;
160625  }
160626  
160627  /*
160628  ** Return the number of changes since the database handle was opened.
160629  */
160630  SQLITE_API int sqlite3_total_changes(sqlite3 *db){
160631  #ifdef SQLITE_ENABLE_API_ARMOR
160632    if( !sqlite3SafetyCheckOk(db) ){
160633      (void)SQLITE_MISUSE_BKPT;
160634      return 0;
160635    }
160636  #endif
160637    return db->nTotalChange;
160638  }
160639  
160640  /*
160641  ** Close all open savepoints. This function only manipulates fields of the
160642  ** database handle object, it does not close any savepoints that may be open
160643  ** at the b-tree/pager level.
160644  */
160645  SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
160646    while( db->pSavepoint ){
160647      Savepoint *pTmp = db->pSavepoint;
160648      db->pSavepoint = pTmp->pNext;
160649      sqlite3DbFree(db, pTmp);
160650    }
160651    db->nSavepoint = 0;
160652    db->nStatement = 0;
160653    db->isTransactionSavepoint = 0;
160654  }
160655  
160656  /*
160657  ** Invoke the destructor function associated with FuncDef p, if any. Except,
160658  ** if this is not the last copy of the function, do not invoke it. Multiple
160659  ** copies of a single function are created when create_function() is called
160660  ** with SQLITE_ANY as the encoding.
160661  */
160662  static void functionDestroy(sqlite3 *db, FuncDef *p){
160663    FuncDestructor *pDestructor = p->u.pDestructor;
160664    if( pDestructor ){
160665      pDestructor->nRef--;
160666      if( pDestructor->nRef==0 ){
160667        pDestructor->xDestroy(pDestructor->pUserData);
160668        sqlite3DbFree(db, pDestructor);
160669      }
160670    }
160671  }
160672  
160673  /*
160674  ** Disconnect all sqlite3_vtab objects that belong to database connection
160675  ** db. This is called when db is being closed.
160676  */
160677  static void disconnectAllVtab(sqlite3 *db){
160678  #ifndef SQLITE_OMIT_VIRTUALTABLE
160679    int i;
160680    HashElem *p;
160681    sqlite3BtreeEnterAll(db);
160682    for(i=0; i<db->nDb; i++){
160683      Schema *pSchema = db->aDb[i].pSchema;
160684      if( pSchema ){
160685        for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
160686          Table *pTab = (Table *)sqliteHashData(p);
160687          if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
160688        }
160689      }
160690    }
160691    for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
160692      Module *pMod = (Module *)sqliteHashData(p);
160693      if( pMod->pEpoTab ){
160694        sqlite3VtabDisconnect(db, pMod->pEpoTab);
160695      }
160696    }
160697    sqlite3VtabUnlockList(db);
160698    sqlite3BtreeLeaveAll(db);
160699  #else
160700    UNUSED_PARAMETER(db);
160701  #endif
160702  }
160703  
160704  /*
160705  ** Return TRUE if database connection db has unfinalized prepared
160706  ** statements or unfinished sqlite3_backup objects.  
160707  */
160708  static int connectionIsBusy(sqlite3 *db){
160709    int j;
160710    assert( sqlite3_mutex_held(db->mutex) );
160711    if( db->pVdbe ) return 1;
160712    for(j=0; j<db->nDb; j++){
160713      Btree *pBt = db->aDb[j].pBt;
160714      if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
160715    }
160716    return 0;
160717  }
160718  
160719  /*
160720  ** Close an existing SQLite database
160721  */
160722  static int sqlite3Close(sqlite3 *db, int forceZombie){
160723    if( !db ){
160724      /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
160725      ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
160726      return SQLITE_OK;
160727    }
160728    if( !sqlite3SafetyCheckSickOrOk(db) ){
160729      return SQLITE_MISUSE_BKPT;
160730    }
160731    sqlite3_mutex_enter(db->mutex);
160732    if( db->mTrace & SQLITE_TRACE_CLOSE ){
160733      db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
160734    }
160735  
160736    /* Force xDisconnect calls on all virtual tables */
160737    disconnectAllVtab(db);
160738  
160739    /* If a transaction is open, the disconnectAllVtab() call above
160740    ** will not have called the xDisconnect() method on any virtual
160741    ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
160742    ** call will do so. We need to do this before the check for active
160743    ** SQL statements below, as the v-table implementation may be storing
160744    ** some prepared statements internally.
160745    */
160746    sqlite3VtabRollback(db);
160747  
160748    /* Legacy behavior (sqlite3_close() behavior) is to return
160749    ** SQLITE_BUSY if the connection can not be closed immediately.
160750    */
160751    if( !forceZombie && connectionIsBusy(db) ){
160752      sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
160753         "statements or unfinished backups");
160754      sqlite3_mutex_leave(db->mutex);
160755      return SQLITE_BUSY;
160756    }
160757  
160758  #ifdef SQLITE_ENABLE_SQLLOG
160759    if( sqlite3GlobalConfig.xSqllog ){
160760      /* Closing the handle. Fourth parameter is passed the value 2. */
160761      sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
160762    }
160763  #endif
160764  
160765    /* Convert the connection into a zombie and then close it.
160766    */
160767    db->magic = SQLITE_MAGIC_ZOMBIE;
160768    sqlite3LeaveMutexAndCloseZombie(db);
160769    return SQLITE_OK;
160770  }
160771  
160772  /*
160773  ** Two variations on the public interface for closing a database
160774  ** connection. The sqlite3_close() version returns SQLITE_BUSY and
160775  ** leaves the connection option if there are unfinalized prepared
160776  ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
160777  ** version forces the connection to become a zombie if there are
160778  ** unclosed resources, and arranges for deallocation when the last
160779  ** prepare statement or sqlite3_backup closes.
160780  */
160781  SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
160782  SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
160783  
160784  
160785  /*
160786  ** Close the mutex on database connection db.
160787  **
160788  ** Furthermore, if database connection db is a zombie (meaning that there
160789  ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
160790  ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
160791  ** finished, then free all resources.
160792  */
160793  SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
160794    HashElem *i;                    /* Hash table iterator */
160795    int j;
160796  
160797    /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
160798    ** or if the connection has not yet been closed by sqlite3_close_v2(),
160799    ** then just leave the mutex and return.
160800    */
160801    if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
160802      sqlite3_mutex_leave(db->mutex);
160803      return;
160804    }
160805  
160806    /* If we reach this point, it means that the database connection has
160807    ** closed all sqlite3_stmt and sqlite3_backup objects and has been
160808    ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
160809    ** go ahead and free all resources.
160810    */
160811  
160812    /* If a transaction is open, roll it back. This also ensures that if
160813    ** any database schemas have been modified by an uncommitted transaction
160814    ** they are reset. And that the required b-tree mutex is held to make
160815    ** the pager rollback and schema reset an atomic operation. */
160816    sqlite3RollbackAll(db, SQLITE_OK);
160817  
160818    /* Free any outstanding Savepoint structures. */
160819    sqlite3CloseSavepoints(db);
160820  
160821    /* Close all database connections */
160822    for(j=0; j<db->nDb; j++){
160823      struct Db *pDb = &db->aDb[j];
160824      if( pDb->pBt ){
160825        sqlite3BtreeClose(pDb->pBt);
160826        pDb->pBt = 0;
160827        if( j!=1 ){
160828          pDb->pSchema = 0;
160829        }
160830      }
160831    }
160832    /* Clear the TEMP schema separately and last */
160833    if( db->aDb[1].pSchema ){
160834      sqlite3SchemaClear(db->aDb[1].pSchema);
160835    }
160836    sqlite3VtabUnlockList(db);
160837  
160838    /* Free up the array of auxiliary databases */
160839    sqlite3CollapseDatabaseArray(db);
160840    assert( db->nDb<=2 );
160841    assert( db->aDb==db->aDbStatic );
160842  
160843    /* Tell the code in notify.c that the connection no longer holds any
160844    ** locks and does not require any further unlock-notify callbacks.
160845    */
160846    sqlite3ConnectionClosed(db);
160847  
160848    for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
160849      FuncDef *pNext, *p;
160850      p = sqliteHashData(i);
160851      do{
160852        functionDestroy(db, p);
160853        pNext = p->pNext;
160854        sqlite3DbFree(db, p);
160855        p = pNext;
160856      }while( p );
160857    }
160858    sqlite3HashClear(&db->aFunc);
160859    for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
160860      CollSeq *pColl = (CollSeq *)sqliteHashData(i);
160861      /* Invoke any destructors registered for collation sequence user data. */
160862      for(j=0; j<3; j++){
160863        if( pColl[j].xDel ){
160864          pColl[j].xDel(pColl[j].pUser);
160865        }
160866      }
160867      sqlite3DbFree(db, pColl);
160868    }
160869    sqlite3HashClear(&db->aCollSeq);
160870  #ifndef SQLITE_OMIT_VIRTUALTABLE
160871    for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
160872      Module *pMod = (Module *)sqliteHashData(i);
160873      if( pMod->xDestroy ){
160874        pMod->xDestroy(pMod->pAux);
160875      }
160876      sqlite3VtabEponymousTableClear(db, pMod);
160877      sqlite3DbFree(db, pMod);
160878    }
160879    sqlite3HashClear(&db->aModule);
160880  #endif
160881  
160882    sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
160883    sqlite3ValueFree(db->pErr);
160884    sqlite3CloseExtensions(db);
160885  #if SQLITE_USER_AUTHENTICATION
160886    sqlite3_free(db->auth.zAuthUser);
160887    sqlite3_free(db->auth.zAuthPW);
160888  #endif
160889  
160890    db->magic = SQLITE_MAGIC_ERROR;
160891  
160892    /* The temp-database schema is allocated differently from the other schema
160893    ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
160894    ** So it needs to be freed here. Todo: Why not roll the temp schema into
160895    ** the same sqliteMalloc() as the one that allocates the database 
160896    ** structure?
160897    */
160898    sqlite3DbFree(db, db->aDb[1].pSchema);
160899    sqlite3_mutex_leave(db->mutex);
160900    db->magic = SQLITE_MAGIC_CLOSED;
160901    sqlite3_mutex_free(db->mutex);
160902    assert( sqlite3LookasideUsed(db,0)==0 );
160903    if( db->lookaside.bMalloced ){
160904      sqlite3_free(db->lookaside.pStart);
160905    }
160906    sqlite3_free(db);
160907  }
160908  
160909  /*
160910  ** Rollback all database files.  If tripCode is not SQLITE_OK, then
160911  ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
160912  ** breaker") and made to return tripCode if there are any further
160913  ** attempts to use that cursor.  Read cursors remain open and valid
160914  ** but are "saved" in case the table pages are moved around.
160915  */
160916  SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
160917    int i;
160918    int inTrans = 0;
160919    int schemaChange;
160920    assert( sqlite3_mutex_held(db->mutex) );
160921    sqlite3BeginBenignMalloc();
160922  
160923    BRANCHTRACE("sqlite3RollbackAll");
160924  
160925    /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
160926    ** This is important in case the transaction being rolled back has
160927    ** modified the database schema. If the b-tree mutexes are not taken
160928    ** here, then another shared-cache connection might sneak in between
160929    ** the database rollback and schema reset, which can cause false
160930    ** corruption reports in some cases.  */
160931    sqlite3BtreeEnterAll(db);
160932    schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
160933  
160934    for(i=0; i<db->nDb; i++){
160935      Btree *p = db->aDb[i].pBt;
160936      if( p ){
160937        if( sqlite3BtreeIsInTrans(p) ){
160938          inTrans = 1;
160939        }
160940        sqlite3BtreeRollback(p, tripCode, !schemaChange);
160941      }
160942    }
160943    sqlite3VtabRollback(db);
160944    sqlite3EndBenignMalloc();
160945  
160946    if( schemaChange ){
160947      sqlite3ExpirePreparedStatements(db, 0);
160948      sqlite3ResetAllSchemasOfConnection(db);
160949    }
160950    sqlite3BtreeLeaveAll(db);
160951  
160952    /* Any deferred constraint violations have now been resolved. */
160953    db->nDeferredCons = 0;
160954    db->nDeferredImmCons = 0;
160955    db->flags &= ~(u64)SQLITE_DeferFKs;
160956  
160957    /* If one has been configured, invoke the rollback-hook callback */
160958    if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
160959      db->xRollbackCallback(db->pRollbackArg);
160960    }
160961  }
160962  
160963  /*
160964  ** Return a static string containing the name corresponding to the error code
160965  ** specified in the argument.
160966  */
160967  #if defined(SQLITE_NEED_ERR_NAME)
160968  SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
160969    const char *zName = 0;
160970    int i, origRc = rc;
160971    for(i=0; i<2 && zName==0; i++, rc &= 0xff){
160972      switch( rc ){
160973        case SQLITE_OK:                 zName = "SQLITE_OK";                break;
160974        case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
160975        case SQLITE_ERROR_SNAPSHOT:     zName = "SQLITE_ERROR_SNAPSHOT";    break;
160976        case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
160977        case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
160978        case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
160979        case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
160980        case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
160981        case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
160982        case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
160983        case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
160984        case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
160985        case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
160986        case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
160987        case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
160988        case SQLITE_READONLY_CANTINIT:  zName = "SQLITE_READONLY_CANTINIT"; break;
160989        case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
160990        case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
160991        case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
160992        case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
160993        case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
160994        case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
160995        case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
160996        case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
160997        case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
160998        case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
160999        case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
161000        case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
161001        case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
161002        case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
161003        case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
161004        case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
161005        case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
161006        case SQLITE_IOERR_CHECKRESERVEDLOCK:
161007                                  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
161008        case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
161009        case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
161010        case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
161011        case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
161012        case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
161013        case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
161014        case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
161015        case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
161016        case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
161017        case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
161018        case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
161019        case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
161020        case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
161021        case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
161022        case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
161023        case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
161024        case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
161025        case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
161026        case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
161027        case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
161028        case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
161029        case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
161030        case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
161031        case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
161032        case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
161033        case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
161034        case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
161035        case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
161036        case SQLITE_CONSTRAINT_FOREIGNKEY:
161037                                  zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
161038        case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
161039        case SQLITE_CONSTRAINT_PRIMARYKEY:
161040                                  zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
161041        case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
161042        case SQLITE_CONSTRAINT_COMMITHOOK:
161043                                  zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
161044        case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
161045        case SQLITE_CONSTRAINT_FUNCTION:
161046                                  zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
161047        case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
161048        case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
161049        case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
161050        case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
161051        case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
161052        case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
161053        case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
161054        case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
161055        case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
161056        case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
161057        case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
161058        case SQLITE_NOTICE_RECOVER_ROLLBACK:
161059                                  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
161060        case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
161061        case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
161062        case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
161063      }
161064    }
161065    if( zName==0 ){
161066      static char zBuf[50];
161067      sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
161068      zName = zBuf;
161069    }
161070    return zName;
161071  }
161072  #endif
161073  
161074  /*
161075  ** Return a static string that describes the kind of error specified in the
161076  ** argument.
161077  */
161078  SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
161079    static const char* const aMsg[] = {
161080      /* SQLITE_OK          */ "not an error",
161081      /* SQLITE_ERROR       */ "SQL logic error",
161082      /* SQLITE_INTERNAL    */ 0,
161083      /* SQLITE_PERM        */ "access permission denied",
161084      /* SQLITE_ABORT       */ "query aborted",
161085      /* SQLITE_BUSY        */ "database is locked",
161086      /* SQLITE_LOCKED      */ "database table is locked",
161087      /* SQLITE_NOMEM       */ "out of memory",
161088      /* SQLITE_READONLY    */ "attempt to write a readonly database",
161089      /* SQLITE_INTERRUPT   */ "interrupted",
161090      /* SQLITE_IOERR       */ "disk I/O error",
161091      /* SQLITE_CORRUPT     */ "database disk image is malformed",
161092      /* SQLITE_NOTFOUND    */ "unknown operation",
161093      /* SQLITE_FULL        */ "database or disk is full",
161094      /* SQLITE_CANTOPEN    */ "unable to open database file",
161095      /* SQLITE_PROTOCOL    */ "locking protocol",
161096      /* SQLITE_EMPTY       */ 0,
161097      /* SQLITE_SCHEMA      */ "database schema has changed",
161098      /* SQLITE_TOOBIG      */ "string or blob too big",
161099      /* SQLITE_CONSTRAINT  */ "constraint failed",
161100      /* SQLITE_MISMATCH    */ "datatype mismatch",
161101      /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
161102  #ifdef SQLITE_DISABLE_LFS
161103      /* SQLITE_NOLFS       */ "large file support is disabled",
161104  #else
161105      /* SQLITE_NOLFS       */ 0,
161106  #endif
161107      /* SQLITE_AUTH        */ "authorization denied",
161108      /* SQLITE_FORMAT      */ 0,
161109      /* SQLITE_RANGE       */ "column index out of range",
161110      /* SQLITE_NOTADB      */ "file is not a database",
161111      /* SQLITE_NOTICE      */ "notification message",
161112      /* SQLITE_WARNING     */ "warning message",
161113    };
161114    const char *zErr = "unknown error";
161115    switch( rc ){
161116      case SQLITE_ABORT_ROLLBACK: {
161117        zErr = "abort due to ROLLBACK";
161118        break;
161119      }
161120      case SQLITE_ROW: {
161121        zErr = "another row available";
161122        break;
161123      }
161124      case SQLITE_DONE: {
161125        zErr = "no more rows available";
161126        break;
161127      }
161128      default: {
161129        rc &= 0xff;
161130        if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
161131          zErr = aMsg[rc];
161132        }
161133        break;
161134      }
161135    }
161136    return zErr;
161137  }
161138  
161139  /*
161140  ** This routine implements a busy callback that sleeps and tries
161141  ** again until a timeout value is reached.  The timeout value is
161142  ** an integer number of milliseconds passed in as the first
161143  ** argument.
161144  **
161145  ** Return non-zero to retry the lock.  Return zero to stop trying
161146  ** and cause SQLite to return SQLITE_BUSY.
161147  */
161148  static int sqliteDefaultBusyCallback(
161149    void *ptr,               /* Database connection */
161150    int count,               /* Number of times table has been busy */
161151    sqlite3_file *pFile      /* The file on which the lock occurred */
161152  ){
161153  #if SQLITE_OS_WIN || HAVE_USLEEP
161154    /* This case is for systems that have support for sleeping for fractions of
161155    ** a second.  Examples:  All windows systems, unix systems with usleep() */
161156    static const u8 delays[] =
161157       { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
161158    static const u8 totals[] =
161159       { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
161160  # define NDELAY ArraySize(delays)
161161    sqlite3 *db = (sqlite3 *)ptr;
161162    int tmout = db->busyTimeout;
161163    int delay, prior;
161164  
161165  #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
161166    if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
161167      if( count ){
161168        tmout = 0;
161169        sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
161170        return 0;
161171      }else{
161172        return 1;
161173      }
161174    }
161175  #else
161176    UNUSED_PARAMETER(pFile);
161177  #endif
161178    assert( count>=0 );
161179    if( count < NDELAY ){
161180      delay = delays[count];
161181      prior = totals[count];
161182    }else{
161183      delay = delays[NDELAY-1];
161184      prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
161185    }
161186    if( prior + delay > tmout ){
161187      delay = tmout - prior;
161188      if( delay<=0 ) return 0;
161189    }
161190    sqlite3OsSleep(db->pVfs, delay*1000);
161191    return 1;
161192  #else
161193    /* This case for unix systems that lack usleep() support.  Sleeping
161194    ** must be done in increments of whole seconds */
161195    sqlite3 *db = (sqlite3 *)ptr;
161196    int tmout = ((sqlite3 *)ptr)->busyTimeout;
161197    UNUSED_PARAMETER(pFile);
161198    if( (count+1)*1000 > tmout ){
161199      return 0;
161200    }
161201    sqlite3OsSleep(db->pVfs, 1000000);
161202    return 1;
161203  #endif
161204  }
161205  
161206  /*
161207  ** Invoke the given busy handler.
161208  **
161209  ** This routine is called when an operation failed to acquire a
161210  ** lock on VFS file pFile.
161211  **
161212  ** If this routine returns non-zero, the lock is retried.  If it
161213  ** returns 0, the operation aborts with an SQLITE_BUSY error.
161214  */
161215  SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
161216    int rc;
161217    if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
161218    if( p->bExtraFileArg ){
161219      /* Add an extra parameter with the pFile pointer to the end of the
161220      ** callback argument list */
161221      int (*xTra)(void*,int,sqlite3_file*);
161222      xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
161223      rc = xTra(p->pBusyArg, p->nBusy, pFile);
161224    }else{
161225      /* Legacy style busy handler callback */
161226      rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
161227    }
161228    if( rc==0 ){
161229      p->nBusy = -1;
161230    }else{
161231      p->nBusy++;
161232    }
161233    return rc; 
161234  }
161235  
161236  /*
161237  ** This routine sets the busy callback for an Sqlite database to the
161238  ** given callback function with the given argument.
161239  */
161240  SQLITE_API int sqlite3_busy_handler(
161241    sqlite3 *db,
161242    int (*xBusy)(void*,int),
161243    void *pArg
161244  ){
161245  #ifdef SQLITE_ENABLE_API_ARMOR
161246    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161247  #endif
161248    sqlite3_mutex_enter(db->mutex);
161249    db->busyHandler.xBusyHandler = xBusy;
161250    db->busyHandler.pBusyArg = pArg;
161251    db->busyHandler.nBusy = 0;
161252    db->busyHandler.bExtraFileArg = 0;
161253    db->busyTimeout = 0;
161254    sqlite3_mutex_leave(db->mutex);
161255    return SQLITE_OK;
161256  }
161257  
161258  #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
161259  /*
161260  ** This routine sets the progress callback for an Sqlite database to the
161261  ** given callback function with the given argument. The progress callback will
161262  ** be invoked every nOps opcodes.
161263  */
161264  SQLITE_API void sqlite3_progress_handler(
161265    sqlite3 *db, 
161266    int nOps,
161267    int (*xProgress)(void*), 
161268    void *pArg
161269  ){
161270  #ifdef SQLITE_ENABLE_API_ARMOR
161271    if( !sqlite3SafetyCheckOk(db) ){
161272      (void)SQLITE_MISUSE_BKPT;
161273      return;
161274    }
161275  #endif
161276    sqlite3_mutex_enter(db->mutex);
161277    if( nOps>0 ){
161278      db->xProgress = xProgress;
161279      db->nProgressOps = (unsigned)nOps;
161280      db->pProgressArg = pArg;
161281    }else{
161282      db->xProgress = 0;
161283      db->nProgressOps = 0;
161284      db->pProgressArg = 0;
161285    }
161286    sqlite3_mutex_leave(db->mutex);
161287  }
161288  #endif
161289  
161290  
161291  /*
161292  ** This routine installs a default busy handler that waits for the
161293  ** specified number of milliseconds before returning 0.
161294  */
161295  SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
161296  #ifdef SQLITE_ENABLE_API_ARMOR
161297    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161298  #endif
161299    if( ms>0 ){
161300      sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
161301                               (void*)db);
161302      db->busyTimeout = ms;
161303      db->busyHandler.bExtraFileArg = 1;
161304    }else{
161305      sqlite3_busy_handler(db, 0, 0);
161306    }
161307    return SQLITE_OK;
161308  }
161309  
161310  /*
161311  ** Cause any pending operation to stop at its earliest opportunity.
161312  */
161313  SQLITE_API void sqlite3_interrupt(sqlite3 *db){
161314  #ifdef SQLITE_ENABLE_API_ARMOR
161315    if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
161316      (void)SQLITE_MISUSE_BKPT;
161317      return;
161318    }
161319  #endif
161320    db->u1.isInterrupted = 1;
161321  }
161322  
161323  
161324  /*
161325  ** This function is exactly the same as sqlite3_create_function(), except
161326  ** that it is designed to be called by internal code. The difference is
161327  ** that if a malloc() fails in sqlite3_create_function(), an error code
161328  ** is returned and the mallocFailed flag cleared. 
161329  */
161330  SQLITE_PRIVATE int sqlite3CreateFunc(
161331    sqlite3 *db,
161332    const char *zFunctionName,
161333    int nArg,
161334    int enc,
161335    void *pUserData,
161336    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
161337    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
161338    void (*xFinal)(sqlite3_context*),
161339    void (*xValue)(sqlite3_context*),
161340    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
161341    FuncDestructor *pDestructor
161342  ){
161343    FuncDef *p;
161344    int nName;
161345    int extraFlags;
161346  
161347    assert( sqlite3_mutex_held(db->mutex) );
161348    assert( xValue==0 || xSFunc==0 );
161349    if( zFunctionName==0                /* Must have a valid name */
161350     || (xSFunc!=0 && xFinal!=0)        /* Not both xSFunc and xFinal */
161351     || ((xFinal==0)!=(xStep==0))       /* Both or neither of xFinal and xStep */
161352     || ((xValue==0)!=(xInverse==0))    /* Both or neither of xValue, xInverse */
161353     || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
161354     || (255<(nName = sqlite3Strlen30( zFunctionName)))
161355    ){
161356      return SQLITE_MISUSE_BKPT;
161357    }
161358  
161359    assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
161360    extraFlags = enc &  SQLITE_DETERMINISTIC;
161361    enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
161362    
161363  #ifndef SQLITE_OMIT_UTF16
161364    /* If SQLITE_UTF16 is specified as the encoding type, transform this
161365    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
161366    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
161367    **
161368    ** If SQLITE_ANY is specified, add three versions of the function
161369    ** to the hash table.
161370    */
161371    if( enc==SQLITE_UTF16 ){
161372      enc = SQLITE_UTF16NATIVE;
161373    }else if( enc==SQLITE_ANY ){
161374      int rc;
161375      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
161376           pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
161377      if( rc==SQLITE_OK ){
161378        rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
161379            pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
161380      }
161381      if( rc!=SQLITE_OK ){
161382        return rc;
161383      }
161384      enc = SQLITE_UTF16BE;
161385    }
161386  #else
161387    enc = SQLITE_UTF8;
161388  #endif
161389    
161390    /* Check if an existing function is being overridden or deleted. If so,
161391    ** and there are active VMs, then return SQLITE_BUSY. If a function
161392    ** is being overridden/deleted but there are no active VMs, allow the
161393    ** operation to continue but invalidate all precompiled statements.
161394    */
161395    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
161396    if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
161397      if( db->nVdbeActive ){
161398        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
161399          "unable to delete/modify user-function due to active statements");
161400        assert( !db->mallocFailed );
161401        return SQLITE_BUSY;
161402      }else{
161403        sqlite3ExpirePreparedStatements(db, 0);
161404      }
161405    }
161406  
161407    p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
161408    assert(p || db->mallocFailed);
161409    if( !p ){
161410      return SQLITE_NOMEM_BKPT;
161411    }
161412  
161413    /* If an older version of the function with a configured destructor is
161414    ** being replaced invoke the destructor function here. */
161415    functionDestroy(db, p);
161416  
161417    if( pDestructor ){
161418      pDestructor->nRef++;
161419    }
161420    p->u.pDestructor = pDestructor;
161421    p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
161422    testcase( p->funcFlags & SQLITE_DETERMINISTIC );
161423    p->xSFunc = xSFunc ? xSFunc : xStep;
161424    p->xFinalize = xFinal;
161425    p->xValue = xValue;
161426    p->xInverse = xInverse;
161427    p->pUserData = pUserData;
161428    p->nArg = (u16)nArg;
161429    return SQLITE_OK;
161430  }
161431  
161432  /*
161433  ** Worker function used by utf-8 APIs that create new functions:
161434  **
161435  **    sqlite3_create_function()
161436  **    sqlite3_create_function_v2()
161437  **    sqlite3_create_window_function()
161438  */
161439  static int createFunctionApi(
161440    sqlite3 *db,
161441    const char *zFunc,
161442    int nArg,
161443    int enc,
161444    void *p,
161445    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
161446    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
161447    void (*xFinal)(sqlite3_context*),
161448    void (*xValue)(sqlite3_context*),
161449    void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
161450    void(*xDestroy)(void*)
161451  ){
161452    int rc = SQLITE_ERROR;
161453    FuncDestructor *pArg = 0;
161454  
161455  #ifdef SQLITE_ENABLE_API_ARMOR
161456    if( !sqlite3SafetyCheckOk(db) ){
161457      return SQLITE_MISUSE_BKPT;
161458    }
161459  #endif
161460    sqlite3_mutex_enter(db->mutex);
161461    if( xDestroy ){
161462      pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
161463      if( !pArg ){
161464        sqlite3OomFault(db);
161465        xDestroy(p);
161466        goto out;
161467      }
161468      pArg->nRef = 0;
161469      pArg->xDestroy = xDestroy;
161470      pArg->pUserData = p;
161471    }
161472    rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, 
161473        xSFunc, xStep, xFinal, xValue, xInverse, pArg
161474    );
161475    if( pArg && pArg->nRef==0 ){
161476      assert( rc!=SQLITE_OK );
161477      xDestroy(p);
161478      sqlite3_free(pArg);
161479    }
161480  
161481   out:
161482    rc = sqlite3ApiExit(db, rc);
161483    sqlite3_mutex_leave(db->mutex);
161484    return rc;
161485  }
161486  
161487  /*
161488  ** Create new user functions.
161489  */
161490  SQLITE_API int sqlite3_create_function(
161491    sqlite3 *db,
161492    const char *zFunc,
161493    int nArg,
161494    int enc,
161495    void *p,
161496    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
161497    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
161498    void (*xFinal)(sqlite3_context*)
161499  ){
161500    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
161501                                      xFinal, 0, 0, 0);
161502  }
161503  SQLITE_API int sqlite3_create_function_v2(
161504    sqlite3 *db,
161505    const char *zFunc,
161506    int nArg,
161507    int enc,
161508    void *p,
161509    void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
161510    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
161511    void (*xFinal)(sqlite3_context*),
161512    void (*xDestroy)(void *)
161513  ){
161514    return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
161515                                      xFinal, 0, 0, xDestroy);
161516  }
161517  SQLITE_API int sqlite3_create_window_function(
161518    sqlite3 *db,
161519    const char *zFunc,
161520    int nArg,
161521    int enc,
161522    void *p,
161523    void (*xStep)(sqlite3_context*,int,sqlite3_value **),
161524    void (*xFinal)(sqlite3_context*),
161525    void (*xValue)(sqlite3_context*),
161526    void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
161527    void (*xDestroy)(void *)
161528  ){
161529    return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
161530                                      xFinal, xValue, xInverse, xDestroy);
161531  }
161532  
161533  #ifndef SQLITE_OMIT_UTF16
161534  SQLITE_API int sqlite3_create_function16(
161535    sqlite3 *db,
161536    const void *zFunctionName,
161537    int nArg,
161538    int eTextRep,
161539    void *p,
161540    void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
161541    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
161542    void (*xFinal)(sqlite3_context*)
161543  ){
161544    int rc;
161545    char *zFunc8;
161546  
161547  #ifdef SQLITE_ENABLE_API_ARMOR
161548    if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
161549  #endif
161550    sqlite3_mutex_enter(db->mutex);
161551    assert( !db->mallocFailed );
161552    zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
161553    rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
161554    sqlite3DbFree(db, zFunc8);
161555    rc = sqlite3ApiExit(db, rc);
161556    sqlite3_mutex_leave(db->mutex);
161557    return rc;
161558  }
161559  #endif
161560  
161561  
161562  /*
161563  ** The following is the implementation of an SQL function that always
161564  ** fails with an error message stating that the function is used in the
161565  ** wrong context.  The sqlite3_overload_function() API might construct
161566  ** SQL function that use this routine so that the functions will exist
161567  ** for name resolution but are actually overloaded by the xFindFunction
161568  ** method of virtual tables.
161569  */
161570  static void sqlite3InvalidFunction(
161571    sqlite3_context *context,  /* The function calling context */
161572    int NotUsed,               /* Number of arguments to the function */
161573    sqlite3_value **NotUsed2   /* Value of each argument */
161574  ){
161575    const char *zName = (const char*)sqlite3_user_data(context);
161576    char *zErr;
161577    UNUSED_PARAMETER2(NotUsed, NotUsed2);
161578    zErr = sqlite3_mprintf(
161579        "unable to use function %s in the requested context", zName);
161580    sqlite3_result_error(context, zErr, -1);
161581    sqlite3_free(zErr);
161582  }
161583  
161584  /*
161585  ** Declare that a function has been overloaded by a virtual table.
161586  **
161587  ** If the function already exists as a regular global function, then
161588  ** this routine is a no-op.  If the function does not exist, then create
161589  ** a new one that always throws a run-time error.  
161590  **
161591  ** When virtual tables intend to provide an overloaded function, they
161592  ** should call this routine to make sure the global function exists.
161593  ** A global function must exist in order for name resolution to work
161594  ** properly.
161595  */
161596  SQLITE_API int sqlite3_overload_function(
161597    sqlite3 *db,
161598    const char *zName,
161599    int nArg
161600  ){
161601    int rc;
161602    char *zCopy;
161603  
161604  #ifdef SQLITE_ENABLE_API_ARMOR
161605    if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
161606      return SQLITE_MISUSE_BKPT;
161607    }
161608  #endif
161609    sqlite3_mutex_enter(db->mutex);
161610    rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
161611    sqlite3_mutex_leave(db->mutex);
161612    if( rc ) return SQLITE_OK;
161613    zCopy = sqlite3_mprintf(zName);
161614    if( zCopy==0 ) return SQLITE_NOMEM;
161615    return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
161616                             zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
161617  }
161618  
161619  #ifndef SQLITE_OMIT_TRACE
161620  /*
161621  ** Register a trace function.  The pArg from the previously registered trace
161622  ** is returned.  
161623  **
161624  ** A NULL trace function means that no tracing is executes.  A non-NULL
161625  ** trace is a pointer to a function that is invoked at the start of each
161626  ** SQL statement.
161627  */
161628  #ifndef SQLITE_OMIT_DEPRECATED
161629  SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
161630    void *pOld;
161631  
161632  #ifdef SQLITE_ENABLE_API_ARMOR
161633    if( !sqlite3SafetyCheckOk(db) ){
161634      (void)SQLITE_MISUSE_BKPT;
161635      return 0;
161636    }
161637  #endif
161638    sqlite3_mutex_enter(db->mutex);
161639    pOld = db->pTraceArg;
161640    db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
161641    db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
161642    db->pTraceArg = pArg;
161643    sqlite3_mutex_leave(db->mutex);
161644    return pOld;
161645  }
161646  #endif /* SQLITE_OMIT_DEPRECATED */
161647  
161648  /* Register a trace callback using the version-2 interface.
161649  */
161650  SQLITE_API int sqlite3_trace_v2(
161651    sqlite3 *db,                               /* Trace this connection */
161652    unsigned mTrace,                           /* Mask of events to be traced */
161653    int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
161654    void *pArg                                 /* Context */
161655  ){
161656  #ifdef SQLITE_ENABLE_API_ARMOR
161657    if( !sqlite3SafetyCheckOk(db) ){
161658      return SQLITE_MISUSE_BKPT;
161659    }
161660  #endif
161661    sqlite3_mutex_enter(db->mutex);
161662    if( mTrace==0 ) xTrace = 0;
161663    if( xTrace==0 ) mTrace = 0;
161664    db->mTrace = mTrace;
161665    db->xTrace = xTrace;
161666    db->pTraceArg = pArg;
161667    sqlite3_mutex_leave(db->mutex);
161668    return SQLITE_OK;
161669  }
161670  
161671  #ifndef SQLITE_OMIT_DEPRECATED
161672  /*
161673  ** Register a profile function.  The pArg from the previously registered 
161674  ** profile function is returned.  
161675  **
161676  ** A NULL profile function means that no profiling is executes.  A non-NULL
161677  ** profile is a pointer to a function that is invoked at the conclusion of
161678  ** each SQL statement that is run.
161679  */
161680  SQLITE_API void *sqlite3_profile(
161681    sqlite3 *db,
161682    void (*xProfile)(void*,const char*,sqlite_uint64),
161683    void *pArg
161684  ){
161685    void *pOld;
161686  
161687  #ifdef SQLITE_ENABLE_API_ARMOR
161688    if( !sqlite3SafetyCheckOk(db) ){
161689      (void)SQLITE_MISUSE_BKPT;
161690      return 0;
161691    }
161692  #endif
161693    sqlite3_mutex_enter(db->mutex);
161694    pOld = db->pProfileArg;
161695    db->xProfile = xProfile;
161696    db->pProfileArg = pArg;
161697    db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
161698    if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
161699    sqlite3_mutex_leave(db->mutex);
161700    return pOld;
161701  }
161702  #endif /* SQLITE_OMIT_DEPRECATED */
161703  #endif /* SQLITE_OMIT_TRACE */
161704  
161705  /*
161706  ** Register a function to be invoked when a transaction commits.
161707  ** If the invoked function returns non-zero, then the commit becomes a
161708  ** rollback.
161709  */
161710  SQLITE_API void *sqlite3_commit_hook(
161711    sqlite3 *db,              /* Attach the hook to this database */
161712    int (*xCallback)(void*),  /* Function to invoke on each commit */
161713    void *pArg                /* Argument to the function */
161714  ){
161715    void *pOld;
161716  
161717  #ifdef SQLITE_ENABLE_API_ARMOR
161718    if( !sqlite3SafetyCheckOk(db) ){
161719      (void)SQLITE_MISUSE_BKPT;
161720      return 0;
161721    }
161722  #endif
161723    sqlite3_mutex_enter(db->mutex);
161724    pOld = db->pCommitArg;
161725    db->xCommitCallback = xCallback;
161726    db->pCommitArg = pArg;
161727    sqlite3_mutex_leave(db->mutex);
161728    return pOld;
161729  }
161730  
161731  /*
161732  ** Register a callback to be invoked each time a row is updated,
161733  ** inserted or deleted using this database connection.
161734  */
161735  SQLITE_API void *sqlite3_update_hook(
161736    sqlite3 *db,              /* Attach the hook to this database */
161737    void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
161738    void *pArg                /* Argument to the function */
161739  ){
161740    void *pRet;
161741  
161742  #ifdef SQLITE_ENABLE_API_ARMOR
161743    if( !sqlite3SafetyCheckOk(db) ){
161744      (void)SQLITE_MISUSE_BKPT;
161745      return 0;
161746    }
161747  #endif
161748    sqlite3_mutex_enter(db->mutex);
161749    pRet = db->pUpdateArg;
161750    db->xUpdateCallback = xCallback;
161751    db->pUpdateArg = pArg;
161752    sqlite3_mutex_leave(db->mutex);
161753    return pRet;
161754  }
161755  
161756  /*
161757  ** Register a callback to be invoked each time a transaction is rolled
161758  ** back by this database connection.
161759  */
161760  SQLITE_API void *sqlite3_rollback_hook(
161761    sqlite3 *db,              /* Attach the hook to this database */
161762    void (*xCallback)(void*), /* Callback function */
161763    void *pArg                /* Argument to the function */
161764  ){
161765    void *pRet;
161766  
161767  #ifdef SQLITE_ENABLE_API_ARMOR
161768    if( !sqlite3SafetyCheckOk(db) ){
161769      (void)SQLITE_MISUSE_BKPT;
161770      return 0;
161771    }
161772  #endif
161773    sqlite3_mutex_enter(db->mutex);
161774    pRet = db->pRollbackArg;
161775    db->xRollbackCallback = xCallback;
161776    db->pRollbackArg = pArg;
161777    sqlite3_mutex_leave(db->mutex);
161778    return pRet;
161779  }
161780  
161781  #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
161782  /*
161783  ** Register a callback to be invoked each time a row is updated,
161784  ** inserted or deleted using this database connection.
161785  */
161786  SQLITE_API void *sqlite3_preupdate_hook(
161787    sqlite3 *db,              /* Attach the hook to this database */
161788    void(*xCallback)(         /* Callback function */
161789      void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
161790    void *pArg                /* First callback argument */
161791  ){
161792    void *pRet;
161793    sqlite3_mutex_enter(db->mutex);
161794    pRet = db->pPreUpdateArg;
161795    db->xPreUpdateCallback = xCallback;
161796    db->pPreUpdateArg = pArg;
161797    sqlite3_mutex_leave(db->mutex);
161798    return pRet;
161799  }
161800  #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
161801  
161802  #ifndef SQLITE_OMIT_WAL
161803  /*
161804  ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
161805  ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
161806  ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
161807  ** wal_autocheckpoint()).
161808  */ 
161809  SQLITE_PRIVATE int sqlite3WalDefaultHook(
161810    void *pClientData,     /* Argument */
161811    sqlite3 *db,           /* Connection */
161812    const char *zDb,       /* Database */
161813    int nFrame             /* Size of WAL */
161814  ){
161815    if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
161816      sqlite3BeginBenignMalloc();
161817      sqlite3_wal_checkpoint(db, zDb);
161818      sqlite3EndBenignMalloc();
161819    }
161820    return SQLITE_OK;
161821  }
161822  #endif /* SQLITE_OMIT_WAL */
161823  
161824  /*
161825  ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
161826  ** a database after committing a transaction if there are nFrame or
161827  ** more frames in the log file. Passing zero or a negative value as the
161828  ** nFrame parameter disables automatic checkpoints entirely.
161829  **
161830  ** The callback registered by this function replaces any existing callback
161831  ** registered using sqlite3_wal_hook(). Likewise, registering a callback
161832  ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
161833  ** configured by this function.
161834  */
161835  SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
161836  #ifdef SQLITE_OMIT_WAL
161837    UNUSED_PARAMETER(db);
161838    UNUSED_PARAMETER(nFrame);
161839  #else
161840  #ifdef SQLITE_ENABLE_API_ARMOR
161841    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161842  #endif
161843    if( nFrame>0 ){
161844      sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
161845    }else{
161846      sqlite3_wal_hook(db, 0, 0);
161847    }
161848  #endif
161849    return SQLITE_OK;
161850  }
161851  
161852  /*
161853  ** Register a callback to be invoked each time a transaction is written
161854  ** into the write-ahead-log by this database connection.
161855  */
161856  SQLITE_API void *sqlite3_wal_hook(
161857    sqlite3 *db,                    /* Attach the hook to this db handle */
161858    int(*xCallback)(void *, sqlite3*, const char*, int),
161859    void *pArg                      /* First argument passed to xCallback() */
161860  ){
161861  #ifndef SQLITE_OMIT_WAL
161862    void *pRet;
161863  #ifdef SQLITE_ENABLE_API_ARMOR
161864    if( !sqlite3SafetyCheckOk(db) ){
161865      (void)SQLITE_MISUSE_BKPT;
161866      return 0;
161867    }
161868  #endif
161869    sqlite3_mutex_enter(db->mutex);
161870    pRet = db->pWalArg;
161871    db->xWalCallback = xCallback;
161872    db->pWalArg = pArg;
161873    sqlite3_mutex_leave(db->mutex);
161874    return pRet;
161875  #else
161876    return 0;
161877  #endif
161878  }
161879  
161880  /*
161881  ** Checkpoint database zDb.
161882  */
161883  SQLITE_API int sqlite3_wal_checkpoint_v2(
161884    sqlite3 *db,                    /* Database handle */
161885    const char *zDb,                /* Name of attached database (or NULL) */
161886    int eMode,                      /* SQLITE_CHECKPOINT_* value */
161887    int *pnLog,                     /* OUT: Size of WAL log in frames */
161888    int *pnCkpt                     /* OUT: Total number of frames checkpointed */
161889  ){
161890  #ifdef SQLITE_OMIT_WAL
161891    return SQLITE_OK;
161892  #else
161893    int rc;                         /* Return code */
161894    int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
161895  
161896  #ifdef SQLITE_ENABLE_API_ARMOR
161897    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161898  #endif
161899  
161900    /* Initialize the output variables to -1 in case an error occurs. */
161901    if( pnLog ) *pnLog = -1;
161902    if( pnCkpt ) *pnCkpt = -1;
161903  
161904    assert( SQLITE_CHECKPOINT_PASSIVE==0 );
161905    assert( SQLITE_CHECKPOINT_FULL==1 );
161906    assert( SQLITE_CHECKPOINT_RESTART==2 );
161907    assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
161908    if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
161909      /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
161910      ** mode: */
161911      return SQLITE_MISUSE;
161912    }
161913  
161914    sqlite3_mutex_enter(db->mutex);
161915    if( zDb && zDb[0] ){
161916      iDb = sqlite3FindDbName(db, zDb);
161917    }
161918    if( iDb<0 ){
161919      rc = SQLITE_ERROR;
161920      sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
161921    }else{
161922      db->busyHandler.nBusy = 0;
161923      rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
161924      sqlite3Error(db, rc);
161925    }
161926    rc = sqlite3ApiExit(db, rc);
161927  
161928    /* If there are no active statements, clear the interrupt flag at this
161929    ** point.  */
161930    if( db->nVdbeActive==0 ){
161931      db->u1.isInterrupted = 0;
161932    }
161933  
161934    sqlite3_mutex_leave(db->mutex);
161935    return rc;
161936  #endif
161937  }
161938  
161939  
161940  /*
161941  ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
161942  ** to contains a zero-length string, all attached databases are 
161943  ** checkpointed.
161944  */
161945  SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
161946    /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
161947    ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
161948    return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
161949  }
161950  
161951  #ifndef SQLITE_OMIT_WAL
161952  /*
161953  ** Run a checkpoint on database iDb. This is a no-op if database iDb is
161954  ** not currently open in WAL mode.
161955  **
161956  ** If a transaction is open on the database being checkpointed, this 
161957  ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
161958  ** an error occurs while running the checkpoint, an SQLite error code is 
161959  ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
161960  **
161961  ** The mutex on database handle db should be held by the caller. The mutex
161962  ** associated with the specific b-tree being checkpointed is taken by
161963  ** this function while the checkpoint is running.
161964  **
161965  ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
161966  ** checkpointed. If an error is encountered it is returned immediately -
161967  ** no attempt is made to checkpoint any remaining databases.
161968  **
161969  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
161970  ** or TRUNCATE.
161971  */
161972  SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
161973    int rc = SQLITE_OK;             /* Return code */
161974    int i;                          /* Used to iterate through attached dbs */
161975    int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
161976  
161977    assert( sqlite3_mutex_held(db->mutex) );
161978    assert( !pnLog || *pnLog==-1 );
161979    assert( !pnCkpt || *pnCkpt==-1 );
161980  
161981    for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
161982      if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
161983        rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
161984        pnLog = 0;
161985        pnCkpt = 0;
161986        if( rc==SQLITE_BUSY ){
161987          bBusy = 1;
161988          rc = SQLITE_OK;
161989        }
161990      }
161991    }
161992  
161993    return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
161994  }
161995  #endif /* SQLITE_OMIT_WAL */
161996  
161997  /*
161998  ** This function returns true if main-memory should be used instead of
161999  ** a temporary file for transient pager files and statement journals.
162000  ** The value returned depends on the value of db->temp_store (runtime
162001  ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
162002  ** following table describes the relationship between these two values
162003  ** and this functions return value.
162004  **
162005  **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
162006  **   -----------------     --------------     ------------------------------
162007  **   0                     any                file      (return 0)
162008  **   1                     1                  file      (return 0)
162009  **   1                     2                  memory    (return 1)
162010  **   1                     0                  file      (return 0)
162011  **   2                     1                  file      (return 0)
162012  **   2                     2                  memory    (return 1)
162013  **   2                     0                  memory    (return 1)
162014  **   3                     any                memory    (return 1)
162015  */
162016  SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
162017  #if SQLITE_TEMP_STORE==1
162018    return ( db->temp_store==2 );
162019  #endif
162020  #if SQLITE_TEMP_STORE==2
162021    return ( db->temp_store!=1 );
162022  #endif
162023  #if SQLITE_TEMP_STORE==3
162024    UNUSED_PARAMETER(db);
162025    return 1;
162026  #endif
162027  #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
162028    UNUSED_PARAMETER(db);
162029    return 0;
162030  #endif
162031  }
162032  
162033  /*
162034  ** Return UTF-8 encoded English language explanation of the most recent
162035  ** error.
162036  */
162037  SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
162038    const char *z;
162039    if( !db ){
162040      return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
162041    }
162042    if( !sqlite3SafetyCheckSickOrOk(db) ){
162043      return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
162044    }
162045    sqlite3_mutex_enter(db->mutex);
162046    if( db->mallocFailed ){
162047      z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
162048    }else{
162049      testcase( db->pErr==0 );
162050      z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
162051      assert( !db->mallocFailed );
162052      if( z==0 ){
162053        z = sqlite3ErrStr(db->errCode);
162054      }
162055    }
162056    sqlite3_mutex_leave(db->mutex);
162057    return z;
162058  }
162059  
162060  #ifndef SQLITE_OMIT_UTF16
162061  /*
162062  ** Return UTF-16 encoded English language explanation of the most recent
162063  ** error.
162064  */
162065  SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
162066    static const u16 outOfMem[] = {
162067      'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
162068    };
162069    static const u16 misuse[] = {
162070      'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
162071      'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
162072      'm', 'i', 's', 'u', 's', 'e', 0
162073    };
162074  
162075    const void *z;
162076    if( !db ){
162077      return (void *)outOfMem;
162078    }
162079    if( !sqlite3SafetyCheckSickOrOk(db) ){
162080      return (void *)misuse;
162081    }
162082    sqlite3_mutex_enter(db->mutex);
162083    if( db->mallocFailed ){
162084      z = (void *)outOfMem;
162085    }else{
162086      z = sqlite3_value_text16(db->pErr);
162087      if( z==0 ){
162088        sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
162089        z = sqlite3_value_text16(db->pErr);
162090      }
162091      /* A malloc() may have failed within the call to sqlite3_value_text16()
162092      ** above. If this is the case, then the db->mallocFailed flag needs to
162093      ** be cleared before returning. Do this directly, instead of via
162094      ** sqlite3ApiExit(), to avoid setting the database handle error message.
162095      */
162096      sqlite3OomClear(db);
162097    }
162098    sqlite3_mutex_leave(db->mutex);
162099    return z;
162100  }
162101  #endif /* SQLITE_OMIT_UTF16 */
162102  
162103  /*
162104  ** Return the most recent error code generated by an SQLite routine. If NULL is
162105  ** passed to this function, we assume a malloc() failed during sqlite3_open().
162106  */
162107  SQLITE_API int sqlite3_errcode(sqlite3 *db){
162108    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
162109      return SQLITE_MISUSE_BKPT;
162110    }
162111    if( !db || db->mallocFailed ){
162112      return SQLITE_NOMEM_BKPT;
162113    }
162114    return db->errCode & db->errMask;
162115  }
162116  SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
162117    if( db && !sqlite3SafetyCheckSickOrOk(db) ){
162118      return SQLITE_MISUSE_BKPT;
162119    }
162120    if( !db || db->mallocFailed ){
162121      return SQLITE_NOMEM_BKPT;
162122    }
162123    return db->errCode;
162124  }
162125  SQLITE_API int sqlite3_system_errno(sqlite3 *db){
162126    return db ? db->iSysErrno : 0;
162127  }  
162128  
162129  /*
162130  ** Return a string that describes the kind of error specified in the
162131  ** argument.  For now, this simply calls the internal sqlite3ErrStr()
162132  ** function.
162133  */
162134  SQLITE_API const char *sqlite3_errstr(int rc){
162135    return sqlite3ErrStr(rc);
162136  }
162137  
162138  /*
162139  ** Create a new collating function for database "db".  The name is zName
162140  ** and the encoding is enc.
162141  */
162142  static int createCollation(
162143    sqlite3* db,
162144    const char *zName, 
162145    u8 enc,
162146    void* pCtx,
162147    int(*xCompare)(void*,int,const void*,int,const void*),
162148    void(*xDel)(void*)
162149  ){
162150    CollSeq *pColl;
162151    int enc2;
162152    
162153    assert( sqlite3_mutex_held(db->mutex) );
162154  
162155    /* If SQLITE_UTF16 is specified as the encoding type, transform this
162156    ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
162157    ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
162158    */
162159    enc2 = enc;
162160    testcase( enc2==SQLITE_UTF16 );
162161    testcase( enc2==SQLITE_UTF16_ALIGNED );
162162    if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
162163      enc2 = SQLITE_UTF16NATIVE;
162164    }
162165    if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
162166      return SQLITE_MISUSE_BKPT;
162167    }
162168  
162169    /* Check if this call is removing or replacing an existing collation 
162170    ** sequence. If so, and there are active VMs, return busy. If there
162171    ** are no active VMs, invalidate any pre-compiled statements.
162172    */
162173    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
162174    if( pColl && pColl->xCmp ){
162175      if( db->nVdbeActive ){
162176        sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
162177          "unable to delete/modify collation sequence due to active statements");
162178        return SQLITE_BUSY;
162179      }
162180      sqlite3ExpirePreparedStatements(db, 0);
162181  
162182      /* If collation sequence pColl was created directly by a call to
162183      ** sqlite3_create_collation, and not generated by synthCollSeq(),
162184      ** then any copies made by synthCollSeq() need to be invalidated.
162185      ** Also, collation destructor - CollSeq.xDel() - function may need
162186      ** to be called.
162187      */ 
162188      if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
162189        CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
162190        int j;
162191        for(j=0; j<3; j++){
162192          CollSeq *p = &aColl[j];
162193          if( p->enc==pColl->enc ){
162194            if( p->xDel ){
162195              p->xDel(p->pUser);
162196            }
162197            p->xCmp = 0;
162198          }
162199        }
162200      }
162201    }
162202  
162203    pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
162204    if( pColl==0 ) return SQLITE_NOMEM_BKPT;
162205    pColl->xCmp = xCompare;
162206    pColl->pUser = pCtx;
162207    pColl->xDel = xDel;
162208    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
162209    sqlite3Error(db, SQLITE_OK);
162210    return SQLITE_OK;
162211  }
162212  
162213  
162214  /*
162215  ** This array defines hard upper bounds on limit values.  The
162216  ** initializer must be kept in sync with the SQLITE_LIMIT_*
162217  ** #defines in sqlite3.h.
162218  */
162219  static const int aHardLimit[] = {
162220    SQLITE_MAX_LENGTH,
162221    SQLITE_MAX_SQL_LENGTH,
162222    SQLITE_MAX_COLUMN,
162223    SQLITE_MAX_EXPR_DEPTH,
162224    SQLITE_MAX_COMPOUND_SELECT,
162225    SQLITE_MAX_VDBE_OP,
162226    SQLITE_MAX_FUNCTION_ARG,
162227    SQLITE_MAX_ATTACHED,
162228    SQLITE_MAX_LIKE_PATTERN_LENGTH,
162229    SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
162230    SQLITE_MAX_TRIGGER_DEPTH,
162231    SQLITE_MAX_WORKER_THREADS,
162232  };
162233  
162234  /*
162235  ** Make sure the hard limits are set to reasonable values
162236  */
162237  #if SQLITE_MAX_LENGTH<100
162238  # error SQLITE_MAX_LENGTH must be at least 100
162239  #endif
162240  #if SQLITE_MAX_SQL_LENGTH<100
162241  # error SQLITE_MAX_SQL_LENGTH must be at least 100
162242  #endif
162243  #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
162244  # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
162245  #endif
162246  #if SQLITE_MAX_COMPOUND_SELECT<2
162247  # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
162248  #endif
162249  #if SQLITE_MAX_VDBE_OP<40
162250  # error SQLITE_MAX_VDBE_OP must be at least 40
162251  #endif
162252  #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
162253  # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
162254  #endif
162255  #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
162256  # error SQLITE_MAX_ATTACHED must be between 0 and 125
162257  #endif
162258  #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
162259  # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
162260  #endif
162261  #if SQLITE_MAX_COLUMN>32767
162262  # error SQLITE_MAX_COLUMN must not exceed 32767
162263  #endif
162264  #if SQLITE_MAX_TRIGGER_DEPTH<1
162265  # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
162266  #endif
162267  #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
162268  # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
162269  #endif
162270  
162271  
162272  /*
162273  ** Change the value of a limit.  Report the old value.
162274  ** If an invalid limit index is supplied, report -1.
162275  ** Make no changes but still report the old value if the
162276  ** new limit is negative.
162277  **
162278  ** A new lower limit does not shrink existing constructs.
162279  ** It merely prevents new constructs that exceed the limit
162280  ** from forming.
162281  */
162282  SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
162283    int oldLimit;
162284  
162285  #ifdef SQLITE_ENABLE_API_ARMOR
162286    if( !sqlite3SafetyCheckOk(db) ){
162287      (void)SQLITE_MISUSE_BKPT;
162288      return -1;
162289    }
162290  #endif
162291  
162292    /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
162293    ** there is a hard upper bound set at compile-time by a C preprocessor
162294    ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
162295    ** "_MAX_".)
162296    */
162297    assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
162298    assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
162299    assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
162300    assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
162301    assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
162302    assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
162303    assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
162304    assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
162305    assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
162306                                                 SQLITE_MAX_LIKE_PATTERN_LENGTH );
162307    assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
162308    assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
162309    assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
162310    assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
162311  
162312  
162313    if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
162314      return -1;
162315    }
162316    oldLimit = db->aLimit[limitId];
162317    if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
162318      if( newLimit>aHardLimit[limitId] ){
162319        newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
162320      }
162321      db->aLimit[limitId] = newLimit;
162322    }
162323    return oldLimit;                     /* IMP: R-53341-35419 */
162324  }
162325  
162326  /*
162327  ** This function is used to parse both URIs and non-URI filenames passed by the
162328  ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
162329  ** URIs specified as part of ATTACH statements.
162330  **
162331  ** The first argument to this function is the name of the VFS to use (or
162332  ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
162333  ** query parameter. The second argument contains the URI (or non-URI filename)
162334  ** itself. When this function is called the *pFlags variable should contain
162335  ** the default flags to open the database handle with. The value stored in
162336  ** *pFlags may be updated before returning if the URI filename contains 
162337  ** "cache=xxx" or "mode=xxx" query parameters.
162338  **
162339  ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
162340  ** the VFS that should be used to open the database file. *pzFile is set to
162341  ** point to a buffer containing the name of the file to open. It is the 
162342  ** responsibility of the caller to eventually call sqlite3_free() to release
162343  ** this buffer.
162344  **
162345  ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
162346  ** may be set to point to a buffer containing an English language error 
162347  ** message. It is the responsibility of the caller to eventually release
162348  ** this buffer by calling sqlite3_free().
162349  */
162350  SQLITE_PRIVATE int sqlite3ParseUri(
162351    const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
162352    const char *zUri,               /* Nul-terminated URI to parse */
162353    unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
162354    sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
162355    char **pzFile,                  /* OUT: Filename component of URI */
162356    char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
162357  ){
162358    int rc = SQLITE_OK;
162359    unsigned int flags = *pFlags;
162360    const char *zVfs = zDefaultVfs;
162361    char *zFile;
162362    char c;
162363    int nUri = sqlite3Strlen30(zUri);
162364  
162365    assert( *pzErrMsg==0 );
162366  
162367    if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
162368              || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
162369     && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
162370    ){
162371      char *zOpt;
162372      int eState;                   /* Parser state when parsing URI */
162373      int iIn;                      /* Input character index */
162374      int iOut = 0;                 /* Output character index */
162375      u64 nByte = nUri+2;           /* Bytes of space to allocate */
162376  
162377      /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
162378      ** method that there may be extra parameters following the file-name.  */
162379      flags |= SQLITE_OPEN_URI;
162380  
162381      for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
162382      zFile = sqlite3_malloc64(nByte);
162383      if( !zFile ) return SQLITE_NOMEM_BKPT;
162384  
162385      iIn = 5;
162386  #ifdef SQLITE_ALLOW_URI_AUTHORITY
162387      if( strncmp(zUri+5, "///", 3)==0 ){
162388        iIn = 7;
162389        /* The following condition causes URIs with five leading / characters
162390        ** like file://///host/path to be converted into UNCs like //host/path.
162391        ** The correct URI for that UNC has only two or four leading / characters
162392        ** file://host/path or file:////host/path.  But 5 leading slashes is a 
162393        ** common error, we are told, so we handle it as a special case. */
162394        if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
162395      }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
162396        iIn = 16;
162397      }
162398  #else
162399      /* Discard the scheme and authority segments of the URI. */
162400      if( zUri[5]=='/' && zUri[6]=='/' ){
162401        iIn = 7;
162402        while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
162403        if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
162404          *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
162405              iIn-7, &zUri[7]);
162406          rc = SQLITE_ERROR;
162407          goto parse_uri_out;
162408        }
162409      }
162410  #endif
162411  
162412      /* Copy the filename and any query parameters into the zFile buffer. 
162413      ** Decode %HH escape codes along the way. 
162414      **
162415      ** Within this loop, variable eState may be set to 0, 1 or 2, depending
162416      ** on the parsing context. As follows:
162417      **
162418      **   0: Parsing file-name.
162419      **   1: Parsing name section of a name=value query parameter.
162420      **   2: Parsing value section of a name=value query parameter.
162421      */
162422      eState = 0;
162423      while( (c = zUri[iIn])!=0 && c!='#' ){
162424        iIn++;
162425        if( c=='%' 
162426         && sqlite3Isxdigit(zUri[iIn]) 
162427         && sqlite3Isxdigit(zUri[iIn+1]) 
162428        ){
162429          int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
162430          octet += sqlite3HexToInt(zUri[iIn++]);
162431  
162432          assert( octet>=0 && octet<256 );
162433          if( octet==0 ){
162434  #ifndef SQLITE_ENABLE_URI_00_ERROR
162435            /* This branch is taken when "%00" appears within the URI. In this
162436            ** case we ignore all text in the remainder of the path, name or
162437            ** value currently being parsed. So ignore the current character
162438            ** and skip to the next "?", "=" or "&", as appropriate. */
162439            while( (c = zUri[iIn])!=0 && c!='#' 
162440                && (eState!=0 || c!='?')
162441                && (eState!=1 || (c!='=' && c!='&'))
162442                && (eState!=2 || c!='&')
162443            ){
162444              iIn++;
162445            }
162446            continue;
162447  #else
162448            /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
162449            *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
162450            rc = SQLITE_ERROR;
162451            goto parse_uri_out;
162452  #endif
162453          }
162454          c = octet;
162455        }else if( eState==1 && (c=='&' || c=='=') ){
162456          if( zFile[iOut-1]==0 ){
162457            /* An empty option name. Ignore this option altogether. */
162458            while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
162459            continue;
162460          }
162461          if( c=='&' ){
162462            zFile[iOut++] = '\0';
162463          }else{
162464            eState = 2;
162465          }
162466          c = 0;
162467        }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
162468          c = 0;
162469          eState = 1;
162470        }
162471        zFile[iOut++] = c;
162472      }
162473      if( eState==1 ) zFile[iOut++] = '\0';
162474      zFile[iOut++] = '\0';
162475      zFile[iOut++] = '\0';
162476  
162477      /* Check if there were any options specified that should be interpreted 
162478      ** here. Options that are interpreted here include "vfs" and those that
162479      ** correspond to flags that may be passed to the sqlite3_open_v2()
162480      ** method. */
162481      zOpt = &zFile[sqlite3Strlen30(zFile)+1];
162482      while( zOpt[0] ){
162483        int nOpt = sqlite3Strlen30(zOpt);
162484        char *zVal = &zOpt[nOpt+1];
162485        int nVal = sqlite3Strlen30(zVal);
162486  
162487        if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
162488          zVfs = zVal;
162489        }else{
162490          struct OpenMode {
162491            const char *z;
162492            int mode;
162493          } *aMode = 0;
162494          char *zModeType = 0;
162495          int mask = 0;
162496          int limit = 0;
162497  
162498          if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
162499            static struct OpenMode aCacheMode[] = {
162500              { "shared",  SQLITE_OPEN_SHAREDCACHE },
162501              { "private", SQLITE_OPEN_PRIVATECACHE },
162502              { 0, 0 }
162503            };
162504  
162505            mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
162506            aMode = aCacheMode;
162507            limit = mask;
162508            zModeType = "cache";
162509          }
162510          if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
162511            static struct OpenMode aOpenMode[] = {
162512              { "ro",  SQLITE_OPEN_READONLY },
162513              { "rw",  SQLITE_OPEN_READWRITE }, 
162514              { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
162515              { "memory", SQLITE_OPEN_MEMORY },
162516              { 0, 0 }
162517            };
162518  
162519            mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
162520                     | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
162521            aMode = aOpenMode;
162522            limit = mask & flags;
162523            zModeType = "access";
162524          }
162525  
162526          if( aMode ){
162527            int i;
162528            int mode = 0;
162529            for(i=0; aMode[i].z; i++){
162530              const char *z = aMode[i].z;
162531              if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
162532                mode = aMode[i].mode;
162533                break;
162534              }
162535            }
162536            if( mode==0 ){
162537              *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
162538              rc = SQLITE_ERROR;
162539              goto parse_uri_out;
162540            }
162541            if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
162542              *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
162543                                          zModeType, zVal);
162544              rc = SQLITE_PERM;
162545              goto parse_uri_out;
162546            }
162547            flags = (flags & ~mask) | mode;
162548          }
162549        }
162550  
162551        zOpt = &zVal[nVal+1];
162552      }
162553  
162554    }else{
162555      zFile = sqlite3_malloc64(nUri+2);
162556      if( !zFile ) return SQLITE_NOMEM_BKPT;
162557      if( nUri ){
162558        memcpy(zFile, zUri, nUri);
162559      }
162560      zFile[nUri] = '\0';
162561      zFile[nUri+1] = '\0';
162562      flags &= ~SQLITE_OPEN_URI;
162563    }
162564  
162565    /* if branching is enabled, use the null VFS */
162566    BRANCHTRACE("checking the URI filename: %s   \n\t\t\t\t converted: %s", zUri, zFile);
162567    {
162568      char *zActive = (char*) sqlite3_uri_parameter(zFile, "branches");
162569      if( zActive && strcmp(zActive,"on")==0 ){
162570        BRANCHTRACE("registering null VFS");
162571        rc = sqlite3_vfs_register(sqlite3_nullvfs(), 0);
162572        zVfs = "null";
162573      }
162574    }
162575    BRANCHTRACE("VFS: %s", zVfs);
162576  
162577    *ppVfs = sqlite3_vfs_find(zVfs);
162578    if( *ppVfs==0 ){
162579      *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
162580      rc = SQLITE_ERROR;
162581    }
162582   parse_uri_out:
162583    if( rc!=SQLITE_OK ){
162584      sqlite3_free(zFile);
162585      zFile = 0;
162586    }
162587    *pFlags = flags;
162588    *pzFile = zFile;
162589    return rc;
162590  }
162591  
162592  #if defined(SQLITE_HAS_CODEC)
162593  /*
162594  ** Process URI filename query parameters relevant to the SQLite Encryption
162595  ** Extension.  Return true if any of the relevant query parameters are
162596  ** seen and return false if not.
162597  */
162598  SQLITE_PRIVATE int sqlite3CodecQueryParameters(
162599    sqlite3 *db,           /* Database connection */
162600    const char *zDb,       /* Which schema is being created/attached */
162601    const char *zUri       /* URI filename */
162602  ){
162603    const char *zKey;
162604    if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){
162605      u8 iByte;
162606      int i;
162607      char zDecoded[40];
162608      for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
162609        iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
162610        if( (i&1)!=0 ) zDecoded[i/2] = iByte;
162611      }
162612      sqlite3_key_v2(db, zDb, zDecoded, i/2);
162613      return 1;
162614    }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){
162615      sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
162616      return 1;
162617    }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){
162618      sqlite3_key_v2(db, zDb, zKey, -1);
162619      return 1;
162620    }else{
162621      return 0;
162622    }
162623  }
162624  #endif
162625  
162626  
162627  /*
162628  ** This routine does the work of opening a database on behalf of
162629  ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
162630  ** is UTF-8 encoded.
162631  */
162632  static int openDatabase(
162633    const char *zFilename, /* Database filename UTF-8 encoded */
162634    sqlite3 **ppDb,        /* OUT: Returned database handle */
162635    unsigned int flags,    /* Operational flags */
162636    const char *zVfs       /* Name of the VFS to use */
162637  ){
162638    sqlite3 *db;                    /* Store allocated handle here */
162639    int rc;                         /* Return code */
162640    int isThreadsafe;               /* True for threadsafe connections */
162641    char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
162642    char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
162643  
162644  #ifdef SQLITE_ENABLE_API_ARMOR
162645    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
162646  #endif
162647    *ppDb = 0;
162648  #ifndef SQLITE_OMIT_AUTOINIT
162649    rc = sqlite3_initialize();
162650    if( rc ) return rc;
162651  #endif
162652  
162653    if( sqlite3GlobalConfig.bCoreMutex==0 ){
162654      isThreadsafe = 0;
162655    }else if( flags & SQLITE_OPEN_NOMUTEX ){
162656      isThreadsafe = 0;
162657    }else if( flags & SQLITE_OPEN_FULLMUTEX ){
162658      isThreadsafe = 1;
162659    }else{
162660      isThreadsafe = sqlite3GlobalConfig.bFullMutex;
162661    }
162662  
162663    if( flags & SQLITE_OPEN_PRIVATECACHE ){
162664      flags &= ~SQLITE_OPEN_SHAREDCACHE;
162665    }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
162666      flags |= SQLITE_OPEN_SHAREDCACHE;
162667    }
162668  
162669    /* Remove harmful bits from the flags parameter
162670    **
162671    ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
162672    ** dealt with in the previous code block.  Besides these, the only
162673    ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
162674    ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
162675    ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
162676    ** off all other flags.
162677    */
162678    flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
162679                 SQLITE_OPEN_EXCLUSIVE |
162680                 SQLITE_OPEN_MAIN_DB |
162681                 SQLITE_OPEN_TEMP_DB | 
162682                 SQLITE_OPEN_TRANSIENT_DB | 
162683                 SQLITE_OPEN_MAIN_JOURNAL | 
162684                 SQLITE_OPEN_TEMP_JOURNAL | 
162685                 SQLITE_OPEN_SUBJOURNAL | 
162686                 SQLITE_OPEN_MASTER_JOURNAL |
162687                 SQLITE_OPEN_NOMUTEX |
162688                 SQLITE_OPEN_FULLMUTEX |
162689                 SQLITE_OPEN_WAL
162690               );
162691  
162692    /* Allocate the sqlite data structure */
162693    db = sqlite3MallocZero( sizeof(sqlite3) );
162694    if( db==0 ) goto opendb_out;
162695    if( isThreadsafe 
162696  #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
162697     || sqlite3GlobalConfig.bCoreMutex
162698  #endif
162699    ){
162700      db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
162701      if( db->mutex==0 ){
162702        sqlite3_free(db);
162703        db = 0;
162704        goto opendb_out;
162705      }
162706      if( isThreadsafe==0 ){
162707        sqlite3MutexWarnOnContention(db->mutex);
162708      }
162709    }
162710    sqlite3_mutex_enter(db->mutex);
162711    db->errMask = 0xff;
162712    db->nDb = 2;
162713    db->magic = SQLITE_MAGIC_BUSY;
162714    db->aDb = db->aDbStatic;
162715    db->lookaside.bDisable = 1;
162716  
162717    assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
162718    memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
162719    db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
162720    db->autoCommit = 1;
162721    db->nextAutovac = -1;
162722    db->szMmap = sqlite3GlobalConfig.szMmap;
162723    db->nextPagesize = 0;
162724    db->nMaxSorterMmap = 0x7FFFFFFF;
162725    db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
162726  #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
162727                   | SQLITE_AutoIndex
162728  #endif
162729  #if SQLITE_DEFAULT_CKPTFULLFSYNC
162730                   | SQLITE_CkptFullFSync
162731  #endif
162732  #if SQLITE_DEFAULT_FILE_FORMAT<4
162733                   | SQLITE_LegacyFileFmt
162734  #endif
162735  #ifdef SQLITE_ENABLE_LOAD_EXTENSION
162736                   | SQLITE_LoadExtension
162737  #endif
162738  #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
162739                   | SQLITE_RecTriggers
162740  #endif
162741  #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
162742                   | SQLITE_ForeignKeys
162743  #endif
162744  #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
162745                   | SQLITE_ReverseOrder
162746  #endif
162747  #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
162748                   | SQLITE_CellSizeCk
162749  #endif
162750  #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
162751                   | SQLITE_Fts3Tokenizer
162752  #endif
162753  #if defined(SQLITE_ENABLE_QPSG)
162754                   | SQLITE_EnableQPSG
162755  #endif
162756  #if defined(SQLITE_DEFAULT_DEFENSIVE)
162757                   | SQLITE_Defensive
162758  #endif
162759        ;
162760    sqlite3HashInit(&db->aCollSeq);
162761  #ifndef SQLITE_OMIT_VIRTUALTABLE
162762    sqlite3HashInit(&db->aModule);
162763  #endif
162764  
162765    /* Add the default collation sequence BINARY. BINARY works for both UTF-8
162766    ** and UTF-16, so add a version for each to avoid any unnecessary
162767    ** conversions. The only error that can occur here is a malloc() failure.
162768    **
162769    ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
162770    ** functions:
162771    */
162772    createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
162773    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
162774    createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
162775    createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
162776    createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
162777    if( db->mallocFailed ){
162778      goto opendb_out;
162779    }
162780    /* EVIDENCE-OF: R-08308-17224 The default collating function for all
162781    ** strings is BINARY. 
162782    */
162783    db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
162784    assert( db->pDfltColl!=0 );
162785  
162786    /* Parse the filename/URI argument
162787    **
162788    ** Only allow sensible combinations of bits in the flags argument.  
162789    ** Throw an error if any non-sense combination is used.  If we
162790    ** do not block illegal combinations here, it could trigger
162791    ** assert() statements in deeper layers.  Sensible combinations
162792    ** are:
162793    **
162794    **  1:  SQLITE_OPEN_READONLY
162795    **  2:  SQLITE_OPEN_READWRITE
162796    **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
162797    */
162798    db->openFlags = flags;
162799    assert( SQLITE_OPEN_READONLY  == 0x01 );
162800    assert( SQLITE_OPEN_READWRITE == 0x02 );
162801    assert( SQLITE_OPEN_CREATE    == 0x04 );
162802    testcase( (1<<(flags&7))==0x02 ); /* READONLY */
162803    testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
162804    testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
162805    if( ((1<<(flags&7)) & 0x46)==0 ){
162806      rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
162807    }else{
162808      rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
162809    }
162810    if( rc!=SQLITE_OK ){
162811      if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
162812      sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
162813      sqlite3_free(zErrMsg);
162814      goto opendb_out;
162815    }
162816  
162817    /* Open the backend database driver */
162818    rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
162819                          flags | SQLITE_OPEN_MAIN_DB);
162820    if( rc!=SQLITE_OK ){
162821      if( rc==SQLITE_IOERR_NOMEM ){
162822        rc = SQLITE_NOMEM_BKPT;
162823      }
162824      sqlite3Error(db, rc);
162825      goto opendb_out;
162826    }
162827    sqlite3BtreeEnter(db->aDb[0].pBt);
162828    db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
162829    if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
162830    sqlite3BtreeLeave(db->aDb[0].pBt);
162831    db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
162832  
162833    /* The default safety_level for the main database is FULL; for the temp
162834    ** database it is OFF. This matches the pager layer defaults.  
162835    */
162836    db->aDb[0].zDbSName = "main";
162837    db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
162838    db->aDb[1].zDbSName = "temp";
162839    db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
162840  
162841    db->magic = SQLITE_MAGIC_OPEN;
162842    if( db->mallocFailed ){
162843      goto opendb_out;
162844    }
162845  
162846    /* Register all built-in functions, but do not attempt to read the
162847    ** database schema yet. This is delayed until the first time the database
162848    ** is accessed.
162849    */
162850    sqlite3Error(db, SQLITE_OK);
162851    sqlite3RegisterPerConnectionBuiltinFunctions(db);
162852    rc = sqlite3_errcode(db);
162853  
162854  #ifdef SQLITE_ENABLE_FTS5
162855    /* Register any built-in FTS5 module before loading the automatic
162856    ** extensions. This allows automatic extensions to register FTS5 
162857    ** tokenizers and auxiliary functions.  */
162858    if( !db->mallocFailed && rc==SQLITE_OK ){
162859      rc = sqlite3Fts5Init(db);
162860    }
162861  #endif
162862  
162863    /* Load automatic extensions - extensions that have been registered
162864    ** using the sqlite3_automatic_extension() API.
162865    */
162866    if( rc==SQLITE_OK ){
162867      sqlite3AutoLoadExtensions(db);
162868      rc = sqlite3_errcode(db);
162869      if( rc!=SQLITE_OK ){
162870        goto opendb_out;
162871      }
162872    }
162873  
162874  #ifdef SQLITE_ENABLE_FTS1
162875    if( !db->mallocFailed ){
162876      extern int sqlite3Fts1Init(sqlite3*);
162877      rc = sqlite3Fts1Init(db);
162878    }
162879  #endif
162880  
162881  #ifdef SQLITE_ENABLE_FTS2
162882    if( !db->mallocFailed && rc==SQLITE_OK ){
162883      extern int sqlite3Fts2Init(sqlite3*);
162884      rc = sqlite3Fts2Init(db);
162885    }
162886  #endif
162887  
162888  #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
162889    if( !db->mallocFailed && rc==SQLITE_OK ){
162890      rc = sqlite3Fts3Init(db);
162891    }
162892  #endif
162893  
162894  #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
162895    if( !db->mallocFailed && rc==SQLITE_OK ){
162896      rc = sqlite3IcuInit(db);
162897    }
162898  #endif
162899  
162900  #ifdef SQLITE_ENABLE_RTREE
162901    if( !db->mallocFailed && rc==SQLITE_OK){
162902      rc = sqlite3RtreeInit(db);
162903    }
162904  #endif
162905  
162906  #ifdef SQLITE_ENABLE_DBPAGE_VTAB
162907    if( !db->mallocFailed && rc==SQLITE_OK){
162908      rc = sqlite3DbpageRegister(db);
162909    }
162910  #endif
162911  
162912  #ifdef SQLITE_ENABLE_DBSTAT_VTAB
162913    if( !db->mallocFailed && rc==SQLITE_OK){
162914      rc = sqlite3DbstatRegister(db);
162915    }
162916  #endif
162917  
162918  #ifdef SQLITE_ENABLE_JSON1
162919    if( !db->mallocFailed && rc==SQLITE_OK){
162920      rc = sqlite3Json1Init(db);
162921    }
162922  #endif
162923  
162924  #ifdef SQLITE_ENABLE_STMTVTAB
162925    if( !db->mallocFailed && rc==SQLITE_OK){
162926      rc = sqlite3StmtVtabInit(db);
162927    }
162928  #endif
162929  
162930    /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
162931    ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
162932    ** mode.  Doing nothing at all also makes NORMAL the default.
162933    */
162934  #ifdef SQLITE_DEFAULT_LOCKING_MODE
162935    db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
162936    sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
162937                            SQLITE_DEFAULT_LOCKING_MODE);
162938  #endif
162939  
162940    if( rc==SQLITE_OK ){
162941      rc = process_branch_uri(db, "main", zOpen);
162942    }
162943  
162944    if( rc ) sqlite3Error(db, rc);
162945  
162946    /* Enable the lookaside-malloc subsystem */
162947    setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
162948                          sqlite3GlobalConfig.nLookaside);
162949  
162950    sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
162951  
162952  opendb_out:
162953    if( db ){
162954      assert( db->mutex!=0 || isThreadsafe==0
162955             || sqlite3GlobalConfig.bFullMutex==0 );
162956      sqlite3_mutex_leave(db->mutex);
162957    }
162958    rc = sqlite3_errcode(db);
162959    assert( db!=0 || rc==SQLITE_NOMEM );
162960    if( rc==SQLITE_NOMEM ){
162961      sqlite3_close(db);
162962      db = 0;
162963    }else if( rc!=SQLITE_OK ){
162964      db->magic = SQLITE_MAGIC_SICK;
162965    }
162966    *ppDb = db;
162967  #ifdef SQLITE_ENABLE_SQLLOG
162968    if( sqlite3GlobalConfig.xSqllog ){
162969      /* Opening a db handle. Fourth parameter is passed 0. */
162970      void *pArg = sqlite3GlobalConfig.pSqllogArg;
162971      sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
162972    }
162973  #endif
162974  #if defined(SQLITE_HAS_CODEC)
162975    if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
162976  #endif
162977    sqlite3_free(zOpen);
162978    return rc & 0xff;
162979  }
162980  
162981  
162982  /*
162983  ** Open a new database handle.
162984  */
162985  SQLITE_API int sqlite3_open(
162986    const char *zFilename, 
162987    sqlite3 **ppDb 
162988  ){
162989    return openDatabase(zFilename, ppDb,
162990                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
162991  }
162992  SQLITE_API int sqlite3_open_v2(
162993    const char *filename,   /* Database filename (UTF-8) */
162994    sqlite3 **ppDb,         /* OUT: SQLite db handle */
162995    int flags,              /* Flags */
162996    const char *zVfs        /* Name of VFS module to use */
162997  ){
162998    return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
162999  }
163000  
163001  #ifndef SQLITE_OMIT_UTF16
163002  /*
163003  ** Open a new database handle.
163004  */
163005  SQLITE_API int sqlite3_open16(
163006    const void *zFilename, 
163007    sqlite3 **ppDb
163008  ){
163009    char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
163010    sqlite3_value *pVal;
163011    int rc;
163012  
163013  #ifdef SQLITE_ENABLE_API_ARMOR
163014    if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
163015  #endif
163016    *ppDb = 0;
163017  #ifndef SQLITE_OMIT_AUTOINIT
163018    rc = sqlite3_initialize();
163019    if( rc ) return rc;
163020  #endif
163021    if( zFilename==0 ) zFilename = "\000\000";
163022    pVal = sqlite3ValueNew(0);
163023    sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
163024    zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
163025    if( zFilename8 ){
163026      rc = openDatabase(zFilename8, ppDb,
163027                        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
163028      assert( *ppDb || rc==SQLITE_NOMEM );
163029      if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
163030        SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
163031      }
163032    }else{
163033      rc = SQLITE_NOMEM_BKPT;
163034    }
163035    sqlite3ValueFree(pVal);
163036  
163037    return rc & 0xff;
163038  }
163039  #endif /* SQLITE_OMIT_UTF16 */
163040  
163041  /*
163042  ** Register a new collation sequence with the database handle db.
163043  */
163044  SQLITE_API int sqlite3_create_collation(
163045    sqlite3* db, 
163046    const char *zName, 
163047    int enc, 
163048    void* pCtx,
163049    int(*xCompare)(void*,int,const void*,int,const void*)
163050  ){
163051    return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
163052  }
163053  
163054  /*
163055  ** Register a new collation sequence with the database handle db.
163056  */
163057  SQLITE_API int sqlite3_create_collation_v2(
163058    sqlite3* db, 
163059    const char *zName, 
163060    int enc, 
163061    void* pCtx,
163062    int(*xCompare)(void*,int,const void*,int,const void*),
163063    void(*xDel)(void*)
163064  ){
163065    int rc;
163066  
163067  #ifdef SQLITE_ENABLE_API_ARMOR
163068    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
163069  #endif
163070    sqlite3_mutex_enter(db->mutex);
163071    assert( !db->mallocFailed );
163072    rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
163073    rc = sqlite3ApiExit(db, rc);
163074    sqlite3_mutex_leave(db->mutex);
163075    return rc;
163076  }
163077  
163078  #ifndef SQLITE_OMIT_UTF16
163079  /*
163080  ** Register a new collation sequence with the database handle db.
163081  */
163082  SQLITE_API int sqlite3_create_collation16(
163083    sqlite3* db, 
163084    const void *zName,
163085    int enc, 
163086    void* pCtx,
163087    int(*xCompare)(void*,int,const void*,int,const void*)
163088  ){
163089    int rc = SQLITE_OK;
163090    char *zName8;
163091  
163092  #ifdef SQLITE_ENABLE_API_ARMOR
163093    if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
163094  #endif
163095    sqlite3_mutex_enter(db->mutex);
163096    assert( !db->mallocFailed );
163097    zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
163098    if( zName8 ){
163099      rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
163100      sqlite3DbFree(db, zName8);
163101    }
163102    rc = sqlite3ApiExit(db, rc);
163103    sqlite3_mutex_leave(db->mutex);
163104    return rc;
163105  }
163106  #endif /* SQLITE_OMIT_UTF16 */
163107  
163108  /*
163109  ** Register a collation sequence factory callback with the database handle
163110  ** db. Replace any previously installed collation sequence factory.
163111  */
163112  SQLITE_API int sqlite3_collation_needed(
163113    sqlite3 *db, 
163114    void *pCollNeededArg, 
163115    void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
163116  ){
163117  #ifdef SQLITE_ENABLE_API_ARMOR
163118    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
163119  #endif
163120    sqlite3_mutex_enter(db->mutex);
163121    db->xCollNeeded = xCollNeeded;
163122    db->xCollNeeded16 = 0;
163123    db->pCollNeededArg = pCollNeededArg;
163124    sqlite3_mutex_leave(db->mutex);
163125    return SQLITE_OK;
163126  }
163127  
163128  #ifndef SQLITE_OMIT_UTF16
163129  /*
163130  ** Register a collation sequence factory callback with the database handle
163131  ** db. Replace any previously installed collation sequence factory.
163132  */
163133  SQLITE_API int sqlite3_collation_needed16(
163134    sqlite3 *db, 
163135    void *pCollNeededArg, 
163136    void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
163137  ){
163138  #ifdef SQLITE_ENABLE_API_ARMOR
163139    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
163140  #endif
163141    sqlite3_mutex_enter(db->mutex);
163142    db->xCollNeeded = 0;
163143    db->xCollNeeded16 = xCollNeeded16;
163144    db->pCollNeededArg = pCollNeededArg;
163145    sqlite3_mutex_leave(db->mutex);
163146    return SQLITE_OK;
163147  }
163148  #endif /* SQLITE_OMIT_UTF16 */
163149  
163150  #ifndef SQLITE_OMIT_DEPRECATED
163151  /*
163152  ** This function is now an anachronism. It used to be used to recover from a
163153  ** malloc() failure, but SQLite now does this automatically.
163154  */
163155  SQLITE_API int sqlite3_global_recover(void){
163156    return SQLITE_OK;
163157  }
163158  #endif
163159  
163160  /*
163161  ** Test to see whether or not the database connection is in autocommit
163162  ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
163163  ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
163164  ** by the next COMMIT or ROLLBACK.
163165  */
163166  SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
163167  #ifdef SQLITE_ENABLE_API_ARMOR
163168    if( !sqlite3SafetyCheckOk(db) ){
163169      (void)SQLITE_MISUSE_BKPT;
163170      return 0;
163171    }
163172  #endif
163173    return db->autoCommit;
163174  }
163175  
163176  /*
163177  ** The following routines are substitutes for constants SQLITE_CORRUPT,
163178  ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
163179  ** constants.  They serve two purposes:
163180  **
163181  **   1.  Serve as a convenient place to set a breakpoint in a debugger
163182  **       to detect when version error conditions occurs.
163183  **
163184  **   2.  Invoke sqlite3_log() to provide the source code location where
163185  **       a low-level error is first detected.
163186  */
163187  SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
163188    sqlite3_log(iErr, "%s at line %d of [%.10s]",
163189                zType, lineno, 20+sqlite3_sourceid());
163190    return iErr;
163191  }
163192  SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
163193    testcase( sqlite3GlobalConfig.xLog!=0 );
163194    return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
163195  }
163196  SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
163197    testcase( sqlite3GlobalConfig.xLog!=0 );
163198    return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
163199  }
163200  SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
163201    testcase( sqlite3GlobalConfig.xLog!=0 );
163202    return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
163203  }
163204  #ifdef SQLITE_DEBUG
163205  SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
163206    char zMsg[100];
163207    sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
163208    testcase( sqlite3GlobalConfig.xLog!=0 );
163209    return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
163210  }
163211  SQLITE_PRIVATE int sqlite3NomemError(int lineno){
163212    testcase( sqlite3GlobalConfig.xLog!=0 );
163213    return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
163214  }
163215  SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
163216    testcase( sqlite3GlobalConfig.xLog!=0 );
163217    return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
163218  }
163219  #endif
163220  
163221  #ifndef SQLITE_OMIT_DEPRECATED
163222  /*
163223  ** This is a convenience routine that makes sure that all thread-specific
163224  ** data for this thread has been deallocated.
163225  **
163226  ** SQLite no longer uses thread-specific data so this routine is now a
163227  ** no-op.  It is retained for historical compatibility.
163228  */
163229  SQLITE_API void sqlite3_thread_cleanup(void){
163230  }
163231  #endif
163232  
163233  /*
163234  ** Return meta information about a specific column of a database table.
163235  ** See comment in sqlite3.h (sqlite.h.in) for details.
163236  */
163237  SQLITE_API int sqlite3_table_column_metadata(
163238    sqlite3 *db,                /* Connection handle */
163239    const char *zDbName,        /* Database name or NULL */
163240    const char *zTableName,     /* Table name */
163241    const char *zColumnName,    /* Column name */
163242    char const **pzDataType,    /* OUTPUT: Declared data type */
163243    char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
163244    int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
163245    int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
163246    int *pAutoinc               /* OUTPUT: True if column is auto-increment */
163247  ){
163248    int rc;
163249    char *zErrMsg = 0;
163250    Table *pTab = 0;
163251    Column *pCol = 0;
163252    int iCol = 0;
163253    char const *zDataType = 0;
163254    char const *zCollSeq = 0;
163255    int notnull = 0;
163256    int primarykey = 0;
163257    int autoinc = 0;
163258  
163259  
163260  #ifdef SQLITE_ENABLE_API_ARMOR
163261    if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
163262      return SQLITE_MISUSE_BKPT;
163263    }
163264  #endif
163265  
163266    /* Ensure the database schema has been loaded */
163267    sqlite3_mutex_enter(db->mutex);
163268    sqlite3BtreeEnterAll(db);
163269    rc = sqlite3Init(db, &zErrMsg);
163270    if( SQLITE_OK!=rc ){
163271      goto error_out;
163272    }
163273  
163274    /* Locate the table in question */
163275    pTab = sqlite3FindTable(db, zTableName, zDbName);
163276    if( !pTab || pTab->pSelect ){
163277      pTab = 0;
163278      goto error_out;
163279    }
163280  
163281    /* Find the column for which info is requested */
163282    if( zColumnName==0 ){
163283      /* Query for existance of table only */
163284    }else{
163285      for(iCol=0; iCol<pTab->nCol; iCol++){
163286        pCol = &pTab->aCol[iCol];
163287        if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
163288          break;
163289        }
163290      }
163291      if( iCol==pTab->nCol ){
163292        if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
163293          iCol = pTab->iPKey;
163294          pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
163295        }else{
163296          pTab = 0;
163297          goto error_out;
163298        }
163299      }
163300    }
163301  
163302    /* The following block stores the meta information that will be returned
163303    ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
163304    ** and autoinc. At this point there are two possibilities:
163305    ** 
163306    **     1. The specified column name was rowid", "oid" or "_rowid_" 
163307    **        and there is no explicitly declared IPK column. 
163308    **
163309    **     2. The table is not a view and the column name identified an 
163310    **        explicitly declared column. Copy meta information from *pCol.
163311    */ 
163312    if( pCol ){
163313      zDataType = sqlite3ColumnType(pCol,0);
163314      zCollSeq = pCol->zColl;
163315      notnull = pCol->notNull!=0;
163316      primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
163317      autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
163318    }else{
163319      zDataType = "INTEGER";
163320      primarykey = 1;
163321    }
163322    if( !zCollSeq ){
163323      zCollSeq = sqlite3StrBINARY;
163324    }
163325  
163326  error_out:
163327    sqlite3BtreeLeaveAll(db);
163328  
163329    /* Whether the function call succeeded or failed, set the output parameters
163330    ** to whatever their local counterparts contain. If an error did occur,
163331    ** this has the effect of zeroing all output parameters.
163332    */
163333    if( pzDataType ) *pzDataType = zDataType;
163334    if( pzCollSeq ) *pzCollSeq = zCollSeq;
163335    if( pNotNull ) *pNotNull = notnull;
163336    if( pPrimaryKey ) *pPrimaryKey = primarykey;
163337    if( pAutoinc ) *pAutoinc = autoinc;
163338  
163339    if( SQLITE_OK==rc && !pTab ){
163340      sqlite3DbFree(db, zErrMsg);
163341      zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
163342          zColumnName);
163343      rc = SQLITE_ERROR;
163344    }
163345    sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
163346    sqlite3DbFree(db, zErrMsg);
163347    rc = sqlite3ApiExit(db, rc);
163348    sqlite3_mutex_leave(db->mutex);
163349    return rc;
163350  }
163351  
163352  /*
163353  ** Sleep for a little while.  Return the amount of time slept.
163354  */
163355  SQLITE_API int sqlite3_sleep(int ms){
163356    sqlite3_vfs *pVfs;
163357    int rc;
163358    pVfs = sqlite3_vfs_find(0);
163359    if( pVfs==0 ) return 0;
163360  
163361    /* This function works in milliseconds, but the underlying OsSleep() 
163362    ** API uses microseconds. Hence the 1000's.
163363    */
163364    rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
163365    return rc;
163366  }
163367  
163368  /*
163369  ** Enable or disable the extended result codes.
163370  */
163371  SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
163372  #ifdef SQLITE_ENABLE_API_ARMOR
163373    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
163374  #endif
163375    sqlite3_mutex_enter(db->mutex);
163376    db->errMask = onoff ? 0xffffffff : 0xff;
163377    sqlite3_mutex_leave(db->mutex);
163378    return SQLITE_OK;
163379  }
163380  
163381  /*
163382  ** Invoke the xFileControl method on a particular database.
163383  */
163384  SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
163385    int rc = SQLITE_ERROR;
163386    Btree *pBtree;
163387  
163388  #ifdef SQLITE_ENABLE_API_ARMOR
163389    if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
163390  #endif
163391    sqlite3_mutex_enter(db->mutex);
163392    pBtree = sqlite3DbNameToBtree(db, zDbName);
163393    if( pBtree ){
163394      Pager *pPager;
163395      sqlite3_file *fd;
163396      sqlite3BtreeEnter(pBtree);
163397      pPager = sqlite3BtreePager(pBtree);
163398      assert( pPager!=0 );
163399      fd = sqlite3PagerFile(pPager);
163400      assert( fd!=0 );
163401      if( op==SQLITE_FCNTL_FILE_POINTER ){
163402        *(sqlite3_file**)pArg = fd;
163403        rc = SQLITE_OK;
163404      }else if( op==SQLITE_FCNTL_VFS_POINTER ){
163405        *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
163406        rc = SQLITE_OK;
163407      }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
163408        *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
163409        rc = SQLITE_OK;
163410      }else if( op==SQLITE_FCNTL_DATA_VERSION ){
163411        *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
163412        rc = SQLITE_OK;
163413      }else{
163414        rc = sqlite3OsFileControl(fd, op, pArg);
163415      }
163416      sqlite3BtreeLeave(pBtree);
163417    }
163418    sqlite3_mutex_leave(db->mutex);
163419    return rc;
163420  }
163421  
163422  /*
163423  ** Interface to the testing logic.
163424  */
163425  SQLITE_API int sqlite3_test_control(int op, ...){
163426    int rc = 0;
163427  #ifdef SQLITE_UNTESTABLE
163428    UNUSED_PARAMETER(op);
163429  #else
163430    va_list ap;
163431    va_start(ap, op);
163432    switch( op ){
163433  
163434      /*
163435      ** Save the current state of the PRNG.
163436      */
163437      case SQLITE_TESTCTRL_PRNG_SAVE: {
163438        sqlite3PrngSaveState();
163439        break;
163440      }
163441  
163442      /*
163443      ** Restore the state of the PRNG to the last state saved using
163444      ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
163445      ** this verb acts like PRNG_RESET.
163446      */
163447      case SQLITE_TESTCTRL_PRNG_RESTORE: {
163448        sqlite3PrngRestoreState();
163449        break;
163450      }
163451  
163452      /*
163453      ** Reset the PRNG back to its uninitialized state.  The next call
163454      ** to sqlite3_randomness() will reseed the PRNG using a single call
163455      ** to the xRandomness method of the default VFS.
163456      */
163457      case SQLITE_TESTCTRL_PRNG_RESET: {
163458        sqlite3_randomness(0,0);
163459        break;
163460      }
163461  
163462      /*
163463      **  sqlite3_test_control(BITVEC_TEST, size, program)
163464      **
163465      ** Run a test against a Bitvec object of size.  The program argument
163466      ** is an array of integers that defines the test.  Return -1 on a
163467      ** memory allocation error, 0 on success, or non-zero for an error.
163468      ** See the sqlite3BitvecBuiltinTest() for additional information.
163469      */
163470      case SQLITE_TESTCTRL_BITVEC_TEST: {
163471        int sz = va_arg(ap, int);
163472        int *aProg = va_arg(ap, int*);
163473        rc = sqlite3BitvecBuiltinTest(sz, aProg);
163474        break;
163475      }
163476  
163477      /*
163478      **  sqlite3_test_control(FAULT_INSTALL, xCallback)
163479      **
163480      ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
163481      ** if xCallback is not NULL.
163482      **
163483      ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
163484      ** is called immediately after installing the new callback and the return
163485      ** value from sqlite3FaultSim(0) becomes the return from
163486      ** sqlite3_test_control().
163487      */
163488      case SQLITE_TESTCTRL_FAULT_INSTALL: {
163489        /* MSVC is picky about pulling func ptrs from va lists.
163490        ** http://support.microsoft.com/kb/47961
163491        ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
163492        */
163493        typedef int(*TESTCALLBACKFUNC_t)(int);
163494        sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
163495        rc = sqlite3FaultSim(0);
163496        break;
163497      }
163498  
163499      /*
163500      **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
163501      **
163502      ** Register hooks to call to indicate which malloc() failures 
163503      ** are benign.
163504      */
163505      case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
163506        typedef void (*void_function)(void);
163507        void_function xBenignBegin;
163508        void_function xBenignEnd;
163509        xBenignBegin = va_arg(ap, void_function);
163510        xBenignEnd = va_arg(ap, void_function);
163511        sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
163512        break;
163513      }
163514  
163515      /*
163516      **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
163517      **
163518      ** Set the PENDING byte to the value in the argument, if X>0.
163519      ** Make no changes if X==0.  Return the value of the pending byte
163520      ** as it existing before this routine was called.
163521      **
163522      ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
163523      ** an incompatible database file format.  Changing the PENDING byte
163524      ** while any database connection is open results in undefined and
163525      ** deleterious behavior.
163526      */
163527      case SQLITE_TESTCTRL_PENDING_BYTE: {
163528        rc = PENDING_BYTE;
163529  #ifndef SQLITE_OMIT_WSD
163530        {
163531          unsigned int newVal = va_arg(ap, unsigned int);
163532          if( newVal ) sqlite3PendingByte = newVal;
163533        }
163534  #endif
163535        break;
163536      }
163537  
163538      /*
163539      **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
163540      **
163541      ** This action provides a run-time test to see whether or not
163542      ** assert() was enabled at compile-time.  If X is true and assert()
163543      ** is enabled, then the return value is true.  If X is true and
163544      ** assert() is disabled, then the return value is zero.  If X is
163545      ** false and assert() is enabled, then the assertion fires and the
163546      ** process aborts.  If X is false and assert() is disabled, then the
163547      ** return value is zero.
163548      */
163549      case SQLITE_TESTCTRL_ASSERT: {
163550        volatile int x = 0;
163551        assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
163552        rc = x;
163553        break;
163554      }
163555  
163556  
163557      /*
163558      **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
163559      **
163560      ** This action provides a run-time test to see how the ALWAYS and
163561      ** NEVER macros were defined at compile-time.
163562      **
163563      ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
163564      **
163565      ** The recommended test is X==2.  If the return value is 2, that means
163566      ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
163567      ** default setting.  If the return value is 1, then ALWAYS() is either
163568      ** hard-coded to true or else it asserts if its argument is false.
163569      ** The first behavior (hard-coded to true) is the case if
163570      ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
163571      ** behavior (assert if the argument to ALWAYS() is false) is the case if
163572      ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
163573      **
163574      ** The run-time test procedure might look something like this:
163575      **
163576      **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
163577      **      // ALWAYS() and NEVER() are no-op pass-through macros
163578      **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
163579      **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
163580      **    }else{
163581      **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
163582      **    }
163583      */
163584      case SQLITE_TESTCTRL_ALWAYS: {
163585        int x = va_arg(ap,int);
163586        rc = x ? ALWAYS(x) : 0;
163587        break;
163588      }
163589  
163590      /*
163591      **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
163592      **
163593      ** The integer returned reveals the byte-order of the computer on which
163594      ** SQLite is running:
163595      **
163596      **       1     big-endian,    determined at run-time
163597      **      10     little-endian, determined at run-time
163598      **  432101     big-endian,    determined at compile-time
163599      **  123410     little-endian, determined at compile-time
163600      */ 
163601      case SQLITE_TESTCTRL_BYTEORDER: {
163602        rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
163603        break;
163604      }
163605  
163606      /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
163607      **
163608      ** Set the nReserve size to N for the main database on the database
163609      ** connection db.
163610      */
163611      case SQLITE_TESTCTRL_RESERVE: {
163612        sqlite3 *db = va_arg(ap, sqlite3*);
163613        int x = va_arg(ap,int);
163614        sqlite3_mutex_enter(db->mutex);
163615        sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
163616        sqlite3_mutex_leave(db->mutex);
163617        break;
163618      }
163619  
163620      /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
163621      **
163622      ** Enable or disable various optimizations for testing purposes.  The 
163623      ** argument N is a bitmask of optimizations to be disabled.  For normal
163624      ** operation N should be 0.  The idea is that a test program (like the
163625      ** SQL Logic Test or SLT test module) can run the same SQL multiple times
163626      ** with various optimizations disabled to verify that the same answer
163627      ** is obtained in every case.
163628      */
163629      case SQLITE_TESTCTRL_OPTIMIZATIONS: {
163630        sqlite3 *db = va_arg(ap, sqlite3*);
163631        db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
163632        break;
163633      }
163634  
163635      /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
163636      **
163637      ** If parameter onoff is non-zero, subsequent calls to localtime()
163638      ** and its variants fail. If onoff is zero, undo this setting.
163639      */
163640      case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
163641        sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
163642        break;
163643      }
163644  
163645      /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
163646      **
163647      ** If parameter onoff is non-zero, internal-use-only SQL functions
163648      ** are visible to ordinary SQL.  This is useful for testing but is
163649      ** unsafe because invalid parameters to those internal-use-only functions
163650      ** can result in crashes or segfaults.
163651      */
163652      case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
163653        sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
163654        break;
163655      }
163656  
163657      /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
163658      **
163659      ** Set or clear a flag that indicates that the database file is always well-
163660      ** formed and never corrupt.  This flag is clear by default, indicating that
163661      ** database files might have arbitrary corruption.  Setting the flag during
163662      ** testing causes certain assert() statements in the code to be activated
163663      ** that demonstrat invariants on well-formed database files.
163664      */
163665      case SQLITE_TESTCTRL_NEVER_CORRUPT: {
163666        sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
163667        break;
163668      }
163669  
163670      /* Set the threshold at which OP_Once counters reset back to zero.
163671      ** By default this is 0x7ffffffe (over 2 billion), but that value is
163672      ** too big to test in a reasonable amount of time, so this control is
163673      ** provided to set a small and easily reachable reset value.
163674      */
163675      case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
163676        sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
163677        break;
163678      }
163679  
163680      /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
163681      **
163682      ** Set the VDBE coverage callback function to xCallback with context 
163683      ** pointer ptr.
163684      */
163685      case SQLITE_TESTCTRL_VDBE_COVERAGE: {
163686  #ifdef SQLITE_VDBE_COVERAGE
163687        typedef void (*branch_callback)(void*,unsigned int,
163688                                        unsigned char,unsigned char);
163689        sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
163690        sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
163691  #endif
163692        break;
163693      }
163694  
163695      /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
163696      case SQLITE_TESTCTRL_SORTER_MMAP: {
163697        sqlite3 *db = va_arg(ap, sqlite3*);
163698        db->nMaxSorterMmap = va_arg(ap, int);
163699        break;
163700      }
163701  
163702      /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
163703      **
163704      ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
163705      ** not.
163706      */
163707      case SQLITE_TESTCTRL_ISINIT: {
163708        if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
163709        break;
163710      }
163711  
163712      /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
163713      **
163714      ** This test control is used to create imposter tables.  "db" is a pointer
163715      ** to the database connection.  dbName is the database name (ex: "main" or
163716      ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
163717      ** or off.  "tnum" is the root page of the b-tree to which the imposter
163718      ** table should connect.
163719      **
163720      ** Enable imposter mode only when the schema has already been parsed.  Then
163721      ** run a single CREATE TABLE statement to construct the imposter table in
163722      ** the parsed schema.  Then turn imposter mode back off again.
163723      **
163724      ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
163725      ** the schema to be reparsed the next time it is needed.  This has the
163726      ** effect of erasing all imposter tables.
163727      */
163728      case SQLITE_TESTCTRL_IMPOSTER: {
163729        sqlite3 *db = va_arg(ap, sqlite3*);
163730        sqlite3_mutex_enter(db->mutex);
163731        db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
163732        db->init.busy = db->init.imposterTable = va_arg(ap,int);
163733        db->init.newTnum = va_arg(ap,int);
163734        if( db->init.busy==0 && db->init.newTnum>0 ){
163735          sqlite3ResetAllSchemasOfConnection(db);
163736        }
163737        sqlite3_mutex_leave(db->mutex);
163738        break;
163739      }
163740  
163741  #if defined(YYCOVERAGE)
163742      /*  sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
163743      **
163744      ** This test control (only available when SQLite is compiled with
163745      ** -DYYCOVERAGE) writes a report onto "out" that shows all
163746      ** state/lookahead combinations in the parser state machine
163747      ** which are never exercised.  If any state is missed, make the
163748      ** return code SQLITE_ERROR.
163749      */
163750      case SQLITE_TESTCTRL_PARSER_COVERAGE: {
163751        FILE *out = va_arg(ap, FILE*);
163752        if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
163753        break;
163754      }
163755  #endif /* defined(YYCOVERAGE) */
163756    }
163757    va_end(ap);
163758  #endif /* SQLITE_UNTESTABLE */
163759    return rc;
163760  }
163761  
163762  /*
163763  ** This is a utility routine, useful to VFS implementations, that checks
163764  ** to see if a database file was a URI that contained a specific query 
163765  ** parameter, and if so obtains the value of the query parameter.
163766  **
163767  ** The zFilename argument is the filename pointer passed into the xOpen()
163768  ** method of a VFS implementation.  The zParam argument is the name of the
163769  ** query parameter we seek.  This routine returns the value of the zParam
163770  ** parameter if it exists.  If the parameter does not exist, this routine
163771  ** returns a NULL pointer.
163772  */
163773  SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
163774    if( zFilename==0 || zParam==0 ) return 0;
163775    zFilename += sqlite3Strlen30(zFilename) + 1;
163776    while( zFilename[0] ){
163777      int x = strcmp(zFilename, zParam);
163778      zFilename += sqlite3Strlen30(zFilename) + 1;
163779      if( x==0 ) return zFilename;
163780      zFilename += sqlite3Strlen30(zFilename) + 1;
163781    }
163782    return 0;
163783  }
163784  
163785  /*
163786  ** Return a boolean value for a query parameter.
163787  */
163788  SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
163789    const char *z = sqlite3_uri_parameter(zFilename, zParam);
163790    bDflt = bDflt!=0;
163791    return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
163792  }
163793  
163794  /*
163795  ** Return a 64-bit integer value for a query parameter.
163796  */
163797  SQLITE_API sqlite3_int64 sqlite3_uri_int64(
163798    const char *zFilename,    /* Filename as passed to xOpen */
163799    const char *zParam,       /* URI parameter sought */
163800    sqlite3_int64 bDflt       /* return if parameter is missing */
163801  ){
163802    const char *z = sqlite3_uri_parameter(zFilename, zParam);
163803    sqlite3_int64 v;
163804    if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
163805      bDflt = v;
163806    }
163807    return bDflt;
163808  }
163809  
163810  /*
163811  ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
163812  */
163813  SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
163814    int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
163815    return iDb<0 ? 0 : db->aDb[iDb].pBt;
163816  }
163817  
163818  /*
163819  ** Return the filename of the database associated with a database
163820  ** connection.
163821  */
163822  SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
163823    Btree *pBt;
163824  #ifdef SQLITE_ENABLE_API_ARMOR
163825    if( !sqlite3SafetyCheckOk(db) ){
163826      (void)SQLITE_MISUSE_BKPT;
163827      return 0;
163828    }
163829  #endif
163830    pBt = sqlite3DbNameToBtree(db, zDbName);
163831    return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
163832  }
163833  
163834  /*
163835  ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
163836  ** no such database exists.
163837  */
163838  SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
163839    Btree *pBt;
163840  #ifdef SQLITE_ENABLE_API_ARMOR
163841    if( !sqlite3SafetyCheckOk(db) ){
163842      (void)SQLITE_MISUSE_BKPT;
163843      return -1;
163844    }
163845  #endif
163846    pBt = sqlite3DbNameToBtree(db, zDbName);
163847    return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
163848  }
163849  
163850  #ifdef SQLITE_ENABLE_SNAPSHOT
163851  /*
163852  ** Obtain a snapshot handle for the snapshot of database zDb currently 
163853  ** being read by handle db.
163854  */
163855  SQLITE_API int sqlite3_snapshot_get(
163856    sqlite3 *db, 
163857    const char *zDb,
163858    sqlite3_snapshot **ppSnapshot
163859  ){
163860    int rc = SQLITE_ERROR;
163861  #ifndef SQLITE_OMIT_WAL
163862  
163863  #ifdef SQLITE_ENABLE_API_ARMOR
163864    if( !sqlite3SafetyCheckOk(db) ){
163865      return SQLITE_MISUSE_BKPT;
163866    }
163867  #endif
163868    sqlite3_mutex_enter(db->mutex);
163869  
163870    if( db->autoCommit==0 ){
163871      int iDb = sqlite3FindDbName(db, zDb);
163872      if( iDb==0 || iDb>1 ){
163873        Btree *pBt = db->aDb[iDb].pBt;
163874        if( 0==sqlite3BtreeIsInTrans(pBt) ){
163875          rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
163876          if( rc==SQLITE_OK ){
163877            rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
163878          }
163879        }
163880      }
163881    }
163882  
163883    sqlite3_mutex_leave(db->mutex);
163884  #endif   /* SQLITE_OMIT_WAL */
163885    return rc;
163886  }
163887  
163888  /*
163889  ** Open a read-transaction on the snapshot idendified by pSnapshot.
163890  */
163891  SQLITE_API int sqlite3_snapshot_open(
163892    sqlite3 *db, 
163893    const char *zDb, 
163894    sqlite3_snapshot *pSnapshot
163895  ){
163896    int rc = SQLITE_ERROR;
163897  #ifndef SQLITE_OMIT_WAL
163898  
163899  #ifdef SQLITE_ENABLE_API_ARMOR
163900    if( !sqlite3SafetyCheckOk(db) ){
163901      return SQLITE_MISUSE_BKPT;
163902    }
163903  #endif
163904    sqlite3_mutex_enter(db->mutex);
163905    if( db->autoCommit==0 ){
163906      int iDb;
163907      iDb = sqlite3FindDbName(db, zDb);
163908      if( iDb==0 || iDb>1 ){
163909        Btree *pBt = db->aDb[iDb].pBt;
163910        if( sqlite3BtreeIsInTrans(pBt)==0 ){
163911          Pager *pPager = sqlite3BtreePager(pBt);
163912          int bUnlock = 0;
163913          if( sqlite3BtreeIsInReadTrans(pBt) ){
163914            if( db->nVdbeActive==0 ){
163915              rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
163916              if( rc==SQLITE_OK ){
163917                bUnlock = 1;
163918                rc = sqlite3BtreeCommit(pBt);
163919              }
163920            }
163921          }else{
163922            rc = SQLITE_OK;
163923          }
163924          if( rc==SQLITE_OK ){
163925            rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
163926          }
163927          if( rc==SQLITE_OK ){
163928            rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
163929            sqlite3PagerSnapshotOpen(pPager, 0);
163930          }
163931          if( bUnlock ){
163932            sqlite3PagerSnapshotUnlock(pPager);
163933          }
163934        }
163935      }
163936    }
163937  
163938    sqlite3_mutex_leave(db->mutex);
163939  #endif   /* SQLITE_OMIT_WAL */
163940    return rc;
163941  }
163942  
163943  /*
163944  ** Recover as many snapshots as possible from the wal file associated with
163945  ** schema zDb of database db.
163946  */
163947  SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
163948    int rc = SQLITE_ERROR;
163949    int iDb;
163950  #ifndef SQLITE_OMIT_WAL
163951  
163952  #ifdef SQLITE_ENABLE_API_ARMOR
163953    if( !sqlite3SafetyCheckOk(db) ){
163954      return SQLITE_MISUSE_BKPT;
163955    }
163956  #endif
163957  
163958    sqlite3_mutex_enter(db->mutex);
163959    iDb = sqlite3FindDbName(db, zDb);
163960    if( iDb==0 || iDb>1 ){
163961      Btree *pBt = db->aDb[iDb].pBt;
163962      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
163963        rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
163964        if( rc==SQLITE_OK ){
163965          rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
163966          sqlite3BtreeCommit(pBt);
163967        }
163968      }
163969    }
163970    sqlite3_mutex_leave(db->mutex);
163971  #endif   /* SQLITE_OMIT_WAL */
163972    return rc;
163973  }
163974  
163975  /*
163976  ** Free a snapshot handle obtained from sqlite3_snapshot_get().
163977  */
163978  SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
163979    sqlite3_free(pSnapshot);
163980  }
163981  #endif /* SQLITE_ENABLE_SNAPSHOT */
163982  
163983  #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
163984  /*
163985  ** Given the name of a compile-time option, return true if that option
163986  ** was used and false if not.
163987  **
163988  ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
163989  ** is not required for a match.
163990  */
163991  SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
163992    int i, n;
163993    int nOpt;
163994    const char **azCompileOpt;
163995   
163996  #if SQLITE_ENABLE_API_ARMOR
163997    if( zOptName==0 ){
163998      (void)SQLITE_MISUSE_BKPT;
163999      return 0;
164000    }
164001  #endif
164002  
164003    azCompileOpt = sqlite3CompileOptions(&nOpt);
164004  
164005    if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
164006    n = sqlite3Strlen30(zOptName);
164007  
164008    /* Since nOpt is normally in single digits, a linear search is 
164009    ** adequate. No need for a binary search. */
164010    for(i=0; i<nOpt; i++){
164011      if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
164012       && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
164013      ){
164014        return 1;
164015      }
164016    }
164017    return 0;
164018  }
164019  
164020  /*
164021  ** Return the N-th compile-time option string.  If N is out of range,
164022  ** return a NULL pointer.
164023  */
164024  SQLITE_API const char *sqlite3_compileoption_get(int N){
164025    int nOpt;
164026    const char **azCompileOpt;
164027    azCompileOpt = sqlite3CompileOptions(&nOpt);
164028    if( N>=0 && N<nOpt ){
164029      return azCompileOpt[N];
164030    }
164031    return 0;
164032  }
164033  #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
164034  
164035  /************** End of main.c ************************************************/
164036  /************** Begin file notify.c ******************************************/
164037  /*
164038  ** 2009 March 3
164039  **
164040  ** The author disclaims copyright to this source code.  In place of
164041  ** a legal notice, here is a blessing:
164042  **
164043  **    May you do good and not evil.
164044  **    May you find forgiveness for yourself and forgive others.
164045  **    May you share freely, never taking more than you give.
164046  **
164047  *************************************************************************
164048  **
164049  ** This file contains the implementation of the sqlite3_unlock_notify()
164050  ** API method and its associated functionality.
164051  */
164052  /* #include "sqliteInt.h" */
164053  /* #include "btreeInt.h" */
164054  
164055  /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
164056  #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
164057  
164058  /*
164059  ** Public interfaces:
164060  **
164061  **   sqlite3ConnectionBlocked()
164062  **   sqlite3ConnectionUnlocked()
164063  **   sqlite3ConnectionClosed()
164064  **   sqlite3_unlock_notify()
164065  */
164066  
164067  #define assertMutexHeld() \
164068    assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
164069  
164070  /*
164071  ** Head of a linked list of all sqlite3 objects created by this process
164072  ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
164073  ** is not NULL. This variable may only accessed while the STATIC_MASTER
164074  ** mutex is held.
164075  */
164076  static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
164077  
164078  #ifndef NDEBUG
164079  /*
164080  ** This function is a complex assert() that verifies the following 
164081  ** properties of the blocked connections list:
164082  **
164083  **   1) Each entry in the list has a non-NULL value for either 
164084  **      pUnlockConnection or pBlockingConnection, or both.
164085  **
164086  **   2) All entries in the list that share a common value for 
164087  **      xUnlockNotify are grouped together.
164088  **
164089  **   3) If the argument db is not NULL, then none of the entries in the
164090  **      blocked connections list have pUnlockConnection or pBlockingConnection
164091  **      set to db. This is used when closing connection db.
164092  */
164093  static void checkListProperties(sqlite3 *db){
164094    sqlite3 *p;
164095    for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
164096      int seen = 0;
164097      sqlite3 *p2;
164098  
164099      /* Verify property (1) */
164100      assert( p->pUnlockConnection || p->pBlockingConnection );
164101  
164102      /* Verify property (2) */
164103      for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
164104        if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
164105        assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
164106        assert( db==0 || p->pUnlockConnection!=db );
164107        assert( db==0 || p->pBlockingConnection!=db );
164108      }
164109    }
164110  }
164111  #else
164112  # define checkListProperties(x)
164113  #endif
164114  
164115  /*
164116  ** Remove connection db from the blocked connections list. If connection
164117  ** db is not currently a part of the list, this function is a no-op.
164118  */
164119  static void removeFromBlockedList(sqlite3 *db){
164120    sqlite3 **pp;
164121    assertMutexHeld();
164122    for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
164123      if( *pp==db ){
164124        *pp = (*pp)->pNextBlocked;
164125        break;
164126      }
164127    }
164128  }
164129  
164130  /*
164131  ** Add connection db to the blocked connections list. It is assumed
164132  ** that it is not already a part of the list.
164133  */
164134  static void addToBlockedList(sqlite3 *db){
164135    sqlite3 **pp;
164136    assertMutexHeld();
164137    for(
164138      pp=&sqlite3BlockedList; 
164139      *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
164140      pp=&(*pp)->pNextBlocked
164141    );
164142    db->pNextBlocked = *pp;
164143    *pp = db;
164144  }
164145  
164146  /*
164147  ** Obtain the STATIC_MASTER mutex.
164148  */
164149  static void enterMutex(void){
164150    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
164151    checkListProperties(0);
164152  }
164153  
164154  /*
164155  ** Release the STATIC_MASTER mutex.
164156  */
164157  static void leaveMutex(void){
164158    assertMutexHeld();
164159    checkListProperties(0);
164160    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
164161  }
164162  
164163  /*
164164  ** Register an unlock-notify callback.
164165  **
164166  ** This is called after connection "db" has attempted some operation
164167  ** but has received an SQLITE_LOCKED error because another connection
164168  ** (call it pOther) in the same process was busy using the same shared
164169  ** cache.  pOther is found by looking at db->pBlockingConnection.
164170  **
164171  ** If there is no blocking connection, the callback is invoked immediately,
164172  ** before this routine returns.
164173  **
164174  ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
164175  ** a deadlock.
164176  **
164177  ** Otherwise, make arrangements to invoke xNotify when pOther drops
164178  ** its locks.
164179  **
164180  ** Each call to this routine overrides any prior callbacks registered
164181  ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
164182  ** cancelled.
164183  */
164184  SQLITE_API int sqlite3_unlock_notify(
164185    sqlite3 *db,
164186    void (*xNotify)(void **, int),
164187    void *pArg
164188  ){
164189    int rc = SQLITE_OK;
164190  
164191    sqlite3_mutex_enter(db->mutex);
164192    enterMutex();
164193  
164194    if( xNotify==0 ){
164195      removeFromBlockedList(db);
164196      db->pBlockingConnection = 0;
164197      db->pUnlockConnection = 0;
164198      db->xUnlockNotify = 0;
164199      db->pUnlockArg = 0;
164200    }else if( 0==db->pBlockingConnection ){
164201      /* The blocking transaction has been concluded. Or there never was a 
164202      ** blocking transaction. In either case, invoke the notify callback
164203      ** immediately. 
164204      */
164205      xNotify(&pArg, 1);
164206    }else{
164207      sqlite3 *p;
164208  
164209      for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
164210      if( p ){
164211        rc = SQLITE_LOCKED;              /* Deadlock detected. */
164212      }else{
164213        db->pUnlockConnection = db->pBlockingConnection;
164214        db->xUnlockNotify = xNotify;
164215        db->pUnlockArg = pArg;
164216        removeFromBlockedList(db);
164217        addToBlockedList(db);
164218      }
164219    }
164220  
164221    leaveMutex();
164222    assert( !db->mallocFailed );
164223    sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
164224    sqlite3_mutex_leave(db->mutex);
164225    return rc;
164226  }
164227  
164228  /*
164229  ** This function is called while stepping or preparing a statement 
164230  ** associated with connection db. The operation will return SQLITE_LOCKED
164231  ** to the user because it requires a lock that will not be available
164232  ** until connection pBlocker concludes its current transaction.
164233  */
164234  SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
164235    enterMutex();
164236    if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
164237      addToBlockedList(db);
164238    }
164239    db->pBlockingConnection = pBlocker;
164240    leaveMutex();
164241  }
164242  
164243  /*
164244  ** This function is called when
164245  ** the transaction opened by database db has just finished. Locks held 
164246  ** by database connection db have been released.
164247  **
164248  ** This function loops through each entry in the blocked connections
164249  ** list and does the following:
164250  **
164251  **   1) If the sqlite3.pBlockingConnection member of a list entry is
164252  **      set to db, then set pBlockingConnection=0.
164253  **
164254  **   2) If the sqlite3.pUnlockConnection member of a list entry is
164255  **      set to db, then invoke the configured unlock-notify callback and
164256  **      set pUnlockConnection=0.
164257  **
164258  **   3) If the two steps above mean that pBlockingConnection==0 and
164259  **      pUnlockConnection==0, remove the entry from the blocked connections
164260  **      list.
164261  */
164262  SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
164263    void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
164264    int nArg = 0;                            /* Number of entries in aArg[] */
164265    sqlite3 **pp;                            /* Iterator variable */
164266    void **aArg;               /* Arguments to the unlock callback */
164267    void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
164268    void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
164269  
164270    aArg = aStatic;
164271    enterMutex();         /* Enter STATIC_MASTER mutex */
164272  
164273    /* This loop runs once for each entry in the blocked-connections list. */
164274    for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
164275      sqlite3 *p = *pp;
164276  
164277      /* Step 1. */
164278      if( p->pBlockingConnection==db ){
164279        p->pBlockingConnection = 0;
164280      }
164281  
164282      /* Step 2. */
164283      if( p->pUnlockConnection==db ){
164284        assert( p->xUnlockNotify );
164285        if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
164286          xUnlockNotify(aArg, nArg);
164287          nArg = 0;
164288        }
164289  
164290        sqlite3BeginBenignMalloc();
164291        assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
164292        assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
164293        if( (!aDyn && nArg==(int)ArraySize(aStatic))
164294         || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
164295        ){
164296          /* The aArg[] array needs to grow. */
164297          void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
164298          if( pNew ){
164299            memcpy(pNew, aArg, nArg*sizeof(void *));
164300            sqlite3_free(aDyn);
164301            aDyn = aArg = pNew;
164302          }else{
164303            /* This occurs when the array of context pointers that need to
164304            ** be passed to the unlock-notify callback is larger than the
164305            ** aStatic[] array allocated on the stack and the attempt to 
164306            ** allocate a larger array from the heap has failed.
164307            **
164308            ** This is a difficult situation to handle. Returning an error
164309            ** code to the caller is insufficient, as even if an error code
164310            ** is returned the transaction on connection db will still be
164311            ** closed and the unlock-notify callbacks on blocked connections
164312            ** will go unissued. This might cause the application to wait
164313            ** indefinitely for an unlock-notify callback that will never 
164314            ** arrive.
164315            **
164316            ** Instead, invoke the unlock-notify callback with the context
164317            ** array already accumulated. We can then clear the array and
164318            ** begin accumulating any further context pointers without 
164319            ** requiring any dynamic allocation. This is sub-optimal because
164320            ** it means that instead of one callback with a large array of
164321            ** context pointers the application will receive two or more
164322            ** callbacks with smaller arrays of context pointers, which will
164323            ** reduce the applications ability to prioritize multiple 
164324            ** connections. But it is the best that can be done under the
164325            ** circumstances.
164326            */
164327            xUnlockNotify(aArg, nArg);
164328            nArg = 0;
164329          }
164330        }
164331        sqlite3EndBenignMalloc();
164332  
164333        aArg[nArg++] = p->pUnlockArg;
164334        xUnlockNotify = p->xUnlockNotify;
164335        p->pUnlockConnection = 0;
164336        p->xUnlockNotify = 0;
164337        p->pUnlockArg = 0;
164338      }
164339  
164340      /* Step 3. */
164341      if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
164342        /* Remove connection p from the blocked connections list. */
164343        *pp = p->pNextBlocked;
164344        p->pNextBlocked = 0;
164345      }else{
164346        pp = &p->pNextBlocked;
164347      }
164348    }
164349  
164350    if( nArg!=0 ){
164351      xUnlockNotify(aArg, nArg);
164352    }
164353    sqlite3_free(aDyn);
164354    leaveMutex();         /* Leave STATIC_MASTER mutex */
164355  }
164356  
164357  /*
164358  ** This is called when the database connection passed as an argument is 
164359  ** being closed. The connection is removed from the blocked list.
164360  */
164361  SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
164362    sqlite3ConnectionUnlocked(db);
164363    enterMutex();
164364    removeFromBlockedList(db);
164365    checkListProperties(db);
164366    leaveMutex();
164367  }
164368  #endif
164369  
164370  /************** End of notify.c **********************************************/
164371  /************** Begin file fts3.c ********************************************/
164372  /*
164373  ** 2006 Oct 10
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  ** This is an SQLite module implementing full-text search.
164385  */
164386  
164387  /*
164388  ** The code in this file is only compiled if:
164389  **
164390  **     * The FTS3 module is being built as an extension
164391  **       (in which case SQLITE_CORE is not defined), or
164392  **
164393  **     * The FTS3 module is being built into the core of
164394  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
164395  */
164396  
164397  /* The full-text index is stored in a series of b+tree (-like)
164398  ** structures called segments which map terms to doclists.  The
164399  ** structures are like b+trees in layout, but are constructed from the
164400  ** bottom up in optimal fashion and are not updatable.  Since trees
164401  ** are built from the bottom up, things will be described from the
164402  ** bottom up.
164403  **
164404  **
164405  **** Varints ****
164406  ** The basic unit of encoding is a variable-length integer called a
164407  ** varint.  We encode variable-length integers in little-endian order
164408  ** using seven bits * per byte as follows:
164409  **
164410  ** KEY:
164411  **         A = 0xxxxxxx    7 bits of data and one flag bit
164412  **         B = 1xxxxxxx    7 bits of data and one flag bit
164413  **
164414  **  7 bits - A
164415  ** 14 bits - BA
164416  ** 21 bits - BBA
164417  ** and so on.
164418  **
164419  ** This is similar in concept to how sqlite encodes "varints" but
164420  ** the encoding is not the same.  SQLite varints are big-endian
164421  ** are are limited to 9 bytes in length whereas FTS3 varints are
164422  ** little-endian and can be up to 10 bytes in length (in theory).
164423  **
164424  ** Example encodings:
164425  **
164426  **     1:    0x01
164427  **   127:    0x7f
164428  **   128:    0x81 0x00
164429  **
164430  **
164431  **** Document lists ****
164432  ** A doclist (document list) holds a docid-sorted list of hits for a
164433  ** given term.  Doclists hold docids and associated token positions.
164434  ** A docid is the unique integer identifier for a single document.
164435  ** A position is the index of a word within the document.  The first 
164436  ** word of the document has a position of 0.
164437  **
164438  ** FTS3 used to optionally store character offsets using a compile-time
164439  ** option.  But that functionality is no longer supported.
164440  **
164441  ** A doclist is stored like this:
164442  **
164443  ** array {
164444  **   varint docid;          (delta from previous doclist)
164445  **   array {                (position list for column 0)
164446  **     varint position;     (2 more than the delta from previous position)
164447  **   }
164448  **   array {
164449  **     varint POS_COLUMN;   (marks start of position list for new column)
164450  **     varint column;       (index of new column)
164451  **     array {
164452  **       varint position;   (2 more than the delta from previous position)
164453  **     }
164454  **   }
164455  **   varint POS_END;        (marks end of positions for this document.
164456  ** }
164457  **
164458  ** Here, array { X } means zero or more occurrences of X, adjacent in
164459  ** memory.  A "position" is an index of a token in the token stream
164460  ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
164461  ** in the same logical place as the position element, and act as sentinals
164462  ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
164463  ** The positions numbers are not stored literally but rather as two more
164464  ** than the difference from the prior position, or the just the position plus
164465  ** 2 for the first position.  Example:
164466  **
164467  **   label:       A B C D E  F  G H   I  J K
164468  **   value:     123 5 9 1 1 14 35 0 234 72 0
164469  **
164470  ** The 123 value is the first docid.  For column zero in this document
164471  ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
164472  ** at D signals the start of a new column; the 1 at E indicates that the
164473  ** new column is column number 1.  There are two positions at 12 and 45
164474  ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
164475  ** 234 at I is the delta to next docid (357).  It has one position 70
164476  ** (72-2) and then terminates with the 0 at K.
164477  **
164478  ** A "position-list" is the list of positions for multiple columns for
164479  ** a single docid.  A "column-list" is the set of positions for a single
164480  ** column.  Hence, a position-list consists of one or more column-lists,
164481  ** a document record consists of a docid followed by a position-list and
164482  ** a doclist consists of one or more document records.
164483  **
164484  ** A bare doclist omits the position information, becoming an 
164485  ** array of varint-encoded docids.
164486  **
164487  **** Segment leaf nodes ****
164488  ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
164489  ** nodes are written using LeafWriter, and read using LeafReader (to
164490  ** iterate through a single leaf node's data) and LeavesReader (to
164491  ** iterate through a segment's entire leaf layer).  Leaf nodes have
164492  ** the format:
164493  **
164494  ** varint iHeight;             (height from leaf level, always 0)
164495  ** varint nTerm;               (length of first term)
164496  ** char pTerm[nTerm];          (content of first term)
164497  ** varint nDoclist;            (length of term's associated doclist)
164498  ** char pDoclist[nDoclist];    (content of doclist)
164499  ** array {
164500  **                             (further terms are delta-encoded)
164501  **   varint nPrefix;           (length of prefix shared with previous term)
164502  **   varint nSuffix;           (length of unshared suffix)
164503  **   char pTermSuffix[nSuffix];(unshared suffix of next term)
164504  **   varint nDoclist;          (length of term's associated doclist)
164505  **   char pDoclist[nDoclist];  (content of doclist)
164506  ** }
164507  **
164508  ** Here, array { X } means zero or more occurrences of X, adjacent in
164509  ** memory.
164510  **
164511  ** Leaf nodes are broken into blocks which are stored contiguously in
164512  ** the %_segments table in sorted order.  This means that when the end
164513  ** of a node is reached, the next term is in the node with the next
164514  ** greater node id.
164515  **
164516  ** New data is spilled to a new leaf node when the current node
164517  ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
164518  ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
164519  ** node (a leaf node with a single term and doclist).  The goal of
164520  ** these settings is to pack together groups of small doclists while
164521  ** making it efficient to directly access large doclists.  The
164522  ** assumption is that large doclists represent terms which are more
164523  ** likely to be query targets.
164524  **
164525  ** TODO(shess) It may be useful for blocking decisions to be more
164526  ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
164527  ** node rather than splitting into 2k and .5k nodes.  My intuition is
164528  ** that this might extend through 2x or 4x the pagesize.
164529  **
164530  **
164531  **** Segment interior nodes ****
164532  ** Segment interior nodes store blockids for subtree nodes and terms
164533  ** to describe what data is stored by the each subtree.  Interior
164534  ** nodes are written using InteriorWriter, and read using
164535  ** InteriorReader.  InteriorWriters are created as needed when
164536  ** SegmentWriter creates new leaf nodes, or when an interior node
164537  ** itself grows too big and must be split.  The format of interior
164538  ** nodes:
164539  **
164540  ** varint iHeight;           (height from leaf level, always >0)
164541  ** varint iBlockid;          (block id of node's leftmost subtree)
164542  ** optional {
164543  **   varint nTerm;           (length of first term)
164544  **   char pTerm[nTerm];      (content of first term)
164545  **   array {
164546  **                                (further terms are delta-encoded)
164547  **     varint nPrefix;            (length of shared prefix with previous term)
164548  **     varint nSuffix;            (length of unshared suffix)
164549  **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
164550  **   }
164551  ** }
164552  **
164553  ** Here, optional { X } means an optional element, while array { X }
164554  ** means zero or more occurrences of X, adjacent in memory.
164555  **
164556  ** An interior node encodes n terms separating n+1 subtrees.  The
164557  ** subtree blocks are contiguous, so only the first subtree's blockid
164558  ** is encoded.  The subtree at iBlockid will contain all terms less
164559  ** than the first term encoded (or all terms if no term is encoded).
164560  ** Otherwise, for terms greater than or equal to pTerm[i] but less
164561  ** than pTerm[i+1], the subtree for that term will be rooted at
164562  ** iBlockid+i.  Interior nodes only store enough term data to
164563  ** distinguish adjacent children (if the rightmost term of the left
164564  ** child is "something", and the leftmost term of the right child is
164565  ** "wicked", only "w" is stored).
164566  **
164567  ** New data is spilled to a new interior node at the same height when
164568  ** the current node exceeds INTERIOR_MAX bytes (default 2048).
164569  ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
164570  ** interior nodes and making the tree too skinny.  The interior nodes
164571  ** at a given height are naturally tracked by interior nodes at
164572  ** height+1, and so on.
164573  **
164574  **
164575  **** Segment directory ****
164576  ** The segment directory in table %_segdir stores meta-information for
164577  ** merging and deleting segments, and also the root node of the
164578  ** segment's tree.
164579  **
164580  ** The root node is the top node of the segment's tree after encoding
164581  ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
164582  ** This could be either a leaf node or an interior node.  If the top
164583  ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
164584  ** and a new root interior node is generated (which should always fit
164585  ** within ROOT_MAX because it only needs space for 2 varints, the
164586  ** height and the blockid of the previous root).
164587  **
164588  ** The meta-information in the segment directory is:
164589  **   level               - segment level (see below)
164590  **   idx                 - index within level
164591  **                       - (level,idx uniquely identify a segment)
164592  **   start_block         - first leaf node
164593  **   leaves_end_block    - last leaf node
164594  **   end_block           - last block (including interior nodes)
164595  **   root                - contents of root node
164596  **
164597  ** If the root node is a leaf node, then start_block,
164598  ** leaves_end_block, and end_block are all 0.
164599  **
164600  **
164601  **** Segment merging ****
164602  ** To amortize update costs, segments are grouped into levels and
164603  ** merged in batches.  Each increase in level represents exponentially
164604  ** more documents.
164605  **
164606  ** New documents (actually, document updates) are tokenized and
164607  ** written individually (using LeafWriter) to a level 0 segment, with
164608  ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
164609  ** level 0 segments are merged into a single level 1 segment.  Level 1
164610  ** is populated like level 0, and eventually MERGE_COUNT level 1
164611  ** segments are merged to a single level 2 segment (representing
164612  ** MERGE_COUNT^2 updates), and so on.
164613  **
164614  ** A segment merge traverses all segments at a given level in
164615  ** parallel, performing a straightforward sorted merge.  Since segment
164616  ** leaf nodes are written in to the %_segments table in order, this
164617  ** merge traverses the underlying sqlite disk structures efficiently.
164618  ** After the merge, all segment blocks from the merged level are
164619  ** deleted.
164620  **
164621  ** MERGE_COUNT controls how often we merge segments.  16 seems to be
164622  ** somewhat of a sweet spot for insertion performance.  32 and 64 show
164623  ** very similar performance numbers to 16 on insertion, though they're
164624  ** a tiny bit slower (perhaps due to more overhead in merge-time
164625  ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
164626  ** 16, 2 about 66% slower than 16.
164627  **
164628  ** At query time, high MERGE_COUNT increases the number of segments
164629  ** which need to be scanned and merged.  For instance, with 100k docs
164630  ** inserted:
164631  **
164632  **    MERGE_COUNT   segments
164633  **       16           25
164634  **        8           12
164635  **        4           10
164636  **        2            6
164637  **
164638  ** This appears to have only a moderate impact on queries for very
164639  ** frequent terms (which are somewhat dominated by segment merge
164640  ** costs), and infrequent and non-existent terms still seem to be fast
164641  ** even with many segments.
164642  **
164643  ** TODO(shess) That said, it would be nice to have a better query-side
164644  ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
164645  ** optimizations to things like doclist merging will swing the sweet
164646  ** spot around.
164647  **
164648  **
164649  **
164650  **** Handling of deletions and updates ****
164651  ** Since we're using a segmented structure, with no docid-oriented
164652  ** index into the term index, we clearly cannot simply update the term
164653  ** index when a document is deleted or updated.  For deletions, we
164654  ** write an empty doclist (varint(docid) varint(POS_END)), for updates
164655  ** we simply write the new doclist.  Segment merges overwrite older
164656  ** data for a particular docid with newer data, so deletes or updates
164657  ** will eventually overtake the earlier data and knock it out.  The
164658  ** query logic likewise merges doclists so that newer data knocks out
164659  ** older data.
164660  */
164661  
164662  /************** Include fts3Int.h in the middle of fts3.c ********************/
164663  /************** Begin file fts3Int.h *****************************************/
164664  /*
164665  ** 2009 Nov 12
164666  **
164667  ** The author disclaims copyright to this source code.  In place of
164668  ** a legal notice, here is a blessing:
164669  **
164670  **    May you do good and not evil.
164671  **    May you find forgiveness for yourself and forgive others.
164672  **    May you share freely, never taking more than you give.
164673  **
164674  ******************************************************************************
164675  **
164676  */
164677  #ifndef _FTSINT_H
164678  #define _FTSINT_H
164679  
164680  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
164681  # define NDEBUG 1
164682  #endif
164683  
164684  /* FTS3/FTS4 require virtual tables */
164685  #ifdef SQLITE_OMIT_VIRTUALTABLE
164686  # undef SQLITE_ENABLE_FTS3
164687  # undef SQLITE_ENABLE_FTS4
164688  #endif
164689  
164690  /*
164691  ** FTS4 is really an extension for FTS3.  It is enabled using the
164692  ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
164693  ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
164694  */
164695  #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
164696  # define SQLITE_ENABLE_FTS3
164697  #endif
164698  
164699  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164700  
164701  /* If not building as part of the core, include sqlite3ext.h. */
164702  #ifndef SQLITE_CORE
164703  /* # include "sqlite3ext.h"  */
164704  SQLITE_EXTENSION_INIT3
164705  #endif
164706  
164707  /* #include "sqlite3.h" */
164708  /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
164709  /************** Begin file fts3_tokenizer.h **********************************/
164710  /*
164711  ** 2006 July 10
164712  **
164713  ** The author disclaims copyright to this source code.
164714  **
164715  *************************************************************************
164716  ** Defines the interface to tokenizers used by fulltext-search.  There
164717  ** are three basic components:
164718  **
164719  ** sqlite3_tokenizer_module is a singleton defining the tokenizer
164720  ** interface functions.  This is essentially the class structure for
164721  ** tokenizers.
164722  **
164723  ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
164724  ** including customization information defined at creation time.
164725  **
164726  ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
164727  ** tokens from a particular input.
164728  */
164729  #ifndef _FTS3_TOKENIZER_H_
164730  #define _FTS3_TOKENIZER_H_
164731  
164732  /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
164733  ** If tokenizers are to be allowed to call sqlite3_*() functions, then
164734  ** we will need a way to register the API consistently.
164735  */
164736  /* #include "sqlite3.h" */
164737  
164738  /*
164739  ** Structures used by the tokenizer interface. When a new tokenizer
164740  ** implementation is registered, the caller provides a pointer to
164741  ** an sqlite3_tokenizer_module containing pointers to the callback
164742  ** functions that make up an implementation.
164743  **
164744  ** When an fts3 table is created, it passes any arguments passed to
164745  ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
164746  ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
164747  ** implementation. The xCreate() function in turn returns an 
164748  ** sqlite3_tokenizer structure representing the specific tokenizer to
164749  ** be used for the fts3 table (customized by the tokenizer clause arguments).
164750  **
164751  ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
164752  ** method is called. It returns an sqlite3_tokenizer_cursor object
164753  ** that may be used to tokenize a specific input buffer based on
164754  ** the tokenization rules supplied by a specific sqlite3_tokenizer
164755  ** object.
164756  */
164757  typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
164758  typedef struct sqlite3_tokenizer sqlite3_tokenizer;
164759  typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
164760  
164761  struct sqlite3_tokenizer_module {
164762  
164763    /*
164764    ** Structure version. Should always be set to 0 or 1.
164765    */
164766    int iVersion;
164767  
164768    /*
164769    ** Create a new tokenizer. The values in the argv[] array are the
164770    ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
164771    ** TABLE statement that created the fts3 table. For example, if
164772    ** the following SQL is executed:
164773    **
164774    **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
164775    **
164776    ** then argc is set to 2, and the argv[] array contains pointers
164777    ** to the strings "arg1" and "arg2".
164778    **
164779    ** This method should return either SQLITE_OK (0), or an SQLite error 
164780    ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
164781    ** to point at the newly created tokenizer structure. The generic
164782    ** sqlite3_tokenizer.pModule variable should not be initialized by
164783    ** this callback. The caller will do so.
164784    */
164785    int (*xCreate)(
164786      int argc,                           /* Size of argv array */
164787      const char *const*argv,             /* Tokenizer argument strings */
164788      sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
164789    );
164790  
164791    /*
164792    ** Destroy an existing tokenizer. The fts3 module calls this method
164793    ** exactly once for each successful call to xCreate().
164794    */
164795    int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
164796  
164797    /*
164798    ** Create a tokenizer cursor to tokenize an input buffer. The caller
164799    ** is responsible for ensuring that the input buffer remains valid
164800    ** until the cursor is closed (using the xClose() method). 
164801    */
164802    int (*xOpen)(
164803      sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
164804      const char *pInput, int nBytes,      /* Input buffer */
164805      sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
164806    );
164807  
164808    /*
164809    ** Destroy an existing tokenizer cursor. The fts3 module calls this 
164810    ** method exactly once for each successful call to xOpen().
164811    */
164812    int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
164813  
164814    /*
164815    ** Retrieve the next token from the tokenizer cursor pCursor. This
164816    ** method should either return SQLITE_OK and set the values of the
164817    ** "OUT" variables identified below, or SQLITE_DONE to indicate that
164818    ** the end of the buffer has been reached, or an SQLite error code.
164819    **
164820    ** *ppToken should be set to point at a buffer containing the 
164821    ** normalized version of the token (i.e. after any case-folding and/or
164822    ** stemming has been performed). *pnBytes should be set to the length
164823    ** of this buffer in bytes. The input text that generated the token is
164824    ** identified by the byte offsets returned in *piStartOffset and
164825    ** *piEndOffset. *piStartOffset should be set to the index of the first
164826    ** byte of the token in the input buffer. *piEndOffset should be set
164827    ** to the index of the first byte just past the end of the token in
164828    ** the input buffer.
164829    **
164830    ** The buffer *ppToken is set to point at is managed by the tokenizer
164831    ** implementation. It is only required to be valid until the next call
164832    ** to xNext() or xClose(). 
164833    */
164834    /* TODO(shess) current implementation requires pInput to be
164835    ** nul-terminated.  This should either be fixed, or pInput/nBytes
164836    ** should be converted to zInput.
164837    */
164838    int (*xNext)(
164839      sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
164840      const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
164841      int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
164842      int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
164843      int *piPosition      /* OUT: Number of tokens returned before this one */
164844    );
164845  
164846    /***********************************************************************
164847    ** Methods below this point are only available if iVersion>=1.
164848    */
164849  
164850    /* 
164851    ** Configure the language id of a tokenizer cursor.
164852    */
164853    int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
164854  };
164855  
164856  struct sqlite3_tokenizer {
164857    const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
164858    /* Tokenizer implementations will typically add additional fields */
164859  };
164860  
164861  struct sqlite3_tokenizer_cursor {
164862    sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
164863    /* Tokenizer implementations will typically add additional fields */
164864  };
164865  
164866  int fts3_global_term_cnt(int iTerm, int iCol);
164867  int fts3_term_cnt(int iTerm, int iCol);
164868  
164869  
164870  #endif /* _FTS3_TOKENIZER_H_ */
164871  
164872  /************** End of fts3_tokenizer.h **************************************/
164873  /************** Continuing where we left off in fts3Int.h ********************/
164874  /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
164875  /************** Begin file fts3_hash.h ***************************************/
164876  /*
164877  ** 2001 September 22
164878  **
164879  ** The author disclaims copyright to this source code.  In place of
164880  ** a legal notice, here is a blessing:
164881  **
164882  **    May you do good and not evil.
164883  **    May you find forgiveness for yourself and forgive others.
164884  **    May you share freely, never taking more than you give.
164885  **
164886  *************************************************************************
164887  ** This is the header file for the generic hash-table implementation
164888  ** used in SQLite.  We've modified it slightly to serve as a standalone
164889  ** hash table implementation for the full-text indexing module.
164890  **
164891  */
164892  #ifndef _FTS3_HASH_H_
164893  #define _FTS3_HASH_H_
164894  
164895  /* Forward declarations of structures. */
164896  typedef struct Fts3Hash Fts3Hash;
164897  typedef struct Fts3HashElem Fts3HashElem;
164898  
164899  /* A complete hash table is an instance of the following structure.
164900  ** The internals of this structure are intended to be opaque -- client
164901  ** code should not attempt to access or modify the fields of this structure
164902  ** directly.  Change this structure only by using the routines below.
164903  ** However, many of the "procedures" and "functions" for modifying and
164904  ** accessing this structure are really macros, so we can't really make
164905  ** this structure opaque.
164906  */
164907  struct Fts3Hash {
164908    char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
164909    char copyKey;           /* True if copy of key made on insert */
164910    int count;              /* Number of entries in this table */
164911    Fts3HashElem *first;    /* The first element of the array */
164912    int htsize;             /* Number of buckets in the hash table */
164913    struct _fts3ht {        /* the hash table */
164914      int count;               /* Number of entries with this hash */
164915      Fts3HashElem *chain;     /* Pointer to first entry with this hash */
164916    } *ht;
164917  };
164918  
164919  /* Each element in the hash table is an instance of the following 
164920  ** structure.  All elements are stored on a single doubly-linked list.
164921  **
164922  ** Again, this structure is intended to be opaque, but it can't really
164923  ** be opaque because it is used by macros.
164924  */
164925  struct Fts3HashElem {
164926    Fts3HashElem *next, *prev; /* Next and previous elements in the table */
164927    void *data;                /* Data associated with this element */
164928    void *pKey; int nKey;      /* Key associated with this element */
164929  };
164930  
164931  /*
164932  ** There are 2 different modes of operation for a hash table:
164933  **
164934  **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
164935  **                           (including the null-terminator, if any).  Case
164936  **                           is respected in comparisons.
164937  **
164938  **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
164939  **                           memcmp() is used to compare keys.
164940  **
164941  ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
164942  */
164943  #define FTS3_HASH_STRING    1
164944  #define FTS3_HASH_BINARY    2
164945  
164946  /*
164947  ** Access routines.  To delete, insert a NULL pointer.
164948  */
164949  SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
164950  SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
164951  SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
164952  SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
164953  SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
164954  
164955  /*
164956  ** Shorthand for the functions above
164957  */
164958  #define fts3HashInit     sqlite3Fts3HashInit
164959  #define fts3HashInsert   sqlite3Fts3HashInsert
164960  #define fts3HashFind     sqlite3Fts3HashFind
164961  #define fts3HashClear    sqlite3Fts3HashClear
164962  #define fts3HashFindElem sqlite3Fts3HashFindElem
164963  
164964  /*
164965  ** Macros for looping over all elements of a hash table.  The idiom is
164966  ** like this:
164967  **
164968  **   Fts3Hash h;
164969  **   Fts3HashElem *p;
164970  **   ...
164971  **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
164972  **     SomeStructure *pData = fts3HashData(p);
164973  **     // do something with pData
164974  **   }
164975  */
164976  #define fts3HashFirst(H)  ((H)->first)
164977  #define fts3HashNext(E)   ((E)->next)
164978  #define fts3HashData(E)   ((E)->data)
164979  #define fts3HashKey(E)    ((E)->pKey)
164980  #define fts3HashKeysize(E) ((E)->nKey)
164981  
164982  /*
164983  ** Number of entries in a hash table
164984  */
164985  #define fts3HashCount(H)  ((H)->count)
164986  
164987  #endif /* _FTS3_HASH_H_ */
164988  
164989  /************** End of fts3_hash.h *******************************************/
164990  /************** Continuing where we left off in fts3Int.h ********************/
164991  
164992  /*
164993  ** This constant determines the maximum depth of an FTS expression tree
164994  ** that the library will create and use. FTS uses recursion to perform 
164995  ** various operations on the query tree, so the disadvantage of a large
164996  ** limit is that it may allow very large queries to use large amounts
164997  ** of stack space (perhaps causing a stack overflow).
164998  */
164999  #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
165000  # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
165001  #endif
165002  
165003  
165004  /*
165005  ** This constant controls how often segments are merged. Once there are
165006  ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
165007  ** segment of level N+1.
165008  */
165009  #define FTS3_MERGE_COUNT 16
165010  
165011  /*
165012  ** This is the maximum amount of data (in bytes) to store in the 
165013  ** Fts3Table.pendingTerms hash table. Normally, the hash table is
165014  ** populated as documents are inserted/updated/deleted in a transaction
165015  ** and used to create a new segment when the transaction is committed.
165016  ** However if this limit is reached midway through a transaction, a new 
165017  ** segment is created and the hash table cleared immediately.
165018  */
165019  #define FTS3_MAX_PENDING_DATA (1*1024*1024)
165020  
165021  /*
165022  ** Macro to return the number of elements in an array. SQLite has a
165023  ** similar macro called ArraySize(). Use a different name to avoid
165024  ** a collision when building an amalgamation with built-in FTS3.
165025  */
165026  #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
165027  
165028  
165029  #ifndef MIN
165030  # define MIN(x,y) ((x)<(y)?(x):(y))
165031  #endif
165032  #ifndef MAX
165033  # define MAX(x,y) ((x)>(y)?(x):(y))
165034  #endif
165035  
165036  /*
165037  ** Maximum length of a varint encoded integer. The varint format is different
165038  ** from that used by SQLite, so the maximum length is 10, not 9.
165039  */
165040  #define FTS3_VARINT_MAX 10
165041  
165042  #define FTS3_BUFFER_PADDING 8
165043  
165044  /*
165045  ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
165046  ** in the document set and zero or more prefix indexes. All indexes are stored
165047  ** as one or more b+-trees in the %_segments and %_segdir tables. 
165048  **
165049  ** It is possible to determine which index a b+-tree belongs to based on the
165050  ** value stored in the "%_segdir.level" column. Given this value L, the index
165051  ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
165052  ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
165053  ** between 1024 and 2047 to index 1, and so on.
165054  **
165055  ** It is considered impossible for an index to use more than 1024 levels. In 
165056  ** theory though this may happen, but only after at least 
165057  ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
165058  */
165059  #define FTS3_SEGDIR_MAXLEVEL      1024
165060  #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
165061  
165062  /*
165063  ** The testcase() macro is only used by the amalgamation.  If undefined,
165064  ** make it a no-op.
165065  */
165066  #ifndef testcase
165067  # define testcase(X)
165068  #endif
165069  
165070  /*
165071  ** Terminator values for position-lists and column-lists.
165072  */
165073  #define POS_COLUMN  (1)     /* Column-list terminator */
165074  #define POS_END     (0)     /* Position-list terminator */ 
165075  
165076  /*
165077  ** The assert_fts3_nc() macro is similar to the assert() macro, except that it
165078  ** is used for assert() conditions that are true only if it can be 
165079  ** guranteed that the database is not corrupt.
165080  */
165081  #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
165082  SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
165083  # define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
165084  #else
165085  # define assert_fts3_nc(x) assert(x)
165086  #endif
165087  
165088  /*
165089  ** This section provides definitions to allow the
165090  ** FTS3 extension to be compiled outside of the 
165091  ** amalgamation.
165092  */
165093  #ifndef SQLITE_AMALGAMATION
165094  /*
165095  ** Macros indicating that conditional expressions are always true or
165096  ** false.
165097  */
165098  #ifdef SQLITE_COVERAGE_TEST
165099  # define ALWAYS(x) (1)
165100  # define NEVER(X)  (0)
165101  #elif defined(SQLITE_DEBUG)
165102  # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
165103  # define NEVER(x) sqlite3Fts3Never((x)!=0)
165104  SQLITE_PRIVATE int sqlite3Fts3Always(int b);
165105  SQLITE_PRIVATE int sqlite3Fts3Never(int b);
165106  #else
165107  # define ALWAYS(x) (x)
165108  # define NEVER(x)  (x)
165109  #endif
165110  
165111  /*
165112  ** Internal types used by SQLite.
165113  */
165114  typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
165115  typedef short int i16;            /* 2-byte (or larger) signed integer */
165116  typedef unsigned int u32;         /* 4-byte unsigned integer */
165117  typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
165118  typedef sqlite3_int64 i64;        /* 8-byte signed integer */
165119  
165120  /*
165121  ** Macro used to suppress compiler warnings for unused parameters.
165122  */
165123  #define UNUSED_PARAMETER(x) (void)(x)
165124  
165125  /*
165126  ** Activate assert() only if SQLITE_TEST is enabled.
165127  */
165128  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
165129  # define NDEBUG 1
165130  #endif
165131  
165132  /*
165133  ** The TESTONLY macro is used to enclose variable declarations or
165134  ** other bits of code that are needed to support the arguments
165135  ** within testcase() and assert() macros.
165136  */
165137  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
165138  # define TESTONLY(X)  X
165139  #else
165140  # define TESTONLY(X)
165141  #endif
165142  
165143  #endif /* SQLITE_AMALGAMATION */
165144  
165145  #ifdef SQLITE_DEBUG
165146  SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
165147  # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
165148  #else
165149  # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
165150  #endif
165151  
165152  typedef struct Fts3Table Fts3Table;
165153  typedef struct Fts3Cursor Fts3Cursor;
165154  typedef struct Fts3Expr Fts3Expr;
165155  typedef struct Fts3Phrase Fts3Phrase;
165156  typedef struct Fts3PhraseToken Fts3PhraseToken;
165157  
165158  typedef struct Fts3Doclist Fts3Doclist;
165159  typedef struct Fts3SegFilter Fts3SegFilter;
165160  typedef struct Fts3DeferredToken Fts3DeferredToken;
165161  typedef struct Fts3SegReader Fts3SegReader;
165162  typedef struct Fts3MultiSegReader Fts3MultiSegReader;
165163  
165164  typedef struct MatchinfoBuffer MatchinfoBuffer;
165165  
165166  /*
165167  ** A connection to a fulltext index is an instance of the following
165168  ** structure. The xCreate and xConnect methods create an instance
165169  ** of this structure and xDestroy and xDisconnect free that instance.
165170  ** All other methods receive a pointer to the structure as one of their
165171  ** arguments.
165172  */
165173  struct Fts3Table {
165174    sqlite3_vtab base;              /* Base class used by SQLite core */
165175    sqlite3 *db;                    /* The database connection */
165176    const char *zDb;                /* logical database name */
165177    const char *zName;              /* virtual table name */
165178    int nColumn;                    /* number of named columns in virtual table */
165179    char **azColumn;                /* column names.  malloced */
165180    u8 *abNotindexed;               /* True for 'notindexed' columns */
165181    sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
165182    char *zContentTbl;              /* content=xxx option, or NULL */
165183    char *zLanguageid;              /* languageid=xxx option, or NULL */
165184    int nAutoincrmerge;             /* Value configured by 'automerge' */
165185    u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
165186  
165187    /* Precompiled statements used by the implementation. Each of these 
165188    ** statements is run and reset within a single virtual table API call. 
165189    */
165190    sqlite3_stmt *aStmt[40];
165191    sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
165192  
165193    char *zReadExprlist;
165194    char *zWriteExprlist;
165195  
165196    int nNodeSize;                  /* Soft limit for node size */
165197    u8 bFts4;                       /* True for FTS4, false for FTS3 */
165198    u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
165199    u8 bHasDocsize;                 /* True if %_docsize table exists */
165200    u8 bDescIdx;                    /* True if doclists are in reverse order */
165201    u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
165202    int nPgsz;                      /* Page size for host database */
165203    char *zSegmentsTbl;             /* Name of %_segments table */
165204    sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
165205  
165206    /* 
165207    ** The following array of hash tables is used to buffer pending index 
165208    ** updates during transactions. All pending updates buffered at any one
165209    ** time must share a common language-id (see the FTS4 langid= feature).
165210    ** The current language id is stored in variable iPrevLangid.
165211    **
165212    ** A single FTS4 table may have multiple full-text indexes. For each index
165213    ** there is an entry in the aIndex[] array. Index 0 is an index of all the
165214    ** terms that appear in the document set. Each subsequent index in aIndex[]
165215    ** is an index of prefixes of a specific length.
165216    **
165217    ** Variable nPendingData contains an estimate the memory consumed by the 
165218    ** pending data structures, including hash table overhead, but not including
165219    ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
165220    ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
165221    ** recently inserted record.
165222    */
165223    int nIndex;                     /* Size of aIndex[] */
165224    struct Fts3Index {
165225      int nPrefix;                  /* Prefix length (0 for main terms index) */
165226      Fts3Hash hPending;            /* Pending terms table for this index */
165227    } *aIndex;
165228    int nMaxPendingData;            /* Max pending data before flush to disk */
165229    int nPendingData;               /* Current bytes of pending data */
165230    sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
165231    int iPrevLangid;                /* Langid of recently inserted document */
165232    int bPrevDelete;                /* True if last operation was a delete */
165233  
165234  #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
165235    /* State variables used for validating that the transaction control
165236    ** methods of the virtual table are called at appropriate times.  These
165237    ** values do not contribute to FTS functionality; they are used for
165238    ** verifying the operation of the SQLite core.
165239    */
165240    int inTransaction;     /* True after xBegin but before xCommit/xRollback */
165241    int mxSavepoint;       /* Largest valid xSavepoint integer */
165242  #endif
165243  
165244  #ifdef SQLITE_TEST
165245    /* True to disable the incremental doclist optimization. This is controled
165246    ** by special insert command 'test-no-incr-doclist'.  */
165247    int bNoIncrDoclist;
165248  #endif
165249  };
165250  
165251  /*
165252  ** When the core wants to read from the virtual table, it creates a
165253  ** virtual table cursor (an instance of the following structure) using
165254  ** the xOpen method. Cursors are destroyed using the xClose method.
165255  */
165256  struct Fts3Cursor {
165257    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
165258    i16 eSearch;                    /* Search strategy (see below) */
165259    u8 isEof;                       /* True if at End Of Results */
165260    u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
165261    u8 bSeekStmt;                   /* True if pStmt is a seek */
165262    sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
165263    Fts3Expr *pExpr;                /* Parsed MATCH query string */
165264    int iLangid;                    /* Language being queried for */
165265    int nPhrase;                    /* Number of matchable phrases in query */
165266    Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
165267    sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
165268    char *pNextId;                  /* Pointer into the body of aDoclist */
165269    char *aDoclist;                 /* List of docids for full-text queries */
165270    int nDoclist;                   /* Size of buffer at aDoclist */
165271    u8 bDesc;                       /* True to sort in descending order */
165272    int eEvalmode;                  /* An FTS3_EVAL_XX constant */
165273    int nRowAvg;                    /* Average size of database rows, in pages */
165274    sqlite3_int64 nDoc;             /* Documents in table */
165275    i64 iMinDocid;                  /* Minimum docid to return */
165276    i64 iMaxDocid;                  /* Maximum docid to return */
165277    int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
165278    MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
165279  };
165280  
165281  #define FTS3_EVAL_FILTER    0
165282  #define FTS3_EVAL_NEXT      1
165283  #define FTS3_EVAL_MATCHINFO 2
165284  
165285  /*
165286  ** The Fts3Cursor.eSearch member is always set to one of the following.
165287  ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
165288  ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
165289  ** of the column to be searched.  For example, in
165290  **
165291  **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
165292  **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
165293  ** 
165294  ** Because the LHS of the MATCH operator is 2nd column "b",
165295  ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
165296  ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
165297  ** indicating that all columns should be searched,
165298  ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
165299  */
165300  #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
165301  #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
165302  #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
165303  
165304  /*
165305  ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
165306  ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
165307  ** above. The upper 16-bits contain a combination of the following
165308  ** bits, used to describe extra constraints on full-text searches.
165309  */
165310  #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
165311  #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
165312  #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
165313  
165314  struct Fts3Doclist {
165315    char *aAll;                    /* Array containing doclist (or NULL) */
165316    int nAll;                      /* Size of a[] in bytes */
165317    char *pNextDocid;              /* Pointer to next docid */
165318  
165319    sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
165320    int bFreeList;                 /* True if pList should be sqlite3_free()d */
165321    char *pList;                   /* Pointer to position list following iDocid */
165322    int nList;                     /* Length of position list */
165323  };
165324  
165325  /*
165326  ** A "phrase" is a sequence of one or more tokens that must match in
165327  ** sequence.  A single token is the base case and the most common case.
165328  ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
165329  ** nToken will be the number of tokens in the string.
165330  */
165331  struct Fts3PhraseToken {
165332    char *z;                        /* Text of the token */
165333    int n;                          /* Number of bytes in buffer z */
165334    int isPrefix;                   /* True if token ends with a "*" character */
165335    int bFirst;                     /* True if token must appear at position 0 */
165336  
165337    /* Variables above this point are populated when the expression is
165338    ** parsed (by code in fts3_expr.c). Below this point the variables are
165339    ** used when evaluating the expression. */
165340    Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
165341    Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
165342  };
165343  
165344  struct Fts3Phrase {
165345    /* Cache of doclist for this phrase. */
165346    Fts3Doclist doclist;
165347    int bIncr;                 /* True if doclist is loaded incrementally */
165348    int iDoclistToken;
165349  
165350    /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
165351    ** OR condition.  */
165352    char *pOrPoslist;
165353    i64 iOrDocid;
165354  
165355    /* Variables below this point are populated by fts3_expr.c when parsing 
165356    ** a MATCH expression. Everything above is part of the evaluation phase. 
165357    */
165358    int nToken;                /* Number of tokens in the phrase */
165359    int iColumn;               /* Index of column this phrase must match */
165360    Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
165361  };
165362  
165363  /*
165364  ** A tree of these objects forms the RHS of a MATCH operator.
165365  **
165366  ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
165367  ** points to a malloced buffer, size nDoclist bytes, containing the results 
165368  ** of this phrase query in FTS3 doclist format. As usual, the initial 
165369  ** "Length" field found in doclists stored on disk is omitted from this 
165370  ** buffer.
165371  **
165372  ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
165373  ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
165374  ** where nCol is the number of columns in the queried FTS table. The array
165375  ** is populated as follows:
165376  **
165377  **   aMI[iCol*3 + 0] = Undefined
165378  **   aMI[iCol*3 + 1] = Number of occurrences
165379  **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
165380  **
165381  ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
165382  ** when the expression node is.
165383  */
165384  struct Fts3Expr {
165385    int eType;                 /* One of the FTSQUERY_XXX values defined below */
165386    int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
165387    Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
165388    Fts3Expr *pLeft;           /* Left operand */
165389    Fts3Expr *pRight;          /* Right operand */
165390    Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
165391  
165392    /* The following are used by the fts3_eval.c module. */
165393    sqlite3_int64 iDocid;      /* Current docid */
165394    u8 bEof;                   /* True this expression is at EOF already */
165395    u8 bStart;                 /* True if iDocid is valid */
165396    u8 bDeferred;              /* True if this expression is entirely deferred */
165397  
165398    /* The following are used by the fts3_snippet.c module. */
165399    int iPhrase;               /* Index of this phrase in matchinfo() results */
165400    u32 *aMI;                  /* See above */
165401  };
165402  
165403  /*
165404  ** Candidate values for Fts3Query.eType. Note that the order of the first
165405  ** four values is in order of precedence when parsing expressions. For 
165406  ** example, the following:
165407  **
165408  **   "a OR b AND c NOT d NEAR e"
165409  **
165410  ** is equivalent to:
165411  **
165412  **   "a OR (b AND (c NOT (d NEAR e)))"
165413  */
165414  #define FTSQUERY_NEAR   1
165415  #define FTSQUERY_NOT    2
165416  #define FTSQUERY_AND    3
165417  #define FTSQUERY_OR     4
165418  #define FTSQUERY_PHRASE 5
165419  
165420  
165421  /* fts3_write.c */
165422  SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
165423  SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
165424  SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
165425  SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
165426  SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
165427    sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
165428  SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
165429    Fts3Table*,int,const char*,int,int,Fts3SegReader**);
165430  SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
165431  SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
165432  SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
165433  
165434  SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
165435  SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
165436  
165437  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
165438  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
165439  SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
165440  SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
165441  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
165442  SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
165443  #else
165444  # define sqlite3Fts3FreeDeferredTokens(x)
165445  # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
165446  # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
165447  # define sqlite3Fts3FreeDeferredDoclists(x)
165448  # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
165449  #endif
165450  
165451  SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
165452  SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
165453  
165454  /* Special values interpreted by sqlite3SegReaderCursor() */
165455  #define FTS3_SEGCURSOR_PENDING        -1
165456  #define FTS3_SEGCURSOR_ALL            -2
165457  
165458  SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
165459  SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
165460  SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
165461  
165462  SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
165463      int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
165464  
165465  /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
165466  #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
165467  #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
165468  #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
165469  #define FTS3_SEGMENT_PREFIX        0x00000008
165470  #define FTS3_SEGMENT_SCAN          0x00000010
165471  #define FTS3_SEGMENT_FIRST         0x00000020
165472  
165473  /* Type passed as 4th argument to SegmentReaderIterate() */
165474  struct Fts3SegFilter {
165475    const char *zTerm;
165476    int nTerm;
165477    int iCol;
165478    int flags;
165479  };
165480  
165481  struct Fts3MultiSegReader {
165482    /* Used internally by sqlite3Fts3SegReaderXXX() calls */
165483    Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
165484    int nSegment;                   /* Size of apSegment array */
165485    int nAdvance;                   /* How many seg-readers to advance */
165486    Fts3SegFilter *pFilter;         /* Pointer to filter object */
165487    char *aBuffer;                  /* Buffer to merge doclists in */
165488    int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
165489  
165490    int iColFilter;                 /* If >=0, filter for this column */
165491    int bRestart;
165492  
165493    /* Used by fts3.c only. */
165494    int nCost;                      /* Cost of running iterator */
165495    int bLookup;                    /* True if a lookup of a single entry. */
165496  
165497    /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
165498    char *zTerm;                    /* Pointer to term buffer */
165499    int nTerm;                      /* Size of zTerm in bytes */
165500    char *aDoclist;                 /* Pointer to doclist buffer */
165501    int nDoclist;                   /* Size of aDoclist[] in bytes */
165502  };
165503  
165504  SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
165505  
165506  #define fts3GetVarint32(p, piVal) (                                           \
165507    (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
165508  )
165509  
165510  /* fts3.c */
165511  SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
165512  SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
165513  SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
165514  SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
165515  SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
165516  SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
165517  SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
165518  SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
165519  SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
165520  SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
165521  SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
165522  
165523  /* fts3_tokenizer.c */
165524  SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
165525  SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
165526  SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
165527      sqlite3_tokenizer **, char **
165528  );
165529  SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
165530  
165531  /* fts3_snippet.c */
165532  SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
165533  SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
165534    const char *, const char *, int, int
165535  );
165536  SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
165537  SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
165538  
165539  /* fts3_expr.c */
165540  SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
165541    char **, int, int, int, const char *, int, Fts3Expr **, char **
165542  );
165543  SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
165544  #ifdef SQLITE_TEST
165545  SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
165546  SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
165547  #endif
165548  
165549  SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
165550    sqlite3_tokenizer_cursor **
165551  );
165552  
165553  /* fts3_aux.c */
165554  SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
165555  
165556  SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
165557  
165558  SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
165559      Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
165560  SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
165561      Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
165562  SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
165563  SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
165564  SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
165565  
165566  /* fts3_tokenize_vtab.c */
165567  SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
165568  
165569  /* fts3_unicode2.c (functions generated by parsing unicode text files) */
165570  #ifndef SQLITE_DISABLE_FTS3_UNICODE
165571  SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
165572  SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
165573  SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
165574  #endif
165575  
165576  #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
165577  #endif /* _FTSINT_H */
165578  
165579  /************** End of fts3Int.h *********************************************/
165580  /************** Continuing where we left off in fts3.c ***********************/
165581  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
165582  
165583  #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
165584  # define SQLITE_CORE 1
165585  #endif
165586  
165587  /* #include <assert.h> */
165588  /* #include <stdlib.h> */
165589  /* #include <stddef.h> */
165590  /* #include <stdio.h> */
165591  /* #include <string.h> */
165592  /* #include <stdarg.h> */
165593  
165594  /* #include "fts3.h" */
165595  #ifndef SQLITE_CORE 
165596  /* # include "sqlite3ext.h" */
165597    SQLITE_EXTENSION_INIT1
165598  #endif
165599  
165600  static int fts3EvalNext(Fts3Cursor *pCsr);
165601  static int fts3EvalStart(Fts3Cursor *pCsr);
165602  static int fts3TermSegReaderCursor(
165603      Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
165604  
165605  #ifndef SQLITE_AMALGAMATION
165606  # if defined(SQLITE_DEBUG)
165607  SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
165608  SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
165609  # endif
165610  #endif
165611  
165612  /*
165613  ** This variable is set to false when running tests for which the on disk
165614  ** structures should not be corrupt. Otherwise, true. If it is false, extra
165615  ** assert() conditions in the fts3 code are activated - conditions that are
165616  ** only true if it is guaranteed that the fts3 database is not corrupt.
165617  */
165618  SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
165619  
165620  /* 
165621  ** Write a 64-bit variable-length integer to memory starting at p[0].
165622  ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
165623  ** The number of bytes written is returned.
165624  */
165625  SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
165626    unsigned char *q = (unsigned char *) p;
165627    sqlite_uint64 vu = v;
165628    do{
165629      *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
165630      vu >>= 7;
165631    }while( vu!=0 );
165632    q[-1] &= 0x7f;  /* turn off high bit in final byte */
165633    assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
165634    return (int) (q - (unsigned char *)p);
165635  }
165636  
165637  #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
165638    v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift );  \
165639    if( (v & mask2)==0 ){ var = v; return ret; }
165640  #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
165641    v = (*ptr++);                                               \
165642    if( (v & mask2)==0 ){ var = v; return ret; }
165643  
165644  /* 
165645  ** Read a 64-bit variable-length integer from memory starting at p[0].
165646  ** Return the number of bytes read, or 0 on error.
165647  ** The value is stored in *v.
165648  */
165649  SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
165650    const unsigned char *p = (const unsigned char*)pBuf;
165651    const unsigned char *pStart = p;
165652    u32 a;
165653    u64 b;
165654    int shift;
165655  
165656    GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
165657    GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
165658    GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
165659    GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
165660    b = (a & 0x0FFFFFFF );
165661  
165662    for(shift=28; shift<=63; shift+=7){
165663      u64 c = *p++;
165664      b += (c&0x7F) << shift;
165665      if( (c & 0x80)==0 ) break;
165666    }
165667    *v = b;
165668    return (int)(p - pStart);
165669  }
165670  
165671  /*
165672  ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to 
165673  ** a non-negative 32-bit integer before it is returned.
165674  */
165675  SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
165676    const unsigned char *ptr = (const unsigned char*)p;
165677    u32 a;
165678  
165679  #ifndef fts3GetVarint32
165680    GETVARINT_INIT(a, ptr, 0,  0x00,     0x80, *pi, 1);
165681  #else
165682    a = (*ptr++);
165683    assert( a & 0x80 );
165684  #endif
165685  
165686    GETVARINT_STEP(a, ptr, 7,  0x7F,     0x4000, *pi, 2);
165687    GETVARINT_STEP(a, ptr, 14, 0x3FFF,   0x200000, *pi, 3);
165688    GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
165689    a = (a & 0x0FFFFFFF );
165690    *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
165691    assert( 0==(a & 0x80000000) );
165692    assert( *pi>=0 );
165693    return 5;
165694  }
165695  
165696  /*
165697  ** Return the number of bytes required to encode v as a varint
165698  */
165699  SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
165700    int i = 0;
165701    do{
165702      i++;
165703      v >>= 7;
165704    }while( v!=0 );
165705    return i;
165706  }
165707  
165708  /*
165709  ** Convert an SQL-style quoted string into a normal string by removing
165710  ** the quote characters.  The conversion is done in-place.  If the
165711  ** input does not begin with a quote character, then this routine
165712  ** is a no-op.
165713  **
165714  ** Examples:
165715  **
165716  **     "abc"   becomes   abc
165717  **     'xyz'   becomes   xyz
165718  **     [pqr]   becomes   pqr
165719  **     `mno`   becomes   mno
165720  **
165721  */
165722  SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
165723    char quote;                     /* Quote character (if any ) */
165724  
165725    quote = z[0];
165726    if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
165727      int iIn = 1;                  /* Index of next byte to read from input */
165728      int iOut = 0;                 /* Index of next byte to write to output */
165729  
165730      /* If the first byte was a '[', then the close-quote character is a ']' */
165731      if( quote=='[' ) quote = ']';  
165732  
165733      while( z[iIn] ){
165734        if( z[iIn]==quote ){
165735          if( z[iIn+1]!=quote ) break;
165736          z[iOut++] = quote;
165737          iIn += 2;
165738        }else{
165739          z[iOut++] = z[iIn++];
165740        }
165741      }
165742      z[iOut] = '\0';
165743    }
165744  }
165745  
165746  /*
165747  ** Read a single varint from the doclist at *pp and advance *pp to point
165748  ** to the first byte past the end of the varint.  Add the value of the varint
165749  ** to *pVal.
165750  */
165751  static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
165752    sqlite3_int64 iVal;
165753    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
165754    *pVal += iVal;
165755  }
165756  
165757  /*
165758  ** When this function is called, *pp points to the first byte following a
165759  ** varint that is part of a doclist (or position-list, or any other list
165760  ** of varints). This function moves *pp to point to the start of that varint,
165761  ** and sets *pVal by the varint value.
165762  **
165763  ** Argument pStart points to the first byte of the doclist that the
165764  ** varint is part of.
165765  */
165766  static void fts3GetReverseVarint(
165767    char **pp, 
165768    char *pStart, 
165769    sqlite3_int64 *pVal
165770  ){
165771    sqlite3_int64 iVal;
165772    char *p;
165773  
165774    /* Pointer p now points at the first byte past the varint we are 
165775    ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
165776    ** clear on character p[-1]. */
165777    for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
165778    p++;
165779    *pp = p;
165780  
165781    sqlite3Fts3GetVarint(p, &iVal);
165782    *pVal = iVal;
165783  }
165784  
165785  /*
165786  ** The xDisconnect() virtual table method.
165787  */
165788  static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
165789    Fts3Table *p = (Fts3Table *)pVtab;
165790    int i;
165791  
165792    assert( p->nPendingData==0 );
165793    assert( p->pSegments==0 );
165794  
165795    /* Free any prepared statements held */
165796    sqlite3_finalize(p->pSeekStmt);
165797    for(i=0; i<SizeofArray(p->aStmt); i++){
165798      sqlite3_finalize(p->aStmt[i]);
165799    }
165800    sqlite3_free(p->zSegmentsTbl);
165801    sqlite3_free(p->zReadExprlist);
165802    sqlite3_free(p->zWriteExprlist);
165803    sqlite3_free(p->zContentTbl);
165804    sqlite3_free(p->zLanguageid);
165805  
165806    /* Invoke the tokenizer destructor to free the tokenizer. */
165807    p->pTokenizer->pModule->xDestroy(p->pTokenizer);
165808  
165809    sqlite3_free(p);
165810    return SQLITE_OK;
165811  }
165812  
165813  /*
165814  ** Write an error message into *pzErr
165815  */
165816  SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
165817    va_list ap;
165818    sqlite3_free(*pzErr);
165819    va_start(ap, zFormat);
165820    *pzErr = sqlite3_vmprintf(zFormat, ap);
165821    va_end(ap);
165822  }
165823  
165824  /*
165825  ** Construct one or more SQL statements from the format string given
165826  ** and then evaluate those statements. The success code is written
165827  ** into *pRc.
165828  **
165829  ** If *pRc is initially non-zero then this routine is a no-op.
165830  */
165831  static void fts3DbExec(
165832    int *pRc,              /* Success code */
165833    sqlite3 *db,           /* Database in which to run SQL */
165834    const char *zFormat,   /* Format string for SQL */
165835    ...                    /* Arguments to the format string */
165836  ){
165837    va_list ap;
165838    char *zSql;
165839    if( *pRc ) return;
165840    va_start(ap, zFormat);
165841    zSql = sqlite3_vmprintf(zFormat, ap);
165842    va_end(ap);
165843    if( zSql==0 ){
165844      *pRc = SQLITE_NOMEM;
165845    }else{
165846      *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
165847      sqlite3_free(zSql);
165848    }
165849  }
165850  
165851  /*
165852  ** The xDestroy() virtual table method.
165853  */
165854  static int fts3DestroyMethod(sqlite3_vtab *pVtab){
165855    Fts3Table *p = (Fts3Table *)pVtab;
165856    int rc = SQLITE_OK;              /* Return code */
165857    const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
165858    sqlite3 *db = p->db;             /* Database handle */
165859  
165860    /* Drop the shadow tables */
165861    fts3DbExec(&rc, db, 
165862      "DROP TABLE IF EXISTS %Q.'%q_segments';"
165863      "DROP TABLE IF EXISTS %Q.'%q_segdir';"
165864      "DROP TABLE IF EXISTS %Q.'%q_docsize';"
165865      "DROP TABLE IF EXISTS %Q.'%q_stat';"
165866      "%s DROP TABLE IF EXISTS %Q.'%q_content';",
165867      zDb, p->zName,
165868      zDb, p->zName,
165869      zDb, p->zName,
165870      zDb, p->zName,
165871      (p->zContentTbl ? "--" : ""), zDb,p->zName
165872    );
165873  
165874    /* If everything has worked, invoke fts3DisconnectMethod() to free the
165875    ** memory associated with the Fts3Table structure and return SQLITE_OK.
165876    ** Otherwise, return an SQLite error code.
165877    */
165878    return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
165879  }
165880  
165881  
165882  /*
165883  ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
165884  ** passed as the first argument. This is done as part of the xConnect()
165885  ** and xCreate() methods.
165886  **
165887  ** If *pRc is non-zero when this function is called, it is a no-op. 
165888  ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
165889  ** before returning.
165890  */
165891  static void fts3DeclareVtab(int *pRc, Fts3Table *p){
165892    if( *pRc==SQLITE_OK ){
165893      int i;                        /* Iterator variable */
165894      int rc;                       /* Return code */
165895      char *zSql;                   /* SQL statement passed to declare_vtab() */
165896      char *zCols;                  /* List of user defined columns */
165897      const char *zLanguageid;
165898  
165899      zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
165900      sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
165901  
165902      /* Create a list of user columns for the virtual table */
165903      zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
165904      for(i=1; zCols && i<p->nColumn; i++){
165905        zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
165906      }
165907  
165908      /* Create the whole "CREATE TABLE" statement to pass to SQLite */
165909      zSql = sqlite3_mprintf(
165910          "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
165911          zCols, p->zName, zLanguageid
165912      );
165913      if( !zCols || !zSql ){
165914        rc = SQLITE_NOMEM;
165915      }else{
165916        rc = sqlite3_declare_vtab(p->db, zSql);
165917      }
165918  
165919      sqlite3_free(zSql);
165920      sqlite3_free(zCols);
165921      *pRc = rc;
165922    }
165923  }
165924  
165925  /*
165926  ** Create the %_stat table if it does not already exist.
165927  */
165928  SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
165929    fts3DbExec(pRc, p->db, 
165930        "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
165931            "(id INTEGER PRIMARY KEY, value BLOB);",
165932        p->zDb, p->zName
165933    );
165934    if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
165935  }
165936  
165937  /*
165938  ** Create the backing store tables (%_content, %_segments and %_segdir)
165939  ** required by the FTS3 table passed as the only argument. This is done
165940  ** as part of the vtab xCreate() method.
165941  **
165942  ** If the p->bHasDocsize boolean is true (indicating that this is an
165943  ** FTS4 table, not an FTS3 table) then also create the %_docsize and
165944  ** %_stat tables required by FTS4.
165945  */
165946  static int fts3CreateTables(Fts3Table *p){
165947    int rc = SQLITE_OK;             /* Return code */
165948    int i;                          /* Iterator variable */
165949    sqlite3 *db = p->db;            /* The database connection */
165950  
165951    if( p->zContentTbl==0 ){
165952      const char *zLanguageid = p->zLanguageid;
165953      char *zContentCols;           /* Columns of %_content table */
165954  
165955      /* Create a list of user columns for the content table */
165956      zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
165957      for(i=0; zContentCols && i<p->nColumn; i++){
165958        char *z = p->azColumn[i];
165959        zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
165960      }
165961      if( zLanguageid && zContentCols ){
165962        zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
165963      }
165964      if( zContentCols==0 ) rc = SQLITE_NOMEM;
165965    
165966      /* Create the content table */
165967      fts3DbExec(&rc, db, 
165968         "CREATE TABLE %Q.'%q_content'(%s)",
165969         p->zDb, p->zName, zContentCols
165970      );
165971      sqlite3_free(zContentCols);
165972    }
165973  
165974    /* Create other tables */
165975    fts3DbExec(&rc, db, 
165976        "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
165977        p->zDb, p->zName
165978    );
165979    fts3DbExec(&rc, db, 
165980        "CREATE TABLE %Q.'%q_segdir'("
165981          "level INTEGER,"
165982          "idx INTEGER,"
165983          "start_block INTEGER,"
165984          "leaves_end_block INTEGER,"
165985          "end_block INTEGER,"
165986          "root BLOB,"
165987          "PRIMARY KEY(level, idx)"
165988        ");",
165989        p->zDb, p->zName
165990    );
165991    if( p->bHasDocsize ){
165992      fts3DbExec(&rc, db, 
165993          "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
165994          p->zDb, p->zName
165995      );
165996    }
165997    assert( p->bHasStat==p->bFts4 );
165998    if( p->bHasStat ){
165999      sqlite3Fts3CreateStatTable(&rc, p);
166000    }
166001    return rc;
166002  }
166003  
166004  /*
166005  ** Store the current database page-size in bytes in p->nPgsz.
166006  **
166007  ** If *pRc is non-zero when this function is called, it is a no-op. 
166008  ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
166009  ** before returning.
166010  */
166011  static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
166012    if( *pRc==SQLITE_OK ){
166013      int rc;                       /* Return code */
166014      char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
166015      sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
166016    
166017      zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
166018      if( !zSql ){
166019        rc = SQLITE_NOMEM;
166020      }else{
166021        rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
166022        if( rc==SQLITE_OK ){
166023          sqlite3_step(pStmt);
166024          p->nPgsz = sqlite3_column_int(pStmt, 0);
166025          rc = sqlite3_finalize(pStmt);
166026        }else if( rc==SQLITE_AUTH ){
166027          p->nPgsz = 1024;
166028          rc = SQLITE_OK;
166029        }
166030      }
166031      assert( p->nPgsz>0 || rc!=SQLITE_OK );
166032      sqlite3_free(zSql);
166033      *pRc = rc;
166034    }
166035  }
166036  
166037  /*
166038  ** "Special" FTS4 arguments are column specifications of the following form:
166039  **
166040  **   <key> = <value>
166041  **
166042  ** There may not be whitespace surrounding the "=" character. The <value> 
166043  ** term may be quoted, but the <key> may not.
166044  */
166045  static int fts3IsSpecialColumn(
166046    const char *z, 
166047    int *pnKey,
166048    char **pzValue
166049  ){
166050    char *zValue;
166051    const char *zCsr = z;
166052  
166053    while( *zCsr!='=' ){
166054      if( *zCsr=='\0' ) return 0;
166055      zCsr++;
166056    }
166057  
166058    *pnKey = (int)(zCsr-z);
166059    zValue = sqlite3_mprintf("%s", &zCsr[1]);
166060    if( zValue ){
166061      sqlite3Fts3Dequote(zValue);
166062    }
166063    *pzValue = zValue;
166064    return 1;
166065  }
166066  
166067  /*
166068  ** Append the output of a printf() style formatting to an existing string.
166069  */
166070  static void fts3Appendf(
166071    int *pRc,                       /* IN/OUT: Error code */
166072    char **pz,                      /* IN/OUT: Pointer to string buffer */
166073    const char *zFormat,            /* Printf format string to append */
166074    ...                             /* Arguments for printf format string */
166075  ){
166076    if( *pRc==SQLITE_OK ){
166077      va_list ap;
166078      char *z;
166079      va_start(ap, zFormat);
166080      z = sqlite3_vmprintf(zFormat, ap);
166081      va_end(ap);
166082      if( z && *pz ){
166083        char *z2 = sqlite3_mprintf("%s%s", *pz, z);
166084        sqlite3_free(z);
166085        z = z2;
166086      }
166087      if( z==0 ) *pRc = SQLITE_NOMEM;
166088      sqlite3_free(*pz);
166089      *pz = z;
166090    }
166091  }
166092  
166093  /*
166094  ** Return a copy of input string zInput enclosed in double-quotes (") and
166095  ** with all double quote characters escaped. For example:
166096  **
166097  **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
166098  **
166099  ** The pointer returned points to memory obtained from sqlite3_malloc(). It
166100  ** is the callers responsibility to call sqlite3_free() to release this
166101  ** memory.
166102  */
166103  static char *fts3QuoteId(char const *zInput){
166104    sqlite3_int64 nRet;
166105    char *zRet;
166106    nRet = 2 + (int)strlen(zInput)*2 + 1;
166107    zRet = sqlite3_malloc64(nRet);
166108    if( zRet ){
166109      int i;
166110      char *z = zRet;
166111      *(z++) = '"';
166112      for(i=0; zInput[i]; i++){
166113        if( zInput[i]=='"' ) *(z++) = '"';
166114        *(z++) = zInput[i];
166115      }
166116      *(z++) = '"';
166117      *(z++) = '\0';
166118    }
166119    return zRet;
166120  }
166121  
166122  /*
166123  ** Return a list of comma separated SQL expressions and a FROM clause that 
166124  ** could be used in a SELECT statement such as the following:
166125  **
166126  **     SELECT <list of expressions> FROM %_content AS x ...
166127  **
166128  ** to return the docid, followed by each column of text data in order
166129  ** from left to write. If parameter zFunc is not NULL, then instead of
166130  ** being returned directly each column of text data is passed to an SQL
166131  ** function named zFunc first. For example, if zFunc is "unzip" and the
166132  ** table has the three user-defined columns "a", "b", and "c", the following
166133  ** string is returned:
166134  **
166135  **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
166136  **
166137  ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
166138  ** is the responsibility of the caller to eventually free it.
166139  **
166140  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
166141  ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
166142  ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
166143  ** no error occurs, *pRc is left unmodified.
166144  */
166145  static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
166146    char *zRet = 0;
166147    char *zFree = 0;
166148    char *zFunction;
166149    int i;
166150  
166151    if( p->zContentTbl==0 ){
166152      if( !zFunc ){
166153        zFunction = "";
166154      }else{
166155        zFree = zFunction = fts3QuoteId(zFunc);
166156      }
166157      fts3Appendf(pRc, &zRet, "docid");
166158      for(i=0; i<p->nColumn; i++){
166159        fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
166160      }
166161      if( p->zLanguageid ){
166162        fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
166163      }
166164      sqlite3_free(zFree);
166165    }else{
166166      fts3Appendf(pRc, &zRet, "rowid");
166167      for(i=0; i<p->nColumn; i++){
166168        fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
166169      }
166170      if( p->zLanguageid ){
166171        fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
166172      }
166173    }
166174    fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
166175        p->zDb,
166176        (p->zContentTbl ? p->zContentTbl : p->zName),
166177        (p->zContentTbl ? "" : "_content")
166178    );
166179    return zRet;
166180  }
166181  
166182  /*
166183  ** Return a list of N comma separated question marks, where N is the number
166184  ** of columns in the %_content table (one for the docid plus one for each
166185  ** user-defined text column).
166186  **
166187  ** If argument zFunc is not NULL, then all but the first question mark
166188  ** is preceded by zFunc and an open bracket, and followed by a closed
166189  ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
166190  ** user-defined text columns, the following string is returned:
166191  **
166192  **     "?, zip(?), zip(?), zip(?)"
166193  **
166194  ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
166195  ** is the responsibility of the caller to eventually free it.
166196  **
166197  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
166198  ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
166199  ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
166200  ** no error occurs, *pRc is left unmodified.
166201  */
166202  static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
166203    char *zRet = 0;
166204    char *zFree = 0;
166205    char *zFunction;
166206    int i;
166207  
166208    if( !zFunc ){
166209      zFunction = "";
166210    }else{
166211      zFree = zFunction = fts3QuoteId(zFunc);
166212    }
166213    fts3Appendf(pRc, &zRet, "?");
166214    for(i=0; i<p->nColumn; i++){
166215      fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
166216    }
166217    if( p->zLanguageid ){
166218      fts3Appendf(pRc, &zRet, ", ?");
166219    }
166220    sqlite3_free(zFree);
166221    return zRet;
166222  }
166223  
166224  /*
166225  ** This function interprets the string at (*pp) as a non-negative integer
166226  ** value. It reads the integer and sets *pnOut to the value read, then 
166227  ** sets *pp to point to the byte immediately following the last byte of
166228  ** the integer value.
166229  **
166230  ** Only decimal digits ('0'..'9') may be part of an integer value. 
166231  **
166232  ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
166233  ** the output value undefined. Otherwise SQLITE_OK is returned.
166234  **
166235  ** This function is used when parsing the "prefix=" FTS4 parameter.
166236  */
166237  static int fts3GobbleInt(const char **pp, int *pnOut){
166238    const int MAX_NPREFIX = 10000000;
166239    const char *p;                  /* Iterator pointer */
166240    int nInt = 0;                   /* Output value */
166241  
166242    for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
166243      nInt = nInt * 10 + (p[0] - '0');
166244      if( nInt>MAX_NPREFIX ){
166245        nInt = 0;
166246        break;
166247      }
166248    }
166249    if( p==*pp ) return SQLITE_ERROR;
166250    *pnOut = nInt;
166251    *pp = p;
166252    return SQLITE_OK;
166253  }
166254  
166255  /*
166256  ** This function is called to allocate an array of Fts3Index structures
166257  ** representing the indexes maintained by the current FTS table. FTS tables
166258  ** always maintain the main "terms" index, but may also maintain one or
166259  ** more "prefix" indexes, depending on the value of the "prefix=" parameter
166260  ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
166261  **
166262  ** Argument zParam is passed the value of the "prefix=" option if one was
166263  ** specified, or NULL otherwise.
166264  **
166265  ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
166266  ** the allocated array. *pnIndex is set to the number of elements in the
166267  ** array. If an error does occur, an SQLite error code is returned.
166268  **
166269  ** Regardless of whether or not an error is returned, it is the responsibility
166270  ** of the caller to call sqlite3_free() on the output array to free it.
166271  */
166272  static int fts3PrefixParameter(
166273    const char *zParam,             /* ABC in prefix=ABC parameter to parse */
166274    int *pnIndex,                   /* OUT: size of *apIndex[] array */
166275    struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
166276  ){
166277    struct Fts3Index *aIndex;       /* Allocated array */
166278    int nIndex = 1;                 /* Number of entries in array */
166279  
166280    if( zParam && zParam[0] ){
166281      const char *p;
166282      nIndex++;
166283      for(p=zParam; *p; p++){
166284        if( *p==',' ) nIndex++;
166285      }
166286    }
166287  
166288    aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
166289    *apIndex = aIndex;
166290    if( !aIndex ){
166291      return SQLITE_NOMEM;
166292    }
166293  
166294    memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
166295    if( zParam ){
166296      const char *p = zParam;
166297      int i;
166298      for(i=1; i<nIndex; i++){
166299        int nPrefix = 0;
166300        if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
166301        assert( nPrefix>=0 );
166302        if( nPrefix==0 ){
166303          nIndex--;
166304          i--;
166305        }else{
166306          aIndex[i].nPrefix = nPrefix;
166307        }
166308        p++;
166309      }
166310    }
166311  
166312    *pnIndex = nIndex;
166313    return SQLITE_OK;
166314  }
166315  
166316  /*
166317  ** This function is called when initializing an FTS4 table that uses the
166318  ** content=xxx option. It determines the number of and names of the columns
166319  ** of the new FTS4 table.
166320  **
166321  ** The third argument passed to this function is the value passed to the
166322  ** config=xxx option (i.e. "xxx"). This function queries the database for
166323  ** a table of that name. If found, the output variables are populated
166324  ** as follows:
166325  **
166326  **   *pnCol:   Set to the number of columns table xxx has,
166327  **
166328  **   *pnStr:   Set to the total amount of space required to store a copy
166329  **             of each columns name, including the nul-terminator.
166330  **
166331  **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
166332  **             the name of the corresponding column in table xxx. The array
166333  **             and its contents are allocated using a single allocation. It
166334  **             is the responsibility of the caller to free this allocation
166335  **             by eventually passing the *pazCol value to sqlite3_free().
166336  **
166337  ** If the table cannot be found, an error code is returned and the output
166338  ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
166339  ** returned (and the output variables are undefined).
166340  */
166341  static int fts3ContentColumns(
166342    sqlite3 *db,                    /* Database handle */
166343    const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
166344    const char *zTbl,               /* Name of content table */
166345    const char ***pazCol,           /* OUT: Malloc'd array of column names */
166346    int *pnCol,                     /* OUT: Size of array *pazCol */
166347    int *pnStr,                     /* OUT: Bytes of string content */
166348    char **pzErr                    /* OUT: error message */
166349  ){
166350    int rc = SQLITE_OK;             /* Return code */
166351    char *zSql;                     /* "SELECT *" statement on zTbl */  
166352    sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
166353  
166354    zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
166355    if( !zSql ){
166356      rc = SQLITE_NOMEM;
166357    }else{
166358      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
166359      if( rc!=SQLITE_OK ){
166360        sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
166361      }
166362    }
166363    sqlite3_free(zSql);
166364  
166365    if( rc==SQLITE_OK ){
166366      const char **azCol;           /* Output array */
166367      sqlite3_int64 nStr = 0;       /* Size of all column names (incl. 0x00) */
166368      int nCol;                     /* Number of table columns */
166369      int i;                        /* Used to iterate through columns */
166370  
166371      /* Loop through the returned columns. Set nStr to the number of bytes of
166372      ** space required to store a copy of each column name, including the
166373      ** nul-terminator byte.  */
166374      nCol = sqlite3_column_count(pStmt);
166375      for(i=0; i<nCol; i++){
166376        const char *zCol = sqlite3_column_name(pStmt, i);
166377        nStr += strlen(zCol) + 1;
166378      }
166379  
166380      /* Allocate and populate the array to return. */
166381      azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
166382      if( azCol==0 ){
166383        rc = SQLITE_NOMEM;
166384      }else{
166385        char *p = (char *)&azCol[nCol];
166386        for(i=0; i<nCol; i++){
166387          const char *zCol = sqlite3_column_name(pStmt, i);
166388          int n = (int)strlen(zCol)+1;
166389          memcpy(p, zCol, n);
166390          azCol[i] = p;
166391          p += n;
166392        }
166393      }
166394      sqlite3_finalize(pStmt);
166395  
166396      /* Set the output variables. */
166397      *pnCol = nCol;
166398      *pnStr = nStr;
166399      *pazCol = azCol;
166400    }
166401  
166402    return rc;
166403  }
166404  
166405  /*
166406  ** This function is the implementation of both the xConnect and xCreate
166407  ** methods of the FTS3 virtual table.
166408  **
166409  ** The argv[] array contains the following:
166410  **
166411  **   argv[0]   -> module name  ("fts3" or "fts4")
166412  **   argv[1]   -> database name
166413  **   argv[2]   -> table name
166414  **   argv[...] -> "column name" and other module argument fields.
166415  */
166416  static int fts3InitVtab(
166417    int isCreate,                   /* True for xCreate, false for xConnect */
166418    sqlite3 *db,                    /* The SQLite database connection */
166419    void *pAux,                     /* Hash table containing tokenizers */
166420    int argc,                       /* Number of elements in argv array */
166421    const char * const *argv,       /* xCreate/xConnect argument array */
166422    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
166423    char **pzErr                    /* Write any error message here */
166424  ){
166425    Fts3Hash *pHash = (Fts3Hash *)pAux;
166426    Fts3Table *p = 0;               /* Pointer to allocated vtab */
166427    int rc = SQLITE_OK;             /* Return code */
166428    int i;                          /* Iterator variable */
166429    sqlite3_int64 nByte;            /* Size of allocation used for *p */
166430    int iCol;                       /* Column index */
166431    int nString = 0;                /* Bytes required to hold all column names */
166432    int nCol = 0;                   /* Number of columns in the FTS table */
166433    char *zCsr;                     /* Space for holding column names */
166434    int nDb;                        /* Bytes required to hold database name */
166435    int nName;                      /* Bytes required to hold table name */
166436    int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
166437    const char **aCol;              /* Array of column names */
166438    sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
166439  
166440    int nIndex = 0;                 /* Size of aIndex[] array */
166441    struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
166442  
166443    /* The results of parsing supported FTS4 key=value options: */
166444    int bNoDocsize = 0;             /* True to omit %_docsize table */
166445    int bDescIdx = 0;               /* True to store descending indexes */
166446    char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
166447    char *zCompress = 0;            /* compress=? parameter (or NULL) */
166448    char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
166449    char *zContent = 0;             /* content=? parameter (or NULL) */
166450    char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
166451    char **azNotindexed = 0;        /* The set of notindexed= columns */
166452    int nNotindexed = 0;            /* Size of azNotindexed[] array */
166453  
166454    assert( strlen(argv[0])==4 );
166455    assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
166456         || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
166457    );
166458  
166459    nDb = (int)strlen(argv[1]) + 1;
166460    nName = (int)strlen(argv[2]) + 1;
166461  
166462    nByte = sizeof(const char *) * (argc-2);
166463    aCol = (const char **)sqlite3_malloc64(nByte);
166464    if( aCol ){
166465      memset((void*)aCol, 0, nByte);
166466      azNotindexed = (char **)sqlite3_malloc64(nByte);
166467    }
166468    if( azNotindexed ){
166469      memset(azNotindexed, 0, nByte);
166470    }
166471    if( !aCol || !azNotindexed ){
166472      rc = SQLITE_NOMEM;
166473      goto fts3_init_out;
166474    }
166475  
166476    /* Loop through all of the arguments passed by the user to the FTS3/4
166477    ** module (i.e. all the column names and special arguments). This loop
166478    ** does the following:
166479    **
166480    **   + Figures out the number of columns the FTSX table will have, and
166481    **     the number of bytes of space that must be allocated to store copies
166482    **     of the column names.
166483    **
166484    **   + If there is a tokenizer specification included in the arguments,
166485    **     initializes the tokenizer pTokenizer.
166486    */
166487    for(i=3; rc==SQLITE_OK && i<argc; i++){
166488      char const *z = argv[i];
166489      int nKey;
166490      char *zVal;
166491  
166492      /* Check if this is a tokenizer specification */
166493      if( !pTokenizer 
166494       && strlen(z)>8
166495       && 0==sqlite3_strnicmp(z, "tokenize", 8) 
166496       && 0==sqlite3Fts3IsIdChar(z[8])
166497      ){
166498        rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
166499      }
166500  
166501      /* Check if it is an FTS4 special argument. */
166502      else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
166503        struct Fts4Option {
166504          const char *zOpt;
166505          int nOpt;
166506        } aFts4Opt[] = {
166507          { "matchinfo",   9 },     /* 0 -> MATCHINFO */
166508          { "prefix",      6 },     /* 1 -> PREFIX */
166509          { "compress",    8 },     /* 2 -> COMPRESS */
166510          { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
166511          { "order",       5 },     /* 4 -> ORDER */
166512          { "content",     7 },     /* 5 -> CONTENT */
166513          { "languageid", 10 },     /* 6 -> LANGUAGEID */
166514          { "notindexed", 10 }      /* 7 -> NOTINDEXED */
166515        };
166516  
166517        int iOpt;
166518        if( !zVal ){
166519          rc = SQLITE_NOMEM;
166520        }else{
166521          for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
166522            struct Fts4Option *pOp = &aFts4Opt[iOpt];
166523            if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
166524              break;
166525            }
166526          }
166527          switch( iOpt ){
166528            case 0:               /* MATCHINFO */
166529              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
166530                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
166531                rc = SQLITE_ERROR;
166532              }
166533              bNoDocsize = 1;
166534              break;
166535  
166536            case 1:               /* PREFIX */
166537              sqlite3_free(zPrefix);
166538              zPrefix = zVal;
166539              zVal = 0;
166540              break;
166541  
166542            case 2:               /* COMPRESS */
166543              sqlite3_free(zCompress);
166544              zCompress = zVal;
166545              zVal = 0;
166546              break;
166547  
166548            case 3:               /* UNCOMPRESS */
166549              sqlite3_free(zUncompress);
166550              zUncompress = zVal;
166551              zVal = 0;
166552              break;
166553  
166554            case 4:               /* ORDER */
166555              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
166556               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
166557              ){
166558                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
166559                rc = SQLITE_ERROR;
166560              }
166561              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
166562              break;
166563  
166564            case 5:              /* CONTENT */
166565              sqlite3_free(zContent);
166566              zContent = zVal;
166567              zVal = 0;
166568              break;
166569  
166570            case 6:              /* LANGUAGEID */
166571              assert( iOpt==6 );
166572              sqlite3_free(zLanguageid);
166573              zLanguageid = zVal;
166574              zVal = 0;
166575              break;
166576  
166577            case 7:              /* NOTINDEXED */
166578              azNotindexed[nNotindexed++] = zVal;
166579              zVal = 0;
166580              break;
166581  
166582            default:
166583              assert( iOpt==SizeofArray(aFts4Opt) );
166584              sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
166585              rc = SQLITE_ERROR;
166586              break;
166587          }
166588          sqlite3_free(zVal);
166589        }
166590      }
166591  
166592      /* Otherwise, the argument is a column name. */
166593      else {
166594        nString += (int)(strlen(z) + 1);
166595        aCol[nCol++] = z;
166596      }
166597    }
166598  
166599    /* If a content=xxx option was specified, the following:
166600    **
166601    **   1. Ignore any compress= and uncompress= options.
166602    **
166603    **   2. If no column names were specified as part of the CREATE VIRTUAL
166604    **      TABLE statement, use all columns from the content table.
166605    */
166606    if( rc==SQLITE_OK && zContent ){
166607      sqlite3_free(zCompress); 
166608      sqlite3_free(zUncompress); 
166609      zCompress = 0;
166610      zUncompress = 0;
166611      if( nCol==0 ){
166612        sqlite3_free((void*)aCol); 
166613        aCol = 0;
166614        rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
166615  
166616        /* If a languageid= option was specified, remove the language id
166617        ** column from the aCol[] array. */ 
166618        if( rc==SQLITE_OK && zLanguageid ){
166619          int j;
166620          for(j=0; j<nCol; j++){
166621            if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
166622              int k;
166623              for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
166624              nCol--;
166625              break;
166626            }
166627          }
166628        }
166629      }
166630    }
166631    if( rc!=SQLITE_OK ) goto fts3_init_out;
166632  
166633    if( nCol==0 ){
166634      assert( nString==0 );
166635      aCol[0] = "content";
166636      nString = 8;
166637      nCol = 1;
166638    }
166639  
166640    if( pTokenizer==0 ){
166641      rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
166642      if( rc!=SQLITE_OK ) goto fts3_init_out;
166643    }
166644    assert( pTokenizer );
166645  
166646    rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
166647    if( rc==SQLITE_ERROR ){
166648      assert( zPrefix );
166649      sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
166650    }
166651    if( rc!=SQLITE_OK ) goto fts3_init_out;
166652  
166653    /* Allocate and populate the Fts3Table structure. */
166654    nByte = sizeof(Fts3Table) +                  /* Fts3Table */
166655            nCol * sizeof(char *) +              /* azColumn */
166656            nIndex * sizeof(struct Fts3Index) +  /* aIndex */
166657            nCol * sizeof(u8) +                  /* abNotindexed */
166658            nName +                              /* zName */
166659            nDb +                                /* zDb */
166660            nString;                             /* Space for azColumn strings */
166661    p = (Fts3Table*)sqlite3_malloc64(nByte);
166662    if( p==0 ){
166663      rc = SQLITE_NOMEM;
166664      goto fts3_init_out;
166665    }
166666    memset(p, 0, nByte);
166667    p->db = db;
166668    p->nColumn = nCol;
166669    p->nPendingData = 0;
166670    p->azColumn = (char **)&p[1];
166671    p->pTokenizer = pTokenizer;
166672    p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
166673    p->bHasDocsize = (isFts4 && bNoDocsize==0);
166674    p->bHasStat = (u8)isFts4;
166675    p->bFts4 = (u8)isFts4;
166676    p->bDescIdx = (u8)bDescIdx;
166677    p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
166678    p->zContentTbl = zContent;
166679    p->zLanguageid = zLanguageid;
166680    zContent = 0;
166681    zLanguageid = 0;
166682    TESTONLY( p->inTransaction = -1 );
166683    TESTONLY( p->mxSavepoint = -1 );
166684  
166685    p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
166686    memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
166687    p->nIndex = nIndex;
166688    for(i=0; i<nIndex; i++){
166689      fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
166690    }
166691    p->abNotindexed = (u8 *)&p->aIndex[nIndex];
166692  
166693    /* Fill in the zName and zDb fields of the vtab structure. */
166694    zCsr = (char *)&p->abNotindexed[nCol];
166695    p->zName = zCsr;
166696    memcpy(zCsr, argv[2], nName);
166697    zCsr += nName;
166698    p->zDb = zCsr;
166699    memcpy(zCsr, argv[1], nDb);
166700    zCsr += nDb;
166701  
166702    /* Fill in the azColumn array */
166703    for(iCol=0; iCol<nCol; iCol++){
166704      char *z; 
166705      int n = 0;
166706      z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
166707      if( n>0 ){
166708        memcpy(zCsr, z, n);
166709      }
166710      zCsr[n] = '\0';
166711      sqlite3Fts3Dequote(zCsr);
166712      p->azColumn[iCol] = zCsr;
166713      zCsr += n+1;
166714      assert( zCsr <= &((char *)p)[nByte] );
166715    }
166716  
166717    /* Fill in the abNotindexed array */
166718    for(iCol=0; iCol<nCol; iCol++){
166719      int n = (int)strlen(p->azColumn[iCol]);
166720      for(i=0; i<nNotindexed; i++){
166721        char *zNot = azNotindexed[i];
166722        if( zNot && n==(int)strlen(zNot)
166723         && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) 
166724        ){
166725          p->abNotindexed[iCol] = 1;
166726          sqlite3_free(zNot);
166727          azNotindexed[i] = 0;
166728        }
166729      }
166730    }
166731    for(i=0; i<nNotindexed; i++){
166732      if( azNotindexed[i] ){
166733        sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
166734        rc = SQLITE_ERROR;
166735      }
166736    }
166737  
166738    if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
166739      char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
166740      rc = SQLITE_ERROR;
166741      sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
166742    }
166743    p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
166744    p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
166745    if( rc!=SQLITE_OK ) goto fts3_init_out;
166746  
166747    /* If this is an xCreate call, create the underlying tables in the 
166748    ** database. TODO: For xConnect(), it could verify that said tables exist.
166749    */
166750    if( isCreate ){
166751      rc = fts3CreateTables(p);
166752    }
166753  
166754    /* Check to see if a legacy fts3 table has been "upgraded" by the
166755    ** addition of a %_stat table so that it can use incremental merge.
166756    */
166757    if( !isFts4 && !isCreate ){
166758      p->bHasStat = 2;
166759    }
166760  
166761    /* Figure out the page-size for the database. This is required in order to
166762    ** estimate the cost of loading large doclists from the database.  */
166763    fts3DatabasePageSize(&rc, p);
166764    p->nNodeSize = p->nPgsz-35;
166765  
166766    /* Declare the table schema to SQLite. */
166767    fts3DeclareVtab(&rc, p);
166768  
166769  fts3_init_out:
166770    sqlite3_free(zPrefix);
166771    sqlite3_free(aIndex);
166772    sqlite3_free(zCompress);
166773    sqlite3_free(zUncompress);
166774    sqlite3_free(zContent);
166775    sqlite3_free(zLanguageid);
166776    for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
166777    sqlite3_free((void *)aCol);
166778    sqlite3_free((void *)azNotindexed);
166779    if( rc!=SQLITE_OK ){
166780      if( p ){
166781        fts3DisconnectMethod((sqlite3_vtab *)p);
166782      }else if( pTokenizer ){
166783        pTokenizer->pModule->xDestroy(pTokenizer);
166784      }
166785    }else{
166786      assert( p->pSegments==0 );
166787      *ppVTab = &p->base;
166788    }
166789    return rc;
166790  }
166791  
166792  /*
166793  ** The xConnect() and xCreate() methods for the virtual table. All the
166794  ** work is done in function fts3InitVtab().
166795  */
166796  static int fts3ConnectMethod(
166797    sqlite3 *db,                    /* Database connection */
166798    void *pAux,                     /* Pointer to tokenizer hash table */
166799    int argc,                       /* Number of elements in argv array */
166800    const char * const *argv,       /* xCreate/xConnect argument array */
166801    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
166802    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
166803  ){
166804    return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
166805  }
166806  static int fts3CreateMethod(
166807    sqlite3 *db,                    /* Database connection */
166808    void *pAux,                     /* Pointer to tokenizer hash table */
166809    int argc,                       /* Number of elements in argv array */
166810    const char * const *argv,       /* xCreate/xConnect argument array */
166811    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
166812    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
166813  ){
166814    return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
166815  }
166816  
166817  /*
166818  ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
166819  ** extension is currently being used by a version of SQLite too old to
166820  ** support estimatedRows. In that case this function is a no-op.
166821  */
166822  static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
166823  #if SQLITE_VERSION_NUMBER>=3008002
166824    if( sqlite3_libversion_number()>=3008002 ){
166825      pIdxInfo->estimatedRows = nRow;
166826    }
166827  #endif
166828  }
166829  
166830  /*
166831  ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
166832  ** extension is currently being used by a version of SQLite too old to
166833  ** support index-info flags. In that case this function is a no-op.
166834  */
166835  static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
166836  #if SQLITE_VERSION_NUMBER>=3008012
166837    if( sqlite3_libversion_number()>=3008012 ){
166838      pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
166839    }
166840  #endif
166841  }
166842  
166843  /* 
166844  ** Implementation of the xBestIndex method for FTS3 tables. There
166845  ** are three possible strategies, in order of preference:
166846  **
166847  **   1. Direct lookup by rowid or docid. 
166848  **   2. Full-text search using a MATCH operator on a non-docid column.
166849  **   3. Linear scan of %_content table.
166850  */
166851  static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
166852    Fts3Table *p = (Fts3Table *)pVTab;
166853    int i;                          /* Iterator variable */
166854    int iCons = -1;                 /* Index of constraint to use */
166855  
166856    int iLangidCons = -1;           /* Index of langid=x constraint, if present */
166857    int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
166858    int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
166859    int iIdx;
166860  
166861    /* By default use a full table scan. This is an expensive option,
166862    ** so search through the constraints to see if a more efficient 
166863    ** strategy is possible.
166864    */
166865    pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
166866    pInfo->estimatedCost = 5000000;
166867    for(i=0; i<pInfo->nConstraint; i++){
166868      int bDocid;                 /* True if this constraint is on docid */
166869      struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
166870      if( pCons->usable==0 ){
166871        if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
166872          /* There exists an unusable MATCH constraint. This means that if
166873          ** the planner does elect to use the results of this call as part
166874          ** of the overall query plan the user will see an "unable to use
166875          ** function MATCH in the requested context" error. To discourage
166876          ** this, return a very high cost here.  */
166877          pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
166878          pInfo->estimatedCost = 1e50;
166879          fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
166880          return SQLITE_OK;
166881        }
166882        continue;
166883      }
166884  
166885      bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
166886  
166887      /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
166888      if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
166889        pInfo->idxNum = FTS3_DOCID_SEARCH;
166890        pInfo->estimatedCost = 1.0;
166891        iCons = i;
166892      }
166893  
166894      /* A MATCH constraint. Use a full-text search.
166895      **
166896      ** If there is more than one MATCH constraint available, use the first
166897      ** one encountered. If there is both a MATCH constraint and a direct
166898      ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
166899      ** though the rowid/docid lookup is faster than a MATCH query, selecting
166900      ** it would lead to an "unable to use function MATCH in the requested 
166901      ** context" error.
166902      */
166903      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
166904       && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
166905      ){
166906        pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
166907        pInfo->estimatedCost = 2.0;
166908        iCons = i;
166909      }
166910  
166911      /* Equality constraint on the langid column */
166912      if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
166913       && pCons->iColumn==p->nColumn + 2
166914      ){
166915        iLangidCons = i;
166916      }
166917  
166918      if( bDocid ){
166919        switch( pCons->op ){
166920          case SQLITE_INDEX_CONSTRAINT_GE:
166921          case SQLITE_INDEX_CONSTRAINT_GT:
166922            iDocidGe = i;
166923            break;
166924  
166925          case SQLITE_INDEX_CONSTRAINT_LE:
166926          case SQLITE_INDEX_CONSTRAINT_LT:
166927            iDocidLe = i;
166928            break;
166929        }
166930      }
166931    }
166932  
166933    /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
166934    if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
166935  
166936    iIdx = 1;
166937    if( iCons>=0 ){
166938      pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
166939      pInfo->aConstraintUsage[iCons].omit = 1;
166940    } 
166941    if( iLangidCons>=0 ){
166942      pInfo->idxNum |= FTS3_HAVE_LANGID;
166943      pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
166944    } 
166945    if( iDocidGe>=0 ){
166946      pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
166947      pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
166948    } 
166949    if( iDocidLe>=0 ){
166950      pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
166951      pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
166952    } 
166953  
166954    /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
166955    ** docid) order. Both ascending and descending are possible. 
166956    */
166957    if( pInfo->nOrderBy==1 ){
166958      struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
166959      if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
166960        if( pOrder->desc ){
166961          pInfo->idxStr = "DESC";
166962        }else{
166963          pInfo->idxStr = "ASC";
166964        }
166965        pInfo->orderByConsumed = 1;
166966      }
166967    }
166968  
166969    assert( p->pSegments==0 );
166970    return SQLITE_OK;
166971  }
166972  
166973  /*
166974  ** Implementation of xOpen method.
166975  */
166976  static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
166977    sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
166978  
166979    UNUSED_PARAMETER(pVTab);
166980  
166981    /* Allocate a buffer large enough for an Fts3Cursor structure. If the
166982    ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
166983    ** if the allocation fails, return SQLITE_NOMEM.
166984    */
166985    *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
166986    if( !pCsr ){
166987      return SQLITE_NOMEM;
166988    }
166989    memset(pCsr, 0, sizeof(Fts3Cursor));
166990    return SQLITE_OK;
166991  }
166992  
166993  /*
166994  ** Finalize the statement handle at pCsr->pStmt.
166995  **
166996  ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
166997  ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
166998  ** pointer there instead of finalizing it.
166999  */
167000  static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
167001    if( pCsr->bSeekStmt ){
167002      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
167003      if( p->pSeekStmt==0 ){
167004        p->pSeekStmt = pCsr->pStmt;
167005        sqlite3_reset(pCsr->pStmt);
167006        pCsr->pStmt = 0;
167007      }
167008      pCsr->bSeekStmt = 0;
167009    }
167010    sqlite3_finalize(pCsr->pStmt);
167011  }
167012  
167013  /*
167014  ** Free all resources currently held by the cursor passed as the only
167015  ** argument.
167016  */
167017  static void fts3ClearCursor(Fts3Cursor *pCsr){
167018    fts3CursorFinalizeStmt(pCsr);
167019    sqlite3Fts3FreeDeferredTokens(pCsr);
167020    sqlite3_free(pCsr->aDoclist);
167021    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
167022    sqlite3Fts3ExprFree(pCsr->pExpr);
167023    memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
167024  }
167025  
167026  /*
167027  ** Close the cursor.  For additional information see the documentation
167028  ** on the xClose method of the virtual table interface.
167029  */
167030  static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
167031    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
167032    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
167033    fts3ClearCursor(pCsr);
167034    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
167035    sqlite3_free(pCsr);
167036    return SQLITE_OK;
167037  }
167038  
167039  /*
167040  ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
167041  ** compose and prepare an SQL statement of the form:
167042  **
167043  **    "SELECT <columns> FROM %_content WHERE rowid = ?"
167044  **
167045  ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
167046  ** it. If an error occurs, return an SQLite error code.
167047  */
167048  static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
167049    int rc = SQLITE_OK;
167050    if( pCsr->pStmt==0 ){
167051      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
167052      char *zSql;
167053      if( p->pSeekStmt ){
167054        pCsr->pStmt = p->pSeekStmt;
167055        p->pSeekStmt = 0;
167056      }else{
167057        zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
167058        if( !zSql ) return SQLITE_NOMEM;
167059        rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
167060        sqlite3_free(zSql);
167061      }
167062      if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
167063    }
167064    return rc;
167065  }
167066  
167067  /*
167068  ** Position the pCsr->pStmt statement so that it is on the row
167069  ** of the %_content table that contains the last match.  Return
167070  ** SQLITE_OK on success.  
167071  */
167072  static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
167073    int rc = SQLITE_OK;
167074    if( pCsr->isRequireSeek ){
167075      rc = fts3CursorSeekStmt(pCsr);
167076      if( rc==SQLITE_OK ){
167077        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
167078        pCsr->isRequireSeek = 0;
167079        if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
167080          return SQLITE_OK;
167081        }else{
167082          rc = sqlite3_reset(pCsr->pStmt);
167083          if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
167084            /* If no row was found and no error has occurred, then the %_content
167085            ** table is missing a row that is present in the full-text index.
167086            ** The data structures are corrupt.  */
167087            rc = FTS_CORRUPT_VTAB;
167088            pCsr->isEof = 1;
167089          }
167090        }
167091      }
167092    }
167093  
167094    if( rc!=SQLITE_OK && pContext ){
167095      sqlite3_result_error_code(pContext, rc);
167096    }
167097    return rc;
167098  }
167099  
167100  /*
167101  ** This function is used to process a single interior node when searching
167102  ** a b-tree for a term or term prefix. The node data is passed to this 
167103  ** function via the zNode/nNode parameters. The term to search for is
167104  ** passed in zTerm/nTerm.
167105  **
167106  ** If piFirst is not NULL, then this function sets *piFirst to the blockid
167107  ** of the child node that heads the sub-tree that may contain the term.
167108  **
167109  ** If piLast is not NULL, then *piLast is set to the right-most child node
167110  ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
167111  ** a prefix.
167112  **
167113  ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
167114  */
167115  static int fts3ScanInteriorNode(
167116    const char *zTerm,              /* Term to select leaves for */
167117    int nTerm,                      /* Size of term zTerm in bytes */
167118    const char *zNode,              /* Buffer containing segment interior node */
167119    int nNode,                      /* Size of buffer at zNode */
167120    sqlite3_int64 *piFirst,         /* OUT: Selected child node */
167121    sqlite3_int64 *piLast           /* OUT: Selected child node */
167122  ){
167123    int rc = SQLITE_OK;             /* Return code */
167124    const char *zCsr = zNode;       /* Cursor to iterate through node */
167125    const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
167126    char *zBuffer = 0;              /* Buffer to load terms into */
167127    i64 nAlloc = 0;                 /* Size of allocated buffer */
167128    int isFirstTerm = 1;            /* True when processing first term on page */
167129    sqlite3_int64 iChild;           /* Block id of child node to descend to */
167130  
167131    /* Skip over the 'height' varint that occurs at the start of every 
167132    ** interior node. Then load the blockid of the left-child of the b-tree
167133    ** node into variable iChild.  
167134    **
167135    ** Even if the data structure on disk is corrupted, this (reading two
167136    ** varints from the buffer) does not risk an overread. If zNode is a
167137    ** root node, then the buffer comes from a SELECT statement. SQLite does
167138    ** not make this guarantee explicitly, but in practice there are always
167139    ** either more than 20 bytes of allocated space following the nNode bytes of
167140    ** contents, or two zero bytes. Or, if the node is read from the %_segments
167141    ** table, then there are always 20 bytes of zeroed padding following the
167142    ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
167143    */
167144    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
167145    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
167146    if( zCsr>zEnd ){
167147      return FTS_CORRUPT_VTAB;
167148    }
167149    
167150    while( zCsr<zEnd && (piFirst || piLast) ){
167151      int cmp;                      /* memcmp() result */
167152      int nSuffix;                  /* Size of term suffix */
167153      int nPrefix = 0;              /* Size of term prefix */
167154      int nBuffer;                  /* Total term size */
167155    
167156      /* Load the next term on the node into zBuffer. Use realloc() to expand
167157      ** the size of zBuffer if required.  */
167158      if( !isFirstTerm ){
167159        zCsr += fts3GetVarint32(zCsr, &nPrefix);
167160      }
167161      isFirstTerm = 0;
167162      zCsr += fts3GetVarint32(zCsr, &nSuffix);
167163      
167164      assert( nPrefix>=0 && nSuffix>=0 );
167165      if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr ){
167166        rc = FTS_CORRUPT_VTAB;
167167        goto finish_scan;
167168      }
167169      if( (i64)nPrefix+nSuffix>nAlloc ){
167170        char *zNew;
167171        nAlloc = ((i64)nPrefix+nSuffix) * 2;
167172        zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
167173        if( !zNew ){
167174          rc = SQLITE_NOMEM;
167175          goto finish_scan;
167176        }
167177        zBuffer = zNew;
167178      }
167179      assert( zBuffer );
167180      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
167181      nBuffer = nPrefix + nSuffix;
167182      zCsr += nSuffix;
167183  
167184      /* Compare the term we are searching for with the term just loaded from
167185      ** the interior node. If the specified term is greater than or equal
167186      ** to the term from the interior node, then all terms on the sub-tree 
167187      ** headed by node iChild are smaller than zTerm. No need to search 
167188      ** iChild.
167189      **
167190      ** If the interior node term is larger than the specified term, then
167191      ** the tree headed by iChild may contain the specified term.
167192      */
167193      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
167194      if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
167195        *piFirst = iChild;
167196        piFirst = 0;
167197      }
167198  
167199      if( piLast && cmp<0 ){
167200        *piLast = iChild;
167201        piLast = 0;
167202      }
167203  
167204      iChild++;
167205    };
167206  
167207    if( piFirst ) *piFirst = iChild;
167208    if( piLast ) *piLast = iChild;
167209  
167210   finish_scan:
167211    sqlite3_free(zBuffer);
167212    return rc;
167213  }
167214  
167215  
167216  /*
167217  ** The buffer pointed to by argument zNode (size nNode bytes) contains an
167218  ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
167219  ** contains a term. This function searches the sub-tree headed by the zNode
167220  ** node for the range of leaf nodes that may contain the specified term
167221  ** or terms for which the specified term is a prefix.
167222  **
167223  ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
167224  ** left-most leaf node in the tree that may contain the specified term.
167225  ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
167226  ** right-most leaf node that may contain a term for which the specified
167227  ** term is a prefix.
167228  **
167229  ** It is possible that the range of returned leaf nodes does not contain 
167230  ** the specified term or any terms for which it is a prefix. However, if the 
167231  ** segment does contain any such terms, they are stored within the identified
167232  ** range. Because this function only inspects interior segment nodes (and
167233  ** never loads leaf nodes into memory), it is not possible to be sure.
167234  **
167235  ** If an error occurs, an error code other than SQLITE_OK is returned.
167236  */ 
167237  static int fts3SelectLeaf(
167238    Fts3Table *p,                   /* Virtual table handle */
167239    const char *zTerm,              /* Term to select leaves for */
167240    int nTerm,                      /* Size of term zTerm in bytes */
167241    const char *zNode,              /* Buffer containing segment interior node */
167242    int nNode,                      /* Size of buffer at zNode */
167243    sqlite3_int64 *piLeaf,          /* Selected leaf node */
167244    sqlite3_int64 *piLeaf2          /* Selected leaf node */
167245  ){
167246    int rc = SQLITE_OK;             /* Return code */
167247    int iHeight;                    /* Height of this node in tree */
167248  
167249    assert( piLeaf || piLeaf2 );
167250  
167251    fts3GetVarint32(zNode, &iHeight);
167252    rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
167253    assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
167254  
167255    if( rc==SQLITE_OK && iHeight>1 ){
167256      char *zBlob = 0;              /* Blob read from %_segments table */
167257      int nBlob = 0;                /* Size of zBlob in bytes */
167258  
167259      if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
167260        rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
167261        if( rc==SQLITE_OK ){
167262          rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
167263        }
167264        sqlite3_free(zBlob);
167265        piLeaf = 0;
167266        zBlob = 0;
167267      }
167268  
167269      if( rc==SQLITE_OK ){
167270        rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
167271      }
167272      if( rc==SQLITE_OK ){
167273        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
167274      }
167275      sqlite3_free(zBlob);
167276    }
167277  
167278    return rc;
167279  }
167280  
167281  /*
167282  ** This function is used to create delta-encoded serialized lists of FTS3 
167283  ** varints. Each call to this function appends a single varint to a list.
167284  */
167285  static void fts3PutDeltaVarint(
167286    char **pp,                      /* IN/OUT: Output pointer */
167287    sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
167288    sqlite3_int64 iVal              /* Write this value to the list */
167289  ){
167290    assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
167291    *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
167292    *piPrev = iVal;
167293  }
167294  
167295  /*
167296  ** When this function is called, *ppPoslist is assumed to point to the 
167297  ** start of a position-list. After it returns, *ppPoslist points to the
167298  ** first byte after the position-list.
167299  **
167300  ** A position list is list of positions (delta encoded) and columns for 
167301  ** a single document record of a doclist.  So, in other words, this
167302  ** routine advances *ppPoslist so that it points to the next docid in
167303  ** the doclist, or to the first byte past the end of the doclist.
167304  **
167305  ** If pp is not NULL, then the contents of the position list are copied
167306  ** to *pp. *pp is set to point to the first byte past the last byte copied
167307  ** before this function returns.
167308  */
167309  static void fts3PoslistCopy(char **pp, char **ppPoslist){
167310    char *pEnd = *ppPoslist;
167311    char c = 0;
167312  
167313    /* The end of a position list is marked by a zero encoded as an FTS3 
167314    ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
167315    ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
167316    ** of some other, multi-byte, value.
167317    **
167318    ** The following while-loop moves pEnd to point to the first byte that is not 
167319    ** immediately preceded by a byte with the 0x80 bit set. Then increments
167320    ** pEnd once more so that it points to the byte immediately following the
167321    ** last byte in the position-list.
167322    */
167323    while( *pEnd | c ){
167324      c = *pEnd++ & 0x80;
167325      testcase( c!=0 && (*pEnd)==0 );
167326    }
167327    pEnd++;  /* Advance past the POS_END terminator byte */
167328  
167329    if( pp ){
167330      int n = (int)(pEnd - *ppPoslist);
167331      char *p = *pp;
167332      memcpy(p, *ppPoslist, n);
167333      p += n;
167334      *pp = p;
167335    }
167336    *ppPoslist = pEnd;
167337  }
167338  
167339  /*
167340  ** When this function is called, *ppPoslist is assumed to point to the 
167341  ** start of a column-list. After it returns, *ppPoslist points to the
167342  ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
167343  **
167344  ** A column-list is list of delta-encoded positions for a single column
167345  ** within a single document within a doclist.
167346  **
167347  ** The column-list is terminated either by a POS_COLUMN varint (1) or
167348  ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
167349  ** the POS_COLUMN or POS_END that terminates the column-list.
167350  **
167351  ** If pp is not NULL, then the contents of the column-list are copied
167352  ** to *pp. *pp is set to point to the first byte past the last byte copied
167353  ** before this function returns.  The POS_COLUMN or POS_END terminator
167354  ** is not copied into *pp.
167355  */
167356  static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
167357    char *pEnd = *ppPoslist;
167358    char c = 0;
167359  
167360    /* A column-list is terminated by either a 0x01 or 0x00 byte that is
167361    ** not part of a multi-byte varint.
167362    */
167363    while( 0xFE & (*pEnd | c) ){
167364      c = *pEnd++ & 0x80;
167365      testcase( c!=0 && ((*pEnd)&0xfe)==0 );
167366    }
167367    if( pp ){
167368      int n = (int)(pEnd - *ppPoslist);
167369      char *p = *pp;
167370      memcpy(p, *ppPoslist, n);
167371      p += n;
167372      *pp = p;
167373    }
167374    *ppPoslist = pEnd;
167375  }
167376  
167377  /*
167378  ** Value used to signify the end of an position-list. This is safe because
167379  ** it is not possible to have a document with 2^31 terms.
167380  */
167381  #define POSITION_LIST_END 0x7fffffff
167382  
167383  /*
167384  ** This function is used to help parse position-lists. When this function is
167385  ** called, *pp may point to the start of the next varint in the position-list
167386  ** being parsed, or it may point to 1 byte past the end of the position-list
167387  ** (in which case **pp will be a terminator bytes POS_END (0) or
167388  ** (1)).
167389  **
167390  ** If *pp points past the end of the current position-list, set *pi to 
167391  ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
167392  ** increment the current value of *pi by the value read, and set *pp to
167393  ** point to the next value before returning.
167394  **
167395  ** Before calling this routine *pi must be initialized to the value of
167396  ** the previous position, or zero if we are reading the first position
167397  ** in the position-list.  Because positions are delta-encoded, the value
167398  ** of the previous position is needed in order to compute the value of
167399  ** the next position.
167400  */
167401  static void fts3ReadNextPos(
167402    char **pp,                    /* IN/OUT: Pointer into position-list buffer */
167403    sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
167404  ){
167405    if( (**pp)&0xFE ){
167406      fts3GetDeltaVarint(pp, pi);
167407      *pi -= 2;
167408    }else{
167409      *pi = POSITION_LIST_END;
167410    }
167411  }
167412  
167413  /*
167414  ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
167415  ** the value of iCol encoded as a varint to *pp.   This will start a new
167416  ** column list.
167417  **
167418  ** Set *pp to point to the byte just after the last byte written before 
167419  ** returning (do not modify it if iCol==0). Return the total number of bytes
167420  ** written (0 if iCol==0).
167421  */
167422  static int fts3PutColNumber(char **pp, int iCol){
167423    int n = 0;                      /* Number of bytes written */
167424    if( iCol ){
167425      char *p = *pp;                /* Output pointer */
167426      n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
167427      *p = 0x01;
167428      *pp = &p[n];
167429    }
167430    return n;
167431  }
167432  
167433  /*
167434  ** Compute the union of two position lists.  The output written
167435  ** into *pp contains all positions of both *pp1 and *pp2 in sorted
167436  ** order and with any duplicates removed.  All pointers are
167437  ** updated appropriately.   The caller is responsible for insuring
167438  ** that there is enough space in *pp to hold the complete output.
167439  */
167440  static int fts3PoslistMerge(
167441    char **pp,                      /* Output buffer */
167442    char **pp1,                     /* Left input list */
167443    char **pp2                      /* Right input list */
167444  ){
167445    char *p = *pp;
167446    char *p1 = *pp1;
167447    char *p2 = *pp2;
167448  
167449    while( *p1 || *p2 ){
167450      int iCol1;         /* The current column index in pp1 */
167451      int iCol2;         /* The current column index in pp2 */
167452  
167453      if( *p1==POS_COLUMN ){ 
167454        fts3GetVarint32(&p1[1], &iCol1);
167455        if( iCol1==0 ) return FTS_CORRUPT_VTAB;
167456      }
167457      else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
167458      else iCol1 = 0;
167459  
167460      if( *p2==POS_COLUMN ){
167461        fts3GetVarint32(&p2[1], &iCol2);
167462        if( iCol2==0 ) return FTS_CORRUPT_VTAB;
167463      }
167464      else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
167465      else iCol2 = 0;
167466  
167467      if( iCol1==iCol2 ){
167468        sqlite3_int64 i1 = 0;       /* Last position from pp1 */
167469        sqlite3_int64 i2 = 0;       /* Last position from pp2 */
167470        sqlite3_int64 iPrev = 0;
167471        int n = fts3PutColNumber(&p, iCol1);
167472        p1 += n;
167473        p2 += n;
167474  
167475        /* At this point, both p1 and p2 point to the start of column-lists
167476        ** for the same column (the column with index iCol1 and iCol2).
167477        ** A column-list is a list of non-negative delta-encoded varints, each 
167478        ** incremented by 2 before being stored. Each list is terminated by a
167479        ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
167480        ** and writes the results to buffer p. p is left pointing to the byte
167481        ** after the list written. No terminator (POS_END or POS_COLUMN) is
167482        ** written to the output.
167483        */
167484        fts3GetDeltaVarint(&p1, &i1);
167485        fts3GetDeltaVarint(&p2, &i2);
167486        do {
167487          fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
167488          iPrev -= 2;
167489          if( i1==i2 ){
167490            fts3ReadNextPos(&p1, &i1);
167491            fts3ReadNextPos(&p2, &i2);
167492          }else if( i1<i2 ){
167493            fts3ReadNextPos(&p1, &i1);
167494          }else{
167495            fts3ReadNextPos(&p2, &i2);
167496          }
167497        }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
167498      }else if( iCol1<iCol2 ){
167499        p1 += fts3PutColNumber(&p, iCol1);
167500        fts3ColumnlistCopy(&p, &p1);
167501      }else{
167502        p2 += fts3PutColNumber(&p, iCol2);
167503        fts3ColumnlistCopy(&p, &p2);
167504      }
167505    }
167506  
167507    *p++ = POS_END;
167508    *pp = p;
167509    *pp1 = p1 + 1;
167510    *pp2 = p2 + 1;
167511    return SQLITE_OK;
167512  }
167513  
167514  /*
167515  ** This function is used to merge two position lists into one. When it is
167516  ** called, *pp1 and *pp2 must both point to position lists. A position-list is
167517  ** the part of a doclist that follows each document id. For example, if a row
167518  ** contains:
167519  **
167520  **     'a b c'|'x y z'|'a b b a'
167521  **
167522  ** Then the position list for this row for token 'b' would consist of:
167523  **
167524  **     0x02 0x01 0x02 0x03 0x03 0x00
167525  **
167526  ** When this function returns, both *pp1 and *pp2 are left pointing to the
167527  ** byte following the 0x00 terminator of their respective position lists.
167528  **
167529  ** If isSaveLeft is 0, an entry is added to the output position list for 
167530  ** each position in *pp2 for which there exists one or more positions in
167531  ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
167532  ** when the *pp1 token appears before the *pp2 token, but not more than nToken
167533  ** slots before it.
167534  **
167535  ** e.g. nToken==1 searches for adjacent positions.
167536  */
167537  static int fts3PoslistPhraseMerge(
167538    char **pp,                      /* IN/OUT: Preallocated output buffer */
167539    int nToken,                     /* Maximum difference in token positions */
167540    int isSaveLeft,                 /* Save the left position */
167541    int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
167542    char **pp1,                     /* IN/OUT: Left input list */
167543    char **pp2                      /* IN/OUT: Right input list */
167544  ){
167545    char *p = *pp;
167546    char *p1 = *pp1;
167547    char *p2 = *pp2;
167548    int iCol1 = 0;
167549    int iCol2 = 0;
167550  
167551    /* Never set both isSaveLeft and isExact for the same invocation. */
167552    assert( isSaveLeft==0 || isExact==0 );
167553  
167554    assert( p!=0 && *p1!=0 && *p2!=0 );
167555    if( *p1==POS_COLUMN ){ 
167556      p1++;
167557      p1 += fts3GetVarint32(p1, &iCol1);
167558    }
167559    if( *p2==POS_COLUMN ){ 
167560      p2++;
167561      p2 += fts3GetVarint32(p2, &iCol2);
167562    }
167563  
167564    while( 1 ){
167565      if( iCol1==iCol2 ){
167566        char *pSave = p;
167567        sqlite3_int64 iPrev = 0;
167568        sqlite3_int64 iPos1 = 0;
167569        sqlite3_int64 iPos2 = 0;
167570  
167571        if( iCol1 ){
167572          *p++ = POS_COLUMN;
167573          p += sqlite3Fts3PutVarint(p, iCol1);
167574        }
167575  
167576        fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
167577        fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
167578        if( iPos1<0 || iPos2<0 ) break;
167579  
167580        while( 1 ){
167581          if( iPos2==iPos1+nToken 
167582           || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
167583          ){
167584            sqlite3_int64 iSave;
167585            iSave = isSaveLeft ? iPos1 : iPos2;
167586            fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
167587            pSave = 0;
167588            assert( p );
167589          }
167590          if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
167591            if( (*p2&0xFE)==0 ) break;
167592            fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
167593          }else{
167594            if( (*p1&0xFE)==0 ) break;
167595            fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
167596          }
167597        }
167598  
167599        if( pSave ){
167600          assert( pp && p );
167601          p = pSave;
167602        }
167603  
167604        fts3ColumnlistCopy(0, &p1);
167605        fts3ColumnlistCopy(0, &p2);
167606        assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
167607        if( 0==*p1 || 0==*p2 ) break;
167608  
167609        p1++;
167610        p1 += fts3GetVarint32(p1, &iCol1);
167611        p2++;
167612        p2 += fts3GetVarint32(p2, &iCol2);
167613      }
167614  
167615      /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
167616      ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
167617      ** end of the position list, or the 0x01 that precedes the next 
167618      ** column-number in the position list. 
167619      */
167620      else if( iCol1<iCol2 ){
167621        fts3ColumnlistCopy(0, &p1);
167622        if( 0==*p1 ) break;
167623        p1++;
167624        p1 += fts3GetVarint32(p1, &iCol1);
167625      }else{
167626        fts3ColumnlistCopy(0, &p2);
167627        if( 0==*p2 ) break;
167628        p2++;
167629        p2 += fts3GetVarint32(p2, &iCol2);
167630      }
167631    }
167632  
167633    fts3PoslistCopy(0, &p2);
167634    fts3PoslistCopy(0, &p1);
167635    *pp1 = p1;
167636    *pp2 = p2;
167637    if( *pp==p ){
167638      return 0;
167639    }
167640    *p++ = 0x00;
167641    *pp = p;
167642    return 1;
167643  }
167644  
167645  /*
167646  ** Merge two position-lists as required by the NEAR operator. The argument
167647  ** position lists correspond to the left and right phrases of an expression 
167648  ** like:
167649  **
167650  **     "phrase 1" NEAR "phrase number 2"
167651  **
167652  ** Position list *pp1 corresponds to the left-hand side of the NEAR 
167653  ** expression and *pp2 to the right. As usual, the indexes in the position 
167654  ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
167655  ** in the example above).
167656  **
167657  ** The output position list - written to *pp - is a copy of *pp2 with those
167658  ** entries that are not sufficiently NEAR entries in *pp1 removed.
167659  */
167660  static int fts3PoslistNearMerge(
167661    char **pp,                      /* Output buffer */
167662    char *aTmp,                     /* Temporary buffer space */
167663    int nRight,                     /* Maximum difference in token positions */
167664    int nLeft,                      /* Maximum difference in token positions */
167665    char **pp1,                     /* IN/OUT: Left input list */
167666    char **pp2                      /* IN/OUT: Right input list */
167667  ){
167668    char *p1 = *pp1;
167669    char *p2 = *pp2;
167670  
167671    char *pTmp1 = aTmp;
167672    char *pTmp2;
167673    char *aTmp2;
167674    int res = 1;
167675  
167676    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
167677    aTmp2 = pTmp2 = pTmp1;
167678    *pp1 = p1;
167679    *pp2 = p2;
167680    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
167681    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
167682      fts3PoslistMerge(pp, &aTmp, &aTmp2);
167683    }else if( pTmp1!=aTmp ){
167684      fts3PoslistCopy(pp, &aTmp);
167685    }else if( pTmp2!=aTmp2 ){
167686      fts3PoslistCopy(pp, &aTmp2);
167687    }else{
167688      res = 0;
167689    }
167690  
167691    return res;
167692  }
167693  
167694  /* 
167695  ** An instance of this function is used to merge together the (potentially
167696  ** large number of) doclists for each term that matches a prefix query.
167697  ** See function fts3TermSelectMerge() for details.
167698  */
167699  typedef struct TermSelect TermSelect;
167700  struct TermSelect {
167701    char *aaOutput[16];             /* Malloc'd output buffers */
167702    int anOutput[16];               /* Size each output buffer in bytes */
167703  };
167704  
167705  /*
167706  ** This function is used to read a single varint from a buffer. Parameter
167707  ** pEnd points 1 byte past the end of the buffer. When this function is
167708  ** called, if *pp points to pEnd or greater, then the end of the buffer
167709  ** has been reached. In this case *pp is set to 0 and the function returns.
167710  **
167711  ** If *pp does not point to or past pEnd, then a single varint is read
167712  ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
167713  **
167714  ** If bDescIdx is false, the value read is added to *pVal before returning.
167715  ** If it is true, the value read is subtracted from *pVal before this 
167716  ** function returns.
167717  */
167718  static void fts3GetDeltaVarint3(
167719    char **pp,                      /* IN/OUT: Point to read varint from */
167720    char *pEnd,                     /* End of buffer */
167721    int bDescIdx,                   /* True if docids are descending */
167722    sqlite3_int64 *pVal             /* IN/OUT: Integer value */
167723  ){
167724    if( *pp>=pEnd ){
167725      *pp = 0;
167726    }else{
167727      sqlite3_int64 iVal;
167728      *pp += sqlite3Fts3GetVarint(*pp, &iVal);
167729      if( bDescIdx ){
167730        *pVal -= iVal;
167731      }else{
167732        *pVal += iVal;
167733      }
167734    }
167735  }
167736  
167737  /*
167738  ** This function is used to write a single varint to a buffer. The varint
167739  ** is written to *pp. Before returning, *pp is set to point 1 byte past the
167740  ** end of the value written.
167741  **
167742  ** If *pbFirst is zero when this function is called, the value written to
167743  ** the buffer is that of parameter iVal. 
167744  **
167745  ** If *pbFirst is non-zero when this function is called, then the value 
167746  ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
167747  ** (if bDescIdx is non-zero).
167748  **
167749  ** Before returning, this function always sets *pbFirst to 1 and *piPrev
167750  ** to the value of parameter iVal.
167751  */
167752  static void fts3PutDeltaVarint3(
167753    char **pp,                      /* IN/OUT: Output pointer */
167754    int bDescIdx,                   /* True for descending docids */
167755    sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
167756    int *pbFirst,                   /* IN/OUT: True after first int written */
167757    sqlite3_int64 iVal              /* Write this value to the list */
167758  ){
167759    sqlite3_int64 iWrite;
167760    if( bDescIdx==0 || *pbFirst==0 ){
167761      iWrite = iVal - *piPrev;
167762    }else{
167763      iWrite = *piPrev - iVal;
167764    }
167765    assert( *pbFirst || *piPrev==0 );
167766    assert( *pbFirst==0 || iWrite>0 );
167767    *pp += sqlite3Fts3PutVarint(*pp, iWrite);
167768    *piPrev = iVal;
167769    *pbFirst = 1;
167770  }
167771  
167772  
167773  /*
167774  ** This macro is used by various functions that merge doclists. The two
167775  ** arguments are 64-bit docid values. If the value of the stack variable
167776  ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
167777  ** Otherwise, (i2-i1).
167778  **
167779  ** Using this makes it easier to write code that can merge doclists that are
167780  ** sorted in either ascending or descending order.
167781  */
167782  #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
167783  
167784  /*
167785  ** This function does an "OR" merge of two doclists (output contains all
167786  ** positions contained in either argument doclist). If the docids in the 
167787  ** input doclists are sorted in ascending order, parameter bDescDoclist
167788  ** should be false. If they are sorted in ascending order, it should be
167789  ** passed a non-zero value.
167790  **
167791  ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
167792  ** containing the output doclist and SQLITE_OK is returned. In this case
167793  ** *pnOut is set to the number of bytes in the output doclist.
167794  **
167795  ** If an error occurs, an SQLite error code is returned. The output values
167796  ** are undefined in this case.
167797  */
167798  static int fts3DoclistOrMerge(
167799    int bDescDoclist,               /* True if arguments are desc */
167800    char *a1, int n1,               /* First doclist */
167801    char *a2, int n2,               /* Second doclist */
167802    char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
167803  ){
167804    int rc = SQLITE_OK;
167805    sqlite3_int64 i1 = 0;
167806    sqlite3_int64 i2 = 0;
167807    sqlite3_int64 iPrev = 0;
167808    char *pEnd1 = &a1[n1];
167809    char *pEnd2 = &a2[n2];
167810    char *p1 = a1;
167811    char *p2 = a2;
167812    char *p;
167813    char *aOut;
167814    int bFirstOut = 0;
167815  
167816    *paOut = 0;
167817    *pnOut = 0;
167818  
167819    /* Allocate space for the output. Both the input and output doclists
167820    ** are delta encoded. If they are in ascending order (bDescDoclist==0),
167821    ** then the first docid in each list is simply encoded as a varint. For
167822    ** each subsequent docid, the varint stored is the difference between the
167823    ** current and previous docid (a positive number - since the list is in
167824    ** ascending order).
167825    **
167826    ** The first docid written to the output is therefore encoded using the 
167827    ** same number of bytes as it is in whichever of the input lists it is
167828    ** read from. And each subsequent docid read from the same input list 
167829    ** consumes either the same or less bytes as it did in the input (since
167830    ** the difference between it and the previous value in the output must
167831    ** be a positive value less than or equal to the delta value read from 
167832    ** the input list). The same argument applies to all but the first docid
167833    ** read from the 'other' list. And to the contents of all position lists
167834    ** that will be copied and merged from the input to the output.
167835    **
167836    ** However, if the first docid copied to the output is a negative number,
167837    ** then the encoding of the first docid from the 'other' input list may
167838    ** be larger in the output than it was in the input (since the delta value
167839    ** may be a larger positive integer than the actual docid).
167840    **
167841    ** The space required to store the output is therefore the sum of the
167842    ** sizes of the two inputs, plus enough space for exactly one of the input
167843    ** docids to grow. 
167844    **
167845    ** A symetric argument may be made if the doclists are in descending 
167846    ** order.
167847    */
167848    aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
167849    if( !aOut ) return SQLITE_NOMEM;
167850  
167851    p = aOut;
167852    fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
167853    fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
167854    while( p1 || p2 ){
167855      sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
167856  
167857      if( p2 && p1 && iDiff==0 ){
167858        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
167859        rc = fts3PoslistMerge(&p, &p1, &p2);
167860        if( rc ) break;
167861        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
167862        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
167863      }else if( !p2 || (p1 && iDiff<0) ){
167864        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
167865        fts3PoslistCopy(&p, &p1);
167866        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
167867      }else{
167868        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
167869        fts3PoslistCopy(&p, &p2);
167870        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
167871      }
167872    }
167873  
167874    if( rc!=SQLITE_OK ){
167875      sqlite3_free(aOut);
167876      p = aOut = 0;
167877    }else{
167878      assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
167879      memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
167880    }
167881    *paOut = aOut;
167882    *pnOut = (int)(p-aOut);
167883    return rc;
167884  }
167885  
167886  /*
167887  ** This function does a "phrase" merge of two doclists. In a phrase merge,
167888  ** the output contains a copy of each position from the right-hand input
167889  ** doclist for which there is a position in the left-hand input doclist
167890  ** exactly nDist tokens before it.
167891  **
167892  ** If the docids in the input doclists are sorted in ascending order,
167893  ** parameter bDescDoclist should be false. If they are sorted in ascending 
167894  ** order, it should be passed a non-zero value.
167895  **
167896  ** The right-hand input doclist is overwritten by this function.
167897  */
167898  static int fts3DoclistPhraseMerge(
167899    int bDescDoclist,               /* True if arguments are desc */
167900    int nDist,                      /* Distance from left to right (1=adjacent) */
167901    char *aLeft, int nLeft,         /* Left doclist */
167902    char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
167903  ){
167904    sqlite3_int64 i1 = 0;
167905    sqlite3_int64 i2 = 0;
167906    sqlite3_int64 iPrev = 0;
167907    char *aRight = *paRight;
167908    char *pEnd1 = &aLeft[nLeft];
167909    char *pEnd2 = &aRight[*pnRight];
167910    char *p1 = aLeft;
167911    char *p2 = aRight;
167912    char *p;
167913    int bFirstOut = 0;
167914    char *aOut;
167915  
167916    assert( nDist>0 );
167917    if( bDescDoclist ){
167918      aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
167919      if( aOut==0 ) return SQLITE_NOMEM;
167920    }else{
167921      aOut = aRight;
167922    }
167923    p = aOut;
167924  
167925    fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
167926    fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
167927  
167928    while( p1 && p2 ){
167929      sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
167930      if( iDiff==0 ){
167931        char *pSave = p;
167932        sqlite3_int64 iPrevSave = iPrev;
167933        int bFirstOutSave = bFirstOut;
167934  
167935        fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
167936        if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
167937          p = pSave;
167938          iPrev = iPrevSave;
167939          bFirstOut = bFirstOutSave;
167940        }
167941        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
167942        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
167943      }else if( iDiff<0 ){
167944        fts3PoslistCopy(0, &p1);
167945        fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
167946      }else{
167947        fts3PoslistCopy(0, &p2);
167948        fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
167949      }
167950    }
167951  
167952    *pnRight = (int)(p - aOut);
167953    if( bDescDoclist ){
167954      sqlite3_free(aRight);
167955      *paRight = aOut;
167956    }
167957  
167958    return SQLITE_OK;
167959  }
167960  
167961  /*
167962  ** Argument pList points to a position list nList bytes in size. This
167963  ** function checks to see if the position list contains any entries for
167964  ** a token in position 0 (of any column). If so, it writes argument iDelta
167965  ** to the output buffer pOut, followed by a position list consisting only
167966  ** of the entries from pList at position 0, and terminated by an 0x00 byte.
167967  ** The value returned is the number of bytes written to pOut (if any).
167968  */
167969  SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
167970    sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
167971    char *pList,                    /* Position list (no 0x00 term) */
167972    int nList,                      /* Size of pList in bytes */
167973    char *pOut                      /* Write output here */
167974  ){
167975    int nOut = 0;
167976    int bWritten = 0;               /* True once iDelta has been written */
167977    char *p = pList;
167978    char *pEnd = &pList[nList];
167979  
167980    if( *p!=0x01 ){
167981      if( *p==0x02 ){
167982        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
167983        pOut[nOut++] = 0x02;
167984        bWritten = 1;
167985      }
167986      fts3ColumnlistCopy(0, &p);
167987    }
167988  
167989    while( p<pEnd ){
167990      sqlite3_int64 iCol;
167991      p++;
167992      p += sqlite3Fts3GetVarint(p, &iCol);
167993      if( *p==0x02 ){
167994        if( bWritten==0 ){
167995          nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
167996          bWritten = 1;
167997        }
167998        pOut[nOut++] = 0x01;
167999        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
168000        pOut[nOut++] = 0x02;
168001      }
168002      fts3ColumnlistCopy(0, &p);
168003    }
168004    if( bWritten ){
168005      pOut[nOut++] = 0x00;
168006    }
168007  
168008    return nOut;
168009  }
168010  
168011  
168012  /*
168013  ** Merge all doclists in the TermSelect.aaOutput[] array into a single
168014  ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
168015  ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
168016  **
168017  ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
168018  ** the responsibility of the caller to free any doclists left in the
168019  ** TermSelect.aaOutput[] array.
168020  */
168021  static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
168022    char *aOut = 0;
168023    int nOut = 0;
168024    int i;
168025  
168026    /* Loop through the doclists in the aaOutput[] array. Merge them all
168027    ** into a single doclist.
168028    */
168029    for(i=0; i<SizeofArray(pTS->aaOutput); i++){
168030      if( pTS->aaOutput[i] ){
168031        if( !aOut ){
168032          aOut = pTS->aaOutput[i];
168033          nOut = pTS->anOutput[i];
168034          pTS->aaOutput[i] = 0;
168035        }else{
168036          int nNew;
168037          char *aNew;
168038  
168039          int rc = fts3DoclistOrMerge(p->bDescIdx, 
168040              pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
168041          );
168042          if( rc!=SQLITE_OK ){
168043            sqlite3_free(aOut);
168044            return rc;
168045          }
168046  
168047          sqlite3_free(pTS->aaOutput[i]);
168048          sqlite3_free(aOut);
168049          pTS->aaOutput[i] = 0;
168050          aOut = aNew;
168051          nOut = nNew;
168052        }
168053      }
168054    }
168055  
168056    pTS->aaOutput[0] = aOut;
168057    pTS->anOutput[0] = nOut;
168058    return SQLITE_OK;
168059  }
168060  
168061  /*
168062  ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
168063  ** as the first argument. The merge is an "OR" merge (see function
168064  ** fts3DoclistOrMerge() for details).
168065  **
168066  ** This function is called with the doclist for each term that matches
168067  ** a queried prefix. It merges all these doclists into one, the doclist
168068  ** for the specified prefix. Since there can be a very large number of
168069  ** doclists to merge, the merging is done pair-wise using the TermSelect
168070  ** object.
168071  **
168072  ** This function returns SQLITE_OK if the merge is successful, or an
168073  ** SQLite error code (SQLITE_NOMEM) if an error occurs.
168074  */
168075  static int fts3TermSelectMerge(
168076    Fts3Table *p,                   /* FTS table handle */
168077    TermSelect *pTS,                /* TermSelect object to merge into */
168078    char *aDoclist,                 /* Pointer to doclist */
168079    int nDoclist                    /* Size of aDoclist in bytes */
168080  ){
168081    if( pTS->aaOutput[0]==0 ){
168082      /* If this is the first term selected, copy the doclist to the output
168083      ** buffer using memcpy(). 
168084      **
168085      ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 
168086      ** allocation. This is so as to ensure that the buffer is big enough
168087      ** to hold the current doclist AND'd with any other doclist. If the
168088      ** doclists are stored in order=ASC order, this padding would not be
168089      ** required (since the size of [doclistA AND doclistB] is always less
168090      ** than or equal to the size of [doclistA] in that case). But this is
168091      ** not true for order=DESC. For example, a doclist containing (1, -1) 
168092      ** may be smaller than (-1), as in the first example the -1 may be stored
168093      ** as a single-byte delta, whereas in the second it must be stored as a
168094      ** FTS3_VARINT_MAX byte varint.
168095      **
168096      ** Similar padding is added in the fts3DoclistOrMerge() function.
168097      */
168098      pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
168099      pTS->anOutput[0] = nDoclist;
168100      if( pTS->aaOutput[0] ){
168101        memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
168102        memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
168103      }else{
168104        return SQLITE_NOMEM;
168105      }
168106    }else{
168107      char *aMerge = aDoclist;
168108      int nMerge = nDoclist;
168109      int iOut;
168110  
168111      for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
168112        if( pTS->aaOutput[iOut]==0 ){
168113          assert( iOut>0 );
168114          pTS->aaOutput[iOut] = aMerge;
168115          pTS->anOutput[iOut] = nMerge;
168116          break;
168117        }else{
168118          char *aNew;
168119          int nNew;
168120  
168121          int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
168122              pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
168123          );
168124          if( rc!=SQLITE_OK ){
168125            if( aMerge!=aDoclist ) sqlite3_free(aMerge);
168126            return rc;
168127          }
168128  
168129          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
168130          sqlite3_free(pTS->aaOutput[iOut]);
168131          pTS->aaOutput[iOut] = 0;
168132    
168133          aMerge = aNew;
168134          nMerge = nNew;
168135          if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
168136            pTS->aaOutput[iOut] = aMerge;
168137            pTS->anOutput[iOut] = nMerge;
168138          }
168139        }
168140      }
168141    }
168142    return SQLITE_OK;
168143  }
168144  
168145  /*
168146  ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
168147  */
168148  static int fts3SegReaderCursorAppend(
168149    Fts3MultiSegReader *pCsr, 
168150    Fts3SegReader *pNew
168151  ){
168152    if( (pCsr->nSegment%16)==0 ){
168153      Fts3SegReader **apNew;
168154      sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
168155      apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
168156      if( !apNew ){
168157        sqlite3Fts3SegReaderFree(pNew);
168158        return SQLITE_NOMEM;
168159      }
168160      pCsr->apSegment = apNew;
168161    }
168162    pCsr->apSegment[pCsr->nSegment++] = pNew;
168163    return SQLITE_OK;
168164  }
168165  
168166  /*
168167  ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
168168  ** 8th argument.
168169  **
168170  ** This function returns SQLITE_OK if successful, or an SQLite error code
168171  ** otherwise.
168172  */
168173  static int fts3SegReaderCursor(
168174    Fts3Table *p,                   /* FTS3 table handle */
168175    int iLangid,                    /* Language id */
168176    int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
168177    int iLevel,                     /* Level of segments to scan */
168178    const char *zTerm,              /* Term to query for */
168179    int nTerm,                      /* Size of zTerm in bytes */
168180    int isPrefix,                   /* True for a prefix search */
168181    int isScan,                     /* True to scan from zTerm to EOF */
168182    Fts3MultiSegReader *pCsr        /* Cursor object to populate */
168183  ){
168184    int rc = SQLITE_OK;             /* Error code */
168185    sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
168186    int rc2;                        /* Result of sqlite3_reset() */
168187  
168188    /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
168189    ** for the pending-terms. If this is a scan, then this call must be being
168190    ** made by an fts4aux module, not an FTS table. In this case calling
168191    ** Fts3SegReaderPending might segfault, as the data structures used by 
168192    ** fts4aux are not completely populated. So it's easiest to filter these
168193    ** calls out here.  */
168194    if( iLevel<0 && p->aIndex ){
168195      Fts3SegReader *pSeg = 0;
168196      rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
168197      if( rc==SQLITE_OK && pSeg ){
168198        rc = fts3SegReaderCursorAppend(pCsr, pSeg);
168199      }
168200    }
168201  
168202    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
168203      if( rc==SQLITE_OK ){
168204        rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
168205      }
168206  
168207      while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
168208        Fts3SegReader *pSeg = 0;
168209  
168210        /* Read the values returned by the SELECT into local variables. */
168211        sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
168212        sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
168213        sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
168214        int nRoot = sqlite3_column_bytes(pStmt, 4);
168215        char const *zRoot = sqlite3_column_blob(pStmt, 4);
168216  
168217        /* If zTerm is not NULL, and this segment is not stored entirely on its
168218        ** root node, the range of leaves scanned can be reduced. Do this. */
168219        if( iStartBlock && zTerm && zRoot ){
168220          sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
168221          rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
168222          if( rc!=SQLITE_OK ) goto finished;
168223          if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
168224        }
168225   
168226        rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
168227            (isPrefix==0 && isScan==0),
168228            iStartBlock, iLeavesEndBlock, 
168229            iEndBlock, zRoot, nRoot, &pSeg
168230        );
168231        if( rc!=SQLITE_OK ) goto finished;
168232        rc = fts3SegReaderCursorAppend(pCsr, pSeg);
168233      }
168234    }
168235  
168236   finished:
168237    rc2 = sqlite3_reset(pStmt);
168238    if( rc==SQLITE_DONE ) rc = rc2;
168239  
168240    return rc;
168241  }
168242  
168243  /*
168244  ** Set up a cursor object for iterating through a full-text index or a 
168245  ** single level therein.
168246  */
168247  SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
168248    Fts3Table *p,                   /* FTS3 table handle */
168249    int iLangid,                    /* Language-id to search */
168250    int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
168251    int iLevel,                     /* Level of segments to scan */
168252    const char *zTerm,              /* Term to query for */
168253    int nTerm,                      /* Size of zTerm in bytes */
168254    int isPrefix,                   /* True for a prefix search */
168255    int isScan,                     /* True to scan from zTerm to EOF */
168256    Fts3MultiSegReader *pCsr       /* Cursor object to populate */
168257  ){
168258    assert( iIndex>=0 && iIndex<p->nIndex );
168259    assert( iLevel==FTS3_SEGCURSOR_ALL
168260        ||  iLevel==FTS3_SEGCURSOR_PENDING 
168261        ||  iLevel>=0
168262    );
168263    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
168264    assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
168265    assert( isPrefix==0 || isScan==0 );
168266  
168267    memset(pCsr, 0, sizeof(Fts3MultiSegReader));
168268    return fts3SegReaderCursor(
168269        p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
168270    );
168271  }
168272  
168273  /*
168274  ** In addition to its current configuration, have the Fts3MultiSegReader
168275  ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
168276  **
168277  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
168278  */
168279  static int fts3SegReaderCursorAddZero(
168280    Fts3Table *p,                   /* FTS virtual table handle */
168281    int iLangid,
168282    const char *zTerm,              /* Term to scan doclist of */
168283    int nTerm,                      /* Number of bytes in zTerm */
168284    Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
168285  ){
168286    return fts3SegReaderCursor(p, 
168287        iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
168288    );
168289  }
168290  
168291  /*
168292  ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
168293  ** if isPrefix is true, to scan the doclist for all terms for which 
168294  ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
168295  ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
168296  ** an SQLite error code.
168297  **
168298  ** It is the responsibility of the caller to free this object by eventually
168299  ** passing it to fts3SegReaderCursorFree() 
168300  **
168301  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
168302  ** Output parameter *ppSegcsr is set to 0 if an error occurs.
168303  */
168304  static int fts3TermSegReaderCursor(
168305    Fts3Cursor *pCsr,               /* Virtual table cursor handle */
168306    const char *zTerm,              /* Term to query for */
168307    int nTerm,                      /* Size of zTerm in bytes */
168308    int isPrefix,                   /* True for a prefix search */
168309    Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
168310  ){
168311    Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
168312    int rc = SQLITE_NOMEM;          /* Return code */
168313  
168314    pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
168315    if( pSegcsr ){
168316      int i;
168317      int bFound = 0;               /* True once an index has been found */
168318      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
168319  
168320      if( isPrefix ){
168321        for(i=1; bFound==0 && i<p->nIndex; i++){
168322          if( p->aIndex[i].nPrefix==nTerm ){
168323            bFound = 1;
168324            rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
168325                i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
168326            );
168327            pSegcsr->bLookup = 1;
168328          }
168329        }
168330  
168331        for(i=1; bFound==0 && i<p->nIndex; i++){
168332          if( p->aIndex[i].nPrefix==nTerm+1 ){
168333            bFound = 1;
168334            rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
168335                i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
168336            );
168337            if( rc==SQLITE_OK ){
168338              rc = fts3SegReaderCursorAddZero(
168339                  p, pCsr->iLangid, zTerm, nTerm, pSegcsr
168340              );
168341            }
168342          }
168343        }
168344      }
168345  
168346      if( bFound==0 ){
168347        rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
168348            0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
168349        );
168350        pSegcsr->bLookup = !isPrefix;
168351      }
168352    }
168353  
168354    *ppSegcsr = pSegcsr;
168355    return rc;
168356  }
168357  
168358  /*
168359  ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
168360  */
168361  static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
168362    sqlite3Fts3SegReaderFinish(pSegcsr);
168363    sqlite3_free(pSegcsr);
168364  }
168365  
168366  /*
168367  ** This function retrieves the doclist for the specified term (or term
168368  ** prefix) from the database.
168369  */
168370  static int fts3TermSelect(
168371    Fts3Table *p,                   /* Virtual table handle */
168372    Fts3PhraseToken *pTok,          /* Token to query for */
168373    int iColumn,                    /* Column to query (or -ve for all columns) */
168374    int *pnOut,                     /* OUT: Size of buffer at *ppOut */
168375    char **ppOut                    /* OUT: Malloced result buffer */
168376  ){
168377    int rc;                         /* Return code */
168378    Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
168379    TermSelect tsc;                 /* Object for pair-wise doclist merging */
168380    Fts3SegFilter filter;           /* Segment term filter configuration */
168381  
168382    pSegcsr = pTok->pSegcsr;
168383    memset(&tsc, 0, sizeof(TermSelect));
168384  
168385    filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
168386          | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
168387          | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
168388          | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
168389    filter.iCol = iColumn;
168390    filter.zTerm = pTok->z;
168391    filter.nTerm = pTok->n;
168392  
168393    rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
168394    while( SQLITE_OK==rc
168395        && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
168396    ){
168397      rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
168398    }
168399  
168400    if( rc==SQLITE_OK ){
168401      rc = fts3TermSelectFinishMerge(p, &tsc);
168402    }
168403    if( rc==SQLITE_OK ){
168404      *ppOut = tsc.aaOutput[0];
168405      *pnOut = tsc.anOutput[0];
168406    }else{
168407      int i;
168408      for(i=0; i<SizeofArray(tsc.aaOutput); i++){
168409        sqlite3_free(tsc.aaOutput[i]);
168410      }
168411    }
168412  
168413    fts3SegReaderCursorFree(pSegcsr);
168414    pTok->pSegcsr = 0;
168415    return rc;
168416  }
168417  
168418  /*
168419  ** This function counts the total number of docids in the doclist stored
168420  ** in buffer aList[], size nList bytes.
168421  **
168422  ** If the isPoslist argument is true, then it is assumed that the doclist
168423  ** contains a position-list following each docid. Otherwise, it is assumed
168424  ** that the doclist is simply a list of docids stored as delta encoded 
168425  ** varints.
168426  */
168427  static int fts3DoclistCountDocids(char *aList, int nList){
168428    int nDoc = 0;                   /* Return value */
168429    if( aList ){
168430      char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
168431      char *p = aList;              /* Cursor */
168432      while( p<aEnd ){
168433        nDoc++;
168434        while( (*p++)&0x80 );     /* Skip docid varint */
168435        fts3PoslistCopy(0, &p);   /* Skip over position list */
168436      }
168437    }
168438  
168439    return nDoc;
168440  }
168441  
168442  /*
168443  ** Advance the cursor to the next row in the %_content table that
168444  ** matches the search criteria.  For a MATCH search, this will be
168445  ** the next row that matches. For a full-table scan, this will be
168446  ** simply the next row in the %_content table.  For a docid lookup,
168447  ** this routine simply sets the EOF flag.
168448  **
168449  ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
168450  ** even if we reach end-of-file.  The fts3EofMethod() will be called
168451  ** subsequently to determine whether or not an EOF was hit.
168452  */
168453  static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
168454    int rc;
168455    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
168456    if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
168457      if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
168458        pCsr->isEof = 1;
168459        rc = sqlite3_reset(pCsr->pStmt);
168460      }else{
168461        pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
168462        rc = SQLITE_OK;
168463      }
168464    }else{
168465      rc = fts3EvalNext((Fts3Cursor *)pCursor);
168466    }
168467    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
168468    return rc;
168469  }
168470  
168471  /*
168472  ** The following are copied from sqliteInt.h.
168473  **
168474  ** Constants for the largest and smallest possible 64-bit signed integers.
168475  ** These macros are designed to work correctly on both 32-bit and 64-bit
168476  ** compilers.
168477  */
168478  #ifndef SQLITE_AMALGAMATION
168479  # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
168480  # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
168481  #endif
168482  
168483  /*
168484  ** If the numeric type of argument pVal is "integer", then return it
168485  ** converted to a 64-bit signed integer. Otherwise, return a copy of
168486  ** the second parameter, iDefault.
168487  */
168488  static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
168489    if( pVal ){
168490      int eType = sqlite3_value_numeric_type(pVal);
168491      if( eType==SQLITE_INTEGER ){
168492        return sqlite3_value_int64(pVal);
168493      }
168494    }
168495    return iDefault;
168496  }
168497  
168498  /*
168499  ** This is the xFilter interface for the virtual table.  See
168500  ** the virtual table xFilter method documentation for additional
168501  ** information.
168502  **
168503  ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
168504  ** the %_content table.
168505  **
168506  ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
168507  ** in the %_content table.
168508  **
168509  ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
168510  ** column on the left-hand side of the MATCH operator is column
168511  ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
168512  ** side of the MATCH operator.
168513  */
168514  static int fts3FilterMethod(
168515    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
168516    int idxNum,                     /* Strategy index */
168517    const char *idxStr,             /* Unused */
168518    int nVal,                       /* Number of elements in apVal */
168519    sqlite3_value **apVal           /* Arguments for the indexing scheme */
168520  ){
168521    int rc = SQLITE_OK;
168522    char *zSql;                     /* SQL statement used to access %_content */
168523    int eSearch;
168524    Fts3Table *p = (Fts3Table *)pCursor->pVtab;
168525    Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
168526  
168527    sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
168528    sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
168529    sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
168530    sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
168531    int iIdx;
168532  
168533    UNUSED_PARAMETER(idxStr);
168534    UNUSED_PARAMETER(nVal);
168535  
168536    eSearch = (idxNum & 0x0000FFFF);
168537    assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
168538    assert( p->pSegments==0 );
168539  
168540    /* Collect arguments into local variables */
168541    iIdx = 0;
168542    if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
168543    if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
168544    if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
168545    if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
168546    assert( iIdx==nVal );
168547  
168548    /* In case the cursor has been used before, clear it now. */
168549    fts3ClearCursor(pCsr);
168550  
168551    /* Set the lower and upper bounds on docids to return */
168552    pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
168553    pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
168554  
168555    if( idxStr ){
168556      pCsr->bDesc = (idxStr[0]=='D');
168557    }else{
168558      pCsr->bDesc = p->bDescIdx;
168559    }
168560    pCsr->eSearch = (i16)eSearch;
168561  
168562    if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
168563      int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
168564      const char *zQuery = (const char *)sqlite3_value_text(pCons);
168565  
168566      if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
168567        return SQLITE_NOMEM;
168568      }
168569  
168570      pCsr->iLangid = 0;
168571      if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
168572  
168573      assert( p->base.zErrMsg==0 );
168574      rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
168575          p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
168576          &p->base.zErrMsg
168577      );
168578      if( rc!=SQLITE_OK ){
168579        return rc;
168580      }
168581  
168582      rc = fts3EvalStart(pCsr);
168583      sqlite3Fts3SegmentsClose(p);
168584      if( rc!=SQLITE_OK ) return rc;
168585      pCsr->pNextId = pCsr->aDoclist;
168586      pCsr->iPrevId = 0;
168587    }
168588  
168589    /* Compile a SELECT statement for this cursor. For a full-table-scan, the
168590    ** statement loops through all rows of the %_content table. For a
168591    ** full-text query or docid lookup, the statement retrieves a single
168592    ** row by docid.
168593    */
168594    if( eSearch==FTS3_FULLSCAN_SEARCH ){
168595      if( pDocidGe || pDocidLe ){
168596        zSql = sqlite3_mprintf(
168597            "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
168598            p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
168599            (pCsr->bDesc ? "DESC" : "ASC")
168600        );
168601      }else{
168602        zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 
168603            p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
168604        );
168605      }
168606      if( zSql ){
168607        rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
168608        sqlite3_free(zSql);
168609      }else{
168610        rc = SQLITE_NOMEM;
168611      }
168612    }else if( eSearch==FTS3_DOCID_SEARCH ){
168613      rc = fts3CursorSeekStmt(pCsr);
168614      if( rc==SQLITE_OK ){
168615        rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
168616      }
168617    }
168618    if( rc!=SQLITE_OK ) return rc;
168619  
168620    return fts3NextMethod(pCursor);
168621  }
168622  
168623  /* 
168624  ** This is the xEof method of the virtual table. SQLite calls this 
168625  ** routine to find out if it has reached the end of a result set.
168626  */
168627  static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
168628    Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
168629    if( pCsr->isEof ){
168630      fts3ClearCursor(pCsr);
168631      pCsr->isEof = 1;
168632    }
168633    return pCsr->isEof;
168634  }
168635  
168636  /* 
168637  ** This is the xRowid method. The SQLite core calls this routine to
168638  ** retrieve the rowid for the current row of the result set. fts3
168639  ** exposes %_content.docid as the rowid for the virtual table. The
168640  ** rowid should be written to *pRowid.
168641  */
168642  static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
168643    Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
168644    *pRowid = pCsr->iPrevId;
168645    return SQLITE_OK;
168646  }
168647  
168648  /* 
168649  ** This is the xColumn method, called by SQLite to request a value from
168650  ** the row that the supplied cursor currently points to.
168651  **
168652  ** If:
168653  **
168654  **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
168655  **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
168656  **   (iCol == p->nColumn+1) -> Docid column
168657  **   (iCol == p->nColumn+2) -> Langid column
168658  */
168659  static int fts3ColumnMethod(
168660    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
168661    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
168662    int iCol                        /* Index of column to read value from */
168663  ){
168664    int rc = SQLITE_OK;             /* Return Code */
168665    Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
168666    Fts3Table *p = (Fts3Table *)pCursor->pVtab;
168667  
168668    /* The column value supplied by SQLite must be in range. */
168669    assert( iCol>=0 && iCol<=p->nColumn+2 );
168670  
168671    switch( iCol-p->nColumn ){
168672      case 0:
168673        /* The special 'table-name' column */
168674        sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
168675        break;
168676  
168677      case 1:
168678        /* The docid column */
168679        sqlite3_result_int64(pCtx, pCsr->iPrevId);
168680        break;
168681  
168682      case 2:
168683        if( pCsr->pExpr ){
168684          sqlite3_result_int64(pCtx, pCsr->iLangid);
168685          break;
168686        }else if( p->zLanguageid==0 ){
168687          sqlite3_result_int(pCtx, 0);
168688          break;
168689        }else{
168690          iCol = p->nColumn;
168691          /* fall-through */
168692        }
168693  
168694      default:
168695        /* A user column. Or, if this is a full-table scan, possibly the
168696        ** language-id column. Seek the cursor. */
168697        rc = fts3CursorSeek(0, pCsr);
168698        if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
168699          sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
168700        }
168701        break;
168702    }
168703  
168704    assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
168705    return rc;
168706  }
168707  
168708  /* 
168709  ** This function is the implementation of the xUpdate callback used by 
168710  ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
168711  ** inserted, updated or deleted.
168712  */
168713  static int fts3UpdateMethod(
168714    sqlite3_vtab *pVtab,            /* Virtual table handle */
168715    int nArg,                       /* Size of argument array */
168716    sqlite3_value **apVal,          /* Array of arguments */
168717    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
168718  ){
168719    return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
168720  }
168721  
168722  /*
168723  ** Implementation of xSync() method. Flush the contents of the pending-terms
168724  ** hash-table to the database.
168725  */
168726  static int fts3SyncMethod(sqlite3_vtab *pVtab){
168727  
168728    /* Following an incremental-merge operation, assuming that the input
168729    ** segments are not completely consumed (the usual case), they are updated
168730    ** in place to remove the entries that have already been merged. This
168731    ** involves updating the leaf block that contains the smallest unmerged
168732    ** entry and each block (if any) between the leaf and the root node. So
168733    ** if the height of the input segment b-trees is N, and input segments
168734    ** are merged eight at a time, updating the input segments at the end
168735    ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
168736    ** small - often between 0 and 2. So the overhead of the incremental
168737    ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
168738    ** dwarfing the actual productive work accomplished, the incremental merge
168739    ** is only attempted if it will write at least 64 leaf blocks. Hence
168740    ** nMinMerge.
168741    **
168742    ** Of course, updating the input segments also involves deleting a bunch
168743    ** of blocks from the segments table. But this is not considered overhead
168744    ** as it would also be required by a crisis-merge that used the same input 
168745    ** segments.
168746    */
168747    const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
168748  
168749    Fts3Table *p = (Fts3Table*)pVtab;
168750    int rc;
168751    i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
168752  
168753    rc = sqlite3Fts3PendingTermsFlush(p);
168754    if( rc==SQLITE_OK 
168755     && p->nLeafAdd>(nMinMerge/16) 
168756     && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
168757    ){
168758      int mxLevel = 0;              /* Maximum relative level value in db */
168759      int A;                        /* Incr-merge parameter A */
168760  
168761      rc = sqlite3Fts3MaxLevel(p, &mxLevel);
168762      assert( rc==SQLITE_OK || mxLevel==0 );
168763      A = p->nLeafAdd * mxLevel;
168764      A += (A/2);
168765      if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
168766    }
168767    sqlite3Fts3SegmentsClose(p);
168768    sqlite3_set_last_insert_rowid(p->db, iLastRowid);
168769    return rc;
168770  }
168771  
168772  /*
168773  ** If it is currently unknown whether or not the FTS table has an %_stat
168774  ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
168775  ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
168776  ** if an error occurs.
168777  */
168778  static int fts3SetHasStat(Fts3Table *p){
168779    int rc = SQLITE_OK;
168780    if( p->bHasStat==2 ){
168781      char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
168782      if( zTbl ){
168783        int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
168784        sqlite3_free(zTbl);
168785        p->bHasStat = (res==SQLITE_OK);
168786      }else{
168787        rc = SQLITE_NOMEM;
168788      }
168789    }
168790    return rc;
168791  }
168792  
168793  /*
168794  ** Implementation of xBegin() method. 
168795  */
168796  static int fts3BeginMethod(sqlite3_vtab *pVtab){
168797    Fts3Table *p = (Fts3Table*)pVtab;
168798    UNUSED_PARAMETER(pVtab);
168799    assert( p->pSegments==0 );
168800    assert( p->nPendingData==0 );
168801    assert( p->inTransaction!=1 );
168802    TESTONLY( p->inTransaction = 1 );
168803    TESTONLY( p->mxSavepoint = -1; );
168804    p->nLeafAdd = 0;
168805    return fts3SetHasStat(p);
168806  }
168807  
168808  /*
168809  ** Implementation of xCommit() method. This is a no-op. The contents of
168810  ** the pending-terms hash-table have already been flushed into the database
168811  ** by fts3SyncMethod().
168812  */
168813  static int fts3CommitMethod(sqlite3_vtab *pVtab){
168814    TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
168815    UNUSED_PARAMETER(pVtab);
168816    assert( p->nPendingData==0 );
168817    assert( p->inTransaction!=0 );
168818    assert( p->pSegments==0 );
168819    TESTONLY( p->inTransaction = 0 );
168820    TESTONLY( p->mxSavepoint = -1; );
168821    return SQLITE_OK;
168822  }
168823  
168824  /*
168825  ** Implementation of xRollback(). Discard the contents of the pending-terms
168826  ** hash-table. Any changes made to the database are reverted by SQLite.
168827  */
168828  static int fts3RollbackMethod(sqlite3_vtab *pVtab){
168829    Fts3Table *p = (Fts3Table*)pVtab;
168830    sqlite3Fts3PendingTermsClear(p);
168831    assert( p->inTransaction!=0 );
168832    TESTONLY( p->inTransaction = 0 );
168833    TESTONLY( p->mxSavepoint = -1; );
168834    return SQLITE_OK;
168835  }
168836  
168837  /*
168838  ** When called, *ppPoslist must point to the byte immediately following the
168839  ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
168840  ** moves *ppPoslist so that it instead points to the first byte of the
168841  ** same position list.
168842  */
168843  static void fts3ReversePoslist(char *pStart, char **ppPoslist){
168844    char *p = &(*ppPoslist)[-2];
168845    char c = 0;
168846  
168847    /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
168848    while( p>pStart && (c=*p--)==0 );
168849  
168850    /* Search backwards for a varint with value zero (the end of the previous 
168851    ** poslist). This is an 0x00 byte preceded by some byte that does not
168852    ** have the 0x80 bit set.  */
168853    while( p>pStart && (*p & 0x80) | c ){ 
168854      c = *p--; 
168855    }
168856    assert( p==pStart || c==0 );
168857  
168858    /* At this point p points to that preceding byte without the 0x80 bit
168859    ** set. So to find the start of the poslist, skip forward 2 bytes then
168860    ** over a varint. 
168861    **
168862    ** Normally. The other case is that p==pStart and the poslist to return
168863    ** is the first in the doclist. In this case do not skip forward 2 bytes.
168864    ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
168865    ** is required for cases where the first byte of a doclist and the
168866    ** doclist is empty. For example, if the first docid is 10, a doclist
168867    ** that begins with:
168868    **
168869    **   0x0A 0x00 <next docid delta varint>
168870    */
168871    if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
168872    while( *p++&0x80 );
168873    *ppPoslist = p;
168874  }
168875  
168876  /*
168877  ** Helper function used by the implementation of the overloaded snippet(),
168878  ** offsets() and optimize() SQL functions.
168879  **
168880  ** If the value passed as the third argument is a blob of size
168881  ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
168882  ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
168883  ** message is written to context pContext and SQLITE_ERROR returned. The
168884  ** string passed via zFunc is used as part of the error message.
168885  */
168886  static int fts3FunctionArg(
168887    sqlite3_context *pContext,      /* SQL function call context */
168888    const char *zFunc,              /* Function name */
168889    sqlite3_value *pVal,            /* argv[0] passed to function */
168890    Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
168891  ){
168892    int rc;
168893    *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
168894    if( (*ppCsr)!=0 ){
168895      rc = SQLITE_OK;
168896    }else{
168897      char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
168898      sqlite3_result_error(pContext, zErr, -1);
168899      sqlite3_free(zErr);
168900      rc = SQLITE_ERROR;
168901    }
168902    return rc;
168903  }
168904  
168905  /*
168906  ** Implementation of the snippet() function for FTS3
168907  */
168908  static void fts3SnippetFunc(
168909    sqlite3_context *pContext,      /* SQLite function call context */
168910    int nVal,                       /* Size of apVal[] array */
168911    sqlite3_value **apVal           /* Array of arguments */
168912  ){
168913    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
168914    const char *zStart = "<b>";
168915    const char *zEnd = "</b>";
168916    const char *zEllipsis = "<b>...</b>";
168917    int iCol = -1;
168918    int nToken = 15;                /* Default number of tokens in snippet */
168919  
168920    /* There must be at least one argument passed to this function (otherwise
168921    ** the non-overloaded version would have been called instead of this one).
168922    */
168923    assert( nVal>=1 );
168924  
168925    if( nVal>6 ){
168926      sqlite3_result_error(pContext, 
168927          "wrong number of arguments to function snippet()", -1);
168928      return;
168929    }
168930    if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
168931  
168932    switch( nVal ){
168933      case 6: nToken = sqlite3_value_int(apVal[5]);
168934      case 5: iCol = sqlite3_value_int(apVal[4]);
168935      case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
168936      case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
168937      case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
168938    }
168939    if( !zEllipsis || !zEnd || !zStart ){
168940      sqlite3_result_error_nomem(pContext);
168941    }else if( nToken==0 ){
168942      sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
168943    }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
168944      sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
168945    }
168946  }
168947  
168948  /*
168949  ** Implementation of the offsets() function for FTS3
168950  */
168951  static void fts3OffsetsFunc(
168952    sqlite3_context *pContext,      /* SQLite function call context */
168953    int nVal,                       /* Size of argument array */
168954    sqlite3_value **apVal           /* Array of arguments */
168955  ){
168956    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
168957  
168958    UNUSED_PARAMETER(nVal);
168959  
168960    assert( nVal==1 );
168961    if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
168962    assert( pCsr );
168963    if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
168964      sqlite3Fts3Offsets(pContext, pCsr);
168965    }
168966  }
168967  
168968  /* 
168969  ** Implementation of the special optimize() function for FTS3. This 
168970  ** function merges all segments in the database to a single segment.
168971  ** Example usage is:
168972  **
168973  **   SELECT optimize(t) FROM t LIMIT 1;
168974  **
168975  ** where 't' is the name of an FTS3 table.
168976  */
168977  static void fts3OptimizeFunc(
168978    sqlite3_context *pContext,      /* SQLite function call context */
168979    int nVal,                       /* Size of argument array */
168980    sqlite3_value **apVal           /* Array of arguments */
168981  ){
168982    int rc;                         /* Return code */
168983    Fts3Table *p;                   /* Virtual table handle */
168984    Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
168985  
168986    UNUSED_PARAMETER(nVal);
168987  
168988    assert( nVal==1 );
168989    if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
168990    p = (Fts3Table *)pCursor->base.pVtab;
168991    assert( p );
168992  
168993    rc = sqlite3Fts3Optimize(p);
168994  
168995    switch( rc ){
168996      case SQLITE_OK:
168997        sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
168998        break;
168999      case SQLITE_DONE:
169000        sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
169001        break;
169002      default:
169003        sqlite3_result_error_code(pContext, rc);
169004        break;
169005    }
169006  }
169007  
169008  /*
169009  ** Implementation of the matchinfo() function for FTS3
169010  */
169011  static void fts3MatchinfoFunc(
169012    sqlite3_context *pContext,      /* SQLite function call context */
169013    int nVal,                       /* Size of argument array */
169014    sqlite3_value **apVal           /* Array of arguments */
169015  ){
169016    Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
169017    assert( nVal==1 || nVal==2 );
169018    if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
169019      const char *zArg = 0;
169020      if( nVal>1 ){
169021        zArg = (const char *)sqlite3_value_text(apVal[1]);
169022      }
169023      sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
169024    }
169025  }
169026  
169027  /*
169028  ** This routine implements the xFindFunction method for the FTS3
169029  ** virtual table.
169030  */
169031  static int fts3FindFunctionMethod(
169032    sqlite3_vtab *pVtab,            /* Virtual table handle */
169033    int nArg,                       /* Number of SQL function arguments */
169034    const char *zName,              /* Name of SQL function */
169035    void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
169036    void **ppArg                    /* Unused */
169037  ){
169038    struct Overloaded {
169039      const char *zName;
169040      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
169041    } aOverload[] = {
169042      { "snippet", fts3SnippetFunc },
169043      { "offsets", fts3OffsetsFunc },
169044      { "optimize", fts3OptimizeFunc },
169045      { "matchinfo", fts3MatchinfoFunc },
169046    };
169047    int i;                          /* Iterator variable */
169048  
169049    UNUSED_PARAMETER(pVtab);
169050    UNUSED_PARAMETER(nArg);
169051    UNUSED_PARAMETER(ppArg);
169052  
169053    for(i=0; i<SizeofArray(aOverload); i++){
169054      if( strcmp(zName, aOverload[i].zName)==0 ){
169055        *pxFunc = aOverload[i].xFunc;
169056        return 1;
169057      }
169058    }
169059  
169060    /* No function of the specified name was found. Return 0. */
169061    return 0;
169062  }
169063  
169064  /*
169065  ** Implementation of FTS3 xRename method. Rename an fts3 table.
169066  */
169067  static int fts3RenameMethod(
169068    sqlite3_vtab *pVtab,            /* Virtual table handle */
169069    const char *zName               /* New name of table */
169070  ){
169071    Fts3Table *p = (Fts3Table *)pVtab;
169072    sqlite3 *db = p->db;            /* Database connection */
169073    int rc;                         /* Return Code */
169074  
169075    /* At this point it must be known if the %_stat table exists or not.
169076    ** So bHasStat may not be 2.  */
169077    rc = fts3SetHasStat(p);
169078    
169079    /* As it happens, the pending terms table is always empty here. This is
169080    ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
169081    ** always opens a savepoint transaction. And the xSavepoint() method 
169082    ** flushes the pending terms table. But leave the (no-op) call to
169083    ** PendingTermsFlush() in in case that changes.
169084    */
169085    assert( p->nPendingData==0 );
169086    if( rc==SQLITE_OK ){
169087      rc = sqlite3Fts3PendingTermsFlush(p);
169088    }
169089  
169090    if( p->zContentTbl==0 ){
169091      fts3DbExec(&rc, db,
169092        "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
169093        p->zDb, p->zName, zName
169094      );
169095    }
169096  
169097    if( p->bHasDocsize ){
169098      fts3DbExec(&rc, db,
169099        "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
169100        p->zDb, p->zName, zName
169101      );
169102    }
169103    if( p->bHasStat ){
169104      fts3DbExec(&rc, db,
169105        "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
169106        p->zDb, p->zName, zName
169107      );
169108    }
169109    fts3DbExec(&rc, db,
169110      "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
169111      p->zDb, p->zName, zName
169112    );
169113    fts3DbExec(&rc, db,
169114      "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
169115      p->zDb, p->zName, zName
169116    );
169117    return rc;
169118  }
169119  
169120  /*
169121  ** The xSavepoint() method.
169122  **
169123  ** Flush the contents of the pending-terms table to disk.
169124  */
169125  static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
169126    int rc = SQLITE_OK;
169127    UNUSED_PARAMETER(iSavepoint);
169128    assert( ((Fts3Table *)pVtab)->inTransaction );
169129    assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
169130    TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
169131    if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
169132      rc = fts3SyncMethod(pVtab);
169133    }
169134    return rc;
169135  }
169136  
169137  /*
169138  ** The xRelease() method.
169139  **
169140  ** This is a no-op.
169141  */
169142  static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
169143    TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
169144    UNUSED_PARAMETER(iSavepoint);
169145    UNUSED_PARAMETER(pVtab);
169146    assert( p->inTransaction );
169147    assert( p->mxSavepoint >= iSavepoint );
169148    TESTONLY( p->mxSavepoint = iSavepoint-1 );
169149    return SQLITE_OK;
169150  }
169151  
169152  /*
169153  ** The xRollbackTo() method.
169154  **
169155  ** Discard the contents of the pending terms table.
169156  */
169157  static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
169158    Fts3Table *p = (Fts3Table*)pVtab;
169159    UNUSED_PARAMETER(iSavepoint);
169160    assert( p->inTransaction );
169161    TESTONLY( p->mxSavepoint = iSavepoint );
169162    sqlite3Fts3PendingTermsClear(p);
169163    return SQLITE_OK;
169164  }
169165  
169166  /*
169167  ** Return true if zName is the extension on one of the shadow tables used
169168  ** by this module.
169169  */
169170  static int fts3ShadowName(const char *zName){
169171    static const char *azName[] = {
169172      "content", "docsize", "segdir", "segments", "stat", 
169173    };
169174    unsigned int i;
169175    for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
169176      if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
169177    }
169178    return 0;
169179  }
169180  
169181  static const sqlite3_module fts3Module = {
169182    /* iVersion      */ 3,
169183    /* xCreate       */ fts3CreateMethod,
169184    /* xConnect      */ fts3ConnectMethod,
169185    /* xBestIndex    */ fts3BestIndexMethod,
169186    /* xDisconnect   */ fts3DisconnectMethod,
169187    /* xDestroy      */ fts3DestroyMethod,
169188    /* xOpen         */ fts3OpenMethod,
169189    /* xClose        */ fts3CloseMethod,
169190    /* xFilter       */ fts3FilterMethod,
169191    /* xNext         */ fts3NextMethod,
169192    /* xEof          */ fts3EofMethod,
169193    /* xColumn       */ fts3ColumnMethod,
169194    /* xRowid        */ fts3RowidMethod,
169195    /* xUpdate       */ fts3UpdateMethod,
169196    /* xBegin        */ fts3BeginMethod,
169197    /* xSync         */ fts3SyncMethod,
169198    /* xCommit       */ fts3CommitMethod,
169199    /* xRollback     */ fts3RollbackMethod,
169200    /* xFindFunction */ fts3FindFunctionMethod,
169201    /* xRename */       fts3RenameMethod,
169202    /* xSavepoint    */ fts3SavepointMethod,
169203    /* xRelease      */ fts3ReleaseMethod,
169204    /* xRollbackTo   */ fts3RollbackToMethod,
169205    /* xShadowName   */ fts3ShadowName,
169206  };
169207  
169208  /*
169209  ** This function is registered as the module destructor (called when an
169210  ** FTS3 enabled database connection is closed). It frees the memory
169211  ** allocated for the tokenizer hash table.
169212  */
169213  static void hashDestroy(void *p){
169214    Fts3Hash *pHash = (Fts3Hash *)p;
169215    sqlite3Fts3HashClear(pHash);
169216    sqlite3_free(pHash);
169217  }
169218  
169219  /*
169220  ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
169221  ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
169222  ** respectively. The following three forward declarations are for functions
169223  ** declared in these files used to retrieve the respective implementations.
169224  **
169225  ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
169226  ** to by the argument to point to the "simple" tokenizer implementation.
169227  ** And so on.
169228  */
169229  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
169230  SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
169231  #ifndef SQLITE_DISABLE_FTS3_UNICODE
169232  SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
169233  #endif
169234  #ifdef SQLITE_ENABLE_ICU
169235  SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
169236  #endif
169237  
169238  /*
169239  ** Initialize the fts3 extension. If this extension is built as part
169240  ** of the sqlite library, then this function is called directly by
169241  ** SQLite. If fts3 is built as a dynamically loadable extension, this
169242  ** function is called by the sqlite3_extension_init() entry point.
169243  */
169244  SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
169245    int rc = SQLITE_OK;
169246    Fts3Hash *pHash = 0;
169247    const sqlite3_tokenizer_module *pSimple = 0;
169248    const sqlite3_tokenizer_module *pPorter = 0;
169249  #ifndef SQLITE_DISABLE_FTS3_UNICODE
169250    const sqlite3_tokenizer_module *pUnicode = 0;
169251  #endif
169252  
169253  #ifdef SQLITE_ENABLE_ICU
169254    const sqlite3_tokenizer_module *pIcu = 0;
169255    sqlite3Fts3IcuTokenizerModule(&pIcu);
169256  #endif
169257  
169258  #ifndef SQLITE_DISABLE_FTS3_UNICODE
169259    sqlite3Fts3UnicodeTokenizer(&pUnicode);
169260  #endif
169261  
169262  #ifdef SQLITE_TEST
169263    rc = sqlite3Fts3InitTerm(db);
169264    if( rc!=SQLITE_OK ) return rc;
169265  #endif
169266  
169267    rc = sqlite3Fts3InitAux(db);
169268    if( rc!=SQLITE_OK ) return rc;
169269  
169270    sqlite3Fts3SimpleTokenizerModule(&pSimple);
169271    sqlite3Fts3PorterTokenizerModule(&pPorter);
169272  
169273    /* Allocate and initialize the hash-table used to store tokenizers. */
169274    pHash = sqlite3_malloc(sizeof(Fts3Hash));
169275    if( !pHash ){
169276      rc = SQLITE_NOMEM;
169277    }else{
169278      sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
169279    }
169280  
169281    /* Load the built-in tokenizers into the hash table */
169282    if( rc==SQLITE_OK ){
169283      if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
169284       || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
169285  
169286  #ifndef SQLITE_DISABLE_FTS3_UNICODE
169287       || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
169288  #endif
169289  #ifdef SQLITE_ENABLE_ICU
169290       || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
169291  #endif
169292      ){
169293        rc = SQLITE_NOMEM;
169294      }
169295    }
169296  
169297  #ifdef SQLITE_TEST
169298    if( rc==SQLITE_OK ){
169299      rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
169300    }
169301  #endif
169302  
169303    /* Create the virtual table wrapper around the hash-table and overload 
169304    ** the four scalar functions. If this is successful, register the
169305    ** module with sqlite.
169306    */
169307    if( SQLITE_OK==rc 
169308     && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
169309     && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
169310     && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
169311     && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
169312     && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
169313     && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
169314    ){
169315      rc = sqlite3_create_module_v2(
169316          db, "fts3", &fts3Module, (void *)pHash, hashDestroy
169317      );
169318      if( rc==SQLITE_OK ){
169319        rc = sqlite3_create_module_v2(
169320            db, "fts4", &fts3Module, (void *)pHash, 0
169321        );
169322      }
169323      if( rc==SQLITE_OK ){
169324        rc = sqlite3Fts3InitTok(db, (void *)pHash);
169325      }
169326      return rc;
169327    }
169328  
169329  
169330    /* An error has occurred. Delete the hash table and return the error code. */
169331    assert( rc!=SQLITE_OK );
169332    if( pHash ){
169333      sqlite3Fts3HashClear(pHash);
169334      sqlite3_free(pHash);
169335    }
169336    return rc;
169337  }
169338  
169339  /*
169340  ** Allocate an Fts3MultiSegReader for each token in the expression headed
169341  ** by pExpr. 
169342  **
169343  ** An Fts3SegReader object is a cursor that can seek or scan a range of
169344  ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
169345  ** Fts3SegReader objects internally to provide an interface to seek or scan
169346  ** within the union of all segments of a b-tree. Hence the name.
169347  **
169348  ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
169349  ** segment b-tree (if the term is not a prefix or it is a prefix for which
169350  ** there exists prefix b-tree of the right length) then it may be traversed
169351  ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
169352  ** doclist and then traversed.
169353  */
169354  static void fts3EvalAllocateReaders(
169355    Fts3Cursor *pCsr,               /* FTS cursor handle */
169356    Fts3Expr *pExpr,                /* Allocate readers for this expression */
169357    int *pnToken,                   /* OUT: Total number of tokens in phrase. */
169358    int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
169359    int *pRc                        /* IN/OUT: Error code */
169360  ){
169361    if( pExpr && SQLITE_OK==*pRc ){
169362      if( pExpr->eType==FTSQUERY_PHRASE ){
169363        int i;
169364        int nToken = pExpr->pPhrase->nToken;
169365        *pnToken += nToken;
169366        for(i=0; i<nToken; i++){
169367          Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
169368          int rc = fts3TermSegReaderCursor(pCsr, 
169369              pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
169370          );
169371          if( rc!=SQLITE_OK ){
169372            *pRc = rc;
169373            return;
169374          }
169375        }
169376        assert( pExpr->pPhrase->iDoclistToken==0 );
169377        pExpr->pPhrase->iDoclistToken = -1;
169378      }else{
169379        *pnOr += (pExpr->eType==FTSQUERY_OR);
169380        fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
169381        fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
169382      }
169383    }
169384  }
169385  
169386  /*
169387  ** Arguments pList/nList contain the doclist for token iToken of phrase p.
169388  ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
169389  **
169390  ** This function assumes that pList points to a buffer allocated using
169391  ** sqlite3_malloc(). This function takes responsibility for eventually
169392  ** freeing the buffer.
169393  **
169394  ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
169395  */
169396  static int fts3EvalPhraseMergeToken(
169397    Fts3Table *pTab,                /* FTS Table pointer */
169398    Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
169399    int iToken,                     /* Token pList/nList corresponds to */
169400    char *pList,                    /* Pointer to doclist */
169401    int nList                       /* Number of bytes in pList */
169402  ){
169403    int rc = SQLITE_OK;
169404    assert( iToken!=p->iDoclistToken );
169405  
169406    if( pList==0 ){
169407      sqlite3_free(p->doclist.aAll);
169408      p->doclist.aAll = 0;
169409      p->doclist.nAll = 0;
169410    }
169411  
169412    else if( p->iDoclistToken<0 ){
169413      p->doclist.aAll = pList;
169414      p->doclist.nAll = nList;
169415    }
169416  
169417    else if( p->doclist.aAll==0 ){
169418      sqlite3_free(pList);
169419    }
169420  
169421    else {
169422      char *pLeft;
169423      char *pRight;
169424      int nLeft;
169425      int nRight;
169426      int nDiff;
169427  
169428      if( p->iDoclistToken<iToken ){
169429        pLeft = p->doclist.aAll;
169430        nLeft = p->doclist.nAll;
169431        pRight = pList;
169432        nRight = nList;
169433        nDiff = iToken - p->iDoclistToken;
169434      }else{
169435        pRight = p->doclist.aAll;
169436        nRight = p->doclist.nAll;
169437        pLeft = pList;
169438        nLeft = nList;
169439        nDiff = p->iDoclistToken - iToken;
169440      }
169441  
169442      rc = fts3DoclistPhraseMerge(
169443          pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
169444      );
169445      sqlite3_free(pLeft);
169446      p->doclist.aAll = pRight;
169447      p->doclist.nAll = nRight;
169448    }
169449  
169450    if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
169451    return rc;
169452  }
169453  
169454  /*
169455  ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
169456  ** does not take deferred tokens into account.
169457  **
169458  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
169459  */
169460  static int fts3EvalPhraseLoad(
169461    Fts3Cursor *pCsr,               /* FTS Cursor handle */
169462    Fts3Phrase *p                   /* Phrase object */
169463  ){
169464    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
169465    int iToken;
169466    int rc = SQLITE_OK;
169467  
169468    for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
169469      Fts3PhraseToken *pToken = &p->aToken[iToken];
169470      assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
169471  
169472      if( pToken->pSegcsr ){
169473        int nThis = 0;
169474        char *pThis = 0;
169475        rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
169476        if( rc==SQLITE_OK ){
169477          rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
169478        }
169479      }
169480      assert( pToken->pSegcsr==0 );
169481    }
169482  
169483    return rc;
169484  }
169485  
169486  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
169487  /*
169488  ** This function is called on each phrase after the position lists for
169489  ** any deferred tokens have been loaded into memory. It updates the phrases
169490  ** current position list to include only those positions that are really
169491  ** instances of the phrase (after considering deferred tokens). If this
169492  ** means that the phrase does not appear in the current row, doclist.pList
169493  ** and doclist.nList are both zeroed.
169494  **
169495  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
169496  */
169497  static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
169498    int iToken;                     /* Used to iterate through phrase tokens */
169499    char *aPoslist = 0;             /* Position list for deferred tokens */
169500    int nPoslist = 0;               /* Number of bytes in aPoslist */
169501    int iPrev = -1;                 /* Token number of previous deferred token */
169502  
169503    assert( pPhrase->doclist.bFreeList==0 );
169504  
169505    for(iToken=0; iToken<pPhrase->nToken; iToken++){
169506      Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
169507      Fts3DeferredToken *pDeferred = pToken->pDeferred;
169508  
169509      if( pDeferred ){
169510        char *pList;
169511        int nList;
169512        int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
169513        if( rc!=SQLITE_OK ) return rc;
169514  
169515        if( pList==0 ){
169516          sqlite3_free(aPoslist);
169517          pPhrase->doclist.pList = 0;
169518          pPhrase->doclist.nList = 0;
169519          return SQLITE_OK;
169520  
169521        }else if( aPoslist==0 ){
169522          aPoslist = pList;
169523          nPoslist = nList;
169524  
169525        }else{
169526          char *aOut = pList;
169527          char *p1 = aPoslist;
169528          char *p2 = aOut;
169529  
169530          assert( iPrev>=0 );
169531          fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
169532          sqlite3_free(aPoslist);
169533          aPoslist = pList;
169534          nPoslist = (int)(aOut - aPoslist);
169535          if( nPoslist==0 ){
169536            sqlite3_free(aPoslist);
169537            pPhrase->doclist.pList = 0;
169538            pPhrase->doclist.nList = 0;
169539            return SQLITE_OK;
169540          }
169541        }
169542        iPrev = iToken;
169543      }
169544    }
169545  
169546    if( iPrev>=0 ){
169547      int nMaxUndeferred = pPhrase->iDoclistToken;
169548      if( nMaxUndeferred<0 ){
169549        pPhrase->doclist.pList = aPoslist;
169550        pPhrase->doclist.nList = nPoslist;
169551        pPhrase->doclist.iDocid = pCsr->iPrevId;
169552        pPhrase->doclist.bFreeList = 1;
169553      }else{
169554        int nDistance;
169555        char *p1;
169556        char *p2;
169557        char *aOut;
169558  
169559        if( nMaxUndeferred>iPrev ){
169560          p1 = aPoslist;
169561          p2 = pPhrase->doclist.pList;
169562          nDistance = nMaxUndeferred - iPrev;
169563        }else{
169564          p1 = pPhrase->doclist.pList;
169565          p2 = aPoslist;
169566          nDistance = iPrev - nMaxUndeferred;
169567        }
169568  
169569        aOut = (char *)sqlite3_malloc(nPoslist+8);
169570        if( !aOut ){
169571          sqlite3_free(aPoslist);
169572          return SQLITE_NOMEM;
169573        }
169574        
169575        pPhrase->doclist.pList = aOut;
169576        if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
169577          pPhrase->doclist.bFreeList = 1;
169578          pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
169579        }else{
169580          sqlite3_free(aOut);
169581          pPhrase->doclist.pList = 0;
169582          pPhrase->doclist.nList = 0;
169583        }
169584        sqlite3_free(aPoslist);
169585      }
169586    }
169587  
169588    return SQLITE_OK;
169589  }
169590  #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
169591  
169592  /*
169593  ** Maximum number of tokens a phrase may have to be considered for the
169594  ** incremental doclists strategy.
169595  */
169596  #define MAX_INCR_PHRASE_TOKENS 4
169597  
169598  /*
169599  ** This function is called for each Fts3Phrase in a full-text query 
169600  ** expression to initialize the mechanism for returning rows. Once this
169601  ** function has been called successfully on an Fts3Phrase, it may be
169602  ** used with fts3EvalPhraseNext() to iterate through the matching docids.
169603  **
169604  ** If parameter bOptOk is true, then the phrase may (or may not) use the
169605  ** incremental loading strategy. Otherwise, the entire doclist is loaded into
169606  ** memory within this call.
169607  **
169608  ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
169609  */
169610  static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
169611    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
169612    int rc = SQLITE_OK;             /* Error code */
169613    int i;
169614  
169615    /* Determine if doclists may be loaded from disk incrementally. This is
169616    ** possible if the bOptOk argument is true, the FTS doclists will be
169617    ** scanned in forward order, and the phrase consists of 
169618    ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
169619    ** tokens or prefix tokens that cannot use a prefix-index.  */
169620    int bHaveIncr = 0;
169621    int bIncrOk = (bOptOk 
169622     && pCsr->bDesc==pTab->bDescIdx 
169623     && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
169624  #ifdef SQLITE_TEST
169625     && pTab->bNoIncrDoclist==0
169626  #endif
169627    );
169628    for(i=0; bIncrOk==1 && i<p->nToken; i++){
169629      Fts3PhraseToken *pToken = &p->aToken[i];
169630      if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
169631        bIncrOk = 0;
169632      }
169633      if( pToken->pSegcsr ) bHaveIncr = 1;
169634    }
169635  
169636    if( bIncrOk && bHaveIncr ){
169637      /* Use the incremental approach. */
169638      int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
169639      for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
169640        Fts3PhraseToken *pToken = &p->aToken[i];
169641        Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
169642        if( pSegcsr ){
169643          rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
169644        }
169645      }
169646      p->bIncr = 1;
169647    }else{
169648      /* Load the full doclist for the phrase into memory. */
169649      rc = fts3EvalPhraseLoad(pCsr, p);
169650      p->bIncr = 0;
169651    }
169652  
169653    assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
169654    return rc;
169655  }
169656  
169657  /*
169658  ** This function is used to iterate backwards (from the end to start) 
169659  ** through doclists. It is used by this module to iterate through phrase
169660  ** doclists in reverse and by the fts3_write.c module to iterate through
169661  ** pending-terms lists when writing to databases with "order=desc".
169662  **
169663  ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
169664  ** descending (parameter bDescIdx==1) order of docid. Regardless, this
169665  ** function iterates from the end of the doclist to the beginning.
169666  */
169667  SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
169668    int bDescIdx,                   /* True if the doclist is desc */
169669    char *aDoclist,                 /* Pointer to entire doclist */
169670    int nDoclist,                   /* Length of aDoclist in bytes */
169671    char **ppIter,                  /* IN/OUT: Iterator pointer */
169672    sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
169673    int *pnList,                    /* OUT: List length pointer */
169674    u8 *pbEof                       /* OUT: End-of-file flag */
169675  ){
169676    char *p = *ppIter;
169677  
169678    assert( nDoclist>0 );
169679    assert( *pbEof==0 );
169680    assert( p || *piDocid==0 );
169681    assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
169682  
169683    if( p==0 ){
169684      sqlite3_int64 iDocid = 0;
169685      char *pNext = 0;
169686      char *pDocid = aDoclist;
169687      char *pEnd = &aDoclist[nDoclist];
169688      int iMul = 1;
169689  
169690      while( pDocid<pEnd ){
169691        sqlite3_int64 iDelta;
169692        pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
169693        iDocid += (iMul * iDelta);
169694        pNext = pDocid;
169695        fts3PoslistCopy(0, &pDocid);
169696        while( pDocid<pEnd && *pDocid==0 ) pDocid++;
169697        iMul = (bDescIdx ? -1 : 1);
169698      }
169699  
169700      *pnList = (int)(pEnd - pNext);
169701      *ppIter = pNext;
169702      *piDocid = iDocid;
169703    }else{
169704      int iMul = (bDescIdx ? -1 : 1);
169705      sqlite3_int64 iDelta;
169706      fts3GetReverseVarint(&p, aDoclist, &iDelta);
169707      *piDocid -= (iMul * iDelta);
169708  
169709      if( p==aDoclist ){
169710        *pbEof = 1;
169711      }else{
169712        char *pSave = p;
169713        fts3ReversePoslist(aDoclist, &p);
169714        *pnList = (int)(pSave - p);
169715      }
169716      *ppIter = p;
169717    }
169718  }
169719  
169720  /*
169721  ** Iterate forwards through a doclist.
169722  */
169723  SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
169724    int bDescIdx,                   /* True if the doclist is desc */
169725    char *aDoclist,                 /* Pointer to entire doclist */
169726    int nDoclist,                   /* Length of aDoclist in bytes */
169727    char **ppIter,                  /* IN/OUT: Iterator pointer */
169728    sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
169729    u8 *pbEof                       /* OUT: End-of-file flag */
169730  ){
169731    char *p = *ppIter;
169732  
169733    assert( nDoclist>0 );
169734    assert( *pbEof==0 );
169735    assert( p || *piDocid==0 );
169736    assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
169737  
169738    if( p==0 ){
169739      p = aDoclist;
169740      p += sqlite3Fts3GetVarint(p, piDocid);
169741    }else{
169742      fts3PoslistCopy(0, &p);
169743      while( p<&aDoclist[nDoclist] && *p==0 ) p++; 
169744      if( p>=&aDoclist[nDoclist] ){
169745        *pbEof = 1;
169746      }else{
169747        sqlite3_int64 iVar;
169748        p += sqlite3Fts3GetVarint(p, &iVar);
169749        *piDocid += ((bDescIdx ? -1 : 1) * iVar);
169750      }
169751    }
169752  
169753    *ppIter = p;
169754  }
169755  
169756  /*
169757  ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
169758  ** to true if EOF is reached.
169759  */
169760  static void fts3EvalDlPhraseNext(
169761    Fts3Table *pTab,
169762    Fts3Doclist *pDL,
169763    u8 *pbEof
169764  ){
169765    char *pIter;                            /* Used to iterate through aAll */
169766    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
169767   
169768    if( pDL->pNextDocid ){
169769      pIter = pDL->pNextDocid;
169770    }else{
169771      pIter = pDL->aAll;
169772    }
169773  
169774    if( pIter>=pEnd ){
169775      /* We have already reached the end of this doclist. EOF. */
169776      *pbEof = 1;
169777    }else{
169778      sqlite3_int64 iDelta;
169779      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
169780      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
169781        pDL->iDocid += iDelta;
169782      }else{
169783        pDL->iDocid -= iDelta;
169784      }
169785      pDL->pList = pIter;
169786      fts3PoslistCopy(0, &pIter);
169787      pDL->nList = (int)(pIter - pDL->pList);
169788  
169789      /* pIter now points just past the 0x00 that terminates the position-
169790      ** list for document pDL->iDocid. However, if this position-list was
169791      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
169792      ** point to the start of the next docid value. The following line deals
169793      ** with this case by advancing pIter past the zero-padding added by
169794      ** fts3EvalNearTrim().  */
169795      while( pIter<pEnd && *pIter==0 ) pIter++;
169796  
169797      pDL->pNextDocid = pIter;
169798      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
169799      *pbEof = 0;
169800    }
169801  }
169802  
169803  /*
169804  ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
169805  */
169806  typedef struct TokenDoclist TokenDoclist;
169807  struct TokenDoclist {
169808    int bIgnore;
169809    sqlite3_int64 iDocid;
169810    char *pList;
169811    int nList;
169812  };
169813  
169814  /*
169815  ** Token pToken is an incrementally loaded token that is part of a 
169816  ** multi-token phrase. Advance it to the next matching document in the
169817  ** database and populate output variable *p with the details of the new
169818  ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
169819  **
169820  ** If an error occurs, return an SQLite error code. Otherwise, return 
169821  ** SQLITE_OK.
169822  */
169823  static int incrPhraseTokenNext(
169824    Fts3Table *pTab,                /* Virtual table handle */
169825    Fts3Phrase *pPhrase,            /* Phrase to advance token of */
169826    int iToken,                     /* Specific token to advance */
169827    TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
169828    u8 *pbEof                       /* OUT: True if iterator is at EOF */
169829  ){
169830    int rc = SQLITE_OK;
169831  
169832    if( pPhrase->iDoclistToken==iToken ){
169833      assert( p->bIgnore==0 );
169834      assert( pPhrase->aToken[iToken].pSegcsr==0 );
169835      fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
169836      p->pList = pPhrase->doclist.pList;
169837      p->nList = pPhrase->doclist.nList;
169838      p->iDocid = pPhrase->doclist.iDocid;
169839    }else{
169840      Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
169841      assert( pToken->pDeferred==0 );
169842      assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
169843      if( pToken->pSegcsr ){
169844        assert( p->bIgnore==0 );
169845        rc = sqlite3Fts3MsrIncrNext(
169846            pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
169847        );
169848        if( p->pList==0 ) *pbEof = 1;
169849      }else{
169850        p->bIgnore = 1;
169851      }
169852    }
169853  
169854    return rc;
169855  }
169856  
169857  
169858  /*
169859  ** The phrase iterator passed as the second argument:
169860  **
169861  **   * features at least one token that uses an incremental doclist, and 
169862  **
169863  **   * does not contain any deferred tokens.
169864  **
169865  ** Advance it to the next matching documnent in the database and populate
169866  ** the Fts3Doclist.pList and nList fields. 
169867  **
169868  ** If there is no "next" entry and no error occurs, then *pbEof is set to
169869  ** 1 before returning. Otherwise, if no error occurs and the iterator is
169870  ** successfully advanced, *pbEof is set to 0.
169871  **
169872  ** If an error occurs, return an SQLite error code. Otherwise, return 
169873  ** SQLITE_OK.
169874  */
169875  static int fts3EvalIncrPhraseNext(
169876    Fts3Cursor *pCsr,               /* FTS Cursor handle */
169877    Fts3Phrase *p,                  /* Phrase object to advance to next docid */
169878    u8 *pbEof                       /* OUT: Set to 1 if EOF */
169879  ){
169880    int rc = SQLITE_OK;
169881    Fts3Doclist *pDL = &p->doclist;
169882    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
169883    u8 bEof = 0;
169884  
169885    /* This is only called if it is guaranteed that the phrase has at least
169886    ** one incremental token. In which case the bIncr flag is set. */
169887    assert( p->bIncr==1 );
169888  
169889    if( p->nToken==1 ){
169890      rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
169891          &pDL->iDocid, &pDL->pList, &pDL->nList
169892      );
169893      if( pDL->pList==0 ) bEof = 1;
169894    }else{
169895      int bDescDoclist = pCsr->bDesc;
169896      struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
169897  
169898      memset(a, 0, sizeof(a));
169899      assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
169900      assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
169901  
169902      while( bEof==0 ){
169903        int bMaxSet = 0;
169904        sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
169905        int i;                      /* Used to iterate through tokens */
169906  
169907        /* Advance the iterator for each token in the phrase once. */
169908        for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
169909          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
169910          if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
169911            iMax = a[i].iDocid;
169912            bMaxSet = 1;
169913          }
169914        }
169915        assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
169916        assert( rc!=SQLITE_OK || bMaxSet );
169917  
169918        /* Keep advancing iterators until they all point to the same document */
169919        for(i=0; i<p->nToken; i++){
169920          while( rc==SQLITE_OK && bEof==0 
169921              && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
169922          ){
169923            rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
169924            if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
169925              iMax = a[i].iDocid;
169926              i = 0;
169927            }
169928          }
169929        }
169930  
169931        /* Check if the current entries really are a phrase match */
169932        if( bEof==0 ){
169933          int nList = 0;
169934          int nByte = a[p->nToken-1].nList;
169935          char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
169936          if( !aDoclist ) return SQLITE_NOMEM;
169937          memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
169938          memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
169939  
169940          for(i=0; i<(p->nToken-1); i++){
169941            if( a[i].bIgnore==0 ){
169942              char *pL = a[i].pList;
169943              char *pR = aDoclist;
169944              char *pOut = aDoclist;
169945              int nDist = p->nToken-1-i;
169946              int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
169947              if( res==0 ) break;
169948              nList = (int)(pOut - aDoclist);
169949            }
169950          }
169951          if( i==(p->nToken-1) ){
169952            pDL->iDocid = iMax;
169953            pDL->pList = aDoclist;
169954            pDL->nList = nList;
169955            pDL->bFreeList = 1;
169956            break;
169957          }
169958          sqlite3_free(aDoclist);
169959        }
169960      }
169961    }
169962  
169963    *pbEof = bEof;
169964    return rc;
169965  }
169966  
169967  /*
169968  ** Attempt to move the phrase iterator to point to the next matching docid. 
169969  ** If an error occurs, return an SQLite error code. Otherwise, return 
169970  ** SQLITE_OK.
169971  **
169972  ** If there is no "next" entry and no error occurs, then *pbEof is set to
169973  ** 1 before returning. Otherwise, if no error occurs and the iterator is
169974  ** successfully advanced, *pbEof is set to 0.
169975  */
169976  static int fts3EvalPhraseNext(
169977    Fts3Cursor *pCsr,               /* FTS Cursor handle */
169978    Fts3Phrase *p,                  /* Phrase object to advance to next docid */
169979    u8 *pbEof                       /* OUT: Set to 1 if EOF */
169980  ){
169981    int rc = SQLITE_OK;
169982    Fts3Doclist *pDL = &p->doclist;
169983    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
169984  
169985    if( p->bIncr ){
169986      rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
169987    }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
169988      sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
169989          &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
169990      );
169991      pDL->pList = pDL->pNextDocid;
169992    }else{
169993      fts3EvalDlPhraseNext(pTab, pDL, pbEof);
169994    }
169995  
169996    return rc;
169997  }
169998  
169999  /*
170000  **
170001  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
170002  ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
170003  ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
170004  ** expressions for which all descendent tokens are deferred.
170005  **
170006  ** If parameter bOptOk is zero, then it is guaranteed that the
170007  ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
170008  ** each phrase in the expression (subject to deferred token processing).
170009  ** Or, if bOptOk is non-zero, then one or more tokens within the expression
170010  ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
170011  **
170012  ** If an error occurs within this function, *pRc is set to an SQLite error
170013  ** code before returning.
170014  */
170015  static void fts3EvalStartReaders(
170016    Fts3Cursor *pCsr,               /* FTS Cursor handle */
170017    Fts3Expr *pExpr,                /* Expression to initialize phrases in */
170018    int *pRc                        /* IN/OUT: Error code */
170019  ){
170020    if( pExpr && SQLITE_OK==*pRc ){
170021      if( pExpr->eType==FTSQUERY_PHRASE ){
170022        int nToken = pExpr->pPhrase->nToken;
170023        if( nToken ){
170024          int i;
170025          for(i=0; i<nToken; i++){
170026            if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
170027          }
170028          pExpr->bDeferred = (i==nToken);
170029        }
170030        *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
170031      }else{
170032        fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
170033        fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
170034        pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
170035      }
170036    }
170037  }
170038  
170039  /*
170040  ** An array of the following structures is assembled as part of the process
170041  ** of selecting tokens to defer before the query starts executing (as part
170042  ** of the xFilter() method). There is one element in the array for each
170043  ** token in the FTS expression.
170044  **
170045  ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
170046  ** to phrases that are connected only by AND and NEAR operators (not OR or
170047  ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
170048  ** separately. The root of a tokens AND/NEAR cluster is stored in 
170049  ** Fts3TokenAndCost.pRoot.
170050  */
170051  typedef struct Fts3TokenAndCost Fts3TokenAndCost;
170052  struct Fts3TokenAndCost {
170053    Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
170054    int iToken;                     /* Position of token in phrase */
170055    Fts3PhraseToken *pToken;        /* The token itself */
170056    Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
170057    int nOvfl;                      /* Number of overflow pages to load doclist */
170058    int iCol;                       /* The column the token must match */
170059  };
170060  
170061  /*
170062  ** This function is used to populate an allocated Fts3TokenAndCost array.
170063  **
170064  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
170065  ** Otherwise, if an error occurs during execution, *pRc is set to an
170066  ** SQLite error code.
170067  */
170068  static void fts3EvalTokenCosts(
170069    Fts3Cursor *pCsr,               /* FTS Cursor handle */
170070    Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
170071    Fts3Expr *pExpr,                /* Expression to consider */
170072    Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
170073    Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
170074    int *pRc                        /* IN/OUT: Error code */
170075  ){
170076    if( *pRc==SQLITE_OK ){
170077      if( pExpr->eType==FTSQUERY_PHRASE ){
170078        Fts3Phrase *pPhrase = pExpr->pPhrase;
170079        int i;
170080        for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
170081          Fts3TokenAndCost *pTC = (*ppTC)++;
170082          pTC->pPhrase = pPhrase;
170083          pTC->iToken = i;
170084          pTC->pRoot = pRoot;
170085          pTC->pToken = &pPhrase->aToken[i];
170086          pTC->iCol = pPhrase->iColumn;
170087          *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
170088        }
170089      }else if( pExpr->eType!=FTSQUERY_NOT ){
170090        assert( pExpr->eType==FTSQUERY_OR
170091             || pExpr->eType==FTSQUERY_AND
170092             || pExpr->eType==FTSQUERY_NEAR
170093        );
170094        assert( pExpr->pLeft && pExpr->pRight );
170095        if( pExpr->eType==FTSQUERY_OR ){
170096          pRoot = pExpr->pLeft;
170097          **ppOr = pRoot;
170098          (*ppOr)++;
170099        }
170100        fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
170101        if( pExpr->eType==FTSQUERY_OR ){
170102          pRoot = pExpr->pRight;
170103          **ppOr = pRoot;
170104          (*ppOr)++;
170105        }
170106        fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
170107      }
170108    }
170109  }
170110  
170111  /*
170112  ** Determine the average document (row) size in pages. If successful,
170113  ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
170114  ** an SQLite error code.
170115  **
170116  ** The average document size in pages is calculated by first calculating 
170117  ** determining the average size in bytes, B. If B is less than the amount
170118  ** of data that will fit on a single leaf page of an intkey table in
170119  ** this database, then the average docsize is 1. Otherwise, it is 1 plus
170120  ** the number of overflow pages consumed by a record B bytes in size.
170121  */
170122  static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
170123    int rc = SQLITE_OK;
170124    if( pCsr->nRowAvg==0 ){
170125      /* The average document size, which is required to calculate the cost
170126      ** of each doclist, has not yet been determined. Read the required 
170127      ** data from the %_stat table to calculate it.
170128      **
170129      ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
170130      ** varints, where nCol is the number of columns in the FTS3 table.
170131      ** The first varint is the number of documents currently stored in
170132      ** the table. The following nCol varints contain the total amount of
170133      ** data stored in all rows of each column of the table, from left
170134      ** to right.
170135      */
170136      Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
170137      sqlite3_stmt *pStmt;
170138      sqlite3_int64 nDoc = 0;
170139      sqlite3_int64 nByte = 0;
170140      const char *pEnd;
170141      const char *a;
170142  
170143      rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
170144      if( rc!=SQLITE_OK ) return rc;
170145      a = sqlite3_column_blob(pStmt, 0);
170146      assert( a );
170147  
170148      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
170149      a += sqlite3Fts3GetVarint(a, &nDoc);
170150      while( a<pEnd ){
170151        a += sqlite3Fts3GetVarint(a, &nByte);
170152      }
170153      if( nDoc==0 || nByte==0 ){
170154        sqlite3_reset(pStmt);
170155        return FTS_CORRUPT_VTAB;
170156      }
170157  
170158      pCsr->nDoc = nDoc;
170159      pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
170160      assert( pCsr->nRowAvg>0 ); 
170161      rc = sqlite3_reset(pStmt);
170162    }
170163  
170164    *pnPage = pCsr->nRowAvg;
170165    return rc;
170166  }
170167  
170168  /*
170169  ** This function is called to select the tokens (if any) that will be 
170170  ** deferred. The array aTC[] has already been populated when this is
170171  ** called.
170172  **
170173  ** This function is called once for each AND/NEAR cluster in the 
170174  ** expression. Each invocation determines which tokens to defer within
170175  ** the cluster with root node pRoot. See comments above the definition
170176  ** of struct Fts3TokenAndCost for more details.
170177  **
170178  ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
170179  ** called on each token to defer. Otherwise, an SQLite error code is
170180  ** returned.
170181  */
170182  static int fts3EvalSelectDeferred(
170183    Fts3Cursor *pCsr,               /* FTS Cursor handle */
170184    Fts3Expr *pRoot,                /* Consider tokens with this root node */
170185    Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
170186    int nTC                         /* Number of entries in aTC[] */
170187  ){
170188    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
170189    int nDocSize = 0;               /* Number of pages per doc loaded */
170190    int rc = SQLITE_OK;             /* Return code */
170191    int ii;                         /* Iterator variable for various purposes */
170192    int nOvfl = 0;                  /* Total overflow pages used by doclists */
170193    int nToken = 0;                 /* Total number of tokens in cluster */
170194  
170195    int nMinEst = 0;                /* The minimum count for any phrase so far. */
170196    int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
170197  
170198    /* Tokens are never deferred for FTS tables created using the content=xxx
170199    ** option. The reason being that it is not guaranteed that the content
170200    ** table actually contains the same data as the index. To prevent this from
170201    ** causing any problems, the deferred token optimization is completely
170202    ** disabled for content=xxx tables. */
170203    if( pTab->zContentTbl ){
170204      return SQLITE_OK;
170205    }
170206  
170207    /* Count the tokens in this AND/NEAR cluster. If none of the doclists
170208    ** associated with the tokens spill onto overflow pages, or if there is
170209    ** only 1 token, exit early. No tokens to defer in this case. */
170210    for(ii=0; ii<nTC; ii++){
170211      if( aTC[ii].pRoot==pRoot ){
170212        nOvfl += aTC[ii].nOvfl;
170213        nToken++;
170214      }
170215    }
170216    if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
170217  
170218    /* Obtain the average docsize (in pages). */
170219    rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
170220    assert( rc!=SQLITE_OK || nDocSize>0 );
170221  
170222  
170223    /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
170224    ** of the number of overflow pages that will be loaded by the pager layer 
170225    ** to retrieve the entire doclist for the token from the full-text index.
170226    ** Load the doclists for tokens that are either:
170227    **
170228    **   a. The cheapest token in the entire query (i.e. the one visited by the
170229    **      first iteration of this loop), or
170230    **
170231    **   b. Part of a multi-token phrase.
170232    **
170233    ** After each token doclist is loaded, merge it with the others from the
170234    ** same phrase and count the number of documents that the merged doclist
170235    ** contains. Set variable "nMinEst" to the smallest number of documents in 
170236    ** any phrase doclist for which 1 or more token doclists have been loaded.
170237    ** Let nOther be the number of other phrases for which it is certain that
170238    ** one or more tokens will not be deferred.
170239    **
170240    ** Then, for each token, defer it if loading the doclist would result in
170241    ** loading N or more overflow pages into memory, where N is computed as:
170242    **
170243    **    (nMinEst + 4^nOther - 1) / (4^nOther)
170244    */
170245    for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
170246      int iTC;                      /* Used to iterate through aTC[] array. */
170247      Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
170248  
170249      /* Set pTC to point to the cheapest remaining token. */
170250      for(iTC=0; iTC<nTC; iTC++){
170251        if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
170252         && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
170253        ){
170254          pTC = &aTC[iTC];
170255        }
170256      }
170257      assert( pTC );
170258  
170259      if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
170260        /* The number of overflow pages to load for this (and therefore all
170261        ** subsequent) tokens is greater than the estimated number of pages 
170262        ** that will be loaded if all subsequent tokens are deferred.
170263        */
170264        Fts3PhraseToken *pToken = pTC->pToken;
170265        rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
170266        fts3SegReaderCursorFree(pToken->pSegcsr);
170267        pToken->pSegcsr = 0;
170268      }else{
170269        /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
170270        ** for-loop. Except, limit the value to 2^24 to prevent it from 
170271        ** overflowing the 32-bit integer it is stored in. */
170272        if( ii<12 ) nLoad4 = nLoad4*4;
170273  
170274        if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
170275          /* Either this is the cheapest token in the entire query, or it is
170276          ** part of a multi-token phrase. Either way, the entire doclist will
170277          ** (eventually) be loaded into memory. It may as well be now. */
170278          Fts3PhraseToken *pToken = pTC->pToken;
170279          int nList = 0;
170280          char *pList = 0;
170281          rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
170282          assert( rc==SQLITE_OK || pList==0 );
170283          if( rc==SQLITE_OK ){
170284            rc = fts3EvalPhraseMergeToken(
170285                pTab, pTC->pPhrase, pTC->iToken,pList,nList
170286            );
170287          }
170288          if( rc==SQLITE_OK ){
170289            int nCount;
170290            nCount = fts3DoclistCountDocids(
170291                pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
170292            );
170293            if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
170294          }
170295        }
170296      }
170297      pTC->pToken = 0;
170298    }
170299  
170300    return rc;
170301  }
170302  
170303  /*
170304  ** This function is called from within the xFilter method. It initializes
170305  ** the full-text query currently stored in pCsr->pExpr. To iterate through
170306  ** the results of a query, the caller does:
170307  **
170308  **    fts3EvalStart(pCsr);
170309  **    while( 1 ){
170310  **      fts3EvalNext(pCsr);
170311  **      if( pCsr->bEof ) break;
170312  **      ... return row pCsr->iPrevId to the caller ...
170313  **    }
170314  */
170315  static int fts3EvalStart(Fts3Cursor *pCsr){
170316    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
170317    int rc = SQLITE_OK;
170318    int nToken = 0;
170319    int nOr = 0;
170320  
170321    /* Allocate a MultiSegReader for each token in the expression. */
170322    fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
170323  
170324    /* Determine which, if any, tokens in the expression should be deferred. */
170325  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
170326    if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
170327      Fts3TokenAndCost *aTC;
170328      Fts3Expr **apOr;
170329      aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
170330          sizeof(Fts3TokenAndCost) * nToken
170331        + sizeof(Fts3Expr *) * nOr * 2
170332      );
170333      apOr = (Fts3Expr **)&aTC[nToken];
170334  
170335      if( !aTC ){
170336        rc = SQLITE_NOMEM;
170337      }else{
170338        int ii;
170339        Fts3TokenAndCost *pTC = aTC;
170340        Fts3Expr **ppOr = apOr;
170341  
170342        fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
170343        nToken = (int)(pTC-aTC);
170344        nOr = (int)(ppOr-apOr);
170345  
170346        if( rc==SQLITE_OK ){
170347          rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
170348          for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
170349            rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
170350          }
170351        }
170352  
170353        sqlite3_free(aTC);
170354      }
170355    }
170356  #endif
170357  
170358    fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
170359    return rc;
170360  }
170361  
170362  /*
170363  ** Invalidate the current position list for phrase pPhrase.
170364  */
170365  static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
170366    if( pPhrase->doclist.bFreeList ){
170367      sqlite3_free(pPhrase->doclist.pList);
170368    }
170369    pPhrase->doclist.pList = 0;
170370    pPhrase->doclist.nList = 0;
170371    pPhrase->doclist.bFreeList = 0;
170372  }
170373  
170374  /*
170375  ** This function is called to edit the position list associated with
170376  ** the phrase object passed as the fifth argument according to a NEAR
170377  ** condition. For example:
170378  **
170379  **     abc NEAR/5 "def ghi"
170380  **
170381  ** Parameter nNear is passed the NEAR distance of the expression (5 in
170382  ** the example above). When this function is called, *paPoslist points to
170383  ** the position list, and *pnToken is the number of phrase tokens in, the
170384  ** phrase on the other side of the NEAR operator to pPhrase. For example,
170385  ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
170386  ** the position list associated with phrase "abc".
170387  **
170388  ** All positions in the pPhrase position list that are not sufficiently
170389  ** close to a position in the *paPoslist position list are removed. If this
170390  ** leaves 0 positions, zero is returned. Otherwise, non-zero.
170391  **
170392  ** Before returning, *paPoslist is set to point to the position lsit 
170393  ** associated with pPhrase. And *pnToken is set to the number of tokens in
170394  ** pPhrase.
170395  */
170396  static int fts3EvalNearTrim(
170397    int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
170398    char *aTmp,                     /* Temporary space to use */
170399    char **paPoslist,               /* IN/OUT: Position list */
170400    int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
170401    Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
170402  ){
170403    int nParam1 = nNear + pPhrase->nToken;
170404    int nParam2 = nNear + *pnToken;
170405    int nNew;
170406    char *p2; 
170407    char *pOut; 
170408    int res;
170409  
170410    assert( pPhrase->doclist.pList );
170411  
170412    p2 = pOut = pPhrase->doclist.pList;
170413    res = fts3PoslistNearMerge(
170414      &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
170415    );
170416    if( res ){
170417      nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
170418      assert( pPhrase->doclist.pList[nNew]=='\0' );
170419      assert( nNew<=pPhrase->doclist.nList && nNew>0 );
170420      memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
170421      pPhrase->doclist.nList = nNew;
170422      *paPoslist = pPhrase->doclist.pList;
170423      *pnToken = pPhrase->nToken;
170424    }
170425  
170426    return res;
170427  }
170428  
170429  /*
170430  ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
170431  ** Otherwise, it advances the expression passed as the second argument to
170432  ** point to the next matching row in the database. Expressions iterate through
170433  ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
170434  ** or descending if it is non-zero.
170435  **
170436  ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
170437  ** successful, the following variables in pExpr are set:
170438  **
170439  **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
170440  **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
170441  **
170442  ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
170443  ** at EOF, then the following variables are populated with the position list
170444  ** for the phrase for the visited row:
170445  **
170446  **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
170447  **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
170448  **
170449  ** It says above that this function advances the expression to the next
170450  ** matching row. This is usually true, but there are the following exceptions:
170451  **
170452  **   1. Deferred tokens are not taken into account. If a phrase consists
170453  **      entirely of deferred tokens, it is assumed to match every row in
170454  **      the db. In this case the position-list is not populated at all. 
170455  **
170456  **      Or, if a phrase contains one or more deferred tokens and one or
170457  **      more non-deferred tokens, then the expression is advanced to the 
170458  **      next possible match, considering only non-deferred tokens. In other
170459  **      words, if the phrase is "A B C", and "B" is deferred, the expression
170460  **      is advanced to the next row that contains an instance of "A * C", 
170461  **      where "*" may match any single token. The position list in this case
170462  **      is populated as for "A * C" before returning.
170463  **
170464  **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
170465  **      advanced to point to the next row that matches "x AND y".
170466  ** 
170467  ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
170468  ** really a match, taking into account deferred tokens and NEAR operators.
170469  */
170470  static void fts3EvalNextRow(
170471    Fts3Cursor *pCsr,               /* FTS Cursor handle */
170472    Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
170473    int *pRc                        /* IN/OUT: Error code */
170474  ){
170475    if( *pRc==SQLITE_OK ){
170476      int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
170477      assert( pExpr->bEof==0 );
170478      pExpr->bStart = 1;
170479  
170480      switch( pExpr->eType ){
170481        case FTSQUERY_NEAR:
170482        case FTSQUERY_AND: {
170483          Fts3Expr *pLeft = pExpr->pLeft;
170484          Fts3Expr *pRight = pExpr->pRight;
170485          assert( !pLeft->bDeferred || !pRight->bDeferred );
170486  
170487          if( pLeft->bDeferred ){
170488            /* LHS is entirely deferred. So we assume it matches every row.
170489            ** Advance the RHS iterator to find the next row visited. */
170490            fts3EvalNextRow(pCsr, pRight, pRc);
170491            pExpr->iDocid = pRight->iDocid;
170492            pExpr->bEof = pRight->bEof;
170493          }else if( pRight->bDeferred ){
170494            /* RHS is entirely deferred. So we assume it matches every row.
170495            ** Advance the LHS iterator to find the next row visited. */
170496            fts3EvalNextRow(pCsr, pLeft, pRc);
170497            pExpr->iDocid = pLeft->iDocid;
170498            pExpr->bEof = pLeft->bEof;
170499          }else{
170500            /* Neither the RHS or LHS are deferred. */
170501            fts3EvalNextRow(pCsr, pLeft, pRc);
170502            fts3EvalNextRow(pCsr, pRight, pRc);
170503            while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
170504              sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
170505              if( iDiff==0 ) break;
170506              if( iDiff<0 ){
170507                fts3EvalNextRow(pCsr, pLeft, pRc);
170508              }else{
170509                fts3EvalNextRow(pCsr, pRight, pRc);
170510              }
170511            }
170512            pExpr->iDocid = pLeft->iDocid;
170513            pExpr->bEof = (pLeft->bEof || pRight->bEof);
170514            if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
170515              assert( pRight->eType==FTSQUERY_PHRASE );
170516              if( pRight->pPhrase->doclist.aAll ){
170517                Fts3Doclist *pDl = &pRight->pPhrase->doclist;
170518                while( *pRc==SQLITE_OK && pRight->bEof==0 ){
170519                  memset(pDl->pList, 0, pDl->nList);
170520                  fts3EvalNextRow(pCsr, pRight, pRc);
170521                }
170522              }
170523              if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
170524                Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
170525                while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
170526                  memset(pDl->pList, 0, pDl->nList);
170527                  fts3EvalNextRow(pCsr, pLeft, pRc);
170528                }
170529              }
170530            }
170531          }
170532          break;
170533        }
170534    
170535        case FTSQUERY_OR: {
170536          Fts3Expr *pLeft = pExpr->pLeft;
170537          Fts3Expr *pRight = pExpr->pRight;
170538          sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
170539  
170540          assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
170541          assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
170542  
170543          if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
170544            fts3EvalNextRow(pCsr, pLeft, pRc);
170545          }else if( pLeft->bEof || iCmp>0 ){
170546            fts3EvalNextRow(pCsr, pRight, pRc);
170547          }else{
170548            fts3EvalNextRow(pCsr, pLeft, pRc);
170549            fts3EvalNextRow(pCsr, pRight, pRc);
170550          }
170551  
170552          pExpr->bEof = (pLeft->bEof && pRight->bEof);
170553          iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
170554          if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
170555            pExpr->iDocid = pLeft->iDocid;
170556          }else{
170557            pExpr->iDocid = pRight->iDocid;
170558          }
170559  
170560          break;
170561        }
170562  
170563        case FTSQUERY_NOT: {
170564          Fts3Expr *pLeft = pExpr->pLeft;
170565          Fts3Expr *pRight = pExpr->pRight;
170566  
170567          if( pRight->bStart==0 ){
170568            fts3EvalNextRow(pCsr, pRight, pRc);
170569            assert( *pRc!=SQLITE_OK || pRight->bStart );
170570          }
170571  
170572          fts3EvalNextRow(pCsr, pLeft, pRc);
170573          if( pLeft->bEof==0 ){
170574            while( !*pRc 
170575                && !pRight->bEof 
170576                && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
170577            ){
170578              fts3EvalNextRow(pCsr, pRight, pRc);
170579            }
170580          }
170581          pExpr->iDocid = pLeft->iDocid;
170582          pExpr->bEof = pLeft->bEof;
170583          break;
170584        }
170585  
170586        default: {
170587          Fts3Phrase *pPhrase = pExpr->pPhrase;
170588          fts3EvalInvalidatePoslist(pPhrase);
170589          *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
170590          pExpr->iDocid = pPhrase->doclist.iDocid;
170591          break;
170592        }
170593      }
170594    }
170595  }
170596  
170597  /*
170598  ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
170599  ** cluster, then this function returns 1 immediately.
170600  **
170601  ** Otherwise, it checks if the current row really does match the NEAR 
170602  ** expression, using the data currently stored in the position lists 
170603  ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
170604  **
170605  ** If the current row is a match, the position list associated with each
170606  ** phrase in the NEAR expression is edited in place to contain only those
170607  ** phrase instances sufficiently close to their peers to satisfy all NEAR
170608  ** constraints. In this case it returns 1. If the NEAR expression does not 
170609  ** match the current row, 0 is returned. The position lists may or may not
170610  ** be edited if 0 is returned.
170611  */
170612  static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
170613    int res = 1;
170614  
170615    /* The following block runs if pExpr is the root of a NEAR query.
170616    ** For example, the query:
170617    **
170618    **         "w" NEAR "x" NEAR "y" NEAR "z"
170619    **
170620    ** which is represented in tree form as:
170621    **
170622    **                               |
170623    **                          +--NEAR--+      <-- root of NEAR query
170624    **                          |        |
170625    **                     +--NEAR--+   "z"
170626    **                     |        |
170627    **                +--NEAR--+   "y"
170628    **                |        |
170629    **               "w"      "x"
170630    **
170631    ** The right-hand child of a NEAR node is always a phrase. The 
170632    ** left-hand child may be either a phrase or a NEAR node. There are
170633    ** no exceptions to this - it's the way the parser in fts3_expr.c works.
170634    */
170635    if( *pRc==SQLITE_OK 
170636     && pExpr->eType==FTSQUERY_NEAR 
170637     && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
170638    ){
170639      Fts3Expr *p; 
170640      sqlite3_int64 nTmp = 0;       /* Bytes of temp space */
170641      char *aTmp;                   /* Temp space for PoslistNearMerge() */
170642  
170643      /* Allocate temporary working space. */
170644      for(p=pExpr; p->pLeft; p=p->pLeft){
170645        assert( p->pRight->pPhrase->doclist.nList>0 );
170646        nTmp += p->pRight->pPhrase->doclist.nList;
170647      }
170648      nTmp += p->pPhrase->doclist.nList;
170649      aTmp = sqlite3_malloc64(nTmp*2);
170650      if( !aTmp ){
170651        *pRc = SQLITE_NOMEM;
170652        res = 0;
170653      }else{
170654        char *aPoslist = p->pPhrase->doclist.pList;
170655        int nToken = p->pPhrase->nToken;
170656  
170657        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
170658          Fts3Phrase *pPhrase = p->pRight->pPhrase;
170659          int nNear = p->nNear;
170660          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
170661        }
170662  
170663        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
170664        nToken = pExpr->pRight->pPhrase->nToken;
170665        for(p=pExpr->pLeft; p && res; p=p->pLeft){
170666          int nNear;
170667          Fts3Phrase *pPhrase;
170668          assert( p->pParent && p->pParent->pLeft==p );
170669          nNear = p->pParent->nNear;
170670          pPhrase = (
170671              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
170672          );
170673          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
170674        }
170675      }
170676  
170677      sqlite3_free(aTmp);
170678    }
170679  
170680    return res;
170681  }
170682  
170683  /*
170684  ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
170685  ** Assuming no error occurs or has occurred, It returns non-zero if the
170686  ** expression passed as the second argument matches the row that pCsr 
170687  ** currently points to, or zero if it does not.
170688  **
170689  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
170690  ** If an error occurs during execution of this function, *pRc is set to 
170691  ** the appropriate SQLite error code. In this case the returned value is 
170692  ** undefined.
170693  */
170694  static int fts3EvalTestExpr(
170695    Fts3Cursor *pCsr,               /* FTS cursor handle */
170696    Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
170697    int *pRc                        /* IN/OUT: Error code */
170698  ){
170699    int bHit = 1;                   /* Return value */
170700    if( *pRc==SQLITE_OK ){
170701      switch( pExpr->eType ){
170702        case FTSQUERY_NEAR:
170703        case FTSQUERY_AND:
170704          bHit = (
170705              fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
170706           && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
170707           && fts3EvalNearTest(pExpr, pRc)
170708          );
170709  
170710          /* If the NEAR expression does not match any rows, zero the doclist for 
170711          ** all phrases involved in the NEAR. This is because the snippet(),
170712          ** offsets() and matchinfo() functions are not supposed to recognize 
170713          ** any instances of phrases that are part of unmatched NEAR queries. 
170714          ** For example if this expression:
170715          **
170716          **    ... MATCH 'a OR (b NEAR c)'
170717          **
170718          ** is matched against a row containing:
170719          **
170720          **        'a b d e'
170721          **
170722          ** then any snippet() should ony highlight the "a" term, not the "b"
170723          ** (as "b" is part of a non-matching NEAR clause).
170724          */
170725          if( bHit==0 
170726           && pExpr->eType==FTSQUERY_NEAR 
170727           && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
170728          ){
170729            Fts3Expr *p;
170730            for(p=pExpr; p->pPhrase==0; p=p->pLeft){
170731              if( p->pRight->iDocid==pCsr->iPrevId ){
170732                fts3EvalInvalidatePoslist(p->pRight->pPhrase);
170733              }
170734            }
170735            if( p->iDocid==pCsr->iPrevId ){
170736              fts3EvalInvalidatePoslist(p->pPhrase);
170737            }
170738          }
170739  
170740          break;
170741  
170742        case FTSQUERY_OR: {
170743          int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
170744          int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
170745          bHit = bHit1 || bHit2;
170746          break;
170747        }
170748  
170749        case FTSQUERY_NOT:
170750          bHit = (
170751              fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
170752           && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
170753          );
170754          break;
170755  
170756        default: {
170757  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
170758          if( pCsr->pDeferred 
170759           && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
170760          ){
170761            Fts3Phrase *pPhrase = pExpr->pPhrase;
170762            assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
170763            if( pExpr->bDeferred ){
170764              fts3EvalInvalidatePoslist(pPhrase);
170765            }
170766            *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
170767            bHit = (pPhrase->doclist.pList!=0);
170768            pExpr->iDocid = pCsr->iPrevId;
170769          }else
170770  #endif
170771          {
170772            bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
170773          }
170774          break;
170775        }
170776      }
170777    }
170778    return bHit;
170779  }
170780  
170781  /*
170782  ** This function is called as the second part of each xNext operation when
170783  ** iterating through the results of a full-text query. At this point the
170784  ** cursor points to a row that matches the query expression, with the
170785  ** following caveats:
170786  **
170787  **   * Up until this point, "NEAR" operators in the expression have been
170788  **     treated as "AND".
170789  **
170790  **   * Deferred tokens have not yet been considered.
170791  **
170792  ** If *pRc is not SQLITE_OK when this function is called, it immediately
170793  ** returns 0. Otherwise, it tests whether or not after considering NEAR
170794  ** operators and deferred tokens the current row is still a match for the
170795  ** expression. It returns 1 if both of the following are true:
170796  **
170797  **   1. *pRc is SQLITE_OK when this function returns, and
170798  **
170799  **   2. After scanning the current FTS table row for the deferred tokens,
170800  **      it is determined that the row does *not* match the query.
170801  **
170802  ** Or, if no error occurs and it seems the current row does match the FTS
170803  ** query, return 0.
170804  */
170805  SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
170806    int rc = *pRc;
170807    int bMiss = 0;
170808    if( rc==SQLITE_OK ){
170809  
170810      /* If there are one or more deferred tokens, load the current row into
170811      ** memory and scan it to determine the position list for each deferred
170812      ** token. Then, see if this row is really a match, considering deferred
170813      ** tokens and NEAR operators (neither of which were taken into account
170814      ** earlier, by fts3EvalNextRow()). 
170815      */
170816      if( pCsr->pDeferred ){
170817        rc = fts3CursorSeek(0, pCsr);
170818        if( rc==SQLITE_OK ){
170819          rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
170820        }
170821      }
170822      bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
170823  
170824      /* Free the position-lists accumulated for each deferred token above. */
170825      sqlite3Fts3FreeDeferredDoclists(pCsr);
170826      *pRc = rc;
170827    }
170828    return (rc==SQLITE_OK && bMiss);
170829  }
170830  
170831  /*
170832  ** Advance to the next document that matches the FTS expression in
170833  ** Fts3Cursor.pExpr.
170834  */
170835  static int fts3EvalNext(Fts3Cursor *pCsr){
170836    int rc = SQLITE_OK;             /* Return Code */
170837    Fts3Expr *pExpr = pCsr->pExpr;
170838    assert( pCsr->isEof==0 );
170839    if( pExpr==0 ){
170840      pCsr->isEof = 1;
170841    }else{
170842      do {
170843        if( pCsr->isRequireSeek==0 ){
170844          sqlite3_reset(pCsr->pStmt);
170845        }
170846        assert( sqlite3_data_count(pCsr->pStmt)==0 );
170847        fts3EvalNextRow(pCsr, pExpr, &rc);
170848        pCsr->isEof = pExpr->bEof;
170849        pCsr->isRequireSeek = 1;
170850        pCsr->isMatchinfoNeeded = 1;
170851        pCsr->iPrevId = pExpr->iDocid;
170852      }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
170853    }
170854  
170855    /* Check if the cursor is past the end of the docid range specified
170856    ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
170857    if( rc==SQLITE_OK && (
170858          (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
170859       || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
170860    )){
170861      pCsr->isEof = 1;
170862    }
170863  
170864    return rc;
170865  }
170866  
170867  /*
170868  ** Restart interation for expression pExpr so that the next call to
170869  ** fts3EvalNext() visits the first row. Do not allow incremental 
170870  ** loading or merging of phrase doclists for this iteration.
170871  **
170872  ** If *pRc is other than SQLITE_OK when this function is called, it is
170873  ** a no-op. If an error occurs within this function, *pRc is set to an
170874  ** SQLite error code before returning.
170875  */
170876  static void fts3EvalRestart(
170877    Fts3Cursor *pCsr,
170878    Fts3Expr *pExpr,
170879    int *pRc
170880  ){
170881    if( pExpr && *pRc==SQLITE_OK ){
170882      Fts3Phrase *pPhrase = pExpr->pPhrase;
170883  
170884      if( pPhrase ){
170885        fts3EvalInvalidatePoslist(pPhrase);
170886        if( pPhrase->bIncr ){
170887          int i;
170888          for(i=0; i<pPhrase->nToken; i++){
170889            Fts3PhraseToken *pToken = &pPhrase->aToken[i];
170890            assert( pToken->pDeferred==0 );
170891            if( pToken->pSegcsr ){
170892              sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
170893            }
170894          }
170895          *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
170896        }
170897        pPhrase->doclist.pNextDocid = 0;
170898        pPhrase->doclist.iDocid = 0;
170899        pPhrase->pOrPoslist = 0;
170900      }
170901  
170902      pExpr->iDocid = 0;
170903      pExpr->bEof = 0;
170904      pExpr->bStart = 0;
170905  
170906      fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
170907      fts3EvalRestart(pCsr, pExpr->pRight, pRc);
170908    }
170909  }
170910  
170911  /*
170912  ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
170913  ** expression rooted at pExpr, the cursor iterates through all rows matched
170914  ** by pExpr, calling this function for each row. This function increments
170915  ** the values in Fts3Expr.aMI[] according to the position-list currently
170916  ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
170917  ** expression nodes.
170918  */
170919  static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
170920    if( pExpr ){
170921      Fts3Phrase *pPhrase = pExpr->pPhrase;
170922      if( pPhrase && pPhrase->doclist.pList ){
170923        int iCol = 0;
170924        char *p = pPhrase->doclist.pList;
170925  
170926        do{
170927          u8 c = 0;
170928          int iCnt = 0;
170929          while( 0xFE & (*p | c) ){
170930            if( (c&0x80)==0 ) iCnt++;
170931            c = *p++ & 0x80;
170932          }
170933  
170934          /* aMI[iCol*3 + 1] = Number of occurrences
170935          ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
170936          */
170937          pExpr->aMI[iCol*3 + 1] += iCnt;
170938          pExpr->aMI[iCol*3 + 2] += (iCnt>0);
170939          if( *p==0x00 ) break;
170940          p++;
170941          p += fts3GetVarint32(p, &iCol);
170942        }while( iCol<nCol );
170943      }
170944  
170945      fts3EvalUpdateCounts(pExpr->pLeft, nCol);
170946      fts3EvalUpdateCounts(pExpr->pRight, nCol);
170947    }
170948  }
170949  
170950  /*
170951  ** Expression pExpr must be of type FTSQUERY_PHRASE.
170952  **
170953  ** If it is not already allocated and populated, this function allocates and
170954  ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
170955  ** of a NEAR expression, then it also allocates and populates the same array
170956  ** for all other phrases that are part of the NEAR expression.
170957  **
170958  ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
170959  ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
170960  */
170961  static int fts3EvalGatherStats(
170962    Fts3Cursor *pCsr,               /* Cursor object */
170963    Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
170964  ){
170965    int rc = SQLITE_OK;             /* Return code */
170966  
170967    assert( pExpr->eType==FTSQUERY_PHRASE );
170968    if( pExpr->aMI==0 ){
170969      Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
170970      Fts3Expr *pRoot;                /* Root of NEAR expression */
170971      Fts3Expr *p;                    /* Iterator used for several purposes */
170972  
170973      sqlite3_int64 iPrevId = pCsr->iPrevId;
170974      sqlite3_int64 iDocid;
170975      u8 bEof;
170976  
170977      /* Find the root of the NEAR expression */
170978      pRoot = pExpr;
170979      while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
170980        pRoot = pRoot->pParent;
170981      }
170982      iDocid = pRoot->iDocid;
170983      bEof = pRoot->bEof;
170984      assert( pRoot->bStart );
170985  
170986      /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
170987      for(p=pRoot; p; p=p->pLeft){
170988        Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
170989        assert( pE->aMI==0 );
170990        pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
170991        if( !pE->aMI ) return SQLITE_NOMEM;
170992        memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
170993      }
170994  
170995      fts3EvalRestart(pCsr, pRoot, &rc);
170996  
170997      while( pCsr->isEof==0 && rc==SQLITE_OK ){
170998  
170999        do {
171000          /* Ensure the %_content statement is reset. */
171001          if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
171002          assert( sqlite3_data_count(pCsr->pStmt)==0 );
171003  
171004          /* Advance to the next document */
171005          fts3EvalNextRow(pCsr, pRoot, &rc);
171006          pCsr->isEof = pRoot->bEof;
171007          pCsr->isRequireSeek = 1;
171008          pCsr->isMatchinfoNeeded = 1;
171009          pCsr->iPrevId = pRoot->iDocid;
171010        }while( pCsr->isEof==0 
171011             && pRoot->eType==FTSQUERY_NEAR 
171012             && sqlite3Fts3EvalTestDeferred(pCsr, &rc) 
171013        );
171014  
171015        if( rc==SQLITE_OK && pCsr->isEof==0 ){
171016          fts3EvalUpdateCounts(pRoot, pTab->nColumn);
171017        }
171018      }
171019  
171020      pCsr->isEof = 0;
171021      pCsr->iPrevId = iPrevId;
171022  
171023      if( bEof ){
171024        pRoot->bEof = bEof;
171025      }else{
171026        /* Caution: pRoot may iterate through docids in ascending or descending
171027        ** order. For this reason, even though it seems more defensive, the 
171028        ** do loop can not be written:
171029        **
171030        **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
171031        */
171032        fts3EvalRestart(pCsr, pRoot, &rc);
171033        do {
171034          fts3EvalNextRow(pCsr, pRoot, &rc);
171035          assert( pRoot->bEof==0 );
171036        }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
171037      }
171038    }
171039    return rc;
171040  }
171041  
171042  /*
171043  ** This function is used by the matchinfo() module to query a phrase 
171044  ** expression node for the following information:
171045  **
171046  **   1. The total number of occurrences of the phrase in each column of 
171047  **      the FTS table (considering all rows), and
171048  **
171049  **   2. For each column, the number of rows in the table for which the
171050  **      column contains at least one instance of the phrase.
171051  **
171052  ** If no error occurs, SQLITE_OK is returned and the values for each column
171053  ** written into the array aiOut as follows:
171054  **
171055  **   aiOut[iCol*3 + 1] = Number of occurrences
171056  **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
171057  **
171058  ** Caveats:
171059  **
171060  **   * If a phrase consists entirely of deferred tokens, then all output 
171061  **     values are set to the number of documents in the table. In other
171062  **     words we assume that very common tokens occur exactly once in each 
171063  **     column of each row of the table.
171064  **
171065  **   * If a phrase contains some deferred tokens (and some non-deferred 
171066  **     tokens), count the potential occurrence identified by considering
171067  **     the non-deferred tokens instead of actual phrase occurrences.
171068  **
171069  **   * If the phrase is part of a NEAR expression, then only phrase instances
171070  **     that meet the NEAR constraint are included in the counts.
171071  */
171072  SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
171073    Fts3Cursor *pCsr,               /* FTS cursor handle */
171074    Fts3Expr *pExpr,                /* Phrase expression */
171075    u32 *aiOut                      /* Array to write results into (see above) */
171076  ){
171077    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
171078    int rc = SQLITE_OK;
171079    int iCol;
171080  
171081    if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
171082      assert( pCsr->nDoc>0 );
171083      for(iCol=0; iCol<pTab->nColumn; iCol++){
171084        aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
171085        aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
171086      }
171087    }else{
171088      rc = fts3EvalGatherStats(pCsr, pExpr);
171089      if( rc==SQLITE_OK ){
171090        assert( pExpr->aMI );
171091        for(iCol=0; iCol<pTab->nColumn; iCol++){
171092          aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
171093          aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
171094        }
171095      }
171096    }
171097  
171098    return rc;
171099  }
171100  
171101  /*
171102  ** The expression pExpr passed as the second argument to this function
171103  ** must be of type FTSQUERY_PHRASE. 
171104  **
171105  ** The returned value is either NULL or a pointer to a buffer containing
171106  ** a position-list indicating the occurrences of the phrase in column iCol
171107  ** of the current row. 
171108  **
171109  ** More specifically, the returned buffer contains 1 varint for each 
171110  ** occurrence of the phrase in the column, stored using the normal (delta+2) 
171111  ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
171112  ** if the requested column contains "a b X c d X X" and the position-list
171113  ** for 'X' is requested, the buffer returned may contain:
171114  **
171115  **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
171116  **
171117  ** This function works regardless of whether or not the phrase is deferred,
171118  ** incremental, or neither.
171119  */
171120  SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
171121    Fts3Cursor *pCsr,               /* FTS3 cursor object */
171122    Fts3Expr *pExpr,                /* Phrase to return doclist for */
171123    int iCol,                       /* Column to return position list for */
171124    char **ppOut                    /* OUT: Pointer to position list */
171125  ){
171126    Fts3Phrase *pPhrase = pExpr->pPhrase;
171127    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
171128    char *pIter;
171129    int iThis;
171130    sqlite3_int64 iDocid;
171131  
171132    /* If this phrase is applies specifically to some column other than 
171133    ** column iCol, return a NULL pointer.  */
171134    *ppOut = 0;
171135    assert( iCol>=0 && iCol<pTab->nColumn );
171136    if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
171137      return SQLITE_OK;
171138    }
171139  
171140    iDocid = pExpr->iDocid;
171141    pIter = pPhrase->doclist.pList;
171142    if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
171143      int rc = SQLITE_OK;
171144      int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
171145      int bOr = 0;
171146      u8 bTreeEof = 0;
171147      Fts3Expr *p;                  /* Used to iterate from pExpr to root */
171148      Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
171149      int bMatch;
171150  
171151      /* Check if this phrase descends from an OR expression node. If not, 
171152      ** return NULL. Otherwise, the entry that corresponds to docid 
171153      ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
171154      ** tree that the node is part of has been marked as EOF, but the node
171155      ** itself is not EOF, then it may point to an earlier entry. */
171156      pNear = pExpr;
171157      for(p=pExpr->pParent; p; p=p->pParent){
171158        if( p->eType==FTSQUERY_OR ) bOr = 1;
171159        if( p->eType==FTSQUERY_NEAR ) pNear = p;
171160        if( p->bEof ) bTreeEof = 1;
171161      }
171162      if( bOr==0 ) return SQLITE_OK;
171163  
171164      /* This is the descendent of an OR node. In this case we cannot use
171165      ** an incremental phrase. Load the entire doclist for the phrase
171166      ** into memory in this case.  */
171167      if( pPhrase->bIncr ){
171168        int bEofSave = pNear->bEof;
171169        fts3EvalRestart(pCsr, pNear, &rc);
171170        while( rc==SQLITE_OK && !pNear->bEof ){
171171          fts3EvalNextRow(pCsr, pNear, &rc);
171172          if( bEofSave==0 && pNear->iDocid==iDocid ) break;
171173        }
171174        assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
171175      }
171176      if( bTreeEof ){
171177        while( rc==SQLITE_OK && !pNear->bEof ){
171178          fts3EvalNextRow(pCsr, pNear, &rc);
171179        }
171180      }
171181      if( rc!=SQLITE_OK ) return rc;
171182  
171183      bMatch = 1;
171184      for(p=pNear; p; p=p->pLeft){
171185        u8 bEof = 0;
171186        Fts3Expr *pTest = p;
171187        Fts3Phrase *pPh;
171188        assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
171189        if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
171190        assert( pTest->eType==FTSQUERY_PHRASE );
171191        pPh = pTest->pPhrase;
171192  
171193        pIter = pPh->pOrPoslist;
171194        iDocid = pPh->iOrDocid;
171195        if( pCsr->bDesc==bDescDoclist ){
171196          bEof = !pPh->doclist.nAll ||
171197            (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
171198          while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
171199            sqlite3Fts3DoclistNext(
171200                bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
171201                &pIter, &iDocid, &bEof
171202            );
171203          }
171204        }else{
171205          bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
171206          while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
171207            int dummy;
171208            sqlite3Fts3DoclistPrev(
171209                bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
171210                &pIter, &iDocid, &dummy, &bEof
171211                );
171212          }
171213        }
171214        pPh->pOrPoslist = pIter;
171215        pPh->iOrDocid = iDocid;
171216        if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
171217      }
171218  
171219      if( bMatch ){
171220        pIter = pPhrase->pOrPoslist;
171221      }else{
171222        pIter = 0;
171223      }
171224    }
171225    if( pIter==0 ) return SQLITE_OK;
171226  
171227    if( *pIter==0x01 ){
171228      pIter++;
171229      pIter += fts3GetVarint32(pIter, &iThis);
171230    }else{
171231      iThis = 0;
171232    }
171233    while( iThis<iCol ){
171234      fts3ColumnlistCopy(0, &pIter);
171235      if( *pIter==0x00 ) return SQLITE_OK;
171236      pIter++;
171237      pIter += fts3GetVarint32(pIter, &iThis);
171238    }
171239    if( *pIter==0x00 ){
171240      pIter = 0;
171241    }
171242  
171243    *ppOut = ((iCol==iThis)?pIter:0);
171244    return SQLITE_OK;
171245  }
171246  
171247  /*
171248  ** Free all components of the Fts3Phrase structure that were allocated by
171249  ** the eval module. Specifically, this means to free:
171250  **
171251  **   * the contents of pPhrase->doclist, and
171252  **   * any Fts3MultiSegReader objects held by phrase tokens.
171253  */
171254  SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
171255    if( pPhrase ){
171256      int i;
171257      sqlite3_free(pPhrase->doclist.aAll);
171258      fts3EvalInvalidatePoslist(pPhrase);
171259      memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
171260      for(i=0; i<pPhrase->nToken; i++){
171261        fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
171262        pPhrase->aToken[i].pSegcsr = 0;
171263      }
171264    }
171265  }
171266  
171267  
171268  /*
171269  ** Return SQLITE_CORRUPT_VTAB.
171270  */
171271  #ifdef SQLITE_DEBUG
171272  SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
171273    return SQLITE_CORRUPT_VTAB;
171274  }
171275  #endif
171276  
171277  #if !SQLITE_CORE
171278  /*
171279  ** Initialize API pointer table, if required.
171280  */
171281  #ifdef _WIN32
171282  __declspec(dllexport)
171283  #endif
171284  SQLITE_API int sqlite3_fts3_init(
171285    sqlite3 *db, 
171286    char **pzErrMsg,
171287    const sqlite3_api_routines *pApi
171288  ){
171289    SQLITE_EXTENSION_INIT2(pApi)
171290    return sqlite3Fts3Init(db);
171291  }
171292  #endif
171293  
171294  #endif
171295  
171296  /************** End of fts3.c ************************************************/
171297  /************** Begin file fts3_aux.c ****************************************/
171298  /*
171299  ** 2011 Jan 27
171300  **
171301  ** The author disclaims copyright to this source code.  In place of
171302  ** a legal notice, here is a blessing:
171303  **
171304  **    May you do good and not evil.
171305  **    May you find forgiveness for yourself and forgive others.
171306  **    May you share freely, never taking more than you give.
171307  **
171308  ******************************************************************************
171309  **
171310  */
171311  /* #include "fts3Int.h" */
171312  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
171313  
171314  /* #include <string.h> */
171315  /* #include <assert.h> */
171316  
171317  typedef struct Fts3auxTable Fts3auxTable;
171318  typedef struct Fts3auxCursor Fts3auxCursor;
171319  
171320  struct Fts3auxTable {
171321    sqlite3_vtab base;              /* Base class used by SQLite core */
171322    Fts3Table *pFts3Tab;
171323  };
171324  
171325  struct Fts3auxCursor {
171326    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
171327    Fts3MultiSegReader csr;        /* Must be right after "base" */
171328    Fts3SegFilter filter;
171329    char *zStop;
171330    int nStop;                      /* Byte-length of string zStop */
171331    int iLangid;                    /* Language id to query */
171332    int isEof;                      /* True if cursor is at EOF */
171333    sqlite3_int64 iRowid;           /* Current rowid */
171334  
171335    int iCol;                       /* Current value of 'col' column */
171336    int nStat;                      /* Size of aStat[] array */
171337    struct Fts3auxColstats {
171338      sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
171339      sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
171340    } *aStat;
171341  };
171342  
171343  /*
171344  ** Schema of the terms table.
171345  */
171346  #define FTS3_AUX_SCHEMA \
171347    "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
171348  
171349  /*
171350  ** This function does all the work for both the xConnect and xCreate methods.
171351  ** These tables have no persistent representation of their own, so xConnect
171352  ** and xCreate are identical operations.
171353  */
171354  static int fts3auxConnectMethod(
171355    sqlite3 *db,                    /* Database connection */
171356    void *pUnused,                  /* Unused */
171357    int argc,                       /* Number of elements in argv array */
171358    const char * const *argv,       /* xCreate/xConnect argument array */
171359    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
171360    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
171361  ){
171362    char const *zDb;                /* Name of database (e.g. "main") */
171363    char const *zFts3;              /* Name of fts3 table */
171364    int nDb;                        /* Result of strlen(zDb) */
171365    int nFts3;                      /* Result of strlen(zFts3) */
171366    sqlite3_int64 nByte;            /* Bytes of space to allocate here */
171367    int rc;                         /* value returned by declare_vtab() */
171368    Fts3auxTable *p;                /* Virtual table object to return */
171369  
171370    UNUSED_PARAMETER(pUnused);
171371  
171372    /* The user should invoke this in one of two forms:
171373    **
171374    **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
171375    **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
171376    */
171377    if( argc!=4 && argc!=5 ) goto bad_args;
171378  
171379    zDb = argv[1]; 
171380    nDb = (int)strlen(zDb);
171381    if( argc==5 ){
171382      if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
171383        zDb = argv[3]; 
171384        nDb = (int)strlen(zDb);
171385        zFts3 = argv[4];
171386      }else{
171387        goto bad_args;
171388      }
171389    }else{
171390      zFts3 = argv[3];
171391    }
171392    nFts3 = (int)strlen(zFts3);
171393  
171394    rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
171395    if( rc!=SQLITE_OK ) return rc;
171396  
171397    nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
171398    p = (Fts3auxTable *)sqlite3_malloc64(nByte);
171399    if( !p ) return SQLITE_NOMEM;
171400    memset(p, 0, nByte);
171401  
171402    p->pFts3Tab = (Fts3Table *)&p[1];
171403    p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
171404    p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
171405    p->pFts3Tab->db = db;
171406    p->pFts3Tab->nIndex = 1;
171407  
171408    memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
171409    memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
171410    sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
171411  
171412    *ppVtab = (sqlite3_vtab *)p;
171413    return SQLITE_OK;
171414  
171415   bad_args:
171416    sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
171417    return SQLITE_ERROR;
171418  }
171419  
171420  /*
171421  ** This function does the work for both the xDisconnect and xDestroy methods.
171422  ** These tables have no persistent representation of their own, so xDisconnect
171423  ** and xDestroy are identical operations.
171424  */
171425  static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
171426    Fts3auxTable *p = (Fts3auxTable *)pVtab;
171427    Fts3Table *pFts3 = p->pFts3Tab;
171428    int i;
171429  
171430    /* Free any prepared statements held */
171431    for(i=0; i<SizeofArray(pFts3->aStmt); i++){
171432      sqlite3_finalize(pFts3->aStmt[i]);
171433    }
171434    sqlite3_free(pFts3->zSegmentsTbl);
171435    sqlite3_free(p);
171436    return SQLITE_OK;
171437  }
171438  
171439  #define FTS4AUX_EQ_CONSTRAINT 1
171440  #define FTS4AUX_GE_CONSTRAINT 2
171441  #define FTS4AUX_LE_CONSTRAINT 4
171442  
171443  /*
171444  ** xBestIndex - Analyze a WHERE and ORDER BY clause.
171445  */
171446  static int fts3auxBestIndexMethod(
171447    sqlite3_vtab *pVTab, 
171448    sqlite3_index_info *pInfo
171449  ){
171450    int i;
171451    int iEq = -1;
171452    int iGe = -1;
171453    int iLe = -1;
171454    int iLangid = -1;
171455    int iNext = 1;                  /* Next free argvIndex value */
171456  
171457    UNUSED_PARAMETER(pVTab);
171458  
171459    /* This vtab delivers always results in "ORDER BY term ASC" order. */
171460    if( pInfo->nOrderBy==1 
171461     && pInfo->aOrderBy[0].iColumn==0 
171462     && pInfo->aOrderBy[0].desc==0
171463    ){
171464      pInfo->orderByConsumed = 1;
171465    }
171466  
171467    /* Search for equality and range constraints on the "term" column. 
171468    ** And equality constraints on the hidden "languageid" column. */
171469    for(i=0; i<pInfo->nConstraint; i++){
171470      if( pInfo->aConstraint[i].usable ){
171471        int op = pInfo->aConstraint[i].op;
171472        int iCol = pInfo->aConstraint[i].iColumn;
171473  
171474        if( iCol==0 ){
171475          if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
171476          if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
171477          if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
171478          if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
171479          if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
171480        }
171481        if( iCol==4 ){
171482          if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
171483        }
171484      }
171485    }
171486  
171487    if( iEq>=0 ){
171488      pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
171489      pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
171490      pInfo->estimatedCost = 5;
171491    }else{
171492      pInfo->idxNum = 0;
171493      pInfo->estimatedCost = 20000;
171494      if( iGe>=0 ){
171495        pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
171496        pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
171497        pInfo->estimatedCost /= 2;
171498      }
171499      if( iLe>=0 ){
171500        pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
171501        pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
171502        pInfo->estimatedCost /= 2;
171503      }
171504    }
171505    if( iLangid>=0 ){
171506      pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
171507      pInfo->estimatedCost--;
171508    }
171509  
171510    return SQLITE_OK;
171511  }
171512  
171513  /*
171514  ** xOpen - Open a cursor.
171515  */
171516  static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
171517    Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
171518  
171519    UNUSED_PARAMETER(pVTab);
171520  
171521    pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
171522    if( !pCsr ) return SQLITE_NOMEM;
171523    memset(pCsr, 0, sizeof(Fts3auxCursor));
171524  
171525    *ppCsr = (sqlite3_vtab_cursor *)pCsr;
171526    return SQLITE_OK;
171527  }
171528  
171529  /*
171530  ** xClose - Close a cursor.
171531  */
171532  static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
171533    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
171534    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
171535  
171536    sqlite3Fts3SegmentsClose(pFts3);
171537    sqlite3Fts3SegReaderFinish(&pCsr->csr);
171538    sqlite3_free((void *)pCsr->filter.zTerm);
171539    sqlite3_free(pCsr->zStop);
171540    sqlite3_free(pCsr->aStat);
171541    sqlite3_free(pCsr);
171542    return SQLITE_OK;
171543  }
171544  
171545  static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
171546    if( nSize>pCsr->nStat ){
171547      struct Fts3auxColstats *aNew;
171548      aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat, 
171549          sizeof(struct Fts3auxColstats) * nSize
171550      );
171551      if( aNew==0 ) return SQLITE_NOMEM;
171552      memset(&aNew[pCsr->nStat], 0, 
171553          sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
171554      );
171555      pCsr->aStat = aNew;
171556      pCsr->nStat = nSize;
171557    }
171558    return SQLITE_OK;
171559  }
171560  
171561  /*
171562  ** xNext - Advance the cursor to the next row, if any.
171563  */
171564  static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
171565    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
171566    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
171567    int rc;
171568  
171569    /* Increment our pretend rowid value. */
171570    pCsr->iRowid++;
171571  
171572    for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
171573      if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
171574    }
171575  
171576    rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
171577    if( rc==SQLITE_ROW ){
171578      int i = 0;
171579      int nDoclist = pCsr->csr.nDoclist;
171580      char *aDoclist = pCsr->csr.aDoclist;
171581      int iCol;
171582  
171583      int eState = 0;
171584  
171585      if( pCsr->zStop ){
171586        int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
171587        int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
171588        if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
171589          pCsr->isEof = 1;
171590          return SQLITE_OK;
171591        }
171592      }
171593  
171594      if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
171595      memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
171596      iCol = 0;
171597  
171598      while( i<nDoclist ){
171599        sqlite3_int64 v = 0;
171600  
171601        i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
171602        switch( eState ){
171603          /* State 0. In this state the integer just read was a docid. */
171604          case 0:
171605            pCsr->aStat[0].nDoc++;
171606            eState = 1;
171607            iCol = 0;
171608            break;
171609  
171610          /* State 1. In this state we are expecting either a 1, indicating
171611          ** that the following integer will be a column number, or the
171612          ** start of a position list for column 0.  
171613          ** 
171614          ** The only difference between state 1 and state 2 is that if the
171615          ** integer encountered in state 1 is not 0 or 1, then we need to
171616          ** increment the column 0 "nDoc" count for this term.
171617          */
171618          case 1:
171619            assert( iCol==0 );
171620            if( v>1 ){
171621              pCsr->aStat[1].nDoc++;
171622            }
171623            eState = 2;
171624            /* fall through */
171625  
171626          case 2:
171627            if( v==0 ){       /* 0x00. Next integer will be a docid. */
171628              eState = 0;
171629            }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
171630              eState = 3;
171631            }else{            /* 2 or greater. A position. */
171632              pCsr->aStat[iCol+1].nOcc++;
171633              pCsr->aStat[0].nOcc++;
171634            }
171635            break;
171636  
171637          /* State 3. The integer just read is a column number. */
171638          default: assert( eState==3 );
171639            iCol = (int)v;
171640            if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
171641            pCsr->aStat[iCol+1].nDoc++;
171642            eState = 2;
171643            break;
171644        }
171645      }
171646  
171647      pCsr->iCol = 0;
171648      rc = SQLITE_OK;
171649    }else{
171650      pCsr->isEof = 1;
171651    }
171652    return rc;
171653  }
171654  
171655  /*
171656  ** xFilter - Initialize a cursor to point at the start of its data.
171657  */
171658  static int fts3auxFilterMethod(
171659    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
171660    int idxNum,                     /* Strategy index */
171661    const char *idxStr,             /* Unused */
171662    int nVal,                       /* Number of elements in apVal */
171663    sqlite3_value **apVal           /* Arguments for the indexing scheme */
171664  ){
171665    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
171666    Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
171667    int rc;
171668    int isScan = 0;
171669    int iLangVal = 0;               /* Language id to query */
171670  
171671    int iEq = -1;                   /* Index of term=? value in apVal */
171672    int iGe = -1;                   /* Index of term>=? value in apVal */
171673    int iLe = -1;                   /* Index of term<=? value in apVal */
171674    int iLangid = -1;               /* Index of languageid=? value in apVal */
171675    int iNext = 0;
171676  
171677    UNUSED_PARAMETER(nVal);
171678    UNUSED_PARAMETER(idxStr);
171679  
171680    assert( idxStr==0 );
171681    assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
171682         || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
171683         || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
171684    );
171685  
171686    if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
171687      iEq = iNext++;
171688    }else{
171689      isScan = 1;
171690      if( idxNum & FTS4AUX_GE_CONSTRAINT ){
171691        iGe = iNext++;
171692      }
171693      if( idxNum & FTS4AUX_LE_CONSTRAINT ){
171694        iLe = iNext++;
171695      }
171696    }
171697    if( iNext<nVal ){
171698      iLangid = iNext++;
171699    }
171700  
171701    /* In case this cursor is being reused, close and zero it. */
171702    testcase(pCsr->filter.zTerm);
171703    sqlite3Fts3SegReaderFinish(&pCsr->csr);
171704    sqlite3_free((void *)pCsr->filter.zTerm);
171705    sqlite3_free(pCsr->aStat);
171706    memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
171707  
171708    pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
171709    if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
171710  
171711    if( iEq>=0 || iGe>=0 ){
171712      const unsigned char *zStr = sqlite3_value_text(apVal[0]);
171713      assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
171714      if( zStr ){
171715        pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
171716        if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
171717        pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
171718      }
171719    }
171720  
171721    if( iLe>=0 ){
171722      pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
171723      if( pCsr->zStop==0 ) return SQLITE_NOMEM;
171724      pCsr->nStop = (int)strlen(pCsr->zStop);
171725    }
171726    
171727    if( iLangid>=0 ){
171728      iLangVal = sqlite3_value_int(apVal[iLangid]);
171729  
171730      /* If the user specified a negative value for the languageid, use zero
171731      ** instead. This works, as the "languageid=?" constraint will also
171732      ** be tested by the VDBE layer. The test will always be false (since
171733      ** this module will not return a row with a negative languageid), and
171734      ** so the overall query will return zero rows.  */
171735      if( iLangVal<0 ) iLangVal = 0;
171736    }
171737    pCsr->iLangid = iLangVal;
171738  
171739    rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
171740        pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
171741    );
171742    if( rc==SQLITE_OK ){
171743      rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
171744    }
171745  
171746    if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
171747    return rc;
171748  }
171749  
171750  /*
171751  ** xEof - Return true if the cursor is at EOF, or false otherwise.
171752  */
171753  static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
171754    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
171755    return pCsr->isEof;
171756  }
171757  
171758  /*
171759  ** xColumn - Return a column value.
171760  */
171761  static int fts3auxColumnMethod(
171762    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
171763    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
171764    int iCol                        /* Index of column to read value from */
171765  ){
171766    Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
171767  
171768    assert( p->isEof==0 );
171769    switch( iCol ){
171770      case 0: /* term */
171771        sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
171772        break;
171773  
171774      case 1: /* col */
171775        if( p->iCol ){
171776          sqlite3_result_int(pCtx, p->iCol-1);
171777        }else{
171778          sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
171779        }
171780        break;
171781  
171782      case 2: /* documents */
171783        sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
171784        break;
171785  
171786      case 3: /* occurrences */
171787        sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
171788        break;
171789  
171790      default: /* languageid */
171791        assert( iCol==4 );
171792        sqlite3_result_int(pCtx, p->iLangid);
171793        break;
171794    }
171795  
171796    return SQLITE_OK;
171797  }
171798  
171799  /*
171800  ** xRowid - Return the current rowid for the cursor.
171801  */
171802  static int fts3auxRowidMethod(
171803    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
171804    sqlite_int64 *pRowid            /* OUT: Rowid value */
171805  ){
171806    Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
171807    *pRowid = pCsr->iRowid;
171808    return SQLITE_OK;
171809  }
171810  
171811  /*
171812  ** Register the fts3aux module with database connection db. Return SQLITE_OK
171813  ** if successful or an error code if sqlite3_create_module() fails.
171814  */
171815  SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
171816    static const sqlite3_module fts3aux_module = {
171817       0,                           /* iVersion      */
171818       fts3auxConnectMethod,        /* xCreate       */
171819       fts3auxConnectMethod,        /* xConnect      */
171820       fts3auxBestIndexMethod,      /* xBestIndex    */
171821       fts3auxDisconnectMethod,     /* xDisconnect   */
171822       fts3auxDisconnectMethod,     /* xDestroy      */
171823       fts3auxOpenMethod,           /* xOpen         */
171824       fts3auxCloseMethod,          /* xClose        */
171825       fts3auxFilterMethod,         /* xFilter       */
171826       fts3auxNextMethod,           /* xNext         */
171827       fts3auxEofMethod,            /* xEof          */
171828       fts3auxColumnMethod,         /* xColumn       */
171829       fts3auxRowidMethod,          /* xRowid        */
171830       0,                           /* xUpdate       */
171831       0,                           /* xBegin        */
171832       0,                           /* xSync         */
171833       0,                           /* xCommit       */
171834       0,                           /* xRollback     */
171835       0,                           /* xFindFunction */
171836       0,                           /* xRename       */
171837       0,                           /* xSavepoint    */
171838       0,                           /* xRelease      */
171839       0,                           /* xRollbackTo   */
171840       0                            /* xShadowName   */
171841    };
171842    int rc;                         /* Return code */
171843  
171844    rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
171845    return rc;
171846  }
171847  
171848  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
171849  
171850  /************** End of fts3_aux.c ********************************************/
171851  /************** Begin file fts3_expr.c ***************************************/
171852  /*
171853  ** 2008 Nov 28
171854  **
171855  ** The author disclaims copyright to this source code.  In place of
171856  ** a legal notice, here is a blessing:
171857  **
171858  **    May you do good and not evil.
171859  **    May you find forgiveness for yourself and forgive others.
171860  **    May you share freely, never taking more than you give.
171861  **
171862  ******************************************************************************
171863  **
171864  ** This module contains code that implements a parser for fts3 query strings
171865  ** (the right-hand argument to the MATCH operator). Because the supported 
171866  ** syntax is relatively simple, the whole tokenizer/parser system is
171867  ** hand-coded. 
171868  */
171869  /* #include "fts3Int.h" */
171870  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
171871  
171872  /*
171873  ** By default, this module parses the legacy syntax that has been 
171874  ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
171875  ** is defined, then it uses the new syntax. The differences between
171876  ** the new and the old syntaxes are:
171877  **
171878  **  a) The new syntax supports parenthesis. The old does not.
171879  **
171880  **  b) The new syntax supports the AND and NOT operators. The old does not.
171881  **
171882  **  c) The old syntax supports the "-" token qualifier. This is not 
171883  **     supported by the new syntax (it is replaced by the NOT operator).
171884  **
171885  **  d) When using the old syntax, the OR operator has a greater precedence
171886  **     than an implicit AND. When using the new, both implicity and explicit
171887  **     AND operators have a higher precedence than OR.
171888  **
171889  ** If compiled with SQLITE_TEST defined, then this module exports the
171890  ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
171891  ** to zero causes the module to use the old syntax. If it is set to 
171892  ** non-zero the new syntax is activated. This is so both syntaxes can
171893  ** be tested using a single build of testfixture.
171894  **
171895  ** The following describes the syntax supported by the fts3 MATCH
171896  ** operator in a similar format to that used by the lemon parser
171897  ** generator. This module does not use actually lemon, it uses a
171898  ** custom parser.
171899  **
171900  **   query ::= andexpr (OR andexpr)*.
171901  **
171902  **   andexpr ::= notexpr (AND? notexpr)*.
171903  **
171904  **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
171905  **   notexpr ::= LP query RP.
171906  **
171907  **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
171908  **
171909  **   distance_opt ::= .
171910  **   distance_opt ::= / INTEGER.
171911  **
171912  **   phrase ::= TOKEN.
171913  **   phrase ::= COLUMN:TOKEN.
171914  **   phrase ::= "TOKEN TOKEN TOKEN...".
171915  */
171916  
171917  #ifdef SQLITE_TEST
171918  SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
171919  #else
171920  # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
171921  #  define sqlite3_fts3_enable_parentheses 1
171922  # else
171923  #  define sqlite3_fts3_enable_parentheses 0
171924  # endif
171925  #endif
171926  
171927  /*
171928  ** Default span for NEAR operators.
171929  */
171930  #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
171931  
171932  /* #include <string.h> */
171933  /* #include <assert.h> */
171934  
171935  /*
171936  ** isNot:
171937  **   This variable is used by function getNextNode(). When getNextNode() is
171938  **   called, it sets ParseContext.isNot to true if the 'next node' is a 
171939  **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
171940  **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
171941  **   zero.
171942  */
171943  typedef struct ParseContext ParseContext;
171944  struct ParseContext {
171945    sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
171946    int iLangid;                        /* Language id used with tokenizer */
171947    const char **azCol;                 /* Array of column names for fts3 table */
171948    int bFts4;                          /* True to allow FTS4-only syntax */
171949    int nCol;                           /* Number of entries in azCol[] */
171950    int iDefaultCol;                    /* Default column to query */
171951    int isNot;                          /* True if getNextNode() sees a unary - */
171952    sqlite3_context *pCtx;              /* Write error message here */
171953    int nNest;                          /* Number of nested brackets */
171954  };
171955  
171956  /*
171957  ** This function is equivalent to the standard isspace() function. 
171958  **
171959  ** The standard isspace() can be awkward to use safely, because although it
171960  ** is defined to accept an argument of type int, its behavior when passed
171961  ** an integer that falls outside of the range of the unsigned char type
171962  ** is undefined (and sometimes, "undefined" means segfault). This wrapper
171963  ** is defined to accept an argument of type char, and always returns 0 for
171964  ** any values that fall outside of the range of the unsigned char type (i.e.
171965  ** negative values).
171966  */
171967  static int fts3isspace(char c){
171968    return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
171969  }
171970  
171971  /*
171972  ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
171973  ** zero the memory before returning a pointer to it. If unsuccessful, 
171974  ** return NULL.
171975  */
171976  static void *fts3MallocZero(sqlite3_int64 nByte){
171977    void *pRet = sqlite3_malloc64(nByte);
171978    if( pRet ) memset(pRet, 0, nByte);
171979    return pRet;
171980  }
171981  
171982  SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
171983    sqlite3_tokenizer *pTokenizer,
171984    int iLangid,
171985    const char *z,
171986    int n,
171987    sqlite3_tokenizer_cursor **ppCsr
171988  ){
171989    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
171990    sqlite3_tokenizer_cursor *pCsr = 0;
171991    int rc;
171992  
171993    rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
171994    assert( rc==SQLITE_OK || pCsr==0 );
171995    if( rc==SQLITE_OK ){
171996      pCsr->pTokenizer = pTokenizer;
171997      if( pModule->iVersion>=1 ){
171998        rc = pModule->xLanguageid(pCsr, iLangid);
171999        if( rc!=SQLITE_OK ){
172000          pModule->xClose(pCsr);
172001          pCsr = 0;
172002        }
172003      }
172004    }
172005    *ppCsr = pCsr;
172006    return rc;
172007  }
172008  
172009  /*
172010  ** Function getNextNode(), which is called by fts3ExprParse(), may itself
172011  ** call fts3ExprParse(). So this forward declaration is required.
172012  */
172013  static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
172014  
172015  /*
172016  ** Extract the next token from buffer z (length n) using the tokenizer
172017  ** and other information (column names etc.) in pParse. Create an Fts3Expr
172018  ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
172019  ** single token and set *ppExpr to point to it. If the end of the buffer is
172020  ** reached before a token is found, set *ppExpr to zero. It is the
172021  ** responsibility of the caller to eventually deallocate the allocated 
172022  ** Fts3Expr structure (if any) by passing it to sqlite3_free().
172023  **
172024  ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
172025  ** fails.
172026  */
172027  static int getNextToken(
172028    ParseContext *pParse,                   /* fts3 query parse context */
172029    int iCol,                               /* Value for Fts3Phrase.iColumn */
172030    const char *z, int n,                   /* Input string */
172031    Fts3Expr **ppExpr,                      /* OUT: expression */
172032    int *pnConsumed                         /* OUT: Number of bytes consumed */
172033  ){
172034    sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
172035    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
172036    int rc;
172037    sqlite3_tokenizer_cursor *pCursor;
172038    Fts3Expr *pRet = 0;
172039    int i = 0;
172040  
172041    /* Set variable i to the maximum number of bytes of input to tokenize. */
172042    for(i=0; i<n; i++){
172043      if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
172044      if( z[i]=='"' ) break;
172045    }
172046  
172047    *pnConsumed = i;
172048    rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
172049    if( rc==SQLITE_OK ){
172050      const char *zToken;
172051      int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
172052      sqlite3_int64 nByte;                    /* total space to allocate */
172053  
172054      rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
172055      if( rc==SQLITE_OK ){
172056        nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
172057        pRet = (Fts3Expr *)fts3MallocZero(nByte);
172058        if( !pRet ){
172059          rc = SQLITE_NOMEM;
172060        }else{
172061          pRet->eType = FTSQUERY_PHRASE;
172062          pRet->pPhrase = (Fts3Phrase *)&pRet[1];
172063          pRet->pPhrase->nToken = 1;
172064          pRet->pPhrase->iColumn = iCol;
172065          pRet->pPhrase->aToken[0].n = nToken;
172066          pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
172067          memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
172068  
172069          if( iEnd<n && z[iEnd]=='*' ){
172070            pRet->pPhrase->aToken[0].isPrefix = 1;
172071            iEnd++;
172072          }
172073  
172074          while( 1 ){
172075            if( !sqlite3_fts3_enable_parentheses 
172076             && iStart>0 && z[iStart-1]=='-' 
172077            ){
172078              pParse->isNot = 1;
172079              iStart--;
172080            }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
172081              pRet->pPhrase->aToken[0].bFirst = 1;
172082              iStart--;
172083            }else{
172084              break;
172085            }
172086          }
172087  
172088        }
172089        *pnConsumed = iEnd;
172090      }else if( i && rc==SQLITE_DONE ){
172091        rc = SQLITE_OK;
172092      }
172093  
172094      pModule->xClose(pCursor);
172095    }
172096    
172097    *ppExpr = pRet;
172098    return rc;
172099  }
172100  
172101  
172102  /*
172103  ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
172104  ** then free the old allocation.
172105  */
172106  static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
172107    void *pRet = sqlite3_realloc64(pOrig, nNew);
172108    if( !pRet ){
172109      sqlite3_free(pOrig);
172110    }
172111    return pRet;
172112  }
172113  
172114  /*
172115  ** Buffer zInput, length nInput, contains the contents of a quoted string
172116  ** that appeared as part of an fts3 query expression. Neither quote character
172117  ** is included in the buffer. This function attempts to tokenize the entire
172118  ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
172119  ** containing the results.
172120  **
172121  ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
172122  ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
172123  ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
172124  ** to 0.
172125  */
172126  static int getNextString(
172127    ParseContext *pParse,                   /* fts3 query parse context */
172128    const char *zInput, int nInput,         /* Input string */
172129    Fts3Expr **ppExpr                       /* OUT: expression */
172130  ){
172131    sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
172132    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
172133    int rc;
172134    Fts3Expr *p = 0;
172135    sqlite3_tokenizer_cursor *pCursor = 0;
172136    char *zTemp = 0;
172137    int nTemp = 0;
172138  
172139    const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
172140    int nToken = 0;
172141  
172142    /* The final Fts3Expr data structure, including the Fts3Phrase,
172143    ** Fts3PhraseToken structures token buffers are all stored as a single 
172144    ** allocation so that the expression can be freed with a single call to
172145    ** sqlite3_free(). Setting this up requires a two pass approach.
172146    **
172147    ** The first pass, in the block below, uses a tokenizer cursor to iterate
172148    ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
172149    ** to assemble data in two dynamic buffers:
172150    **
172151    **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
172152    **             structure, followed by the array of Fts3PhraseToken 
172153    **             structures. This pass only populates the Fts3PhraseToken array.
172154    **
172155    **   Buffer zTemp: Contains copies of all tokens.
172156    **
172157    ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
172158    ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
172159    ** structures.
172160    */
172161    rc = sqlite3Fts3OpenTokenizer(
172162        pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
172163    if( rc==SQLITE_OK ){
172164      int ii;
172165      for(ii=0; rc==SQLITE_OK; ii++){
172166        const char *zByte;
172167        int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
172168        rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
172169        if( rc==SQLITE_OK ){
172170          Fts3PhraseToken *pToken;
172171  
172172          p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
172173          if( !p ) goto no_mem;
172174  
172175          zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
172176          if( !zTemp ) goto no_mem;
172177  
172178          assert( nToken==ii );
172179          pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
172180          memset(pToken, 0, sizeof(Fts3PhraseToken));
172181  
172182          memcpy(&zTemp[nTemp], zByte, nByte);
172183          nTemp += nByte;
172184  
172185          pToken->n = nByte;
172186          pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
172187          pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
172188          nToken = ii+1;
172189        }
172190      }
172191  
172192      pModule->xClose(pCursor);
172193      pCursor = 0;
172194    }
172195  
172196    if( rc==SQLITE_DONE ){
172197      int jj;
172198      char *zBuf = 0;
172199  
172200      p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
172201      if( !p ) goto no_mem;
172202      memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
172203      p->eType = FTSQUERY_PHRASE;
172204      p->pPhrase = (Fts3Phrase *)&p[1];
172205      p->pPhrase->iColumn = pParse->iDefaultCol;
172206      p->pPhrase->nToken = nToken;
172207  
172208      zBuf = (char *)&p->pPhrase->aToken[nToken];
172209      if( zTemp ){
172210        memcpy(zBuf, zTemp, nTemp);
172211        sqlite3_free(zTemp);
172212      }else{
172213        assert( nTemp==0 );
172214      }
172215  
172216      for(jj=0; jj<p->pPhrase->nToken; jj++){
172217        p->pPhrase->aToken[jj].z = zBuf;
172218        zBuf += p->pPhrase->aToken[jj].n;
172219      }
172220      rc = SQLITE_OK;
172221    }
172222  
172223    *ppExpr = p;
172224    return rc;
172225  no_mem:
172226  
172227    if( pCursor ){
172228      pModule->xClose(pCursor);
172229    }
172230    sqlite3_free(zTemp);
172231    sqlite3_free(p);
172232    *ppExpr = 0;
172233    return SQLITE_NOMEM;
172234  }
172235  
172236  /*
172237  ** The output variable *ppExpr is populated with an allocated Fts3Expr 
172238  ** structure, or set to 0 if the end of the input buffer is reached.
172239  **
172240  ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
172241  ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
172242  ** If SQLITE_ERROR is returned, pContext is populated with an error message.
172243  */
172244  static int getNextNode(
172245    ParseContext *pParse,                   /* fts3 query parse context */
172246    const char *z, int n,                   /* Input string */
172247    Fts3Expr **ppExpr,                      /* OUT: expression */
172248    int *pnConsumed                         /* OUT: Number of bytes consumed */
172249  ){
172250    static const struct Fts3Keyword {
172251      char *z;                              /* Keyword text */
172252      unsigned char n;                      /* Length of the keyword */
172253      unsigned char parenOnly;              /* Only valid in paren mode */
172254      unsigned char eType;                  /* Keyword code */
172255    } aKeyword[] = {
172256      { "OR" ,  2, 0, FTSQUERY_OR   },
172257      { "AND",  3, 1, FTSQUERY_AND  },
172258      { "NOT",  3, 1, FTSQUERY_NOT  },
172259      { "NEAR", 4, 0, FTSQUERY_NEAR }
172260    };
172261    int ii;
172262    int iCol;
172263    int iColLen;
172264    int rc;
172265    Fts3Expr *pRet = 0;
172266  
172267    const char *zInput = z;
172268    int nInput = n;
172269  
172270    pParse->isNot = 0;
172271  
172272    /* Skip over any whitespace before checking for a keyword, an open or
172273    ** close bracket, or a quoted string. 
172274    */
172275    while( nInput>0 && fts3isspace(*zInput) ){
172276      nInput--;
172277      zInput++;
172278    }
172279    if( nInput==0 ){
172280      return SQLITE_DONE;
172281    }
172282  
172283    /* See if we are dealing with a keyword. */
172284    for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
172285      const struct Fts3Keyword *pKey = &aKeyword[ii];
172286  
172287      if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
172288        continue;
172289      }
172290  
172291      if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
172292        int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
172293        int nKey = pKey->n;
172294        char cNext;
172295  
172296        /* If this is a "NEAR" keyword, check for an explicit nearness. */
172297        if( pKey->eType==FTSQUERY_NEAR ){
172298          assert( nKey==4 );
172299          if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
172300            nNear = 0;
172301            for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
172302              nNear = nNear * 10 + (zInput[nKey] - '0');
172303            }
172304          }
172305        }
172306  
172307        /* At this point this is probably a keyword. But for that to be true,
172308        ** the next byte must contain either whitespace, an open or close
172309        ** parenthesis, a quote character, or EOF. 
172310        */
172311        cNext = zInput[nKey];
172312        if( fts3isspace(cNext) 
172313         || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
172314        ){
172315          pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
172316          if( !pRet ){
172317            return SQLITE_NOMEM;
172318          }
172319          pRet->eType = pKey->eType;
172320          pRet->nNear = nNear;
172321          *ppExpr = pRet;
172322          *pnConsumed = (int)((zInput - z) + nKey);
172323          return SQLITE_OK;
172324        }
172325  
172326        /* Turns out that wasn't a keyword after all. This happens if the
172327        ** user has supplied a token such as "ORacle". Continue.
172328        */
172329      }
172330    }
172331  
172332    /* See if we are dealing with a quoted phrase. If this is the case, then
172333    ** search for the closing quote and pass the whole string to getNextString()
172334    ** for processing. This is easy to do, as fts3 has no syntax for escaping
172335    ** a quote character embedded in a string.
172336    */
172337    if( *zInput=='"' ){
172338      for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
172339      *pnConsumed = (int)((zInput - z) + ii + 1);
172340      if( ii==nInput ){
172341        return SQLITE_ERROR;
172342      }
172343      return getNextString(pParse, &zInput[1], ii-1, ppExpr);
172344    }
172345  
172346    if( sqlite3_fts3_enable_parentheses ){
172347      if( *zInput=='(' ){
172348        int nConsumed = 0;
172349        pParse->nNest++;
172350        rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
172351        *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
172352        return rc;
172353      }else if( *zInput==')' ){
172354        pParse->nNest--;
172355        *pnConsumed = (int)((zInput - z) + 1);
172356        *ppExpr = 0;
172357        return SQLITE_DONE;
172358      }
172359    }
172360  
172361    /* If control flows to this point, this must be a regular token, or 
172362    ** the end of the input. Read a regular token using the sqlite3_tokenizer
172363    ** interface. Before doing so, figure out if there is an explicit
172364    ** column specifier for the token. 
172365    **
172366    ** TODO: Strangely, it is not possible to associate a column specifier
172367    ** with a quoted phrase, only with a single token. Not sure if this was
172368    ** an implementation artifact or an intentional decision when fts3 was
172369    ** first implemented. Whichever it was, this module duplicates the 
172370    ** limitation.
172371    */
172372    iCol = pParse->iDefaultCol;
172373    iColLen = 0;
172374    for(ii=0; ii<pParse->nCol; ii++){
172375      const char *zStr = pParse->azCol[ii];
172376      int nStr = (int)strlen(zStr);
172377      if( nInput>nStr && zInput[nStr]==':' 
172378       && sqlite3_strnicmp(zStr, zInput, nStr)==0 
172379      ){
172380        iCol = ii;
172381        iColLen = (int)((zInput - z) + nStr + 1);
172382        break;
172383      }
172384    }
172385    rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
172386    *pnConsumed += iColLen;
172387    return rc;
172388  }
172389  
172390  /*
172391  ** The argument is an Fts3Expr structure for a binary operator (any type
172392  ** except an FTSQUERY_PHRASE). Return an integer value representing the
172393  ** precedence of the operator. Lower values have a higher precedence (i.e.
172394  ** group more tightly). For example, in the C language, the == operator
172395  ** groups more tightly than ||, and would therefore have a higher precedence.
172396  **
172397  ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
172398  ** is defined), the order of the operators in precedence from highest to
172399  ** lowest is:
172400  **
172401  **   NEAR
172402  **   NOT
172403  **   AND (including implicit ANDs)
172404  **   OR
172405  **
172406  ** Note that when using the old query syntax, the OR operator has a higher
172407  ** precedence than the AND operator.
172408  */
172409  static int opPrecedence(Fts3Expr *p){
172410    assert( p->eType!=FTSQUERY_PHRASE );
172411    if( sqlite3_fts3_enable_parentheses ){
172412      return p->eType;
172413    }else if( p->eType==FTSQUERY_NEAR ){
172414      return 1;
172415    }else if( p->eType==FTSQUERY_OR ){
172416      return 2;
172417    }
172418    assert( p->eType==FTSQUERY_AND );
172419    return 3;
172420  }
172421  
172422  /*
172423  ** Argument ppHead contains a pointer to the current head of a query 
172424  ** expression tree being parsed. pPrev is the expression node most recently
172425  ** inserted into the tree. This function adds pNew, which is always a binary
172426  ** operator node, into the expression tree based on the relative precedence
172427  ** of pNew and the existing nodes of the tree. This may result in the head
172428  ** of the tree changing, in which case *ppHead is set to the new root node.
172429  */
172430  static void insertBinaryOperator(
172431    Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
172432    Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
172433    Fts3Expr *pNew           /* New binary node to insert into expression tree */
172434  ){
172435    Fts3Expr *pSplit = pPrev;
172436    while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
172437      pSplit = pSplit->pParent;
172438    }
172439  
172440    if( pSplit->pParent ){
172441      assert( pSplit->pParent->pRight==pSplit );
172442      pSplit->pParent->pRight = pNew;
172443      pNew->pParent = pSplit->pParent;
172444    }else{
172445      *ppHead = pNew;
172446    }
172447    pNew->pLeft = pSplit;
172448    pSplit->pParent = pNew;
172449  }
172450  
172451  /*
172452  ** Parse the fts3 query expression found in buffer z, length n. This function
172453  ** returns either when the end of the buffer is reached or an unmatched 
172454  ** closing bracket - ')' - is encountered.
172455  **
172456  ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
172457  ** parsed form of the expression and *pnConsumed is set to the number of
172458  ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
172459  ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
172460  */
172461  static int fts3ExprParse(
172462    ParseContext *pParse,                   /* fts3 query parse context */
172463    const char *z, int n,                   /* Text of MATCH query */
172464    Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
172465    int *pnConsumed                         /* OUT: Number of bytes consumed */
172466  ){
172467    Fts3Expr *pRet = 0;
172468    Fts3Expr *pPrev = 0;
172469    Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
172470    int nIn = n;
172471    const char *zIn = z;
172472    int rc = SQLITE_OK;
172473    int isRequirePhrase = 1;
172474  
172475    while( rc==SQLITE_OK ){
172476      Fts3Expr *p = 0;
172477      int nByte = 0;
172478  
172479      rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
172480      assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
172481      if( rc==SQLITE_OK ){
172482        if( p ){
172483          int isPhrase;
172484  
172485          if( !sqlite3_fts3_enable_parentheses 
172486              && p->eType==FTSQUERY_PHRASE && pParse->isNot 
172487          ){
172488            /* Create an implicit NOT operator. */
172489            Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
172490            if( !pNot ){
172491              sqlite3Fts3ExprFree(p);
172492              rc = SQLITE_NOMEM;
172493              goto exprparse_out;
172494            }
172495            pNot->eType = FTSQUERY_NOT;
172496            pNot->pRight = p;
172497            p->pParent = pNot;
172498            if( pNotBranch ){
172499              pNot->pLeft = pNotBranch;
172500              pNotBranch->pParent = pNot;
172501            }
172502            pNotBranch = pNot;
172503            p = pPrev;
172504          }else{
172505            int eType = p->eType;
172506            isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
172507  
172508            /* The isRequirePhrase variable is set to true if a phrase or
172509            ** an expression contained in parenthesis is required. If a
172510            ** binary operator (AND, OR, NOT or NEAR) is encounted when
172511            ** isRequirePhrase is set, this is a syntax error.
172512            */
172513            if( !isPhrase && isRequirePhrase ){
172514              sqlite3Fts3ExprFree(p);
172515              rc = SQLITE_ERROR;
172516              goto exprparse_out;
172517            }
172518  
172519            if( isPhrase && !isRequirePhrase ){
172520              /* Insert an implicit AND operator. */
172521              Fts3Expr *pAnd;
172522              assert( pRet && pPrev );
172523              pAnd = fts3MallocZero(sizeof(Fts3Expr));
172524              if( !pAnd ){
172525                sqlite3Fts3ExprFree(p);
172526                rc = SQLITE_NOMEM;
172527                goto exprparse_out;
172528              }
172529              pAnd->eType = FTSQUERY_AND;
172530              insertBinaryOperator(&pRet, pPrev, pAnd);
172531              pPrev = pAnd;
172532            }
172533  
172534            /* This test catches attempts to make either operand of a NEAR
172535             ** operator something other than a phrase. For example, either of
172536             ** the following:
172537             **
172538             **    (bracketed expression) NEAR phrase
172539             **    phrase NEAR (bracketed expression)
172540             **
172541             ** Return an error in either case.
172542             */
172543            if( pPrev && (
172544              (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
172545           || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
172546            )){
172547              sqlite3Fts3ExprFree(p);
172548              rc = SQLITE_ERROR;
172549              goto exprparse_out;
172550            }
172551  
172552            if( isPhrase ){
172553              if( pRet ){
172554                assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
172555                pPrev->pRight = p;
172556                p->pParent = pPrev;
172557              }else{
172558                pRet = p;
172559              }
172560            }else{
172561              insertBinaryOperator(&pRet, pPrev, p);
172562            }
172563            isRequirePhrase = !isPhrase;
172564          }
172565          pPrev = p;
172566        }
172567        assert( nByte>0 );
172568      }
172569      assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
172570      nIn -= nByte;
172571      zIn += nByte;
172572    }
172573  
172574    if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
172575      rc = SQLITE_ERROR;
172576    }
172577  
172578    if( rc==SQLITE_DONE ){
172579      rc = SQLITE_OK;
172580      if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
172581        if( !pRet ){
172582          rc = SQLITE_ERROR;
172583        }else{
172584          Fts3Expr *pIter = pNotBranch;
172585          while( pIter->pLeft ){
172586            pIter = pIter->pLeft;
172587          }
172588          pIter->pLeft = pRet;
172589          pRet->pParent = pIter;
172590          pRet = pNotBranch;
172591        }
172592      }
172593    }
172594    *pnConsumed = n - nIn;
172595  
172596  exprparse_out:
172597    if( rc!=SQLITE_OK ){
172598      sqlite3Fts3ExprFree(pRet);
172599      sqlite3Fts3ExprFree(pNotBranch);
172600      pRet = 0;
172601    }
172602    *ppExpr = pRet;
172603    return rc;
172604  }
172605  
172606  /*
172607  ** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
172608  ** as the only argument is more than nMaxDepth.
172609  */
172610  static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
172611    int rc = SQLITE_OK;
172612    if( p ){
172613      if( nMaxDepth<0 ){ 
172614        rc = SQLITE_TOOBIG;
172615      }else{
172616        rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
172617        if( rc==SQLITE_OK ){
172618          rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
172619        }
172620      }
172621    }
172622    return rc;
172623  }
172624  
172625  /*
172626  ** This function attempts to transform the expression tree at (*pp) to
172627  ** an equivalent but more balanced form. The tree is modified in place.
172628  ** If successful, SQLITE_OK is returned and (*pp) set to point to the 
172629  ** new root expression node. 
172630  **
172631  ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
172632  **
172633  ** Otherwise, if an error occurs, an SQLite error code is returned and 
172634  ** expression (*pp) freed.
172635  */
172636  static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
172637    int rc = SQLITE_OK;             /* Return code */
172638    Fts3Expr *pRoot = *pp;          /* Initial root node */
172639    Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
172640    int eType = pRoot->eType;       /* Type of node in this tree */
172641  
172642    if( nMaxDepth==0 ){
172643      rc = SQLITE_ERROR;
172644    }
172645  
172646    if( rc==SQLITE_OK ){
172647      if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
172648        Fts3Expr **apLeaf;
172649        apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
172650        if( 0==apLeaf ){
172651          rc = SQLITE_NOMEM;
172652        }else{
172653          memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
172654        }
172655  
172656        if( rc==SQLITE_OK ){
172657          int i;
172658          Fts3Expr *p;
172659  
172660          /* Set $p to point to the left-most leaf in the tree of eType nodes. */
172661          for(p=pRoot; p->eType==eType; p=p->pLeft){
172662            assert( p->pParent==0 || p->pParent->pLeft==p );
172663            assert( p->pLeft && p->pRight );
172664          }
172665  
172666          /* This loop runs once for each leaf in the tree of eType nodes. */
172667          while( 1 ){
172668            int iLvl;
172669            Fts3Expr *pParent = p->pParent;     /* Current parent of p */
172670  
172671            assert( pParent==0 || pParent->pLeft==p );
172672            p->pParent = 0;
172673            if( pParent ){
172674              pParent->pLeft = 0;
172675            }else{
172676              pRoot = 0;
172677            }
172678            rc = fts3ExprBalance(&p, nMaxDepth-1);
172679            if( rc!=SQLITE_OK ) break;
172680  
172681            for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
172682              if( apLeaf[iLvl]==0 ){
172683                apLeaf[iLvl] = p;
172684                p = 0;
172685              }else{
172686                assert( pFree );
172687                pFree->pLeft = apLeaf[iLvl];
172688                pFree->pRight = p;
172689                pFree->pLeft->pParent = pFree;
172690                pFree->pRight->pParent = pFree;
172691  
172692                p = pFree;
172693                pFree = pFree->pParent;
172694                p->pParent = 0;
172695                apLeaf[iLvl] = 0;
172696              }
172697            }
172698            if( p ){
172699              sqlite3Fts3ExprFree(p);
172700              rc = SQLITE_TOOBIG;
172701              break;
172702            }
172703  
172704            /* If that was the last leaf node, break out of the loop */
172705            if( pParent==0 ) break;
172706  
172707            /* Set $p to point to the next leaf in the tree of eType nodes */
172708            for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
172709  
172710            /* Remove pParent from the original tree. */
172711            assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
172712            pParent->pRight->pParent = pParent->pParent;
172713            if( pParent->pParent ){
172714              pParent->pParent->pLeft = pParent->pRight;
172715            }else{
172716              assert( pParent==pRoot );
172717              pRoot = pParent->pRight;
172718            }
172719  
172720            /* Link pParent into the free node list. It will be used as an
172721            ** internal node of the new tree.  */
172722            pParent->pParent = pFree;
172723            pFree = pParent;
172724          }
172725  
172726          if( rc==SQLITE_OK ){
172727            p = 0;
172728            for(i=0; i<nMaxDepth; i++){
172729              if( apLeaf[i] ){
172730                if( p==0 ){
172731                  p = apLeaf[i];
172732                  p->pParent = 0;
172733                }else{
172734                  assert( pFree!=0 );
172735                  pFree->pRight = p;
172736                  pFree->pLeft = apLeaf[i];
172737                  pFree->pLeft->pParent = pFree;
172738                  pFree->pRight->pParent = pFree;
172739  
172740                  p = pFree;
172741                  pFree = pFree->pParent;
172742                  p->pParent = 0;
172743                }
172744              }
172745            }
172746            pRoot = p;
172747          }else{
172748            /* An error occurred. Delete the contents of the apLeaf[] array 
172749            ** and pFree list. Everything else is cleaned up by the call to
172750            ** sqlite3Fts3ExprFree(pRoot) below.  */
172751            Fts3Expr *pDel;
172752            for(i=0; i<nMaxDepth; i++){
172753              sqlite3Fts3ExprFree(apLeaf[i]);
172754            }
172755            while( (pDel=pFree)!=0 ){
172756              pFree = pDel->pParent;
172757              sqlite3_free(pDel);
172758            }
172759          }
172760  
172761          assert( pFree==0 );
172762          sqlite3_free( apLeaf );
172763        }
172764      }else if( eType==FTSQUERY_NOT ){
172765        Fts3Expr *pLeft = pRoot->pLeft;
172766        Fts3Expr *pRight = pRoot->pRight;
172767  
172768        pRoot->pLeft = 0;
172769        pRoot->pRight = 0;
172770        pLeft->pParent = 0;
172771        pRight->pParent = 0;
172772  
172773        rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
172774        if( rc==SQLITE_OK ){
172775          rc = fts3ExprBalance(&pRight, nMaxDepth-1);
172776        }
172777  
172778        if( rc!=SQLITE_OK ){
172779          sqlite3Fts3ExprFree(pRight);
172780          sqlite3Fts3ExprFree(pLeft);
172781        }else{
172782          assert( pLeft && pRight );
172783          pRoot->pLeft = pLeft;
172784          pLeft->pParent = pRoot;
172785          pRoot->pRight = pRight;
172786          pRight->pParent = pRoot;
172787        }
172788      }
172789    }
172790    
172791    if( rc!=SQLITE_OK ){
172792      sqlite3Fts3ExprFree(pRoot);
172793      pRoot = 0;
172794    }
172795    *pp = pRoot;
172796    return rc;
172797  }
172798  
172799  /*
172800  ** This function is similar to sqlite3Fts3ExprParse(), with the following
172801  ** differences:
172802  **
172803  **   1. It does not do expression rebalancing.
172804  **   2. It does not check that the expression does not exceed the 
172805  **      maximum allowable depth.
172806  **   3. Even if it fails, *ppExpr may still be set to point to an 
172807  **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
172808  **      in this case.
172809  */
172810  static int fts3ExprParseUnbalanced(
172811    sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
172812    int iLangid,                        /* Language id for tokenizer */
172813    char **azCol,                       /* Array of column names for fts3 table */
172814    int bFts4,                          /* True to allow FTS4-only syntax */
172815    int nCol,                           /* Number of entries in azCol[] */
172816    int iDefaultCol,                    /* Default column to query */
172817    const char *z, int n,               /* Text of MATCH query */
172818    Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
172819  ){
172820    int nParsed;
172821    int rc;
172822    ParseContext sParse;
172823  
172824    memset(&sParse, 0, sizeof(ParseContext));
172825    sParse.pTokenizer = pTokenizer;
172826    sParse.iLangid = iLangid;
172827    sParse.azCol = (const char **)azCol;
172828    sParse.nCol = nCol;
172829    sParse.iDefaultCol = iDefaultCol;
172830    sParse.bFts4 = bFts4;
172831    if( z==0 ){
172832      *ppExpr = 0;
172833      return SQLITE_OK;
172834    }
172835    if( n<0 ){
172836      n = (int)strlen(z);
172837    }
172838    rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
172839    assert( rc==SQLITE_OK || *ppExpr==0 );
172840  
172841    /* Check for mismatched parenthesis */
172842    if( rc==SQLITE_OK && sParse.nNest ){
172843      rc = SQLITE_ERROR;
172844    }
172845    
172846    return rc;
172847  }
172848  
172849  /*
172850  ** Parameters z and n contain a pointer to and length of a buffer containing
172851  ** an fts3 query expression, respectively. This function attempts to parse the
172852  ** query expression and create a tree of Fts3Expr structures representing the
172853  ** parsed expression. If successful, *ppExpr is set to point to the head
172854  ** of the parsed expression tree and SQLITE_OK is returned. If an error
172855  ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
172856  ** error) is returned and *ppExpr is set to 0.
172857  **
172858  ** If parameter n is a negative number, then z is assumed to point to a
172859  ** nul-terminated string and the length is determined using strlen().
172860  **
172861  ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
172862  ** use to normalize query tokens while parsing the expression. The azCol[]
172863  ** array, which is assumed to contain nCol entries, should contain the names
172864  ** of each column in the target fts3 table, in order from left to right. 
172865  ** Column names must be nul-terminated strings.
172866  **
172867  ** The iDefaultCol parameter should be passed the index of the table column
172868  ** that appears on the left-hand-side of the MATCH operator (the default
172869  ** column to match against for tokens for which a column name is not explicitly
172870  ** specified as part of the query string), or -1 if tokens may by default
172871  ** match any table column.
172872  */
172873  SQLITE_PRIVATE int sqlite3Fts3ExprParse(
172874    sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
172875    int iLangid,                        /* Language id for tokenizer */
172876    char **azCol,                       /* Array of column names for fts3 table */
172877    int bFts4,                          /* True to allow FTS4-only syntax */
172878    int nCol,                           /* Number of entries in azCol[] */
172879    int iDefaultCol,                    /* Default column to query */
172880    const char *z, int n,               /* Text of MATCH query */
172881    Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
172882    char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
172883  ){
172884    int rc = fts3ExprParseUnbalanced(
172885        pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
172886    );
172887    
172888    /* Rebalance the expression. And check that its depth does not exceed
172889    ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
172890    if( rc==SQLITE_OK && *ppExpr ){
172891      rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
172892      if( rc==SQLITE_OK ){
172893        rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
172894      }
172895    }
172896  
172897    if( rc!=SQLITE_OK ){
172898      sqlite3Fts3ExprFree(*ppExpr);
172899      *ppExpr = 0;
172900      if( rc==SQLITE_TOOBIG ){
172901        sqlite3Fts3ErrMsg(pzErr,
172902            "FTS expression tree is too large (maximum depth %d)", 
172903            SQLITE_FTS3_MAX_EXPR_DEPTH
172904        );
172905        rc = SQLITE_ERROR;
172906      }else if( rc==SQLITE_ERROR ){
172907        sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
172908      }
172909    }
172910  
172911    return rc;
172912  }
172913  
172914  /*
172915  ** Free a single node of an expression tree.
172916  */
172917  static void fts3FreeExprNode(Fts3Expr *p){
172918    assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
172919    sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
172920    sqlite3_free(p->aMI);
172921    sqlite3_free(p);
172922  }
172923  
172924  /*
172925  ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
172926  **
172927  ** This function would be simpler if it recursively called itself. But
172928  ** that would mean passing a sufficiently large expression to ExprParse()
172929  ** could cause a stack overflow.
172930  */
172931  SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
172932    Fts3Expr *p;
172933    assert( pDel==0 || pDel->pParent==0 );
172934    for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
172935      assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
172936    }
172937    while( p ){
172938      Fts3Expr *pParent = p->pParent;
172939      fts3FreeExprNode(p);
172940      if( pParent && p==pParent->pLeft && pParent->pRight ){
172941        p = pParent->pRight;
172942        while( p && (p->pLeft || p->pRight) ){
172943          assert( p==p->pParent->pRight || p==p->pParent->pLeft );
172944          p = (p->pLeft ? p->pLeft : p->pRight);
172945        }
172946      }else{
172947        p = pParent;
172948      }
172949    }
172950  }
172951  
172952  /****************************************************************************
172953  *****************************************************************************
172954  ** Everything after this point is just test code.
172955  */
172956  
172957  #ifdef SQLITE_TEST
172958  
172959  /* #include <stdio.h> */
172960  
172961  /*
172962  ** Return a pointer to a buffer containing a text representation of the
172963  ** expression passed as the first argument. The buffer is obtained from
172964  ** sqlite3_malloc(). It is the responsibility of the caller to use 
172965  ** sqlite3_free() to release the memory. If an OOM condition is encountered,
172966  ** NULL is returned.
172967  **
172968  ** If the second argument is not NULL, then its contents are prepended to 
172969  ** the returned expression text and then freed using sqlite3_free().
172970  */
172971  static char *exprToString(Fts3Expr *pExpr, char *zBuf){
172972    if( pExpr==0 ){
172973      return sqlite3_mprintf("");
172974    }
172975    switch( pExpr->eType ){
172976      case FTSQUERY_PHRASE: {
172977        Fts3Phrase *pPhrase = pExpr->pPhrase;
172978        int i;
172979        zBuf = sqlite3_mprintf(
172980            "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
172981        for(i=0; zBuf && i<pPhrase->nToken; i++){
172982          zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
172983              pPhrase->aToken[i].n, pPhrase->aToken[i].z,
172984              (pPhrase->aToken[i].isPrefix?"+":"")
172985          );
172986        }
172987        return zBuf;
172988      }
172989  
172990      case FTSQUERY_NEAR:
172991        zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
172992        break;
172993      case FTSQUERY_NOT:
172994        zBuf = sqlite3_mprintf("%zNOT ", zBuf);
172995        break;
172996      case FTSQUERY_AND:
172997        zBuf = sqlite3_mprintf("%zAND ", zBuf);
172998        break;
172999      case FTSQUERY_OR:
173000        zBuf = sqlite3_mprintf("%zOR ", zBuf);
173001        break;
173002    }
173003  
173004    if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
173005    if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
173006    if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
173007  
173008    if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
173009    if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
173010  
173011    return zBuf;
173012  }
173013  
173014  /*
173015  ** This is the implementation of a scalar SQL function used to test the 
173016  ** expression parser. It should be called as follows:
173017  **
173018  **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
173019  **
173020  ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
173021  ** to parse the query expression (see README.tokenizers). The second argument
173022  ** is the query expression to parse. Each subsequent argument is the name
173023  ** of a column of the fts3 table that the query expression may refer to.
173024  ** For example:
173025  **
173026  **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
173027  */
173028  static void fts3ExprTestCommon(
173029    int bRebalance,
173030    sqlite3_context *context,
173031    int argc,
173032    sqlite3_value **argv
173033  ){
173034    sqlite3_tokenizer *pTokenizer = 0;
173035    int rc;
173036    char **azCol = 0;
173037    const char *zExpr;
173038    int nExpr;
173039    int nCol;
173040    int ii;
173041    Fts3Expr *pExpr;
173042    char *zBuf = 0;
173043    Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
173044    const char *zTokenizer = 0;
173045    char *zErr = 0;
173046  
173047    if( argc<3 ){
173048      sqlite3_result_error(context, 
173049          "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
173050      );
173051      return;
173052    }
173053  
173054    zTokenizer = (const char*)sqlite3_value_text(argv[0]);
173055    rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
173056    if( rc!=SQLITE_OK ){
173057      if( rc==SQLITE_NOMEM ){
173058        sqlite3_result_error_nomem(context);
173059      }else{
173060        sqlite3_result_error(context, zErr, -1);
173061      }
173062      sqlite3_free(zErr);
173063      return;
173064    }
173065  
173066    zExpr = (const char *)sqlite3_value_text(argv[1]);
173067    nExpr = sqlite3_value_bytes(argv[1]);
173068    nCol = argc-2;
173069    azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
173070    if( !azCol ){
173071      sqlite3_result_error_nomem(context);
173072      goto exprtest_out;
173073    }
173074    for(ii=0; ii<nCol; ii++){
173075      azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
173076    }
173077  
173078    if( bRebalance ){
173079      char *zDummy = 0;
173080      rc = sqlite3Fts3ExprParse(
173081          pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
173082      );
173083      assert( rc==SQLITE_OK || pExpr==0 );
173084      sqlite3_free(zDummy);
173085    }else{
173086      rc = fts3ExprParseUnbalanced(
173087          pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
173088      );
173089    }
173090  
173091    if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
173092      sqlite3Fts3ExprFree(pExpr);
173093      sqlite3_result_error(context, "Error parsing expression", -1);
173094    }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
173095      sqlite3_result_error_nomem(context);
173096    }else{
173097      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
173098      sqlite3_free(zBuf);
173099    }
173100  
173101    sqlite3Fts3ExprFree(pExpr);
173102  
173103  exprtest_out:
173104    if( pTokenizer ){
173105      rc = pTokenizer->pModule->xDestroy(pTokenizer);
173106    }
173107    sqlite3_free(azCol);
173108  }
173109  
173110  static void fts3ExprTest(
173111    sqlite3_context *context,
173112    int argc,
173113    sqlite3_value **argv
173114  ){
173115    fts3ExprTestCommon(0, context, argc, argv);
173116  }
173117  static void fts3ExprTestRebalance(
173118    sqlite3_context *context,
173119    int argc,
173120    sqlite3_value **argv
173121  ){
173122    fts3ExprTestCommon(1, context, argc, argv);
173123  }
173124  
173125  /*
173126  ** Register the query expression parser test function fts3_exprtest() 
173127  ** with database connection db. 
173128  */
173129  SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
173130    int rc = sqlite3_create_function(
173131        db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
173132    );
173133    if( rc==SQLITE_OK ){
173134      rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
173135          -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
173136      );
173137    }
173138    return rc;
173139  }
173140  
173141  #endif
173142  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
173143  
173144  /************** End of fts3_expr.c *******************************************/
173145  /************** Begin file fts3_hash.c ***************************************/
173146  /*
173147  ** 2001 September 22
173148  **
173149  ** The author disclaims copyright to this source code.  In place of
173150  ** a legal notice, here is a blessing:
173151  **
173152  **    May you do good and not evil.
173153  **    May you find forgiveness for yourself and forgive others.
173154  **    May you share freely, never taking more than you give.
173155  **
173156  *************************************************************************
173157  ** This is the implementation of generic hash-tables used in SQLite.
173158  ** We've modified it slightly to serve as a standalone hash table
173159  ** implementation for the full-text indexing module.
173160  */
173161  
173162  /*
173163  ** The code in this file is only compiled if:
173164  **
173165  **     * The FTS3 module is being built as an extension
173166  **       (in which case SQLITE_CORE is not defined), or
173167  **
173168  **     * The FTS3 module is being built into the core of
173169  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
173170  */
173171  /* #include "fts3Int.h" */
173172  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
173173  
173174  /* #include <assert.h> */
173175  /* #include <stdlib.h> */
173176  /* #include <string.h> */
173177  
173178  /* #include "fts3_hash.h" */
173179  
173180  /*
173181  ** Malloc and Free functions
173182  */
173183  static void *fts3HashMalloc(sqlite3_int64 n){
173184    void *p = sqlite3_malloc64(n);
173185    if( p ){
173186      memset(p, 0, n);
173187    }
173188    return p;
173189  }
173190  static void fts3HashFree(void *p){
173191    sqlite3_free(p);
173192  }
173193  
173194  /* Turn bulk memory into a hash table object by initializing the
173195  ** fields of the Hash structure.
173196  **
173197  ** "pNew" is a pointer to the hash table that is to be initialized.
173198  ** keyClass is one of the constants 
173199  ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
173200  ** determines what kind of key the hash table will use.  "copyKey" is
173201  ** true if the hash table should make its own private copy of keys and
173202  ** false if it should just use the supplied pointer.
173203  */
173204  SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
173205    assert( pNew!=0 );
173206    assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
173207    pNew->keyClass = keyClass;
173208    pNew->copyKey = copyKey;
173209    pNew->first = 0;
173210    pNew->count = 0;
173211    pNew->htsize = 0;
173212    pNew->ht = 0;
173213  }
173214  
173215  /* Remove all entries from a hash table.  Reclaim all memory.
173216  ** Call this routine to delete a hash table or to reset a hash table
173217  ** to the empty state.
173218  */
173219  SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
173220    Fts3HashElem *elem;         /* For looping over all elements of the table */
173221  
173222    assert( pH!=0 );
173223    elem = pH->first;
173224    pH->first = 0;
173225    fts3HashFree(pH->ht);
173226    pH->ht = 0;
173227    pH->htsize = 0;
173228    while( elem ){
173229      Fts3HashElem *next_elem = elem->next;
173230      if( pH->copyKey && elem->pKey ){
173231        fts3HashFree(elem->pKey);
173232      }
173233      fts3HashFree(elem);
173234      elem = next_elem;
173235    }
173236    pH->count = 0;
173237  }
173238  
173239  /*
173240  ** Hash and comparison functions when the mode is FTS3_HASH_STRING
173241  */
173242  static int fts3StrHash(const void *pKey, int nKey){
173243    const char *z = (const char *)pKey;
173244    unsigned h = 0;
173245    if( nKey<=0 ) nKey = (int) strlen(z);
173246    while( nKey > 0  ){
173247      h = (h<<3) ^ h ^ *z++;
173248      nKey--;
173249    }
173250    return (int)(h & 0x7fffffff);
173251  }
173252  static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
173253    if( n1!=n2 ) return 1;
173254    return strncmp((const char*)pKey1,(const char*)pKey2,n1);
173255  }
173256  
173257  /*
173258  ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
173259  */
173260  static int fts3BinHash(const void *pKey, int nKey){
173261    int h = 0;
173262    const char *z = (const char *)pKey;
173263    while( nKey-- > 0 ){
173264      h = (h<<3) ^ h ^ *(z++);
173265    }
173266    return h & 0x7fffffff;
173267  }
173268  static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
173269    if( n1!=n2 ) return 1;
173270    return memcmp(pKey1,pKey2,n1);
173271  }
173272  
173273  /*
173274  ** Return a pointer to the appropriate hash function given the key class.
173275  **
173276  ** The C syntax in this function definition may be unfamilar to some 
173277  ** programmers, so we provide the following additional explanation:
173278  **
173279  ** The name of the function is "ftsHashFunction".  The function takes a
173280  ** single parameter "keyClass".  The return value of ftsHashFunction()
173281  ** is a pointer to another function.  Specifically, the return value
173282  ** of ftsHashFunction() is a pointer to a function that takes two parameters
173283  ** with types "const void*" and "int" and returns an "int".
173284  */
173285  static int (*ftsHashFunction(int keyClass))(const void*,int){
173286    if( keyClass==FTS3_HASH_STRING ){
173287      return &fts3StrHash;
173288    }else{
173289      assert( keyClass==FTS3_HASH_BINARY );
173290      return &fts3BinHash;
173291    }
173292  }
173293  
173294  /*
173295  ** Return a pointer to the appropriate hash function given the key class.
173296  **
173297  ** For help in interpreted the obscure C code in the function definition,
173298  ** see the header comment on the previous function.
173299  */
173300  static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
173301    if( keyClass==FTS3_HASH_STRING ){
173302      return &fts3StrCompare;
173303    }else{
173304      assert( keyClass==FTS3_HASH_BINARY );
173305      return &fts3BinCompare;
173306    }
173307  }
173308  
173309  /* Link an element into the hash table
173310  */
173311  static void fts3HashInsertElement(
173312    Fts3Hash *pH,            /* The complete hash table */
173313    struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
173314    Fts3HashElem *pNew       /* The element to be inserted */
173315  ){
173316    Fts3HashElem *pHead;     /* First element already in pEntry */
173317    pHead = pEntry->chain;
173318    if( pHead ){
173319      pNew->next = pHead;
173320      pNew->prev = pHead->prev;
173321      if( pHead->prev ){ pHead->prev->next = pNew; }
173322      else             { pH->first = pNew; }
173323      pHead->prev = pNew;
173324    }else{
173325      pNew->next = pH->first;
173326      if( pH->first ){ pH->first->prev = pNew; }
173327      pNew->prev = 0;
173328      pH->first = pNew;
173329    }
173330    pEntry->count++;
173331    pEntry->chain = pNew;
173332  }
173333  
173334  
173335  /* Resize the hash table so that it cantains "new_size" buckets.
173336  ** "new_size" must be a power of 2.  The hash table might fail 
173337  ** to resize if sqliteMalloc() fails.
173338  **
173339  ** Return non-zero if a memory allocation error occurs.
173340  */
173341  static int fts3Rehash(Fts3Hash *pH, int new_size){
173342    struct _fts3ht *new_ht;          /* The new hash table */
173343    Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
173344    int (*xHash)(const void*,int);   /* The hash function */
173345  
173346    assert( (new_size & (new_size-1))==0 );
173347    new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
173348    if( new_ht==0 ) return 1;
173349    fts3HashFree(pH->ht);
173350    pH->ht = new_ht;
173351    pH->htsize = new_size;
173352    xHash = ftsHashFunction(pH->keyClass);
173353    for(elem=pH->first, pH->first=0; elem; elem = next_elem){
173354      int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
173355      next_elem = elem->next;
173356      fts3HashInsertElement(pH, &new_ht[h], elem);
173357    }
173358    return 0;
173359  }
173360  
173361  /* This function (for internal use only) locates an element in an
173362  ** hash table that matches the given key.  The hash for this key has
173363  ** already been computed and is passed as the 4th parameter.
173364  */
173365  static Fts3HashElem *fts3FindElementByHash(
173366    const Fts3Hash *pH, /* The pH to be searched */
173367    const void *pKey,   /* The key we are searching for */
173368    int nKey,
173369    int h               /* The hash for this key. */
173370  ){
173371    Fts3HashElem *elem;            /* Used to loop thru the element list */
173372    int count;                     /* Number of elements left to test */
173373    int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
173374  
173375    if( pH->ht ){
173376      struct _fts3ht *pEntry = &pH->ht[h];
173377      elem = pEntry->chain;
173378      count = pEntry->count;
173379      xCompare = ftsCompareFunction(pH->keyClass);
173380      while( count-- && elem ){
173381        if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
173382          return elem;
173383        }
173384        elem = elem->next;
173385      }
173386    }
173387    return 0;
173388  }
173389  
173390  /* Remove a single entry from the hash table given a pointer to that
173391  ** element and a hash on the element's key.
173392  */
173393  static void fts3RemoveElementByHash(
173394    Fts3Hash *pH,         /* The pH containing "elem" */
173395    Fts3HashElem* elem,   /* The element to be removed from the pH */
173396    int h                 /* Hash value for the element */
173397  ){
173398    struct _fts3ht *pEntry;
173399    if( elem->prev ){
173400      elem->prev->next = elem->next; 
173401    }else{
173402      pH->first = elem->next;
173403    }
173404    if( elem->next ){
173405      elem->next->prev = elem->prev;
173406    }
173407    pEntry = &pH->ht[h];
173408    if( pEntry->chain==elem ){
173409      pEntry->chain = elem->next;
173410    }
173411    pEntry->count--;
173412    if( pEntry->count<=0 ){
173413      pEntry->chain = 0;
173414    }
173415    if( pH->copyKey && elem->pKey ){
173416      fts3HashFree(elem->pKey);
173417    }
173418    fts3HashFree( elem );
173419    pH->count--;
173420    if( pH->count<=0 ){
173421      assert( pH->first==0 );
173422      assert( pH->count==0 );
173423      fts3HashClear(pH);
173424    }
173425  }
173426  
173427  SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
173428    const Fts3Hash *pH, 
173429    const void *pKey, 
173430    int nKey
173431  ){
173432    int h;                          /* A hash on key */
173433    int (*xHash)(const void*,int);  /* The hash function */
173434  
173435    if( pH==0 || pH->ht==0 ) return 0;
173436    xHash = ftsHashFunction(pH->keyClass);
173437    assert( xHash!=0 );
173438    h = (*xHash)(pKey,nKey);
173439    assert( (pH->htsize & (pH->htsize-1))==0 );
173440    return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
173441  }
173442  
173443  /* 
173444  ** Attempt to locate an element of the hash table pH with a key
173445  ** that matches pKey,nKey.  Return the data for this element if it is
173446  ** found, or NULL if there is no match.
173447  */
173448  SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
173449    Fts3HashElem *pElem;            /* The element that matches key (if any) */
173450  
173451    pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
173452    return pElem ? pElem->data : 0;
173453  }
173454  
173455  /* Insert an element into the hash table pH.  The key is pKey,nKey
173456  ** and the data is "data".
173457  **
173458  ** If no element exists with a matching key, then a new
173459  ** element is created.  A copy of the key is made if the copyKey
173460  ** flag is set.  NULL is returned.
173461  **
173462  ** If another element already exists with the same key, then the
173463  ** new data replaces the old data and the old data is returned.
173464  ** The key is not copied in this instance.  If a malloc fails, then
173465  ** the new data is returned and the hash table is unchanged.
173466  **
173467  ** If the "data" parameter to this function is NULL, then the
173468  ** element corresponding to "key" is removed from the hash table.
173469  */
173470  SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
173471    Fts3Hash *pH,        /* The hash table to insert into */
173472    const void *pKey,    /* The key */
173473    int nKey,            /* Number of bytes in the key */
173474    void *data           /* The data */
173475  ){
173476    int hraw;                 /* Raw hash value of the key */
173477    int h;                    /* the hash of the key modulo hash table size */
173478    Fts3HashElem *elem;       /* Used to loop thru the element list */
173479    Fts3HashElem *new_elem;   /* New element added to the pH */
173480    int (*xHash)(const void*,int);  /* The hash function */
173481  
173482    assert( pH!=0 );
173483    xHash = ftsHashFunction(pH->keyClass);
173484    assert( xHash!=0 );
173485    hraw = (*xHash)(pKey, nKey);
173486    assert( (pH->htsize & (pH->htsize-1))==0 );
173487    h = hraw & (pH->htsize-1);
173488    elem = fts3FindElementByHash(pH,pKey,nKey,h);
173489    if( elem ){
173490      void *old_data = elem->data;
173491      if( data==0 ){
173492        fts3RemoveElementByHash(pH,elem,h);
173493      }else{
173494        elem->data = data;
173495      }
173496      return old_data;
173497    }
173498    if( data==0 ) return 0;
173499    if( (pH->htsize==0 && fts3Rehash(pH,8))
173500     || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
173501    ){
173502      pH->count = 0;
173503      return data;
173504    }
173505    assert( pH->htsize>0 );
173506    new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
173507    if( new_elem==0 ) return data;
173508    if( pH->copyKey && pKey!=0 ){
173509      new_elem->pKey = fts3HashMalloc( nKey );
173510      if( new_elem->pKey==0 ){
173511        fts3HashFree(new_elem);
173512        return data;
173513      }
173514      memcpy((void*)new_elem->pKey, pKey, nKey);
173515    }else{
173516      new_elem->pKey = (void*)pKey;
173517    }
173518    new_elem->nKey = nKey;
173519    pH->count++;
173520    assert( pH->htsize>0 );
173521    assert( (pH->htsize & (pH->htsize-1))==0 );
173522    h = hraw & (pH->htsize-1);
173523    fts3HashInsertElement(pH, &pH->ht[h], new_elem);
173524    new_elem->data = data;
173525    return 0;
173526  }
173527  
173528  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
173529  
173530  /************** End of fts3_hash.c *******************************************/
173531  /************** Begin file fts3_porter.c *************************************/
173532  /*
173533  ** 2006 September 30
173534  **
173535  ** The author disclaims copyright to this source code.  In place of
173536  ** a legal notice, here is a blessing:
173537  **
173538  **    May you do good and not evil.
173539  **    May you find forgiveness for yourself and forgive others.
173540  **    May you share freely, never taking more than you give.
173541  **
173542  *************************************************************************
173543  ** Implementation of the full-text-search tokenizer that implements
173544  ** a Porter stemmer.
173545  */
173546  
173547  /*
173548  ** The code in this file is only compiled if:
173549  **
173550  **     * The FTS3 module is being built as an extension
173551  **       (in which case SQLITE_CORE is not defined), or
173552  **
173553  **     * The FTS3 module is being built into the core of
173554  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
173555  */
173556  /* #include "fts3Int.h" */
173557  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
173558  
173559  /* #include <assert.h> */
173560  /* #include <stdlib.h> */
173561  /* #include <stdio.h> */
173562  /* #include <string.h> */
173563  
173564  /* #include "fts3_tokenizer.h" */
173565  
173566  /*
173567  ** Class derived from sqlite3_tokenizer
173568  */
173569  typedef struct porter_tokenizer {
173570    sqlite3_tokenizer base;      /* Base class */
173571  } porter_tokenizer;
173572  
173573  /*
173574  ** Class derived from sqlite3_tokenizer_cursor
173575  */
173576  typedef struct porter_tokenizer_cursor {
173577    sqlite3_tokenizer_cursor base;
173578    const char *zInput;          /* input we are tokenizing */
173579    int nInput;                  /* size of the input */
173580    int iOffset;                 /* current position in zInput */
173581    int iToken;                  /* index of next token to be returned */
173582    char *zToken;                /* storage for current token */
173583    int nAllocated;              /* space allocated to zToken buffer */
173584  } porter_tokenizer_cursor;
173585  
173586  
173587  /*
173588  ** Create a new tokenizer instance.
173589  */
173590  static int porterCreate(
173591    int argc, const char * const *argv,
173592    sqlite3_tokenizer **ppTokenizer
173593  ){
173594    porter_tokenizer *t;
173595  
173596    UNUSED_PARAMETER(argc);
173597    UNUSED_PARAMETER(argv);
173598  
173599    t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
173600    if( t==NULL ) return SQLITE_NOMEM;
173601    memset(t, 0, sizeof(*t));
173602    *ppTokenizer = &t->base;
173603    return SQLITE_OK;
173604  }
173605  
173606  /*
173607  ** Destroy a tokenizer
173608  */
173609  static int porterDestroy(sqlite3_tokenizer *pTokenizer){
173610    sqlite3_free(pTokenizer);
173611    return SQLITE_OK;
173612  }
173613  
173614  /*
173615  ** Prepare to begin tokenizing a particular string.  The input
173616  ** string to be tokenized is zInput[0..nInput-1].  A cursor
173617  ** used to incrementally tokenize this string is returned in 
173618  ** *ppCursor.
173619  */
173620  static int porterOpen(
173621    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
173622    const char *zInput, int nInput,        /* String to be tokenized */
173623    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
173624  ){
173625    porter_tokenizer_cursor *c;
173626  
173627    UNUSED_PARAMETER(pTokenizer);
173628  
173629    c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
173630    if( c==NULL ) return SQLITE_NOMEM;
173631  
173632    c->zInput = zInput;
173633    if( zInput==0 ){
173634      c->nInput = 0;
173635    }else if( nInput<0 ){
173636      c->nInput = (int)strlen(zInput);
173637    }else{
173638      c->nInput = nInput;
173639    }
173640    c->iOffset = 0;                 /* start tokenizing at the beginning */
173641    c->iToken = 0;
173642    c->zToken = NULL;               /* no space allocated, yet. */
173643    c->nAllocated = 0;
173644  
173645    *ppCursor = &c->base;
173646    return SQLITE_OK;
173647  }
173648  
173649  /*
173650  ** Close a tokenization cursor previously opened by a call to
173651  ** porterOpen() above.
173652  */
173653  static int porterClose(sqlite3_tokenizer_cursor *pCursor){
173654    porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
173655    sqlite3_free(c->zToken);
173656    sqlite3_free(c);
173657    return SQLITE_OK;
173658  }
173659  /*
173660  ** Vowel or consonant
173661  */
173662  static const char cType[] = {
173663     0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
173664     1, 1, 1, 2, 1
173665  };
173666  
173667  /*
173668  ** isConsonant() and isVowel() determine if their first character in
173669  ** the string they point to is a consonant or a vowel, according
173670  ** to Porter ruls.  
173671  **
173672  ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
173673  ** 'Y' is a consonant unless it follows another consonant,
173674  ** in which case it is a vowel.
173675  **
173676  ** In these routine, the letters are in reverse order.  So the 'y' rule
173677  ** is that 'y' is a consonant unless it is followed by another
173678  ** consonent.
173679  */
173680  static int isVowel(const char*);
173681  static int isConsonant(const char *z){
173682    int j;
173683    char x = *z;
173684    if( x==0 ) return 0;
173685    assert( x>='a' && x<='z' );
173686    j = cType[x-'a'];
173687    if( j<2 ) return j;
173688    return z[1]==0 || isVowel(z + 1);
173689  }
173690  static int isVowel(const char *z){
173691    int j;
173692    char x = *z;
173693    if( x==0 ) return 0;
173694    assert( x>='a' && x<='z' );
173695    j = cType[x-'a'];
173696    if( j<2 ) return 1-j;
173697    return isConsonant(z + 1);
173698  }
173699  
173700  /*
173701  ** Let any sequence of one or more vowels be represented by V and let
173702  ** C be sequence of one or more consonants.  Then every word can be
173703  ** represented as:
173704  **
173705  **           [C] (VC){m} [V]
173706  **
173707  ** In prose:  A word is an optional consonant followed by zero or
173708  ** vowel-consonant pairs followed by an optional vowel.  "m" is the
173709  ** number of vowel consonant pairs.  This routine computes the value
173710  ** of m for the first i bytes of a word.
173711  **
173712  ** Return true if the m-value for z is 1 or more.  In other words,
173713  ** return true if z contains at least one vowel that is followed
173714  ** by a consonant.
173715  **
173716  ** In this routine z[] is in reverse order.  So we are really looking
173717  ** for an instance of a consonant followed by a vowel.
173718  */
173719  static int m_gt_0(const char *z){
173720    while( isVowel(z) ){ z++; }
173721    if( *z==0 ) return 0;
173722    while( isConsonant(z) ){ z++; }
173723    return *z!=0;
173724  }
173725  
173726  /* Like mgt0 above except we are looking for a value of m which is
173727  ** exactly 1
173728  */
173729  static int m_eq_1(const char *z){
173730    while( isVowel(z) ){ z++; }
173731    if( *z==0 ) return 0;
173732    while( isConsonant(z) ){ z++; }
173733    if( *z==0 ) return 0;
173734    while( isVowel(z) ){ z++; }
173735    if( *z==0 ) return 1;
173736    while( isConsonant(z) ){ z++; }
173737    return *z==0;
173738  }
173739  
173740  /* Like mgt0 above except we are looking for a value of m>1 instead
173741  ** or m>0
173742  */
173743  static int m_gt_1(const char *z){
173744    while( isVowel(z) ){ z++; }
173745    if( *z==0 ) return 0;
173746    while( isConsonant(z) ){ z++; }
173747    if( *z==0 ) return 0;
173748    while( isVowel(z) ){ z++; }
173749    if( *z==0 ) return 0;
173750    while( isConsonant(z) ){ z++; }
173751    return *z!=0;
173752  }
173753  
173754  /*
173755  ** Return TRUE if there is a vowel anywhere within z[0..n-1]
173756  */
173757  static int hasVowel(const char *z){
173758    while( isConsonant(z) ){ z++; }
173759    return *z!=0;
173760  }
173761  
173762  /*
173763  ** Return TRUE if the word ends in a double consonant.
173764  **
173765  ** The text is reversed here. So we are really looking at
173766  ** the first two characters of z[].
173767  */
173768  static int doubleConsonant(const char *z){
173769    return isConsonant(z) && z[0]==z[1];
173770  }
173771  
173772  /*
173773  ** Return TRUE if the word ends with three letters which
173774  ** are consonant-vowel-consonent and where the final consonant
173775  ** is not 'w', 'x', or 'y'.
173776  **
173777  ** The word is reversed here.  So we are really checking the
173778  ** first three letters and the first one cannot be in [wxy].
173779  */
173780  static int star_oh(const char *z){
173781    return
173782      isConsonant(z) &&
173783      z[0]!='w' && z[0]!='x' && z[0]!='y' &&
173784      isVowel(z+1) &&
173785      isConsonant(z+2);
173786  }
173787  
173788  /*
173789  ** If the word ends with zFrom and xCond() is true for the stem
173790  ** of the word that preceeds the zFrom ending, then change the 
173791  ** ending to zTo.
173792  **
173793  ** The input word *pz and zFrom are both in reverse order.  zTo
173794  ** is in normal order. 
173795  **
173796  ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
173797  ** match.  Not that TRUE is returned even if xCond() fails and
173798  ** no substitution occurs.
173799  */
173800  static int stem(
173801    char **pz,             /* The word being stemmed (Reversed) */
173802    const char *zFrom,     /* If the ending matches this... (Reversed) */
173803    const char *zTo,       /* ... change the ending to this (not reversed) */
173804    int (*xCond)(const char*)   /* Condition that must be true */
173805  ){
173806    char *z = *pz;
173807    while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
173808    if( *zFrom!=0 ) return 0;
173809    if( xCond && !xCond(z) ) return 1;
173810    while( *zTo ){
173811      *(--z) = *(zTo++);
173812    }
173813    *pz = z;
173814    return 1;
173815  }
173816  
173817  /*
173818  ** This is the fallback stemmer used when the porter stemmer is
173819  ** inappropriate.  The input word is copied into the output with
173820  ** US-ASCII case folding.  If the input word is too long (more
173821  ** than 20 bytes if it contains no digits or more than 6 bytes if
173822  ** it contains digits) then word is truncated to 20 or 6 bytes
173823  ** by taking 10 or 3 bytes from the beginning and end.
173824  */
173825  static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
173826    int i, mx, j;
173827    int hasDigit = 0;
173828    for(i=0; i<nIn; i++){
173829      char c = zIn[i];
173830      if( c>='A' && c<='Z' ){
173831        zOut[i] = c - 'A' + 'a';
173832      }else{
173833        if( c>='0' && c<='9' ) hasDigit = 1;
173834        zOut[i] = c;
173835      }
173836    }
173837    mx = hasDigit ? 3 : 10;
173838    if( nIn>mx*2 ){
173839      for(j=mx, i=nIn-mx; i<nIn; i++, j++){
173840        zOut[j] = zOut[i];
173841      }
173842      i = j;
173843    }
173844    zOut[i] = 0;
173845    *pnOut = i;
173846  }
173847  
173848  
173849  /*
173850  ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
173851  ** zOut is at least big enough to hold nIn bytes.  Write the actual
173852  ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
173853  **
173854  ** Any upper-case characters in the US-ASCII character set ([A-Z])
173855  ** are converted to lower case.  Upper-case UTF characters are
173856  ** unchanged.
173857  **
173858  ** Words that are longer than about 20 bytes are stemmed by retaining
173859  ** a few bytes from the beginning and the end of the word.  If the
173860  ** word contains digits, 3 bytes are taken from the beginning and
173861  ** 3 bytes from the end.  For long words without digits, 10 bytes
173862  ** are taken from each end.  US-ASCII case folding still applies.
173863  ** 
173864  ** If the input word contains not digits but does characters not 
173865  ** in [a-zA-Z] then no stemming is attempted and this routine just 
173866  ** copies the input into the input into the output with US-ASCII
173867  ** case folding.
173868  **
173869  ** Stemming never increases the length of the word.  So there is
173870  ** no chance of overflowing the zOut buffer.
173871  */
173872  static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
173873    int i, j;
173874    char zReverse[28];
173875    char *z, *z2;
173876    if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
173877      /* The word is too big or too small for the porter stemmer.
173878      ** Fallback to the copy stemmer */
173879      copy_stemmer(zIn, nIn, zOut, pnOut);
173880      return;
173881    }
173882    for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
173883      char c = zIn[i];
173884      if( c>='A' && c<='Z' ){
173885        zReverse[j] = c + 'a' - 'A';
173886      }else if( c>='a' && c<='z' ){
173887        zReverse[j] = c;
173888      }else{
173889        /* The use of a character not in [a-zA-Z] means that we fallback
173890        ** to the copy stemmer */
173891        copy_stemmer(zIn, nIn, zOut, pnOut);
173892        return;
173893      }
173894    }
173895    memset(&zReverse[sizeof(zReverse)-5], 0, 5);
173896    z = &zReverse[j+1];
173897  
173898  
173899    /* Step 1a */
173900    if( z[0]=='s' ){
173901      if(
173902       !stem(&z, "sess", "ss", 0) &&
173903       !stem(&z, "sei", "i", 0)  &&
173904       !stem(&z, "ss", "ss", 0)
173905      ){
173906        z++;
173907      }
173908    }
173909  
173910    /* Step 1b */  
173911    z2 = z;
173912    if( stem(&z, "dee", "ee", m_gt_0) ){
173913      /* Do nothing.  The work was all in the test */
173914    }else if( 
173915       (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
173916        && z!=z2
173917    ){
173918       if( stem(&z, "ta", "ate", 0) ||
173919           stem(&z, "lb", "ble", 0) ||
173920           stem(&z, "zi", "ize", 0) ){
173921         /* Do nothing.  The work was all in the test */
173922       }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
173923         z++;
173924       }else if( m_eq_1(z) && star_oh(z) ){
173925         *(--z) = 'e';
173926       }
173927    }
173928  
173929    /* Step 1c */
173930    if( z[0]=='y' && hasVowel(z+1) ){
173931      z[0] = 'i';
173932    }
173933  
173934    /* Step 2 */
173935    switch( z[1] ){
173936     case 'a':
173937       if( !stem(&z, "lanoita", "ate", m_gt_0) ){
173938         stem(&z, "lanoit", "tion", m_gt_0);
173939       }
173940       break;
173941     case 'c':
173942       if( !stem(&z, "icne", "ence", m_gt_0) ){
173943         stem(&z, "icna", "ance", m_gt_0);
173944       }
173945       break;
173946     case 'e':
173947       stem(&z, "rezi", "ize", m_gt_0);
173948       break;
173949     case 'g':
173950       stem(&z, "igol", "log", m_gt_0);
173951       break;
173952     case 'l':
173953       if( !stem(&z, "ilb", "ble", m_gt_0) 
173954        && !stem(&z, "illa", "al", m_gt_0)
173955        && !stem(&z, "iltne", "ent", m_gt_0)
173956        && !stem(&z, "ile", "e", m_gt_0)
173957       ){
173958         stem(&z, "ilsuo", "ous", m_gt_0);
173959       }
173960       break;
173961     case 'o':
173962       if( !stem(&z, "noitazi", "ize", m_gt_0)
173963        && !stem(&z, "noita", "ate", m_gt_0)
173964       ){
173965         stem(&z, "rota", "ate", m_gt_0);
173966       }
173967       break;
173968     case 's':
173969       if( !stem(&z, "msila", "al", m_gt_0)
173970        && !stem(&z, "ssenevi", "ive", m_gt_0)
173971        && !stem(&z, "ssenluf", "ful", m_gt_0)
173972       ){
173973         stem(&z, "ssensuo", "ous", m_gt_0);
173974       }
173975       break;
173976     case 't':
173977       if( !stem(&z, "itila", "al", m_gt_0)
173978        && !stem(&z, "itivi", "ive", m_gt_0)
173979       ){
173980         stem(&z, "itilib", "ble", m_gt_0);
173981       }
173982       break;
173983    }
173984  
173985    /* Step 3 */
173986    switch( z[0] ){
173987     case 'e':
173988       if( !stem(&z, "etaci", "ic", m_gt_0)
173989        && !stem(&z, "evita", "", m_gt_0)
173990       ){
173991         stem(&z, "ezila", "al", m_gt_0);
173992       }
173993       break;
173994     case 'i':
173995       stem(&z, "itici", "ic", m_gt_0);
173996       break;
173997     case 'l':
173998       if( !stem(&z, "laci", "ic", m_gt_0) ){
173999         stem(&z, "luf", "", m_gt_0);
174000       }
174001       break;
174002     case 's':
174003       stem(&z, "ssen", "", m_gt_0);
174004       break;
174005    }
174006  
174007    /* Step 4 */
174008    switch( z[1] ){
174009     case 'a':
174010       if( z[0]=='l' && m_gt_1(z+2) ){
174011         z += 2;
174012       }
174013       break;
174014     case 'c':
174015       if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
174016         z += 4;
174017       }
174018       break;
174019     case 'e':
174020       if( z[0]=='r' && m_gt_1(z+2) ){
174021         z += 2;
174022       }
174023       break;
174024     case 'i':
174025       if( z[0]=='c' && m_gt_1(z+2) ){
174026         z += 2;
174027       }
174028       break;
174029     case 'l':
174030       if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
174031         z += 4;
174032       }
174033       break;
174034     case 'n':
174035       if( z[0]=='t' ){
174036         if( z[2]=='a' ){
174037           if( m_gt_1(z+3) ){
174038             z += 3;
174039           }
174040         }else if( z[2]=='e' ){
174041           if( !stem(&z, "tneme", "", m_gt_1)
174042            && !stem(&z, "tnem", "", m_gt_1)
174043           ){
174044             stem(&z, "tne", "", m_gt_1);
174045           }
174046         }
174047       }
174048       break;
174049     case 'o':
174050       if( z[0]=='u' ){
174051         if( m_gt_1(z+2) ){
174052           z += 2;
174053         }
174054       }else if( z[3]=='s' || z[3]=='t' ){
174055         stem(&z, "noi", "", m_gt_1);
174056       }
174057       break;
174058     case 's':
174059       if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
174060         z += 3;
174061       }
174062       break;
174063     case 't':
174064       if( !stem(&z, "eta", "", m_gt_1) ){
174065         stem(&z, "iti", "", m_gt_1);
174066       }
174067       break;
174068     case 'u':
174069       if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
174070         z += 3;
174071       }
174072       break;
174073     case 'v':
174074     case 'z':
174075       if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
174076         z += 3;
174077       }
174078       break;
174079    }
174080  
174081    /* Step 5a */
174082    if( z[0]=='e' ){
174083      if( m_gt_1(z+1) ){
174084        z++;
174085      }else if( m_eq_1(z+1) && !star_oh(z+1) ){
174086        z++;
174087      }
174088    }
174089  
174090    /* Step 5b */
174091    if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
174092      z++;
174093    }
174094  
174095    /* z[] is now the stemmed word in reverse order.  Flip it back
174096    ** around into forward order and return.
174097    */
174098    *pnOut = i = (int)strlen(z);
174099    zOut[i] = 0;
174100    while( *z ){
174101      zOut[--i] = *(z++);
174102    }
174103  }
174104  
174105  /*
174106  ** Characters that can be part of a token.  We assume any character
174107  ** whose value is greater than 0x80 (any UTF character) can be
174108  ** part of a token.  In other words, delimiters all must have
174109  ** values of 0x7f or lower.
174110  */
174111  static const char porterIdChar[] = {
174112  /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
174113      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
174114      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
174115      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
174116      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
174117      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
174118  };
174119  #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
174120  
174121  /*
174122  ** Extract the next token from a tokenization cursor.  The cursor must
174123  ** have been opened by a prior call to porterOpen().
174124  */
174125  static int porterNext(
174126    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
174127    const char **pzToken,               /* OUT: *pzToken is the token text */
174128    int *pnBytes,                       /* OUT: Number of bytes in token */
174129    int *piStartOffset,                 /* OUT: Starting offset of token */
174130    int *piEndOffset,                   /* OUT: Ending offset of token */
174131    int *piPosition                     /* OUT: Position integer of token */
174132  ){
174133    porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
174134    const char *z = c->zInput;
174135  
174136    while( c->iOffset<c->nInput ){
174137      int iStartOffset, ch;
174138  
174139      /* Scan past delimiter characters */
174140      while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
174141        c->iOffset++;
174142      }
174143  
174144      /* Count non-delimiter characters. */
174145      iStartOffset = c->iOffset;
174146      while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
174147        c->iOffset++;
174148      }
174149  
174150      if( c->iOffset>iStartOffset ){
174151        int n = c->iOffset-iStartOffset;
174152        if( n>c->nAllocated ){
174153          char *pNew;
174154          c->nAllocated = n+20;
174155          pNew = sqlite3_realloc(c->zToken, c->nAllocated);
174156          if( !pNew ) return SQLITE_NOMEM;
174157          c->zToken = pNew;
174158        }
174159        porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
174160        *pzToken = c->zToken;
174161        *piStartOffset = iStartOffset;
174162        *piEndOffset = c->iOffset;
174163        *piPosition = c->iToken++;
174164        return SQLITE_OK;
174165      }
174166    }
174167    return SQLITE_DONE;
174168  }
174169  
174170  /*
174171  ** The set of routines that implement the porter-stemmer tokenizer
174172  */
174173  static const sqlite3_tokenizer_module porterTokenizerModule = {
174174    0,
174175    porterCreate,
174176    porterDestroy,
174177    porterOpen,
174178    porterClose,
174179    porterNext,
174180    0
174181  };
174182  
174183  /*
174184  ** Allocate a new porter tokenizer.  Return a pointer to the new
174185  ** tokenizer in *ppModule
174186  */
174187  SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
174188    sqlite3_tokenizer_module const**ppModule
174189  ){
174190    *ppModule = &porterTokenizerModule;
174191  }
174192  
174193  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
174194  
174195  /************** End of fts3_porter.c *****************************************/
174196  /************** Begin file fts3_tokenizer.c **********************************/
174197  /*
174198  ** 2007 June 22
174199  **
174200  ** The author disclaims copyright to this source code.  In place of
174201  ** a legal notice, here is a blessing:
174202  **
174203  **    May you do good and not evil.
174204  **    May you find forgiveness for yourself and forgive others.
174205  **    May you share freely, never taking more than you give.
174206  **
174207  ******************************************************************************
174208  **
174209  ** This is part of an SQLite module implementing full-text search.
174210  ** This particular file implements the generic tokenizer interface.
174211  */
174212  
174213  /*
174214  ** The code in this file is only compiled if:
174215  **
174216  **     * The FTS3 module is being built as an extension
174217  **       (in which case SQLITE_CORE is not defined), or
174218  **
174219  **     * The FTS3 module is being built into the core of
174220  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
174221  */
174222  /* #include "fts3Int.h" */
174223  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
174224  
174225  /* #include <assert.h> */
174226  /* #include <string.h> */
174227  
174228  /*
174229  ** Return true if the two-argument version of fts3_tokenizer()
174230  ** has been activated via a prior call to sqlite3_db_config(db,
174231  ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
174232  */
174233  static int fts3TokenizerEnabled(sqlite3_context *context){
174234    sqlite3 *db = sqlite3_context_db_handle(context);
174235    int isEnabled = 0;
174236    sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
174237    return isEnabled;
174238  }
174239  
174240  /*
174241  ** Implementation of the SQL scalar function for accessing the underlying 
174242  ** hash table. This function may be called as follows:
174243  **
174244  **   SELECT <function-name>(<key-name>);
174245  **   SELECT <function-name>(<key-name>, <pointer>);
174246  **
174247  ** where <function-name> is the name passed as the second argument
174248  ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
174249  **
174250  ** If the <pointer> argument is specified, it must be a blob value
174251  ** containing a pointer to be stored as the hash data corresponding
174252  ** to the string <key-name>. If <pointer> is not specified, then
174253  ** the string <key-name> must already exist in the has table. Otherwise,
174254  ** an error is returned.
174255  **
174256  ** Whether or not the <pointer> argument is specified, the value returned
174257  ** is a blob containing the pointer stored as the hash data corresponding
174258  ** to string <key-name> (after the hash-table is updated, if applicable).
174259  */
174260  static void fts3TokenizerFunc(
174261    sqlite3_context *context,
174262    int argc,
174263    sqlite3_value **argv
174264  ){
174265    Fts3Hash *pHash;
174266    void *pPtr = 0;
174267    const unsigned char *zName;
174268    int nName;
174269  
174270    assert( argc==1 || argc==2 );
174271  
174272    pHash = (Fts3Hash *)sqlite3_user_data(context);
174273  
174274    zName = sqlite3_value_text(argv[0]);
174275    nName = sqlite3_value_bytes(argv[0])+1;
174276  
174277    if( argc==2 ){
174278      if( fts3TokenizerEnabled(context) ){
174279        void *pOld;
174280        int n = sqlite3_value_bytes(argv[1]);
174281        if( zName==0 || n!=sizeof(pPtr) ){
174282          sqlite3_result_error(context, "argument type mismatch", -1);
174283          return;
174284        }
174285        pPtr = *(void **)sqlite3_value_blob(argv[1]);
174286        pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
174287        if( pOld==pPtr ){
174288          sqlite3_result_error(context, "out of memory", -1);
174289        }
174290      }else{
174291        sqlite3_result_error(context, "fts3tokenize disabled", -1);
174292        return;
174293      }
174294    }else{
174295      if( zName ){
174296        pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
174297      }
174298      if( !pPtr ){
174299        char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
174300        sqlite3_result_error(context, zErr, -1);
174301        sqlite3_free(zErr);
174302        return;
174303      }
174304    }
174305    sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
174306  }
174307  
174308  SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
174309    static const char isFtsIdChar[] = {
174310        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
174311        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
174312        0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
174313        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
174314        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
174315        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
174316        0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
174317        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
174318    };
174319    return (c&0x80 || isFtsIdChar[(int)(c)]);
174320  }
174321  
174322  SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
174323    const char *z1;
174324    const char *z2 = 0;
174325  
174326    /* Find the start of the next token. */
174327    z1 = zStr;
174328    while( z2==0 ){
174329      char c = *z1;
174330      switch( c ){
174331        case '\0': return 0;        /* No more tokens here */
174332        case '\'':
174333        case '"':
174334        case '`': {
174335          z2 = z1;
174336          while( *++z2 && (*z2!=c || *++z2==c) );
174337          break;
174338        }
174339        case '[':
174340          z2 = &z1[1];
174341          while( *z2 && z2[0]!=']' ) z2++;
174342          if( *z2 ) z2++;
174343          break;
174344  
174345        default:
174346          if( sqlite3Fts3IsIdChar(*z1) ){
174347            z2 = &z1[1];
174348            while( sqlite3Fts3IsIdChar(*z2) ) z2++;
174349          }else{
174350            z1++;
174351          }
174352      }
174353    }
174354  
174355    *pn = (int)(z2-z1);
174356    return z1;
174357  }
174358  
174359  SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
174360    Fts3Hash *pHash,                /* Tokenizer hash table */
174361    const char *zArg,               /* Tokenizer name */
174362    sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
174363    char **pzErr                    /* OUT: Set to malloced error message */
174364  ){
174365    int rc;
174366    char *z = (char *)zArg;
174367    int n = 0;
174368    char *zCopy;
174369    char *zEnd;                     /* Pointer to nul-term of zCopy */
174370    sqlite3_tokenizer_module *m;
174371  
174372    zCopy = sqlite3_mprintf("%s", zArg);
174373    if( !zCopy ) return SQLITE_NOMEM;
174374    zEnd = &zCopy[strlen(zCopy)];
174375  
174376    z = (char *)sqlite3Fts3NextToken(zCopy, &n);
174377    if( z==0 ){
174378      assert( n==0 );
174379      z = zCopy;
174380    }
174381    z[n] = '\0';
174382    sqlite3Fts3Dequote(z);
174383  
174384    m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
174385    if( !m ){
174386      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
174387      rc = SQLITE_ERROR;
174388    }else{
174389      char const **aArg = 0;
174390      int iArg = 0;
174391      z = &z[n+1];
174392      while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
174393        int nNew = sizeof(char *)*(iArg+1);
174394        char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
174395        if( !aNew ){
174396          sqlite3_free(zCopy);
174397          sqlite3_free((void *)aArg);
174398          return SQLITE_NOMEM;
174399        }
174400        aArg = aNew;
174401        aArg[iArg++] = z;
174402        z[n] = '\0';
174403        sqlite3Fts3Dequote(z);
174404        z = &z[n+1];
174405      }
174406      rc = m->xCreate(iArg, aArg, ppTok);
174407      assert( rc!=SQLITE_OK || *ppTok );
174408      if( rc!=SQLITE_OK ){
174409        sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
174410      }else{
174411        (*ppTok)->pModule = m; 
174412      }
174413      sqlite3_free((void *)aArg);
174414    }
174415  
174416    sqlite3_free(zCopy);
174417    return rc;
174418  }
174419  
174420  
174421  #ifdef SQLITE_TEST
174422  
174423  #if defined(INCLUDE_SQLITE_TCL_H)
174424  #  include "sqlite_tcl.h"
174425  #else
174426  #  include "tcl.h"
174427  #endif
174428  /* #include <string.h> */
174429  
174430  /*
174431  ** Implementation of a special SQL scalar function for testing tokenizers 
174432  ** designed to be used in concert with the Tcl testing framework. This
174433  ** function must be called with two or more arguments:
174434  **
174435  **   SELECT <function-name>(<key-name>, ..., <input-string>);
174436  **
174437  ** where <function-name> is the name passed as the second argument
174438  ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
174439  ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
174440  **
174441  ** The return value is a string that may be interpreted as a Tcl
174442  ** list. For each token in the <input-string>, three elements are
174443  ** added to the returned list. The first is the token position, the 
174444  ** second is the token text (folded, stemmed, etc.) and the third is the
174445  ** substring of <input-string> associated with the token. For example, 
174446  ** using the built-in "simple" tokenizer:
174447  **
174448  **   SELECT fts_tokenizer_test('simple', 'I don't see how');
174449  **
174450  ** will return the string:
174451  **
174452  **   "{0 i I 1 dont don't 2 see see 3 how how}"
174453  **   
174454  */
174455  static void testFunc(
174456    sqlite3_context *context,
174457    int argc,
174458    sqlite3_value **argv
174459  ){
174460    Fts3Hash *pHash;
174461    sqlite3_tokenizer_module *p;
174462    sqlite3_tokenizer *pTokenizer = 0;
174463    sqlite3_tokenizer_cursor *pCsr = 0;
174464  
174465    const char *zErr = 0;
174466  
174467    const char *zName;
174468    int nName;
174469    const char *zInput;
174470    int nInput;
174471  
174472    const char *azArg[64];
174473  
174474    const char *zToken;
174475    int nToken = 0;
174476    int iStart = 0;
174477    int iEnd = 0;
174478    int iPos = 0;
174479    int i;
174480  
174481    Tcl_Obj *pRet;
174482  
174483    if( argc<2 ){
174484      sqlite3_result_error(context, "insufficient arguments", -1);
174485      return;
174486    }
174487  
174488    nName = sqlite3_value_bytes(argv[0]);
174489    zName = (const char *)sqlite3_value_text(argv[0]);
174490    nInput = sqlite3_value_bytes(argv[argc-1]);
174491    zInput = (const char *)sqlite3_value_text(argv[argc-1]);
174492  
174493    pHash = (Fts3Hash *)sqlite3_user_data(context);
174494    p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
174495  
174496    if( !p ){
174497      char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
174498      sqlite3_result_error(context, zErr2, -1);
174499      sqlite3_free(zErr2);
174500      return;
174501    }
174502  
174503    pRet = Tcl_NewObj();
174504    Tcl_IncrRefCount(pRet);
174505  
174506    for(i=1; i<argc-1; i++){
174507      azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
174508    }
174509  
174510    if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
174511      zErr = "error in xCreate()";
174512      goto finish;
174513    }
174514    pTokenizer->pModule = p;
174515    if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
174516      zErr = "error in xOpen()";
174517      goto finish;
174518    }
174519  
174520    while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
174521      Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
174522      Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
174523      zToken = &zInput[iStart];
174524      nToken = iEnd-iStart;
174525      Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
174526    }
174527  
174528    if( SQLITE_OK!=p->xClose(pCsr) ){
174529      zErr = "error in xClose()";
174530      goto finish;
174531    }
174532    if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
174533      zErr = "error in xDestroy()";
174534      goto finish;
174535    }
174536  
174537  finish:
174538    if( zErr ){
174539      sqlite3_result_error(context, zErr, -1);
174540    }else{
174541      sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
174542    }
174543    Tcl_DecrRefCount(pRet);
174544  }
174545  
174546  static
174547  int registerTokenizer(
174548    sqlite3 *db, 
174549    char *zName, 
174550    const sqlite3_tokenizer_module *p
174551  ){
174552    int rc;
174553    sqlite3_stmt *pStmt;
174554    const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
174555  
174556    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
174557    if( rc!=SQLITE_OK ){
174558      return rc;
174559    }
174560  
174561    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
174562    sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
174563    sqlite3_step(pStmt);
174564  
174565    return sqlite3_finalize(pStmt);
174566  }
174567  
174568  
174569  static
174570  int queryTokenizer(
174571    sqlite3 *db, 
174572    char *zName,  
174573    const sqlite3_tokenizer_module **pp
174574  ){
174575    int rc;
174576    sqlite3_stmt *pStmt;
174577    const char zSql[] = "SELECT fts3_tokenizer(?)";
174578  
174579    *pp = 0;
174580    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
174581    if( rc!=SQLITE_OK ){
174582      return rc;
174583    }
174584  
174585    sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
174586    if( SQLITE_ROW==sqlite3_step(pStmt) ){
174587      if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
174588        memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
174589      }
174590    }
174591  
174592    return sqlite3_finalize(pStmt);
174593  }
174594  
174595  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
174596  
174597  /*
174598  ** Implementation of the scalar function fts3_tokenizer_internal_test().
174599  ** This function is used for testing only, it is not included in the
174600  ** build unless SQLITE_TEST is defined.
174601  **
174602  ** The purpose of this is to test that the fts3_tokenizer() function
174603  ** can be used as designed by the C-code in the queryTokenizer and
174604  ** registerTokenizer() functions above. These two functions are repeated
174605  ** in the README.tokenizer file as an example, so it is important to
174606  ** test them.
174607  **
174608  ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
174609  ** function with no arguments. An assert() will fail if a problem is
174610  ** detected. i.e.:
174611  **
174612  **     SELECT fts3_tokenizer_internal_test();
174613  **
174614  */
174615  static void intTestFunc(
174616    sqlite3_context *context,
174617    int argc,
174618    sqlite3_value **argv
174619  ){
174620    int rc;
174621    const sqlite3_tokenizer_module *p1;
174622    const sqlite3_tokenizer_module *p2;
174623    sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
174624  
174625    UNUSED_PARAMETER(argc);
174626    UNUSED_PARAMETER(argv);
174627  
174628    /* Test the query function */
174629    sqlite3Fts3SimpleTokenizerModule(&p1);
174630    rc = queryTokenizer(db, "simple", &p2);
174631    assert( rc==SQLITE_OK );
174632    assert( p1==p2 );
174633    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
174634    assert( rc==SQLITE_ERROR );
174635    assert( p2==0 );
174636    assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
174637  
174638    /* Test the storage function */
174639    if( fts3TokenizerEnabled(context) ){
174640      rc = registerTokenizer(db, "nosuchtokenizer", p1);
174641      assert( rc==SQLITE_OK );
174642      rc = queryTokenizer(db, "nosuchtokenizer", &p2);
174643      assert( rc==SQLITE_OK );
174644      assert( p2==p1 );
174645    }
174646  
174647    sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
174648  }
174649  
174650  #endif
174651  
174652  /*
174653  ** Set up SQL objects in database db used to access the contents of
174654  ** the hash table pointed to by argument pHash. The hash table must
174655  ** been initialized to use string keys, and to take a private copy 
174656  ** of the key when a value is inserted. i.e. by a call similar to:
174657  **
174658  **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
174659  **
174660  ** This function adds a scalar function (see header comment above
174661  ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
174662  ** defined at compilation time, a temporary virtual table (see header 
174663  ** comment above struct HashTableVtab) to the database schema. Both 
174664  ** provide read/write access to the contents of *pHash.
174665  **
174666  ** The third argument to this function, zName, is used as the name
174667  ** of both the scalar and, if created, the virtual table.
174668  */
174669  SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
174670    sqlite3 *db, 
174671    Fts3Hash *pHash, 
174672    const char *zName
174673  ){
174674    int rc = SQLITE_OK;
174675    void *p = (void *)pHash;
174676    const int any = SQLITE_ANY;
174677  
174678  #ifdef SQLITE_TEST
174679    char *zTest = 0;
174680    char *zTest2 = 0;
174681    void *pdb = (void *)db;
174682    zTest = sqlite3_mprintf("%s_test", zName);
174683    zTest2 = sqlite3_mprintf("%s_internal_test", zName);
174684    if( !zTest || !zTest2 ){
174685      rc = SQLITE_NOMEM;
174686    }
174687  #endif
174688  
174689    if( SQLITE_OK==rc ){
174690      rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
174691    }
174692    if( SQLITE_OK==rc ){
174693      rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
174694    }
174695  #ifdef SQLITE_TEST
174696    if( SQLITE_OK==rc ){
174697      rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
174698    }
174699    if( SQLITE_OK==rc ){
174700      rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
174701    }
174702  #endif
174703  
174704  #ifdef SQLITE_TEST
174705    sqlite3_free(zTest);
174706    sqlite3_free(zTest2);
174707  #endif
174708  
174709    return rc;
174710  }
174711  
174712  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
174713  
174714  /************** End of fts3_tokenizer.c **************************************/
174715  /************** Begin file fts3_tokenizer1.c *********************************/
174716  /*
174717  ** 2006 Oct 10
174718  **
174719  ** The author disclaims copyright to this source code.  In place of
174720  ** a legal notice, here is a blessing:
174721  **
174722  **    May you do good and not evil.
174723  **    May you find forgiveness for yourself and forgive others.
174724  **    May you share freely, never taking more than you give.
174725  **
174726  ******************************************************************************
174727  **
174728  ** Implementation of the "simple" full-text-search tokenizer.
174729  */
174730  
174731  /*
174732  ** The code in this file is only compiled if:
174733  **
174734  **     * The FTS3 module is being built as an extension
174735  **       (in which case SQLITE_CORE is not defined), or
174736  **
174737  **     * The FTS3 module is being built into the core of
174738  **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
174739  */
174740  /* #include "fts3Int.h" */
174741  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
174742  
174743  /* #include <assert.h> */
174744  /* #include <stdlib.h> */
174745  /* #include <stdio.h> */
174746  /* #include <string.h> */
174747  
174748  /* #include "fts3_tokenizer.h" */
174749  
174750  typedef struct simple_tokenizer {
174751    sqlite3_tokenizer base;
174752    char delim[128];             /* flag ASCII delimiters */
174753  } simple_tokenizer;
174754  
174755  typedef struct simple_tokenizer_cursor {
174756    sqlite3_tokenizer_cursor base;
174757    const char *pInput;          /* input we are tokenizing */
174758    int nBytes;                  /* size of the input */
174759    int iOffset;                 /* current position in pInput */
174760    int iToken;                  /* index of next token to be returned */
174761    char *pToken;                /* storage for current token */
174762    int nTokenAllocated;         /* space allocated to zToken buffer */
174763  } simple_tokenizer_cursor;
174764  
174765  
174766  static int simpleDelim(simple_tokenizer *t, unsigned char c){
174767    return c<0x80 && t->delim[c];
174768  }
174769  static int fts3_isalnum(int x){
174770    return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
174771  }
174772  
174773  /*
174774  ** Create a new tokenizer instance.
174775  */
174776  static int simpleCreate(
174777    int argc, const char * const *argv,
174778    sqlite3_tokenizer **ppTokenizer
174779  ){
174780    simple_tokenizer *t;
174781  
174782    t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
174783    if( t==NULL ) return SQLITE_NOMEM;
174784    memset(t, 0, sizeof(*t));
174785  
174786    /* TODO(shess) Delimiters need to remain the same from run to run,
174787    ** else we need to reindex.  One solution would be a meta-table to
174788    ** track such information in the database, then we'd only want this
174789    ** information on the initial create.
174790    */
174791    if( argc>1 ){
174792      int i, n = (int)strlen(argv[1]);
174793      for(i=0; i<n; i++){
174794        unsigned char ch = argv[1][i];
174795        /* We explicitly don't support UTF-8 delimiters for now. */
174796        if( ch>=0x80 ){
174797          sqlite3_free(t);
174798          return SQLITE_ERROR;
174799        }
174800        t->delim[ch] = 1;
174801      }
174802    } else {
174803      /* Mark non-alphanumeric ASCII characters as delimiters */
174804      int i;
174805      for(i=1; i<0x80; i++){
174806        t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
174807      }
174808    }
174809  
174810    *ppTokenizer = &t->base;
174811    return SQLITE_OK;
174812  }
174813  
174814  /*
174815  ** Destroy a tokenizer
174816  */
174817  static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
174818    sqlite3_free(pTokenizer);
174819    return SQLITE_OK;
174820  }
174821  
174822  /*
174823  ** Prepare to begin tokenizing a particular string.  The input
174824  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
174825  ** used to incrementally tokenize this string is returned in 
174826  ** *ppCursor.
174827  */
174828  static int simpleOpen(
174829    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
174830    const char *pInput, int nBytes,        /* String to be tokenized */
174831    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
174832  ){
174833    simple_tokenizer_cursor *c;
174834  
174835    UNUSED_PARAMETER(pTokenizer);
174836  
174837    c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
174838    if( c==NULL ) return SQLITE_NOMEM;
174839  
174840    c->pInput = pInput;
174841    if( pInput==0 ){
174842      c->nBytes = 0;
174843    }else if( nBytes<0 ){
174844      c->nBytes = (int)strlen(pInput);
174845    }else{
174846      c->nBytes = nBytes;
174847    }
174848    c->iOffset = 0;                 /* start tokenizing at the beginning */
174849    c->iToken = 0;
174850    c->pToken = NULL;               /* no space allocated, yet. */
174851    c->nTokenAllocated = 0;
174852  
174853    *ppCursor = &c->base;
174854    return SQLITE_OK;
174855  }
174856  
174857  /*
174858  ** Close a tokenization cursor previously opened by a call to
174859  ** simpleOpen() above.
174860  */
174861  static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
174862    simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
174863    sqlite3_free(c->pToken);
174864    sqlite3_free(c);
174865    return SQLITE_OK;
174866  }
174867  
174868  /*
174869  ** Extract the next token from a tokenization cursor.  The cursor must
174870  ** have been opened by a prior call to simpleOpen().
174871  */
174872  static int simpleNext(
174873    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
174874    const char **ppToken,               /* OUT: *ppToken is the token text */
174875    int *pnBytes,                       /* OUT: Number of bytes in token */
174876    int *piStartOffset,                 /* OUT: Starting offset of token */
174877    int *piEndOffset,                   /* OUT: Ending offset of token */
174878    int *piPosition                     /* OUT: Position integer of token */
174879  ){
174880    simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
174881    simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
174882    unsigned char *p = (unsigned char *)c->pInput;
174883  
174884    while( c->iOffset<c->nBytes ){
174885      int iStartOffset;
174886  
174887      /* Scan past delimiter characters */
174888      while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
174889        c->iOffset++;
174890      }
174891  
174892      /* Count non-delimiter characters. */
174893      iStartOffset = c->iOffset;
174894      while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
174895        c->iOffset++;
174896      }
174897  
174898      if( c->iOffset>iStartOffset ){
174899        int i, n = c->iOffset-iStartOffset;
174900        if( n>c->nTokenAllocated ){
174901          char *pNew;
174902          c->nTokenAllocated = n+20;
174903          pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
174904          if( !pNew ) return SQLITE_NOMEM;
174905          c->pToken = pNew;
174906        }
174907        for(i=0; i<n; i++){
174908          /* TODO(shess) This needs expansion to handle UTF-8
174909          ** case-insensitivity.
174910          */
174911          unsigned char ch = p[iStartOffset+i];
174912          c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
174913        }
174914        *ppToken = c->pToken;
174915        *pnBytes = n;
174916        *piStartOffset = iStartOffset;
174917        *piEndOffset = c->iOffset;
174918        *piPosition = c->iToken++;
174919  
174920        return SQLITE_OK;
174921      }
174922    }
174923    return SQLITE_DONE;
174924  }
174925  
174926  /*
174927  ** The set of routines that implement the simple tokenizer
174928  */
174929  static const sqlite3_tokenizer_module simpleTokenizerModule = {
174930    0,
174931    simpleCreate,
174932    simpleDestroy,
174933    simpleOpen,
174934    simpleClose,
174935    simpleNext,
174936    0,
174937  };
174938  
174939  /*
174940  ** Allocate a new simple tokenizer.  Return a pointer to the new
174941  ** tokenizer in *ppModule
174942  */
174943  SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
174944    sqlite3_tokenizer_module const**ppModule
174945  ){
174946    *ppModule = &simpleTokenizerModule;
174947  }
174948  
174949  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
174950  
174951  /************** End of fts3_tokenizer1.c *************************************/
174952  /************** Begin file fts3_tokenize_vtab.c ******************************/
174953  /*
174954  ** 2013 Apr 22
174955  **
174956  ** The author disclaims copyright to this source code.  In place of
174957  ** a legal notice, here is a blessing:
174958  **
174959  **    May you do good and not evil.
174960  **    May you find forgiveness for yourself and forgive others.
174961  **    May you share freely, never taking more than you give.
174962  **
174963  ******************************************************************************
174964  **
174965  ** This file contains code for the "fts3tokenize" virtual table module.
174966  ** An fts3tokenize virtual table is created as follows:
174967  **
174968  **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
174969  **       <tokenizer-name>, <arg-1>, ...
174970  **   );
174971  **
174972  ** The table created has the following schema:
174973  **
174974  **   CREATE TABLE <tbl>(input, token, start, end, position)
174975  **
174976  ** When queried, the query must include a WHERE clause of type:
174977  **
174978  **   input = <string>
174979  **
174980  ** The virtual table module tokenizes this <string>, using the FTS3 
174981  ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
174982  ** statement and returns one row for each token in the result. With
174983  ** fields set as follows:
174984  **
174985  **   input:   Always set to a copy of <string>
174986  **   token:   A token from the input.
174987  **   start:   Byte offset of the token within the input <string>.
174988  **   end:     Byte offset of the byte immediately following the end of the
174989  **            token within the input string.
174990  **   pos:     Token offset of token within input.
174991  **
174992  */
174993  /* #include "fts3Int.h" */
174994  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
174995  
174996  /* #include <string.h> */
174997  /* #include <assert.h> */
174998  
174999  typedef struct Fts3tokTable Fts3tokTable;
175000  typedef struct Fts3tokCursor Fts3tokCursor;
175001  
175002  /*
175003  ** Virtual table structure.
175004  */
175005  struct Fts3tokTable {
175006    sqlite3_vtab base;              /* Base class used by SQLite core */
175007    const sqlite3_tokenizer_module *pMod;
175008    sqlite3_tokenizer *pTok;
175009  };
175010  
175011  /*
175012  ** Virtual table cursor structure.
175013  */
175014  struct Fts3tokCursor {
175015    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
175016    char *zInput;                   /* Input string */
175017    sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
175018    int iRowid;                     /* Current 'rowid' value */
175019    const char *zToken;             /* Current 'token' value */
175020    int nToken;                     /* Size of zToken in bytes */
175021    int iStart;                     /* Current 'start' value */
175022    int iEnd;                       /* Current 'end' value */
175023    int iPos;                       /* Current 'pos' value */
175024  };
175025  
175026  /*
175027  ** Query FTS for the tokenizer implementation named zName.
175028  */
175029  static int fts3tokQueryTokenizer(
175030    Fts3Hash *pHash,
175031    const char *zName,
175032    const sqlite3_tokenizer_module **pp,
175033    char **pzErr
175034  ){
175035    sqlite3_tokenizer_module *p;
175036    int nName = (int)strlen(zName);
175037  
175038    p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
175039    if( !p ){
175040      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
175041      return SQLITE_ERROR;
175042    }
175043  
175044    *pp = p;
175045    return SQLITE_OK;
175046  }
175047  
175048  /*
175049  ** The second argument, argv[], is an array of pointers to nul-terminated
175050  ** strings. This function makes a copy of the array and strings into a 
175051  ** single block of memory. It then dequotes any of the strings that appear
175052  ** to be quoted.
175053  **
175054  ** If successful, output parameter *pazDequote is set to point at the
175055  ** array of dequoted strings and SQLITE_OK is returned. The caller is
175056  ** responsible for eventually calling sqlite3_free() to free the array
175057  ** in this case. Or, if an error occurs, an SQLite error code is returned.
175058  ** The final value of *pazDequote is undefined in this case.
175059  */
175060  static int fts3tokDequoteArray(
175061    int argc,                       /* Number of elements in argv[] */
175062    const char * const *argv,       /* Input array */
175063    char ***pazDequote              /* Output array */
175064  ){
175065    int rc = SQLITE_OK;             /* Return code */
175066    if( argc==0 ){
175067      *pazDequote = 0;
175068    }else{
175069      int i;
175070      int nByte = 0;
175071      char **azDequote;
175072  
175073      for(i=0; i<argc; i++){
175074        nByte += (int)(strlen(argv[i]) + 1);
175075      }
175076  
175077      *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
175078      if( azDequote==0 ){
175079        rc = SQLITE_NOMEM;
175080      }else{
175081        char *pSpace = (char *)&azDequote[argc];
175082        for(i=0; i<argc; i++){
175083          int n = (int)strlen(argv[i]);
175084          azDequote[i] = pSpace;
175085          memcpy(pSpace, argv[i], n+1);
175086          sqlite3Fts3Dequote(pSpace);
175087          pSpace += (n+1);
175088        }
175089      }
175090    }
175091  
175092    return rc;
175093  }
175094  
175095  /*
175096  ** Schema of the tokenizer table.
175097  */
175098  #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
175099  
175100  /*
175101  ** This function does all the work for both the xConnect and xCreate methods.
175102  ** These tables have no persistent representation of their own, so xConnect
175103  ** and xCreate are identical operations.
175104  **
175105  **   argv[0]: module name
175106  **   argv[1]: database name 
175107  **   argv[2]: table name
175108  **   argv[3]: first argument (tokenizer name)
175109  */
175110  static int fts3tokConnectMethod(
175111    sqlite3 *db,                    /* Database connection */
175112    void *pHash,                    /* Hash table of tokenizers */
175113    int argc,                       /* Number of elements in argv array */
175114    const char * const *argv,       /* xCreate/xConnect argument array */
175115    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
175116    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
175117  ){
175118    Fts3tokTable *pTab = 0;
175119    const sqlite3_tokenizer_module *pMod = 0;
175120    sqlite3_tokenizer *pTok = 0;
175121    int rc;
175122    char **azDequote = 0;
175123    int nDequote;
175124  
175125    rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
175126    if( rc!=SQLITE_OK ) return rc;
175127  
175128    nDequote = argc-3;
175129    rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
175130  
175131    if( rc==SQLITE_OK ){
175132      const char *zModule;
175133      if( nDequote<1 ){
175134        zModule = "simple";
175135      }else{
175136        zModule = azDequote[0];
175137      }
175138      rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
175139    }
175140  
175141    assert( (rc==SQLITE_OK)==(pMod!=0) );
175142    if( rc==SQLITE_OK ){
175143      const char * const *azArg = (const char * const *)&azDequote[1];
175144      rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
175145    }
175146  
175147    if( rc==SQLITE_OK ){
175148      pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
175149      if( pTab==0 ){
175150        rc = SQLITE_NOMEM;
175151      }
175152    }
175153  
175154    if( rc==SQLITE_OK ){
175155      memset(pTab, 0, sizeof(Fts3tokTable));
175156      pTab->pMod = pMod;
175157      pTab->pTok = pTok;
175158      *ppVtab = &pTab->base;
175159    }else{
175160      if( pTok ){
175161        pMod->xDestroy(pTok);
175162      }
175163    }
175164  
175165    sqlite3_free(azDequote);
175166    return rc;
175167  }
175168  
175169  /*
175170  ** This function does the work for both the xDisconnect and xDestroy methods.
175171  ** These tables have no persistent representation of their own, so xDisconnect
175172  ** and xDestroy are identical operations.
175173  */
175174  static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
175175    Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
175176  
175177    pTab->pMod->xDestroy(pTab->pTok);
175178    sqlite3_free(pTab);
175179    return SQLITE_OK;
175180  }
175181  
175182  /*
175183  ** xBestIndex - Analyze a WHERE and ORDER BY clause.
175184  */
175185  static int fts3tokBestIndexMethod(
175186    sqlite3_vtab *pVTab, 
175187    sqlite3_index_info *pInfo
175188  ){
175189    int i;
175190    UNUSED_PARAMETER(pVTab);
175191  
175192    for(i=0; i<pInfo->nConstraint; i++){
175193      if( pInfo->aConstraint[i].usable 
175194       && pInfo->aConstraint[i].iColumn==0 
175195       && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
175196      ){
175197        pInfo->idxNum = 1;
175198        pInfo->aConstraintUsage[i].argvIndex = 1;
175199        pInfo->aConstraintUsage[i].omit = 1;
175200        pInfo->estimatedCost = 1;
175201        return SQLITE_OK;
175202      }
175203    }
175204  
175205    pInfo->idxNum = 0;
175206    assert( pInfo->estimatedCost>1000000.0 );
175207  
175208    return SQLITE_OK;
175209  }
175210  
175211  /*
175212  ** xOpen - Open a cursor.
175213  */
175214  static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
175215    Fts3tokCursor *pCsr;
175216    UNUSED_PARAMETER(pVTab);
175217  
175218    pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
175219    if( pCsr==0 ){
175220      return SQLITE_NOMEM;
175221    }
175222    memset(pCsr, 0, sizeof(Fts3tokCursor));
175223  
175224    *ppCsr = (sqlite3_vtab_cursor *)pCsr;
175225    return SQLITE_OK;
175226  }
175227  
175228  /*
175229  ** Reset the tokenizer cursor passed as the only argument. As if it had
175230  ** just been returned by fts3tokOpenMethod().
175231  */
175232  static void fts3tokResetCursor(Fts3tokCursor *pCsr){
175233    if( pCsr->pCsr ){
175234      Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
175235      pTab->pMod->xClose(pCsr->pCsr);
175236      pCsr->pCsr = 0;
175237    }
175238    sqlite3_free(pCsr->zInput);
175239    pCsr->zInput = 0;
175240    pCsr->zToken = 0;
175241    pCsr->nToken = 0;
175242    pCsr->iStart = 0;
175243    pCsr->iEnd = 0;
175244    pCsr->iPos = 0;
175245    pCsr->iRowid = 0;
175246  }
175247  
175248  /*
175249  ** xClose - Close a cursor.
175250  */
175251  static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
175252    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175253  
175254    fts3tokResetCursor(pCsr);
175255    sqlite3_free(pCsr);
175256    return SQLITE_OK;
175257  }
175258  
175259  /*
175260  ** xNext - Advance the cursor to the next row, if any.
175261  */
175262  static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
175263    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175264    Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
175265    int rc;                         /* Return code */
175266  
175267    pCsr->iRowid++;
175268    rc = pTab->pMod->xNext(pCsr->pCsr,
175269        &pCsr->zToken, &pCsr->nToken,
175270        &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
175271    );
175272  
175273    if( rc!=SQLITE_OK ){
175274      fts3tokResetCursor(pCsr);
175275      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
175276    }
175277  
175278    return rc;
175279  }
175280  
175281  /*
175282  ** xFilter - Initialize a cursor to point at the start of its data.
175283  */
175284  static int fts3tokFilterMethod(
175285    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
175286    int idxNum,                     /* Strategy index */
175287    const char *idxStr,             /* Unused */
175288    int nVal,                       /* Number of elements in apVal */
175289    sqlite3_value **apVal           /* Arguments for the indexing scheme */
175290  ){
175291    int rc = SQLITE_ERROR;
175292    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175293    Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
175294    UNUSED_PARAMETER(idxStr);
175295    UNUSED_PARAMETER(nVal);
175296  
175297    fts3tokResetCursor(pCsr);
175298    if( idxNum==1 ){
175299      const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
175300      int nByte = sqlite3_value_bytes(apVal[0]);
175301      pCsr->zInput = sqlite3_malloc(nByte+1);
175302      if( pCsr->zInput==0 ){
175303        rc = SQLITE_NOMEM;
175304      }else{
175305        memcpy(pCsr->zInput, zByte, nByte);
175306        pCsr->zInput[nByte] = 0;
175307        rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
175308        if( rc==SQLITE_OK ){
175309          pCsr->pCsr->pTokenizer = pTab->pTok;
175310        }
175311      }
175312    }
175313  
175314    if( rc!=SQLITE_OK ) return rc;
175315    return fts3tokNextMethod(pCursor);
175316  }
175317  
175318  /*
175319  ** xEof - Return true if the cursor is at EOF, or false otherwise.
175320  */
175321  static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
175322    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175323    return (pCsr->zToken==0);
175324  }
175325  
175326  /*
175327  ** xColumn - Return a column value.
175328  */
175329  static int fts3tokColumnMethod(
175330    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
175331    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
175332    int iCol                        /* Index of column to read value from */
175333  ){
175334    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175335  
175336    /* CREATE TABLE x(input, token, start, end, position) */
175337    switch( iCol ){
175338      case 0:
175339        sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
175340        break;
175341      case 1:
175342        sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
175343        break;
175344      case 2:
175345        sqlite3_result_int(pCtx, pCsr->iStart);
175346        break;
175347      case 3:
175348        sqlite3_result_int(pCtx, pCsr->iEnd);
175349        break;
175350      default:
175351        assert( iCol==4 );
175352        sqlite3_result_int(pCtx, pCsr->iPos);
175353        break;
175354    }
175355    return SQLITE_OK;
175356  }
175357  
175358  /*
175359  ** xRowid - Return the current rowid for the cursor.
175360  */
175361  static int fts3tokRowidMethod(
175362    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
175363    sqlite_int64 *pRowid            /* OUT: Rowid value */
175364  ){
175365    Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
175366    *pRowid = (sqlite3_int64)pCsr->iRowid;
175367    return SQLITE_OK;
175368  }
175369  
175370  /*
175371  ** Register the fts3tok module with database connection db. Return SQLITE_OK
175372  ** if successful or an error code if sqlite3_create_module() fails.
175373  */
175374  SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
175375    static const sqlite3_module fts3tok_module = {
175376       0,                           /* iVersion      */
175377       fts3tokConnectMethod,        /* xCreate       */
175378       fts3tokConnectMethod,        /* xConnect      */
175379       fts3tokBestIndexMethod,      /* xBestIndex    */
175380       fts3tokDisconnectMethod,     /* xDisconnect   */
175381       fts3tokDisconnectMethod,     /* xDestroy      */
175382       fts3tokOpenMethod,           /* xOpen         */
175383       fts3tokCloseMethod,          /* xClose        */
175384       fts3tokFilterMethod,         /* xFilter       */
175385       fts3tokNextMethod,           /* xNext         */
175386       fts3tokEofMethod,            /* xEof          */
175387       fts3tokColumnMethod,         /* xColumn       */
175388       fts3tokRowidMethod,          /* xRowid        */
175389       0,                           /* xUpdate       */
175390       0,                           /* xBegin        */
175391       0,                           /* xSync         */
175392       0,                           /* xCommit       */
175393       0,                           /* xRollback     */
175394       0,                           /* xFindFunction */
175395       0,                           /* xRename       */
175396       0,                           /* xSavepoint    */
175397       0,                           /* xRelease      */
175398       0,                           /* xRollbackTo   */
175399       0                            /* xShadowName   */
175400    };
175401    int rc;                         /* Return code */
175402  
175403    rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
175404    return rc;
175405  }
175406  
175407  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
175408  
175409  /************** End of fts3_tokenize_vtab.c **********************************/
175410  /************** Begin file fts3_write.c **************************************/
175411  /*
175412  ** 2009 Oct 23
175413  **
175414  ** The author disclaims copyright to this source code.  In place of
175415  ** a legal notice, here is a blessing:
175416  **
175417  **    May you do good and not evil.
175418  **    May you find forgiveness for yourself and forgive others.
175419  **    May you share freely, never taking more than you give.
175420  **
175421  ******************************************************************************
175422  **
175423  ** This file is part of the SQLite FTS3 extension module. Specifically,
175424  ** this file contains code to insert, update and delete rows from FTS3
175425  ** tables. It also contains code to merge FTS3 b-tree segments. Some
175426  ** of the sub-routines used to merge segments are also used by the query 
175427  ** code in fts3.c.
175428  */
175429  
175430  /* #include "fts3Int.h" */
175431  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
175432  
175433  /* #include <string.h> */
175434  /* #include <assert.h> */
175435  /* #include <stdlib.h> */
175436  
175437  
175438  #define FTS_MAX_APPENDABLE_HEIGHT 16
175439  
175440  /*
175441  ** When full-text index nodes are loaded from disk, the buffer that they
175442  ** are loaded into has the following number of bytes of padding at the end 
175443  ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
175444  ** of 920 bytes is allocated for it.
175445  **
175446  ** This means that if we have a pointer into a buffer containing node data,
175447  ** it is always safe to read up to two varints from it without risking an
175448  ** overread, even if the node data is corrupted.
175449  */
175450  #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
175451  
175452  /*
175453  ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
175454  ** memory incrementally instead of all at once. This can be a big performance
175455  ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
175456  ** method before retrieving all query results (as may happen, for example,
175457  ** if a query has a LIMIT clause).
175458  **
175459  ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
175460  ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
175461  ** The code is written so that the hard lower-limit for each of these values 
175462  ** is 1. Clearly such small values would be inefficient, but can be useful 
175463  ** for testing purposes.
175464  **
175465  ** If this module is built with SQLITE_TEST defined, these constants may
175466  ** be overridden at runtime for testing purposes. File fts3_test.c contains
175467  ** a Tcl interface to read and write the values.
175468  */
175469  #ifdef SQLITE_TEST
175470  int test_fts3_node_chunksize = (4*1024);
175471  int test_fts3_node_chunk_threshold = (4*1024)*4;
175472  # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
175473  # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
175474  #else
175475  # define FTS3_NODE_CHUNKSIZE (4*1024) 
175476  # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
175477  #endif
175478  
175479  /*
175480  ** The two values that may be meaningfully bound to the :1 parameter in
175481  ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
175482  */
175483  #define FTS_STAT_DOCTOTAL      0
175484  #define FTS_STAT_INCRMERGEHINT 1
175485  #define FTS_STAT_AUTOINCRMERGE 2
175486  
175487  /*
175488  ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
175489  ** and incremental merge operation that takes place. This is used for 
175490  ** debugging FTS only, it should not usually be turned on in production
175491  ** systems.
175492  */
175493  #ifdef FTS3_LOG_MERGES
175494  static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
175495    sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
175496  }
175497  #else
175498  #define fts3LogMerge(x, y)
175499  #endif
175500  
175501  
175502  typedef struct PendingList PendingList;
175503  typedef struct SegmentNode SegmentNode;
175504  typedef struct SegmentWriter SegmentWriter;
175505  
175506  /*
175507  ** An instance of the following data structure is used to build doclists
175508  ** incrementally. See function fts3PendingListAppend() for details.
175509  */
175510  struct PendingList {
175511    int nData;
175512    char *aData;
175513    int nSpace;
175514    sqlite3_int64 iLastDocid;
175515    sqlite3_int64 iLastCol;
175516    sqlite3_int64 iLastPos;
175517  };
175518  
175519  
175520  /*
175521  ** Each cursor has a (possibly empty) linked list of the following objects.
175522  */
175523  struct Fts3DeferredToken {
175524    Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
175525    int iCol;                       /* Column token must occur in */
175526    Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
175527    PendingList *pList;             /* Doclist is assembled here */
175528  };
175529  
175530  /*
175531  ** An instance of this structure is used to iterate through the terms on
175532  ** a contiguous set of segment b-tree leaf nodes. Although the details of
175533  ** this structure are only manipulated by code in this file, opaque handles
175534  ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
175535  ** terms when querying the full-text index. See functions:
175536  **
175537  **   sqlite3Fts3SegReaderNew()
175538  **   sqlite3Fts3SegReaderFree()
175539  **   sqlite3Fts3SegReaderIterate()
175540  **
175541  ** Methods used to manipulate Fts3SegReader structures:
175542  **
175543  **   fts3SegReaderNext()
175544  **   fts3SegReaderFirstDocid()
175545  **   fts3SegReaderNextDocid()
175546  */
175547  struct Fts3SegReader {
175548    int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
175549    u8 bLookup;                     /* True for a lookup only */
175550    u8 rootOnly;                    /* True for a root-only reader */
175551  
175552    sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
175553    sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
175554    sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
175555    sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
175556  
175557    char *aNode;                    /* Pointer to node data (or NULL) */
175558    int nNode;                      /* Size of buffer at aNode (or 0) */
175559    int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
175560    sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
175561  
175562    Fts3HashElem **ppNextElem;
175563  
175564    /* Variables set by fts3SegReaderNext(). These may be read directly
175565    ** by the caller. They are valid from the time SegmentReaderNew() returns
175566    ** until SegmentReaderNext() returns something other than SQLITE_OK
175567    ** (i.e. SQLITE_DONE).
175568    */
175569    int nTerm;                      /* Number of bytes in current term */
175570    char *zTerm;                    /* Pointer to current term */
175571    int nTermAlloc;                 /* Allocated size of zTerm buffer */
175572    char *aDoclist;                 /* Pointer to doclist of current entry */
175573    int nDoclist;                   /* Size of doclist in current entry */
175574  
175575    /* The following variables are used by fts3SegReaderNextDocid() to iterate 
175576    ** through the current doclist (aDoclist/nDoclist).
175577    */
175578    char *pOffsetList;
175579    int nOffsetList;                /* For descending pending seg-readers only */
175580    sqlite3_int64 iDocid;
175581  };
175582  
175583  #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
175584  #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
175585  
175586  /*
175587  ** An instance of this structure is used to create a segment b-tree in the
175588  ** database. The internal details of this type are only accessed by the
175589  ** following functions:
175590  **
175591  **   fts3SegWriterAdd()
175592  **   fts3SegWriterFlush()
175593  **   fts3SegWriterFree()
175594  */
175595  struct SegmentWriter {
175596    SegmentNode *pTree;             /* Pointer to interior tree structure */
175597    sqlite3_int64 iFirst;           /* First slot in %_segments written */
175598    sqlite3_int64 iFree;            /* Next free slot in %_segments */
175599    char *zTerm;                    /* Pointer to previous term buffer */
175600    int nTerm;                      /* Number of bytes in zTerm */
175601    int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
175602    char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
175603    int nSize;                      /* Size of allocation at aData */
175604    int nData;                      /* Bytes of data in aData */
175605    char *aData;                    /* Pointer to block from malloc() */
175606    i64 nLeafData;                  /* Number of bytes of leaf data written */
175607  };
175608  
175609  /*
175610  ** Type SegmentNode is used by the following three functions to create
175611  ** the interior part of the segment b+-tree structures (everything except
175612  ** the leaf nodes). These functions and type are only ever used by code
175613  ** within the fts3SegWriterXXX() family of functions described above.
175614  **
175615  **   fts3NodeAddTerm()
175616  **   fts3NodeWrite()
175617  **   fts3NodeFree()
175618  **
175619  ** When a b+tree is written to the database (either as a result of a merge
175620  ** or the pending-terms table being flushed), leaves are written into the 
175621  ** database file as soon as they are completely populated. The interior of
175622  ** the tree is assembled in memory and written out only once all leaves have
175623  ** been populated and stored. This is Ok, as the b+-tree fanout is usually
175624  ** very large, meaning that the interior of the tree consumes relatively 
175625  ** little memory.
175626  */
175627  struct SegmentNode {
175628    SegmentNode *pParent;           /* Parent node (or NULL for root node) */
175629    SegmentNode *pRight;            /* Pointer to right-sibling */
175630    SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
175631    int nEntry;                     /* Number of terms written to node so far */
175632    char *zTerm;                    /* Pointer to previous term buffer */
175633    int nTerm;                      /* Number of bytes in zTerm */
175634    int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
175635    char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
175636    int nData;                      /* Bytes of valid data so far */
175637    char *aData;                    /* Node data */
175638  };
175639  
175640  /*
175641  ** Valid values for the second argument to fts3SqlStmt().
175642  */
175643  #define SQL_DELETE_CONTENT             0
175644  #define SQL_IS_EMPTY                   1
175645  #define SQL_DELETE_ALL_CONTENT         2 
175646  #define SQL_DELETE_ALL_SEGMENTS        3
175647  #define SQL_DELETE_ALL_SEGDIR          4
175648  #define SQL_DELETE_ALL_DOCSIZE         5
175649  #define SQL_DELETE_ALL_STAT            6
175650  #define SQL_SELECT_CONTENT_BY_ROWID    7
175651  #define SQL_NEXT_SEGMENT_INDEX         8
175652  #define SQL_INSERT_SEGMENTS            9
175653  #define SQL_NEXT_SEGMENTS_ID          10
175654  #define SQL_INSERT_SEGDIR             11
175655  #define SQL_SELECT_LEVEL              12
175656  #define SQL_SELECT_LEVEL_RANGE        13
175657  #define SQL_SELECT_LEVEL_COUNT        14
175658  #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
175659  #define SQL_DELETE_SEGDIR_LEVEL       16
175660  #define SQL_DELETE_SEGMENTS_RANGE     17
175661  #define SQL_CONTENT_INSERT            18
175662  #define SQL_DELETE_DOCSIZE            19
175663  #define SQL_REPLACE_DOCSIZE           20
175664  #define SQL_SELECT_DOCSIZE            21
175665  #define SQL_SELECT_STAT               22
175666  #define SQL_REPLACE_STAT              23
175667  
175668  #define SQL_SELECT_ALL_PREFIX_LEVEL   24
175669  #define SQL_DELETE_ALL_TERMS_SEGDIR   25
175670  #define SQL_DELETE_SEGDIR_RANGE       26
175671  #define SQL_SELECT_ALL_LANGID         27
175672  #define SQL_FIND_MERGE_LEVEL          28
175673  #define SQL_MAX_LEAF_NODE_ESTIMATE    29
175674  #define SQL_DELETE_SEGDIR_ENTRY       30
175675  #define SQL_SHIFT_SEGDIR_ENTRY        31
175676  #define SQL_SELECT_SEGDIR             32
175677  #define SQL_CHOMP_SEGDIR              33
175678  #define SQL_SEGMENT_IS_APPENDABLE     34
175679  #define SQL_SELECT_INDEXES            35
175680  #define SQL_SELECT_MXLEVEL            36
175681  
175682  #define SQL_SELECT_LEVEL_RANGE2       37
175683  #define SQL_UPDATE_LEVEL_IDX          38
175684  #define SQL_UPDATE_LEVEL              39
175685  
175686  /*
175687  ** This function is used to obtain an SQLite prepared statement handle
175688  ** for the statement identified by the second argument. If successful,
175689  ** *pp is set to the requested statement handle and SQLITE_OK returned.
175690  ** Otherwise, an SQLite error code is returned and *pp is set to 0.
175691  **
175692  ** If argument apVal is not NULL, then it must point to an array with
175693  ** at least as many entries as the requested statement has bound 
175694  ** parameters. The values are bound to the statements parameters before
175695  ** returning.
175696  */
175697  static int fts3SqlStmt(
175698    Fts3Table *p,                   /* Virtual table handle */
175699    int eStmt,                      /* One of the SQL_XXX constants above */
175700    sqlite3_stmt **pp,              /* OUT: Statement handle */
175701    sqlite3_value **apVal           /* Values to bind to statement */
175702  ){
175703    const char *azSql[] = {
175704  /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
175705  /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
175706  /* 2  */  "DELETE FROM %Q.'%q_content'",
175707  /* 3  */  "DELETE FROM %Q.'%q_segments'",
175708  /* 4  */  "DELETE FROM %Q.'%q_segdir'",
175709  /* 5  */  "DELETE FROM %Q.'%q_docsize'",
175710  /* 6  */  "DELETE FROM %Q.'%q_stat'",
175711  /* 7  */  "SELECT %s WHERE rowid=?",
175712  /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
175713  /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
175714  /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
175715  /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
175716  
175717            /* Return segments in order from oldest to newest.*/ 
175718  /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
175719              "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
175720  /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
175721              "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
175722              "ORDER BY level DESC, idx ASC",
175723  
175724  /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
175725  /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
175726  
175727  /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
175728  /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
175729  /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
175730  /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
175731  /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
175732  /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
175733  /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
175734  /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
175735  /* 24 */  "",
175736  /* 25 */  "",
175737  
175738  /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
175739  /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
175740  
175741  /* This statement is used to determine which level to read the input from
175742  ** when performing an incremental merge. It returns the absolute level number
175743  ** of the oldest level in the db that contains at least ? segments. Or,
175744  ** if no level in the FTS index contains more than ? segments, the statement
175745  ** returns zero rows.  */
175746  /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
175747           "  GROUP BY level HAVING cnt>=?"
175748           "  ORDER BY (level %% 1024) ASC LIMIT 1",
175749  
175750  /* Estimate the upper limit on the number of leaf nodes in a new segment
175751  ** created by merging the oldest :2 segments from absolute level :1. See 
175752  ** function sqlite3Fts3Incrmerge() for details.  */
175753  /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
175754           "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
175755  
175756  /* SQL_DELETE_SEGDIR_ENTRY
175757  **   Delete the %_segdir entry on absolute level :1 with index :2.  */
175758  /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
175759  
175760  /* SQL_SHIFT_SEGDIR_ENTRY
175761  **   Modify the idx value for the segment with idx=:3 on absolute level :2
175762  **   to :1.  */
175763  /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
175764  
175765  /* SQL_SELECT_SEGDIR
175766  **   Read a single entry from the %_segdir table. The entry from absolute 
175767  **   level :1 with index value :2.  */
175768  /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
175769              "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
175770  
175771  /* SQL_CHOMP_SEGDIR
175772  **   Update the start_block (:1) and root (:2) fields of the %_segdir
175773  **   entry located on absolute level :3 with index :4.  */
175774  /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
175775              "WHERE level = ? AND idx = ?",
175776  
175777  /* SQL_SEGMENT_IS_APPENDABLE
175778  **   Return a single row if the segment with end_block=? is appendable. Or
175779  **   no rows otherwise.  */
175780  /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
175781  
175782  /* SQL_SELECT_INDEXES
175783  **   Return the list of valid segment indexes for absolute level ?  */
175784  /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
175785  
175786  /* SQL_SELECT_MXLEVEL
175787  **   Return the largest relative level in the FTS index or indexes.  */
175788  /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
175789  
175790            /* Return segments in order from oldest to newest.*/ 
175791  /* 37 */  "SELECT level, idx, end_block "
175792              "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
175793              "ORDER BY level DESC, idx ASC",
175794  
175795            /* Update statements used while promoting segments */
175796  /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
175797              "WHERE level=? AND idx=?",
175798  /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
175799  
175800    };
175801    int rc = SQLITE_OK;
175802    sqlite3_stmt *pStmt;
175803  
175804    assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
175805    assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
175806    
175807    pStmt = p->aStmt[eStmt];
175808    if( !pStmt ){
175809      int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
175810      char *zSql;
175811      if( eStmt==SQL_CONTENT_INSERT ){
175812        zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
175813      }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
175814        f &= ~SQLITE_PREPARE_NO_VTAB;
175815        zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
175816      }else{
175817        zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
175818      }
175819      if( !zSql ){
175820        rc = SQLITE_NOMEM;
175821      }else{
175822        rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
175823        sqlite3_free(zSql);
175824        assert( rc==SQLITE_OK || pStmt==0 );
175825        p->aStmt[eStmt] = pStmt;
175826      }
175827    }
175828    if( apVal ){
175829      int i;
175830      int nParam = sqlite3_bind_parameter_count(pStmt);
175831      for(i=0; rc==SQLITE_OK && i<nParam; i++){
175832        rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
175833      }
175834    }
175835    *pp = pStmt;
175836    return rc;
175837  }
175838  
175839  
175840  static int fts3SelectDocsize(
175841    Fts3Table *pTab,                /* FTS3 table handle */
175842    sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
175843    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
175844  ){
175845    sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
175846    int rc;                         /* Return code */
175847  
175848    rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
175849    if( rc==SQLITE_OK ){
175850      sqlite3_bind_int64(pStmt, 1, iDocid);
175851      rc = sqlite3_step(pStmt);
175852      if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
175853        rc = sqlite3_reset(pStmt);
175854        if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
175855        pStmt = 0;
175856      }else{
175857        rc = SQLITE_OK;
175858      }
175859    }
175860  
175861    *ppStmt = pStmt;
175862    return rc;
175863  }
175864  
175865  SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
175866    Fts3Table *pTab,                /* Fts3 table handle */
175867    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
175868  ){
175869    sqlite3_stmt *pStmt = 0;
175870    int rc;
175871    rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
175872    if( rc==SQLITE_OK ){
175873      sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
175874      if( sqlite3_step(pStmt)!=SQLITE_ROW
175875       || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
175876      ){
175877        rc = sqlite3_reset(pStmt);
175878        if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
175879        pStmt = 0;
175880      }
175881    }
175882    *ppStmt = pStmt;
175883    return rc;
175884  }
175885  
175886  SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
175887    Fts3Table *pTab,                /* Fts3 table handle */
175888    sqlite3_int64 iDocid,           /* Docid to read size data for */
175889    sqlite3_stmt **ppStmt           /* OUT: Statement handle */
175890  ){
175891    return fts3SelectDocsize(pTab, iDocid, ppStmt);
175892  }
175893  
175894  /*
175895  ** Similar to fts3SqlStmt(). Except, after binding the parameters in
175896  ** array apVal[] to the SQL statement identified by eStmt, the statement
175897  ** is executed.
175898  **
175899  ** Returns SQLITE_OK if the statement is successfully executed, or an
175900  ** SQLite error code otherwise.
175901  */
175902  static void fts3SqlExec(
175903    int *pRC,                /* Result code */
175904    Fts3Table *p,            /* The FTS3 table */
175905    int eStmt,               /* Index of statement to evaluate */
175906    sqlite3_value **apVal    /* Parameters to bind */
175907  ){
175908    sqlite3_stmt *pStmt;
175909    int rc;
175910    if( *pRC ) return;
175911    rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
175912    if( rc==SQLITE_OK ){
175913      sqlite3_step(pStmt);
175914      rc = sqlite3_reset(pStmt);
175915    }
175916    *pRC = rc;
175917  }
175918  
175919  
175920  /*
175921  ** This function ensures that the caller has obtained an exclusive 
175922  ** shared-cache table-lock on the %_segdir table. This is required before 
175923  ** writing data to the fts3 table. If this lock is not acquired first, then
175924  ** the caller may end up attempting to take this lock as part of committing
175925  ** a transaction, causing SQLite to return SQLITE_LOCKED or 
175926  ** LOCKED_SHAREDCACHEto a COMMIT command.
175927  **
175928  ** It is best to avoid this because if FTS3 returns any error when 
175929  ** committing a transaction, the whole transaction will be rolled back. 
175930  ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
175931  ** It can still happen if the user locks the underlying tables directly 
175932  ** instead of accessing them via FTS.
175933  */
175934  static int fts3Writelock(Fts3Table *p){
175935    int rc = SQLITE_OK;
175936    
175937    if( p->nPendingData==0 ){
175938      sqlite3_stmt *pStmt;
175939      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
175940      if( rc==SQLITE_OK ){
175941        sqlite3_bind_null(pStmt, 1);
175942        sqlite3_step(pStmt);
175943        rc = sqlite3_reset(pStmt);
175944      }
175945    }
175946  
175947    return rc;
175948  }
175949  
175950  /*
175951  ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
175952  ** Within each language id, a separate index is maintained to store the
175953  ** document terms, and each configured prefix size (configured the FTS 
175954  ** "prefix=" option). And each index consists of multiple levels ("relative
175955  ** levels").
175956  **
175957  ** All three of these values (the language id, the specific index and the
175958  ** level within the index) are encoded in 64-bit integer values stored
175959  ** in the %_segdir table on disk. This function is used to convert three
175960  ** separate component values into the single 64-bit integer value that
175961  ** can be used to query the %_segdir table.
175962  **
175963  ** Specifically, each language-id/index combination is allocated 1024 
175964  ** 64-bit integer level values ("absolute levels"). The main terms index
175965  ** for language-id 0 is allocate values 0-1023. The first prefix index
175966  ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
175967  ** Language 1 indexes are allocated immediately following language 0.
175968  **
175969  ** So, for a system with nPrefix prefix indexes configured, the block of
175970  ** absolute levels that corresponds to language-id iLangid and index 
175971  ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
175972  */
175973  static sqlite3_int64 getAbsoluteLevel(
175974    Fts3Table *p,                   /* FTS3 table handle */
175975    int iLangid,                    /* Language id */
175976    int iIndex,                     /* Index in p->aIndex[] */
175977    int iLevel                      /* Level of segments */
175978  ){
175979    sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
175980    assert_fts3_nc( iLangid>=0 );
175981    assert( p->nIndex>0 );
175982    assert( iIndex>=0 && iIndex<p->nIndex );
175983  
175984    iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
175985    return iBase + iLevel;
175986  }
175987  
175988  /*
175989  ** Set *ppStmt to a statement handle that may be used to iterate through
175990  ** all rows in the %_segdir table, from oldest to newest. If successful,
175991  ** return SQLITE_OK. If an error occurs while preparing the statement, 
175992  ** return an SQLite error code.
175993  **
175994  ** There is only ever one instance of this SQL statement compiled for
175995  ** each FTS3 table.
175996  **
175997  ** The statement returns the following columns from the %_segdir table:
175998  **
175999  **   0: idx
176000  **   1: start_block
176001  **   2: leaves_end_block
176002  **   3: end_block
176003  **   4: root
176004  */
176005  SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
176006    Fts3Table *p,                   /* FTS3 table */
176007    int iLangid,                    /* Language being queried */
176008    int iIndex,                     /* Index for p->aIndex[] */
176009    int iLevel,                     /* Level to select (relative level) */
176010    sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
176011  ){
176012    int rc;
176013    sqlite3_stmt *pStmt = 0;
176014  
176015    assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
176016    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
176017    assert( iIndex>=0 && iIndex<p->nIndex );
176018  
176019    if( iLevel<0 ){
176020      /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
176021      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
176022      if( rc==SQLITE_OK ){ 
176023        sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
176024        sqlite3_bind_int64(pStmt, 2, 
176025            getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
176026        );
176027      }
176028    }else{
176029      /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
176030      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
176031      if( rc==SQLITE_OK ){ 
176032        sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
176033      }
176034    }
176035    *ppStmt = pStmt;
176036    return rc;
176037  }
176038  
176039  
176040  /*
176041  ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
176042  ** if successful, or an SQLite error code otherwise.
176043  **
176044  ** This function also serves to allocate the PendingList structure itself.
176045  ** For example, to create a new PendingList structure containing two
176046  ** varints:
176047  **
176048  **   PendingList *p = 0;
176049  **   fts3PendingListAppendVarint(&p, 1);
176050  **   fts3PendingListAppendVarint(&p, 2);
176051  */
176052  static int fts3PendingListAppendVarint(
176053    PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
176054    sqlite3_int64 i                 /* Value to append to data */
176055  ){
176056    PendingList *p = *pp;
176057  
176058    /* Allocate or grow the PendingList as required. */
176059    if( !p ){
176060      p = sqlite3_malloc(sizeof(*p) + 100);
176061      if( !p ){
176062        return SQLITE_NOMEM;
176063      }
176064      p->nSpace = 100;
176065      p->aData = (char *)&p[1];
176066      p->nData = 0;
176067    }
176068    else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
176069      int nNew = p->nSpace * 2;
176070      p = sqlite3_realloc(p, sizeof(*p) + nNew);
176071      if( !p ){
176072        sqlite3_free(*pp);
176073        *pp = 0;
176074        return SQLITE_NOMEM;
176075      }
176076      p->nSpace = nNew;
176077      p->aData = (char *)&p[1];
176078    }
176079  
176080    /* Append the new serialized varint to the end of the list. */
176081    p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
176082    p->aData[p->nData] = '\0';
176083    *pp = p;
176084    return SQLITE_OK;
176085  }
176086  
176087  /*
176088  ** Add a docid/column/position entry to a PendingList structure. Non-zero
176089  ** is returned if the structure is sqlite3_realloced as part of adding
176090  ** the entry. Otherwise, zero.
176091  **
176092  ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
176093  ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
176094  ** it is set to SQLITE_OK.
176095  */
176096  static int fts3PendingListAppend(
176097    PendingList **pp,               /* IN/OUT: PendingList structure */
176098    sqlite3_int64 iDocid,           /* Docid for entry to add */
176099    sqlite3_int64 iCol,             /* Column for entry to add */
176100    sqlite3_int64 iPos,             /* Position of term for entry to add */
176101    int *pRc                        /* OUT: Return code */
176102  ){
176103    PendingList *p = *pp;
176104    int rc = SQLITE_OK;
176105  
176106    assert( !p || p->iLastDocid<=iDocid );
176107  
176108    if( !p || p->iLastDocid!=iDocid ){
176109      sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
176110      if( p ){
176111        assert( p->nData<p->nSpace );
176112        assert( p->aData[p->nData]==0 );
176113        p->nData++;
176114      }
176115      if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
176116        goto pendinglistappend_out;
176117      }
176118      p->iLastCol = -1;
176119      p->iLastPos = 0;
176120      p->iLastDocid = iDocid;
176121    }
176122    if( iCol>0 && p->iLastCol!=iCol ){
176123      if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
176124       || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
176125      ){
176126        goto pendinglistappend_out;
176127      }
176128      p->iLastCol = iCol;
176129      p->iLastPos = 0;
176130    }
176131    if( iCol>=0 ){
176132      assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
176133      rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
176134      if( rc==SQLITE_OK ){
176135        p->iLastPos = iPos;
176136      }
176137    }
176138  
176139   pendinglistappend_out:
176140    *pRc = rc;
176141    if( p!=*pp ){
176142      *pp = p;
176143      return 1;
176144    }
176145    return 0;
176146  }
176147  
176148  /*
176149  ** Free a PendingList object allocated by fts3PendingListAppend().
176150  */
176151  static void fts3PendingListDelete(PendingList *pList){
176152    sqlite3_free(pList);
176153  }
176154  
176155  /*
176156  ** Add an entry to one of the pending-terms hash tables.
176157  */
176158  static int fts3PendingTermsAddOne(
176159    Fts3Table *p,
176160    int iCol,
176161    int iPos,
176162    Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
176163    const char *zToken,
176164    int nToken
176165  ){
176166    PendingList *pList;
176167    int rc = SQLITE_OK;
176168  
176169    pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
176170    if( pList ){
176171      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
176172    }
176173    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
176174      if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
176175        /* Malloc failed while inserting the new entry. This can only 
176176        ** happen if there was no previous entry for this token.
176177        */
176178        assert( 0==fts3HashFind(pHash, zToken, nToken) );
176179        sqlite3_free(pList);
176180        rc = SQLITE_NOMEM;
176181      }
176182    }
176183    if( rc==SQLITE_OK ){
176184      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
176185    }
176186    return rc;
176187  }
176188  
176189  /*
176190  ** Tokenize the nul-terminated string zText and add all tokens to the
176191  ** pending-terms hash-table. The docid used is that currently stored in
176192  ** p->iPrevDocid, and the column is specified by argument iCol.
176193  **
176194  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
176195  */
176196  static int fts3PendingTermsAdd(
176197    Fts3Table *p,                   /* Table into which text will be inserted */
176198    int iLangid,                    /* Language id to use */
176199    const char *zText,              /* Text of document to be inserted */
176200    int iCol,                       /* Column into which text is being inserted */
176201    u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
176202  ){
176203    int rc;
176204    int iStart = 0;
176205    int iEnd = 0;
176206    int iPos = 0;
176207    int nWord = 0;
176208  
176209    char const *zToken;
176210    int nToken = 0;
176211  
176212    sqlite3_tokenizer *pTokenizer = p->pTokenizer;
176213    sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
176214    sqlite3_tokenizer_cursor *pCsr;
176215    int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
176216        const char**,int*,int*,int*,int*);
176217  
176218    assert( pTokenizer && pModule );
176219  
176220    /* If the user has inserted a NULL value, this function may be called with
176221    ** zText==0. In this case, add zero token entries to the hash table and 
176222    ** return early. */
176223    if( zText==0 ){
176224      *pnWord = 0;
176225      return SQLITE_OK;
176226    }
176227  
176228    rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
176229    if( rc!=SQLITE_OK ){
176230      return rc;
176231    }
176232  
176233    xNext = pModule->xNext;
176234    while( SQLITE_OK==rc
176235        && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
176236    ){
176237      int i;
176238      if( iPos>=nWord ) nWord = iPos+1;
176239  
176240      /* Positions cannot be negative; we use -1 as a terminator internally.
176241      ** Tokens must have a non-zero length.
176242      */
176243      if( iPos<0 || !zToken || nToken<=0 ){
176244        rc = SQLITE_ERROR;
176245        break;
176246      }
176247  
176248      /* Add the term to the terms index */
176249      rc = fts3PendingTermsAddOne(
176250          p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
176251      );
176252      
176253      /* Add the term to each of the prefix indexes that it is not too 
176254      ** short for. */
176255      for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
176256        struct Fts3Index *pIndex = &p->aIndex[i];
176257        if( nToken<pIndex->nPrefix ) continue;
176258        rc = fts3PendingTermsAddOne(
176259            p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
176260        );
176261      }
176262    }
176263  
176264    pModule->xClose(pCsr);
176265    *pnWord += nWord;
176266    return (rc==SQLITE_DONE ? SQLITE_OK : rc);
176267  }
176268  
176269  /* 
176270  ** Calling this function indicates that subsequent calls to 
176271  ** fts3PendingTermsAdd() are to add term/position-list pairs for the
176272  ** contents of the document with docid iDocid.
176273  */
176274  static int fts3PendingTermsDocid(
176275    Fts3Table *p,                   /* Full-text table handle */
176276    int bDelete,                    /* True if this op is a delete */
176277    int iLangid,                    /* Language id of row being written */
176278    sqlite_int64 iDocid             /* Docid of row being written */
176279  ){
176280    assert( iLangid>=0 );
176281    assert( bDelete==1 || bDelete==0 );
176282  
176283    /* TODO(shess) Explore whether partially flushing the buffer on
176284    ** forced-flush would provide better performance.  I suspect that if
176285    ** we ordered the doclists by size and flushed the largest until the
176286    ** buffer was half empty, that would let the less frequent terms
176287    ** generate longer doclists.
176288    */
176289    if( iDocid<p->iPrevDocid 
176290     || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
176291     || p->iPrevLangid!=iLangid
176292     || p->nPendingData>p->nMaxPendingData 
176293    ){
176294      int rc = sqlite3Fts3PendingTermsFlush(p);
176295      if( rc!=SQLITE_OK ) return rc;
176296    }
176297    p->iPrevDocid = iDocid;
176298    p->iPrevLangid = iLangid;
176299    p->bPrevDelete = bDelete;
176300    return SQLITE_OK;
176301  }
176302  
176303  /*
176304  ** Discard the contents of the pending-terms hash tables. 
176305  */
176306  SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
176307    int i;
176308    for(i=0; i<p->nIndex; i++){
176309      Fts3HashElem *pElem;
176310      Fts3Hash *pHash = &p->aIndex[i].hPending;
176311      for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
176312        PendingList *pList = (PendingList *)fts3HashData(pElem);
176313        fts3PendingListDelete(pList);
176314      }
176315      fts3HashClear(pHash);
176316    }
176317    p->nPendingData = 0;
176318  }
176319  
176320  /*
176321  ** This function is called by the xUpdate() method as part of an INSERT
176322  ** operation. It adds entries for each term in the new record to the
176323  ** pendingTerms hash table.
176324  **
176325  ** Argument apVal is the same as the similarly named argument passed to
176326  ** fts3InsertData(). Parameter iDocid is the docid of the new row.
176327  */
176328  static int fts3InsertTerms(
176329    Fts3Table *p, 
176330    int iLangid, 
176331    sqlite3_value **apVal, 
176332    u32 *aSz
176333  ){
176334    int i;                          /* Iterator variable */
176335    for(i=2; i<p->nColumn+2; i++){
176336      int iCol = i-2;
176337      if( p->abNotindexed[iCol]==0 ){
176338        const char *zText = (const char *)sqlite3_value_text(apVal[i]);
176339        int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
176340        if( rc!=SQLITE_OK ){
176341          return rc;
176342        }
176343        aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
176344      }
176345    }
176346    return SQLITE_OK;
176347  }
176348  
176349  /*
176350  ** This function is called by the xUpdate() method for an INSERT operation.
176351  ** The apVal parameter is passed a copy of the apVal argument passed by
176352  ** SQLite to the xUpdate() method. i.e:
176353  **
176354  **   apVal[0]                Not used for INSERT.
176355  **   apVal[1]                rowid
176356  **   apVal[2]                Left-most user-defined column
176357  **   ...
176358  **   apVal[p->nColumn+1]     Right-most user-defined column
176359  **   apVal[p->nColumn+2]     Hidden column with same name as table
176360  **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
176361  **   apVal[p->nColumn+4]     Hidden languageid column
176362  */
176363  static int fts3InsertData(
176364    Fts3Table *p,                   /* Full-text table */
176365    sqlite3_value **apVal,          /* Array of values to insert */
176366    sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
176367  ){
176368    int rc;                         /* Return code */
176369    sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
176370  
176371    if( p->zContentTbl ){
176372      sqlite3_value *pRowid = apVal[p->nColumn+3];
176373      if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
176374        pRowid = apVal[1];
176375      }
176376      if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
176377        return SQLITE_CONSTRAINT;
176378      }
176379      *piDocid = sqlite3_value_int64(pRowid);
176380      return SQLITE_OK;
176381    }
176382  
176383    /* Locate the statement handle used to insert data into the %_content
176384    ** table. The SQL for this statement is:
176385    **
176386    **   INSERT INTO %_content VALUES(?, ?, ?, ...)
176387    **
176388    ** The statement features N '?' variables, where N is the number of user
176389    ** defined columns in the FTS3 table, plus one for the docid field.
176390    */
176391    rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
176392    if( rc==SQLITE_OK && p->zLanguageid ){
176393      rc = sqlite3_bind_int(
176394          pContentInsert, p->nColumn+2, 
176395          sqlite3_value_int(apVal[p->nColumn+4])
176396      );
176397    }
176398    if( rc!=SQLITE_OK ) return rc;
176399  
176400    /* There is a quirk here. The users INSERT statement may have specified
176401    ** a value for the "rowid" field, for the "docid" field, or for both.
176402    ** Which is a problem, since "rowid" and "docid" are aliases for the
176403    ** same value. For example:
176404    **
176405    **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
176406    **
176407    ** In FTS3, this is an error. It is an error to specify non-NULL values
176408    ** for both docid and some other rowid alias.
176409    */
176410    if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
176411      if( SQLITE_NULL==sqlite3_value_type(apVal[0])
176412       && SQLITE_NULL!=sqlite3_value_type(apVal[1])
176413      ){
176414        /* A rowid/docid conflict. */
176415        return SQLITE_ERROR;
176416      }
176417      rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
176418      if( rc!=SQLITE_OK ) return rc;
176419    }
176420  
176421    /* Execute the statement to insert the record. Set *piDocid to the 
176422    ** new docid value. 
176423    */
176424    sqlite3_step(pContentInsert);
176425    rc = sqlite3_reset(pContentInsert);
176426  
176427    *piDocid = sqlite3_last_insert_rowid(p->db);
176428    return rc;
176429  }
176430  
176431  
176432  
176433  /*
176434  ** Remove all data from the FTS3 table. Clear the hash table containing
176435  ** pending terms.
176436  */
176437  static int fts3DeleteAll(Fts3Table *p, int bContent){
176438    int rc = SQLITE_OK;             /* Return code */
176439  
176440    /* Discard the contents of the pending-terms hash table. */
176441    sqlite3Fts3PendingTermsClear(p);
176442  
176443    /* Delete everything from the shadow tables. Except, leave %_content as
176444    ** is if bContent is false.  */
176445    assert( p->zContentTbl==0 || bContent==0 );
176446    if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
176447    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
176448    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
176449    if( p->bHasDocsize ){
176450      fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
176451    }
176452    if( p->bHasStat ){
176453      fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
176454    }
176455    return rc;
176456  }
176457  
176458  /*
176459  **
176460  */
176461  static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
176462    int iLangid = 0;
176463    if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
176464    return iLangid;
176465  }
176466  
176467  /*
176468  ** The first element in the apVal[] array is assumed to contain the docid
176469  ** (an integer) of a row about to be deleted. Remove all terms from the
176470  ** full-text index.
176471  */
176472  static void fts3DeleteTerms( 
176473    int *pRC,               /* Result code */
176474    Fts3Table *p,           /* The FTS table to delete from */
176475    sqlite3_value *pRowid,  /* The docid to be deleted */
176476    u32 *aSz,               /* Sizes of deleted document written here */
176477    int *pbFound            /* OUT: Set to true if row really does exist */
176478  ){
176479    int rc;
176480    sqlite3_stmt *pSelect;
176481  
176482    assert( *pbFound==0 );
176483    if( *pRC ) return;
176484    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
176485    if( rc==SQLITE_OK ){
176486      if( SQLITE_ROW==sqlite3_step(pSelect) ){
176487        int i;
176488        int iLangid = langidFromSelect(p, pSelect);
176489        i64 iDocid = sqlite3_column_int64(pSelect, 0);
176490        rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
176491        for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
176492          int iCol = i-1;
176493          if( p->abNotindexed[iCol]==0 ){
176494            const char *zText = (const char *)sqlite3_column_text(pSelect, i);
176495            rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
176496            aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
176497          }
176498        }
176499        if( rc!=SQLITE_OK ){
176500          sqlite3_reset(pSelect);
176501          *pRC = rc;
176502          return;
176503        }
176504        *pbFound = 1;
176505      }
176506      rc = sqlite3_reset(pSelect);
176507    }else{
176508      sqlite3_reset(pSelect);
176509    }
176510    *pRC = rc;
176511  }
176512  
176513  /*
176514  ** Forward declaration to account for the circular dependency between
176515  ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
176516  */
176517  static int fts3SegmentMerge(Fts3Table *, int, int, int);
176518  
176519  /* 
176520  ** This function allocates a new level iLevel index in the segdir table.
176521  ** Usually, indexes are allocated within a level sequentially starting
176522  ** with 0, so the allocated index is one greater than the value returned
176523  ** by:
176524  **
176525  **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
176526  **
176527  ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
176528  ** level, they are merged into a single level (iLevel+1) segment and the 
176529  ** allocated index is 0.
176530  **
176531  ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
176532  ** returned. Otherwise, an SQLite error code is returned.
176533  */
176534  static int fts3AllocateSegdirIdx(
176535    Fts3Table *p, 
176536    int iLangid,                    /* Language id */
176537    int iIndex,                     /* Index for p->aIndex */
176538    int iLevel, 
176539    int *piIdx
176540  ){
176541    int rc;                         /* Return Code */
176542    sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
176543    int iNext = 0;                  /* Result of query pNextIdx */
176544  
176545    assert( iLangid>=0 );
176546    assert( p->nIndex>=1 );
176547  
176548    /* Set variable iNext to the next available segdir index at level iLevel. */
176549    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
176550    if( rc==SQLITE_OK ){
176551      sqlite3_bind_int64(
176552          pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
176553      );
176554      if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
176555        iNext = sqlite3_column_int(pNextIdx, 0);
176556      }
176557      rc = sqlite3_reset(pNextIdx);
176558    }
176559  
176560    if( rc==SQLITE_OK ){
176561      /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
176562      ** full, merge all segments in level iLevel into a single iLevel+1
176563      ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
176564      ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
176565      */
176566      if( iNext>=FTS3_MERGE_COUNT ){
176567        fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
176568        rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
176569        *piIdx = 0;
176570      }else{
176571        *piIdx = iNext;
176572      }
176573    }
176574  
176575    return rc;
176576  }
176577  
176578  /*
176579  ** The %_segments table is declared as follows:
176580  **
176581  **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
176582  **
176583  ** This function reads data from a single row of the %_segments table. The
176584  ** specific row is identified by the iBlockid parameter. If paBlob is not
176585  ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
176586  ** with the contents of the blob stored in the "block" column of the 
176587  ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
176588  ** to the size of the blob in bytes before returning.
176589  **
176590  ** If an error occurs, or the table does not contain the specified row,
176591  ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
176592  ** paBlob is non-NULL, then it is the responsibility of the caller to
176593  ** eventually free the returned buffer.
176594  **
176595  ** This function may leave an open sqlite3_blob* handle in the
176596  ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
176597  ** to this function. The handle may be closed by calling the
176598  ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
176599  ** performance improvement, but the blob handle should always be closed
176600  ** before control is returned to the user (to prevent a lock being held
176601  ** on the database file for longer than necessary). Thus, any virtual table
176602  ** method (xFilter etc.) that may directly or indirectly call this function
176603  ** must call sqlite3Fts3SegmentsClose() before returning.
176604  */
176605  SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
176606    Fts3Table *p,                   /* FTS3 table handle */
176607    sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
176608    char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
176609    int *pnBlob,                    /* OUT: Size of blob data */
176610    int *pnLoad                     /* OUT: Bytes actually loaded */
176611  ){
176612    int rc;                         /* Return code */
176613  
176614    /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
176615    assert( pnBlob );
176616  
176617    if( p->pSegments ){
176618      rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
176619    }else{
176620      if( 0==p->zSegmentsTbl ){
176621        p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
176622        if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
176623      }
176624      rc = sqlite3_blob_open(
176625         p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
176626      );
176627    }
176628  
176629    if( rc==SQLITE_OK ){
176630      int nByte = sqlite3_blob_bytes(p->pSegments);
176631      *pnBlob = nByte;
176632      if( paBlob ){
176633        char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
176634        if( !aByte ){
176635          rc = SQLITE_NOMEM;
176636        }else{
176637          if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
176638            nByte = FTS3_NODE_CHUNKSIZE;
176639            *pnLoad = nByte;
176640          }
176641          rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
176642          memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
176643          if( rc!=SQLITE_OK ){
176644            sqlite3_free(aByte);
176645            aByte = 0;
176646          }
176647        }
176648        *paBlob = aByte;
176649      }
176650    }
176651  
176652    return rc;
176653  }
176654  
176655  /*
176656  ** Close the blob handle at p->pSegments, if it is open. See comments above
176657  ** the sqlite3Fts3ReadBlock() function for details.
176658  */
176659  SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
176660    sqlite3_blob_close(p->pSegments);
176661    p->pSegments = 0;
176662  }
176663      
176664  static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
176665    int nRead;                      /* Number of bytes to read */
176666    int rc;                         /* Return code */
176667  
176668    nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
176669    rc = sqlite3_blob_read(
176670        pReader->pBlob, 
176671        &pReader->aNode[pReader->nPopulate],
176672        nRead,
176673        pReader->nPopulate
176674    );
176675  
176676    if( rc==SQLITE_OK ){
176677      pReader->nPopulate += nRead;
176678      memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
176679      if( pReader->nPopulate==pReader->nNode ){
176680        sqlite3_blob_close(pReader->pBlob);
176681        pReader->pBlob = 0;
176682        pReader->nPopulate = 0;
176683      }
176684    }
176685    return rc;
176686  }
176687  
176688  static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
176689    int rc = SQLITE_OK;
176690    assert( !pReader->pBlob 
176691         || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
176692    );
176693    while( pReader->pBlob && rc==SQLITE_OK 
176694       &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
176695    ){
176696      rc = fts3SegReaderIncrRead(pReader);
176697    }
176698    return rc;
176699  }
176700  
176701  /*
176702  ** Set an Fts3SegReader cursor to point at EOF.
176703  */
176704  static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
176705    if( !fts3SegReaderIsRootOnly(pSeg) ){
176706      sqlite3_free(pSeg->aNode);
176707      sqlite3_blob_close(pSeg->pBlob);
176708      pSeg->pBlob = 0;
176709    }
176710    pSeg->aNode = 0;
176711  }
176712  
176713  /*
176714  ** Move the iterator passed as the first argument to the next term in the
176715  ** segment. If successful, SQLITE_OK is returned. If there is no next term,
176716  ** SQLITE_DONE. Otherwise, an SQLite error code.
176717  */
176718  static int fts3SegReaderNext(
176719    Fts3Table *p, 
176720    Fts3SegReader *pReader,
176721    int bIncr
176722  ){
176723    int rc;                         /* Return code of various sub-routines */
176724    char *pNext;                    /* Cursor variable */
176725    int nPrefix;                    /* Number of bytes in term prefix */
176726    int nSuffix;                    /* Number of bytes in term suffix */
176727  
176728    if( !pReader->aDoclist ){
176729      pNext = pReader->aNode;
176730    }else{
176731      pNext = &pReader->aDoclist[pReader->nDoclist];
176732    }
176733  
176734    if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
176735  
176736      if( fts3SegReaderIsPending(pReader) ){
176737        Fts3HashElem *pElem = *(pReader->ppNextElem);
176738        sqlite3_free(pReader->aNode);
176739        pReader->aNode = 0;
176740        if( pElem ){
176741          char *aCopy;
176742          PendingList *pList = (PendingList *)fts3HashData(pElem);
176743          int nCopy = pList->nData+1;
176744          pReader->zTerm = (char *)fts3HashKey(pElem);
176745          pReader->nTerm = fts3HashKeysize(pElem);
176746          aCopy = (char*)sqlite3_malloc(nCopy);
176747          if( !aCopy ) return SQLITE_NOMEM;
176748          memcpy(aCopy, pList->aData, nCopy);
176749          pReader->nNode = pReader->nDoclist = nCopy;
176750          pReader->aNode = pReader->aDoclist = aCopy;
176751          pReader->ppNextElem++;
176752          assert( pReader->aNode );
176753        }
176754        return SQLITE_OK;
176755      }
176756  
176757      fts3SegReaderSetEof(pReader);
176758  
176759      /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
176760      ** blocks have already been traversed.  */
176761      assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
176762      if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
176763        return SQLITE_OK;
176764      }
176765  
176766      rc = sqlite3Fts3ReadBlock(
176767          p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
176768          (bIncr ? &pReader->nPopulate : 0)
176769      );
176770      if( rc!=SQLITE_OK ) return rc;
176771      assert( pReader->pBlob==0 );
176772      if( bIncr && pReader->nPopulate<pReader->nNode ){
176773        pReader->pBlob = p->pSegments;
176774        p->pSegments = 0;
176775      }
176776      pNext = pReader->aNode;
176777    }
176778  
176779    assert( !fts3SegReaderIsPending(pReader) );
176780  
176781    rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
176782    if( rc!=SQLITE_OK ) return rc;
176783    
176784    /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
176785    ** safe (no risk of overread) even if the node data is corrupted. */
176786    pNext += fts3GetVarint32(pNext, &nPrefix);
176787    pNext += fts3GetVarint32(pNext, &nSuffix);
176788    if( nSuffix<=0 
176789     || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
176790     || nPrefix>pReader->nTermAlloc
176791    ){
176792      return FTS_CORRUPT_VTAB;
176793    }
176794  
176795    /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
176796    ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
176797    ** overflow - hence the (i64) casts.  */
176798    if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
176799      i64 nNew = ((i64)nPrefix+nSuffix)*2;
176800      char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
176801      if( !zNew ){
176802        return SQLITE_NOMEM;
176803      }
176804      pReader->zTerm = zNew;
176805      pReader->nTermAlloc = nNew;
176806    }
176807  
176808    rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
176809    if( rc!=SQLITE_OK ) return rc;
176810  
176811    memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
176812    pReader->nTerm = nPrefix+nSuffix;
176813    pNext += nSuffix;
176814    pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
176815    pReader->aDoclist = pNext;
176816    pReader->pOffsetList = 0;
176817  
176818    /* Check that the doclist does not appear to extend past the end of the
176819    ** b-tree node. And that the final byte of the doclist is 0x00. If either 
176820    ** of these statements is untrue, then the data structure is corrupt.
176821    */
176822    if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
176823     || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
176824    ){
176825      return FTS_CORRUPT_VTAB;
176826    }
176827    return SQLITE_OK;
176828  }
176829  
176830  /*
176831  ** Set the SegReader to point to the first docid in the doclist associated
176832  ** with the current term.
176833  */
176834  static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
176835    int rc = SQLITE_OK;
176836    assert( pReader->aDoclist );
176837    assert( !pReader->pOffsetList );
176838    if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
176839      u8 bEof = 0;
176840      pReader->iDocid = 0;
176841      pReader->nOffsetList = 0;
176842      sqlite3Fts3DoclistPrev(0,
176843          pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
176844          &pReader->iDocid, &pReader->nOffsetList, &bEof
176845      );
176846    }else{
176847      rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
176848      if( rc==SQLITE_OK ){
176849        int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
176850        pReader->pOffsetList = &pReader->aDoclist[n];
176851      }
176852    }
176853    return rc;
176854  }
176855  
176856  /*
176857  ** Advance the SegReader to point to the next docid in the doclist
176858  ** associated with the current term.
176859  ** 
176860  ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
176861  ** *ppOffsetList is set to point to the first column-offset list
176862  ** in the doclist entry (i.e. immediately past the docid varint).
176863  ** *pnOffsetList is set to the length of the set of column-offset
176864  ** lists, not including the nul-terminator byte. For example:
176865  */
176866  static int fts3SegReaderNextDocid(
176867    Fts3Table *pTab,
176868    Fts3SegReader *pReader,         /* Reader to advance to next docid */
176869    char **ppOffsetList,            /* OUT: Pointer to current position-list */
176870    int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
176871  ){
176872    int rc = SQLITE_OK;
176873    char *p = pReader->pOffsetList;
176874    char c = 0;
176875  
176876    assert( p );
176877  
176878    if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
176879      /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
176880      ** Pending-terms doclists are always built up in ascending order, so
176881      ** we have to iterate through them backwards here. */
176882      u8 bEof = 0;
176883      if( ppOffsetList ){
176884        *ppOffsetList = pReader->pOffsetList;
176885        *pnOffsetList = pReader->nOffsetList - 1;
176886      }
176887      sqlite3Fts3DoclistPrev(0,
176888          pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
176889          &pReader->nOffsetList, &bEof
176890      );
176891      if( bEof ){
176892        pReader->pOffsetList = 0;
176893      }else{
176894        pReader->pOffsetList = p;
176895      }
176896    }else{
176897      char *pEnd = &pReader->aDoclist[pReader->nDoclist];
176898  
176899      /* Pointer p currently points at the first byte of an offset list. The
176900      ** following block advances it to point one byte past the end of
176901      ** the same offset list. */
176902      while( 1 ){
176903    
176904        /* The following line of code (and the "p++" below the while() loop) is
176905        ** normally all that is required to move pointer p to the desired 
176906        ** position. The exception is if this node is being loaded from disk
176907        ** incrementally and pointer "p" now points to the first byte past
176908        ** the populated part of pReader->aNode[].
176909        */
176910        while( *p | c ) c = *p++ & 0x80;
176911        assert( *p==0 );
176912    
176913        if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
176914        rc = fts3SegReaderIncrRead(pReader);
176915        if( rc!=SQLITE_OK ) return rc;
176916      }
176917      p++;
176918    
176919      /* If required, populate the output variables with a pointer to and the
176920      ** size of the previous offset-list.
176921      */
176922      if( ppOffsetList ){
176923        *ppOffsetList = pReader->pOffsetList;
176924        *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
176925      }
176926  
176927      /* List may have been edited in place by fts3EvalNearTrim() */
176928      while( p<pEnd && *p==0 ) p++;
176929    
176930      /* If there are no more entries in the doclist, set pOffsetList to
176931      ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
176932      ** Fts3SegReader.pOffsetList to point to the next offset list before
176933      ** returning.
176934      */
176935      if( p>=pEnd ){
176936        pReader->pOffsetList = 0;
176937      }else{
176938        rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
176939        if( rc==SQLITE_OK ){
176940          sqlite3_int64 iDelta;
176941          pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
176942          if( pTab->bDescIdx ){
176943            pReader->iDocid -= iDelta;
176944          }else{
176945            pReader->iDocid += iDelta;
176946          }
176947        }
176948      }
176949    }
176950  
176951    return SQLITE_OK;
176952  }
176953  
176954  
176955  SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
176956    Fts3Cursor *pCsr, 
176957    Fts3MultiSegReader *pMsr,
176958    int *pnOvfl
176959  ){
176960    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
176961    int nOvfl = 0;
176962    int ii;
176963    int rc = SQLITE_OK;
176964    int pgsz = p->nPgsz;
176965  
176966    assert( p->bFts4 );
176967    assert( pgsz>0 );
176968  
176969    for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
176970      Fts3SegReader *pReader = pMsr->apSegment[ii];
176971      if( !fts3SegReaderIsPending(pReader) 
176972       && !fts3SegReaderIsRootOnly(pReader) 
176973      ){
176974        sqlite3_int64 jj;
176975        for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
176976          int nBlob;
176977          rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
176978          if( rc!=SQLITE_OK ) break;
176979          if( (nBlob+35)>pgsz ){
176980            nOvfl += (nBlob + 34)/pgsz;
176981          }
176982        }
176983      }
176984    }
176985    *pnOvfl = nOvfl;
176986    return rc;
176987  }
176988  
176989  /*
176990  ** Free all allocations associated with the iterator passed as the 
176991  ** second argument.
176992  */
176993  SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
176994    if( pReader ){
176995      if( !fts3SegReaderIsPending(pReader) ){
176996        sqlite3_free(pReader->zTerm);
176997      }
176998      if( !fts3SegReaderIsRootOnly(pReader) ){
176999        sqlite3_free(pReader->aNode);
177000      }
177001      sqlite3_blob_close(pReader->pBlob);
177002    }
177003    sqlite3_free(pReader);
177004  }
177005  
177006  /*
177007  ** Allocate a new SegReader object.
177008  */
177009  SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
177010    int iAge,                       /* Segment "age". */
177011    int bLookup,                    /* True for a lookup only */
177012    sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
177013    sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
177014    sqlite3_int64 iEndBlock,        /* Final block of segment */
177015    const char *zRoot,              /* Buffer containing root node */
177016    int nRoot,                      /* Size of buffer containing root node */
177017    Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
177018  ){
177019    Fts3SegReader *pReader;         /* Newly allocated SegReader object */
177020    int nExtra = 0;                 /* Bytes to allocate segment root node */
177021  
177022    assert( zRoot!=0 || nRoot==0 );
177023  #ifdef CORRUPT_DB
177024    assert( zRoot!=0 || CORRUPT_DB );
177025  #endif
177026  
177027    if( iStartLeaf==0 ){
177028      if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
177029      nExtra = nRoot + FTS3_NODE_PADDING;
177030    }
177031  
177032    pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
177033    if( !pReader ){
177034      return SQLITE_NOMEM;
177035    }
177036    memset(pReader, 0, sizeof(Fts3SegReader));
177037    pReader->iIdx = iAge;
177038    pReader->bLookup = bLookup!=0;
177039    pReader->iStartBlock = iStartLeaf;
177040    pReader->iLeafEndBlock = iEndLeaf;
177041    pReader->iEndBlock = iEndBlock;
177042  
177043    if( nExtra ){
177044      /* The entire segment is stored in the root node. */
177045      pReader->aNode = (char *)&pReader[1];
177046      pReader->rootOnly = 1;
177047      pReader->nNode = nRoot;
177048      if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
177049      memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
177050    }else{
177051      pReader->iCurrentBlock = iStartLeaf-1;
177052    }
177053    *ppReader = pReader;
177054    return SQLITE_OK;
177055  }
177056  
177057  /*
177058  ** This is a comparison function used as a qsort() callback when sorting
177059  ** an array of pending terms by term. This occurs as part of flushing
177060  ** the contents of the pending-terms hash table to the database.
177061  */
177062  static int SQLITE_CDECL fts3CompareElemByTerm(
177063    const void *lhs,
177064    const void *rhs
177065  ){
177066    char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
177067    char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
177068    int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
177069    int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
177070  
177071    int n = (n1<n2 ? n1 : n2);
177072    int c = memcmp(z1, z2, n);
177073    if( c==0 ){
177074      c = n1 - n2;
177075    }
177076    return c;
177077  }
177078  
177079  /*
177080  ** This function is used to allocate an Fts3SegReader that iterates through
177081  ** a subset of the terms stored in the Fts3Table.pendingTerms array.
177082  **
177083  ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
177084  ** through each term in the pending-terms table. Or, if isPrefixIter is
177085  ** non-zero, it iterates through each term and its prefixes. For example, if
177086  ** the pending terms hash table contains the terms "sqlite", "mysql" and
177087  ** "firebird", then the iterator visits the following 'terms' (in the order
177088  ** shown):
177089  **
177090  **   f fi fir fire fireb firebi firebir firebird
177091  **   m my mys mysq mysql
177092  **   s sq sql sqli sqlit sqlite
177093  **
177094  ** Whereas if isPrefixIter is zero, the terms visited are:
177095  **
177096  **   firebird mysql sqlite
177097  */
177098  SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
177099    Fts3Table *p,                   /* Virtual table handle */
177100    int iIndex,                     /* Index for p->aIndex */
177101    const char *zTerm,              /* Term to search for */
177102    int nTerm,                      /* Size of buffer zTerm */
177103    int bPrefix,                    /* True for a prefix iterator */
177104    Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
177105  ){
177106    Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
177107    Fts3HashElem *pE;               /* Iterator variable */
177108    Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
177109    int nElem = 0;                  /* Size of array at aElem */
177110    int rc = SQLITE_OK;             /* Return Code */
177111    Fts3Hash *pHash;
177112  
177113    pHash = &p->aIndex[iIndex].hPending;
177114    if( bPrefix ){
177115      int nAlloc = 0;               /* Size of allocated array at aElem */
177116  
177117      for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
177118        char *zKey = (char *)fts3HashKey(pE);
177119        int nKey = fts3HashKeysize(pE);
177120        if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
177121          if( nElem==nAlloc ){
177122            Fts3HashElem **aElem2;
177123            nAlloc += 16;
177124            aElem2 = (Fts3HashElem **)sqlite3_realloc(
177125                aElem, nAlloc*sizeof(Fts3HashElem *)
177126            );
177127            if( !aElem2 ){
177128              rc = SQLITE_NOMEM;
177129              nElem = 0;
177130              break;
177131            }
177132            aElem = aElem2;
177133          }
177134  
177135          aElem[nElem++] = pE;
177136        }
177137      }
177138  
177139      /* If more than one term matches the prefix, sort the Fts3HashElem
177140      ** objects in term order using qsort(). This uses the same comparison
177141      ** callback as is used when flushing terms to disk.
177142      */
177143      if( nElem>1 ){
177144        qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
177145      }
177146  
177147    }else{
177148      /* The query is a simple term lookup that matches at most one term in
177149      ** the index. All that is required is a straight hash-lookup. 
177150      **
177151      ** Because the stack address of pE may be accessed via the aElem pointer
177152      ** below, the "Fts3HashElem *pE" must be declared so that it is valid
177153      ** within this entire function, not just this "else{...}" block.
177154      */
177155      pE = fts3HashFindElem(pHash, zTerm, nTerm);
177156      if( pE ){
177157        aElem = &pE;
177158        nElem = 1;
177159      }
177160    }
177161  
177162    if( nElem>0 ){
177163      int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
177164      pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
177165      if( !pReader ){
177166        rc = SQLITE_NOMEM;
177167      }else{
177168        memset(pReader, 0, nByte);
177169        pReader->iIdx = 0x7FFFFFFF;
177170        pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
177171        memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
177172      }
177173    }
177174  
177175    if( bPrefix ){
177176      sqlite3_free(aElem);
177177    }
177178    *ppReader = pReader;
177179    return rc;
177180  }
177181  
177182  /*
177183  ** Compare the entries pointed to by two Fts3SegReader structures. 
177184  ** Comparison is as follows:
177185  **
177186  **   1) EOF is greater than not EOF.
177187  **
177188  **   2) The current terms (if any) are compared using memcmp(). If one
177189  **      term is a prefix of another, the longer term is considered the
177190  **      larger.
177191  **
177192  **   3) By segment age. An older segment is considered larger.
177193  */
177194  static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
177195    int rc;
177196    if( pLhs->aNode && pRhs->aNode ){
177197      int rc2 = pLhs->nTerm - pRhs->nTerm;
177198      if( rc2<0 ){
177199        rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
177200      }else{
177201        rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
177202      }
177203      if( rc==0 ){
177204        rc = rc2;
177205      }
177206    }else{
177207      rc = (pLhs->aNode==0) - (pRhs->aNode==0);
177208    }
177209    if( rc==0 ){
177210      rc = pRhs->iIdx - pLhs->iIdx;
177211    }
177212    assert( rc!=0 );
177213    return rc;
177214  }
177215  
177216  /*
177217  ** A different comparison function for SegReader structures. In this
177218  ** version, it is assumed that each SegReader points to an entry in
177219  ** a doclist for identical terms. Comparison is made as follows:
177220  **
177221  **   1) EOF (end of doclist in this case) is greater than not EOF.
177222  **
177223  **   2) By current docid.
177224  **
177225  **   3) By segment age. An older segment is considered larger.
177226  */
177227  static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
177228    int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
177229    if( rc==0 ){
177230      if( pLhs->iDocid==pRhs->iDocid ){
177231        rc = pRhs->iIdx - pLhs->iIdx;
177232      }else{
177233        rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
177234      }
177235    }
177236    assert( pLhs->aNode && pRhs->aNode );
177237    return rc;
177238  }
177239  static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
177240    int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
177241    if( rc==0 ){
177242      if( pLhs->iDocid==pRhs->iDocid ){
177243        rc = pRhs->iIdx - pLhs->iIdx;
177244      }else{
177245        rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
177246      }
177247    }
177248    assert( pLhs->aNode && pRhs->aNode );
177249    return rc;
177250  }
177251  
177252  /*
177253  ** Compare the term that the Fts3SegReader object passed as the first argument
177254  ** points to with the term specified by arguments zTerm and nTerm. 
177255  **
177256  ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
177257  ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
177258  ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
177259  */
177260  static int fts3SegReaderTermCmp(
177261    Fts3SegReader *pSeg,            /* Segment reader object */
177262    const char *zTerm,              /* Term to compare to */
177263    int nTerm                       /* Size of term zTerm in bytes */
177264  ){
177265    int res = 0;
177266    if( pSeg->aNode ){
177267      if( pSeg->nTerm>nTerm ){
177268        res = memcmp(pSeg->zTerm, zTerm, nTerm);
177269      }else{
177270        res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
177271      }
177272      if( res==0 ){
177273        res = pSeg->nTerm-nTerm;
177274      }
177275    }
177276    return res;
177277  }
177278  
177279  /*
177280  ** Argument apSegment is an array of nSegment elements. It is known that
177281  ** the final (nSegment-nSuspect) members are already in sorted order
177282  ** (according to the comparison function provided). This function shuffles
177283  ** the array around until all entries are in sorted order.
177284  */
177285  static void fts3SegReaderSort(
177286    Fts3SegReader **apSegment,                     /* Array to sort entries of */
177287    int nSegment,                                  /* Size of apSegment array */
177288    int nSuspect,                                  /* Unsorted entry count */
177289    int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
177290  ){
177291    int i;                          /* Iterator variable */
177292  
177293    assert( nSuspect<=nSegment );
177294  
177295    if( nSuspect==nSegment ) nSuspect--;
177296    for(i=nSuspect-1; i>=0; i--){
177297      int j;
177298      for(j=i; j<(nSegment-1); j++){
177299        Fts3SegReader *pTmp;
177300        if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
177301        pTmp = apSegment[j+1];
177302        apSegment[j+1] = apSegment[j];
177303        apSegment[j] = pTmp;
177304      }
177305    }
177306  
177307  #ifndef NDEBUG
177308    /* Check that the list really is sorted now. */
177309    for(i=0; i<(nSuspect-1); i++){
177310      assert( xCmp(apSegment[i], apSegment[i+1])<0 );
177311    }
177312  #endif
177313  }
177314  
177315  /* 
177316  ** Insert a record into the %_segments table.
177317  */
177318  static int fts3WriteSegment(
177319    Fts3Table *p,                   /* Virtual table handle */
177320    sqlite3_int64 iBlock,           /* Block id for new block */
177321    char *z,                        /* Pointer to buffer containing block data */
177322    int n                           /* Size of buffer z in bytes */
177323  ){
177324    sqlite3_stmt *pStmt;
177325    int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
177326    if( rc==SQLITE_OK ){
177327      sqlite3_bind_int64(pStmt, 1, iBlock);
177328      sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
177329      sqlite3_step(pStmt);
177330      rc = sqlite3_reset(pStmt);
177331      sqlite3_bind_null(pStmt, 2);
177332    }
177333    return rc;
177334  }
177335  
177336  /*
177337  ** Find the largest relative level number in the table. If successful, set
177338  ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
177339  ** set *pnMax to zero and return an SQLite error code.
177340  */
177341  SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
177342    int rc;
177343    int mxLevel = 0;
177344    sqlite3_stmt *pStmt = 0;
177345  
177346    rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
177347    if( rc==SQLITE_OK ){
177348      if( SQLITE_ROW==sqlite3_step(pStmt) ){
177349        mxLevel = sqlite3_column_int(pStmt, 0);
177350      }
177351      rc = sqlite3_reset(pStmt);
177352    }
177353    *pnMax = mxLevel;
177354    return rc;
177355  }
177356  
177357  /* 
177358  ** Insert a record into the %_segdir table.
177359  */
177360  static int fts3WriteSegdir(
177361    Fts3Table *p,                   /* Virtual table handle */
177362    sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
177363    int iIdx,                       /* Value for "idx" field */
177364    sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
177365    sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
177366    sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
177367    sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
177368    char *zRoot,                    /* Blob value for "root" field */
177369    int nRoot                       /* Number of bytes in buffer zRoot */
177370  ){
177371    sqlite3_stmt *pStmt;
177372    int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
177373    if( rc==SQLITE_OK ){
177374      sqlite3_bind_int64(pStmt, 1, iLevel);
177375      sqlite3_bind_int(pStmt, 2, iIdx);
177376      sqlite3_bind_int64(pStmt, 3, iStartBlock);
177377      sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
177378      if( nLeafData==0 ){
177379        sqlite3_bind_int64(pStmt, 5, iEndBlock);
177380      }else{
177381        char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
177382        if( !zEnd ) return SQLITE_NOMEM;
177383        sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
177384      }
177385      sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
177386      sqlite3_step(pStmt);
177387      rc = sqlite3_reset(pStmt);
177388      sqlite3_bind_null(pStmt, 6);
177389    }
177390    return rc;
177391  }
177392  
177393  /*
177394  ** Return the size of the common prefix (if any) shared by zPrev and
177395  ** zNext, in bytes. For example, 
177396  **
177397  **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
177398  **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
177399  **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
177400  */
177401  static int fts3PrefixCompress(
177402    const char *zPrev,              /* Buffer containing previous term */
177403    int nPrev,                      /* Size of buffer zPrev in bytes */
177404    const char *zNext,              /* Buffer containing next term */
177405    int nNext                       /* Size of buffer zNext in bytes */
177406  ){
177407    int n;
177408    UNUSED_PARAMETER(nNext);
177409    for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
177410    return n;
177411  }
177412  
177413  /*
177414  ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
177415  ** (according to memcmp) than the previous term.
177416  */
177417  static int fts3NodeAddTerm(
177418    Fts3Table *p,                   /* Virtual table handle */
177419    SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
177420    int isCopyTerm,                 /* True if zTerm/nTerm is transient */
177421    const char *zTerm,              /* Pointer to buffer containing term */
177422    int nTerm                       /* Size of term in bytes */
177423  ){
177424    SegmentNode *pTree = *ppTree;
177425    int rc;
177426    SegmentNode *pNew;
177427  
177428    /* First try to append the term to the current node. Return early if 
177429    ** this is possible.
177430    */
177431    if( pTree ){
177432      int nData = pTree->nData;     /* Current size of node in bytes */
177433      int nReq = nData;             /* Required space after adding zTerm */
177434      int nPrefix;                  /* Number of bytes of prefix compression */
177435      int nSuffix;                  /* Suffix length */
177436  
177437      nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
177438      nSuffix = nTerm-nPrefix;
177439  
177440      nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
177441      if( nReq<=p->nNodeSize || !pTree->zTerm ){
177442  
177443        if( nReq>p->nNodeSize ){
177444          /* An unusual case: this is the first term to be added to the node
177445          ** and the static node buffer (p->nNodeSize bytes) is not large
177446          ** enough. Use a separately malloced buffer instead This wastes
177447          ** p->nNodeSize bytes, but since this scenario only comes about when
177448          ** the database contain two terms that share a prefix of almost 2KB, 
177449          ** this is not expected to be a serious problem. 
177450          */
177451          assert( pTree->aData==(char *)&pTree[1] );
177452          pTree->aData = (char *)sqlite3_malloc(nReq);
177453          if( !pTree->aData ){
177454            return SQLITE_NOMEM;
177455          }
177456        }
177457  
177458        if( pTree->zTerm ){
177459          /* There is no prefix-length field for first term in a node */
177460          nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
177461        }
177462  
177463        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
177464        memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
177465        pTree->nData = nData + nSuffix;
177466        pTree->nEntry++;
177467  
177468        if( isCopyTerm ){
177469          if( pTree->nMalloc<nTerm ){
177470            char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
177471            if( !zNew ){
177472              return SQLITE_NOMEM;
177473            }
177474            pTree->nMalloc = nTerm*2;
177475            pTree->zMalloc = zNew;
177476          }
177477          pTree->zTerm = pTree->zMalloc;
177478          memcpy(pTree->zTerm, zTerm, nTerm);
177479          pTree->nTerm = nTerm;
177480        }else{
177481          pTree->zTerm = (char *)zTerm;
177482          pTree->nTerm = nTerm;
177483        }
177484        return SQLITE_OK;
177485      }
177486    }
177487  
177488    /* If control flows to here, it was not possible to append zTerm to the
177489    ** current node. Create a new node (a right-sibling of the current node).
177490    ** If this is the first node in the tree, the term is added to it.
177491    **
177492    ** Otherwise, the term is not added to the new node, it is left empty for
177493    ** now. Instead, the term is inserted into the parent of pTree. If pTree 
177494    ** has no parent, one is created here.
177495    */
177496    pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
177497    if( !pNew ){
177498      return SQLITE_NOMEM;
177499    }
177500    memset(pNew, 0, sizeof(SegmentNode));
177501    pNew->nData = 1 + FTS3_VARINT_MAX;
177502    pNew->aData = (char *)&pNew[1];
177503  
177504    if( pTree ){
177505      SegmentNode *pParent = pTree->pParent;
177506      rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
177507      if( pTree->pParent==0 ){
177508        pTree->pParent = pParent;
177509      }
177510      pTree->pRight = pNew;
177511      pNew->pLeftmost = pTree->pLeftmost;
177512      pNew->pParent = pParent;
177513      pNew->zMalloc = pTree->zMalloc;
177514      pNew->nMalloc = pTree->nMalloc;
177515      pTree->zMalloc = 0;
177516    }else{
177517      pNew->pLeftmost = pNew;
177518      rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
177519    }
177520  
177521    *ppTree = pNew;
177522    return rc;
177523  }
177524  
177525  /*
177526  ** Helper function for fts3NodeWrite().
177527  */
177528  static int fts3TreeFinishNode(
177529    SegmentNode *pTree, 
177530    int iHeight, 
177531    sqlite3_int64 iLeftChild
177532  ){
177533    int nStart;
177534    assert( iHeight>=1 && iHeight<128 );
177535    nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
177536    pTree->aData[nStart] = (char)iHeight;
177537    sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
177538    return nStart;
177539  }
177540  
177541  /*
177542  ** Write the buffer for the segment node pTree and all of its peers to the
177543  ** database. Then call this function recursively to write the parent of 
177544  ** pTree and its peers to the database. 
177545  **
177546  ** Except, if pTree is a root node, do not write it to the database. Instead,
177547  ** set output variables *paRoot and *pnRoot to contain the root node.
177548  **
177549  ** If successful, SQLITE_OK is returned and output variable *piLast is
177550  ** set to the largest blockid written to the database (or zero if no
177551  ** blocks were written to the db). Otherwise, an SQLite error code is 
177552  ** returned.
177553  */
177554  static int fts3NodeWrite(
177555    Fts3Table *p,                   /* Virtual table handle */
177556    SegmentNode *pTree,             /* SegmentNode handle */
177557    int iHeight,                    /* Height of this node in tree */
177558    sqlite3_int64 iLeaf,            /* Block id of first leaf node */
177559    sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
177560    sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
177561    char **paRoot,                  /* OUT: Data for root node */
177562    int *pnRoot                     /* OUT: Size of root node in bytes */
177563  ){
177564    int rc = SQLITE_OK;
177565  
177566    if( !pTree->pParent ){
177567      /* Root node of the tree. */
177568      int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
177569      *piLast = iFree-1;
177570      *pnRoot = pTree->nData - nStart;
177571      *paRoot = &pTree->aData[nStart];
177572    }else{
177573      SegmentNode *pIter;
177574      sqlite3_int64 iNextFree = iFree;
177575      sqlite3_int64 iNextLeaf = iLeaf;
177576      for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
177577        int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
177578        int nWrite = pIter->nData - nStart;
177579    
177580        rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
177581        iNextFree++;
177582        iNextLeaf += (pIter->nEntry+1);
177583      }
177584      if( rc==SQLITE_OK ){
177585        assert( iNextLeaf==iFree );
177586        rc = fts3NodeWrite(
177587            p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
177588        );
177589      }
177590    }
177591  
177592    return rc;
177593  }
177594  
177595  /*
177596  ** Free all memory allocations associated with the tree pTree.
177597  */
177598  static void fts3NodeFree(SegmentNode *pTree){
177599    if( pTree ){
177600      SegmentNode *p = pTree->pLeftmost;
177601      fts3NodeFree(p->pParent);
177602      while( p ){
177603        SegmentNode *pRight = p->pRight;
177604        if( p->aData!=(char *)&p[1] ){
177605          sqlite3_free(p->aData);
177606        }
177607        assert( pRight==0 || p->zMalloc==0 );
177608        sqlite3_free(p->zMalloc);
177609        sqlite3_free(p);
177610        p = pRight;
177611      }
177612    }
177613  }
177614  
177615  /*
177616  ** Add a term to the segment being constructed by the SegmentWriter object
177617  ** *ppWriter. When adding the first term to a segment, *ppWriter should
177618  ** be passed NULL. This function will allocate a new SegmentWriter object
177619  ** and return it via the input/output variable *ppWriter in this case.
177620  **
177621  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
177622  */
177623  static int fts3SegWriterAdd(
177624    Fts3Table *p,                   /* Virtual table handle */
177625    SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
177626    int isCopyTerm,                 /* True if buffer zTerm must be copied */
177627    const char *zTerm,              /* Pointer to buffer containing term */
177628    int nTerm,                      /* Size of term in bytes */
177629    const char *aDoclist,           /* Pointer to buffer containing doclist */
177630    int nDoclist                    /* Size of doclist in bytes */
177631  ){
177632    int nPrefix;                    /* Size of term prefix in bytes */
177633    int nSuffix;                    /* Size of term suffix in bytes */
177634    int nReq;                       /* Number of bytes required on leaf page */
177635    int nData;
177636    SegmentWriter *pWriter = *ppWriter;
177637  
177638    if( !pWriter ){
177639      int rc;
177640      sqlite3_stmt *pStmt;
177641  
177642      /* Allocate the SegmentWriter structure */
177643      pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
177644      if( !pWriter ) return SQLITE_NOMEM;
177645      memset(pWriter, 0, sizeof(SegmentWriter));
177646      *ppWriter = pWriter;
177647  
177648      /* Allocate a buffer in which to accumulate data */
177649      pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
177650      if( !pWriter->aData ) return SQLITE_NOMEM;
177651      pWriter->nSize = p->nNodeSize;
177652  
177653      /* Find the next free blockid in the %_segments table */
177654      rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
177655      if( rc!=SQLITE_OK ) return rc;
177656      if( SQLITE_ROW==sqlite3_step(pStmt) ){
177657        pWriter->iFree = sqlite3_column_int64(pStmt, 0);
177658        pWriter->iFirst = pWriter->iFree;
177659      }
177660      rc = sqlite3_reset(pStmt);
177661      if( rc!=SQLITE_OK ) return rc;
177662    }
177663    nData = pWriter->nData;
177664  
177665    nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
177666    nSuffix = nTerm-nPrefix;
177667  
177668    /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of 
177669    ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
177670    ** compared with BINARY collation. This indicates corruption.  */
177671    if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
177672  
177673    /* Figure out how many bytes are required by this new entry */
177674    nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
177675      sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
177676      nSuffix +                               /* Term suffix */
177677      sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
177678      nDoclist;                               /* Doclist data */
177679  
177680    if( nData>0 && nData+nReq>p->nNodeSize ){
177681      int rc;
177682  
177683      /* The current leaf node is full. Write it out to the database. */
177684      rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
177685      if( rc!=SQLITE_OK ) return rc;
177686      p->nLeafAdd++;
177687  
177688      /* Add the current term to the interior node tree. The term added to
177689      ** the interior tree must:
177690      **
177691      **   a) be greater than the largest term on the leaf node just written
177692      **      to the database (still available in pWriter->zTerm), and
177693      **
177694      **   b) be less than or equal to the term about to be added to the new
177695      **      leaf node (zTerm/nTerm).
177696      **
177697      ** In other words, it must be the prefix of zTerm 1 byte longer than
177698      ** the common prefix (if any) of zTerm and pWriter->zTerm.
177699      */
177700      assert( nPrefix<nTerm );
177701      rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
177702      if( rc!=SQLITE_OK ) return rc;
177703  
177704      nData = 0;
177705      pWriter->nTerm = 0;
177706  
177707      nPrefix = 0;
177708      nSuffix = nTerm;
177709      nReq = 1 +                              /* varint containing prefix size */
177710        sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
177711        nTerm +                               /* Term suffix */
177712        sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
177713        nDoclist;                             /* Doclist data */
177714    }
177715  
177716    /* Increase the total number of bytes written to account for the new entry. */
177717    pWriter->nLeafData += nReq;
177718  
177719    /* If the buffer currently allocated is too small for this entry, realloc
177720    ** the buffer to make it large enough.
177721    */
177722    if( nReq>pWriter->nSize ){
177723      char *aNew = sqlite3_realloc(pWriter->aData, nReq);
177724      if( !aNew ) return SQLITE_NOMEM;
177725      pWriter->aData = aNew;
177726      pWriter->nSize = nReq;
177727    }
177728    assert( nData+nReq<=pWriter->nSize );
177729  
177730    /* Append the prefix-compressed term and doclist to the buffer. */
177731    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
177732    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
177733    memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
177734    nData += nSuffix;
177735    nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
177736    memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
177737    pWriter->nData = nData + nDoclist;
177738  
177739    /* Save the current term so that it can be used to prefix-compress the next.
177740    ** If the isCopyTerm parameter is true, then the buffer pointed to by
177741    ** zTerm is transient, so take a copy of the term data. Otherwise, just
177742    ** store a copy of the pointer.
177743    */
177744    if( isCopyTerm ){
177745      if( nTerm>pWriter->nMalloc ){
177746        char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
177747        if( !zNew ){
177748          return SQLITE_NOMEM;
177749        }
177750        pWriter->nMalloc = nTerm*2;
177751        pWriter->zMalloc = zNew;
177752        pWriter->zTerm = zNew;
177753      }
177754      assert( pWriter->zTerm==pWriter->zMalloc );
177755      memcpy(pWriter->zTerm, zTerm, nTerm);
177756    }else{
177757      pWriter->zTerm = (char *)zTerm;
177758    }
177759    pWriter->nTerm = nTerm;
177760  
177761    return SQLITE_OK;
177762  }
177763  
177764  /*
177765  ** Flush all data associated with the SegmentWriter object pWriter to the
177766  ** database. This function must be called after all terms have been added
177767  ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
177768  ** returned. Otherwise, an SQLite error code.
177769  */
177770  static int fts3SegWriterFlush(
177771    Fts3Table *p,                   /* Virtual table handle */
177772    SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
177773    sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
177774    int iIdx                        /* Value for 'idx' column of %_segdir */
177775  ){
177776    int rc;                         /* Return code */
177777    if( pWriter->pTree ){
177778      sqlite3_int64 iLast = 0;      /* Largest block id written to database */
177779      sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
177780      char *zRoot = NULL;           /* Pointer to buffer containing root node */
177781      int nRoot = 0;                /* Size of buffer zRoot */
177782  
177783      iLastLeaf = pWriter->iFree;
177784      rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
177785      if( rc==SQLITE_OK ){
177786        rc = fts3NodeWrite(p, pWriter->pTree, 1,
177787            pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
177788      }
177789      if( rc==SQLITE_OK ){
177790        rc = fts3WriteSegdir(p, iLevel, iIdx, 
177791            pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
177792      }
177793    }else{
177794      /* The entire tree fits on the root node. Write it to the segdir table. */
177795      rc = fts3WriteSegdir(p, iLevel, iIdx, 
177796          0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
177797    }
177798    p->nLeafAdd++;
177799    return rc;
177800  }
177801  
177802  /*
177803  ** Release all memory held by the SegmentWriter object passed as the 
177804  ** first argument.
177805  */
177806  static void fts3SegWriterFree(SegmentWriter *pWriter){
177807    if( pWriter ){
177808      sqlite3_free(pWriter->aData);
177809      sqlite3_free(pWriter->zMalloc);
177810      fts3NodeFree(pWriter->pTree);
177811      sqlite3_free(pWriter);
177812    }
177813  }
177814  
177815  /*
177816  ** The first value in the apVal[] array is assumed to contain an integer.
177817  ** This function tests if there exist any documents with docid values that
177818  ** are different from that integer. i.e. if deleting the document with docid
177819  ** pRowid would mean the FTS3 table were empty.
177820  **
177821  ** If successful, *pisEmpty is set to true if the table is empty except for
177822  ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
177823  ** error occurs, an SQLite error code is returned.
177824  */
177825  static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
177826    sqlite3_stmt *pStmt;
177827    int rc;
177828    if( p->zContentTbl ){
177829      /* If using the content=xxx option, assume the table is never empty */
177830      *pisEmpty = 0;
177831      rc = SQLITE_OK;
177832    }else{
177833      rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
177834      if( rc==SQLITE_OK ){
177835        if( SQLITE_ROW==sqlite3_step(pStmt) ){
177836          *pisEmpty = sqlite3_column_int(pStmt, 0);
177837        }
177838        rc = sqlite3_reset(pStmt);
177839      }
177840    }
177841    return rc;
177842  }
177843  
177844  /*
177845  ** Set *pnMax to the largest segment level in the database for the index
177846  ** iIndex.
177847  **
177848  ** Segment levels are stored in the 'level' column of the %_segdir table.
177849  **
177850  ** Return SQLITE_OK if successful, or an SQLite error code if not.
177851  */
177852  static int fts3SegmentMaxLevel(
177853    Fts3Table *p, 
177854    int iLangid,
177855    int iIndex, 
177856    sqlite3_int64 *pnMax
177857  ){
177858    sqlite3_stmt *pStmt;
177859    int rc;
177860    assert( iIndex>=0 && iIndex<p->nIndex );
177861  
177862    /* Set pStmt to the compiled version of:
177863    **
177864    **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
177865    **
177866    ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
177867    */
177868    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
177869    if( rc!=SQLITE_OK ) return rc;
177870    sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
177871    sqlite3_bind_int64(pStmt, 2, 
177872        getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
177873    );
177874    if( SQLITE_ROW==sqlite3_step(pStmt) ){
177875      *pnMax = sqlite3_column_int64(pStmt, 0);
177876    }
177877    return sqlite3_reset(pStmt);
177878  }
177879  
177880  /*
177881  ** iAbsLevel is an absolute level that may be assumed to exist within
177882  ** the database. This function checks if it is the largest level number
177883  ** within its index. Assuming no error occurs, *pbMax is set to 1 if
177884  ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
177885  ** is returned. If an error occurs, an error code is returned and the
177886  ** final value of *pbMax is undefined.
177887  */
177888  static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
177889  
177890    /* Set pStmt to the compiled version of:
177891    **
177892    **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
177893    **
177894    ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
177895    */
177896    sqlite3_stmt *pStmt;
177897    int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
177898    if( rc!=SQLITE_OK ) return rc;
177899    sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
177900    sqlite3_bind_int64(pStmt, 2, 
177901        ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
177902    );
177903  
177904    *pbMax = 0;
177905    if( SQLITE_ROW==sqlite3_step(pStmt) ){
177906      *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
177907    }
177908    return sqlite3_reset(pStmt);
177909  }
177910  
177911  /*
177912  ** Delete all entries in the %_segments table associated with the segment
177913  ** opened with seg-reader pSeg. This function does not affect the contents
177914  ** of the %_segdir table.
177915  */
177916  static int fts3DeleteSegment(
177917    Fts3Table *p,                   /* FTS table handle */
177918    Fts3SegReader *pSeg             /* Segment to delete */
177919  ){
177920    int rc = SQLITE_OK;             /* Return code */
177921    if( pSeg->iStartBlock ){
177922      sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
177923      rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
177924      if( rc==SQLITE_OK ){
177925        sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
177926        sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
177927        sqlite3_step(pDelete);
177928        rc = sqlite3_reset(pDelete);
177929      }
177930    }
177931    return rc;
177932  }
177933  
177934  /*
177935  ** This function is used after merging multiple segments into a single large
177936  ** segment to delete the old, now redundant, segment b-trees. Specifically,
177937  ** it:
177938  ** 
177939  **   1) Deletes all %_segments entries for the segments associated with 
177940  **      each of the SegReader objects in the array passed as the third 
177941  **      argument, and
177942  **
177943  **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
177944  **      entries regardless of level if (iLevel<0).
177945  **
177946  ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
177947  */
177948  static int fts3DeleteSegdir(
177949    Fts3Table *p,                   /* Virtual table handle */
177950    int iLangid,                    /* Language id */
177951    int iIndex,                     /* Index for p->aIndex */
177952    int iLevel,                     /* Level of %_segdir entries to delete */
177953    Fts3SegReader **apSegment,      /* Array of SegReader objects */
177954    int nReader                     /* Size of array apSegment */
177955  ){
177956    int rc = SQLITE_OK;             /* Return Code */
177957    int i;                          /* Iterator variable */
177958    sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
177959  
177960    for(i=0; rc==SQLITE_OK && i<nReader; i++){
177961      rc = fts3DeleteSegment(p, apSegment[i]);
177962    }
177963    if( rc!=SQLITE_OK ){
177964      return rc;
177965    }
177966  
177967    assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
177968    if( iLevel==FTS3_SEGCURSOR_ALL ){
177969      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
177970      if( rc==SQLITE_OK ){
177971        sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
177972        sqlite3_bind_int64(pDelete, 2, 
177973            getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
177974        );
177975      }
177976    }else{
177977      rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
177978      if( rc==SQLITE_OK ){
177979        sqlite3_bind_int64(
177980            pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
177981        );
177982      }
177983    }
177984  
177985    if( rc==SQLITE_OK ){
177986      sqlite3_step(pDelete);
177987      rc = sqlite3_reset(pDelete);
177988    }
177989  
177990    return rc;
177991  }
177992  
177993  /*
177994  ** When this function is called, buffer *ppList (size *pnList bytes) contains 
177995  ** a position list that may (or may not) feature multiple columns. This
177996  ** function adjusts the pointer *ppList and the length *pnList so that they
177997  ** identify the subset of the position list that corresponds to column iCol.
177998  **
177999  ** If there are no entries in the input position list for column iCol, then
178000  ** *pnList is set to zero before returning.
178001  **
178002  ** If parameter bZero is non-zero, then any part of the input list following
178003  ** the end of the output list is zeroed before returning.
178004  */
178005  static void fts3ColumnFilter(
178006    int iCol,                       /* Column to filter on */
178007    int bZero,                      /* Zero out anything following *ppList */
178008    char **ppList,                  /* IN/OUT: Pointer to position list */
178009    int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
178010  ){
178011    char *pList = *ppList;
178012    int nList = *pnList;
178013    char *pEnd = &pList[nList];
178014    int iCurrent = 0;
178015    char *p = pList;
178016  
178017    assert( iCol>=0 );
178018    while( 1 ){
178019      char c = 0;
178020      while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
178021    
178022      if( iCol==iCurrent ){
178023        nList = (int)(p - pList);
178024        break;
178025      }
178026  
178027      nList -= (int)(p - pList);
178028      pList = p;
178029      if( nList==0 ){
178030        break;
178031      }
178032      p = &pList[1];
178033      p += fts3GetVarint32(p, &iCurrent);
178034    }
178035  
178036    if( bZero && &pList[nList]!=pEnd ){
178037      memset(&pList[nList], 0, pEnd - &pList[nList]);
178038    }
178039    *ppList = pList;
178040    *pnList = nList;
178041  }
178042  
178043  /*
178044  ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
178045  ** existing data). Grow the buffer if required.
178046  **
178047  ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
178048  ** trying to resize the buffer, return SQLITE_NOMEM.
178049  */
178050  static int fts3MsrBufferData(
178051    Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
178052    char *pList,
178053    int nList
178054  ){
178055    if( nList>pMsr->nBuffer ){
178056      char *pNew;
178057      pMsr->nBuffer = nList*2;
178058      pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
178059      if( !pNew ) return SQLITE_NOMEM;
178060      pMsr->aBuffer = pNew;
178061    }
178062  
178063    memcpy(pMsr->aBuffer, pList, nList);
178064    return SQLITE_OK;
178065  }
178066  
178067  SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
178068    Fts3Table *p,                   /* Virtual table handle */
178069    Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
178070    sqlite3_int64 *piDocid,         /* OUT: Docid value */
178071    char **paPoslist,               /* OUT: Pointer to position list */
178072    int *pnPoslist                  /* OUT: Size of position list in bytes */
178073  ){
178074    int nMerge = pMsr->nAdvance;
178075    Fts3SegReader **apSegment = pMsr->apSegment;
178076    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
178077      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
178078    );
178079  
178080    if( nMerge==0 ){
178081      *paPoslist = 0;
178082      return SQLITE_OK;
178083    }
178084  
178085    while( 1 ){
178086      Fts3SegReader *pSeg;
178087      pSeg = pMsr->apSegment[0];
178088  
178089      if( pSeg->pOffsetList==0 ){
178090        *paPoslist = 0;
178091        break;
178092      }else{
178093        int rc;
178094        char *pList;
178095        int nList;
178096        int j;
178097        sqlite3_int64 iDocid = apSegment[0]->iDocid;
178098  
178099        rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
178100        j = 1;
178101        while( rc==SQLITE_OK 
178102          && j<nMerge
178103          && apSegment[j]->pOffsetList
178104          && apSegment[j]->iDocid==iDocid
178105        ){
178106          rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
178107          j++;
178108        }
178109        if( rc!=SQLITE_OK ) return rc;
178110        fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
178111  
178112        if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
178113          rc = fts3MsrBufferData(pMsr, pList, nList+1);
178114          if( rc!=SQLITE_OK ) return rc;
178115          assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
178116          pList = pMsr->aBuffer;
178117        }
178118  
178119        if( pMsr->iColFilter>=0 ){
178120          fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
178121        }
178122  
178123        if( nList>0 ){
178124          *paPoslist = pList;
178125          *piDocid = iDocid;
178126          *pnPoslist = nList;
178127          break;
178128        }
178129      }
178130    }
178131  
178132    return SQLITE_OK;
178133  }
178134  
178135  static int fts3SegReaderStart(
178136    Fts3Table *p,                   /* Virtual table handle */
178137    Fts3MultiSegReader *pCsr,       /* Cursor object */
178138    const char *zTerm,              /* Term searched for (or NULL) */
178139    int nTerm                       /* Length of zTerm in bytes */
178140  ){
178141    int i;
178142    int nSeg = pCsr->nSegment;
178143  
178144    /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
178145    ** for, then advance each segment iterator until it points to a term of
178146    ** equal or greater value than the specified term. This prevents many
178147    ** unnecessary merge/sort operations for the case where single segment
178148    ** b-tree leaf nodes contain more than one term.
178149    */
178150    for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
178151      int res = 0;
178152      Fts3SegReader *pSeg = pCsr->apSegment[i];
178153      do {
178154        int rc = fts3SegReaderNext(p, pSeg, 0);
178155        if( rc!=SQLITE_OK ) return rc;
178156      }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
178157  
178158      if( pSeg->bLookup && res!=0 ){
178159        fts3SegReaderSetEof(pSeg);
178160      }
178161    }
178162    fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
178163  
178164    return SQLITE_OK;
178165  }
178166  
178167  SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
178168    Fts3Table *p,                   /* Virtual table handle */
178169    Fts3MultiSegReader *pCsr,       /* Cursor object */
178170    Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
178171  ){
178172    pCsr->pFilter = pFilter;
178173    return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
178174  }
178175  
178176  SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
178177    Fts3Table *p,                   /* Virtual table handle */
178178    Fts3MultiSegReader *pCsr,       /* Cursor object */
178179    int iCol,                       /* Column to match on. */
178180    const char *zTerm,              /* Term to iterate through a doclist for */
178181    int nTerm                       /* Number of bytes in zTerm */
178182  ){
178183    int i;
178184    int rc;
178185    int nSegment = pCsr->nSegment;
178186    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
178187      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
178188    );
178189  
178190    assert( pCsr->pFilter==0 );
178191    assert( zTerm && nTerm>0 );
178192  
178193    /* Advance each segment iterator until it points to the term zTerm/nTerm. */
178194    rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
178195    if( rc!=SQLITE_OK ) return rc;
178196  
178197    /* Determine how many of the segments actually point to zTerm/nTerm. */
178198    for(i=0; i<nSegment; i++){
178199      Fts3SegReader *pSeg = pCsr->apSegment[i];
178200      if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
178201        break;
178202      }
178203    }
178204    pCsr->nAdvance = i;
178205  
178206    /* Advance each of the segments to point to the first docid. */
178207    for(i=0; i<pCsr->nAdvance; i++){
178208      rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
178209      if( rc!=SQLITE_OK ) return rc;
178210    }
178211    fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
178212  
178213    assert( iCol<0 || iCol<p->nColumn );
178214    pCsr->iColFilter = iCol;
178215  
178216    return SQLITE_OK;
178217  }
178218  
178219  /*
178220  ** This function is called on a MultiSegReader that has been started using
178221  ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
178222  ** have been made. Calling this function puts the MultiSegReader in such
178223  ** a state that if the next two calls are:
178224  **
178225  **   sqlite3Fts3SegReaderStart()
178226  **   sqlite3Fts3SegReaderStep()
178227  **
178228  ** then the entire doclist for the term is available in 
178229  ** MultiSegReader.aDoclist/nDoclist.
178230  */
178231  SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
178232    int i;                          /* Used to iterate through segment-readers */
178233  
178234    assert( pCsr->zTerm==0 );
178235    assert( pCsr->nTerm==0 );
178236    assert( pCsr->aDoclist==0 );
178237    assert( pCsr->nDoclist==0 );
178238  
178239    pCsr->nAdvance = 0;
178240    pCsr->bRestart = 1;
178241    for(i=0; i<pCsr->nSegment; i++){
178242      pCsr->apSegment[i]->pOffsetList = 0;
178243      pCsr->apSegment[i]->nOffsetList = 0;
178244      pCsr->apSegment[i]->iDocid = 0;
178245    }
178246  
178247    return SQLITE_OK;
178248  }
178249  
178250  
178251  SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
178252    Fts3Table *p,                   /* Virtual table handle */
178253    Fts3MultiSegReader *pCsr        /* Cursor object */
178254  ){
178255    int rc = SQLITE_OK;
178256  
178257    int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
178258    int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
178259    int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
178260    int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
178261    int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
178262    int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
178263  
178264    Fts3SegReader **apSegment = pCsr->apSegment;
178265    int nSegment = pCsr->nSegment;
178266    Fts3SegFilter *pFilter = pCsr->pFilter;
178267    int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
178268      p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
178269    );
178270  
178271    if( pCsr->nSegment==0 ) return SQLITE_OK;
178272  
178273    do {
178274      int nMerge;
178275      int i;
178276    
178277      /* Advance the first pCsr->nAdvance entries in the apSegment[] array
178278      ** forward. Then sort the list in order of current term again.  
178279      */
178280      for(i=0; i<pCsr->nAdvance; i++){
178281        Fts3SegReader *pSeg = apSegment[i];
178282        if( pSeg->bLookup ){
178283          fts3SegReaderSetEof(pSeg);
178284        }else{
178285          rc = fts3SegReaderNext(p, pSeg, 0);
178286        }
178287        if( rc!=SQLITE_OK ) return rc;
178288      }
178289      fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
178290      pCsr->nAdvance = 0;
178291  
178292      /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
178293      assert( rc==SQLITE_OK );
178294      if( apSegment[0]->aNode==0 ) break;
178295  
178296      pCsr->nTerm = apSegment[0]->nTerm;
178297      pCsr->zTerm = apSegment[0]->zTerm;
178298  
178299      /* If this is a prefix-search, and if the term that apSegment[0] points
178300      ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
178301      ** required callbacks have been made. In this case exit early.
178302      **
178303      ** Similarly, if this is a search for an exact match, and the first term
178304      ** of segment apSegment[0] is not a match, exit early.
178305      */
178306      if( pFilter->zTerm && !isScan ){
178307        if( pCsr->nTerm<pFilter->nTerm 
178308         || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
178309         || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
178310        ){
178311          break;
178312        }
178313      }
178314  
178315      nMerge = 1;
178316      while( nMerge<nSegment 
178317          && apSegment[nMerge]->aNode
178318          && apSegment[nMerge]->nTerm==pCsr->nTerm 
178319          && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
178320      ){
178321        nMerge++;
178322      }
178323  
178324      assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
178325      if( nMerge==1 
178326       && !isIgnoreEmpty 
178327       && !isFirst 
178328       && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
178329      ){
178330        pCsr->nDoclist = apSegment[0]->nDoclist;
178331        if( fts3SegReaderIsPending(apSegment[0]) ){
178332          rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
178333          pCsr->aDoclist = pCsr->aBuffer;
178334        }else{
178335          pCsr->aDoclist = apSegment[0]->aDoclist;
178336        }
178337        if( rc==SQLITE_OK ) rc = SQLITE_ROW;
178338      }else{
178339        int nDoclist = 0;           /* Size of doclist */
178340        sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
178341  
178342        /* The current term of the first nMerge entries in the array
178343        ** of Fts3SegReader objects is the same. The doclists must be merged
178344        ** and a single term returned with the merged doclist.
178345        */
178346        for(i=0; i<nMerge; i++){
178347          fts3SegReaderFirstDocid(p, apSegment[i]);
178348        }
178349        fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
178350        while( apSegment[0]->pOffsetList ){
178351          int j;                    /* Number of segments that share a docid */
178352          char *pList = 0;
178353          int nList = 0;
178354          int nByte;
178355          sqlite3_int64 iDocid = apSegment[0]->iDocid;
178356          fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
178357          j = 1;
178358          while( j<nMerge
178359              && apSegment[j]->pOffsetList
178360              && apSegment[j]->iDocid==iDocid
178361          ){
178362            fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
178363            j++;
178364          }
178365  
178366          if( isColFilter ){
178367            fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
178368          }
178369  
178370          if( !isIgnoreEmpty || nList>0 ){
178371  
178372            /* Calculate the 'docid' delta value to write into the merged 
178373            ** doclist. */
178374            sqlite3_int64 iDelta;
178375            if( p->bDescIdx && nDoclist>0 ){
178376              iDelta = iPrev - iDocid;
178377            }else{
178378              iDelta = iDocid - iPrev;
178379            }
178380            if( iDelta<=0 && (nDoclist>0 || iDelta!=iDocid) ){
178381              return FTS_CORRUPT_VTAB;
178382            }
178383            assert( nDoclist>0 || iDelta==iDocid );
178384  
178385            nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
178386            if( nDoclist+nByte>pCsr->nBuffer ){
178387              char *aNew;
178388              pCsr->nBuffer = (nDoclist+nByte)*2;
178389              aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
178390              if( !aNew ){
178391                return SQLITE_NOMEM;
178392              }
178393              pCsr->aBuffer = aNew;
178394            }
178395  
178396            if( isFirst ){
178397              char *a = &pCsr->aBuffer[nDoclist];
178398              int nWrite;
178399             
178400              nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
178401              if( nWrite ){
178402                iPrev = iDocid;
178403                nDoclist += nWrite;
178404              }
178405            }else{
178406              nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
178407              iPrev = iDocid;
178408              if( isRequirePos ){
178409                memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
178410                nDoclist += nList;
178411                pCsr->aBuffer[nDoclist++] = '\0';
178412              }
178413            }
178414          }
178415  
178416          fts3SegReaderSort(apSegment, nMerge, j, xCmp);
178417        }
178418        if( nDoclist>0 ){
178419          pCsr->aDoclist = pCsr->aBuffer;
178420          pCsr->nDoclist = nDoclist;
178421          rc = SQLITE_ROW;
178422        }
178423      }
178424      pCsr->nAdvance = nMerge;
178425    }while( rc==SQLITE_OK );
178426  
178427    return rc;
178428  }
178429  
178430  
178431  SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
178432    Fts3MultiSegReader *pCsr       /* Cursor object */
178433  ){
178434    if( pCsr ){
178435      int i;
178436      for(i=0; i<pCsr->nSegment; i++){
178437        sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
178438      }
178439      sqlite3_free(pCsr->apSegment);
178440      sqlite3_free(pCsr->aBuffer);
178441  
178442      pCsr->nSegment = 0;
178443      pCsr->apSegment = 0;
178444      pCsr->aBuffer = 0;
178445    }
178446  }
178447  
178448  /*
178449  ** Decode the "end_block" field, selected by column iCol of the SELECT 
178450  ** statement passed as the first argument. 
178451  **
178452  ** The "end_block" field may contain either an integer, or a text field
178453  ** containing the text representation of two non-negative integers separated 
178454  ** by one or more space (0x20) characters. In the first case, set *piEndBlock 
178455  ** to the integer value and *pnByte to zero before returning. In the second, 
178456  ** set *piEndBlock to the first value and *pnByte to the second.
178457  */
178458  static void fts3ReadEndBlockField(
178459    sqlite3_stmt *pStmt, 
178460    int iCol, 
178461    i64 *piEndBlock,
178462    i64 *pnByte
178463  ){
178464    const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
178465    if( zText ){
178466      int i;
178467      int iMul = 1;
178468      i64 iVal = 0;
178469      for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
178470        iVal = iVal*10 + (zText[i] - '0');
178471      }
178472      *piEndBlock = iVal;
178473      while( zText[i]==' ' ) i++;
178474      iVal = 0;
178475      if( zText[i]=='-' ){
178476        i++;
178477        iMul = -1;
178478      }
178479      for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
178480        iVal = iVal*10 + (zText[i] - '0');
178481      }
178482      *pnByte = (iVal * (i64)iMul);
178483    }
178484  }
178485  
178486  
178487  /*
178488  ** A segment of size nByte bytes has just been written to absolute level
178489  ** iAbsLevel. Promote any segments that should be promoted as a result.
178490  */
178491  static int fts3PromoteSegments(
178492    Fts3Table *p,                   /* FTS table handle */
178493    sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
178494    sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
178495  ){
178496    int rc = SQLITE_OK;
178497    sqlite3_stmt *pRange;
178498  
178499    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
178500  
178501    if( rc==SQLITE_OK ){
178502      int bOk = 0;
178503      i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
178504      i64 nLimit = (nByte*3)/2;
178505  
178506      /* Loop through all entries in the %_segdir table corresponding to 
178507      ** segments in this index on levels greater than iAbsLevel. If there is
178508      ** at least one such segment, and it is possible to determine that all 
178509      ** such segments are smaller than nLimit bytes in size, they will be 
178510      ** promoted to level iAbsLevel.  */
178511      sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
178512      sqlite3_bind_int64(pRange, 2, iLast);
178513      while( SQLITE_ROW==sqlite3_step(pRange) ){
178514        i64 nSize = 0, dummy;
178515        fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
178516        if( nSize<=0 || nSize>nLimit ){
178517          /* If nSize==0, then the %_segdir.end_block field does not not 
178518          ** contain a size value. This happens if it was written by an
178519          ** old version of FTS. In this case it is not possible to determine
178520          ** the size of the segment, and so segment promotion does not
178521          ** take place.  */
178522          bOk = 0;
178523          break;
178524        }
178525        bOk = 1;
178526      }
178527      rc = sqlite3_reset(pRange);
178528  
178529      if( bOk ){
178530        int iIdx = 0;
178531        sqlite3_stmt *pUpdate1 = 0;
178532        sqlite3_stmt *pUpdate2 = 0;
178533  
178534        if( rc==SQLITE_OK ){
178535          rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
178536        }
178537        if( rc==SQLITE_OK ){
178538          rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
178539        }
178540  
178541        if( rc==SQLITE_OK ){
178542  
178543          /* Loop through all %_segdir entries for segments in this index with
178544          ** levels equal to or greater than iAbsLevel. As each entry is visited,
178545          ** updated it to set (level = -1) and (idx = N), where N is 0 for the
178546          ** oldest segment in the range, 1 for the next oldest, and so on.
178547          **
178548          ** In other words, move all segments being promoted to level -1,
178549          ** setting the "idx" fields as appropriate to keep them in the same
178550          ** order. The contents of level -1 (which is never used, except
178551          ** transiently here), will be moved back to level iAbsLevel below.  */
178552          sqlite3_bind_int64(pRange, 1, iAbsLevel);
178553          while( SQLITE_ROW==sqlite3_step(pRange) ){
178554            sqlite3_bind_int(pUpdate1, 1, iIdx++);
178555            sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
178556            sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
178557            sqlite3_step(pUpdate1);
178558            rc = sqlite3_reset(pUpdate1);
178559            if( rc!=SQLITE_OK ){
178560              sqlite3_reset(pRange);
178561              break;
178562            }
178563          }
178564        }
178565        if( rc==SQLITE_OK ){
178566          rc = sqlite3_reset(pRange);
178567        }
178568  
178569        /* Move level -1 to level iAbsLevel */
178570        if( rc==SQLITE_OK ){
178571          sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
178572          sqlite3_step(pUpdate2);
178573          rc = sqlite3_reset(pUpdate2);
178574        }
178575      }
178576    }
178577  
178578  
178579    return rc;
178580  }
178581  
178582  /*
178583  ** Merge all level iLevel segments in the database into a single 
178584  ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
178585  ** single segment with a level equal to the numerically largest level 
178586  ** currently present in the database.
178587  **
178588  ** If this function is called with iLevel<0, but there is only one
178589  ** segment in the database, SQLITE_DONE is returned immediately. 
178590  ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
178591  ** an SQLite error code is returned.
178592  */
178593  static int fts3SegmentMerge(
178594    Fts3Table *p, 
178595    int iLangid,                    /* Language id to merge */
178596    int iIndex,                     /* Index in p->aIndex[] to merge */
178597    int iLevel                      /* Level to merge */
178598  ){
178599    int rc;                         /* Return code */
178600    int iIdx = 0;                   /* Index of new segment */
178601    sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
178602    SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
178603    Fts3SegFilter filter;           /* Segment term filter condition */
178604    Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
178605    int bIgnoreEmpty = 0;           /* True to ignore empty segments */
178606    i64 iMaxLevel = 0;              /* Max level number for this index/langid */
178607  
178608    assert( iLevel==FTS3_SEGCURSOR_ALL
178609         || iLevel==FTS3_SEGCURSOR_PENDING
178610         || iLevel>=0
178611    );
178612    assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
178613    assert( iIndex>=0 && iIndex<p->nIndex );
178614  
178615    rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
178616    if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
178617  
178618    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
178619      rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
178620      if( rc!=SQLITE_OK ) goto finished;
178621    }
178622  
178623    if( iLevel==FTS3_SEGCURSOR_ALL ){
178624      /* This call is to merge all segments in the database to a single
178625      ** segment. The level of the new segment is equal to the numerically
178626      ** greatest segment level currently present in the database for this
178627      ** index. The idx of the new segment is always 0.  */
178628      if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
178629        rc = SQLITE_DONE;
178630        goto finished;
178631      }
178632      iNewLevel = iMaxLevel;
178633      bIgnoreEmpty = 1;
178634  
178635    }else{
178636      /* This call is to merge all segments at level iLevel. find the next
178637      ** available segment index at level iLevel+1. The call to
178638      ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
178639      ** a single iLevel+2 segment if necessary.  */
178640      assert( FTS3_SEGCURSOR_PENDING==-1 );
178641      iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
178642      rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
178643      bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
178644    }
178645    if( rc!=SQLITE_OK ) goto finished;
178646  
178647    assert( csr.nSegment>0 );
178648    assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
178649    assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
178650  
178651    memset(&filter, 0, sizeof(Fts3SegFilter));
178652    filter.flags = FTS3_SEGMENT_REQUIRE_POS;
178653    filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
178654  
178655    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
178656    while( SQLITE_OK==rc ){
178657      rc = sqlite3Fts3SegReaderStep(p, &csr);
178658      if( rc!=SQLITE_ROW ) break;
178659      rc = fts3SegWriterAdd(p, &pWriter, 1, 
178660          csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
178661    }
178662    if( rc!=SQLITE_OK ) goto finished;
178663    assert( pWriter || bIgnoreEmpty );
178664  
178665    if( iLevel!=FTS3_SEGCURSOR_PENDING ){
178666      rc = fts3DeleteSegdir(
178667          p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
178668      );
178669      if( rc!=SQLITE_OK ) goto finished;
178670    }
178671    if( pWriter ){
178672      rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
178673      if( rc==SQLITE_OK ){
178674        if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
178675          rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
178676        }
178677      }
178678    }
178679  
178680   finished:
178681    fts3SegWriterFree(pWriter);
178682    sqlite3Fts3SegReaderFinish(&csr);
178683    return rc;
178684  }
178685  
178686  
178687  /* 
178688  ** Flush the contents of pendingTerms to level 0 segments. 
178689  */
178690  SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
178691    int rc = SQLITE_OK;
178692    int i;
178693          
178694    for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
178695      rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
178696      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
178697    }
178698    sqlite3Fts3PendingTermsClear(p);
178699  
178700    /* Determine the auto-incr-merge setting if unknown.  If enabled,
178701    ** estimate the number of leaf blocks of content to be written
178702    */
178703    if( rc==SQLITE_OK && p->bHasStat
178704     && p->nAutoincrmerge==0xff && p->nLeafAdd>0
178705    ){
178706      sqlite3_stmt *pStmt = 0;
178707      rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
178708      if( rc==SQLITE_OK ){
178709        sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
178710        rc = sqlite3_step(pStmt);
178711        if( rc==SQLITE_ROW ){
178712          p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
178713          if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
178714        }else if( rc==SQLITE_DONE ){
178715          p->nAutoincrmerge = 0;
178716        }
178717        rc = sqlite3_reset(pStmt);
178718      }
178719    }
178720    return rc;
178721  }
178722  
178723  /*
178724  ** Encode N integers as varints into a blob.
178725  */
178726  static void fts3EncodeIntArray(
178727    int N,             /* The number of integers to encode */
178728    u32 *a,            /* The integer values */
178729    char *zBuf,        /* Write the BLOB here */
178730    int *pNBuf         /* Write number of bytes if zBuf[] used here */
178731  ){
178732    int i, j;
178733    for(i=j=0; i<N; i++){
178734      j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
178735    }
178736    *pNBuf = j;
178737  }
178738  
178739  /*
178740  ** Decode a blob of varints into N integers
178741  */
178742  static void fts3DecodeIntArray(
178743    int N,             /* The number of integers to decode */
178744    u32 *a,            /* Write the integer values */
178745    const char *zBuf,  /* The BLOB containing the varints */
178746    int nBuf           /* size of the BLOB */
178747  ){
178748    int i = 0;
178749    if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
178750      int j;
178751      for(i=j=0; i<N && j<nBuf; i++){
178752        sqlite3_int64 x;
178753        j += sqlite3Fts3GetVarint(&zBuf[j], &x);
178754        a[i] = (u32)(x & 0xffffffff);
178755      }
178756    }
178757    while( i<N ) a[i++] = 0;
178758  }
178759  
178760  /*
178761  ** Insert the sizes (in tokens) for each column of the document
178762  ** with docid equal to p->iPrevDocid.  The sizes are encoded as
178763  ** a blob of varints.
178764  */
178765  static void fts3InsertDocsize(
178766    int *pRC,                       /* Result code */
178767    Fts3Table *p,                   /* Table into which to insert */
178768    u32 *aSz                        /* Sizes of each column, in tokens */
178769  ){
178770    char *pBlob;             /* The BLOB encoding of the document size */
178771    int nBlob;               /* Number of bytes in the BLOB */
178772    sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
178773    int rc;                  /* Result code from subfunctions */
178774  
178775    if( *pRC ) return;
178776    pBlob = sqlite3_malloc( 10*p->nColumn );
178777    if( pBlob==0 ){
178778      *pRC = SQLITE_NOMEM;
178779      return;
178780    }
178781    fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
178782    rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
178783    if( rc ){
178784      sqlite3_free(pBlob);
178785      *pRC = rc;
178786      return;
178787    }
178788    sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
178789    sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
178790    sqlite3_step(pStmt);
178791    *pRC = sqlite3_reset(pStmt);
178792  }
178793  
178794  /*
178795  ** Record 0 of the %_stat table contains a blob consisting of N varints,
178796  ** where N is the number of user defined columns in the fts3 table plus
178797  ** two. If nCol is the number of user defined columns, then values of the 
178798  ** varints are set as follows:
178799  **
178800  **   Varint 0:       Total number of rows in the table.
178801  **
178802  **   Varint 1..nCol: For each column, the total number of tokens stored in
178803  **                   the column for all rows of the table.
178804  **
178805  **   Varint 1+nCol:  The total size, in bytes, of all text values in all
178806  **                   columns of all rows of the table.
178807  **
178808  */
178809  static void fts3UpdateDocTotals(
178810    int *pRC,                       /* The result code */
178811    Fts3Table *p,                   /* Table being updated */
178812    u32 *aSzIns,                    /* Size increases */
178813    u32 *aSzDel,                    /* Size decreases */
178814    int nChng                       /* Change in the number of documents */
178815  ){
178816    char *pBlob;             /* Storage for BLOB written into %_stat */
178817    int nBlob;               /* Size of BLOB written into %_stat */
178818    u32 *a;                  /* Array of integers that becomes the BLOB */
178819    sqlite3_stmt *pStmt;     /* Statement for reading and writing */
178820    int i;                   /* Loop counter */
178821    int rc;                  /* Result code from subfunctions */
178822  
178823    const int nStat = p->nColumn+2;
178824  
178825    if( *pRC ) return;
178826    a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
178827    if( a==0 ){
178828      *pRC = SQLITE_NOMEM;
178829      return;
178830    }
178831    pBlob = (char*)&a[nStat];
178832    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
178833    if( rc ){
178834      sqlite3_free(a);
178835      *pRC = rc;
178836      return;
178837    }
178838    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
178839    if( sqlite3_step(pStmt)==SQLITE_ROW ){
178840      fts3DecodeIntArray(nStat, a,
178841           sqlite3_column_blob(pStmt, 0),
178842           sqlite3_column_bytes(pStmt, 0));
178843    }else{
178844      memset(a, 0, sizeof(u32)*(nStat) );
178845    }
178846    rc = sqlite3_reset(pStmt);
178847    if( rc!=SQLITE_OK ){
178848      sqlite3_free(a);
178849      *pRC = rc;
178850      return;
178851    }
178852    if( nChng<0 && a[0]<(u32)(-nChng) ){
178853      a[0] = 0;
178854    }else{
178855      a[0] += nChng;
178856    }
178857    for(i=0; i<p->nColumn+1; i++){
178858      u32 x = a[i+1];
178859      if( x+aSzIns[i] < aSzDel[i] ){
178860        x = 0;
178861      }else{
178862        x = x + aSzIns[i] - aSzDel[i];
178863      }
178864      a[i+1] = x;
178865    }
178866    fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
178867    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
178868    if( rc ){
178869      sqlite3_free(a);
178870      *pRC = rc;
178871      return;
178872    }
178873    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
178874    sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
178875    sqlite3_step(pStmt);
178876    *pRC = sqlite3_reset(pStmt);
178877    sqlite3_bind_null(pStmt, 2);
178878    sqlite3_free(a);
178879  }
178880  
178881  /*
178882  ** Merge the entire database so that there is one segment for each 
178883  ** iIndex/iLangid combination.
178884  */
178885  static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
178886    int bSeenDone = 0;
178887    int rc;
178888    sqlite3_stmt *pAllLangid = 0;
178889  
178890    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
178891    if( rc==SQLITE_OK ){
178892      int rc2;
178893      sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
178894      sqlite3_bind_int(pAllLangid, 2, p->nIndex);
178895      while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
178896        int i;
178897        int iLangid = sqlite3_column_int(pAllLangid, 0);
178898        for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
178899          rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
178900          if( rc==SQLITE_DONE ){
178901            bSeenDone = 1;
178902            rc = SQLITE_OK;
178903          }
178904        }
178905      }
178906      rc2 = sqlite3_reset(pAllLangid);
178907      if( rc==SQLITE_OK ) rc = rc2;
178908    }
178909  
178910    sqlite3Fts3SegmentsClose(p);
178911    sqlite3Fts3PendingTermsClear(p);
178912  
178913    return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
178914  }
178915  
178916  /*
178917  ** This function is called when the user executes the following statement:
178918  **
178919  **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
178920  **
178921  ** The entire FTS index is discarded and rebuilt. If the table is one 
178922  ** created using the content=xxx option, then the new index is based on
178923  ** the current contents of the xxx table. Otherwise, it is rebuilt based
178924  ** on the contents of the %_content table.
178925  */
178926  static int fts3DoRebuild(Fts3Table *p){
178927    int rc;                         /* Return Code */
178928  
178929    rc = fts3DeleteAll(p, 0);
178930    if( rc==SQLITE_OK ){
178931      u32 *aSz = 0;
178932      u32 *aSzIns = 0;
178933      u32 *aSzDel = 0;
178934      sqlite3_stmt *pStmt = 0;
178935      int nEntry = 0;
178936  
178937      /* Compose and prepare an SQL statement to loop through the content table */
178938      char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
178939      if( !zSql ){
178940        rc = SQLITE_NOMEM;
178941      }else{
178942        rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
178943        sqlite3_free(zSql);
178944      }
178945  
178946      if( rc==SQLITE_OK ){
178947        int nByte = sizeof(u32) * (p->nColumn+1)*3;
178948        aSz = (u32 *)sqlite3_malloc(nByte);
178949        if( aSz==0 ){
178950          rc = SQLITE_NOMEM;
178951        }else{
178952          memset(aSz, 0, nByte);
178953          aSzIns = &aSz[p->nColumn+1];
178954          aSzDel = &aSzIns[p->nColumn+1];
178955        }
178956      }
178957  
178958      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
178959        int iCol;
178960        int iLangid = langidFromSelect(p, pStmt);
178961        rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
178962        memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
178963        for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
178964          if( p->abNotindexed[iCol]==0 ){
178965            const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
178966            rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
178967            aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
178968          }
178969        }
178970        if( p->bHasDocsize ){
178971          fts3InsertDocsize(&rc, p, aSz);
178972        }
178973        if( rc!=SQLITE_OK ){
178974          sqlite3_finalize(pStmt);
178975          pStmt = 0;
178976        }else{
178977          nEntry++;
178978          for(iCol=0; iCol<=p->nColumn; iCol++){
178979            aSzIns[iCol] += aSz[iCol];
178980          }
178981        }
178982      }
178983      if( p->bFts4 ){
178984        fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
178985      }
178986      sqlite3_free(aSz);
178987  
178988      if( pStmt ){
178989        int rc2 = sqlite3_finalize(pStmt);
178990        if( rc==SQLITE_OK ){
178991          rc = rc2;
178992        }
178993      }
178994    }
178995  
178996    return rc;
178997  }
178998  
178999  
179000  /*
179001  ** This function opens a cursor used to read the input data for an 
179002  ** incremental merge operation. Specifically, it opens a cursor to scan
179003  ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
179004  ** level iAbsLevel.
179005  */
179006  static int fts3IncrmergeCsr(
179007    Fts3Table *p,                   /* FTS3 table handle */
179008    sqlite3_int64 iAbsLevel,        /* Absolute level to open */
179009    int nSeg,                       /* Number of segments to merge */
179010    Fts3MultiSegReader *pCsr        /* Cursor object to populate */
179011  ){
179012    int rc;                         /* Return Code */
179013    sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
179014    int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
179015  
179016    /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
179017    memset(pCsr, 0, sizeof(*pCsr));
179018    nByte = sizeof(Fts3SegReader *) * nSeg;
179019    pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
179020  
179021    if( pCsr->apSegment==0 ){
179022      rc = SQLITE_NOMEM;
179023    }else{
179024      memset(pCsr->apSegment, 0, nByte);
179025      rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
179026    }
179027    if( rc==SQLITE_OK ){
179028      int i;
179029      int rc2;
179030      sqlite3_bind_int64(pStmt, 1, iAbsLevel);
179031      assert( pCsr->nSegment==0 );
179032      for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
179033        rc = sqlite3Fts3SegReaderNew(i, 0,
179034            sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
179035            sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
179036            sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
179037            sqlite3_column_blob(pStmt, 4),         /* segdir.root */
179038            sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
179039            &pCsr->apSegment[i]
179040        );
179041        pCsr->nSegment++;
179042      }
179043      rc2 = sqlite3_reset(pStmt);
179044      if( rc==SQLITE_OK ) rc = rc2;
179045    }
179046  
179047    return rc;
179048  }
179049  
179050  typedef struct IncrmergeWriter IncrmergeWriter;
179051  typedef struct NodeWriter NodeWriter;
179052  typedef struct Blob Blob;
179053  typedef struct NodeReader NodeReader;
179054  
179055  /*
179056  ** An instance of the following structure is used as a dynamic buffer
179057  ** to build up nodes or other blobs of data in.
179058  **
179059  ** The function blobGrowBuffer() is used to extend the allocation.
179060  */
179061  struct Blob {
179062    char *a;                        /* Pointer to allocation */
179063    int n;                          /* Number of valid bytes of data in a[] */
179064    int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
179065  };
179066  
179067  /*
179068  ** This structure is used to build up buffers containing segment b-tree 
179069  ** nodes (blocks).
179070  */
179071  struct NodeWriter {
179072    sqlite3_int64 iBlock;           /* Current block id */
179073    Blob key;                       /* Last key written to the current block */
179074    Blob block;                     /* Current block image */
179075  };
179076  
179077  /*
179078  ** An object of this type contains the state required to create or append
179079  ** to an appendable b-tree segment.
179080  */
179081  struct IncrmergeWriter {
179082    int nLeafEst;                   /* Space allocated for leaf blocks */
179083    int nWork;                      /* Number of leaf pages flushed */
179084    sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
179085    int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
179086    sqlite3_int64 iStart;           /* Block number of first allocated block */
179087    sqlite3_int64 iEnd;             /* Block number of last allocated block */
179088    sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
179089    u8 bNoLeafData;                 /* If true, store 0 for segment size */
179090    NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
179091  };
179092  
179093  /*
179094  ** An object of the following type is used to read data from a single
179095  ** FTS segment node. See the following functions:
179096  **
179097  **     nodeReaderInit()
179098  **     nodeReaderNext()
179099  **     nodeReaderRelease()
179100  */
179101  struct NodeReader {
179102    const char *aNode;
179103    int nNode;
179104    int iOff;                       /* Current offset within aNode[] */
179105  
179106    /* Output variables. Containing the current node entry. */
179107    sqlite3_int64 iChild;           /* Pointer to child node */
179108    Blob term;                      /* Current term */
179109    const char *aDoclist;           /* Pointer to doclist */
179110    int nDoclist;                   /* Size of doclist in bytes */
179111  };
179112  
179113  /*
179114  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
179115  ** Otherwise, if the allocation at pBlob->a is not already at least nMin
179116  ** bytes in size, extend (realloc) it to be so.
179117  **
179118  ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
179119  ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
179120  ** to reflect the new size of the pBlob->a[] buffer.
179121  */
179122  static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
179123    if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
179124      int nAlloc = nMin;
179125      char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
179126      if( a ){
179127        pBlob->nAlloc = nAlloc;
179128        pBlob->a = a;
179129      }else{
179130        *pRc = SQLITE_NOMEM;
179131      }
179132    }
179133  }
179134  
179135  /*
179136  ** Attempt to advance the node-reader object passed as the first argument to
179137  ** the next entry on the node. 
179138  **
179139  ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
179140  ** Otherwise return SQLITE_OK. If there is no next entry on the node
179141  ** (e.g. because the current entry is the last) set NodeReader->aNode to
179142  ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
179143  ** variables for the new entry.
179144  */
179145  static int nodeReaderNext(NodeReader *p){
179146    int bFirst = (p->term.n==0);    /* True for first term on the node */
179147    int nPrefix = 0;                /* Bytes to copy from previous term */
179148    int nSuffix = 0;                /* Bytes to append to the prefix */
179149    int rc = SQLITE_OK;             /* Return code */
179150  
179151    assert( p->aNode );
179152    if( p->iChild && bFirst==0 ) p->iChild++;
179153    if( p->iOff>=p->nNode ){
179154      /* EOF */
179155      p->aNode = 0;
179156    }else{
179157      if( bFirst==0 ){
179158        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
179159      }
179160      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
179161  
179162      if( nPrefix>p->iOff || nSuffix>p->nNode-p->iOff ){
179163        return FTS_CORRUPT_VTAB;
179164      }
179165      blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
179166      if( rc==SQLITE_OK ){
179167        memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
179168        p->term.n = nPrefix+nSuffix;
179169        p->iOff += nSuffix;
179170        if( p->iChild==0 ){
179171          p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
179172          if( (p->nNode-p->iOff)<p->nDoclist ){
179173            return FTS_CORRUPT_VTAB;
179174          }
179175          p->aDoclist = &p->aNode[p->iOff];
179176          p->iOff += p->nDoclist;
179177        }
179178      }
179179    }
179180  
179181    assert( p->iOff<=p->nNode );
179182    return rc;
179183  }
179184  
179185  /*
179186  ** Release all dynamic resources held by node-reader object *p.
179187  */
179188  static void nodeReaderRelease(NodeReader *p){
179189    sqlite3_free(p->term.a);
179190  }
179191  
179192  /*
179193  ** Initialize a node-reader object to read the node in buffer aNode/nNode.
179194  **
179195  ** If successful, SQLITE_OK is returned and the NodeReader object set to 
179196  ** point to the first entry on the node (if any). Otherwise, an SQLite
179197  ** error code is returned.
179198  */
179199  static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
179200    memset(p, 0, sizeof(NodeReader));
179201    p->aNode = aNode;
179202    p->nNode = nNode;
179203  
179204    /* Figure out if this is a leaf or an internal node. */
179205    if( p->aNode[0] ){
179206      /* An internal node. */
179207      p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
179208    }else{
179209      p->iOff = 1;
179210    }
179211  
179212    return nodeReaderNext(p);
179213  }
179214  
179215  /*
179216  ** This function is called while writing an FTS segment each time a leaf o
179217  ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
179218  ** to be greater than the largest key on the node just written, but smaller
179219  ** than or equal to the first key that will be written to the next leaf
179220  ** node.
179221  **
179222  ** The block id of the leaf node just written to disk may be found in
179223  ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
179224  */
179225  static int fts3IncrmergePush(
179226    Fts3Table *p,                   /* Fts3 table handle */
179227    IncrmergeWriter *pWriter,       /* Writer object */
179228    const char *zTerm,              /* Term to write to internal node */
179229    int nTerm                       /* Bytes at zTerm */
179230  ){
179231    sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
179232    int iLayer;
179233  
179234    assert( nTerm>0 );
179235    for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
179236      sqlite3_int64 iNextPtr = 0;
179237      NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
179238      int rc = SQLITE_OK;
179239      int nPrefix;
179240      int nSuffix;
179241      int nSpace;
179242  
179243      /* Figure out how much space the key will consume if it is written to
179244      ** the current node of layer iLayer. Due to the prefix compression, 
179245      ** the space required changes depending on which node the key is to
179246      ** be added to.  */
179247      nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
179248      nSuffix = nTerm - nPrefix;
179249      nSpace  = sqlite3Fts3VarintLen(nPrefix);
179250      nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
179251  
179252      if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
179253        /* If the current node of layer iLayer contains zero keys, or if adding
179254        ** the key to it will not cause it to grow to larger than nNodeSize 
179255        ** bytes in size, write the key here.  */
179256  
179257        Blob *pBlk = &pNode->block;
179258        if( pBlk->n==0 ){
179259          blobGrowBuffer(pBlk, p->nNodeSize, &rc);
179260          if( rc==SQLITE_OK ){
179261            pBlk->a[0] = (char)iLayer;
179262            pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
179263          }
179264        }
179265        blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
179266        blobGrowBuffer(&pNode->key, nTerm, &rc);
179267  
179268        if( rc==SQLITE_OK ){
179269          if( pNode->key.n ){
179270            pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
179271          }
179272          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
179273          memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
179274          pBlk->n += nSuffix;
179275  
179276          memcpy(pNode->key.a, zTerm, nTerm);
179277          pNode->key.n = nTerm;
179278        }
179279      }else{
179280        /* Otherwise, flush the current node of layer iLayer to disk.
179281        ** Then allocate a new, empty sibling node. The key will be written
179282        ** into the parent of this node. */
179283        rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
179284  
179285        assert( pNode->block.nAlloc>=p->nNodeSize );
179286        pNode->block.a[0] = (char)iLayer;
179287        pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
179288  
179289        iNextPtr = pNode->iBlock;
179290        pNode->iBlock++;
179291        pNode->key.n = 0;
179292      }
179293  
179294      if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
179295      iPtr = iNextPtr;
179296    }
179297  
179298    assert( 0 );
179299    return 0;
179300  }
179301  
179302  /*
179303  ** Append a term and (optionally) doclist to the FTS segment node currently
179304  ** stored in blob *pNode. The node need not contain any terms, but the
179305  ** header must be written before this function is called.
179306  **
179307  ** A node header is a single 0x00 byte for a leaf node, or a height varint
179308  ** followed by the left-hand-child varint for an internal node.
179309  **
179310  ** The term to be appended is passed via arguments zTerm/nTerm. For a 
179311  ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
179312  ** node, both aDoclist and nDoclist must be passed 0.
179313  **
179314  ** If the size of the value in blob pPrev is zero, then this is the first
179315  ** term written to the node. Otherwise, pPrev contains a copy of the 
179316  ** previous term. Before this function returns, it is updated to contain a
179317  ** copy of zTerm/nTerm.
179318  **
179319  ** It is assumed that the buffer associated with pNode is already large
179320  ** enough to accommodate the new entry. The buffer associated with pPrev
179321  ** is extended by this function if requrired.
179322  **
179323  ** If an error (i.e. OOM condition) occurs, an SQLite error code is
179324  ** returned. Otherwise, SQLITE_OK.
179325  */
179326  static int fts3AppendToNode(
179327    Blob *pNode,                    /* Current node image to append to */
179328    Blob *pPrev,                    /* Buffer containing previous term written */
179329    const char *zTerm,              /* New term to write */
179330    int nTerm,                      /* Size of zTerm in bytes */
179331    const char *aDoclist,           /* Doclist (or NULL) to write */
179332    int nDoclist                    /* Size of aDoclist in bytes */ 
179333  ){
179334    int rc = SQLITE_OK;             /* Return code */
179335    int bFirst = (pPrev->n==0);     /* True if this is the first term written */
179336    int nPrefix;                    /* Size of term prefix in bytes */
179337    int nSuffix;                    /* Size of term suffix in bytes */
179338  
179339    /* Node must have already been started. There must be a doclist for a
179340    ** leaf node, and there must not be a doclist for an internal node.  */
179341    assert( pNode->n>0 );
179342    assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
179343  
179344    blobGrowBuffer(pPrev, nTerm, &rc);
179345    if( rc!=SQLITE_OK ) return rc;
179346  
179347    nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
179348    nSuffix = nTerm - nPrefix;
179349    memcpy(pPrev->a, zTerm, nTerm);
179350    pPrev->n = nTerm;
179351  
179352    if( bFirst==0 ){
179353      pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
179354    }
179355    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
179356    memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
179357    pNode->n += nSuffix;
179358  
179359    if( aDoclist ){
179360      pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
179361      memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
179362      pNode->n += nDoclist;
179363    }
179364  
179365    assert( pNode->n<=pNode->nAlloc );
179366  
179367    return SQLITE_OK;
179368  }
179369  
179370  /*
179371  ** Append the current term and doclist pointed to by cursor pCsr to the
179372  ** appendable b-tree segment opened for writing by pWriter.
179373  **
179374  ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
179375  */
179376  static int fts3IncrmergeAppend(
179377    Fts3Table *p,                   /* Fts3 table handle */
179378    IncrmergeWriter *pWriter,       /* Writer object */
179379    Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
179380  ){
179381    const char *zTerm = pCsr->zTerm;
179382    int nTerm = pCsr->nTerm;
179383    const char *aDoclist = pCsr->aDoclist;
179384    int nDoclist = pCsr->nDoclist;
179385    int rc = SQLITE_OK;           /* Return code */
179386    int nSpace;                   /* Total space in bytes required on leaf */
179387    int nPrefix;                  /* Size of prefix shared with previous term */
179388    int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
179389    NodeWriter *pLeaf;            /* Object used to write leaf nodes */
179390  
179391    pLeaf = &pWriter->aNodeWriter[0];
179392    nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
179393    nSuffix = nTerm - nPrefix;
179394  
179395    nSpace  = sqlite3Fts3VarintLen(nPrefix);
179396    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
179397    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
179398  
179399    /* If the current block is not empty, and if adding this term/doclist
179400    ** to the current block would make it larger than Fts3Table.nNodeSize
179401    ** bytes, write this block out to the database. */
179402    if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
179403      rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
179404      pWriter->nWork++;
179405  
179406      /* Add the current term to the parent node. The term added to the 
179407      ** parent must:
179408      **
179409      **   a) be greater than the largest term on the leaf node just written
179410      **      to the database (still available in pLeaf->key), and
179411      **
179412      **   b) be less than or equal to the term about to be added to the new
179413      **      leaf node (zTerm/nTerm).
179414      **
179415      ** In other words, it must be the prefix of zTerm 1 byte longer than
179416      ** the common prefix (if any) of zTerm and pWriter->zTerm.
179417      */
179418      if( rc==SQLITE_OK ){
179419        rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
179420      }
179421  
179422      /* Advance to the next output block */
179423      pLeaf->iBlock++;
179424      pLeaf->key.n = 0;
179425      pLeaf->block.n = 0;
179426  
179427      nSuffix = nTerm;
179428      nSpace  = 1;
179429      nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
179430      nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
179431    }
179432  
179433    pWriter->nLeafData += nSpace;
179434    blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
179435    if( rc==SQLITE_OK ){
179436      if( pLeaf->block.n==0 ){
179437        pLeaf->block.n = 1;
179438        pLeaf->block.a[0] = '\0';
179439      }
179440      rc = fts3AppendToNode(
179441          &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
179442      );
179443    }
179444  
179445    return rc;
179446  }
179447  
179448  /*
179449  ** This function is called to release all dynamic resources held by the
179450  ** merge-writer object pWriter, and if no error has occurred, to flush
179451  ** all outstanding node buffers held by pWriter to disk.
179452  **
179453  ** If *pRc is not SQLITE_OK when this function is called, then no attempt
179454  ** is made to write any data to disk. Instead, this function serves only
179455  ** to release outstanding resources.
179456  **
179457  ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
179458  ** flushing buffers to disk, *pRc is set to an SQLite error code before
179459  ** returning.
179460  */
179461  static void fts3IncrmergeRelease(
179462    Fts3Table *p,                   /* FTS3 table handle */
179463    IncrmergeWriter *pWriter,       /* Merge-writer object */
179464    int *pRc                        /* IN/OUT: Error code */
179465  ){
179466    int i;                          /* Used to iterate through non-root layers */
179467    int iRoot;                      /* Index of root in pWriter->aNodeWriter */
179468    NodeWriter *pRoot;              /* NodeWriter for root node */
179469    int rc = *pRc;                  /* Error code */
179470  
179471    /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
179472    ** root node. If the segment fits entirely on a single leaf node, iRoot
179473    ** will be set to 0. If the root node is the parent of the leaves, iRoot
179474    ** will be 1. And so on.  */
179475    for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
179476      NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
179477      if( pNode->block.n>0 ) break;
179478      assert( *pRc || pNode->block.nAlloc==0 );
179479      assert( *pRc || pNode->key.nAlloc==0 );
179480      sqlite3_free(pNode->block.a);
179481      sqlite3_free(pNode->key.a);
179482    }
179483  
179484    /* Empty output segment. This is a no-op. */
179485    if( iRoot<0 ) return;
179486  
179487    /* The entire output segment fits on a single node. Normally, this means
179488    ** the node would be stored as a blob in the "root" column of the %_segdir
179489    ** table. However, this is not permitted in this case. The problem is that 
179490    ** space has already been reserved in the %_segments table, and so the 
179491    ** start_block and end_block fields of the %_segdir table must be populated. 
179492    ** And, by design or by accident, released versions of FTS cannot handle 
179493    ** segments that fit entirely on the root node with start_block!=0.
179494    **
179495    ** Instead, create a synthetic root node that contains nothing but a 
179496    ** pointer to the single content node. So that the segment consists of a
179497    ** single leaf and a single interior (root) node.
179498    **
179499    ** Todo: Better might be to defer allocating space in the %_segments 
179500    ** table until we are sure it is needed.
179501    */
179502    if( iRoot==0 ){
179503      Blob *pBlock = &pWriter->aNodeWriter[1].block;
179504      blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
179505      if( rc==SQLITE_OK ){
179506        pBlock->a[0] = 0x01;
179507        pBlock->n = 1 + sqlite3Fts3PutVarint(
179508            &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
179509        );
179510      }
179511      iRoot = 1;
179512    }
179513    pRoot = &pWriter->aNodeWriter[iRoot];
179514  
179515    /* Flush all currently outstanding nodes to disk. */
179516    for(i=0; i<iRoot; i++){
179517      NodeWriter *pNode = &pWriter->aNodeWriter[i];
179518      if( pNode->block.n>0 && rc==SQLITE_OK ){
179519        rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
179520      }
179521      sqlite3_free(pNode->block.a);
179522      sqlite3_free(pNode->key.a);
179523    }
179524  
179525    /* Write the %_segdir record. */
179526    if( rc==SQLITE_OK ){
179527      rc = fts3WriteSegdir(p, 
179528          pWriter->iAbsLevel+1,               /* level */
179529          pWriter->iIdx,                      /* idx */
179530          pWriter->iStart,                    /* start_block */
179531          pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
179532          pWriter->iEnd,                      /* end_block */
179533          (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
179534          pRoot->block.a, pRoot->block.n      /* root */
179535      );
179536    }
179537    sqlite3_free(pRoot->block.a);
179538    sqlite3_free(pRoot->key.a);
179539  
179540    *pRc = rc;
179541  }
179542  
179543  /*
179544  ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
179545  ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
179546  ** the other, it is considered to be smaller than the other.
179547  **
179548  ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
179549  ** if it is greater.
179550  */
179551  static int fts3TermCmp(
179552    const char *zLhs, int nLhs,     /* LHS of comparison */
179553    const char *zRhs, int nRhs      /* RHS of comparison */
179554  ){
179555    int nCmp = MIN(nLhs, nRhs);
179556    int res;
179557  
179558    res = memcmp(zLhs, zRhs, nCmp);
179559    if( res==0 ) res = nLhs - nRhs;
179560  
179561    return res;
179562  }
179563  
179564  
179565  /*
179566  ** Query to see if the entry in the %_segments table with blockid iEnd is 
179567  ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
179568  ** returning. Otherwise, set *pbRes to 0. 
179569  **
179570  ** Or, if an error occurs while querying the database, return an SQLite 
179571  ** error code. The final value of *pbRes is undefined in this case.
179572  **
179573  ** This is used to test if a segment is an "appendable" segment. If it
179574  ** is, then a NULL entry has been inserted into the %_segments table
179575  ** with blockid %_segdir.end_block.
179576  */
179577  static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
179578    int bRes = 0;                   /* Result to set *pbRes to */
179579    sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
179580    int rc;                         /* Return code */
179581  
179582    rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
179583    if( rc==SQLITE_OK ){
179584      sqlite3_bind_int64(pCheck, 1, iEnd);
179585      if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
179586      rc = sqlite3_reset(pCheck);
179587    }
179588    
179589    *pbRes = bRes;
179590    return rc;
179591  }
179592  
179593  /*
179594  ** This function is called when initializing an incremental-merge operation.
179595  ** It checks if the existing segment with index value iIdx at absolute level 
179596  ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
179597  ** merge-writer object *pWriter is initialized to write to it.
179598  **
179599  ** An existing segment can be appended to by an incremental merge if:
179600  **
179601  **   * It was initially created as an appendable segment (with all required
179602  **     space pre-allocated), and
179603  **
179604  **   * The first key read from the input (arguments zKey and nKey) is 
179605  **     greater than the largest key currently stored in the potential
179606  **     output segment.
179607  */
179608  static int fts3IncrmergeLoad(
179609    Fts3Table *p,                   /* Fts3 table handle */
179610    sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
179611    int iIdx,                       /* Index of candidate output segment */
179612    const char *zKey,               /* First key to write */
179613    int nKey,                       /* Number of bytes in nKey */
179614    IncrmergeWriter *pWriter        /* Populate this object */
179615  ){
179616    int rc;                         /* Return code */
179617    sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
179618  
179619    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
179620    if( rc==SQLITE_OK ){
179621      sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
179622      sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
179623      sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
179624      const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
179625      int nRoot = 0;                /* Size of aRoot[] in bytes */
179626      int rc2;                      /* Return code from sqlite3_reset() */
179627      int bAppendable = 0;          /* Set to true if segment is appendable */
179628  
179629      /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
179630      sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
179631      sqlite3_bind_int(pSelect, 2, iIdx);
179632      if( sqlite3_step(pSelect)==SQLITE_ROW ){
179633        iStart = sqlite3_column_int64(pSelect, 1);
179634        iLeafEnd = sqlite3_column_int64(pSelect, 2);
179635        fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
179636        if( pWriter->nLeafData<0 ){
179637          pWriter->nLeafData = pWriter->nLeafData * -1;
179638        }
179639        pWriter->bNoLeafData = (pWriter->nLeafData==0);
179640        nRoot = sqlite3_column_bytes(pSelect, 4);
179641        aRoot = sqlite3_column_blob(pSelect, 4);
179642      }else{
179643        return sqlite3_reset(pSelect);
179644      }
179645  
179646      /* Check for the zero-length marker in the %_segments table */
179647      rc = fts3IsAppendable(p, iEnd, &bAppendable);
179648  
179649      /* Check that zKey/nKey is larger than the largest key the candidate */
179650      if( rc==SQLITE_OK && bAppendable ){
179651        char *aLeaf = 0;
179652        int nLeaf = 0;
179653  
179654        rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
179655        if( rc==SQLITE_OK ){
179656          NodeReader reader;
179657          for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
179658              rc==SQLITE_OK && reader.aNode;
179659              rc = nodeReaderNext(&reader)
179660          ){
179661            assert( reader.aNode );
179662          }
179663          if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
179664            bAppendable = 0;
179665          }
179666          nodeReaderRelease(&reader);
179667        }
179668        sqlite3_free(aLeaf);
179669      }
179670  
179671      if( rc==SQLITE_OK && bAppendable ){
179672        /* It is possible to append to this segment. Set up the IncrmergeWriter
179673        ** object to do so.  */
179674        int i;
179675        int nHeight = (int)aRoot[0];
179676        NodeWriter *pNode;
179677  
179678        pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
179679        pWriter->iStart = iStart;
179680        pWriter->iEnd = iEnd;
179681        pWriter->iAbsLevel = iAbsLevel;
179682        pWriter->iIdx = iIdx;
179683  
179684        for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
179685          pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
179686        }
179687  
179688        pNode = &pWriter->aNodeWriter[nHeight];
179689        pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
179690        blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
179691        if( rc==SQLITE_OK ){
179692          memcpy(pNode->block.a, aRoot, nRoot);
179693          pNode->block.n = nRoot;
179694        }
179695  
179696        for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
179697          NodeReader reader;
179698          pNode = &pWriter->aNodeWriter[i];
179699  
179700          rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
179701          while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
179702          blobGrowBuffer(&pNode->key, reader.term.n, &rc);
179703          if( rc==SQLITE_OK ){
179704            memcpy(pNode->key.a, reader.term.a, reader.term.n);
179705            pNode->key.n = reader.term.n;
179706            if( i>0 ){
179707              char *aBlock = 0;
179708              int nBlock = 0;
179709              pNode = &pWriter->aNodeWriter[i-1];
179710              pNode->iBlock = reader.iChild;
179711              rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
179712              blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
179713              if( rc==SQLITE_OK ){
179714                memcpy(pNode->block.a, aBlock, nBlock);
179715                pNode->block.n = nBlock;
179716              }
179717              sqlite3_free(aBlock);
179718            }
179719          }
179720          nodeReaderRelease(&reader);
179721        }
179722      }
179723  
179724      rc2 = sqlite3_reset(pSelect);
179725      if( rc==SQLITE_OK ) rc = rc2;
179726    }
179727  
179728    return rc;
179729  }
179730  
179731  /*
179732  ** Determine the largest segment index value that exists within absolute
179733  ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
179734  ** one before returning SQLITE_OK. Or, if there are no segments at all 
179735  ** within level iAbsLevel, set *piIdx to zero.
179736  **
179737  ** If an error occurs, return an SQLite error code. The final value of
179738  ** *piIdx is undefined in this case.
179739  */
179740  static int fts3IncrmergeOutputIdx( 
179741    Fts3Table *p,                   /* FTS Table handle */
179742    sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
179743    int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
179744  ){
179745    int rc;
179746    sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
179747  
179748    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
179749    if( rc==SQLITE_OK ){
179750      sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
179751      sqlite3_step(pOutputIdx);
179752      *piIdx = sqlite3_column_int(pOutputIdx, 0);
179753      rc = sqlite3_reset(pOutputIdx);
179754    }
179755  
179756    return rc;
179757  }
179758  
179759  /* 
179760  ** Allocate an appendable output segment on absolute level iAbsLevel+1
179761  ** with idx value iIdx.
179762  **
179763  ** In the %_segdir table, a segment is defined by the values in three
179764  ** columns:
179765  **
179766  **     start_block
179767  **     leaves_end_block
179768  **     end_block
179769  **
179770  ** When an appendable segment is allocated, it is estimated that the
179771  ** maximum number of leaf blocks that may be required is the sum of the
179772  ** number of leaf blocks consumed by the input segments, plus the number
179773  ** of input segments, multiplied by two. This value is stored in stack 
179774  ** variable nLeafEst.
179775  **
179776  ** A total of 16*nLeafEst blocks are allocated when an appendable segment
179777  ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
179778  ** array of leaf nodes starts at the first block allocated. The array
179779  ** of interior nodes that are parents of the leaf nodes start at block
179780  ** (start_block + (1 + end_block - start_block) / 16). And so on.
179781  **
179782  ** In the actual code below, the value "16" is replaced with the 
179783  ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
179784  */
179785  static int fts3IncrmergeWriter( 
179786    Fts3Table *p,                   /* Fts3 table handle */
179787    sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
179788    int iIdx,                       /* Index of new output segment */
179789    Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
179790    IncrmergeWriter *pWriter        /* Populate this object */
179791  ){
179792    int rc;                         /* Return Code */
179793    int i;                          /* Iterator variable */
179794    int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
179795    sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
179796    sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
179797  
179798    /* Calculate nLeafEst. */
179799    rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
179800    if( rc==SQLITE_OK ){
179801      sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
179802      sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
179803      if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
179804        nLeafEst = sqlite3_column_int(pLeafEst, 0);
179805      }
179806      rc = sqlite3_reset(pLeafEst);
179807    }
179808    if( rc!=SQLITE_OK ) return rc;
179809  
179810    /* Calculate the first block to use in the output segment */
179811    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
179812    if( rc==SQLITE_OK ){
179813      if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
179814        pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
179815        pWriter->iEnd = pWriter->iStart - 1;
179816        pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
179817      }
179818      rc = sqlite3_reset(pFirstBlock);
179819    }
179820    if( rc!=SQLITE_OK ) return rc;
179821  
179822    /* Insert the marker in the %_segments table to make sure nobody tries
179823    ** to steal the space just allocated. This is also used to identify 
179824    ** appendable segments.  */
179825    rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
179826    if( rc!=SQLITE_OK ) return rc;
179827  
179828    pWriter->iAbsLevel = iAbsLevel;
179829    pWriter->nLeafEst = nLeafEst;
179830    pWriter->iIdx = iIdx;
179831  
179832    /* Set up the array of NodeWriter objects */
179833    for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
179834      pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
179835    }
179836    return SQLITE_OK;
179837  }
179838  
179839  /*
179840  ** Remove an entry from the %_segdir table. This involves running the 
179841  ** following two statements:
179842  **
179843  **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
179844  **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
179845  **
179846  ** The DELETE statement removes the specific %_segdir level. The UPDATE 
179847  ** statement ensures that the remaining segments have contiguously allocated
179848  ** idx values.
179849  */
179850  static int fts3RemoveSegdirEntry(
179851    Fts3Table *p,                   /* FTS3 table handle */
179852    sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
179853    int iIdx                        /* Index of %_segdir entry to delete */
179854  ){
179855    int rc;                         /* Return code */
179856    sqlite3_stmt *pDelete = 0;      /* DELETE statement */
179857  
179858    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
179859    if( rc==SQLITE_OK ){
179860      sqlite3_bind_int64(pDelete, 1, iAbsLevel);
179861      sqlite3_bind_int(pDelete, 2, iIdx);
179862      sqlite3_step(pDelete);
179863      rc = sqlite3_reset(pDelete);
179864    }
179865  
179866    return rc;
179867  }
179868  
179869  /*
179870  ** One or more segments have just been removed from absolute level iAbsLevel.
179871  ** Update the 'idx' values of the remaining segments in the level so that
179872  ** the idx values are a contiguous sequence starting from 0.
179873  */
179874  static int fts3RepackSegdirLevel(
179875    Fts3Table *p,                   /* FTS3 table handle */
179876    sqlite3_int64 iAbsLevel         /* Absolute level to repack */
179877  ){
179878    int rc;                         /* Return code */
179879    int *aIdx = 0;                  /* Array of remaining idx values */
179880    int nIdx = 0;                   /* Valid entries in aIdx[] */
179881    int nAlloc = 0;                 /* Allocated size of aIdx[] */
179882    int i;                          /* Iterator variable */
179883    sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
179884    sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
179885  
179886    rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
179887    if( rc==SQLITE_OK ){
179888      int rc2;
179889      sqlite3_bind_int64(pSelect, 1, iAbsLevel);
179890      while( SQLITE_ROW==sqlite3_step(pSelect) ){
179891        if( nIdx>=nAlloc ){
179892          int *aNew;
179893          nAlloc += 16;
179894          aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
179895          if( !aNew ){
179896            rc = SQLITE_NOMEM;
179897            break;
179898          }
179899          aIdx = aNew;
179900        }
179901        aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
179902      }
179903      rc2 = sqlite3_reset(pSelect);
179904      if( rc==SQLITE_OK ) rc = rc2;
179905    }
179906  
179907    if( rc==SQLITE_OK ){
179908      rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
179909    }
179910    if( rc==SQLITE_OK ){
179911      sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
179912    }
179913  
179914    assert( p->bIgnoreSavepoint==0 );
179915    p->bIgnoreSavepoint = 1;
179916    for(i=0; rc==SQLITE_OK && i<nIdx; i++){
179917      if( aIdx[i]!=i ){
179918        sqlite3_bind_int(pUpdate, 3, aIdx[i]);
179919        sqlite3_bind_int(pUpdate, 1, i);
179920        sqlite3_step(pUpdate);
179921        rc = sqlite3_reset(pUpdate);
179922      }
179923    }
179924    p->bIgnoreSavepoint = 0;
179925  
179926    sqlite3_free(aIdx);
179927    return rc;
179928  }
179929  
179930  static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
179931    pNode->a[0] = (char)iHeight;
179932    if( iChild ){
179933      assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
179934      pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
179935    }else{
179936      assert( pNode->nAlloc>=1 );
179937      pNode->n = 1;
179938    }
179939  }
179940  
179941  /*
179942  ** The first two arguments are a pointer to and the size of a segment b-tree
179943  ** node. The node may be a leaf or an internal node.
179944  **
179945  ** This function creates a new node image in blob object *pNew by copying
179946  ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
179947  ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
179948  */
179949  static int fts3TruncateNode(
179950    const char *aNode,              /* Current node image */
179951    int nNode,                      /* Size of aNode in bytes */
179952    Blob *pNew,                     /* OUT: Write new node image here */
179953    const char *zTerm,              /* Omit all terms smaller than this */
179954    int nTerm,                      /* Size of zTerm in bytes */
179955    sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
179956  ){
179957    NodeReader reader;              /* Reader object */
179958    Blob prev = {0, 0, 0};          /* Previous term written to new node */
179959    int rc = SQLITE_OK;             /* Return code */
179960    int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
179961  
179962    /* Allocate required output space */
179963    blobGrowBuffer(pNew, nNode, &rc);
179964    if( rc!=SQLITE_OK ) return rc;
179965    pNew->n = 0;
179966  
179967    /* Populate new node buffer */
179968    for(rc = nodeReaderInit(&reader, aNode, nNode); 
179969        rc==SQLITE_OK && reader.aNode; 
179970        rc = nodeReaderNext(&reader)
179971    ){
179972      if( pNew->n==0 ){
179973        int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
179974        if( res<0 || (bLeaf==0 && res==0) ) continue;
179975        fts3StartNode(pNew, (int)aNode[0], reader.iChild);
179976        *piBlock = reader.iChild;
179977      }
179978      rc = fts3AppendToNode(
179979          pNew, &prev, reader.term.a, reader.term.n,
179980          reader.aDoclist, reader.nDoclist
179981      );
179982      if( rc!=SQLITE_OK ) break;
179983    }
179984    if( pNew->n==0 ){
179985      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
179986      *piBlock = reader.iChild;
179987    }
179988    assert( pNew->n<=pNew->nAlloc );
179989  
179990    nodeReaderRelease(&reader);
179991    sqlite3_free(prev.a);
179992    return rc;
179993  }
179994  
179995  /*
179996  ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
179997  ** level iAbsLevel. This may involve deleting entries from the %_segments
179998  ** table, and modifying existing entries in both the %_segments and %_segdir
179999  ** tables.
180000  **
180001  ** SQLITE_OK is returned if the segment is updated successfully. Or an
180002  ** SQLite error code otherwise.
180003  */
180004  static int fts3TruncateSegment(
180005    Fts3Table *p,                   /* FTS3 table handle */
180006    sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
180007    int iIdx,                       /* Index within level of segment to modify */
180008    const char *zTerm,              /* Remove terms smaller than this */
180009    int nTerm                      /* Number of bytes in buffer zTerm */
180010  ){
180011    int rc = SQLITE_OK;             /* Return code */
180012    Blob root = {0,0,0};            /* New root page image */
180013    Blob block = {0,0,0};           /* Buffer used for any other block */
180014    sqlite3_int64 iBlock = 0;       /* Block id */
180015    sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
180016    sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
180017    sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
180018  
180019    rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
180020    if( rc==SQLITE_OK ){
180021      int rc2;                      /* sqlite3_reset() return code */
180022      sqlite3_bind_int64(pFetch, 1, iAbsLevel);
180023      sqlite3_bind_int(pFetch, 2, iIdx);
180024      if( SQLITE_ROW==sqlite3_step(pFetch) ){
180025        const char *aRoot = sqlite3_column_blob(pFetch, 4);
180026        int nRoot = sqlite3_column_bytes(pFetch, 4);
180027        iOldStart = sqlite3_column_int64(pFetch, 1);
180028        rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
180029      }
180030      rc2 = sqlite3_reset(pFetch);
180031      if( rc==SQLITE_OK ) rc = rc2;
180032    }
180033  
180034    while( rc==SQLITE_OK && iBlock ){
180035      char *aBlock = 0;
180036      int nBlock = 0;
180037      iNewStart = iBlock;
180038  
180039      rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
180040      if( rc==SQLITE_OK ){
180041        rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
180042      }
180043      if( rc==SQLITE_OK ){
180044        rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
180045      }
180046      sqlite3_free(aBlock);
180047    }
180048  
180049    /* Variable iNewStart now contains the first valid leaf node. */
180050    if( rc==SQLITE_OK && iNewStart ){
180051      sqlite3_stmt *pDel = 0;
180052      rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
180053      if( rc==SQLITE_OK ){
180054        sqlite3_bind_int64(pDel, 1, iOldStart);
180055        sqlite3_bind_int64(pDel, 2, iNewStart-1);
180056        sqlite3_step(pDel);
180057        rc = sqlite3_reset(pDel);
180058      }
180059    }
180060  
180061    if( rc==SQLITE_OK ){
180062      sqlite3_stmt *pChomp = 0;
180063      rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
180064      if( rc==SQLITE_OK ){
180065        sqlite3_bind_int64(pChomp, 1, iNewStart);
180066        sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
180067        sqlite3_bind_int64(pChomp, 3, iAbsLevel);
180068        sqlite3_bind_int(pChomp, 4, iIdx);
180069        sqlite3_step(pChomp);
180070        rc = sqlite3_reset(pChomp);
180071        sqlite3_bind_null(pChomp, 2);
180072      }
180073    }
180074  
180075    sqlite3_free(root.a);
180076    sqlite3_free(block.a);
180077    return rc;
180078  }
180079  
180080  /*
180081  ** This function is called after an incrmental-merge operation has run to
180082  ** merge (or partially merge) two or more segments from absolute level
180083  ** iAbsLevel.
180084  **
180085  ** Each input segment is either removed from the db completely (if all of
180086  ** its data was copied to the output segment by the incrmerge operation)
180087  ** or modified in place so that it no longer contains those entries that
180088  ** have been duplicated in the output segment.
180089  */
180090  static int fts3IncrmergeChomp(
180091    Fts3Table *p,                   /* FTS table handle */
180092    sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
180093    Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
180094    int *pnRem                      /* Number of segments not deleted */
180095  ){
180096    int i;
180097    int nRem = 0;
180098    int rc = SQLITE_OK;
180099  
180100    for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
180101      Fts3SegReader *pSeg = 0;
180102      int j;
180103  
180104      /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
180105      ** somewhere in the pCsr->apSegment[] array.  */
180106      for(j=0; ALWAYS(j<pCsr->nSegment); j++){
180107        pSeg = pCsr->apSegment[j];
180108        if( pSeg->iIdx==i ) break;
180109      }
180110      assert( j<pCsr->nSegment && pSeg->iIdx==i );
180111  
180112      if( pSeg->aNode==0 ){
180113        /* Seg-reader is at EOF. Remove the entire input segment. */
180114        rc = fts3DeleteSegment(p, pSeg);
180115        if( rc==SQLITE_OK ){
180116          rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
180117        }
180118        *pnRem = 0;
180119      }else{
180120        /* The incremental merge did not copy all the data from this 
180121        ** segment to the upper level. The segment is modified in place
180122        ** so that it contains no keys smaller than zTerm/nTerm. */ 
180123        const char *zTerm = pSeg->zTerm;
180124        int nTerm = pSeg->nTerm;
180125        rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
180126        nRem++;
180127      }
180128    }
180129  
180130    if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
180131      rc = fts3RepackSegdirLevel(p, iAbsLevel);
180132    }
180133  
180134    *pnRem = nRem;
180135    return rc;
180136  }
180137  
180138  /*
180139  ** Store an incr-merge hint in the database.
180140  */
180141  static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
180142    sqlite3_stmt *pReplace = 0;
180143    int rc;                         /* Return code */
180144  
180145    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
180146    if( rc==SQLITE_OK ){
180147      sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
180148      sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
180149      sqlite3_step(pReplace);
180150      rc = sqlite3_reset(pReplace);
180151      sqlite3_bind_null(pReplace, 2);
180152    }
180153  
180154    return rc;
180155  }
180156  
180157  /*
180158  ** Load an incr-merge hint from the database. The incr-merge hint, if one 
180159  ** exists, is stored in the rowid==1 row of the %_stat table.
180160  **
180161  ** If successful, populate blob *pHint with the value read from the %_stat
180162  ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
180163  ** SQLite error code.
180164  */
180165  static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
180166    sqlite3_stmt *pSelect = 0;
180167    int rc;
180168  
180169    pHint->n = 0;
180170    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
180171    if( rc==SQLITE_OK ){
180172      int rc2;
180173      sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
180174      if( SQLITE_ROW==sqlite3_step(pSelect) ){
180175        const char *aHint = sqlite3_column_blob(pSelect, 0);
180176        int nHint = sqlite3_column_bytes(pSelect, 0);
180177        if( aHint ){
180178          blobGrowBuffer(pHint, nHint, &rc);
180179          if( rc==SQLITE_OK ){
180180            memcpy(pHint->a, aHint, nHint);
180181            pHint->n = nHint;
180182          }
180183        }
180184      }
180185      rc2 = sqlite3_reset(pSelect);
180186      if( rc==SQLITE_OK ) rc = rc2;
180187    }
180188  
180189    return rc;
180190  }
180191  
180192  /*
180193  ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
180194  ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
180195  ** consists of two varints, the absolute level number of the input segments 
180196  ** and the number of input segments.
180197  **
180198  ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
180199  ** set *pRc to an SQLite error code before returning.
180200  */
180201  static void fts3IncrmergeHintPush(
180202    Blob *pHint,                    /* Hint blob to append to */
180203    i64 iAbsLevel,                  /* First varint to store in hint */
180204    int nInput,                     /* Second varint to store in hint */
180205    int *pRc                        /* IN/OUT: Error code */
180206  ){
180207    blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
180208    if( *pRc==SQLITE_OK ){
180209      pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
180210      pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
180211    }
180212  }
180213  
180214  /*
180215  ** Read the last entry (most recently pushed) from the hint blob *pHint
180216  ** and then remove the entry. Write the two values read to *piAbsLevel and 
180217  ** *pnInput before returning.
180218  **
180219  ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
180220  ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
180221  */
180222  static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
180223    const int nHint = pHint->n;
180224    int i;
180225  
180226    i = pHint->n-2;
180227    while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
180228    while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
180229  
180230    pHint->n = i;
180231    i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
180232    i += fts3GetVarint32(&pHint->a[i], pnInput);
180233    if( i!=nHint ) return FTS_CORRUPT_VTAB;
180234  
180235    return SQLITE_OK;
180236  }
180237  
180238  
180239  /*
180240  ** Attempt an incremental merge that writes nMerge leaf blocks.
180241  **
180242  ** Incremental merges happen nMin segments at a time. The segments 
180243  ** to be merged are the nMin oldest segments (the ones with the smallest 
180244  ** values for the _segdir.idx field) in the highest level that contains 
180245  ** at least nMin segments. Multiple merges might occur in an attempt to 
180246  ** write the quota of nMerge leaf blocks.
180247  */
180248  SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
180249    int rc;                         /* Return code */
180250    int nRem = nMerge;              /* Number of leaf pages yet to  be written */
180251    Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
180252    Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
180253    IncrmergeWriter *pWriter;       /* Writer object */
180254    int nSeg = 0;                   /* Number of input segments */
180255    sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
180256    Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
180257    int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
180258  
180259    /* Allocate space for the cursor, filter and writer objects */
180260    const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
180261    pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
180262    if( !pWriter ) return SQLITE_NOMEM;
180263    pFilter = (Fts3SegFilter *)&pWriter[1];
180264    pCsr = (Fts3MultiSegReader *)&pFilter[1];
180265  
180266    rc = fts3IncrmergeHintLoad(p, &hint);
180267    while( rc==SQLITE_OK && nRem>0 ){
180268      const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
180269      sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
180270      int bUseHint = 0;             /* True if attempting to append */
180271      int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
180272  
180273      /* Search the %_segdir table for the absolute level with the smallest
180274      ** relative level number that contains at least nMin segments, if any.
180275      ** If one is found, set iAbsLevel to the absolute level number and
180276      ** nSeg to nMin. If no level with at least nMin segments can be found, 
180277      ** set nSeg to -1.
180278      */
180279      rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
180280      sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
180281      if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
180282        iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
180283        nSeg = sqlite3_column_int(pFindLevel, 1);
180284        assert( nSeg>=2 );
180285      }else{
180286        nSeg = -1;
180287      }
180288      rc = sqlite3_reset(pFindLevel);
180289  
180290      /* If the hint read from the %_stat table is not empty, check if the
180291      ** last entry in it specifies a relative level smaller than or equal
180292      ** to the level identified by the block above (if any). If so, this 
180293      ** iteration of the loop will work on merging at the hinted level.
180294      */
180295      if( rc==SQLITE_OK && hint.n ){
180296        int nHint = hint.n;
180297        sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
180298        int nHintSeg = 0;                     /* Hint number of segments */
180299  
180300        rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
180301        if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
180302          iAbsLevel = iHintAbsLevel;
180303          nSeg = nHintSeg;
180304          bUseHint = 1;
180305          bDirtyHint = 1;
180306        }else{
180307          /* This undoes the effect of the HintPop() above - so that no entry
180308          ** is removed from the hint blob.  */
180309          hint.n = nHint;
180310        }
180311      }
180312  
180313      /* If nSeg is less that zero, then there is no level with at least
180314      ** nMin segments and no hint in the %_stat table. No work to do.
180315      ** Exit early in this case.  */
180316      if( nSeg<0 ) break;
180317  
180318      /* Open a cursor to iterate through the contents of the oldest nSeg 
180319      ** indexes of absolute level iAbsLevel. If this cursor is opened using 
180320      ** the 'hint' parameters, it is possible that there are less than nSeg
180321      ** segments available in level iAbsLevel. In this case, no work is
180322      ** done on iAbsLevel - fall through to the next iteration of the loop 
180323      ** to start work on some other level.  */
180324      memset(pWriter, 0, nAlloc);
180325      pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
180326  
180327      if( rc==SQLITE_OK ){
180328        rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
180329        assert( bUseHint==1 || bUseHint==0 );
180330        if( iIdx==0 || (bUseHint && iIdx==1) ){
180331          int bIgnore = 0;
180332          rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
180333          if( bIgnore ){
180334            pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
180335          }
180336        }
180337      }
180338  
180339      if( rc==SQLITE_OK ){
180340        rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
180341      }
180342      if( SQLITE_OK==rc && pCsr->nSegment==nSeg
180343       && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
180344       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
180345      ){
180346        if( bUseHint && iIdx>0 ){
180347          const char *zKey = pCsr->zTerm;
180348          int nKey = pCsr->nTerm;
180349          rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
180350        }else{
180351          rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
180352        }
180353  
180354        if( rc==SQLITE_OK && pWriter->nLeafEst ){
180355          fts3LogMerge(nSeg, iAbsLevel);
180356          do {
180357            rc = fts3IncrmergeAppend(p, pWriter, pCsr);
180358            if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
180359            if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
180360          }while( rc==SQLITE_ROW );
180361  
180362          /* Update or delete the input segments */
180363          if( rc==SQLITE_OK ){
180364            nRem -= (1 + pWriter->nWork);
180365            rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
180366            if( nSeg!=0 ){
180367              bDirtyHint = 1;
180368              fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
180369            }
180370          }
180371        }
180372  
180373        if( nSeg!=0 ){
180374          pWriter->nLeafData = pWriter->nLeafData * -1;
180375        }
180376        fts3IncrmergeRelease(p, pWriter, &rc);
180377        if( nSeg==0 && pWriter->bNoLeafData==0 ){
180378          fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
180379        }
180380      }
180381  
180382      sqlite3Fts3SegReaderFinish(pCsr);
180383    }
180384  
180385    /* Write the hint values into the %_stat table for the next incr-merger */
180386    if( bDirtyHint && rc==SQLITE_OK ){
180387      rc = fts3IncrmergeHintStore(p, &hint);
180388    }
180389  
180390    sqlite3_free(pWriter);
180391    sqlite3_free(hint.a);
180392    return rc;
180393  }
180394  
180395  /*
180396  ** Convert the text beginning at *pz into an integer and return
180397  ** its value.  Advance *pz to point to the first character past
180398  ** the integer.
180399  **
180400  ** This function used for parameters to merge= and incrmerge=
180401  ** commands. 
180402  */
180403  static int fts3Getint(const char **pz){
180404    const char *z = *pz;
180405    int i = 0;
180406    while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
180407    *pz = z;
180408    return i;
180409  }
180410  
180411  /*
180412  ** Process statements of the form:
180413  **
180414  **    INSERT INTO table(table) VALUES('merge=A,B');
180415  **
180416  ** A and B are integers that decode to be the number of leaf pages
180417  ** written for the merge, and the minimum number of segments on a level
180418  ** before it will be selected for a merge, respectively.
180419  */
180420  static int fts3DoIncrmerge(
180421    Fts3Table *p,                   /* FTS3 table handle */
180422    const char *zParam              /* Nul-terminated string containing "A,B" */
180423  ){
180424    int rc;
180425    int nMin = (FTS3_MERGE_COUNT / 2);
180426    int nMerge = 0;
180427    const char *z = zParam;
180428  
180429    /* Read the first integer value */
180430    nMerge = fts3Getint(&z);
180431  
180432    /* If the first integer value is followed by a ',',  read the second
180433    ** integer value. */
180434    if( z[0]==',' && z[1]!='\0' ){
180435      z++;
180436      nMin = fts3Getint(&z);
180437    }
180438  
180439    if( z[0]!='\0' || nMin<2 ){
180440      rc = SQLITE_ERROR;
180441    }else{
180442      rc = SQLITE_OK;
180443      if( !p->bHasStat ){
180444        assert( p->bFts4==0 );
180445        sqlite3Fts3CreateStatTable(&rc, p);
180446      }
180447      if( rc==SQLITE_OK ){
180448        rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
180449      }
180450      sqlite3Fts3SegmentsClose(p);
180451    }
180452    return rc;
180453  }
180454  
180455  /*
180456  ** Process statements of the form:
180457  **
180458  **    INSERT INTO table(table) VALUES('automerge=X');
180459  **
180460  ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
180461  ** turn it on.  The setting is persistent.
180462  */
180463  static int fts3DoAutoincrmerge(
180464    Fts3Table *p,                   /* FTS3 table handle */
180465    const char *zParam              /* Nul-terminated string containing boolean */
180466  ){
180467    int rc = SQLITE_OK;
180468    sqlite3_stmt *pStmt = 0;
180469    p->nAutoincrmerge = fts3Getint(&zParam);
180470    if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
180471      p->nAutoincrmerge = 8;
180472    }
180473    if( !p->bHasStat ){
180474      assert( p->bFts4==0 );
180475      sqlite3Fts3CreateStatTable(&rc, p);
180476      if( rc ) return rc;
180477    }
180478    rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
180479    if( rc ) return rc;
180480    sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
180481    sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
180482    sqlite3_step(pStmt);
180483    rc = sqlite3_reset(pStmt);
180484    return rc;
180485  }
180486  
180487  /*
180488  ** Return a 64-bit checksum for the FTS index entry specified by the
180489  ** arguments to this function.
180490  */
180491  static u64 fts3ChecksumEntry(
180492    const char *zTerm,              /* Pointer to buffer containing term */
180493    int nTerm,                      /* Size of zTerm in bytes */
180494    int iLangid,                    /* Language id for current row */
180495    int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
180496    i64 iDocid,                     /* Docid for current row. */
180497    int iCol,                       /* Column number */
180498    int iPos                        /* Position */
180499  ){
180500    int i;
180501    u64 ret = (u64)iDocid;
180502  
180503    ret += (ret<<3) + iLangid;
180504    ret += (ret<<3) + iIndex;
180505    ret += (ret<<3) + iCol;
180506    ret += (ret<<3) + iPos;
180507    for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
180508  
180509    return ret;
180510  }
180511  
180512  /*
180513  ** Return a checksum of all entries in the FTS index that correspond to
180514  ** language id iLangid. The checksum is calculated by XORing the checksums
180515  ** of each individual entry (see fts3ChecksumEntry()) together.
180516  **
180517  ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
180518  ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
180519  ** return value is undefined in this case.
180520  */
180521  static u64 fts3ChecksumIndex(
180522    Fts3Table *p,                   /* FTS3 table handle */
180523    int iLangid,                    /* Language id to return cksum for */
180524    int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
180525    int *pRc                        /* OUT: Return code */
180526  ){
180527    Fts3SegFilter filter;
180528    Fts3MultiSegReader csr;
180529    int rc;
180530    u64 cksum = 0;
180531  
180532    assert( *pRc==SQLITE_OK );
180533  
180534    memset(&filter, 0, sizeof(filter));
180535    memset(&csr, 0, sizeof(csr));
180536    filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
180537    filter.flags |= FTS3_SEGMENT_SCAN;
180538  
180539    rc = sqlite3Fts3SegReaderCursor(
180540        p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
180541    );
180542    if( rc==SQLITE_OK ){
180543      rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
180544    }
180545  
180546    if( rc==SQLITE_OK ){
180547      while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
180548        char *pCsr = csr.aDoclist;
180549        char *pEnd = &pCsr[csr.nDoclist];
180550  
180551        i64 iDocid = 0;
180552        i64 iCol = 0;
180553        i64 iPos = 0;
180554  
180555        pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
180556        while( pCsr<pEnd ){
180557          i64 iVal = 0;
180558          pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
180559          if( pCsr<pEnd ){
180560            if( iVal==0 || iVal==1 ){
180561              iCol = 0;
180562              iPos = 0;
180563              if( iVal ){
180564                pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
180565              }else{
180566                pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
180567                iDocid += iVal;
180568              }
180569            }else{
180570              iPos += (iVal - 2);
180571              cksum = cksum ^ fts3ChecksumEntry(
180572                  csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
180573                  (int)iCol, (int)iPos
180574              );
180575            }
180576          }
180577        }
180578      }
180579    }
180580    sqlite3Fts3SegReaderFinish(&csr);
180581  
180582    *pRc = rc;
180583    return cksum;
180584  }
180585  
180586  /*
180587  ** Check if the contents of the FTS index match the current contents of the
180588  ** content table. If no error occurs and the contents do match, set *pbOk
180589  ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
180590  ** to false before returning.
180591  **
180592  ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
180593  ** code. The final value of *pbOk is undefined in this case.
180594  */
180595  static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
180596    int rc = SQLITE_OK;             /* Return code */
180597    u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
180598    u64 cksum2 = 0;                 /* Checksum based on %_content contents */
180599    sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
180600  
180601    /* This block calculates the checksum according to the FTS index. */
180602    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
180603    if( rc==SQLITE_OK ){
180604      int rc2;
180605      sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
180606      sqlite3_bind_int(pAllLangid, 2, p->nIndex);
180607      while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
180608        int iLangid = sqlite3_column_int(pAllLangid, 0);
180609        int i;
180610        for(i=0; i<p->nIndex; i++){
180611          cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
180612        }
180613      }
180614      rc2 = sqlite3_reset(pAllLangid);
180615      if( rc==SQLITE_OK ) rc = rc2;
180616    }
180617  
180618    /* This block calculates the checksum according to the %_content table */
180619    if( rc==SQLITE_OK ){
180620      sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
180621      sqlite3_stmt *pStmt = 0;
180622      char *zSql;
180623     
180624      zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
180625      if( !zSql ){
180626        rc = SQLITE_NOMEM;
180627      }else{
180628        rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
180629        sqlite3_free(zSql);
180630      }
180631  
180632      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
180633        i64 iDocid = sqlite3_column_int64(pStmt, 0);
180634        int iLang = langidFromSelect(p, pStmt);
180635        int iCol;
180636  
180637        for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
180638          if( p->abNotindexed[iCol]==0 ){
180639            const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
180640            int nText = sqlite3_column_bytes(pStmt, iCol+1);
180641            sqlite3_tokenizer_cursor *pT = 0;
180642  
180643            rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
180644            while( rc==SQLITE_OK ){
180645              char const *zToken;       /* Buffer containing token */
180646              int nToken = 0;           /* Number of bytes in token */
180647              int iDum1 = 0, iDum2 = 0; /* Dummy variables */
180648              int iPos = 0;             /* Position of token in zText */
180649  
180650              rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
180651              if( rc==SQLITE_OK ){
180652                int i;
180653                cksum2 = cksum2 ^ fts3ChecksumEntry(
180654                    zToken, nToken, iLang, 0, iDocid, iCol, iPos
180655                );
180656                for(i=1; i<p->nIndex; i++){
180657                  if( p->aIndex[i].nPrefix<=nToken ){
180658                    cksum2 = cksum2 ^ fts3ChecksumEntry(
180659                        zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
180660                    );
180661                  }
180662                }
180663              }
180664            }
180665            if( pT ) pModule->xClose(pT);
180666            if( rc==SQLITE_DONE ) rc = SQLITE_OK;
180667          }
180668        }
180669      }
180670  
180671      sqlite3_finalize(pStmt);
180672    }
180673  
180674    *pbOk = (cksum1==cksum2);
180675    return rc;
180676  }
180677  
180678  /*
180679  ** Run the integrity-check. If no error occurs and the current contents of
180680  ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
180681  ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
180682  **
180683  ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
180684  ** error code.
180685  **
180686  ** The integrity-check works as follows. For each token and indexed token
180687  ** prefix in the document set, a 64-bit checksum is calculated (by code
180688  ** in fts3ChecksumEntry()) based on the following:
180689  **
180690  **     + The index number (0 for the main index, 1 for the first prefix
180691  **       index etc.),
180692  **     + The token (or token prefix) text itself, 
180693  **     + The language-id of the row it appears in,
180694  **     + The docid of the row it appears in,
180695  **     + The column it appears in, and
180696  **     + The tokens position within that column.
180697  **
180698  ** The checksums for all entries in the index are XORed together to create
180699  ** a single checksum for the entire index.
180700  **
180701  ** The integrity-check code calculates the same checksum in two ways:
180702  **
180703  **     1. By scanning the contents of the FTS index, and 
180704  **     2. By scanning and tokenizing the content table.
180705  **
180706  ** If the two checksums are identical, the integrity-check is deemed to have
180707  ** passed.
180708  */
180709  static int fts3DoIntegrityCheck(
180710    Fts3Table *p                    /* FTS3 table handle */
180711  ){
180712    int rc;
180713    int bOk = 0;
180714    rc = fts3IntegrityCheck(p, &bOk);
180715    if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
180716    return rc;
180717  }
180718  
180719  /*
180720  ** Handle a 'special' INSERT of the form:
180721  **
180722  **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
180723  **
180724  ** Argument pVal contains the result of <expr>. Currently the only 
180725  ** meaningful value to insert is the text 'optimize'.
180726  */
180727  static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
180728    int rc;                         /* Return Code */
180729    const char *zVal = (const char *)sqlite3_value_text(pVal);
180730    int nVal = sqlite3_value_bytes(pVal);
180731  
180732    if( !zVal ){
180733      return SQLITE_NOMEM;
180734    }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
180735      rc = fts3DoOptimize(p, 0);
180736    }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
180737      rc = fts3DoRebuild(p);
180738    }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
180739      rc = fts3DoIntegrityCheck(p);
180740    }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
180741      rc = fts3DoIncrmerge(p, &zVal[6]);
180742    }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
180743      rc = fts3DoAutoincrmerge(p, &zVal[10]);
180744  #ifdef SQLITE_TEST
180745    }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
180746      p->nNodeSize = atoi(&zVal[9]);
180747      rc = SQLITE_OK;
180748    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
180749      p->nMaxPendingData = atoi(&zVal[11]);
180750      rc = SQLITE_OK;
180751    }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
180752      p->bNoIncrDoclist = atoi(&zVal[21]);
180753      rc = SQLITE_OK;
180754  #endif
180755    }else{
180756      rc = SQLITE_ERROR;
180757    }
180758  
180759    return rc;
180760  }
180761  
180762  #ifndef SQLITE_DISABLE_FTS4_DEFERRED
180763  /*
180764  ** Delete all cached deferred doclists. Deferred doclists are cached
180765  ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
180766  */
180767  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
180768    Fts3DeferredToken *pDef;
180769    for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
180770      fts3PendingListDelete(pDef->pList);
180771      pDef->pList = 0;
180772    }
180773  }
180774  
180775  /*
180776  ** Free all entries in the pCsr->pDeffered list. Entries are added to 
180777  ** this list using sqlite3Fts3DeferToken().
180778  */
180779  SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
180780    Fts3DeferredToken *pDef;
180781    Fts3DeferredToken *pNext;
180782    for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
180783      pNext = pDef->pNext;
180784      fts3PendingListDelete(pDef->pList);
180785      sqlite3_free(pDef);
180786    }
180787    pCsr->pDeferred = 0;
180788  }
180789  
180790  /*
180791  ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
180792  ** based on the row that pCsr currently points to.
180793  **
180794  ** A deferred-doclist is like any other doclist with position information
180795  ** included, except that it only contains entries for a single row of the
180796  ** table, not for all rows.
180797  */
180798  SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
180799    int rc = SQLITE_OK;             /* Return code */
180800    if( pCsr->pDeferred ){
180801      int i;                        /* Used to iterate through table columns */
180802      sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
180803      Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
180804    
180805      Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
180806      sqlite3_tokenizer *pT = p->pTokenizer;
180807      sqlite3_tokenizer_module const *pModule = pT->pModule;
180808     
180809      assert( pCsr->isRequireSeek==0 );
180810      iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
180811    
180812      for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
180813        if( p->abNotindexed[i]==0 ){
180814          const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
180815          sqlite3_tokenizer_cursor *pTC = 0;
180816  
180817          rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
180818          while( rc==SQLITE_OK ){
180819            char const *zToken;       /* Buffer containing token */
180820            int nToken = 0;           /* Number of bytes in token */
180821            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
180822            int iPos = 0;             /* Position of token in zText */
180823  
180824            rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
180825            for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
180826              Fts3PhraseToken *pPT = pDef->pToken;
180827              if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
180828                  && (pPT->bFirst==0 || iPos==0)
180829                  && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
180830                  && (0==memcmp(zToken, pPT->z, pPT->n))
180831                ){
180832                fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
180833              }
180834            }
180835          }
180836          if( pTC ) pModule->xClose(pTC);
180837          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
180838        }
180839      }
180840  
180841      for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
180842        if( pDef->pList ){
180843          rc = fts3PendingListAppendVarint(&pDef->pList, 0);
180844        }
180845      }
180846    }
180847  
180848    return rc;
180849  }
180850  
180851  SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
180852    Fts3DeferredToken *p, 
180853    char **ppData, 
180854    int *pnData
180855  ){
180856    char *pRet;
180857    int nSkip;
180858    sqlite3_int64 dummy;
180859  
180860    *ppData = 0;
180861    *pnData = 0;
180862  
180863    if( p->pList==0 ){
180864      return SQLITE_OK;
180865    }
180866  
180867    pRet = (char *)sqlite3_malloc(p->pList->nData);
180868    if( !pRet ) return SQLITE_NOMEM;
180869  
180870    nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
180871    *pnData = p->pList->nData - nSkip;
180872    *ppData = pRet;
180873    
180874    memcpy(pRet, &p->pList->aData[nSkip], *pnData);
180875    return SQLITE_OK;
180876  }
180877  
180878  /*
180879  ** Add an entry for token pToken to the pCsr->pDeferred list.
180880  */
180881  SQLITE_PRIVATE int sqlite3Fts3DeferToken(
180882    Fts3Cursor *pCsr,               /* Fts3 table cursor */
180883    Fts3PhraseToken *pToken,        /* Token to defer */
180884    int iCol                        /* Column that token must appear in (or -1) */
180885  ){
180886    Fts3DeferredToken *pDeferred;
180887    pDeferred = sqlite3_malloc(sizeof(*pDeferred));
180888    if( !pDeferred ){
180889      return SQLITE_NOMEM;
180890    }
180891    memset(pDeferred, 0, sizeof(*pDeferred));
180892    pDeferred->pToken = pToken;
180893    pDeferred->pNext = pCsr->pDeferred; 
180894    pDeferred->iCol = iCol;
180895    pCsr->pDeferred = pDeferred;
180896  
180897    assert( pToken->pDeferred==0 );
180898    pToken->pDeferred = pDeferred;
180899  
180900    return SQLITE_OK;
180901  }
180902  #endif
180903  
180904  /*
180905  ** SQLite value pRowid contains the rowid of a row that may or may not be
180906  ** present in the FTS3 table. If it is, delete it and adjust the contents
180907  ** of subsiduary data structures accordingly.
180908  */
180909  static int fts3DeleteByRowid(
180910    Fts3Table *p, 
180911    sqlite3_value *pRowid, 
180912    int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
180913    u32 *aSzDel
180914  ){
180915    int rc = SQLITE_OK;             /* Return code */
180916    int bFound = 0;                 /* True if *pRowid really is in the table */
180917  
180918    fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
180919    if( bFound && rc==SQLITE_OK ){
180920      int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
180921      rc = fts3IsEmpty(p, pRowid, &isEmpty);
180922      if( rc==SQLITE_OK ){
180923        if( isEmpty ){
180924          /* Deleting this row means the whole table is empty. In this case
180925          ** delete the contents of all three tables and throw away any
180926          ** data in the pendingTerms hash table.  */
180927          rc = fts3DeleteAll(p, 1);
180928          *pnChng = 0;
180929          memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
180930        }else{
180931          *pnChng = *pnChng - 1;
180932          if( p->zContentTbl==0 ){
180933            fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
180934          }
180935          if( p->bHasDocsize ){
180936            fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
180937          }
180938        }
180939      }
180940    }
180941  
180942    return rc;
180943  }
180944  
180945  /*
180946  ** This function does the work for the xUpdate method of FTS3 virtual
180947  ** tables. The schema of the virtual table being:
180948  **
180949  **     CREATE TABLE <table name>( 
180950  **       <user columns>,
180951  **       <table name> HIDDEN, 
180952  **       docid HIDDEN, 
180953  **       <langid> HIDDEN
180954  **     );
180955  **
180956  ** 
180957  */
180958  SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
180959    sqlite3_vtab *pVtab,            /* FTS3 vtab object */
180960    int nArg,                       /* Size of argument array */
180961    sqlite3_value **apVal,          /* Array of arguments */
180962    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
180963  ){
180964    Fts3Table *p = (Fts3Table *)pVtab;
180965    int rc = SQLITE_OK;             /* Return Code */
180966    u32 *aSzIns = 0;                /* Sizes of inserted documents */
180967    u32 *aSzDel = 0;                /* Sizes of deleted documents */
180968    int nChng = 0;                  /* Net change in number of documents */
180969    int bInsertDone = 0;
180970  
180971    /* At this point it must be known if the %_stat table exists or not.
180972    ** So bHasStat may not be 2.  */
180973    assert( p->bHasStat==0 || p->bHasStat==1 );
180974  
180975    assert( p->pSegments==0 );
180976    assert( 
180977        nArg==1                     /* DELETE operations */
180978     || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
180979    );
180980  
180981    /* Check for a "special" INSERT operation. One of the form:
180982    **
180983    **   INSERT INTO xyz(xyz) VALUES('command');
180984    */
180985    if( nArg>1 
180986     && sqlite3_value_type(apVal[0])==SQLITE_NULL 
180987     && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
180988    ){
180989      rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
180990      goto update_out;
180991    }
180992  
180993    if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
180994      rc = SQLITE_CONSTRAINT;
180995      goto update_out;
180996    }
180997  
180998    /* Allocate space to hold the change in document sizes */
180999    aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
181000    if( aSzDel==0 ){
181001      rc = SQLITE_NOMEM;
181002      goto update_out;
181003    }
181004    aSzIns = &aSzDel[p->nColumn+1];
181005    memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
181006  
181007    rc = fts3Writelock(p);
181008    if( rc!=SQLITE_OK ) goto update_out;
181009  
181010    /* If this is an INSERT operation, or an UPDATE that modifies the rowid
181011    ** value, then this operation requires constraint handling.
181012    **
181013    ** If the on-conflict mode is REPLACE, this means that the existing row
181014    ** should be deleted from the database before inserting the new row. Or,
181015    ** if the on-conflict mode is other than REPLACE, then this method must
181016    ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
181017    ** modify the database file.
181018    */
181019    if( nArg>1 && p->zContentTbl==0 ){
181020      /* Find the value object that holds the new rowid value. */
181021      sqlite3_value *pNewRowid = apVal[3+p->nColumn];
181022      if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
181023        pNewRowid = apVal[1];
181024      }
181025  
181026      if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
181027          sqlite3_value_type(apVal[0])==SQLITE_NULL
181028       || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
181029      )){
181030        /* The new rowid is not NULL (in this case the rowid will be
181031        ** automatically assigned and there is no chance of a conflict), and 
181032        ** the statement is either an INSERT or an UPDATE that modifies the
181033        ** rowid column. So if the conflict mode is REPLACE, then delete any
181034        ** existing row with rowid=pNewRowid. 
181035        **
181036        ** Or, if the conflict mode is not REPLACE, insert the new record into 
181037        ** the %_content table. If we hit the duplicate rowid constraint (or any
181038        ** other error) while doing so, return immediately.
181039        **
181040        ** This branch may also run if pNewRowid contains a value that cannot
181041        ** be losslessly converted to an integer. In this case, the eventual 
181042        ** call to fts3InsertData() (either just below or further on in this
181043        ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
181044        ** invoked, it will delete zero rows (since no row will have
181045        ** docid=$pNewRowid if $pNewRowid is not an integer value).
181046        */
181047        if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
181048          rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
181049        }else{
181050          rc = fts3InsertData(p, apVal, pRowid);
181051          bInsertDone = 1;
181052        }
181053      }
181054    }
181055    if( rc!=SQLITE_OK ){
181056      goto update_out;
181057    }
181058  
181059    /* If this is a DELETE or UPDATE operation, remove the old record. */
181060    if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
181061      assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
181062      rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
181063    }
181064    
181065    /* If this is an INSERT or UPDATE operation, insert the new record. */
181066    if( nArg>1 && rc==SQLITE_OK ){
181067      int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
181068      if( bInsertDone==0 ){
181069        rc = fts3InsertData(p, apVal, pRowid);
181070        if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
181071          rc = FTS_CORRUPT_VTAB;
181072        }
181073      }
181074      if( rc==SQLITE_OK ){
181075        rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
181076      }
181077      if( rc==SQLITE_OK ){
181078        assert( p->iPrevDocid==*pRowid );
181079        rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
181080      }
181081      if( p->bHasDocsize ){
181082        fts3InsertDocsize(&rc, p, aSzIns);
181083      }
181084      nChng++;
181085    }
181086  
181087    if( p->bFts4 ){
181088      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
181089    }
181090  
181091   update_out:
181092    sqlite3_free(aSzDel);
181093    sqlite3Fts3SegmentsClose(p);
181094    return rc;
181095  }
181096  
181097  /* 
181098  ** Flush any data in the pending-terms hash table to disk. If successful,
181099  ** merge all segments in the database (including the new segment, if 
181100  ** there was any data to flush) into a single segment. 
181101  */
181102  SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
181103    int rc;
181104    rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
181105    if( rc==SQLITE_OK ){
181106      rc = fts3DoOptimize(p, 1);
181107      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
181108        int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
181109        if( rc2!=SQLITE_OK ) rc = rc2;
181110      }else{
181111        sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
181112        sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
181113      }
181114    }
181115    sqlite3Fts3SegmentsClose(p);
181116    return rc;
181117  }
181118  
181119  #endif
181120  
181121  /************** End of fts3_write.c ******************************************/
181122  /************** Begin file fts3_snippet.c ************************************/
181123  /*
181124  ** 2009 Oct 23
181125  **
181126  ** The author disclaims copyright to this source code.  In place of
181127  ** a legal notice, here is a blessing:
181128  **
181129  **    May you do good and not evil.
181130  **    May you find forgiveness for yourself and forgive others.
181131  **    May you share freely, never taking more than you give.
181132  **
181133  ******************************************************************************
181134  */
181135  
181136  /* #include "fts3Int.h" */
181137  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
181138  
181139  /* #include <string.h> */
181140  /* #include <assert.h> */
181141  
181142  /*
181143  ** Characters that may appear in the second argument to matchinfo().
181144  */
181145  #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
181146  #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
181147  #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
181148  #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
181149  #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
181150  #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
181151  #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
181152  #define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
181153  #define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
181154  
181155  /*
181156  ** The default value for the second argument to matchinfo(). 
181157  */
181158  #define FTS3_MATCHINFO_DEFAULT   "pcx"
181159  
181160  
181161  /*
181162  ** Used as an fts3ExprIterate() context when loading phrase doclists to
181163  ** Fts3Expr.aDoclist[]/nDoclist.
181164  */
181165  typedef struct LoadDoclistCtx LoadDoclistCtx;
181166  struct LoadDoclistCtx {
181167    Fts3Cursor *pCsr;               /* FTS3 Cursor */
181168    int nPhrase;                    /* Number of phrases seen so far */
181169    int nToken;                     /* Number of tokens seen so far */
181170  };
181171  
181172  /*
181173  ** The following types are used as part of the implementation of the 
181174  ** fts3BestSnippet() routine.
181175  */
181176  typedef struct SnippetIter SnippetIter;
181177  typedef struct SnippetPhrase SnippetPhrase;
181178  typedef struct SnippetFragment SnippetFragment;
181179  
181180  struct SnippetIter {
181181    Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
181182    int iCol;                       /* Extract snippet from this column */
181183    int nSnippet;                   /* Requested snippet length (in tokens) */
181184    int nPhrase;                    /* Number of phrases in query */
181185    SnippetPhrase *aPhrase;         /* Array of size nPhrase */
181186    int iCurrent;                   /* First token of current snippet */
181187  };
181188  
181189  struct SnippetPhrase {
181190    int nToken;                     /* Number of tokens in phrase */
181191    char *pList;                    /* Pointer to start of phrase position list */
181192    int iHead;                      /* Next value in position list */
181193    char *pHead;                    /* Position list data following iHead */
181194    int iTail;                      /* Next value in trailing position list */
181195    char *pTail;                    /* Position list data following iTail */
181196  };
181197  
181198  struct SnippetFragment {
181199    int iCol;                       /* Column snippet is extracted from */
181200    int iPos;                       /* Index of first token in snippet */
181201    u64 covered;                    /* Mask of query phrases covered */
181202    u64 hlmask;                     /* Mask of snippet terms to highlight */
181203  };
181204  
181205  /*
181206  ** This type is used as an fts3ExprIterate() context object while 
181207  ** accumulating the data returned by the matchinfo() function.
181208  */
181209  typedef struct MatchInfo MatchInfo;
181210  struct MatchInfo {
181211    Fts3Cursor *pCursor;            /* FTS3 Cursor */
181212    int nCol;                       /* Number of columns in table */
181213    int nPhrase;                    /* Number of matchable phrases in query */
181214    sqlite3_int64 nDoc;             /* Number of docs in database */
181215    char flag;
181216    u32 *aMatchinfo;                /* Pre-allocated buffer */
181217  };
181218  
181219  /*
181220  ** An instance of this structure is used to manage a pair of buffers, each
181221  ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
181222  ** for details.
181223  */
181224  struct MatchinfoBuffer {
181225    u8 aRef[3];
181226    int nElem;
181227    int bGlobal;                    /* Set if global data is loaded */
181228    char *zMatchinfo;
181229    u32 aMatchinfo[1];
181230  };
181231  
181232  
181233  /*
181234  ** The snippet() and offsets() functions both return text values. An instance
181235  ** of the following structure is used to accumulate those values while the
181236  ** functions are running. See fts3StringAppend() for details.
181237  */
181238  typedef struct StrBuffer StrBuffer;
181239  struct StrBuffer {
181240    char *z;                        /* Pointer to buffer containing string */
181241    int n;                          /* Length of z in bytes (excl. nul-term) */
181242    int nAlloc;                     /* Allocated size of buffer z in bytes */
181243  };
181244  
181245  
181246  /*************************************************************************
181247  ** Start of MatchinfoBuffer code.
181248  */
181249  
181250  /*
181251  ** Allocate a two-slot MatchinfoBuffer object.
181252  */
181253  static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
181254    MatchinfoBuffer *pRet;
181255    int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
181256    int nStr = (int)strlen(zMatchinfo);
181257  
181258    pRet = sqlite3_malloc(nByte + nStr+1);
181259    if( pRet ){
181260      memset(pRet, 0, nByte);
181261      pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
181262      pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
181263      pRet->nElem = nElem;
181264      pRet->zMatchinfo = ((char*)pRet) + nByte;
181265      memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
181266      pRet->aRef[0] = 1;
181267    }
181268  
181269    return pRet;
181270  }
181271  
181272  static void fts3MIBufferFree(void *p){
181273    MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
181274  
181275    assert( (u32*)p==&pBuf->aMatchinfo[1] 
181276         || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] 
181277    );
181278    if( (u32*)p==&pBuf->aMatchinfo[1] ){
181279      pBuf->aRef[1] = 0;
181280    }else{
181281      pBuf->aRef[2] = 0;
181282    }
181283  
181284    if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
181285      sqlite3_free(pBuf);
181286    }
181287  }
181288  
181289  static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
181290    void (*xRet)(void*) = 0;
181291    u32 *aOut = 0;
181292  
181293    if( p->aRef[1]==0 ){
181294      p->aRef[1] = 1;
181295      aOut = &p->aMatchinfo[1];
181296      xRet = fts3MIBufferFree;
181297    }
181298    else if( p->aRef[2]==0 ){
181299      p->aRef[2] = 1;
181300      aOut = &p->aMatchinfo[p->nElem+2];
181301      xRet = fts3MIBufferFree;
181302    }else{
181303      aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
181304      if( aOut ){
181305        xRet = sqlite3_free;
181306        if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
181307      }
181308    }
181309  
181310    *paOut = aOut;
181311    return xRet;
181312  }
181313  
181314  static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
181315    p->bGlobal = 1;
181316    memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
181317  }
181318  
181319  /*
181320  ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
181321  */
181322  SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
181323    if( p ){
181324      assert( p->aRef[0]==1 );
181325      p->aRef[0] = 0;
181326      if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
181327        sqlite3_free(p);
181328      }
181329    }
181330  }
181331  
181332  /* 
181333  ** End of MatchinfoBuffer code.
181334  *************************************************************************/
181335  
181336  
181337  /*
181338  ** This function is used to help iterate through a position-list. A position
181339  ** list is a list of unique integers, sorted from smallest to largest. Each
181340  ** element of the list is represented by an FTS3 varint that takes the value
181341  ** of the difference between the current element and the previous one plus
181342  ** two. For example, to store the position-list:
181343  **
181344  **     4 9 113
181345  **
181346  ** the three varints:
181347  **
181348  **     6 7 106
181349  **
181350  ** are encoded.
181351  **
181352  ** When this function is called, *pp points to the start of an element of
181353  ** the list. *piPos contains the value of the previous entry in the list.
181354  ** After it returns, *piPos contains the value of the next element of the
181355  ** list and *pp is advanced to the following varint.
181356  */
181357  static void fts3GetDeltaPosition(char **pp, int *piPos){
181358    int iVal;
181359    *pp += fts3GetVarint32(*pp, &iVal);
181360    *piPos += (iVal-2);
181361  }
181362  
181363  /*
181364  ** Helper function for fts3ExprIterate() (see below).
181365  */
181366  static int fts3ExprIterate2(
181367    Fts3Expr *pExpr,                /* Expression to iterate phrases of */
181368    int *piPhrase,                  /* Pointer to phrase counter */
181369    int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
181370    void *pCtx                      /* Second argument to pass to callback */
181371  ){
181372    int rc;                         /* Return code */
181373    int eType = pExpr->eType;     /* Type of expression node pExpr */
181374  
181375    if( eType!=FTSQUERY_PHRASE ){
181376      assert( pExpr->pLeft && pExpr->pRight );
181377      rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
181378      if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
181379        rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
181380      }
181381    }else{
181382      rc = x(pExpr, *piPhrase, pCtx);
181383      (*piPhrase)++;
181384    }
181385    return rc;
181386  }
181387  
181388  /*
181389  ** Iterate through all phrase nodes in an FTS3 query, except those that
181390  ** are part of a sub-tree that is the right-hand-side of a NOT operator.
181391  ** For each phrase node found, the supplied callback function is invoked.
181392  **
181393  ** If the callback function returns anything other than SQLITE_OK, 
181394  ** the iteration is abandoned and the error code returned immediately.
181395  ** Otherwise, SQLITE_OK is returned after a callback has been made for
181396  ** all eligible phrase nodes.
181397  */
181398  static int fts3ExprIterate(
181399    Fts3Expr *pExpr,                /* Expression to iterate phrases of */
181400    int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
181401    void *pCtx                      /* Second argument to pass to callback */
181402  ){
181403    int iPhrase = 0;                /* Variable used as the phrase counter */
181404    return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
181405  }
181406  
181407  
181408  /*
181409  ** This is an fts3ExprIterate() callback used while loading the doclists
181410  ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
181411  ** fts3ExprLoadDoclists().
181412  */
181413  static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
181414    int rc = SQLITE_OK;
181415    Fts3Phrase *pPhrase = pExpr->pPhrase;
181416    LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
181417  
181418    UNUSED_PARAMETER(iPhrase);
181419  
181420    p->nPhrase++;
181421    p->nToken += pPhrase->nToken;
181422  
181423    return rc;
181424  }
181425  
181426  /*
181427  ** Load the doclists for each phrase in the query associated with FTS3 cursor
181428  ** pCsr. 
181429  **
181430  ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
181431  ** phrases in the expression (all phrases except those directly or 
181432  ** indirectly descended from the right-hand-side of a NOT operator). If 
181433  ** pnToken is not NULL, then it is set to the number of tokens in all
181434  ** matchable phrases of the expression.
181435  */
181436  static int fts3ExprLoadDoclists(
181437    Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
181438    int *pnPhrase,                  /* OUT: Number of phrases in query */
181439    int *pnToken                    /* OUT: Number of tokens in query */
181440  ){
181441    int rc;                         /* Return Code */
181442    LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
181443    sCtx.pCsr = pCsr;
181444    rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
181445    if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
181446    if( pnToken ) *pnToken = sCtx.nToken;
181447    return rc;
181448  }
181449  
181450  static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
181451    (*(int *)ctx)++;
181452    pExpr->iPhrase = iPhrase;
181453    return SQLITE_OK;
181454  }
181455  static int fts3ExprPhraseCount(Fts3Expr *pExpr){
181456    int nPhrase = 0;
181457    (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
181458    return nPhrase;
181459  }
181460  
181461  /*
181462  ** Advance the position list iterator specified by the first two 
181463  ** arguments so that it points to the first element with a value greater
181464  ** than or equal to parameter iNext.
181465  */
181466  static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
181467    char *pIter = *ppIter;
181468    if( pIter ){
181469      int iIter = *piIter;
181470  
181471      while( iIter<iNext ){
181472        if( 0==(*pIter & 0xFE) ){
181473          iIter = -1;
181474          pIter = 0;
181475          break;
181476        }
181477        fts3GetDeltaPosition(&pIter, &iIter);
181478      }
181479  
181480      *piIter = iIter;
181481      *ppIter = pIter;
181482    }
181483  }
181484  
181485  /*
181486  ** Advance the snippet iterator to the next candidate snippet.
181487  */
181488  static int fts3SnippetNextCandidate(SnippetIter *pIter){
181489    int i;                          /* Loop counter */
181490  
181491    if( pIter->iCurrent<0 ){
181492      /* The SnippetIter object has just been initialized. The first snippet
181493      ** candidate always starts at offset 0 (even if this candidate has a
181494      ** score of 0.0).
181495      */
181496      pIter->iCurrent = 0;
181497  
181498      /* Advance the 'head' iterator of each phrase to the first offset that
181499      ** is greater than or equal to (iNext+nSnippet).
181500      */
181501      for(i=0; i<pIter->nPhrase; i++){
181502        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
181503        fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
181504      }
181505    }else{
181506      int iStart;
181507      int iEnd = 0x7FFFFFFF;
181508  
181509      for(i=0; i<pIter->nPhrase; i++){
181510        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
181511        if( pPhrase->pHead && pPhrase->iHead<iEnd ){
181512          iEnd = pPhrase->iHead;
181513        }
181514      }
181515      if( iEnd==0x7FFFFFFF ){
181516        return 1;
181517      }
181518  
181519      pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
181520      for(i=0; i<pIter->nPhrase; i++){
181521        SnippetPhrase *pPhrase = &pIter->aPhrase[i];
181522        fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
181523        fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
181524      }
181525    }
181526  
181527    return 0;
181528  }
181529  
181530  /*
181531  ** Retrieve information about the current candidate snippet of snippet 
181532  ** iterator pIter.
181533  */
181534  static void fts3SnippetDetails(
181535    SnippetIter *pIter,             /* Snippet iterator */
181536    u64 mCovered,                   /* Bitmask of phrases already covered */
181537    int *piToken,                   /* OUT: First token of proposed snippet */
181538    int *piScore,                   /* OUT: "Score" for this snippet */
181539    u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
181540    u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
181541  ){
181542    int iStart = pIter->iCurrent;   /* First token of snippet */
181543    int iScore = 0;                 /* Score of this snippet */
181544    int i;                          /* Loop counter */
181545    u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
181546    u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
181547  
181548    for(i=0; i<pIter->nPhrase; i++){
181549      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
181550      if( pPhrase->pTail ){
181551        char *pCsr = pPhrase->pTail;
181552        int iCsr = pPhrase->iTail;
181553  
181554        while( iCsr<(iStart+pIter->nSnippet) ){
181555          int j;
181556          u64 mPhrase = (u64)1 << i;
181557          u64 mPos = (u64)1 << (iCsr - iStart);
181558          assert( iCsr>=iStart && (iCsr - iStart)<=64 );
181559          assert( i>=0 && i<=64 );
181560          if( (mCover|mCovered)&mPhrase ){
181561            iScore++;
181562          }else{
181563            iScore += 1000;
181564          }
181565          mCover |= mPhrase;
181566  
181567          for(j=0; j<pPhrase->nToken; j++){
181568            mHighlight |= (mPos>>j);
181569          }
181570  
181571          if( 0==(*pCsr & 0x0FE) ) break;
181572          fts3GetDeltaPosition(&pCsr, &iCsr);
181573        }
181574      }
181575    }
181576  
181577    /* Set the output variables before returning. */
181578    *piToken = iStart;
181579    *piScore = iScore;
181580    *pmCover = mCover;
181581    *pmHighlight = mHighlight;
181582  }
181583  
181584  /*
181585  ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
181586  ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
181587  */
181588  static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
181589    SnippetIter *p = (SnippetIter *)ctx;
181590    SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
181591    char *pCsr;
181592    int rc;
181593  
181594    pPhrase->nToken = pExpr->pPhrase->nToken;
181595    rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
181596    assert( rc==SQLITE_OK || pCsr==0 );
181597    if( pCsr ){
181598      int iFirst = 0;
181599      pPhrase->pList = pCsr;
181600      fts3GetDeltaPosition(&pCsr, &iFirst);
181601      if( iFirst<0 ){
181602        rc = FTS_CORRUPT_VTAB;
181603      }else{
181604        pPhrase->pHead = pCsr;
181605        pPhrase->pTail = pCsr;
181606        pPhrase->iHead = iFirst;
181607        pPhrase->iTail = iFirst;
181608      }
181609    }else{
181610      assert( rc!=SQLITE_OK || (
181611         pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
181612      ));
181613    }
181614  
181615    return rc;
181616  }
181617  
181618  /*
181619  ** Select the fragment of text consisting of nFragment contiguous tokens 
181620  ** from column iCol that represent the "best" snippet. The best snippet
181621  ** is the snippet with the highest score, where scores are calculated
181622  ** by adding:
181623  **
181624  **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
181625  **
181626  **   (b) +1000 points for the first occurrence of each matchable phrase in 
181627  **       the snippet for which the corresponding mCovered bit is not set.
181628  **
181629  ** The selected snippet parameters are stored in structure *pFragment before
181630  ** returning. The score of the selected snippet is stored in *piScore
181631  ** before returning.
181632  */
181633  static int fts3BestSnippet(
181634    int nSnippet,                   /* Desired snippet length */
181635    Fts3Cursor *pCsr,               /* Cursor to create snippet for */
181636    int iCol,                       /* Index of column to create snippet from */
181637    u64 mCovered,                   /* Mask of phrases already covered */
181638    u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
181639    SnippetFragment *pFragment,     /* OUT: Best snippet found */
181640    int *piScore                    /* OUT: Score of snippet pFragment */
181641  ){
181642    int rc;                         /* Return Code */
181643    int nList;                      /* Number of phrases in expression */
181644    SnippetIter sIter;              /* Iterates through snippet candidates */
181645    sqlite3_int64 nByte;            /* Number of bytes of space to allocate */
181646    int iBestScore = -1;            /* Best snippet score found so far */
181647    int i;                          /* Loop counter */
181648  
181649    memset(&sIter, 0, sizeof(sIter));
181650  
181651    /* Iterate through the phrases in the expression to count them. The same
181652    ** callback makes sure the doclists are loaded for each phrase.
181653    */
181654    rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
181655    if( rc!=SQLITE_OK ){
181656      return rc;
181657    }
181658  
181659    /* Now that it is known how many phrases there are, allocate and zero
181660    ** the required space using malloc().
181661    */
181662    nByte = sizeof(SnippetPhrase) * nList;
181663    sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
181664    if( !sIter.aPhrase ){
181665      return SQLITE_NOMEM;
181666    }
181667    memset(sIter.aPhrase, 0, nByte);
181668  
181669    /* Initialize the contents of the SnippetIter object. Then iterate through
181670    ** the set of phrases in the expression to populate the aPhrase[] array.
181671    */
181672    sIter.pCsr = pCsr;
181673    sIter.iCol = iCol;
181674    sIter.nSnippet = nSnippet;
181675    sIter.nPhrase = nList;
181676    sIter.iCurrent = -1;
181677    rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
181678    if( rc==SQLITE_OK ){
181679  
181680      /* Set the *pmSeen output variable. */
181681      for(i=0; i<nList; i++){
181682        if( sIter.aPhrase[i].pHead ){
181683          *pmSeen |= (u64)1 << i;
181684        }
181685      }
181686  
181687      /* Loop through all candidate snippets. Store the best snippet in 
181688       ** *pFragment. Store its associated 'score' in iBestScore.
181689       */
181690      pFragment->iCol = iCol;
181691      while( !fts3SnippetNextCandidate(&sIter) ){
181692        int iPos;
181693        int iScore;
181694        u64 mCover;
181695        u64 mHighlite;
181696        fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
181697        assert( iScore>=0 );
181698        if( iScore>iBestScore ){
181699          pFragment->iPos = iPos;
181700          pFragment->hlmask = mHighlite;
181701          pFragment->covered = mCover;
181702          iBestScore = iScore;
181703        }
181704      }
181705  
181706      *piScore = iBestScore;
181707    }
181708    sqlite3_free(sIter.aPhrase);
181709    return rc;
181710  }
181711  
181712  
181713  /*
181714  ** Append a string to the string-buffer passed as the first argument.
181715  **
181716  ** If nAppend is negative, then the length of the string zAppend is
181717  ** determined using strlen().
181718  */
181719  static int fts3StringAppend(
181720    StrBuffer *pStr,                /* Buffer to append to */
181721    const char *zAppend,            /* Pointer to data to append to buffer */
181722    int nAppend                     /* Size of zAppend in bytes (or -1) */
181723  ){
181724    if( nAppend<0 ){
181725      nAppend = (int)strlen(zAppend);
181726    }
181727  
181728    /* If there is insufficient space allocated at StrBuffer.z, use realloc()
181729    ** to grow the buffer until so that it is big enough to accomadate the
181730    ** appended data.
181731    */
181732    if( pStr->n+nAppend+1>=pStr->nAlloc ){
181733      sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
181734      char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
181735      if( !zNew ){
181736        return SQLITE_NOMEM;
181737      }
181738      pStr->z = zNew;
181739      pStr->nAlloc = nAlloc;
181740    }
181741    assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
181742  
181743    /* Append the data to the string buffer. */
181744    memcpy(&pStr->z[pStr->n], zAppend, nAppend);
181745    pStr->n += nAppend;
181746    pStr->z[pStr->n] = '\0';
181747  
181748    return SQLITE_OK;
181749  }
181750  
181751  /*
181752  ** The fts3BestSnippet() function often selects snippets that end with a
181753  ** query term. That is, the final term of the snippet is always a term
181754  ** that requires highlighting. For example, if 'X' is a highlighted term
181755  ** and '.' is a non-highlighted term, BestSnippet() may select:
181756  **
181757  **     ........X.....X
181758  **
181759  ** This function "shifts" the beginning of the snippet forward in the 
181760  ** document so that there are approximately the same number of 
181761  ** non-highlighted terms to the right of the final highlighted term as there
181762  ** are to the left of the first highlighted term. For example, to this:
181763  **
181764  **     ....X.....X....
181765  **
181766  ** This is done as part of extracting the snippet text, not when selecting
181767  ** the snippet. Snippet selection is done based on doclists only, so there
181768  ** is no way for fts3BestSnippet() to know whether or not the document 
181769  ** actually contains terms that follow the final highlighted term. 
181770  */
181771  static int fts3SnippetShift(
181772    Fts3Table *pTab,                /* FTS3 table snippet comes from */
181773    int iLangid,                    /* Language id to use in tokenizing */
181774    int nSnippet,                   /* Number of tokens desired for snippet */
181775    const char *zDoc,               /* Document text to extract snippet from */
181776    int nDoc,                       /* Size of buffer zDoc in bytes */
181777    int *piPos,                     /* IN/OUT: First token of snippet */
181778    u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
181779  ){
181780    u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
181781  
181782    if( hlmask ){
181783      int nLeft;                    /* Tokens to the left of first highlight */
181784      int nRight;                   /* Tokens to the right of last highlight */
181785      int nDesired;                 /* Ideal number of tokens to shift forward */
181786  
181787      for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
181788      for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
181789      assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
181790      nDesired = (nLeft-nRight)/2;
181791  
181792      /* Ideally, the start of the snippet should be pushed forward in the
181793      ** document nDesired tokens. This block checks if there are actually
181794      ** nDesired tokens to the right of the snippet. If so, *piPos and
181795      ** *pHlMask are updated to shift the snippet nDesired tokens to the
181796      ** right. Otherwise, the snippet is shifted by the number of tokens
181797      ** available.
181798      */
181799      if( nDesired>0 ){
181800        int nShift;                 /* Number of tokens to shift snippet by */
181801        int iCurrent = 0;           /* Token counter */
181802        int rc;                     /* Return Code */
181803        sqlite3_tokenizer_module *pMod;
181804        sqlite3_tokenizer_cursor *pC;
181805        pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
181806  
181807        /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
181808        ** or more tokens in zDoc/nDoc.
181809        */
181810        rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
181811        if( rc!=SQLITE_OK ){
181812          return rc;
181813        }
181814        while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
181815          const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
181816          rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
181817        }
181818        pMod->xClose(pC);
181819        if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
181820  
181821        nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
181822        assert( nShift<=nDesired );
181823        if( nShift>0 ){
181824          *piPos += nShift;
181825          *pHlmask = hlmask >> nShift;
181826        }
181827      }
181828    }
181829    return SQLITE_OK;
181830  }
181831  
181832  /*
181833  ** Extract the snippet text for fragment pFragment from cursor pCsr and
181834  ** append it to string buffer pOut.
181835  */
181836  static int fts3SnippetText(
181837    Fts3Cursor *pCsr,               /* FTS3 Cursor */
181838    SnippetFragment *pFragment,     /* Snippet to extract */
181839    int iFragment,                  /* Fragment number */
181840    int isLast,                     /* True for final fragment in snippet */
181841    int nSnippet,                   /* Number of tokens in extracted snippet */
181842    const char *zOpen,              /* String inserted before highlighted term */
181843    const char *zClose,             /* String inserted after highlighted term */
181844    const char *zEllipsis,          /* String inserted between snippets */
181845    StrBuffer *pOut                 /* Write output here */
181846  ){
181847    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
181848    int rc;                         /* Return code */
181849    const char *zDoc;               /* Document text to extract snippet from */
181850    int nDoc;                       /* Size of zDoc in bytes */
181851    int iCurrent = 0;               /* Current token number of document */
181852    int iEnd = 0;                   /* Byte offset of end of current token */
181853    int isShiftDone = 0;            /* True after snippet is shifted */
181854    int iPos = pFragment->iPos;     /* First token of snippet */
181855    u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
181856    int iCol = pFragment->iCol+1;   /* Query column to extract text from */
181857    sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
181858    sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
181859    
181860    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
181861    if( zDoc==0 ){
181862      if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
181863        return SQLITE_NOMEM;
181864      }
181865      return SQLITE_OK;
181866    }
181867    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
181868  
181869    /* Open a token cursor on the document. */
181870    pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
181871    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
181872    if( rc!=SQLITE_OK ){
181873      return rc;
181874    }
181875  
181876    while( rc==SQLITE_OK ){
181877      const char *ZDUMMY;           /* Dummy argument used with tokenizer */
181878      int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
181879      int iBegin = 0;               /* Offset in zDoc of start of token */
181880      int iFin = 0;                 /* Offset in zDoc of end of token */
181881      int isHighlight = 0;          /* True for highlighted terms */
181882  
181883      /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
181884      ** in the FTS code the variable that the third argument to xNext points to
181885      ** is initialized to zero before the first (*but not necessarily
181886      ** subsequent*) call to xNext(). This is done for a particular application
181887      ** that needs to know whether or not the tokenizer is being used for
181888      ** snippet generation or for some other purpose.
181889      **
181890      ** Extreme care is required when writing code to depend on this
181891      ** initialization. It is not a documented part of the tokenizer interface.
181892      ** If a tokenizer is used directly by any code outside of FTS, this
181893      ** convention might not be respected.  */
181894      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
181895      if( rc!=SQLITE_OK ){
181896        if( rc==SQLITE_DONE ){
181897          /* Special case - the last token of the snippet is also the last token
181898          ** of the column. Append any punctuation that occurred between the end
181899          ** of the previous token and the end of the document to the output. 
181900          ** Then break out of the loop. */
181901          rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
181902        }
181903        break;
181904      }
181905      if( iCurrent<iPos ){ continue; }
181906  
181907      if( !isShiftDone ){
181908        int n = nDoc - iBegin;
181909        rc = fts3SnippetShift(
181910            pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
181911        );
181912        isShiftDone = 1;
181913  
181914        /* Now that the shift has been done, check if the initial "..." are
181915        ** required. They are required if (a) this is not the first fragment,
181916        ** or (b) this fragment does not begin at position 0 of its column. 
181917        */
181918        if( rc==SQLITE_OK ){
181919          if( iPos>0 || iFragment>0 ){
181920            rc = fts3StringAppend(pOut, zEllipsis, -1);
181921          }else if( iBegin ){
181922            rc = fts3StringAppend(pOut, zDoc, iBegin);
181923          }
181924        }
181925        if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
181926      }
181927  
181928      if( iCurrent>=(iPos+nSnippet) ){
181929        if( isLast ){
181930          rc = fts3StringAppend(pOut, zEllipsis, -1);
181931        }
181932        break;
181933      }
181934  
181935      /* Set isHighlight to true if this term should be highlighted. */
181936      isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
181937  
181938      if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
181939      if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
181940      if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
181941      if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
181942  
181943      iEnd = iFin;
181944    }
181945  
181946    pMod->xClose(pC);
181947    return rc;
181948  }
181949  
181950  
181951  /*
181952  ** This function is used to count the entries in a column-list (a 
181953  ** delta-encoded list of term offsets within a single column of a single 
181954  ** row). When this function is called, *ppCollist should point to the
181955  ** beginning of the first varint in the column-list (the varint that
181956  ** contains the position of the first matching term in the column data).
181957  ** Before returning, *ppCollist is set to point to the first byte after
181958  ** the last varint in the column-list (either the 0x00 signifying the end
181959  ** of the position-list, or the 0x01 that precedes the column number of
181960  ** the next column in the position-list).
181961  **
181962  ** The number of elements in the column-list is returned.
181963  */
181964  static int fts3ColumnlistCount(char **ppCollist){
181965    char *pEnd = *ppCollist;
181966    char c = 0;
181967    int nEntry = 0;
181968  
181969    /* A column-list is terminated by either a 0x01 or 0x00. */
181970    while( 0xFE & (*pEnd | c) ){
181971      c = *pEnd++ & 0x80;
181972      if( !c ) nEntry++;
181973    }
181974  
181975    *ppCollist = pEnd;
181976    return nEntry;
181977  }
181978  
181979  /*
181980  ** This function gathers 'y' or 'b' data for a single phrase.
181981  */
181982  static int fts3ExprLHits(
181983    Fts3Expr *pExpr,                /* Phrase expression node */
181984    MatchInfo *p                    /* Matchinfo context */
181985  ){
181986    Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
181987    int iStart;
181988    Fts3Phrase *pPhrase = pExpr->pPhrase;
181989    char *pIter = pPhrase->doclist.pList;
181990    int iCol = 0;
181991  
181992    assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
181993    if( p->flag==FTS3_MATCHINFO_LHITS ){
181994      iStart = pExpr->iPhrase * p->nCol;
181995    }else{
181996      iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
181997    }
181998  
181999    while( 1 ){
182000      int nHit = fts3ColumnlistCount(&pIter);
182001      if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
182002        if( p->flag==FTS3_MATCHINFO_LHITS ){
182003          p->aMatchinfo[iStart + iCol] = (u32)nHit;
182004        }else if( nHit ){
182005          p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
182006        }
182007      }
182008      assert( *pIter==0x00 || *pIter==0x01 );
182009      if( *pIter!=0x01 ) break;
182010      pIter++;
182011      pIter += fts3GetVarint32(pIter, &iCol);
182012      if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
182013    }
182014    return SQLITE_OK;
182015  }
182016  
182017  /*
182018  ** Gather the results for matchinfo directives 'y' and 'b'.
182019  */
182020  static int fts3ExprLHitGather(
182021    Fts3Expr *pExpr,
182022    MatchInfo *p
182023  ){
182024    int rc = SQLITE_OK;
182025    assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
182026    if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
182027      if( pExpr->pLeft ){
182028        rc = fts3ExprLHitGather(pExpr->pLeft, p);
182029        if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
182030      }else{
182031        rc = fts3ExprLHits(pExpr, p);
182032      }
182033    }
182034    return rc;
182035  }
182036  
182037  /*
182038  ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
182039  ** for a single query. 
182040  **
182041  ** fts3ExprIterate() callback to load the 'global' elements of a
182042  ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
182043  ** of the matchinfo array that are constant for all rows returned by the 
182044  ** current query.
182045  **
182046  ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
182047  ** function populates Matchinfo.aMatchinfo[] as follows:
182048  **
182049  **   for(iCol=0; iCol<nCol; iCol++){
182050  **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
182051  **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
182052  **   }
182053  **
182054  ** where X is the number of matches for phrase iPhrase is column iCol of all
182055  ** rows of the table. Y is the number of rows for which column iCol contains
182056  ** at least one instance of phrase iPhrase.
182057  **
182058  ** If the phrase pExpr consists entirely of deferred tokens, then all X and
182059  ** Y values are set to nDoc, where nDoc is the number of documents in the 
182060  ** file system. This is done because the full-text index doclist is required
182061  ** to calculate these values properly, and the full-text index doclist is
182062  ** not available for deferred tokens.
182063  */
182064  static int fts3ExprGlobalHitsCb(
182065    Fts3Expr *pExpr,                /* Phrase expression node */
182066    int iPhrase,                    /* Phrase number (numbered from zero) */
182067    void *pCtx                      /* Pointer to MatchInfo structure */
182068  ){
182069    MatchInfo *p = (MatchInfo *)pCtx;
182070    return sqlite3Fts3EvalPhraseStats(
182071        p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
182072    );
182073  }
182074  
182075  /*
182076  ** fts3ExprIterate() callback used to collect the "local" part of the
182077  ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
182078  ** array that are different for each row returned by the query.
182079  */
182080  static int fts3ExprLocalHitsCb(
182081    Fts3Expr *pExpr,                /* Phrase expression node */
182082    int iPhrase,                    /* Phrase number */
182083    void *pCtx                      /* Pointer to MatchInfo structure */
182084  ){
182085    int rc = SQLITE_OK;
182086    MatchInfo *p = (MatchInfo *)pCtx;
182087    int iStart = iPhrase * p->nCol * 3;
182088    int i;
182089  
182090    for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
182091      char *pCsr;
182092      rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
182093      if( pCsr ){
182094        p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
182095      }else{
182096        p->aMatchinfo[iStart+i*3] = 0;
182097      }
182098    }
182099  
182100    return rc;
182101  }
182102  
182103  static int fts3MatchinfoCheck(
182104    Fts3Table *pTab, 
182105    char cArg,
182106    char **pzErr
182107  ){
182108    if( (cArg==FTS3_MATCHINFO_NPHRASE)
182109     || (cArg==FTS3_MATCHINFO_NCOL)
182110     || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
182111     || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
182112     || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
182113     || (cArg==FTS3_MATCHINFO_LCS)
182114     || (cArg==FTS3_MATCHINFO_HITS)
182115     || (cArg==FTS3_MATCHINFO_LHITS)
182116     || (cArg==FTS3_MATCHINFO_LHITS_BM)
182117    ){
182118      return SQLITE_OK;
182119    }
182120    sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
182121    return SQLITE_ERROR;
182122  }
182123  
182124  static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
182125    int nVal;                       /* Number of integers output by cArg */
182126  
182127    switch( cArg ){
182128      case FTS3_MATCHINFO_NDOC:
182129      case FTS3_MATCHINFO_NPHRASE: 
182130      case FTS3_MATCHINFO_NCOL: 
182131        nVal = 1;
182132        break;
182133  
182134      case FTS3_MATCHINFO_AVGLENGTH:
182135      case FTS3_MATCHINFO_LENGTH:
182136      case FTS3_MATCHINFO_LCS:
182137        nVal = pInfo->nCol;
182138        break;
182139  
182140      case FTS3_MATCHINFO_LHITS:
182141        nVal = pInfo->nCol * pInfo->nPhrase;
182142        break;
182143  
182144      case FTS3_MATCHINFO_LHITS_BM:
182145        nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
182146        break;
182147  
182148      default:
182149        assert( cArg==FTS3_MATCHINFO_HITS );
182150        nVal = pInfo->nCol * pInfo->nPhrase * 3;
182151        break;
182152    }
182153  
182154    return nVal;
182155  }
182156  
182157  static int fts3MatchinfoSelectDoctotal(
182158    Fts3Table *pTab,
182159    sqlite3_stmt **ppStmt,
182160    sqlite3_int64 *pnDoc,
182161    const char **paLen
182162  ){
182163    sqlite3_stmt *pStmt;
182164    const char *a;
182165    sqlite3_int64 nDoc;
182166  
182167    if( !*ppStmt ){
182168      int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
182169      if( rc!=SQLITE_OK ) return rc;
182170    }
182171    pStmt = *ppStmt;
182172    assert( sqlite3_data_count(pStmt)==1 );
182173  
182174    a = sqlite3_column_blob(pStmt, 0);
182175    a += sqlite3Fts3GetVarint(a, &nDoc);
182176    if( nDoc==0 ) return FTS_CORRUPT_VTAB;
182177    *pnDoc = (u32)nDoc;
182178  
182179    if( paLen ) *paLen = a;
182180    return SQLITE_OK;
182181  }
182182  
182183  /*
182184  ** An instance of the following structure is used to store state while 
182185  ** iterating through a multi-column position-list corresponding to the
182186  ** hits for a single phrase on a single row in order to calculate the
182187  ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
182188  */
182189  typedef struct LcsIterator LcsIterator;
182190  struct LcsIterator {
182191    Fts3Expr *pExpr;                /* Pointer to phrase expression */
182192    int iPosOffset;                 /* Tokens count up to end of this phrase */
182193    char *pRead;                    /* Cursor used to iterate through aDoclist */
182194    int iPos;                       /* Current position */
182195  };
182196  
182197  /* 
182198  ** If LcsIterator.iCol is set to the following value, the iterator has
182199  ** finished iterating through all offsets for all columns.
182200  */
182201  #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
182202  
182203  static int fts3MatchinfoLcsCb(
182204    Fts3Expr *pExpr,                /* Phrase expression node */
182205    int iPhrase,                    /* Phrase number (numbered from zero) */
182206    void *pCtx                      /* Pointer to MatchInfo structure */
182207  ){
182208    LcsIterator *aIter = (LcsIterator *)pCtx;
182209    aIter[iPhrase].pExpr = pExpr;
182210    return SQLITE_OK;
182211  }
182212  
182213  /*
182214  ** Advance the iterator passed as an argument to the next position. Return
182215  ** 1 if the iterator is at EOF or if it now points to the start of the
182216  ** position list for the next column.
182217  */
182218  static int fts3LcsIteratorAdvance(LcsIterator *pIter){
182219    char *pRead = pIter->pRead;
182220    sqlite3_int64 iRead;
182221    int rc = 0;
182222  
182223    pRead += sqlite3Fts3GetVarint(pRead, &iRead);
182224    if( iRead==0 || iRead==1 ){
182225      pRead = 0;
182226      rc = 1;
182227    }else{
182228      pIter->iPos += (int)(iRead-2);
182229    }
182230  
182231    pIter->pRead = pRead;
182232    return rc;
182233  }
182234    
182235  /*
182236  ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
182237  **
182238  ** If the call is successful, the longest-common-substring lengths for each
182239  ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
182240  ** array before returning. SQLITE_OK is returned in this case.
182241  **
182242  ** Otherwise, if an error occurs, an SQLite error code is returned and the
182243  ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
182244  ** undefined.
182245  */
182246  static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
182247    LcsIterator *aIter;
182248    int i;
182249    int iCol;
182250    int nToken = 0;
182251    int rc = SQLITE_OK;
182252  
182253    /* Allocate and populate the array of LcsIterator objects. The array
182254    ** contains one element for each matchable phrase in the query.
182255    **/
182256    aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
182257    if( !aIter ) return SQLITE_NOMEM;
182258    memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
182259    (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
182260  
182261    for(i=0; i<pInfo->nPhrase; i++){
182262      LcsIterator *pIter = &aIter[i];
182263      nToken -= pIter->pExpr->pPhrase->nToken;
182264      pIter->iPosOffset = nToken;
182265    }
182266  
182267    for(iCol=0; iCol<pInfo->nCol; iCol++){
182268      int nLcs = 0;                 /* LCS value for this column */
182269      int nLive = 0;                /* Number of iterators in aIter not at EOF */
182270  
182271      for(i=0; i<pInfo->nPhrase; i++){
182272        LcsIterator *pIt = &aIter[i];
182273        rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
182274        if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
182275        if( pIt->pRead ){
182276          pIt->iPos = pIt->iPosOffset;
182277          fts3LcsIteratorAdvance(pIt);
182278          if( pIt->pRead==0 ){
182279            rc = FTS_CORRUPT_VTAB;
182280            goto matchinfo_lcs_out;
182281          }
182282          nLive++;
182283        }
182284      }
182285  
182286      while( nLive>0 ){
182287        LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
182288        int nThisLcs = 0;           /* LCS for the current iterator positions */
182289  
182290        for(i=0; i<pInfo->nPhrase; i++){
182291          LcsIterator *pIter = &aIter[i];
182292          if( pIter->pRead==0 ){
182293            /* This iterator is already at EOF for this column. */
182294            nThisLcs = 0;
182295          }else{
182296            if( pAdv==0 || pIter->iPos<pAdv->iPos ){
182297              pAdv = pIter;
182298            }
182299            if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
182300              nThisLcs++;
182301            }else{
182302              nThisLcs = 1;
182303            }
182304            if( nThisLcs>nLcs ) nLcs = nThisLcs;
182305          }
182306        }
182307        if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
182308      }
182309  
182310      pInfo->aMatchinfo[iCol] = nLcs;
182311    }
182312  
182313   matchinfo_lcs_out:
182314    sqlite3_free(aIter);
182315    return rc;
182316  }
182317  
182318  /*
182319  ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
182320  ** be returned by the matchinfo() function. Argument zArg contains the 
182321  ** format string passed as the second argument to matchinfo (or the
182322  ** default value "pcx" if no second argument was specified). The format
182323  ** string has already been validated and the pInfo->aMatchinfo[] array
182324  ** is guaranteed to be large enough for the output.
182325  **
182326  ** If bGlobal is true, then populate all fields of the matchinfo() output.
182327  ** If it is false, then assume that those fields that do not change between
182328  ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
182329  ** have already been populated.
182330  **
182331  ** Return SQLITE_OK if successful, or an SQLite error code if an error 
182332  ** occurs. If a value other than SQLITE_OK is returned, the state the
182333  ** pInfo->aMatchinfo[] buffer is left in is undefined.
182334  */
182335  static int fts3MatchinfoValues(
182336    Fts3Cursor *pCsr,               /* FTS3 cursor object */
182337    int bGlobal,                    /* True to grab the global stats */
182338    MatchInfo *pInfo,               /* Matchinfo context object */
182339    const char *zArg                /* Matchinfo format string */
182340  ){
182341    int rc = SQLITE_OK;
182342    int i;
182343    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
182344    sqlite3_stmt *pSelect = 0;
182345  
182346    for(i=0; rc==SQLITE_OK && zArg[i]; i++){
182347      pInfo->flag = zArg[i];
182348      switch( zArg[i] ){
182349        case FTS3_MATCHINFO_NPHRASE:
182350          if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
182351          break;
182352  
182353        case FTS3_MATCHINFO_NCOL:
182354          if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
182355          break;
182356          
182357        case FTS3_MATCHINFO_NDOC:
182358          if( bGlobal ){
182359            sqlite3_int64 nDoc = 0;
182360            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
182361            pInfo->aMatchinfo[0] = (u32)nDoc;
182362          }
182363          break;
182364  
182365        case FTS3_MATCHINFO_AVGLENGTH: 
182366          if( bGlobal ){
182367            sqlite3_int64 nDoc;     /* Number of rows in table */
182368            const char *a;          /* Aggregate column length array */
182369  
182370            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
182371            if( rc==SQLITE_OK ){
182372              int iCol;
182373              for(iCol=0; iCol<pInfo->nCol; iCol++){
182374                u32 iVal;
182375                sqlite3_int64 nToken;
182376                a += sqlite3Fts3GetVarint(a, &nToken);
182377                iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
182378                pInfo->aMatchinfo[iCol] = iVal;
182379              }
182380            }
182381          }
182382          break;
182383  
182384        case FTS3_MATCHINFO_LENGTH: {
182385          sqlite3_stmt *pSelectDocsize = 0;
182386          rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
182387          if( rc==SQLITE_OK ){
182388            int iCol;
182389            const char *a = sqlite3_column_blob(pSelectDocsize, 0);
182390            for(iCol=0; iCol<pInfo->nCol; iCol++){
182391              sqlite3_int64 nToken;
182392              a += sqlite3Fts3GetVarint(a, &nToken);
182393              pInfo->aMatchinfo[iCol] = (u32)nToken;
182394            }
182395          }
182396          sqlite3_reset(pSelectDocsize);
182397          break;
182398        }
182399  
182400        case FTS3_MATCHINFO_LCS:
182401          rc = fts3ExprLoadDoclists(pCsr, 0, 0);
182402          if( rc==SQLITE_OK ){
182403            rc = fts3MatchinfoLcs(pCsr, pInfo);
182404          }
182405          break;
182406  
182407        case FTS3_MATCHINFO_LHITS_BM:
182408        case FTS3_MATCHINFO_LHITS: {
182409          int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
182410          memset(pInfo->aMatchinfo, 0, nZero);
182411          rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
182412          break;
182413        }
182414  
182415        default: {
182416          Fts3Expr *pExpr;
182417          assert( zArg[i]==FTS3_MATCHINFO_HITS );
182418          pExpr = pCsr->pExpr;
182419          rc = fts3ExprLoadDoclists(pCsr, 0, 0);
182420          if( rc!=SQLITE_OK ) break;
182421          if( bGlobal ){
182422            if( pCsr->pDeferred ){
182423              rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
182424              if( rc!=SQLITE_OK ) break;
182425            }
182426            rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
182427            sqlite3Fts3EvalTestDeferred(pCsr, &rc);
182428            if( rc!=SQLITE_OK ) break;
182429          }
182430          (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
182431          break;
182432        }
182433      }
182434  
182435      pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
182436    }
182437  
182438    sqlite3_reset(pSelect);
182439    return rc;
182440  }
182441  
182442  
182443  /*
182444  ** Populate pCsr->aMatchinfo[] with data for the current row. The 
182445  ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
182446  */
182447  static void fts3GetMatchinfo(
182448    sqlite3_context *pCtx,        /* Return results here */
182449    Fts3Cursor *pCsr,               /* FTS3 Cursor object */
182450    const char *zArg                /* Second argument to matchinfo() function */
182451  ){
182452    MatchInfo sInfo;
182453    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
182454    int rc = SQLITE_OK;
182455    int bGlobal = 0;                /* Collect 'global' stats as well as local */
182456  
182457    u32 *aOut = 0;
182458    void (*xDestroyOut)(void*) = 0;
182459  
182460    memset(&sInfo, 0, sizeof(MatchInfo));
182461    sInfo.pCursor = pCsr;
182462    sInfo.nCol = pTab->nColumn;
182463  
182464    /* If there is cached matchinfo() data, but the format string for the 
182465    ** cache does not match the format string for this request, discard 
182466    ** the cached data. */
182467    if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
182468      sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
182469      pCsr->pMIBuffer = 0;
182470    }
182471  
182472    /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
182473    ** matchinfo function has been called for this query. In this case 
182474    ** allocate the array used to accumulate the matchinfo data and
182475    ** initialize those elements that are constant for every row.
182476    */
182477    if( pCsr->pMIBuffer==0 ){
182478      int nMatchinfo = 0;           /* Number of u32 elements in match-info */
182479      int i;                        /* Used to iterate through zArg */
182480  
182481      /* Determine the number of phrases in the query */
182482      pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
182483      sInfo.nPhrase = pCsr->nPhrase;
182484  
182485      /* Determine the number of integers in the buffer returned by this call. */
182486      for(i=0; zArg[i]; i++){
182487        char *zErr = 0;
182488        if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
182489          sqlite3_result_error(pCtx, zErr, -1);
182490          sqlite3_free(zErr);
182491          return;
182492        }
182493        nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
182494      }
182495  
182496      /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
182497      pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
182498      if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
182499  
182500      pCsr->isMatchinfoNeeded = 1;
182501      bGlobal = 1;
182502    }
182503  
182504    if( rc==SQLITE_OK ){
182505      xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
182506      if( xDestroyOut==0 ){
182507        rc = SQLITE_NOMEM;
182508      }
182509    }
182510  
182511    if( rc==SQLITE_OK ){
182512      sInfo.aMatchinfo = aOut;
182513      sInfo.nPhrase = pCsr->nPhrase;
182514      rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
182515      if( bGlobal ){
182516        fts3MIBufferSetGlobal(pCsr->pMIBuffer);
182517      }
182518    }
182519  
182520    if( rc!=SQLITE_OK ){
182521      sqlite3_result_error_code(pCtx, rc);
182522      if( xDestroyOut ) xDestroyOut(aOut);
182523    }else{
182524      int n = pCsr->pMIBuffer->nElem * sizeof(u32);
182525      sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
182526    }
182527  }
182528  
182529  /*
182530  ** Implementation of snippet() function.
182531  */
182532  SQLITE_PRIVATE void sqlite3Fts3Snippet(
182533    sqlite3_context *pCtx,          /* SQLite function call context */
182534    Fts3Cursor *pCsr,               /* Cursor object */
182535    const char *zStart,             /* Snippet start text - "<b>" */
182536    const char *zEnd,               /* Snippet end text - "</b>" */
182537    const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
182538    int iCol,                       /* Extract snippet from this column */
182539    int nToken                      /* Approximate number of tokens in snippet */
182540  ){
182541    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
182542    int rc = SQLITE_OK;
182543    int i;
182544    StrBuffer res = {0, 0, 0};
182545  
182546    /* The returned text includes up to four fragments of text extracted from
182547    ** the data in the current row. The first iteration of the for(...) loop
182548    ** below attempts to locate a single fragment of text nToken tokens in 
182549    ** size that contains at least one instance of all phrases in the query
182550    ** expression that appear in the current row. If such a fragment of text
182551    ** cannot be found, the second iteration of the loop attempts to locate
182552    ** a pair of fragments, and so on.
182553    */
182554    int nSnippet = 0;               /* Number of fragments in this snippet */
182555    SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
182556    int nFToken = -1;               /* Number of tokens in each fragment */
182557  
182558    if( !pCsr->pExpr ){
182559      sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
182560      return;
182561    }
182562  
182563    /* Limit the snippet length to 64 tokens. */
182564    if( nToken<-64 ) nToken = -64;
182565    if( nToken>+64 ) nToken = +64;
182566  
182567    for(nSnippet=1; 1; nSnippet++){
182568  
182569      int iSnip;                    /* Loop counter 0..nSnippet-1 */
182570      u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
182571      u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
182572  
182573      if( nToken>=0 ){
182574        nFToken = (nToken+nSnippet-1) / nSnippet;
182575      }else{
182576        nFToken = -1 * nToken;
182577      }
182578  
182579      for(iSnip=0; iSnip<nSnippet; iSnip++){
182580        int iBestScore = -1;        /* Best score of columns checked so far */
182581        int iRead;                  /* Used to iterate through columns */
182582        SnippetFragment *pFragment = &aSnippet[iSnip];
182583  
182584        memset(pFragment, 0, sizeof(*pFragment));
182585  
182586        /* Loop through all columns of the table being considered for snippets.
182587        ** If the iCol argument to this function was negative, this means all
182588        ** columns of the FTS3 table. Otherwise, only column iCol is considered.
182589        */
182590        for(iRead=0; iRead<pTab->nColumn; iRead++){
182591          SnippetFragment sF = {0, 0, 0, 0};
182592          int iS = 0;
182593          if( iCol>=0 && iRead!=iCol ) continue;
182594  
182595          /* Find the best snippet of nFToken tokens in column iRead. */
182596          rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
182597          if( rc!=SQLITE_OK ){
182598            goto snippet_out;
182599          }
182600          if( iS>iBestScore ){
182601            *pFragment = sF;
182602            iBestScore = iS;
182603          }
182604        }
182605  
182606        mCovered |= pFragment->covered;
182607      }
182608  
182609      /* If all query phrases seen by fts3BestSnippet() are present in at least
182610      ** one of the nSnippet snippet fragments, break out of the loop.
182611      */
182612      assert( (mCovered&mSeen)==mCovered );
182613      if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
182614    }
182615  
182616    assert( nFToken>0 );
182617  
182618    for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
182619      rc = fts3SnippetText(pCsr, &aSnippet[i], 
182620          i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
182621      );
182622    }
182623  
182624   snippet_out:
182625    sqlite3Fts3SegmentsClose(pTab);
182626    if( rc!=SQLITE_OK ){
182627      sqlite3_result_error_code(pCtx, rc);
182628      sqlite3_free(res.z);
182629    }else{
182630      sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
182631    }
182632  }
182633  
182634  
182635  typedef struct TermOffset TermOffset;
182636  typedef struct TermOffsetCtx TermOffsetCtx;
182637  
182638  struct TermOffset {
182639    char *pList;                    /* Position-list */
182640    int iPos;                       /* Position just read from pList */
182641    int iOff;                       /* Offset of this term from read positions */
182642  };
182643  
182644  struct TermOffsetCtx {
182645    Fts3Cursor *pCsr;
182646    int iCol;                       /* Column of table to populate aTerm for */
182647    int iTerm;
182648    sqlite3_int64 iDocid;
182649    TermOffset *aTerm;
182650  };
182651  
182652  /*
182653  ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
182654  */
182655  static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
182656    TermOffsetCtx *p = (TermOffsetCtx *)ctx;
182657    int nTerm;                      /* Number of tokens in phrase */
182658    int iTerm;                      /* For looping through nTerm phrase terms */
182659    char *pList;                    /* Pointer to position list for phrase */
182660    int iPos = 0;                   /* First position in position-list */
182661    int rc;
182662  
182663    UNUSED_PARAMETER(iPhrase);
182664    rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
182665    nTerm = pExpr->pPhrase->nToken;
182666    if( pList ){
182667      fts3GetDeltaPosition(&pList, &iPos);
182668      assert( iPos>=0 );
182669    }
182670  
182671    for(iTerm=0; iTerm<nTerm; iTerm++){
182672      TermOffset *pT = &p->aTerm[p->iTerm++];
182673      pT->iOff = nTerm-iTerm-1;
182674      pT->pList = pList;
182675      pT->iPos = iPos;
182676    }
182677  
182678    return rc;
182679  }
182680  
182681  /*
182682  ** Implementation of offsets() function.
182683  */
182684  SQLITE_PRIVATE void sqlite3Fts3Offsets(
182685    sqlite3_context *pCtx,          /* SQLite function call context */
182686    Fts3Cursor *pCsr                /* Cursor object */
182687  ){
182688    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
182689    sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
182690    int rc;                         /* Return Code */
182691    int nToken;                     /* Number of tokens in query */
182692    int iCol;                       /* Column currently being processed */
182693    StrBuffer res = {0, 0, 0};      /* Result string */
182694    TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
182695  
182696    if( !pCsr->pExpr ){
182697      sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
182698      return;
182699    }
182700  
182701    memset(&sCtx, 0, sizeof(sCtx));
182702    assert( pCsr->isRequireSeek==0 );
182703  
182704    /* Count the number of terms in the query */
182705    rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
182706    if( rc!=SQLITE_OK ) goto offsets_out;
182707  
182708    /* Allocate the array of TermOffset iterators. */
182709    sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
182710    if( 0==sCtx.aTerm ){
182711      rc = SQLITE_NOMEM;
182712      goto offsets_out;
182713    }
182714    sCtx.iDocid = pCsr->iPrevId;
182715    sCtx.pCsr = pCsr;
182716  
182717    /* Loop through the table columns, appending offset information to 
182718    ** string-buffer res for each column.
182719    */
182720    for(iCol=0; iCol<pTab->nColumn; iCol++){
182721      sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
182722      const char *ZDUMMY;           /* Dummy argument used with xNext() */
182723      int NDUMMY = 0;               /* Dummy argument used with xNext() */
182724      int iStart = 0;
182725      int iEnd = 0;
182726      int iCurrent = 0;
182727      const char *zDoc;
182728      int nDoc;
182729  
182730      /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
182731      ** no way that this operation can fail, so the return code from
182732      ** fts3ExprIterate() can be discarded.
182733      */
182734      sCtx.iCol = iCol;
182735      sCtx.iTerm = 0;
182736      (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
182737  
182738      /* Retreive the text stored in column iCol. If an SQL NULL is stored 
182739      ** in column iCol, jump immediately to the next iteration of the loop.
182740      ** If an OOM occurs while retrieving the data (this can happen if SQLite
182741      ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
182742      ** to the caller. 
182743      */
182744      zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
182745      nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
182746      if( zDoc==0 ){
182747        if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
182748          continue;
182749        }
182750        rc = SQLITE_NOMEM;
182751        goto offsets_out;
182752      }
182753  
182754      /* Initialize a tokenizer iterator to iterate through column iCol. */
182755      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
182756          zDoc, nDoc, &pC
182757      );
182758      if( rc!=SQLITE_OK ) goto offsets_out;
182759  
182760      rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
182761      while( rc==SQLITE_OK ){
182762        int i;                      /* Used to loop through terms */
182763        int iMinPos = 0x7FFFFFFF;   /* Position of next token */
182764        TermOffset *pTerm = 0;      /* TermOffset associated with next token */
182765  
182766        for(i=0; i<nToken; i++){
182767          TermOffset *pT = &sCtx.aTerm[i];
182768          if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
182769            iMinPos = pT->iPos-pT->iOff;
182770            pTerm = pT;
182771          }
182772        }
182773  
182774        if( !pTerm ){
182775          /* All offsets for this column have been gathered. */
182776          rc = SQLITE_DONE;
182777        }else{
182778          assert( iCurrent<=iMinPos );
182779          if( 0==(0xFE&*pTerm->pList) ){
182780            pTerm->pList = 0;
182781          }else{
182782            fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
182783          }
182784          while( rc==SQLITE_OK && iCurrent<iMinPos ){
182785            rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
182786          }
182787          if( rc==SQLITE_OK ){
182788            char aBuffer[64];
182789            sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
182790                "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
182791            );
182792            rc = fts3StringAppend(&res, aBuffer, -1);
182793          }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
182794            rc = FTS_CORRUPT_VTAB;
182795          }
182796        }
182797      }
182798      if( rc==SQLITE_DONE ){
182799        rc = SQLITE_OK;
182800      }
182801  
182802      pMod->xClose(pC);
182803      if( rc!=SQLITE_OK ) goto offsets_out;
182804    }
182805  
182806   offsets_out:
182807    sqlite3_free(sCtx.aTerm);
182808    assert( rc!=SQLITE_DONE );
182809    sqlite3Fts3SegmentsClose(pTab);
182810    if( rc!=SQLITE_OK ){
182811      sqlite3_result_error_code(pCtx,  rc);
182812      sqlite3_free(res.z);
182813    }else{
182814      sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
182815    }
182816    return;
182817  }
182818  
182819  /*
182820  ** Implementation of matchinfo() function.
182821  */
182822  SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
182823    sqlite3_context *pContext,      /* Function call context */
182824    Fts3Cursor *pCsr,               /* FTS3 table cursor */
182825    const char *zArg                /* Second arg to matchinfo() function */
182826  ){
182827    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
182828    const char *zFormat;
182829  
182830    if( zArg ){
182831      zFormat = zArg;
182832    }else{
182833      zFormat = FTS3_MATCHINFO_DEFAULT;
182834    }
182835  
182836    if( !pCsr->pExpr ){
182837      sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
182838      return;
182839    }else{
182840      /* Retrieve matchinfo() data. */
182841      fts3GetMatchinfo(pContext, pCsr, zFormat);
182842      sqlite3Fts3SegmentsClose(pTab);
182843    }
182844  }
182845  
182846  #endif
182847  
182848  /************** End of fts3_snippet.c ****************************************/
182849  /************** Begin file fts3_unicode.c ************************************/
182850  /*
182851  ** 2012 May 24
182852  **
182853  ** The author disclaims copyright to this source code.  In place of
182854  ** a legal notice, here is a blessing:
182855  **
182856  **    May you do good and not evil.
182857  **    May you find forgiveness for yourself and forgive others.
182858  **    May you share freely, never taking more than you give.
182859  **
182860  ******************************************************************************
182861  **
182862  ** Implementation of the "unicode" full-text-search tokenizer.
182863  */
182864  
182865  #ifndef SQLITE_DISABLE_FTS3_UNICODE
182866  
182867  /* #include "fts3Int.h" */
182868  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
182869  
182870  /* #include <assert.h> */
182871  /* #include <stdlib.h> */
182872  /* #include <stdio.h> */
182873  /* #include <string.h> */
182874  
182875  /* #include "fts3_tokenizer.h" */
182876  
182877  /*
182878  ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
182879  ** from the sqlite3 source file utf.c. If this file is compiled as part
182880  ** of the amalgamation, they are not required.
182881  */
182882  #ifndef SQLITE_AMALGAMATION
182883  
182884  static const unsigned char sqlite3Utf8Trans1[] = {
182885    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182886    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182887    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
182888    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
182889    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182890    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
182891    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
182892    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
182893  };
182894  
182895  #define READ_UTF8(zIn, zTerm, c)                           \
182896    c = *(zIn++);                                            \
182897    if( c>=0xc0 ){                                           \
182898      c = sqlite3Utf8Trans1[c-0xc0];                         \
182899      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
182900        c = (c<<6) + (0x3f & *(zIn++));                      \
182901      }                                                      \
182902      if( c<0x80                                             \
182903          || (c&0xFFFFF800)==0xD800                          \
182904          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
182905    }
182906  
182907  #define WRITE_UTF8(zOut, c) {                          \
182908    if( c<0x00080 ){                                     \
182909      *zOut++ = (u8)(c&0xFF);                            \
182910    }                                                    \
182911    else if( c<0x00800 ){                                \
182912      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
182913      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
182914    }                                                    \
182915    else if( c<0x10000 ){                                \
182916      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
182917      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
182918      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
182919    }else{                                               \
182920      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
182921      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
182922      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
182923      *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
182924    }                                                    \
182925  }
182926  
182927  #endif /* ifndef SQLITE_AMALGAMATION */
182928  
182929  typedef struct unicode_tokenizer unicode_tokenizer;
182930  typedef struct unicode_cursor unicode_cursor;
182931  
182932  struct unicode_tokenizer {
182933    sqlite3_tokenizer base;
182934    int eRemoveDiacritic;
182935    int nException;
182936    int *aiException;
182937  };
182938  
182939  struct unicode_cursor {
182940    sqlite3_tokenizer_cursor base;
182941    const unsigned char *aInput;    /* Input text being tokenized */
182942    int nInput;                     /* Size of aInput[] in bytes */
182943    int iOff;                       /* Current offset within aInput[] */
182944    int iToken;                     /* Index of next token to be returned */
182945    char *zToken;                   /* storage for current token */
182946    int nAlloc;                     /* space allocated at zToken */
182947  };
182948  
182949  
182950  /*
182951  ** Destroy a tokenizer allocated by unicodeCreate().
182952  */
182953  static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
182954    if( pTokenizer ){
182955      unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
182956      sqlite3_free(p->aiException);
182957      sqlite3_free(p);
182958    }
182959    return SQLITE_OK;
182960  }
182961  
182962  /*
182963  ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
182964  ** statement has specified that the tokenizer for this table shall consider
182965  ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
182966  ** token characters (if bAlnum==1).
182967  **
182968  ** For each codepoint in the zIn/nIn string, this function checks if the
182969  ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
182970  ** If so, no action is taken. Otherwise, the codepoint is added to the 
182971  ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
182972  ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
182973  ** codepoints in the aiException[] array.
182974  **
182975  ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
182976  ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
182977  ** It is not possible to change the behavior of the tokenizer with respect
182978  ** to these codepoints.
182979  */
182980  static int unicodeAddExceptions(
182981    unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
182982    int bAlnum,                     /* Replace Isalnum() return value with this */
182983    const char *zIn,                /* Array of characters to make exceptions */
182984    int nIn                         /* Length of z in bytes */
182985  ){
182986    const unsigned char *z = (const unsigned char *)zIn;
182987    const unsigned char *zTerm = &z[nIn];
182988    unsigned int iCode;
182989    int nEntry = 0;
182990  
182991    assert( bAlnum==0 || bAlnum==1 );
182992  
182993    while( z<zTerm ){
182994      READ_UTF8(z, zTerm, iCode);
182995      assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
182996      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
182997       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 
182998      ){
182999        nEntry++;
183000      }
183001    }
183002  
183003    if( nEntry ){
183004      int *aNew;                    /* New aiException[] array */
183005      int nNew;                     /* Number of valid entries in array aNew[] */
183006  
183007      aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
183008      if( aNew==0 ) return SQLITE_NOMEM;
183009      nNew = p->nException;
183010  
183011      z = (const unsigned char *)zIn;
183012      while( z<zTerm ){
183013        READ_UTF8(z, zTerm, iCode);
183014        if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
183015         && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
183016        ){
183017          int i, j;
183018          for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
183019          for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
183020          aNew[i] = (int)iCode;
183021          nNew++;
183022        }
183023      }
183024      p->aiException = aNew;
183025      p->nException = nNew;
183026    }
183027  
183028    return SQLITE_OK;
183029  }
183030  
183031  /*
183032  ** Return true if the p->aiException[] array contains the value iCode.
183033  */
183034  static int unicodeIsException(unicode_tokenizer *p, int iCode){
183035    if( p->nException>0 ){
183036      int *a = p->aiException;
183037      int iLo = 0;
183038      int iHi = p->nException-1;
183039  
183040      while( iHi>=iLo ){
183041        int iTest = (iHi + iLo) / 2;
183042        if( iCode==a[iTest] ){
183043          return 1;
183044        }else if( iCode>a[iTest] ){
183045          iLo = iTest+1;
183046        }else{
183047          iHi = iTest-1;
183048        }
183049      }
183050    }
183051  
183052    return 0;
183053  }
183054  
183055  /*
183056  ** Return true if, for the purposes of tokenization, codepoint iCode is
183057  ** considered a token character (not a separator).
183058  */
183059  static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
183060    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
183061    return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
183062  }
183063  
183064  /*
183065  ** Create a new tokenizer instance.
183066  */
183067  static int unicodeCreate(
183068    int nArg,                       /* Size of array argv[] */
183069    const char * const *azArg,      /* Tokenizer creation arguments */
183070    sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
183071  ){
183072    unicode_tokenizer *pNew;        /* New tokenizer object */
183073    int i;
183074    int rc = SQLITE_OK;
183075  
183076    pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
183077    if( pNew==NULL ) return SQLITE_NOMEM;
183078    memset(pNew, 0, sizeof(unicode_tokenizer));
183079    pNew->eRemoveDiacritic = 1;
183080  
183081    for(i=0; rc==SQLITE_OK && i<nArg; i++){
183082      const char *z = azArg[i];
183083      int n = (int)strlen(z);
183084  
183085      if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
183086        pNew->eRemoveDiacritic = 1;
183087      }
183088      else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
183089        pNew->eRemoveDiacritic = 0;
183090      }
183091      else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
183092        pNew->eRemoveDiacritic = 2;
183093      }
183094      else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
183095        rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
183096      }
183097      else if( n>=11 && memcmp("separators=", z, 11)==0 ){
183098        rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
183099      }
183100      else{
183101        /* Unrecognized argument */
183102        rc  = SQLITE_ERROR;
183103      }
183104    }
183105  
183106    if( rc!=SQLITE_OK ){
183107      unicodeDestroy((sqlite3_tokenizer *)pNew);
183108      pNew = 0;
183109    }
183110    *pp = (sqlite3_tokenizer *)pNew;
183111    return rc;
183112  }
183113  
183114  /*
183115  ** Prepare to begin tokenizing a particular string.  The input
183116  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
183117  ** used to incrementally tokenize this string is returned in 
183118  ** *ppCursor.
183119  */
183120  static int unicodeOpen(
183121    sqlite3_tokenizer *p,           /* The tokenizer */
183122    const char *aInput,             /* Input string */
183123    int nInput,                     /* Size of string aInput in bytes */
183124    sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
183125  ){
183126    unicode_cursor *pCsr;
183127  
183128    pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
183129    if( pCsr==0 ){
183130      return SQLITE_NOMEM;
183131    }
183132    memset(pCsr, 0, sizeof(unicode_cursor));
183133  
183134    pCsr->aInput = (const unsigned char *)aInput;
183135    if( aInput==0 ){
183136      pCsr->nInput = 0;
183137    }else if( nInput<0 ){
183138      pCsr->nInput = (int)strlen(aInput);
183139    }else{
183140      pCsr->nInput = nInput;
183141    }
183142  
183143    *pp = &pCsr->base;
183144    UNUSED_PARAMETER(p);
183145    return SQLITE_OK;
183146  }
183147  
183148  /*
183149  ** Close a tokenization cursor previously opened by a call to
183150  ** simpleOpen() above.
183151  */
183152  static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
183153    unicode_cursor *pCsr = (unicode_cursor *) pCursor;
183154    sqlite3_free(pCsr->zToken);
183155    sqlite3_free(pCsr);
183156    return SQLITE_OK;
183157  }
183158  
183159  /*
183160  ** Extract the next token from a tokenization cursor.  The cursor must
183161  ** have been opened by a prior call to simpleOpen().
183162  */
183163  static int unicodeNext(
183164    sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
183165    const char **paToken,           /* OUT: Token text */
183166    int *pnToken,                   /* OUT: Number of bytes at *paToken */
183167    int *piStart,                   /* OUT: Starting offset of token */
183168    int *piEnd,                     /* OUT: Ending offset of token */
183169    int *piPos                      /* OUT: Position integer of token */
183170  ){
183171    unicode_cursor *pCsr = (unicode_cursor *)pC;
183172    unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
183173    unsigned int iCode = 0;
183174    char *zOut;
183175    const unsigned char *z = &pCsr->aInput[pCsr->iOff];
183176    const unsigned char *zStart = z;
183177    const unsigned char *zEnd;
183178    const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
183179  
183180    /* Scan past any delimiter characters before the start of the next token.
183181    ** Return SQLITE_DONE early if this takes us all the way to the end of 
183182    ** the input.  */
183183    while( z<zTerm ){
183184      READ_UTF8(z, zTerm, iCode);
183185      if( unicodeIsAlnum(p, (int)iCode) ) break;
183186      zStart = z;
183187    }
183188    if( zStart>=zTerm ) return SQLITE_DONE;
183189  
183190    zOut = pCsr->zToken;
183191    do {
183192      int iOut;
183193  
183194      /* Grow the output buffer if required. */
183195      if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
183196        char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
183197        if( !zNew ) return SQLITE_NOMEM;
183198        zOut = &zNew[zOut - pCsr->zToken];
183199        pCsr->zToken = zNew;
183200        pCsr->nAlloc += 64;
183201      }
183202  
183203      /* Write the folded case of the last character read to the output */
183204      zEnd = z;
183205      iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
183206      if( iOut ){
183207        WRITE_UTF8(zOut, iOut);
183208      }
183209  
183210      /* If the cursor is not at EOF, read the next character */
183211      if( z>=zTerm ) break;
183212      READ_UTF8(z, zTerm, iCode);
183213    }while( unicodeIsAlnum(p, (int)iCode) 
183214         || sqlite3FtsUnicodeIsdiacritic((int)iCode)
183215    );
183216  
183217    /* Set the output variables and return. */
183218    pCsr->iOff = (int)(z - pCsr->aInput);
183219    *paToken = pCsr->zToken;
183220    *pnToken = (int)(zOut - pCsr->zToken);
183221    *piStart = (int)(zStart - pCsr->aInput);
183222    *piEnd = (int)(zEnd - pCsr->aInput);
183223    *piPos = pCsr->iToken++;
183224    return SQLITE_OK;
183225  }
183226  
183227  /*
183228  ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
183229  ** structure for the unicode tokenizer.
183230  */
183231  SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
183232    static const sqlite3_tokenizer_module module = {
183233      0,
183234      unicodeCreate,
183235      unicodeDestroy,
183236      unicodeOpen,
183237      unicodeClose,
183238      unicodeNext,
183239      0,
183240    };
183241    *ppModule = &module;
183242  }
183243  
183244  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
183245  #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
183246  
183247  /************** End of fts3_unicode.c ****************************************/
183248  /************** Begin file fts3_unicode2.c ***********************************/
183249  /*
183250  ** 2012-05-25
183251  **
183252  ** The author disclaims copyright to this source code.  In place of
183253  ** a legal notice, here is a blessing:
183254  **
183255  **    May you do good and not evil.
183256  **    May you find forgiveness for yourself and forgive others.
183257  **    May you share freely, never taking more than you give.
183258  **
183259  ******************************************************************************
183260  */
183261  
183262  /*
183263  ** DO NOT EDIT THIS MACHINE GENERATED FILE.
183264  */
183265  
183266  #ifndef SQLITE_DISABLE_FTS3_UNICODE
183267  #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
183268  
183269  /* #include <assert.h> */
183270  
183271  /*
183272  ** Return true if the argument corresponds to a unicode codepoint
183273  ** classified as either a letter or a number. Otherwise false.
183274  **
183275  ** The results are undefined if the value passed to this function
183276  ** is less than zero.
183277  */
183278  SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
183279    /* Each unsigned integer in the following array corresponds to a contiguous
183280    ** range of unicode codepoints that are not either letters or numbers (i.e.
183281    ** codepoints for which this function should return 0).
183282    **
183283    ** The most significant 22 bits in each 32-bit value contain the first 
183284    ** codepoint in the range. The least significant 10 bits are used to store
183285    ** the size of the range (always at least 1). In other words, the value 
183286    ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
183287    ** C. It is not possible to represent a range larger than 1023 codepoints 
183288    ** using this format.
183289    */
183290    static const unsigned int aEntry[] = {
183291      0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
183292      0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
183293      0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
183294      0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
183295      0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
183296      0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
183297      0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
183298      0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
183299      0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
183300      0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
183301      0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
183302      0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
183303      0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
183304      0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
183305      0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
183306      0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
183307      0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
183308      0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
183309      0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
183310      0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
183311      0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
183312      0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
183313      0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
183314      0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
183315      0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
183316      0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
183317      0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
183318      0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
183319      0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
183320      0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
183321      0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
183322      0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
183323      0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
183324      0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
183325      0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
183326      0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
183327      0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
183328      0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
183329      0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
183330      0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
183331      0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
183332      0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
183333      0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
183334      0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
183335      0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
183336      0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
183337      0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
183338      0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
183339      0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
183340      0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
183341      0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
183342      0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
183343      0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
183344      0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
183345      0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
183346      0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
183347      0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
183348      0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
183349      0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
183350      0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
183351      0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
183352      0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
183353      0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
183354      0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
183355      0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
183356      0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
183357      0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
183358      0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
183359      0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
183360      0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
183361      0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
183362      0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
183363      0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
183364      0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
183365      0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
183366      0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
183367      0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
183368      0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
183369      0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
183370      0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
183371      0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
183372      0x380400F0,
183373    };
183374    static const unsigned int aAscii[4] = {
183375      0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
183376    };
183377  
183378    if( (unsigned int)c<128 ){
183379      return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
183380    }else if( (unsigned int)c<(1<<22) ){
183381      unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
183382      int iRes = 0;
183383      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183384      int iLo = 0;
183385      while( iHi>=iLo ){
183386        int iTest = (iHi + iLo) / 2;
183387        if( key >= aEntry[iTest] ){
183388          iRes = iTest;
183389          iLo = iTest+1;
183390        }else{
183391          iHi = iTest-1;
183392        }
183393      }
183394      assert( aEntry[0]<key );
183395      assert( key>=aEntry[iRes] );
183396      return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
183397    }
183398    return 1;
183399  }
183400  
183401  
183402  /*
183403  ** If the argument is a codepoint corresponding to a lowercase letter
183404  ** in the ASCII range with a diacritic added, return the codepoint
183405  ** of the ASCII letter only. For example, if passed 235 - "LATIN
183406  ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
183407  ** E"). The resuls of passing a codepoint that corresponds to an
183408  ** uppercase letter are undefined.
183409  */
183410  static int remove_diacritic(int c, int bComplex){
183411    unsigned short aDia[] = {
183412          0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
183413       2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
183414       2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
183415       2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
183416       3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, 
183417       3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, 
183418       4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, 
183419       4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, 
183420       6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, 
183421      61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, 
183422      61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, 
183423      61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, 
183424      62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, 
183425      62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, 
183426      62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, 
183427      63182, 63242, 63274, 63310, 63368, 63390, 
183428    };
183429  #define HIBIT ((unsigned char)0x80)
183430    unsigned char aChar[] = {
183431      '\0',      'a',       'c',       'e',       'i',       'n',       
183432      'o',       'u',       'y',       'y',       'a',       'c',       
183433      'd',       'e',       'e',       'g',       'h',       'i',       
183434      'j',       'k',       'l',       'n',       'o',       'r',       
183435      's',       't',       'u',       'u',       'w',       'y',       
183436      'z',       'o',       'u',       'a',       'i',       'o',       
183437      'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       
183438      'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       
183439      'e',       'i',       'o',       'r',       'u',       's',       
183440      't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       
183441      'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',      
183442      '\0',      '\0',      '\0',      '\0',      'a',       'b',       
183443      'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, 
183444      'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, 
183445      'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       
183446      'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       
183447      's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       
183448      'w',       'x',       'y',       'z',       'h',       't',       
183449      'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, 
183450      'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, 
183451      'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       
183452    };
183453  
183454    unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
183455    int iRes = 0;
183456    int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
183457    int iLo = 0;
183458    while( iHi>=iLo ){
183459      int iTest = (iHi + iLo) / 2;
183460      if( key >= aDia[iTest] ){
183461        iRes = iTest;
183462        iLo = iTest+1;
183463      }else{
183464        iHi = iTest-1;
183465      }
183466    }
183467    assert( key>=aDia[iRes] );
183468    if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
183469    return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
183470  }
183471  
183472  
183473  /*
183474  ** Return true if the argument interpreted as a unicode codepoint
183475  ** is a diacritical modifier character.
183476  */
183477  SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
183478    unsigned int mask0 = 0x08029FDF;
183479    unsigned int mask1 = 0x000361F8;
183480    if( c<768 || c>817 ) return 0;
183481    return (c < 768+32) ?
183482        (mask0 & ((unsigned int)1 << (c-768))) :
183483        (mask1 & ((unsigned int)1 << (c-768-32)));
183484  }
183485  
183486  
183487  /*
183488  ** Interpret the argument as a unicode codepoint. If the codepoint
183489  ** is an upper case character that has a lower case equivalent,
183490  ** return the codepoint corresponding to the lower case version.
183491  ** Otherwise, return a copy of the argument.
183492  **
183493  ** The results are undefined if the value passed to this function
183494  ** is less than zero.
183495  */
183496  SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
183497    /* Each entry in the following array defines a rule for folding a range
183498    ** of codepoints to lower case. The rule applies to a range of nRange
183499    ** codepoints starting at codepoint iCode.
183500    **
183501    ** If the least significant bit in flags is clear, then the rule applies
183502    ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
183503    ** need to be folded). Or, if it is set, then the rule only applies to
183504    ** every second codepoint in the range, starting with codepoint C.
183505    **
183506    ** The 7 most significant bits in flags are an index into the aiOff[]
183507    ** array. If a specific codepoint C does require folding, then its lower
183508    ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
183509    **
183510    ** The contents of this array are generated by parsing the CaseFolding.txt
183511    ** file distributed as part of the "Unicode Character Database". See
183512    ** http://www.unicode.org for details.
183513    */
183514    static const struct TableEntry {
183515      unsigned short iCode;
183516      unsigned char flags;
183517      unsigned char nRange;
183518    } aEntry[] = {
183519      {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
183520      {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
183521      {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
183522      {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
183523      {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
183524      {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
183525      {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
183526      {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
183527      {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
183528      {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
183529      {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
183530      {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
183531      {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
183532      {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
183533      {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
183534      {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
183535      {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
183536      {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
183537      {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
183538      {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
183539      {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
183540      {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
183541      {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
183542      {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
183543      {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
183544      {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
183545      {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
183546      {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
183547      {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
183548      {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
183549      {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
183550      {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
183551      {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
183552      {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
183553      {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
183554      {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
183555      {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
183556      {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
183557      {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
183558      {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
183559      {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
183560      {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
183561      {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
183562      {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
183563      {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
183564      {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
183565      {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
183566      {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
183567      {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
183568      {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
183569      {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
183570      {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
183571      {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
183572      {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
183573      {65313, 14, 26},       
183574    };
183575    static const unsigned short aiOff[] = {
183576     1,     2,     8,     15,    16,    26,    28,    32,    
183577     37,    38,    40,    48,    63,    64,    69,    71,    
183578     79,    80,    116,   202,   203,   205,   206,   207,   
183579     209,   210,   211,   213,   214,   217,   218,   219,   
183580     775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
183581     54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
183582     57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
183583     65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
183584     65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
183585     65514, 65521, 65527, 65528, 65529, 
183586    };
183587  
183588    int ret = c;
183589  
183590    assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
183591  
183592    if( c<128 ){
183593      if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
183594    }else if( c<65536 ){
183595      const struct TableEntry *p;
183596      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
183597      int iLo = 0;
183598      int iRes = -1;
183599  
183600      assert( c>aEntry[0].iCode );
183601      while( iHi>=iLo ){
183602        int iTest = (iHi + iLo) / 2;
183603        int cmp = (c - aEntry[iTest].iCode);
183604        if( cmp>=0 ){
183605          iRes = iTest;
183606          iLo = iTest+1;
183607        }else{
183608          iHi = iTest-1;
183609        }
183610      }
183611  
183612      assert( iRes>=0 && c>=aEntry[iRes].iCode );
183613      p = &aEntry[iRes];
183614      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
183615        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
183616        assert( ret>0 );
183617      }
183618  
183619      if( eRemoveDiacritic ){
183620        ret = remove_diacritic(ret, eRemoveDiacritic==2);
183621      }
183622    }
183623    
183624    else if( c>=66560 && c<66600 ){
183625      ret = c + 40;
183626    }
183627  
183628    return ret;
183629  }
183630  #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
183631  #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
183632  
183633  /************** End of fts3_unicode2.c ***************************************/
183634  /************** Begin file json1.c *******************************************/
183635  /*
183636  ** 2015-08-12
183637  **
183638  ** The author disclaims copyright to this source code.  In place of
183639  ** a legal notice, here is a blessing:
183640  **
183641  **    May you do good and not evil.
183642  **    May you find forgiveness for yourself and forgive others.
183643  **    May you share freely, never taking more than you give.
183644  **
183645  ******************************************************************************
183646  **
183647  ** This SQLite extension implements JSON functions.  The interface is
183648  ** modeled after MySQL JSON functions:
183649  **
183650  **     https://dev.mysql.com/doc/refman/5.7/en/json.html
183651  **
183652  ** For the time being, all JSON is stored as pure text.  (We might add
183653  ** a JSONB type in the future which stores a binary encoding of JSON in
183654  ** a BLOB, but there is no support for JSONB in the current implementation.
183655  ** This implementation parses JSON text at 250 MB/s, so it is hard to see
183656  ** how JSONB might improve on that.)
183657  */
183658  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
183659  #if !defined(SQLITEINT_H)
183660  /* #include "sqlite3ext.h" */
183661  #endif
183662  SQLITE_EXTENSION_INIT1
183663  /* #include <assert.h> */
183664  /* #include <string.h> */
183665  /* #include <stdlib.h> */
183666  /* #include <stdarg.h> */
183667  
183668  /* Mark a function parameter as unused, to suppress nuisance compiler
183669  ** warnings. */
183670  #ifndef UNUSED_PARAM
183671  # define UNUSED_PARAM(X)  (void)(X)
183672  #endif
183673  
183674  #ifndef LARGEST_INT64
183675  # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
183676  # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
183677  #endif
183678  
183679  /*
183680  ** Versions of isspace(), isalnum() and isdigit() to which it is safe
183681  ** to pass signed char values.
183682  */
183683  #ifdef sqlite3Isdigit
183684     /* Use the SQLite core versions if this routine is part of the
183685     ** SQLite amalgamation */
183686  #  define safe_isdigit(x)  sqlite3Isdigit(x)
183687  #  define safe_isalnum(x)  sqlite3Isalnum(x)
183688  #  define safe_isxdigit(x) sqlite3Isxdigit(x)
183689  #else
183690     /* Use the standard library for separate compilation */
183691  #include <ctype.h>  /* amalgamator: keep */
183692  #  define safe_isdigit(x)  isdigit((unsigned char)(x))
183693  #  define safe_isalnum(x)  isalnum((unsigned char)(x))
183694  #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
183695  #endif
183696  
183697  /*
183698  ** Growing our own isspace() routine this way is twice as fast as
183699  ** the library isspace() function, resulting in a 7% overall performance
183700  ** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
183701  */
183702  static const char jsonIsSpace[] = {
183703    0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
183704    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183705    1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183706    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183707    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183708    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183709    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183710    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183711    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183712    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183713    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183714    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183715    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183716    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183717    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183718    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
183719  };
183720  #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
183721  
183722  #ifndef SQLITE_AMALGAMATION
183723    /* Unsigned integer types.  These are already defined in the sqliteInt.h,
183724    ** but the definitions need to be repeated for separate compilation. */
183725    typedef sqlite3_uint64 u64;
183726    typedef unsigned int u32;
183727    typedef unsigned short int u16;
183728    typedef unsigned char u8;
183729  #endif
183730  
183731  /* Objects */
183732  typedef struct JsonString JsonString;
183733  typedef struct JsonNode JsonNode;
183734  typedef struct JsonParse JsonParse;
183735  
183736  /* An instance of this object represents a JSON string
183737  ** under construction.  Really, this is a generic string accumulator
183738  ** that can be and is used to create strings other than JSON.
183739  */
183740  struct JsonString {
183741    sqlite3_context *pCtx;   /* Function context - put error messages here */
183742    char *zBuf;              /* Append JSON content here */
183743    u64 nAlloc;              /* Bytes of storage available in zBuf[] */
183744    u64 nUsed;               /* Bytes of zBuf[] currently used */
183745    u8 bStatic;              /* True if zBuf is static space */
183746    u8 bErr;                 /* True if an error has been encountered */
183747    char zSpace[100];        /* Initial static space */
183748  };
183749  
183750  /* JSON type values
183751  */
183752  #define JSON_NULL     0
183753  #define JSON_TRUE     1
183754  #define JSON_FALSE    2
183755  #define JSON_INT      3
183756  #define JSON_REAL     4
183757  #define JSON_STRING   5
183758  #define JSON_ARRAY    6
183759  #define JSON_OBJECT   7
183760  
183761  /* The "subtype" set for JSON values */
183762  #define JSON_SUBTYPE  74    /* Ascii for "J" */
183763  
183764  /*
183765  ** Names of the various JSON types:
183766  */
183767  static const char * const jsonType[] = {
183768    "null", "true", "false", "integer", "real", "text", "array", "object"
183769  };
183770  
183771  /* Bit values for the JsonNode.jnFlag field
183772  */
183773  #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
183774  #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
183775  #define JNODE_REMOVE  0x04         /* Do not output */
183776  #define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
183777  #define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
183778  #define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
183779  #define JNODE_LABEL   0x40         /* Is a label of an object */
183780  
183781  
183782  /* A single node of parsed JSON
183783  */
183784  struct JsonNode {
183785    u8 eType;              /* One of the JSON_ type values */
183786    u8 jnFlags;            /* JNODE flags */
183787    u32 n;                 /* Bytes of content, or number of sub-nodes */
183788    union {
183789      const char *zJContent; /* Content for INT, REAL, and STRING */
183790      u32 iAppend;           /* More terms for ARRAY and OBJECT */
183791      u32 iKey;              /* Key for ARRAY objects in json_tree() */
183792      u32 iReplace;          /* Replacement content for JNODE_REPLACE */
183793      JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
183794    } u;
183795  };
183796  
183797  /* A completely parsed JSON string
183798  */
183799  struct JsonParse {
183800    u32 nNode;         /* Number of slots of aNode[] used */
183801    u32 nAlloc;        /* Number of slots of aNode[] allocated */
183802    JsonNode *aNode;   /* Array of nodes containing the parse */
183803    const char *zJson; /* Original JSON string */
183804    u32 *aUp;          /* Index of parent of each node */
183805    u8 oom;            /* Set to true if out of memory */
183806    u8 nErr;           /* Number of errors seen */
183807    u16 iDepth;        /* Nesting depth */
183808    int nJson;         /* Length of the zJson string in bytes */
183809    u32 iHold;         /* Replace cache line with the lowest iHold value */
183810  };
183811  
183812  /*
183813  ** Maximum nesting depth of JSON for this implementation.
183814  **
183815  ** This limit is needed to avoid a stack overflow in the recursive
183816  ** descent parser.  A depth of 2000 is far deeper than any sane JSON
183817  ** should go.
183818  */
183819  #define JSON_MAX_DEPTH  2000
183820  
183821  /**************************************************************************
183822  ** Utility routines for dealing with JsonString objects
183823  **************************************************************************/
183824  
183825  /* Set the JsonString object to an empty string
183826  */
183827  static void jsonZero(JsonString *p){
183828    p->zBuf = p->zSpace;
183829    p->nAlloc = sizeof(p->zSpace);
183830    p->nUsed = 0;
183831    p->bStatic = 1;
183832  }
183833  
183834  /* Initialize the JsonString object
183835  */
183836  static void jsonInit(JsonString *p, sqlite3_context *pCtx){
183837    p->pCtx = pCtx;
183838    p->bErr = 0;
183839    jsonZero(p);
183840  }
183841  
183842  
183843  /* Free all allocated memory and reset the JsonString object back to its
183844  ** initial state.
183845  */
183846  static void jsonReset(JsonString *p){
183847    if( !p->bStatic ) sqlite3_free(p->zBuf);
183848    jsonZero(p);
183849  }
183850  
183851  
183852  /* Report an out-of-memory (OOM) condition 
183853  */
183854  static void jsonOom(JsonString *p){
183855    p->bErr = 1;
183856    sqlite3_result_error_nomem(p->pCtx);
183857    jsonReset(p);
183858  }
183859  
183860  /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
183861  ** Return zero on success.  Return non-zero on an OOM error
183862  */
183863  static int jsonGrow(JsonString *p, u32 N){
183864    u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
183865    char *zNew;
183866    if( p->bStatic ){
183867      if( p->bErr ) return 1;
183868      zNew = sqlite3_malloc64(nTotal);
183869      if( zNew==0 ){
183870        jsonOom(p);
183871        return SQLITE_NOMEM;
183872      }
183873      memcpy(zNew, p->zBuf, (size_t)p->nUsed);
183874      p->zBuf = zNew;
183875      p->bStatic = 0;
183876    }else{
183877      zNew = sqlite3_realloc64(p->zBuf, nTotal);
183878      if( zNew==0 ){
183879        jsonOom(p);
183880        return SQLITE_NOMEM;
183881      }
183882      p->zBuf = zNew;
183883    }
183884    p->nAlloc = nTotal;
183885    return SQLITE_OK;
183886  }
183887  
183888  /* Append N bytes from zIn onto the end of the JsonString string.
183889  */
183890  static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
183891    if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
183892    memcpy(p->zBuf+p->nUsed, zIn, N);
183893    p->nUsed += N;
183894  }
183895  
183896  /* Append formatted text (not to exceed N bytes) to the JsonString.
183897  */
183898  static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
183899    va_list ap;
183900    if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
183901    va_start(ap, zFormat);
183902    sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
183903    va_end(ap);
183904    p->nUsed += (int)strlen(p->zBuf+p->nUsed);
183905  }
183906  
183907  /* Append a single character
183908  */
183909  static void jsonAppendChar(JsonString *p, char c){
183910    if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
183911    p->zBuf[p->nUsed++] = c;
183912  }
183913  
183914  /* Append a comma separator to the output buffer, if the previous
183915  ** character is not '[' or '{'.
183916  */
183917  static void jsonAppendSeparator(JsonString *p){
183918    char c;
183919    if( p->nUsed==0 ) return;
183920    c = p->zBuf[p->nUsed-1];
183921    if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
183922  }
183923  
183924  /* Append the N-byte string in zIn to the end of the JsonString string
183925  ** under construction.  Enclose the string in "..." and escape
183926  ** any double-quotes or backslash characters contained within the
183927  ** string.
183928  */
183929  static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
183930    u32 i;
183931    if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
183932    p->zBuf[p->nUsed++] = '"';
183933    for(i=0; i<N; i++){
183934      unsigned char c = ((unsigned const char*)zIn)[i];
183935      if( c=='"' || c=='\\' ){
183936        json_simple_escape:
183937        if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
183938        p->zBuf[p->nUsed++] = '\\';
183939      }else if( c<=0x1f ){
183940        static const char aSpecial[] = {
183941           0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
183942           0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
183943        };
183944        assert( sizeof(aSpecial)==32 );
183945        assert( aSpecial['\b']=='b' );
183946        assert( aSpecial['\f']=='f' );
183947        assert( aSpecial['\n']=='n' );
183948        assert( aSpecial['\r']=='r' );
183949        assert( aSpecial['\t']=='t' );
183950        if( aSpecial[c] ){
183951          c = aSpecial[c];
183952          goto json_simple_escape;
183953        }
183954        if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
183955        p->zBuf[p->nUsed++] = '\\';
183956        p->zBuf[p->nUsed++] = 'u';
183957        p->zBuf[p->nUsed++] = '0';
183958        p->zBuf[p->nUsed++] = '0';
183959        p->zBuf[p->nUsed++] = '0' + (c>>4);
183960        c = "0123456789abcdef"[c&0xf];
183961      }
183962      p->zBuf[p->nUsed++] = c;
183963    }
183964    p->zBuf[p->nUsed++] = '"';
183965    assert( p->nUsed<p->nAlloc );
183966  }
183967  
183968  /*
183969  ** Append a function parameter value to the JSON string under 
183970  ** construction.
183971  */
183972  static void jsonAppendValue(
183973    JsonString *p,                 /* Append to this JSON string */
183974    sqlite3_value *pValue          /* Value to append */
183975  ){
183976    switch( sqlite3_value_type(pValue) ){
183977      case SQLITE_NULL: {
183978        jsonAppendRaw(p, "null", 4);
183979        break;
183980      }
183981      case SQLITE_INTEGER:
183982      case SQLITE_FLOAT: {
183983        const char *z = (const char*)sqlite3_value_text(pValue);
183984        u32 n = (u32)sqlite3_value_bytes(pValue);
183985        jsonAppendRaw(p, z, n);
183986        break;
183987      }
183988      case SQLITE_TEXT: {
183989        const char *z = (const char*)sqlite3_value_text(pValue);
183990        u32 n = (u32)sqlite3_value_bytes(pValue);
183991        if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
183992          jsonAppendRaw(p, z, n);
183993        }else{
183994          jsonAppendString(p, z, n);
183995        }
183996        break;
183997      }
183998      default: {
183999        if( p->bErr==0 ){
184000          sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
184001          p->bErr = 2;
184002          jsonReset(p);
184003        }
184004        break;
184005      }
184006    }
184007  }
184008  
184009  
184010  /* Make the JSON in p the result of the SQL function.
184011  */
184012  static void jsonResult(JsonString *p){
184013    if( p->bErr==0 ){
184014      sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, 
184015                            p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
184016                            SQLITE_UTF8);
184017      jsonZero(p);
184018    }
184019    assert( p->bStatic );
184020  }
184021  
184022  /**************************************************************************
184023  ** Utility routines for dealing with JsonNode and JsonParse objects
184024  **************************************************************************/
184025  
184026  /*
184027  ** Return the number of consecutive JsonNode slots need to represent
184028  ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
184029  ** OBJECT types, the number might be larger.
184030  **
184031  ** Appended elements are not counted.  The value returned is the number
184032  ** by which the JsonNode counter should increment in order to go to the
184033  ** next peer value.
184034  */
184035  static u32 jsonNodeSize(JsonNode *pNode){
184036    return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
184037  }
184038  
184039  /*
184040  ** Reclaim all memory allocated by a JsonParse object.  But do not
184041  ** delete the JsonParse object itself.
184042  */
184043  static void jsonParseReset(JsonParse *pParse){
184044    sqlite3_free(pParse->aNode);
184045    pParse->aNode = 0;
184046    pParse->nNode = 0;
184047    pParse->nAlloc = 0;
184048    sqlite3_free(pParse->aUp);
184049    pParse->aUp = 0;
184050  }
184051  
184052  /*
184053  ** Free a JsonParse object that was obtained from sqlite3_malloc().
184054  */
184055  static void jsonParseFree(JsonParse *pParse){
184056    jsonParseReset(pParse);
184057    sqlite3_free(pParse);
184058  }
184059  
184060  /*
184061  ** Convert the JsonNode pNode into a pure JSON string and
184062  ** append to pOut.  Subsubstructure is also included.  Return
184063  ** the number of JsonNode objects that are encoded.
184064  */
184065  static void jsonRenderNode(
184066    JsonNode *pNode,               /* The node to render */
184067    JsonString *pOut,              /* Write JSON here */
184068    sqlite3_value **aReplace       /* Replacement values */
184069  ){
184070    if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
184071      if( pNode->jnFlags & JNODE_REPLACE ){
184072        jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
184073        return;
184074      }
184075      pNode = pNode->u.pPatch;
184076    }
184077    switch( pNode->eType ){
184078      default: {
184079        assert( pNode->eType==JSON_NULL );
184080        jsonAppendRaw(pOut, "null", 4);
184081        break;
184082      }
184083      case JSON_TRUE: {
184084        jsonAppendRaw(pOut, "true", 4);
184085        break;
184086      }
184087      case JSON_FALSE: {
184088        jsonAppendRaw(pOut, "false", 5);
184089        break;
184090      }
184091      case JSON_STRING: {
184092        if( pNode->jnFlags & JNODE_RAW ){
184093          jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
184094          break;
184095        }
184096        /* Fall through into the next case */
184097      }
184098      case JSON_REAL:
184099      case JSON_INT: {
184100        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
184101        break;
184102      }
184103      case JSON_ARRAY: {
184104        u32 j = 1;
184105        jsonAppendChar(pOut, '[');
184106        for(;;){
184107          while( j<=pNode->n ){
184108            if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
184109              jsonAppendSeparator(pOut);
184110              jsonRenderNode(&pNode[j], pOut, aReplace);
184111            }
184112            j += jsonNodeSize(&pNode[j]);
184113          }
184114          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
184115          pNode = &pNode[pNode->u.iAppend];
184116          j = 1;
184117        }
184118        jsonAppendChar(pOut, ']');
184119        break;
184120      }
184121      case JSON_OBJECT: {
184122        u32 j = 1;
184123        jsonAppendChar(pOut, '{');
184124        for(;;){
184125          while( j<=pNode->n ){
184126            if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
184127              jsonAppendSeparator(pOut);
184128              jsonRenderNode(&pNode[j], pOut, aReplace);
184129              jsonAppendChar(pOut, ':');
184130              jsonRenderNode(&pNode[j+1], pOut, aReplace);
184131            }
184132            j += 1 + jsonNodeSize(&pNode[j+1]);
184133          }
184134          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
184135          pNode = &pNode[pNode->u.iAppend];
184136          j = 1;
184137        }
184138        jsonAppendChar(pOut, '}');
184139        break;
184140      }
184141    }
184142  }
184143  
184144  /*
184145  ** Return a JsonNode and all its descendents as a JSON string.
184146  */
184147  static void jsonReturnJson(
184148    JsonNode *pNode,            /* Node to return */
184149    sqlite3_context *pCtx,      /* Return value for this function */
184150    sqlite3_value **aReplace    /* Array of replacement values */
184151  ){
184152    JsonString s;
184153    jsonInit(&s, pCtx);
184154    jsonRenderNode(pNode, &s, aReplace);
184155    jsonResult(&s);
184156    sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
184157  }
184158  
184159  /*
184160  ** Make the JsonNode the return value of the function.
184161  */
184162  static void jsonReturn(
184163    JsonNode *pNode,            /* Node to return */
184164    sqlite3_context *pCtx,      /* Return value for this function */
184165    sqlite3_value **aReplace    /* Array of replacement values */
184166  ){
184167    switch( pNode->eType ){
184168      default: {
184169        assert( pNode->eType==JSON_NULL );
184170        sqlite3_result_null(pCtx);
184171        break;
184172      }
184173      case JSON_TRUE: {
184174        sqlite3_result_int(pCtx, 1);
184175        break;
184176      }
184177      case JSON_FALSE: {
184178        sqlite3_result_int(pCtx, 0);
184179        break;
184180      }
184181      case JSON_INT: {
184182        sqlite3_int64 i = 0;
184183        const char *z = pNode->u.zJContent;
184184        if( z[0]=='-' ){ z++; }
184185        while( z[0]>='0' && z[0]<='9' ){
184186          unsigned v = *(z++) - '0';
184187          if( i>=LARGEST_INT64/10 ){
184188            if( i>LARGEST_INT64/10 ) goto int_as_real;
184189            if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
184190            if( v==9 ) goto int_as_real;
184191            if( v==8 ){
184192              if( pNode->u.zJContent[0]=='-' ){
184193                sqlite3_result_int64(pCtx, SMALLEST_INT64);
184194                goto int_done;
184195              }else{
184196                goto int_as_real;
184197              }
184198            }
184199          }
184200          i = i*10 + v;
184201        }
184202        if( pNode->u.zJContent[0]=='-' ){ i = -i; }
184203        sqlite3_result_int64(pCtx, i);
184204        int_done:
184205        break;
184206        int_as_real: /* fall through to real */;
184207      }
184208      case JSON_REAL: {
184209        double r;
184210  #ifdef SQLITE_AMALGAMATION
184211        const char *z = pNode->u.zJContent;
184212        sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
184213  #else
184214        r = strtod(pNode->u.zJContent, 0);
184215  #endif
184216        sqlite3_result_double(pCtx, r);
184217        break;
184218      }
184219      case JSON_STRING: {
184220  #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
184221        ** json_insert() and json_replace() and those routines do not
184222        ** call jsonReturn() */
184223        if( pNode->jnFlags & JNODE_RAW ){
184224          sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
184225                              SQLITE_TRANSIENT);
184226        }else 
184227  #endif
184228        assert( (pNode->jnFlags & JNODE_RAW)==0 );
184229        if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
184230          /* JSON formatted without any backslash-escapes */
184231          sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
184232                              SQLITE_TRANSIENT);
184233        }else{
184234          /* Translate JSON formatted string into raw text */
184235          u32 i;
184236          u32 n = pNode->n;
184237          const char *z = pNode->u.zJContent;
184238          char *zOut;
184239          u32 j;
184240          zOut = sqlite3_malloc( n+1 );
184241          if( zOut==0 ){
184242            sqlite3_result_error_nomem(pCtx);
184243            break;
184244          }
184245          for(i=1, j=0; i<n-1; i++){
184246            char c = z[i];
184247            if( c!='\\' ){
184248              zOut[j++] = c;
184249            }else{
184250              c = z[++i];
184251              if( c=='u' ){
184252                u32 v = 0, k;
184253                for(k=0; k<4; i++, k++){
184254                  assert( i<n-2 );
184255                  c = z[i+1];
184256                  assert( safe_isxdigit(c) );
184257                  if( c<='9' ) v = v*16 + c - '0';
184258                  else if( c<='F' ) v = v*16 + c - 'A' + 10;
184259                  else v = v*16 + c - 'a' + 10;
184260                }
184261                if( v==0 ) break;
184262                if( v<=0x7f ){
184263                  zOut[j++] = (char)v;
184264                }else if( v<=0x7ff ){
184265                  zOut[j++] = (char)(0xc0 | (v>>6));
184266                  zOut[j++] = 0x80 | (v&0x3f);
184267                }else{
184268                  zOut[j++] = (char)(0xe0 | (v>>12));
184269                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
184270                  zOut[j++] = 0x80 | (v&0x3f);
184271                }
184272              }else{
184273                if( c=='b' ){
184274                  c = '\b';
184275                }else if( c=='f' ){
184276                  c = '\f';
184277                }else if( c=='n' ){
184278                  c = '\n';
184279                }else if( c=='r' ){
184280                  c = '\r';
184281                }else if( c=='t' ){
184282                  c = '\t';
184283                }
184284                zOut[j++] = c;
184285              }
184286            }
184287          }
184288          zOut[j] = 0;
184289          sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
184290        }
184291        break;
184292      }
184293      case JSON_ARRAY:
184294      case JSON_OBJECT: {
184295        jsonReturnJson(pNode, pCtx, aReplace);
184296        break;
184297      }
184298    }
184299  }
184300  
184301  /* Forward reference */
184302  static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
184303  
184304  /*
184305  ** A macro to hint to the compiler that a function should not be
184306  ** inlined.
184307  */
184308  #if defined(__GNUC__)
184309  #  define JSON_NOINLINE  __attribute__((noinline))
184310  #elif defined(_MSC_VER) && _MSC_VER>=1310
184311  #  define JSON_NOINLINE  __declspec(noinline)
184312  #else
184313  #  define JSON_NOINLINE
184314  #endif
184315  
184316  
184317  static JSON_NOINLINE int jsonParseAddNodeExpand(
184318    JsonParse *pParse,        /* Append the node to this object */
184319    u32 eType,                /* Node type */
184320    u32 n,                    /* Content size or sub-node count */
184321    const char *zContent      /* Content */
184322  ){
184323    u32 nNew;
184324    JsonNode *pNew;
184325    assert( pParse->nNode>=pParse->nAlloc );
184326    if( pParse->oom ) return -1;
184327    nNew = pParse->nAlloc*2 + 10;
184328    pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
184329    if( pNew==0 ){
184330      pParse->oom = 1;
184331      return -1;
184332    }
184333    pParse->nAlloc = nNew;
184334    pParse->aNode = pNew;
184335    assert( pParse->nNode<pParse->nAlloc );
184336    return jsonParseAddNode(pParse, eType, n, zContent);
184337  }
184338  
184339  /*
184340  ** Create a new JsonNode instance based on the arguments and append that
184341  ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
184342  ** new node, or -1 if a memory allocation fails.
184343  */
184344  static int jsonParseAddNode(
184345    JsonParse *pParse,        /* Append the node to this object */
184346    u32 eType,                /* Node type */
184347    u32 n,                    /* Content size or sub-node count */
184348    const char *zContent      /* Content */
184349  ){
184350    JsonNode *p;
184351    if( pParse->nNode>=pParse->nAlloc ){
184352      return jsonParseAddNodeExpand(pParse, eType, n, zContent);
184353    }
184354    p = &pParse->aNode[pParse->nNode];
184355    p->eType = (u8)eType;
184356    p->jnFlags = 0;
184357    p->n = n;
184358    p->u.zJContent = zContent;
184359    return pParse->nNode++;
184360  }
184361  
184362  /*
184363  ** Return true if z[] begins with 4 (or more) hexadecimal digits
184364  */
184365  static int jsonIs4Hex(const char *z){
184366    int i;
184367    for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
184368    return 1;
184369  }
184370  
184371  /*
184372  ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
184373  ** index of the first character past the end of the value parsed.
184374  **
184375  ** Return negative for a syntax error.  Special cases:  return -2 if the
184376  ** first non-whitespace character is '}' and return -3 if the first
184377  ** non-whitespace character is ']'.
184378  */
184379  static int jsonParseValue(JsonParse *pParse, u32 i){
184380    char c;
184381    u32 j;
184382    int iThis;
184383    int x;
184384    JsonNode *pNode;
184385    const char *z = pParse->zJson;
184386    while( safe_isspace(z[i]) ){ i++; }
184387    if( (c = z[i])=='{' ){
184388      /* Parse object */
184389      iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
184390      if( iThis<0 ) return -1;
184391      for(j=i+1;;j++){
184392        while( safe_isspace(z[j]) ){ j++; }
184393        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
184394        x = jsonParseValue(pParse, j);
184395        if( x<0 ){
184396          pParse->iDepth--;
184397          if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
184398          return -1;
184399        }
184400        if( pParse->oom ) return -1;
184401        pNode = &pParse->aNode[pParse->nNode-1];
184402        if( pNode->eType!=JSON_STRING ) return -1;
184403        pNode->jnFlags |= JNODE_LABEL;
184404        j = x;
184405        while( safe_isspace(z[j]) ){ j++; }
184406        if( z[j]!=':' ) return -1;
184407        j++;
184408        x = jsonParseValue(pParse, j);
184409        pParse->iDepth--;
184410        if( x<0 ) return -1;
184411        j = x;
184412        while( safe_isspace(z[j]) ){ j++; }
184413        c = z[j];
184414        if( c==',' ) continue;
184415        if( c!='}' ) return -1;
184416        break;
184417      }
184418      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
184419      return j+1;
184420    }else if( c=='[' ){
184421      /* Parse array */
184422      iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
184423      if( iThis<0 ) return -1;
184424      for(j=i+1;;j++){
184425        while( safe_isspace(z[j]) ){ j++; }
184426        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
184427        x = jsonParseValue(pParse, j);
184428        pParse->iDepth--;
184429        if( x<0 ){
184430          if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
184431          return -1;
184432        }
184433        j = x;
184434        while( safe_isspace(z[j]) ){ j++; }
184435        c = z[j];
184436        if( c==',' ) continue;
184437        if( c!=']' ) return -1;
184438        break;
184439      }
184440      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
184441      return j+1;
184442    }else if( c=='"' ){
184443      /* Parse string */
184444      u8 jnFlags = 0;
184445      j = i+1;
184446      for(;;){
184447        c = z[j];
184448        if( (c & ~0x1f)==0 ){
184449          /* Control characters are not allowed in strings */
184450          return -1;
184451        }
184452        if( c=='\\' ){
184453          c = z[++j];
184454          if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
184455             || c=='n' || c=='r' || c=='t'
184456             || (c=='u' && jsonIs4Hex(z+j+1)) ){
184457            jnFlags = JNODE_ESCAPE;
184458          }else{
184459            return -1;
184460          }
184461        }else if( c=='"' ){
184462          break;
184463        }
184464        j++;
184465      }
184466      jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
184467      if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
184468      return j+1;
184469    }else if( c=='n'
184470           && strncmp(z+i,"null",4)==0
184471           && !safe_isalnum(z[i+4]) ){
184472      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
184473      return i+4;
184474    }else if( c=='t'
184475           && strncmp(z+i,"true",4)==0
184476           && !safe_isalnum(z[i+4]) ){
184477      jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
184478      return i+4;
184479    }else if( c=='f'
184480           && strncmp(z+i,"false",5)==0
184481           && !safe_isalnum(z[i+5]) ){
184482      jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
184483      return i+5;
184484    }else if( c=='-' || (c>='0' && c<='9') ){
184485      /* Parse number */
184486      u8 seenDP = 0;
184487      u8 seenE = 0;
184488      assert( '-' < '0' );
184489      if( c<='0' ){
184490        j = c=='-' ? i+1 : i;
184491        if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
184492      }
184493      j = i+1;
184494      for(;; j++){
184495        c = z[j];
184496        if( c>='0' && c<='9' ) continue;
184497        if( c=='.' ){
184498          if( z[j-1]=='-' ) return -1;
184499          if( seenDP ) return -1;
184500          seenDP = 1;
184501          continue;
184502        }
184503        if( c=='e' || c=='E' ){
184504          if( z[j-1]<'0' ) return -1;
184505          if( seenE ) return -1;
184506          seenDP = seenE = 1;
184507          c = z[j+1];
184508          if( c=='+' || c=='-' ){
184509            j++;
184510            c = z[j+1];
184511          }
184512          if( c<'0' || c>'9' ) return -1;
184513          continue;
184514        }
184515        break;
184516      }
184517      if( z[j-1]<'0' ) return -1;
184518      jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
184519                          j - i, &z[i]);
184520      return j;
184521    }else if( c=='}' ){
184522      return -2;  /* End of {...} */
184523    }else if( c==']' ){
184524      return -3;  /* End of [...] */
184525    }else if( c==0 ){
184526      return 0;   /* End of file */
184527    }else{
184528      return -1;  /* Syntax error */
184529    }
184530  }
184531  
184532  /*
184533  ** Parse a complete JSON string.  Return 0 on success or non-zero if there
184534  ** are any errors.  If an error occurs, free all memory associated with
184535  ** pParse.
184536  **
184537  ** pParse is uninitialized when this routine is called.
184538  */
184539  static int jsonParse(
184540    JsonParse *pParse,           /* Initialize and fill this JsonParse object */
184541    sqlite3_context *pCtx,       /* Report errors here */
184542    const char *zJson            /* Input JSON text to be parsed */
184543  ){
184544    int i;
184545    memset(pParse, 0, sizeof(*pParse));
184546    if( zJson==0 ) return 1;
184547    pParse->zJson = zJson;
184548    i = jsonParseValue(pParse, 0);
184549    if( pParse->oom ) i = -1;
184550    if( i>0 ){
184551      assert( pParse->iDepth==0 );
184552      while( safe_isspace(zJson[i]) ) i++;
184553      if( zJson[i] ) i = -1;
184554    }
184555    if( i<=0 ){
184556      if( pCtx!=0 ){
184557        if( pParse->oom ){
184558          sqlite3_result_error_nomem(pCtx);
184559        }else{
184560          sqlite3_result_error(pCtx, "malformed JSON", -1);
184561        }
184562      }
184563      jsonParseReset(pParse);
184564      return 1;
184565    }
184566    return 0;
184567  }
184568  
184569  /* Mark node i of pParse as being a child of iParent.  Call recursively
184570  ** to fill in all the descendants of node i.
184571  */
184572  static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
184573    JsonNode *pNode = &pParse->aNode[i];
184574    u32 j;
184575    pParse->aUp[i] = iParent;
184576    switch( pNode->eType ){
184577      case JSON_ARRAY: {
184578        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
184579          jsonParseFillInParentage(pParse, i+j, i);
184580        }
184581        break;
184582      }
184583      case JSON_OBJECT: {
184584        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
184585          pParse->aUp[i+j] = i;
184586          jsonParseFillInParentage(pParse, i+j+1, i);
184587        }
184588        break;
184589      }
184590      default: {
184591        break;
184592      }
184593    }
184594  }
184595  
184596  /*
184597  ** Compute the parentage of all nodes in a completed parse.
184598  */
184599  static int jsonParseFindParents(JsonParse *pParse){
184600    u32 *aUp;
184601    assert( pParse->aUp==0 );
184602    aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
184603    if( aUp==0 ){
184604      pParse->oom = 1;
184605      return SQLITE_NOMEM;
184606    }
184607    jsonParseFillInParentage(pParse, 0, 0);
184608    return SQLITE_OK;
184609  }
184610  
184611  /*
184612  ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
184613  */
184614  #define JSON_CACHE_ID  (-429938)  /* First cache entry */
184615  #define JSON_CACHE_SZ  4          /* Max number of cache entries */
184616  
184617  /*
184618  ** Obtain a complete parse of the JSON found in the first argument
184619  ** of the argv array.  Use the sqlite3_get_auxdata() cache for this
184620  ** parse if it is available.  If the cache is not available or if it
184621  ** is no longer valid, parse the JSON again and return the new parse,
184622  ** and also register the new parse so that it will be available for
184623  ** future sqlite3_get_auxdata() calls.
184624  */
184625  static JsonParse *jsonParseCached(
184626    sqlite3_context *pCtx,
184627    sqlite3_value **argv,
184628    sqlite3_context *pErrCtx
184629  ){
184630    const char *zJson = (const char*)sqlite3_value_text(argv[0]);
184631    int nJson = sqlite3_value_bytes(argv[0]);
184632    JsonParse *p;
184633    JsonParse *pMatch = 0;
184634    int iKey;
184635    int iMinKey = 0;
184636    u32 iMinHold = 0xffffffff;
184637    u32 iMaxHold = 0;
184638    if( zJson==0 ) return 0;
184639    for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
184640      p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
184641      if( p==0 ){
184642        iMinKey = iKey;
184643        break;
184644      }
184645      if( pMatch==0
184646       && p->nJson==nJson
184647       && memcmp(p->zJson,zJson,nJson)==0
184648      ){
184649        p->nErr = 0;
184650        pMatch = p;
184651      }else if( p->iHold<iMinHold ){
184652        iMinHold = p->iHold;
184653        iMinKey = iKey;
184654      }
184655      if( p->iHold>iMaxHold ){
184656        iMaxHold = p->iHold;
184657      }
184658    }
184659    if( pMatch ){
184660      pMatch->nErr = 0;
184661      pMatch->iHold = iMaxHold+1;
184662      return pMatch;
184663    }
184664    p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
184665    if( p==0 ){
184666      sqlite3_result_error_nomem(pCtx);
184667      return 0;
184668    }
184669    memset(p, 0, sizeof(*p));
184670    p->zJson = (char*)&p[1];
184671    memcpy((char*)p->zJson, zJson, nJson+1);
184672    if( jsonParse(p, pErrCtx, p->zJson) ){
184673      sqlite3_free(p);
184674      return 0;
184675    }
184676    p->nJson = nJson;
184677    p->iHold = iMaxHold+1;
184678    sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
184679                        (void(*)(void*))jsonParseFree);
184680    return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
184681  }
184682  
184683  /*
184684  ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
184685  ** a match.
184686  */
184687  static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
184688    if( pNode->jnFlags & JNODE_RAW ){
184689      if( pNode->n!=nKey ) return 0;
184690      return strncmp(pNode->u.zJContent, zKey, nKey)==0;
184691    }else{
184692      if( pNode->n!=nKey+2 ) return 0;
184693      return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
184694    }
184695  }
184696  
184697  /* forward declaration */
184698  static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
184699  
184700  /*
184701  ** Search along zPath to find the node specified.  Return a pointer
184702  ** to that node, or NULL if zPath is malformed or if there is no such
184703  ** node.
184704  **
184705  ** If pApnd!=0, then try to append new nodes to complete zPath if it is
184706  ** possible to do so and if no existing node corresponds to zPath.  If
184707  ** new nodes are appended *pApnd is set to 1.
184708  */
184709  static JsonNode *jsonLookupStep(
184710    JsonParse *pParse,      /* The JSON to search */
184711    u32 iRoot,              /* Begin the search at this node */
184712    const char *zPath,      /* The path to search */
184713    int *pApnd,             /* Append nodes to complete path if not NULL */
184714    const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
184715  ){
184716    u32 i, j, nKey;
184717    const char *zKey;
184718    JsonNode *pRoot = &pParse->aNode[iRoot];
184719    if( zPath[0]==0 ) return pRoot;
184720    if( zPath[0]=='.' ){
184721      if( pRoot->eType!=JSON_OBJECT ) return 0;
184722      zPath++;
184723      if( zPath[0]=='"' ){
184724        zKey = zPath + 1;
184725        for(i=1; zPath[i] && zPath[i]!='"'; i++){}
184726        nKey = i-1;
184727        if( zPath[i] ){
184728          i++;
184729        }else{
184730          *pzErr = zPath;
184731          return 0;
184732        }
184733      }else{
184734        zKey = zPath;
184735        for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
184736        nKey = i;
184737      }
184738      if( nKey==0 ){
184739        *pzErr = zPath;
184740        return 0;
184741      }
184742      j = 1;
184743      for(;;){
184744        while( j<=pRoot->n ){
184745          if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
184746            return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
184747          }
184748          j++;
184749          j += jsonNodeSize(&pRoot[j]);
184750        }
184751        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
184752        iRoot += pRoot->u.iAppend;
184753        pRoot = &pParse->aNode[iRoot];
184754        j = 1;
184755      }
184756      if( pApnd ){
184757        u32 iStart, iLabel;
184758        JsonNode *pNode;
184759        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
184760        iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
184761        zPath += i;
184762        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
184763        if( pParse->oom ) return 0;
184764        if( pNode ){
184765          pRoot = &pParse->aNode[iRoot];
184766          pRoot->u.iAppend = iStart - iRoot;
184767          pRoot->jnFlags |= JNODE_APPEND;
184768          pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
184769        }
184770        return pNode;
184771      }
184772    }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
184773      if( pRoot->eType!=JSON_ARRAY ) return 0;
184774      i = 0;
184775      j = 1;
184776      while( safe_isdigit(zPath[j]) ){
184777        i = i*10 + zPath[j] - '0';
184778        j++;
184779      }
184780      if( zPath[j]!=']' ){
184781        *pzErr = zPath;
184782        return 0;
184783      }
184784      zPath += j + 1;
184785      j = 1;
184786      for(;;){
184787        while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
184788          if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
184789          j += jsonNodeSize(&pRoot[j]);
184790        }
184791        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
184792        iRoot += pRoot->u.iAppend;
184793        pRoot = &pParse->aNode[iRoot];
184794        j = 1;
184795      }
184796      if( j<=pRoot->n ){
184797        return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
184798      }
184799      if( i==0 && pApnd ){
184800        u32 iStart;
184801        JsonNode *pNode;
184802        iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
184803        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
184804        if( pParse->oom ) return 0;
184805        if( pNode ){
184806          pRoot = &pParse->aNode[iRoot];
184807          pRoot->u.iAppend = iStart - iRoot;
184808          pRoot->jnFlags |= JNODE_APPEND;
184809        }
184810        return pNode;
184811      }
184812    }else{
184813      *pzErr = zPath;
184814    }
184815    return 0;
184816  }
184817  
184818  /*
184819  ** Append content to pParse that will complete zPath.  Return a pointer
184820  ** to the inserted node, or return NULL if the append fails.
184821  */
184822  static JsonNode *jsonLookupAppend(
184823    JsonParse *pParse,     /* Append content to the JSON parse */
184824    const char *zPath,     /* Description of content to append */
184825    int *pApnd,            /* Set this flag to 1 */
184826    const char **pzErr     /* Make this point to any syntax error */
184827  ){
184828    *pApnd = 1;
184829    if( zPath[0]==0 ){
184830      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
184831      return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
184832    }
184833    if( zPath[0]=='.' ){
184834      jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
184835    }else if( strncmp(zPath,"[0]",3)==0 ){
184836      jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
184837    }else{
184838      return 0;
184839    }
184840    if( pParse->oom ) return 0;
184841    return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
184842  }
184843  
184844  /*
184845  ** Return the text of a syntax error message on a JSON path.  Space is
184846  ** obtained from sqlite3_malloc().
184847  */
184848  static char *jsonPathSyntaxError(const char *zErr){
184849    return sqlite3_mprintf("JSON path error near '%q'", zErr);
184850  }
184851  
184852  /*
184853  ** Do a node lookup using zPath.  Return a pointer to the node on success.
184854  ** Return NULL if not found or if there is an error.
184855  **
184856  ** On an error, write an error message into pCtx and increment the
184857  ** pParse->nErr counter.
184858  **
184859  ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
184860  ** nodes are appended.
184861  */
184862  static JsonNode *jsonLookup(
184863    JsonParse *pParse,      /* The JSON to search */
184864    const char *zPath,      /* The path to search */
184865    int *pApnd,             /* Append nodes to complete path if not NULL */
184866    sqlite3_context *pCtx   /* Report errors here, if not NULL */
184867  ){
184868    const char *zErr = 0;
184869    JsonNode *pNode = 0;
184870    char *zMsg;
184871  
184872    if( zPath==0 ) return 0;
184873    if( zPath[0]!='$' ){
184874      zErr = zPath;
184875      goto lookup_err;
184876    }
184877    zPath++;
184878    pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
184879    if( zErr==0 ) return pNode;
184880  
184881  lookup_err:
184882    pParse->nErr++;
184883    assert( zErr!=0 && pCtx!=0 );
184884    zMsg = jsonPathSyntaxError(zErr);
184885    if( zMsg ){
184886      sqlite3_result_error(pCtx, zMsg, -1);
184887      sqlite3_free(zMsg);
184888    }else{
184889      sqlite3_result_error_nomem(pCtx);
184890    }
184891    return 0;
184892  }
184893  
184894  
184895  /*
184896  ** Report the wrong number of arguments for json_insert(), json_replace()
184897  ** or json_set().
184898  */
184899  static void jsonWrongNumArgs(
184900    sqlite3_context *pCtx,
184901    const char *zFuncName
184902  ){
184903    char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
184904                                 zFuncName);
184905    sqlite3_result_error(pCtx, zMsg, -1);
184906    sqlite3_free(zMsg);     
184907  }
184908  
184909  /*
184910  ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
184911  */
184912  static void jsonRemoveAllNulls(JsonNode *pNode){
184913    int i, n;
184914    assert( pNode->eType==JSON_OBJECT );
184915    n = pNode->n;
184916    for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
184917      switch( pNode[i].eType ){
184918        case JSON_NULL:
184919          pNode[i].jnFlags |= JNODE_REMOVE;
184920          break;
184921        case JSON_OBJECT:
184922          jsonRemoveAllNulls(&pNode[i]);
184923          break;
184924      }
184925    }
184926  }
184927  
184928  
184929  /****************************************************************************
184930  ** SQL functions used for testing and debugging
184931  ****************************************************************************/
184932  
184933  #ifdef SQLITE_DEBUG
184934  /*
184935  ** The json_parse(JSON) function returns a string which describes
184936  ** a parse of the JSON provided.  Or it returns NULL if JSON is not
184937  ** well-formed.
184938  */
184939  static void jsonParseFunc(
184940    sqlite3_context *ctx,
184941    int argc,
184942    sqlite3_value **argv
184943  ){
184944    JsonString s;       /* Output string - not real JSON */
184945    JsonParse x;        /* The parse */
184946    u32 i;
184947  
184948    assert( argc==1 );
184949    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
184950    jsonParseFindParents(&x);
184951    jsonInit(&s, ctx);
184952    for(i=0; i<x.nNode; i++){
184953      const char *zType;
184954      if( x.aNode[i].jnFlags & JNODE_LABEL ){
184955        assert( x.aNode[i].eType==JSON_STRING );
184956        zType = "label";
184957      }else{
184958        zType = jsonType[x.aNode[i].eType];
184959      }
184960      jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
184961                 i, zType, x.aNode[i].n, x.aUp[i]);
184962      if( x.aNode[i].u.zJContent!=0 ){
184963        jsonAppendRaw(&s, " ", 1);
184964        jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
184965      }
184966      jsonAppendRaw(&s, "\n", 1);
184967    }
184968    jsonParseReset(&x);
184969    jsonResult(&s);
184970  }
184971  
184972  /*
184973  ** The json_test1(JSON) function return true (1) if the input is JSON
184974  ** text generated by another json function.  It returns (0) if the input
184975  ** is not known to be JSON.
184976  */
184977  static void jsonTest1Func(
184978    sqlite3_context *ctx,
184979    int argc,
184980    sqlite3_value **argv
184981  ){
184982    UNUSED_PARAM(argc);
184983    sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
184984  }
184985  #endif /* SQLITE_DEBUG */
184986  
184987  /****************************************************************************
184988  ** Scalar SQL function implementations
184989  ****************************************************************************/
184990  
184991  /*
184992  ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
184993  ** corresponding to the SQL value input.  Mostly this means putting 
184994  ** double-quotes around strings and returning the unquoted string "null"
184995  ** when given a NULL input.
184996  */
184997  static void jsonQuoteFunc(
184998    sqlite3_context *ctx,
184999    int argc,
185000    sqlite3_value **argv
185001  ){
185002    JsonString jx;
185003    UNUSED_PARAM(argc);
185004  
185005    jsonInit(&jx, ctx);
185006    jsonAppendValue(&jx, argv[0]);
185007    jsonResult(&jx);
185008    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185009  }
185010  
185011  /*
185012  ** Implementation of the json_array(VALUE,...) function.  Return a JSON
185013  ** array that contains all values given in arguments.  Or if any argument
185014  ** is a BLOB, throw an error.
185015  */
185016  static void jsonArrayFunc(
185017    sqlite3_context *ctx,
185018    int argc,
185019    sqlite3_value **argv
185020  ){
185021    int i;
185022    JsonString jx;
185023  
185024    jsonInit(&jx, ctx);
185025    jsonAppendChar(&jx, '[');
185026    for(i=0; i<argc; i++){
185027      jsonAppendSeparator(&jx);
185028      jsonAppendValue(&jx, argv[i]);
185029    }
185030    jsonAppendChar(&jx, ']');
185031    jsonResult(&jx);
185032    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185033  }
185034  
185035  
185036  /*
185037  ** json_array_length(JSON)
185038  ** json_array_length(JSON, PATH)
185039  **
185040  ** Return the number of elements in the top-level JSON array.  
185041  ** Return 0 if the input is not a well-formed JSON array.
185042  */
185043  static void jsonArrayLengthFunc(
185044    sqlite3_context *ctx,
185045    int argc,
185046    sqlite3_value **argv
185047  ){
185048    JsonParse *p;          /* The parse */
185049    sqlite3_int64 n = 0;
185050    u32 i;
185051    JsonNode *pNode;
185052  
185053    p = jsonParseCached(ctx, argv, ctx);
185054    if( p==0 ) return;
185055    assert( p->nNode );
185056    if( argc==2 ){
185057      const char *zPath = (const char*)sqlite3_value_text(argv[1]);
185058      pNode = jsonLookup(p, zPath, 0, ctx);
185059    }else{
185060      pNode = p->aNode;
185061    }
185062    if( pNode==0 ){
185063      return;
185064    }
185065    if( pNode->eType==JSON_ARRAY ){
185066      assert( (pNode->jnFlags & JNODE_APPEND)==0 );
185067      for(i=1; i<=pNode->n; n++){
185068        i += jsonNodeSize(&pNode[i]);
185069      }
185070    }
185071    sqlite3_result_int64(ctx, n);
185072  }
185073  
185074  /*
185075  ** json_extract(JSON, PATH, ...)
185076  **
185077  ** Return the element described by PATH.  Return NULL if there is no
185078  ** PATH element.  If there are multiple PATHs, then return a JSON array
185079  ** with the result from each path.  Throw an error if the JSON or any PATH
185080  ** is malformed.
185081  */
185082  static void jsonExtractFunc(
185083    sqlite3_context *ctx,
185084    int argc,
185085    sqlite3_value **argv
185086  ){
185087    JsonParse *p;          /* The parse */
185088    JsonNode *pNode;
185089    const char *zPath;
185090    JsonString jx;
185091    int i;
185092  
185093    if( argc<2 ) return;
185094    p = jsonParseCached(ctx, argv, ctx);
185095    if( p==0 ) return;
185096    jsonInit(&jx, ctx);
185097    jsonAppendChar(&jx, '[');
185098    for(i=1; i<argc; i++){
185099      zPath = (const char*)sqlite3_value_text(argv[i]);
185100      pNode = jsonLookup(p, zPath, 0, ctx);
185101      if( p->nErr ) break;
185102      if( argc>2 ){
185103        jsonAppendSeparator(&jx);
185104        if( pNode ){
185105          jsonRenderNode(pNode, &jx, 0);
185106        }else{
185107          jsonAppendRaw(&jx, "null", 4);
185108        }
185109      }else if( pNode ){
185110        jsonReturn(pNode, ctx, 0);
185111      }
185112    }
185113    if( argc>2 && i==argc ){
185114      jsonAppendChar(&jx, ']');
185115      jsonResult(&jx);
185116      sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185117    }
185118    jsonReset(&jx);
185119  }
185120  
185121  /* This is the RFC 7396 MergePatch algorithm.
185122  */
185123  static JsonNode *jsonMergePatch(
185124    JsonParse *pParse,   /* The JSON parser that contains the TARGET */
185125    u32 iTarget,         /* Node of the TARGET in pParse */
185126    JsonNode *pPatch     /* The PATCH */
185127  ){
185128    u32 i, j;
185129    u32 iRoot;
185130    JsonNode *pTarget;
185131    if( pPatch->eType!=JSON_OBJECT ){
185132      return pPatch;
185133    }
185134    assert( iTarget>=0 && iTarget<pParse->nNode );
185135    pTarget = &pParse->aNode[iTarget];
185136    assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
185137    if( pTarget->eType!=JSON_OBJECT ){
185138      jsonRemoveAllNulls(pPatch);
185139      return pPatch;
185140    }
185141    iRoot = iTarget;
185142    for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
185143      u32 nKey;
185144      const char *zKey;
185145      assert( pPatch[i].eType==JSON_STRING );
185146      assert( pPatch[i].jnFlags & JNODE_LABEL );
185147      nKey = pPatch[i].n;
185148      zKey = pPatch[i].u.zJContent;
185149      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
185150      for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
185151        assert( pTarget[j].eType==JSON_STRING );
185152        assert( pTarget[j].jnFlags & JNODE_LABEL );
185153        assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
185154        if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
185155          if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
185156          if( pPatch[i+1].eType==JSON_NULL ){
185157            pTarget[j+1].jnFlags |= JNODE_REMOVE;
185158          }else{
185159            JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
185160            if( pNew==0 ) return 0;
185161            pTarget = &pParse->aNode[iTarget];
185162            if( pNew!=&pTarget[j+1] ){
185163              pTarget[j+1].u.pPatch = pNew;
185164              pTarget[j+1].jnFlags |= JNODE_PATCH;
185165            }
185166          }
185167          break;
185168        }
185169      }
185170      if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
185171        int iStart, iPatch;
185172        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
185173        jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
185174        iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
185175        if( pParse->oom ) return 0;
185176        jsonRemoveAllNulls(pPatch);
185177        pTarget = &pParse->aNode[iTarget];
185178        pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
185179        pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
185180        iRoot = iStart;
185181        pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
185182        pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
185183      }
185184    }
185185    return pTarget;
185186  }
185187  
185188  /*
185189  ** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
185190  ** object that is the result of running the RFC 7396 MergePatch() algorithm
185191  ** on the two arguments.
185192  */
185193  static void jsonPatchFunc(
185194    sqlite3_context *ctx,
185195    int argc,
185196    sqlite3_value **argv
185197  ){
185198    JsonParse x;     /* The JSON that is being patched */
185199    JsonParse y;     /* The patch */
185200    JsonNode *pResult;   /* The result of the merge */
185201  
185202    UNUSED_PARAM(argc);
185203    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
185204    if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
185205      jsonParseReset(&x);
185206      return;
185207    }
185208    pResult = jsonMergePatch(&x, 0, y.aNode);
185209    assert( pResult!=0 || x.oom );
185210    if( pResult ){
185211      jsonReturnJson(pResult, ctx, 0);
185212    }else{
185213      sqlite3_result_error_nomem(ctx);
185214    }
185215    jsonParseReset(&x);
185216    jsonParseReset(&y);
185217  }
185218  
185219  
185220  /*
185221  ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
185222  ** object that contains all name/value given in arguments.  Or if any name
185223  ** is not a string or if any value is a BLOB, throw an error.
185224  */
185225  static void jsonObjectFunc(
185226    sqlite3_context *ctx,
185227    int argc,
185228    sqlite3_value **argv
185229  ){
185230    int i;
185231    JsonString jx;
185232    const char *z;
185233    u32 n;
185234  
185235    if( argc&1 ){
185236      sqlite3_result_error(ctx, "json_object() requires an even number "
185237                                    "of arguments", -1);
185238      return;
185239    }
185240    jsonInit(&jx, ctx);
185241    jsonAppendChar(&jx, '{');
185242    for(i=0; i<argc; i+=2){
185243      if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
185244        sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
185245        jsonReset(&jx);
185246        return;
185247      }
185248      jsonAppendSeparator(&jx);
185249      z = (const char*)sqlite3_value_text(argv[i]);
185250      n = (u32)sqlite3_value_bytes(argv[i]);
185251      jsonAppendString(&jx, z, n);
185252      jsonAppendChar(&jx, ':');
185253      jsonAppendValue(&jx, argv[i+1]);
185254    }
185255    jsonAppendChar(&jx, '}');
185256    jsonResult(&jx);
185257    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185258  }
185259  
185260  
185261  /*
185262  ** json_remove(JSON, PATH, ...)
185263  **
185264  ** Remove the named elements from JSON and return the result.  malformed
185265  ** JSON or PATH arguments result in an error.
185266  */
185267  static void jsonRemoveFunc(
185268    sqlite3_context *ctx,
185269    int argc,
185270    sqlite3_value **argv
185271  ){
185272    JsonParse x;          /* The parse */
185273    JsonNode *pNode;
185274    const char *zPath;
185275    u32 i;
185276  
185277    if( argc<1 ) return;
185278    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
185279    assert( x.nNode );
185280    for(i=1; i<(u32)argc; i++){
185281      zPath = (const char*)sqlite3_value_text(argv[i]);
185282      if( zPath==0 ) goto remove_done;
185283      pNode = jsonLookup(&x, zPath, 0, ctx);
185284      if( x.nErr ) goto remove_done;
185285      if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
185286    }
185287    if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
185288      jsonReturnJson(x.aNode, ctx, 0);
185289    }
185290  remove_done:
185291    jsonParseReset(&x);
185292  }
185293  
185294  /*
185295  ** json_replace(JSON, PATH, VALUE, ...)
185296  **
185297  ** Replace the value at PATH with VALUE.  If PATH does not already exist,
185298  ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
185299  */
185300  static void jsonReplaceFunc(
185301    sqlite3_context *ctx,
185302    int argc,
185303    sqlite3_value **argv
185304  ){
185305    JsonParse x;          /* The parse */
185306    JsonNode *pNode;
185307    const char *zPath;
185308    u32 i;
185309  
185310    if( argc<1 ) return;
185311    if( (argc&1)==0 ) {
185312      jsonWrongNumArgs(ctx, "replace");
185313      return;
185314    }
185315    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
185316    assert( x.nNode );
185317    for(i=1; i<(u32)argc; i+=2){
185318      zPath = (const char*)sqlite3_value_text(argv[i]);
185319      pNode = jsonLookup(&x, zPath, 0, ctx);
185320      if( x.nErr ) goto replace_err;
185321      if( pNode ){
185322        pNode->jnFlags |= (u8)JNODE_REPLACE;
185323        pNode->u.iReplace = i + 1;
185324      }
185325    }
185326    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
185327      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
185328    }else{
185329      jsonReturnJson(x.aNode, ctx, argv);
185330    }
185331  replace_err:
185332    jsonParseReset(&x);
185333  }
185334  
185335  /*
185336  ** json_set(JSON, PATH, VALUE, ...)
185337  **
185338  ** Set the value at PATH to VALUE.  Create the PATH if it does not already
185339  ** exist.  Overwrite existing values that do exist.
185340  ** If JSON or PATH is malformed, throw an error.
185341  **
185342  ** json_insert(JSON, PATH, VALUE, ...)
185343  **
185344  ** Create PATH and initialize it to VALUE.  If PATH already exists, this
185345  ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
185346  */
185347  static void jsonSetFunc(
185348    sqlite3_context *ctx,
185349    int argc,
185350    sqlite3_value **argv
185351  ){
185352    JsonParse x;          /* The parse */
185353    JsonNode *pNode;
185354    const char *zPath;
185355    u32 i;
185356    int bApnd;
185357    int bIsSet = *(int*)sqlite3_user_data(ctx);
185358  
185359    if( argc<1 ) return;
185360    if( (argc&1)==0 ) {
185361      jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
185362      return;
185363    }
185364    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
185365    assert( x.nNode );
185366    for(i=1; i<(u32)argc; i+=2){
185367      zPath = (const char*)sqlite3_value_text(argv[i]);
185368      bApnd = 0;
185369      pNode = jsonLookup(&x, zPath, &bApnd, ctx);
185370      if( x.oom ){
185371        sqlite3_result_error_nomem(ctx);
185372        goto jsonSetDone;
185373      }else if( x.nErr ){
185374        goto jsonSetDone;
185375      }else if( pNode && (bApnd || bIsSet) ){
185376        pNode->jnFlags |= (u8)JNODE_REPLACE;
185377        pNode->u.iReplace = i + 1;
185378      }
185379    }
185380    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
185381      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
185382    }else{
185383      jsonReturnJson(x.aNode, ctx, argv);
185384    }
185385  jsonSetDone:
185386    jsonParseReset(&x);
185387  }
185388  
185389  /*
185390  ** json_type(JSON)
185391  ** json_type(JSON, PATH)
185392  **
185393  ** Return the top-level "type" of a JSON string.  Throw an error if
185394  ** either the JSON or PATH inputs are not well-formed.
185395  */
185396  static void jsonTypeFunc(
185397    sqlite3_context *ctx,
185398    int argc,
185399    sqlite3_value **argv
185400  ){
185401    JsonParse *p;          /* The parse */
185402    const char *zPath;
185403    JsonNode *pNode;
185404  
185405    p = jsonParseCached(ctx, argv, ctx);
185406    if( p==0 ) return;
185407    if( argc==2 ){
185408      zPath = (const char*)sqlite3_value_text(argv[1]);
185409      pNode = jsonLookup(p, zPath, 0, ctx);
185410    }else{
185411      pNode = p->aNode;
185412    }
185413    if( pNode ){
185414      sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
185415    }
185416  }
185417  
185418  /*
185419  ** json_valid(JSON)
185420  **
185421  ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
185422  ** Return 0 otherwise.
185423  */
185424  static void jsonValidFunc(
185425    sqlite3_context *ctx,
185426    int argc,
185427    sqlite3_value **argv
185428  ){
185429    JsonParse *p;          /* The parse */
185430    UNUSED_PARAM(argc);
185431    p = jsonParseCached(ctx, argv, 0);
185432    sqlite3_result_int(ctx, p!=0);
185433  }
185434  
185435  
185436  /****************************************************************************
185437  ** Aggregate SQL function implementations
185438  ****************************************************************************/
185439  /*
185440  ** json_group_array(VALUE)
185441  **
185442  ** Return a JSON array composed of all values in the aggregate.
185443  */
185444  static void jsonArrayStep(
185445    sqlite3_context *ctx,
185446    int argc,
185447    sqlite3_value **argv
185448  ){
185449    JsonString *pStr;
185450    UNUSED_PARAM(argc);
185451    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
185452    if( pStr ){
185453      if( pStr->zBuf==0 ){
185454        jsonInit(pStr, ctx);
185455        jsonAppendChar(pStr, '[');
185456      }else{
185457        jsonAppendChar(pStr, ',');
185458        pStr->pCtx = ctx;
185459      }
185460      jsonAppendValue(pStr, argv[0]);
185461    }
185462  }
185463  static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
185464    JsonString *pStr;
185465    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
185466    if( pStr ){
185467      pStr->pCtx = ctx;
185468      jsonAppendChar(pStr, ']');
185469      if( pStr->bErr ){
185470        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
185471        assert( pStr->bStatic );
185472      }else if( isFinal ){
185473        sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
185474                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
185475        pStr->bStatic = 1;
185476      }else{
185477        sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
185478        pStr->nUsed--;
185479      }
185480    }else{
185481      sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
185482    }
185483    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185484  }
185485  static void jsonArrayValue(sqlite3_context *ctx){
185486    jsonArrayCompute(ctx, 0);
185487  }
185488  static void jsonArrayFinal(sqlite3_context *ctx){
185489    jsonArrayCompute(ctx, 1);
185490  }
185491  
185492  #ifndef SQLITE_OMIT_WINDOWFUNC
185493  /*
185494  ** This method works for both json_group_array() and json_group_object().
185495  ** It works by removing the first element of the group by searching forward
185496  ** to the first comma (",") that is not within a string and deleting all
185497  ** text through that comma.
185498  */
185499  static void jsonGroupInverse(
185500    sqlite3_context *ctx,
185501    int argc,
185502    sqlite3_value **argv
185503  ){
185504    int i;
185505    int inStr = 0;
185506    char *z;
185507    JsonString *pStr;
185508    UNUSED_PARAM(argc);
185509    UNUSED_PARAM(argv);
185510    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
185511  #ifdef NEVER
185512    /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
185513    ** always have been called to initalize it */
185514    if( NEVER(!pStr) ) return;
185515  #endif
185516    z = pStr->zBuf;
185517    for(i=1; z[i]!=',' || inStr; i++){
185518      assert( i<pStr->nUsed );
185519      if( z[i]=='"' ){
185520        inStr = !inStr;
185521      }else if( z[i]=='\\' ){
185522        i++;
185523      }
185524    }
185525    pStr->nUsed -= i;      
185526    memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
185527  }
185528  #else
185529  # define jsonGroupInverse 0
185530  #endif
185531  
185532  
185533  /*
185534  ** json_group_obj(NAME,VALUE)
185535  **
185536  ** Return a JSON object composed of all names and values in the aggregate.
185537  */
185538  static void jsonObjectStep(
185539    sqlite3_context *ctx,
185540    int argc,
185541    sqlite3_value **argv
185542  ){
185543    JsonString *pStr;
185544    const char *z;
185545    u32 n;
185546    UNUSED_PARAM(argc);
185547    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
185548    if( pStr ){
185549      if( pStr->zBuf==0 ){
185550        jsonInit(pStr, ctx);
185551        jsonAppendChar(pStr, '{');
185552      }else{
185553        jsonAppendChar(pStr, ',');
185554        pStr->pCtx = ctx;
185555      }
185556      z = (const char*)sqlite3_value_text(argv[0]);
185557      n = (u32)sqlite3_value_bytes(argv[0]);
185558      jsonAppendString(pStr, z, n);
185559      jsonAppendChar(pStr, ':');
185560      jsonAppendValue(pStr, argv[1]);
185561    }
185562  }
185563  static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
185564    JsonString *pStr;
185565    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
185566    if( pStr ){
185567      jsonAppendChar(pStr, '}');
185568      if( pStr->bErr ){
185569        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
185570        assert( pStr->bStatic );
185571      }else if( isFinal ){
185572        sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
185573                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
185574        pStr->bStatic = 1;
185575      }else{
185576        sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
185577        pStr->nUsed--;
185578      }
185579    }else{
185580      sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
185581    }
185582    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
185583  }
185584  static void jsonObjectValue(sqlite3_context *ctx){
185585    jsonObjectCompute(ctx, 0);
185586  }
185587  static void jsonObjectFinal(sqlite3_context *ctx){
185588    jsonObjectCompute(ctx, 1);
185589  }
185590  
185591  
185592  
185593  #ifndef SQLITE_OMIT_VIRTUALTABLE
185594  /****************************************************************************
185595  ** The json_each virtual table
185596  ****************************************************************************/
185597  typedef struct JsonEachCursor JsonEachCursor;
185598  struct JsonEachCursor {
185599    sqlite3_vtab_cursor base;  /* Base class - must be first */
185600    u32 iRowid;                /* The rowid */
185601    u32 iBegin;                /* The first node of the scan */
185602    u32 i;                     /* Index in sParse.aNode[] of current row */
185603    u32 iEnd;                  /* EOF when i equals or exceeds this value */
185604    u8 eType;                  /* Type of top-level element */
185605    u8 bRecursive;             /* True for json_tree().  False for json_each() */
185606    char *zJson;               /* Input JSON */
185607    char *zRoot;               /* Path by which to filter zJson */
185608    JsonParse sParse;          /* Parse of the input JSON */
185609  };
185610  
185611  /* Constructor for the json_each virtual table */
185612  static int jsonEachConnect(
185613    sqlite3 *db,
185614    void *pAux,
185615    int argc, const char *const*argv,
185616    sqlite3_vtab **ppVtab,
185617    char **pzErr
185618  ){
185619    sqlite3_vtab *pNew;
185620    int rc;
185621  
185622  /* Column numbers */
185623  #define JEACH_KEY     0
185624  #define JEACH_VALUE   1
185625  #define JEACH_TYPE    2
185626  #define JEACH_ATOM    3
185627  #define JEACH_ID      4
185628  #define JEACH_PARENT  5
185629  #define JEACH_FULLKEY 6
185630  #define JEACH_PATH    7
185631  /* The xBestIndex method assumes that the JSON and ROOT columns are
185632  ** the last two columns in the table.  Should this ever changes, be
185633  ** sure to update the xBestIndex method. */
185634  #define JEACH_JSON    8
185635  #define JEACH_ROOT    9
185636  
185637    UNUSED_PARAM(pzErr);
185638    UNUSED_PARAM(argv);
185639    UNUSED_PARAM(argc);
185640    UNUSED_PARAM(pAux);
185641    rc = sqlite3_declare_vtab(db, 
185642       "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
185643                      "json HIDDEN,root HIDDEN)");
185644    if( rc==SQLITE_OK ){
185645      pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
185646      if( pNew==0 ) return SQLITE_NOMEM;
185647      memset(pNew, 0, sizeof(*pNew));
185648    }
185649    return rc;
185650  }
185651  
185652  /* destructor for json_each virtual table */
185653  static int jsonEachDisconnect(sqlite3_vtab *pVtab){
185654    sqlite3_free(pVtab);
185655    return SQLITE_OK;
185656  }
185657  
185658  /* constructor for a JsonEachCursor object for json_each(). */
185659  static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
185660    JsonEachCursor *pCur;
185661  
185662    UNUSED_PARAM(p);
185663    pCur = sqlite3_malloc( sizeof(*pCur) );
185664    if( pCur==0 ) return SQLITE_NOMEM;
185665    memset(pCur, 0, sizeof(*pCur));
185666    *ppCursor = &pCur->base;
185667    return SQLITE_OK;
185668  }
185669  
185670  /* constructor for a JsonEachCursor object for json_tree(). */
185671  static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
185672    int rc = jsonEachOpenEach(p, ppCursor);
185673    if( rc==SQLITE_OK ){
185674      JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
185675      pCur->bRecursive = 1;
185676    }
185677    return rc;
185678  }
185679  
185680  /* Reset a JsonEachCursor back to its original state.  Free any memory
185681  ** held. */
185682  static void jsonEachCursorReset(JsonEachCursor *p){
185683    sqlite3_free(p->zJson);
185684    sqlite3_free(p->zRoot);
185685    jsonParseReset(&p->sParse);
185686    p->iRowid = 0;
185687    p->i = 0;
185688    p->iEnd = 0;
185689    p->eType = 0;
185690    p->zJson = 0;
185691    p->zRoot = 0;
185692  }
185693  
185694  /* Destructor for a jsonEachCursor object */
185695  static int jsonEachClose(sqlite3_vtab_cursor *cur){
185696    JsonEachCursor *p = (JsonEachCursor*)cur;
185697    jsonEachCursorReset(p);
185698    sqlite3_free(cur);
185699    return SQLITE_OK;
185700  }
185701  
185702  /* Return TRUE if the jsonEachCursor object has been advanced off the end
185703  ** of the JSON object */
185704  static int jsonEachEof(sqlite3_vtab_cursor *cur){
185705    JsonEachCursor *p = (JsonEachCursor*)cur;
185706    return p->i >= p->iEnd;
185707  }
185708  
185709  /* Advance the cursor to the next element for json_tree() */
185710  static int jsonEachNext(sqlite3_vtab_cursor *cur){
185711    JsonEachCursor *p = (JsonEachCursor*)cur;
185712    if( p->bRecursive ){
185713      if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
185714      p->i++;
185715      p->iRowid++;
185716      if( p->i<p->iEnd ){
185717        u32 iUp = p->sParse.aUp[p->i];
185718        JsonNode *pUp = &p->sParse.aNode[iUp];
185719        p->eType = pUp->eType;
185720        if( pUp->eType==JSON_ARRAY ){
185721          if( iUp==p->i-1 ){
185722            pUp->u.iKey = 0;
185723          }else{
185724            pUp->u.iKey++;
185725          }
185726        }
185727      }
185728    }else{
185729      switch( p->eType ){
185730        case JSON_ARRAY: {
185731          p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
185732          p->iRowid++;
185733          break;
185734        }
185735        case JSON_OBJECT: {
185736          p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
185737          p->iRowid++;
185738          break;
185739        }
185740        default: {
185741          p->i = p->iEnd;
185742          break;
185743        }
185744      }
185745    }
185746    return SQLITE_OK;
185747  }
185748  
185749  /* Append the name of the path for element i to pStr
185750  */
185751  static void jsonEachComputePath(
185752    JsonEachCursor *p,       /* The cursor */
185753    JsonString *pStr,        /* Write the path here */
185754    u32 i                    /* Path to this element */
185755  ){
185756    JsonNode *pNode, *pUp;
185757    u32 iUp;
185758    if( i==0 ){
185759      jsonAppendChar(pStr, '$');
185760      return;
185761    }
185762    iUp = p->sParse.aUp[i];
185763    jsonEachComputePath(p, pStr, iUp);
185764    pNode = &p->sParse.aNode[i];
185765    pUp = &p->sParse.aNode[iUp];
185766    if( pUp->eType==JSON_ARRAY ){
185767      jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
185768    }else{
185769      assert( pUp->eType==JSON_OBJECT );
185770      if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
185771      assert( pNode->eType==JSON_STRING );
185772      assert( pNode->jnFlags & JNODE_LABEL );
185773      jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
185774    }
185775  }
185776  
185777  /* Return the value of a column */
185778  static int jsonEachColumn(
185779    sqlite3_vtab_cursor *cur,   /* The cursor */
185780    sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
185781    int i                       /* Which column to return */
185782  ){
185783    JsonEachCursor *p = (JsonEachCursor*)cur;
185784    JsonNode *pThis = &p->sParse.aNode[p->i];
185785    switch( i ){
185786      case JEACH_KEY: {
185787        if( p->i==0 ) break;
185788        if( p->eType==JSON_OBJECT ){
185789          jsonReturn(pThis, ctx, 0);
185790        }else if( p->eType==JSON_ARRAY ){
185791          u32 iKey;
185792          if( p->bRecursive ){
185793            if( p->iRowid==0 ) break;
185794            iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
185795          }else{
185796            iKey = p->iRowid;
185797          }
185798          sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
185799        }
185800        break;
185801      }
185802      case JEACH_VALUE: {
185803        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
185804        jsonReturn(pThis, ctx, 0);
185805        break;
185806      }
185807      case JEACH_TYPE: {
185808        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
185809        sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
185810        break;
185811      }
185812      case JEACH_ATOM: {
185813        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
185814        if( pThis->eType>=JSON_ARRAY ) break;
185815        jsonReturn(pThis, ctx, 0);
185816        break;
185817      }
185818      case JEACH_ID: {
185819        sqlite3_result_int64(ctx, 
185820           (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
185821        break;
185822      }
185823      case JEACH_PARENT: {
185824        if( p->i>p->iBegin && p->bRecursive ){
185825          sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
185826        }
185827        break;
185828      }
185829      case JEACH_FULLKEY: {
185830        JsonString x;
185831        jsonInit(&x, ctx);
185832        if( p->bRecursive ){
185833          jsonEachComputePath(p, &x, p->i);
185834        }else{
185835          if( p->zRoot ){
185836            jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
185837          }else{
185838            jsonAppendChar(&x, '$');
185839          }
185840          if( p->eType==JSON_ARRAY ){
185841            jsonPrintf(30, &x, "[%d]", p->iRowid);
185842          }else if( p->eType==JSON_OBJECT ){
185843            jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
185844          }
185845        }
185846        jsonResult(&x);
185847        break;
185848      }
185849      case JEACH_PATH: {
185850        if( p->bRecursive ){
185851          JsonString x;
185852          jsonInit(&x, ctx);
185853          jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
185854          jsonResult(&x);
185855          break;
185856        }
185857        /* For json_each() path and root are the same so fall through
185858        ** into the root case */
185859      }
185860      default: {
185861        const char *zRoot = p->zRoot;
185862        if( zRoot==0 ) zRoot = "$";
185863        sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
185864        break;
185865      }
185866      case JEACH_JSON: {
185867        assert( i==JEACH_JSON );
185868        sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
185869        break;
185870      }
185871    }
185872    return SQLITE_OK;
185873  }
185874  
185875  /* Return the current rowid value */
185876  static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
185877    JsonEachCursor *p = (JsonEachCursor*)cur;
185878    *pRowid = p->iRowid;
185879    return SQLITE_OK;
185880  }
185881  
185882  /* The query strategy is to look for an equality constraint on the json
185883  ** column.  Without such a constraint, the table cannot operate.  idxNum is
185884  ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
185885  ** and 0 otherwise.
185886  */
185887  static int jsonEachBestIndex(
185888    sqlite3_vtab *tab,
185889    sqlite3_index_info *pIdxInfo
185890  ){
185891    int i;                     /* Loop counter or computed array index */
185892    int aIdx[2];               /* Index of constraints for JSON and ROOT */
185893    int unusableMask = 0;      /* Mask of unusable JSON and ROOT constraints */
185894    int idxMask = 0;           /* Mask of usable == constraints JSON and ROOT */
185895    const struct sqlite3_index_constraint *pConstraint;
185896  
185897    /* This implementation assumes that JSON and ROOT are the last two
185898    ** columns in the table */
185899    assert( JEACH_ROOT == JEACH_JSON+1 );
185900    UNUSED_PARAM(tab);
185901    aIdx[0] = aIdx[1] = -1;
185902    pConstraint = pIdxInfo->aConstraint;
185903    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
185904      int iCol;
185905      int iMask;
185906      if( pConstraint->iColumn < JEACH_JSON ) continue;
185907      iCol = pConstraint->iColumn - JEACH_JSON;
185908      assert( iCol==0 || iCol==1 );
185909      iMask = 1 << iCol;
185910      if( pConstraint->usable==0 ){
185911        unusableMask |= iMask;
185912      }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
185913        aIdx[iCol] = i;
185914        idxMask |= iMask;
185915      }
185916    }
185917    if( (unusableMask & ~idxMask)!=0 ){
185918      /* If there are any unusable constraints on JSON or ROOT, then reject
185919      ** this entire plan */
185920      return SQLITE_CONSTRAINT;
185921    }
185922    if( aIdx[0]<0 ){
185923      /* No JSON input.  Leave estimatedCost at the huge value that it was
185924      ** initialized to to discourage the query planner from selecting this
185925      ** plan. */
185926      pIdxInfo->idxNum = 0;
185927    }else{
185928      pIdxInfo->estimatedCost = 1.0;
185929      i = aIdx[0];
185930      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
185931      pIdxInfo->aConstraintUsage[i].omit = 1;
185932      if( aIdx[1]<0 ){
185933        pIdxInfo->idxNum = 1;  /* Only JSON supplied.  Plan 1 */
185934      }else{
185935        i = aIdx[1];
185936        pIdxInfo->aConstraintUsage[i].argvIndex = 2;
185937        pIdxInfo->aConstraintUsage[i].omit = 1;
185938        pIdxInfo->idxNum = 3;  /* Both JSON and ROOT are supplied.  Plan 3 */
185939      }
185940    }
185941    return SQLITE_OK;
185942  }
185943  
185944  /* Start a search on a new JSON string */
185945  static int jsonEachFilter(
185946    sqlite3_vtab_cursor *cur,
185947    int idxNum, const char *idxStr,
185948    int argc, sqlite3_value **argv
185949  ){
185950    JsonEachCursor *p = (JsonEachCursor*)cur;
185951    const char *z;
185952    const char *zRoot = 0;
185953    sqlite3_int64 n;
185954  
185955    UNUSED_PARAM(idxStr);
185956    UNUSED_PARAM(argc);
185957    jsonEachCursorReset(p);
185958    if( idxNum==0 ) return SQLITE_OK;
185959    z = (const char*)sqlite3_value_text(argv[0]);
185960    if( z==0 ) return SQLITE_OK;
185961    n = sqlite3_value_bytes(argv[0]);
185962    p->zJson = sqlite3_malloc64( n+1 );
185963    if( p->zJson==0 ) return SQLITE_NOMEM;
185964    memcpy(p->zJson, z, (size_t)n+1);
185965    if( jsonParse(&p->sParse, 0, p->zJson) ){
185966      int rc = SQLITE_NOMEM;
185967      if( p->sParse.oom==0 ){
185968        sqlite3_free(cur->pVtab->zErrMsg);
185969        cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
185970        if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
185971      }
185972      jsonEachCursorReset(p);
185973      return rc;
185974    }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
185975      jsonEachCursorReset(p);
185976      return SQLITE_NOMEM;
185977    }else{
185978      JsonNode *pNode = 0;
185979      if( idxNum==3 ){
185980        const char *zErr = 0;
185981        zRoot = (const char*)sqlite3_value_text(argv[1]);
185982        if( zRoot==0 ) return SQLITE_OK;
185983        n = sqlite3_value_bytes(argv[1]);
185984        p->zRoot = sqlite3_malloc64( n+1 );
185985        if( p->zRoot==0 ) return SQLITE_NOMEM;
185986        memcpy(p->zRoot, zRoot, (size_t)n+1);
185987        if( zRoot[0]!='$' ){
185988          zErr = zRoot;
185989        }else{
185990          pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
185991        }
185992        if( zErr ){
185993          sqlite3_free(cur->pVtab->zErrMsg);
185994          cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
185995          jsonEachCursorReset(p);
185996          return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
185997        }else if( pNode==0 ){
185998          return SQLITE_OK;
185999        }
186000      }else{
186001        pNode = p->sParse.aNode;
186002      }
186003      p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
186004      p->eType = pNode->eType;
186005      if( p->eType>=JSON_ARRAY ){
186006        pNode->u.iKey = 0;
186007        p->iEnd = p->i + pNode->n + 1;
186008        if( p->bRecursive ){
186009          p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
186010          if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
186011            p->i--;
186012          }
186013        }else{
186014          p->i++;
186015        }
186016      }else{
186017        p->iEnd = p->i+1;
186018      }
186019    }
186020    return SQLITE_OK;
186021  }
186022  
186023  /* The methods of the json_each virtual table */
186024  static sqlite3_module jsonEachModule = {
186025    0,                         /* iVersion */
186026    0,                         /* xCreate */
186027    jsonEachConnect,           /* xConnect */
186028    jsonEachBestIndex,         /* xBestIndex */
186029    jsonEachDisconnect,        /* xDisconnect */
186030    0,                         /* xDestroy */
186031    jsonEachOpenEach,          /* xOpen - open a cursor */
186032    jsonEachClose,             /* xClose - close a cursor */
186033    jsonEachFilter,            /* xFilter - configure scan constraints */
186034    jsonEachNext,              /* xNext - advance a cursor */
186035    jsonEachEof,               /* xEof - check for end of scan */
186036    jsonEachColumn,            /* xColumn - read data */
186037    jsonEachRowid,             /* xRowid - read data */
186038    0,                         /* xUpdate */
186039    0,                         /* xBegin */
186040    0,                         /* xSync */
186041    0,                         /* xCommit */
186042    0,                         /* xRollback */
186043    0,                         /* xFindMethod */
186044    0,                         /* xRename */
186045    0,                         /* xSavepoint */
186046    0,                         /* xRelease */
186047    0,                         /* xRollbackTo */
186048    0                          /* xShadowName */
186049  };
186050  
186051  /* The methods of the json_tree virtual table. */
186052  static sqlite3_module jsonTreeModule = {
186053    0,                         /* iVersion */
186054    0,                         /* xCreate */
186055    jsonEachConnect,           /* xConnect */
186056    jsonEachBestIndex,         /* xBestIndex */
186057    jsonEachDisconnect,        /* xDisconnect */
186058    0,                         /* xDestroy */
186059    jsonEachOpenTree,          /* xOpen - open a cursor */
186060    jsonEachClose,             /* xClose - close a cursor */
186061    jsonEachFilter,            /* xFilter - configure scan constraints */
186062    jsonEachNext,              /* xNext - advance a cursor */
186063    jsonEachEof,               /* xEof - check for end of scan */
186064    jsonEachColumn,            /* xColumn - read data */
186065    jsonEachRowid,             /* xRowid - read data */
186066    0,                         /* xUpdate */
186067    0,                         /* xBegin */
186068    0,                         /* xSync */
186069    0,                         /* xCommit */
186070    0,                         /* xRollback */
186071    0,                         /* xFindMethod */
186072    0,                         /* xRename */
186073    0,                         /* xSavepoint */
186074    0,                         /* xRelease */
186075    0,                         /* xRollbackTo */
186076    0                          /* xShadowName */
186077  };
186078  #endif /* SQLITE_OMIT_VIRTUALTABLE */
186079  
186080  /****************************************************************************
186081  ** The following routines are the only publically visible identifiers in this
186082  ** file.  Call the following routines in order to register the various SQL
186083  ** functions and the virtual table implemented by this file.
186084  ****************************************************************************/
186085  
186086  SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
186087    int rc = SQLITE_OK;
186088    unsigned int i;
186089    static const struct {
186090       const char *zName;
186091       int nArg;
186092       int flag;
186093       void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
186094    } aFunc[] = {
186095      { "json",                 1, 0,   jsonRemoveFunc        },
186096      { "json_array",          -1, 0,   jsonArrayFunc         },
186097      { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
186098      { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
186099      { "json_extract",        -1, 0,   jsonExtractFunc       },
186100      { "json_insert",         -1, 0,   jsonSetFunc           },
186101      { "json_object",         -1, 0,   jsonObjectFunc        },
186102      { "json_patch",           2, 0,   jsonPatchFunc         },
186103      { "json_quote",           1, 0,   jsonQuoteFunc         },
186104      { "json_remove",         -1, 0,   jsonRemoveFunc        },
186105      { "json_replace",        -1, 0,   jsonReplaceFunc       },
186106      { "json_set",            -1, 1,   jsonSetFunc           },
186107      { "json_type",            1, 0,   jsonTypeFunc          },
186108      { "json_type",            2, 0,   jsonTypeFunc          },
186109      { "json_valid",           1, 0,   jsonValidFunc         },
186110  
186111  #if SQLITE_DEBUG
186112      /* DEBUG and TESTING functions */
186113      { "json_parse",           1, 0,   jsonParseFunc         },
186114      { "json_test1",           1, 0,   jsonTest1Func         },
186115  #endif
186116    };
186117    static const struct {
186118       const char *zName;
186119       int nArg;
186120       void (*xStep)(sqlite3_context*,int,sqlite3_value**);
186121       void (*xFinal)(sqlite3_context*);
186122       void (*xValue)(sqlite3_context*);
186123    } aAgg[] = {
186124      { "json_group_array",     1,
186125        jsonArrayStep,   jsonArrayFinal,  jsonArrayValue  },
186126      { "json_group_object",    2,
186127        jsonObjectStep,  jsonObjectFinal, jsonObjectValue },
186128    };
186129  #ifndef SQLITE_OMIT_VIRTUALTABLE
186130    static const struct {
186131       const char *zName;
186132       sqlite3_module *pModule;
186133    } aMod[] = {
186134      { "json_each",            &jsonEachModule               },
186135      { "json_tree",            &jsonTreeModule               },
186136    };
186137  #endif
186138    for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
186139      rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
186140                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 
186141                                   (void*)&aFunc[i].flag,
186142                                   aFunc[i].xFunc, 0, 0);
186143    }
186144  #ifndef SQLITE_OMIT_WINDOWFUNC
186145    for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
186146      rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
186147                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
186148                                   aAgg[i].xStep, aAgg[i].xFinal,
186149                                   aAgg[i].xValue, jsonGroupInverse, 0);
186150    }
186151  #endif
186152  #ifndef SQLITE_OMIT_VIRTUALTABLE
186153    for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
186154      rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
186155    }
186156  #endif
186157    return rc;
186158  }
186159  
186160  
186161  #ifndef SQLITE_CORE
186162  #ifdef _WIN32
186163  __declspec(dllexport)
186164  #endif
186165  SQLITE_API int sqlite3_json_init(
186166    sqlite3 *db, 
186167    char **pzErrMsg, 
186168    const sqlite3_api_routines *pApi
186169  ){
186170    SQLITE_EXTENSION_INIT2(pApi);
186171    (void)pzErrMsg;  /* Unused parameter */
186172    return sqlite3Json1Init(db);
186173  }
186174  #endif
186175  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
186176  
186177  /************** End of json1.c ***********************************************/
186178  /************** Begin file rtree.c *******************************************/
186179  /*
186180  ** 2001 September 15
186181  **
186182  ** The author disclaims copyright to this source code.  In place of
186183  ** a legal notice, here is a blessing:
186184  **
186185  **    May you do good and not evil.
186186  **    May you find forgiveness for yourself and forgive others.
186187  **    May you share freely, never taking more than you give.
186188  **
186189  *************************************************************************
186190  ** This file contains code for implementations of the r-tree and r*-tree
186191  ** algorithms packaged as an SQLite virtual table module.
186192  */
186193  
186194  /*
186195  ** Database Format of R-Tree Tables
186196  ** --------------------------------
186197  **
186198  ** The data structure for a single virtual r-tree table is stored in three 
186199  ** native SQLite tables declared as follows. In each case, the '%' character
186200  ** in the table name is replaced with the user-supplied name of the r-tree
186201  ** table.
186202  **
186203  **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
186204  **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
186205  **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
186206  **
186207  ** The data for each node of the r-tree structure is stored in the %_node
186208  ** table. For each node that is not the root node of the r-tree, there is
186209  ** an entry in the %_parent table associating the node with its parent.
186210  ** And for each row of data in the table, there is an entry in the %_rowid
186211  ** table that maps from the entries rowid to the id of the node that it
186212  ** is stored on.  If the r-tree contains auxiliary columns, those are stored
186213  ** on the end of the %_rowid table.
186214  **
186215  ** The root node of an r-tree always exists, even if the r-tree table is
186216  ** empty. The nodeno of the root node is always 1. All other nodes in the
186217  ** table must be the same size as the root node. The content of each node
186218  ** is formatted as follows:
186219  **
186220  **   1. If the node is the root node (node 1), then the first 2 bytes
186221  **      of the node contain the tree depth as a big-endian integer.
186222  **      For non-root nodes, the first 2 bytes are left unused.
186223  **
186224  **   2. The next 2 bytes contain the number of entries currently 
186225  **      stored in the node.
186226  **
186227  **   3. The remainder of the node contains the node entries. Each entry
186228  **      consists of a single 8-byte integer followed by an even number
186229  **      of 4-byte coordinates. For leaf nodes the integer is the rowid
186230  **      of a record. For internal nodes it is the node number of a
186231  **      child page.
186232  */
186233  
186234  #if !defined(SQLITE_CORE) \
186235    || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
186236  
186237  #ifndef SQLITE_CORE
186238  /*   #include "sqlite3ext.h" */
186239    SQLITE_EXTENSION_INIT1
186240  #else
186241  /*   #include "sqlite3.h" */
186242  #endif
186243  
186244  /* #include <string.h> */
186245  /* #include <assert.h> */
186246  /* #include <stdio.h> */
186247  
186248  #ifndef SQLITE_AMALGAMATION
186249  #include "sqlite3rtree.h"
186250  typedef sqlite3_int64 i64;
186251  typedef sqlite3_uint64 u64;
186252  typedef unsigned char u8;
186253  typedef unsigned short u16;
186254  typedef unsigned int u32;
186255  #endif
186256  
186257  /*  The following macro is used to suppress compiler warnings.
186258  */
186259  #ifndef UNUSED_PARAMETER
186260  # define UNUSED_PARAMETER(x) (void)(x)
186261  #endif
186262  
186263  typedef struct Rtree Rtree;
186264  typedef struct RtreeCursor RtreeCursor;
186265  typedef struct RtreeNode RtreeNode;
186266  typedef struct RtreeCell RtreeCell;
186267  typedef struct RtreeConstraint RtreeConstraint;
186268  typedef struct RtreeMatchArg RtreeMatchArg;
186269  typedef struct RtreeGeomCallback RtreeGeomCallback;
186270  typedef union RtreeCoord RtreeCoord;
186271  typedef struct RtreeSearchPoint RtreeSearchPoint;
186272  
186273  /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
186274  #define RTREE_MAX_DIMENSIONS 5
186275  
186276  /* Maximum number of auxiliary columns */
186277  #define RTREE_MAX_AUX_COLUMN 100
186278  
186279  /* Size of hash table Rtree.aHash. This hash table is not expected to
186280  ** ever contain very many entries, so a fixed number of buckets is 
186281  ** used.
186282  */
186283  #define HASHSIZE 97
186284  
186285  /* The xBestIndex method of this virtual table requires an estimate of
186286  ** the number of rows in the virtual table to calculate the costs of
186287  ** various strategies. If possible, this estimate is loaded from the
186288  ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
186289  ** Otherwise, if no sqlite_stat1 entry is available, use 
186290  ** RTREE_DEFAULT_ROWEST.
186291  */
186292  #define RTREE_DEFAULT_ROWEST 1048576
186293  #define RTREE_MIN_ROWEST         100
186294  
186295  /* 
186296  ** An rtree virtual-table object.
186297  */
186298  struct Rtree {
186299    sqlite3_vtab base;          /* Base class.  Must be first */
186300    sqlite3 *db;                /* Host database connection */
186301    int iNodeSize;              /* Size in bytes of each node in the node table */
186302    u8 nDim;                    /* Number of dimensions */
186303    u8 nDim2;                   /* Twice the number of dimensions */
186304    u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
186305    u8 nBytesPerCell;           /* Bytes consumed per cell */
186306    u8 inWrTrans;               /* True if inside write transaction */
186307    u8 nAux;                    /* # of auxiliary columns in %_rowid */
186308    u8 nAuxNotNull;             /* Number of initial not-null aux columns */
186309  #ifdef SQLITE_DEBUG
186310    u8 bCorrupt;                /* Shadow table corruption detected */
186311  #endif
186312    int iDepth;                 /* Current depth of the r-tree structure */
186313    char *zDb;                  /* Name of database containing r-tree table */
186314    char *zName;                /* Name of r-tree table */ 
186315    u32 nBusy;                  /* Current number of users of this structure */
186316    i64 nRowEst;                /* Estimated number of rows in this table */
186317    u32 nCursor;                /* Number of open cursors */
186318    u32 nNodeRef;               /* Number RtreeNodes with positive nRef */
186319    char *zReadAuxSql;          /* SQL for statement to read aux data */
186320  
186321    /* List of nodes removed during a CondenseTree operation. List is
186322    ** linked together via the pointer normally used for hash chains -
186323    ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
186324    ** headed by the node (leaf nodes have RtreeNode.iNode==0).
186325    */
186326    RtreeNode *pDeleted;
186327    int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
186328  
186329    /* Blob I/O on xxx_node */
186330    sqlite3_blob *pNodeBlob;
186331  
186332    /* Statements to read/write/delete a record from xxx_node */
186333    sqlite3_stmt *pWriteNode;
186334    sqlite3_stmt *pDeleteNode;
186335  
186336    /* Statements to read/write/delete a record from xxx_rowid */
186337    sqlite3_stmt *pReadRowid;
186338    sqlite3_stmt *pWriteRowid;
186339    sqlite3_stmt *pDeleteRowid;
186340  
186341    /* Statements to read/write/delete a record from xxx_parent */
186342    sqlite3_stmt *pReadParent;
186343    sqlite3_stmt *pWriteParent;
186344    sqlite3_stmt *pDeleteParent;
186345  
186346    /* Statement for writing to the "aux:" fields, if there are any */
186347    sqlite3_stmt *pWriteAux;
186348  
186349    RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
186350  };
186351  
186352  /* Possible values for Rtree.eCoordType: */
186353  #define RTREE_COORD_REAL32 0
186354  #define RTREE_COORD_INT32  1
186355  
186356  /*
186357  ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
186358  ** only deal with integer coordinates.  No floating point operations
186359  ** will be done.
186360  */
186361  #ifdef SQLITE_RTREE_INT_ONLY
186362    typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
186363    typedef int RtreeValue;                  /* Low accuracy coordinate */
186364  # define RTREE_ZERO 0
186365  #else
186366    typedef double RtreeDValue;              /* High accuracy coordinate */
186367    typedef float RtreeValue;                /* Low accuracy coordinate */
186368  # define RTREE_ZERO 0.0
186369  #endif
186370  
186371  /*
186372  ** Set the Rtree.bCorrupt flag
186373  */
186374  #ifdef SQLITE_DEBUG
186375  # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
186376  #else
186377  # define RTREE_IS_CORRUPT(X)
186378  #endif
186379  
186380  /*
186381  ** When doing a search of an r-tree, instances of the following structure
186382  ** record intermediate results from the tree walk.
186383  **
186384  ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
186385  ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
186386  ** the id is of the parent node and the cell that RtreeSearchPoint
186387  ** represents is the iCell-th entry in the parent node.
186388  */
186389  struct RtreeSearchPoint {
186390    RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
186391    sqlite3_int64 id;      /* Node ID */
186392    u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
186393    u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
186394    u8 iCell;              /* Cell index within the node */
186395  };
186396  
186397  /*
186398  ** The minimum number of cells allowed for a node is a third of the 
186399  ** maximum. In Gutman's notation:
186400  **
186401  **     m = M/3
186402  **
186403  ** If an R*-tree "Reinsert" operation is required, the same number of
186404  ** cells are removed from the overfull node and reinserted into the tree.
186405  */
186406  #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
186407  #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
186408  #define RTREE_MAXCELLS 51
186409  
186410  /*
186411  ** The smallest possible node-size is (512-64)==448 bytes. And the largest
186412  ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
186413  ** Therefore all non-root nodes must contain at least 3 entries. Since 
186414  ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
186415  ** 40 or less.
186416  */
186417  #define RTREE_MAX_DEPTH 40
186418  
186419  
186420  /*
186421  ** Number of entries in the cursor RtreeNode cache.  The first entry is
186422  ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
186423  ** entries cache the RtreeNode for the first elements of the priority queue.
186424  */
186425  #define RTREE_CACHE_SZ  5
186426  
186427  /* 
186428  ** An rtree cursor object.
186429  */
186430  struct RtreeCursor {
186431    sqlite3_vtab_cursor base;         /* Base class.  Must be first */
186432    u8 atEOF;                         /* True if at end of search */
186433    u8 bPoint;                        /* True if sPoint is valid */
186434    u8 bAuxValid;                     /* True if pReadAux is valid */
186435    int iStrategy;                    /* Copy of idxNum search parameter */
186436    int nConstraint;                  /* Number of entries in aConstraint */
186437    RtreeConstraint *aConstraint;     /* Search constraints. */
186438    int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
186439    int nPoint;                       /* Number of slots used in aPoint[] */
186440    int mxLevel;                      /* iLevel value for root of the tree */
186441    RtreeSearchPoint *aPoint;         /* Priority queue for search points */
186442    sqlite3_stmt *pReadAux;           /* Statement to read aux-data */
186443    RtreeSearchPoint sPoint;          /* Cached next search point */
186444    RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
186445    u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
186446  };
186447  
186448  /* Return the Rtree of a RtreeCursor */
186449  #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
186450  
186451  /*
186452  ** A coordinate can be either a floating point number or a integer.  All
186453  ** coordinates within a single R-Tree are always of the same time.
186454  */
186455  union RtreeCoord {
186456    RtreeValue f;      /* Floating point value */
186457    int i;             /* Integer value */
186458    u32 u;             /* Unsigned for byte-order conversions */
186459  };
186460  
186461  /*
186462  ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
186463  ** formatted as a RtreeDValue (double or int64). This macro assumes that local
186464  ** variable pRtree points to the Rtree structure associated with the
186465  ** RtreeCoord.
186466  */
186467  #ifdef SQLITE_RTREE_INT_ONLY
186468  # define DCOORD(coord) ((RtreeDValue)coord.i)
186469  #else
186470  # define DCOORD(coord) (                           \
186471      (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
186472        ((double)coord.f) :                           \
186473        ((double)coord.i)                             \
186474    )
186475  #endif
186476  
186477  /*
186478  ** A search constraint.
186479  */
186480  struct RtreeConstraint {
186481    int iCoord;                     /* Index of constrained coordinate */
186482    int op;                         /* Constraining operation */
186483    union {
186484      RtreeDValue rValue;             /* Constraint value. */
186485      int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
186486      int (*xQueryFunc)(sqlite3_rtree_query_info*);
186487    } u;
186488    sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
186489  };
186490  
186491  /* Possible values for RtreeConstraint.op */
186492  #define RTREE_EQ    0x41  /* A */
186493  #define RTREE_LE    0x42  /* B */
186494  #define RTREE_LT    0x43  /* C */
186495  #define RTREE_GE    0x44  /* D */
186496  #define RTREE_GT    0x45  /* E */
186497  #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
186498  #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
186499  
186500  
186501  /* 
186502  ** An rtree structure node.
186503  */
186504  struct RtreeNode {
186505    RtreeNode *pParent;         /* Parent node */
186506    i64 iNode;                  /* The node number */
186507    int nRef;                   /* Number of references to this node */
186508    int isDirty;                /* True if the node needs to be written to disk */
186509    u8 *zData;                  /* Content of the node, as should be on disk */
186510    RtreeNode *pNext;           /* Next node in this hash collision chain */
186511  };
186512  
186513  /* Return the number of cells in a node  */
186514  #define NCELL(pNode) readInt16(&(pNode)->zData[2])
186515  
186516  /* 
186517  ** A single cell from a node, deserialized
186518  */
186519  struct RtreeCell {
186520    i64 iRowid;                                 /* Node or entry ID */
186521    RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
186522  };
186523  
186524  
186525  /*
186526  ** This object becomes the sqlite3_user_data() for the SQL functions
186527  ** that are created by sqlite3_rtree_geometry_callback() and
186528  ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
186529  ** operators in order to constrain a search.
186530  **
186531  ** xGeom and xQueryFunc are the callback functions.  Exactly one of 
186532  ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
186533  ** SQL function was created using sqlite3_rtree_geometry_callback() or
186534  ** sqlite3_rtree_query_callback().
186535  ** 
186536  ** This object is deleted automatically by the destructor mechanism in
186537  ** sqlite3_create_function_v2().
186538  */
186539  struct RtreeGeomCallback {
186540    int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
186541    int (*xQueryFunc)(sqlite3_rtree_query_info*);
186542    void (*xDestructor)(void*);
186543    void *pContext;
186544  };
186545  
186546  /*
186547  ** An instance of this structure (in the form of a BLOB) is returned by
186548  ** the SQL functions that sqlite3_rtree_geometry_callback() and
186549  ** sqlite3_rtree_query_callback() create, and is read as the right-hand
186550  ** operand to the MATCH operator of an R-Tree.
186551  */
186552  struct RtreeMatchArg {
186553    u32 iSize;                  /* Size of this object */
186554    RtreeGeomCallback cb;       /* Info about the callback functions */
186555    int nParam;                 /* Number of parameters to the SQL function */
186556    sqlite3_value **apSqlParam; /* Original SQL parameter values */
186557    RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
186558  };
186559  
186560  #ifndef MAX
186561  # define MAX(x,y) ((x) < (y) ? (y) : (x))
186562  #endif
186563  #ifndef MIN
186564  # define MIN(x,y) ((x) > (y) ? (y) : (x))
186565  #endif
186566  
186567  /* What version of GCC is being used.  0 means GCC is not being used .
186568  ** Note that the GCC_VERSION macro will also be set correctly when using
186569  ** clang, since clang works hard to be gcc compatible.  So the gcc
186570  ** optimizations will also work when compiling with clang.
186571  */
186572  #ifndef GCC_VERSION
186573  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
186574  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
186575  #else
186576  # define GCC_VERSION 0
186577  #endif
186578  #endif
186579  
186580  /* The testcase() macro should already be defined in the amalgamation.  If
186581  ** it is not, make it a no-op.
186582  */
186583  #ifndef SQLITE_AMALGAMATION
186584  # define testcase(X)
186585  #endif
186586  
186587  /*
186588  ** Macros to determine whether the machine is big or little endian,
186589  ** and whether or not that determination is run-time or compile-time.
186590  **
186591  ** For best performance, an attempt is made to guess at the byte-order
186592  ** using C-preprocessor macros.  If that is unsuccessful, or if
186593  ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
186594  ** at run-time.
186595  */
186596  #ifndef SQLITE_BYTEORDER
186597  #if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
186598      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
186599      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
186600      defined(__arm__)
186601  # define SQLITE_BYTEORDER    1234
186602  #elif defined(sparc)    || defined(__ppc__)
186603  # define SQLITE_BYTEORDER    4321
186604  #else
186605  # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
186606  #endif
186607  #endif
186608  
186609  
186610  /* What version of MSVC is being used.  0 means MSVC is not being used */
186611  #ifndef MSVC_VERSION
186612  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
186613  # define MSVC_VERSION _MSC_VER
186614  #else
186615  # define MSVC_VERSION 0
186616  #endif
186617  #endif
186618  
186619  /*
186620  ** Functions to deserialize a 16 bit integer, 32 bit real number and
186621  ** 64 bit integer. The deserialized value is returned.
186622  */
186623  static int readInt16(u8 *p){
186624    return (p[0]<<8) + p[1];
186625  }
186626  static void readCoord(u8 *p, RtreeCoord *pCoord){
186627    assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
186628  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
186629    pCoord->u = _byteswap_ulong(*(u32*)p);
186630  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
186631    pCoord->u = __builtin_bswap32(*(u32*)p);
186632  #elif SQLITE_BYTEORDER==4321
186633    pCoord->u = *(u32*)p;
186634  #else
186635    pCoord->u = (
186636      (((u32)p[0]) << 24) + 
186637      (((u32)p[1]) << 16) + 
186638      (((u32)p[2]) <<  8) + 
186639      (((u32)p[3]) <<  0)
186640    );
186641  #endif
186642  }
186643  static i64 readInt64(u8 *p){
186644  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
186645    u64 x;
186646    memcpy(&x, p, 8);
186647    return (i64)_byteswap_uint64(x);
186648  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
186649    u64 x;
186650    memcpy(&x, p, 8);
186651    return (i64)__builtin_bswap64(x);
186652  #elif SQLITE_BYTEORDER==4321
186653    i64 x;
186654    memcpy(&x, p, 8);
186655    return x;
186656  #else
186657    return (i64)(
186658      (((u64)p[0]) << 56) + 
186659      (((u64)p[1]) << 48) + 
186660      (((u64)p[2]) << 40) + 
186661      (((u64)p[3]) << 32) + 
186662      (((u64)p[4]) << 24) + 
186663      (((u64)p[5]) << 16) + 
186664      (((u64)p[6]) <<  8) + 
186665      (((u64)p[7]) <<  0)
186666    );
186667  #endif
186668  }
186669  
186670  /*
186671  ** Functions to serialize a 16 bit integer, 32 bit real number and
186672  ** 64 bit integer. The value returned is the number of bytes written
186673  ** to the argument buffer (always 2, 4 and 8 respectively).
186674  */
186675  static void writeInt16(u8 *p, int i){
186676    p[0] = (i>> 8)&0xFF;
186677    p[1] = (i>> 0)&0xFF;
186678  }
186679  static int writeCoord(u8 *p, RtreeCoord *pCoord){
186680    u32 i;
186681    assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
186682    assert( sizeof(RtreeCoord)==4 );
186683    assert( sizeof(u32)==4 );
186684  #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
186685    i = __builtin_bswap32(pCoord->u);
186686    memcpy(p, &i, 4);
186687  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
186688    i = _byteswap_ulong(pCoord->u);
186689    memcpy(p, &i, 4);
186690  #elif SQLITE_BYTEORDER==4321
186691    i = pCoord->u;
186692    memcpy(p, &i, 4);
186693  #else
186694    i = pCoord->u;
186695    p[0] = (i>>24)&0xFF;
186696    p[1] = (i>>16)&0xFF;
186697    p[2] = (i>> 8)&0xFF;
186698    p[3] = (i>> 0)&0xFF;
186699  #endif
186700    return 4;
186701  }
186702  static int writeInt64(u8 *p, i64 i){
186703  #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
186704    i = (i64)__builtin_bswap64((u64)i);
186705    memcpy(p, &i, 8);
186706  #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
186707    i = (i64)_byteswap_uint64((u64)i);
186708    memcpy(p, &i, 8);
186709  #elif SQLITE_BYTEORDER==4321
186710    memcpy(p, &i, 8);
186711  #else
186712    p[0] = (i>>56)&0xFF;
186713    p[1] = (i>>48)&0xFF;
186714    p[2] = (i>>40)&0xFF;
186715    p[3] = (i>>32)&0xFF;
186716    p[4] = (i>>24)&0xFF;
186717    p[5] = (i>>16)&0xFF;
186718    p[6] = (i>> 8)&0xFF;
186719    p[7] = (i>> 0)&0xFF;
186720  #endif
186721    return 8;
186722  }
186723  
186724  /*
186725  ** Increment the reference count of node p.
186726  */
186727  static void nodeReference(RtreeNode *p){
186728    if( p ){
186729      assert( p->nRef>0 );
186730      p->nRef++;
186731    }
186732  }
186733  
186734  /*
186735  ** Clear the content of node p (set all bytes to 0x00).
186736  */
186737  static void nodeZero(Rtree *pRtree, RtreeNode *p){
186738    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
186739    p->isDirty = 1;
186740  }
186741  
186742  /*
186743  ** Given a node number iNode, return the corresponding key to use
186744  ** in the Rtree.aHash table.
186745  */
186746  static unsigned int nodeHash(i64 iNode){
186747    return ((unsigned)iNode) % HASHSIZE;
186748  }
186749  
186750  /*
186751  ** Search the node hash table for node iNode. If found, return a pointer
186752  ** to it. Otherwise, return 0.
186753  */
186754  static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
186755    RtreeNode *p;
186756    for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
186757    return p;
186758  }
186759  
186760  /*
186761  ** Add node pNode to the node hash table.
186762  */
186763  static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
186764    int iHash;
186765    assert( pNode->pNext==0 );
186766    iHash = nodeHash(pNode->iNode);
186767    pNode->pNext = pRtree->aHash[iHash];
186768    pRtree->aHash[iHash] = pNode;
186769  }
186770  
186771  /*
186772  ** Remove node pNode from the node hash table.
186773  */
186774  static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
186775    RtreeNode **pp;
186776    if( pNode->iNode!=0 ){
186777      pp = &pRtree->aHash[nodeHash(pNode->iNode)];
186778      for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
186779      *pp = pNode->pNext;
186780      pNode->pNext = 0;
186781    }
186782  }
186783  
186784  /*
186785  ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
186786  ** indicating that node has not yet been assigned a node number. It is
186787  ** assigned a node number when nodeWrite() is called to write the
186788  ** node contents out to the database.
186789  */
186790  static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
186791    RtreeNode *pNode;
186792    pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
186793    if( pNode ){
186794      memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
186795      pNode->zData = (u8 *)&pNode[1];
186796      pNode->nRef = 1;
186797      pRtree->nNodeRef++;
186798      pNode->pParent = pParent;
186799      pNode->isDirty = 1;
186800      nodeReference(pParent);
186801    }
186802    return pNode;
186803  }
186804  
186805  /*
186806  ** Clear the Rtree.pNodeBlob object
186807  */
186808  static void nodeBlobReset(Rtree *pRtree){
186809    if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
186810      sqlite3_blob *pBlob = pRtree->pNodeBlob;
186811      pRtree->pNodeBlob = 0;
186812      sqlite3_blob_close(pBlob);
186813    }
186814  }
186815  
186816  /*
186817  ** Check to see if pNode is the same as pParent or any of the parents
186818  ** of pParent.
186819  */
186820  static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
186821    do{
186822      if( pNode==pParent ) return 1;
186823      pParent = pParent->pParent;
186824    }while( pParent );
186825    return 0;
186826  }
186827  
186828  /*
186829  ** Obtain a reference to an r-tree node.
186830  */
186831  static int nodeAcquire(
186832    Rtree *pRtree,             /* R-tree structure */
186833    i64 iNode,                 /* Node number to load */
186834    RtreeNode *pParent,        /* Either the parent node or NULL */
186835    RtreeNode **ppNode         /* OUT: Acquired node */
186836  ){
186837    int rc = SQLITE_OK;
186838    RtreeNode *pNode = 0;
186839  
186840    /* Check if the requested node is already in the hash table. If so,
186841    ** increase its reference count and return it.
186842    */
186843    if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
186844      assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
186845      if( pParent && !pNode->pParent ){
186846        if( nodeInParentChain(pNode, pParent) ){
186847          RTREE_IS_CORRUPT(pRtree);
186848          return SQLITE_CORRUPT_VTAB;
186849        }
186850        pParent->nRef++;
186851        pNode->pParent = pParent;
186852      }
186853      pNode->nRef++;
186854      *ppNode = pNode;
186855      return SQLITE_OK;
186856    }
186857  
186858    if( pRtree->pNodeBlob ){
186859      sqlite3_blob *pBlob = pRtree->pNodeBlob;
186860      pRtree->pNodeBlob = 0;
186861      rc = sqlite3_blob_reopen(pBlob, iNode);
186862      pRtree->pNodeBlob = pBlob;
186863      if( rc ){
186864        nodeBlobReset(pRtree);
186865        if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
186866      }
186867    }
186868    if( pRtree->pNodeBlob==0 ){
186869      char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
186870      if( zTab==0 ) return SQLITE_NOMEM;
186871      rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
186872                             &pRtree->pNodeBlob);
186873      sqlite3_free(zTab);
186874    }
186875    if( rc ){
186876      nodeBlobReset(pRtree);
186877      *ppNode = 0;
186878      /* If unable to open an sqlite3_blob on the desired row, that can only
186879      ** be because the shadow tables hold erroneous data. */
186880      if( rc==SQLITE_ERROR ){
186881        rc = SQLITE_CORRUPT_VTAB;
186882        RTREE_IS_CORRUPT(pRtree);
186883      }
186884    }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
186885      pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
186886      if( !pNode ){
186887        rc = SQLITE_NOMEM;
186888      }else{
186889        pNode->pParent = pParent;
186890        pNode->zData = (u8 *)&pNode[1];
186891        pNode->nRef = 1;
186892        pRtree->nNodeRef++;
186893        pNode->iNode = iNode;
186894        pNode->isDirty = 0;
186895        pNode->pNext = 0;
186896        rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
186897                               pRtree->iNodeSize, 0);
186898      }
186899    }
186900  
186901    /* If the root node was just loaded, set pRtree->iDepth to the height
186902    ** of the r-tree structure. A height of zero means all data is stored on
186903    ** the root node. A height of one means the children of the root node
186904    ** are the leaves, and so on. If the depth as specified on the root node
186905    ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
186906    */
186907    if( pNode && iNode==1 ){
186908      pRtree->iDepth = readInt16(pNode->zData);
186909      if( pRtree->iDepth>RTREE_MAX_DEPTH ){
186910        rc = SQLITE_CORRUPT_VTAB;
186911        RTREE_IS_CORRUPT(pRtree);
186912      }
186913    }
186914  
186915    /* If no error has occurred so far, check if the "number of entries"
186916    ** field on the node is too large. If so, set the return code to 
186917    ** SQLITE_CORRUPT_VTAB.
186918    */
186919    if( pNode && rc==SQLITE_OK ){
186920      if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
186921        rc = SQLITE_CORRUPT_VTAB;
186922        RTREE_IS_CORRUPT(pRtree);
186923      }
186924    }
186925  
186926    if( rc==SQLITE_OK ){
186927      if( pNode!=0 ){
186928        nodeReference(pParent);
186929        nodeHashInsert(pRtree, pNode);
186930      }else{
186931        rc = SQLITE_CORRUPT_VTAB;
186932        RTREE_IS_CORRUPT(pRtree);
186933      }
186934      *ppNode = pNode;
186935    }else{
186936      if( pNode ){
186937        pRtree->nNodeRef--;
186938        sqlite3_free(pNode);
186939      }
186940      *ppNode = 0;
186941    }
186942  
186943    return rc;
186944  }
186945  
186946  /*
186947  ** Overwrite cell iCell of node pNode with the contents of pCell.
186948  */
186949  static void nodeOverwriteCell(
186950    Rtree *pRtree,             /* The overall R-Tree */
186951    RtreeNode *pNode,          /* The node into which the cell is to be written */
186952    RtreeCell *pCell,          /* The cell to write */
186953    int iCell                  /* Index into pNode into which pCell is written */
186954  ){
186955    int ii;
186956    u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
186957    p += writeInt64(p, pCell->iRowid);
186958    for(ii=0; ii<pRtree->nDim2; ii++){
186959      p += writeCoord(p, &pCell->aCoord[ii]);
186960    }
186961    pNode->isDirty = 1;
186962  }
186963  
186964  /*
186965  ** Remove the cell with index iCell from node pNode.
186966  */
186967  static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
186968    u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
186969    u8 *pSrc = &pDst[pRtree->nBytesPerCell];
186970    int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
186971    memmove(pDst, pSrc, nByte);
186972    writeInt16(&pNode->zData[2], NCELL(pNode)-1);
186973    pNode->isDirty = 1;
186974  }
186975  
186976  /*
186977  ** Insert the contents of cell pCell into node pNode. If the insert
186978  ** is successful, return SQLITE_OK.
186979  **
186980  ** If there is not enough free space in pNode, return SQLITE_FULL.
186981  */
186982  static int nodeInsertCell(
186983    Rtree *pRtree,                /* The overall R-Tree */
186984    RtreeNode *pNode,             /* Write new cell into this node */
186985    RtreeCell *pCell              /* The cell to be inserted */
186986  ){
186987    int nCell;                    /* Current number of cells in pNode */
186988    int nMaxCell;                 /* Maximum number of cells for pNode */
186989  
186990    nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
186991    nCell = NCELL(pNode);
186992  
186993    assert( nCell<=nMaxCell );
186994    if( nCell<nMaxCell ){
186995      nodeOverwriteCell(pRtree, pNode, pCell, nCell);
186996      writeInt16(&pNode->zData[2], nCell+1);
186997      pNode->isDirty = 1;
186998    }
186999  
187000    return (nCell==nMaxCell);
187001  }
187002  
187003  /*
187004  ** If the node is dirty, write it out to the database.
187005  */
187006  static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
187007    int rc = SQLITE_OK;
187008    if( pNode->isDirty ){
187009      sqlite3_stmt *p = pRtree->pWriteNode;
187010      if( pNode->iNode ){
187011        sqlite3_bind_int64(p, 1, pNode->iNode);
187012      }else{
187013        sqlite3_bind_null(p, 1);
187014      }
187015      sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
187016      sqlite3_step(p);
187017      pNode->isDirty = 0;
187018      rc = sqlite3_reset(p);
187019      sqlite3_bind_null(p, 2);
187020      if( pNode->iNode==0 && rc==SQLITE_OK ){
187021        pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
187022        nodeHashInsert(pRtree, pNode);
187023      }
187024    }
187025    return rc;
187026  }
187027  
187028  /*
187029  ** Release a reference to a node. If the node is dirty and the reference
187030  ** count drops to zero, the node data is written to the database.
187031  */
187032  static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
187033    int rc = SQLITE_OK;
187034    if( pNode ){
187035      assert( pNode->nRef>0 );
187036      assert( pRtree->nNodeRef>0 );
187037      pNode->nRef--;
187038      if( pNode->nRef==0 ){
187039        pRtree->nNodeRef--;
187040        if( pNode->iNode==1 ){
187041          pRtree->iDepth = -1;
187042        }
187043        if( pNode->pParent ){
187044          rc = nodeRelease(pRtree, pNode->pParent);
187045        }
187046        if( rc==SQLITE_OK ){
187047          rc = nodeWrite(pRtree, pNode);
187048        }
187049        nodeHashDelete(pRtree, pNode);
187050        sqlite3_free(pNode);
187051      }
187052    }
187053    return rc;
187054  }
187055  
187056  /*
187057  ** Return the 64-bit integer value associated with cell iCell of
187058  ** node pNode. If pNode is a leaf node, this is a rowid. If it is
187059  ** an internal node, then the 64-bit integer is a child page number.
187060  */
187061  static i64 nodeGetRowid(
187062    Rtree *pRtree,       /* The overall R-Tree */
187063    RtreeNode *pNode,    /* The node from which to extract the ID */
187064    int iCell            /* The cell index from which to extract the ID */
187065  ){
187066    assert( iCell<NCELL(pNode) );
187067    return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
187068  }
187069  
187070  /*
187071  ** Return coordinate iCoord from cell iCell in node pNode.
187072  */
187073  static void nodeGetCoord(
187074    Rtree *pRtree,               /* The overall R-Tree */
187075    RtreeNode *pNode,            /* The node from which to extract a coordinate */
187076    int iCell,                   /* The index of the cell within the node */
187077    int iCoord,                  /* Which coordinate to extract */
187078    RtreeCoord *pCoord           /* OUT: Space to write result to */
187079  ){
187080    readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
187081  }
187082  
187083  /*
187084  ** Deserialize cell iCell of node pNode. Populate the structure pointed
187085  ** to by pCell with the results.
187086  */
187087  static void nodeGetCell(
187088    Rtree *pRtree,               /* The overall R-Tree */
187089    RtreeNode *pNode,            /* The node containing the cell to be read */
187090    int iCell,                   /* Index of the cell within the node */
187091    RtreeCell *pCell             /* OUT: Write the cell contents here */
187092  ){
187093    u8 *pData;
187094    RtreeCoord *pCoord;
187095    int ii = 0;
187096    pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
187097    pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
187098    pCoord = pCell->aCoord;
187099    do{
187100      readCoord(pData, &pCoord[ii]);
187101      readCoord(pData+4, &pCoord[ii+1]);
187102      pData += 8;
187103      ii += 2;
187104    }while( ii<pRtree->nDim2 );
187105  }
187106  
187107  
187108  /* Forward declaration for the function that does the work of
187109  ** the virtual table module xCreate() and xConnect() methods.
187110  */
187111  static int rtreeInit(
187112    sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
187113  );
187114  
187115  /* 
187116  ** Rtree virtual table module xCreate method.
187117  */
187118  static int rtreeCreate(
187119    sqlite3 *db,
187120    void *pAux,
187121    int argc, const char *const*argv,
187122    sqlite3_vtab **ppVtab,
187123    char **pzErr
187124  ){
187125    return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
187126  }
187127  
187128  /* 
187129  ** Rtree virtual table module xConnect method.
187130  */
187131  static int rtreeConnect(
187132    sqlite3 *db,
187133    void *pAux,
187134    int argc, const char *const*argv,
187135    sqlite3_vtab **ppVtab,
187136    char **pzErr
187137  ){
187138    return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
187139  }
187140  
187141  /*
187142  ** Increment the r-tree reference count.
187143  */
187144  static void rtreeReference(Rtree *pRtree){
187145    pRtree->nBusy++;
187146  }
187147  
187148  /*
187149  ** Decrement the r-tree reference count. When the reference count reaches
187150  ** zero the structure is deleted.
187151  */
187152  static void rtreeRelease(Rtree *pRtree){
187153    pRtree->nBusy--;
187154    if( pRtree->nBusy==0 ){
187155      pRtree->inWrTrans = 0;
187156      assert( pRtree->nCursor==0 );
187157      nodeBlobReset(pRtree);
187158      assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
187159      sqlite3_finalize(pRtree->pWriteNode);
187160      sqlite3_finalize(pRtree->pDeleteNode);
187161      sqlite3_finalize(pRtree->pReadRowid);
187162      sqlite3_finalize(pRtree->pWriteRowid);
187163      sqlite3_finalize(pRtree->pDeleteRowid);
187164      sqlite3_finalize(pRtree->pReadParent);
187165      sqlite3_finalize(pRtree->pWriteParent);
187166      sqlite3_finalize(pRtree->pDeleteParent);
187167      sqlite3_finalize(pRtree->pWriteAux);
187168      sqlite3_free(pRtree->zReadAuxSql);
187169      sqlite3_free(pRtree);
187170    }
187171  }
187172  
187173  /* 
187174  ** Rtree virtual table module xDisconnect method.
187175  */
187176  static int rtreeDisconnect(sqlite3_vtab *pVtab){
187177    rtreeRelease((Rtree *)pVtab);
187178    return SQLITE_OK;
187179  }
187180  
187181  /* 
187182  ** Rtree virtual table module xDestroy method.
187183  */
187184  static int rtreeDestroy(sqlite3_vtab *pVtab){
187185    Rtree *pRtree = (Rtree *)pVtab;
187186    int rc;
187187    char *zCreate = sqlite3_mprintf(
187188      "DROP TABLE '%q'.'%q_node';"
187189      "DROP TABLE '%q'.'%q_rowid';"
187190      "DROP TABLE '%q'.'%q_parent';",
187191      pRtree->zDb, pRtree->zName, 
187192      pRtree->zDb, pRtree->zName,
187193      pRtree->zDb, pRtree->zName
187194    );
187195    if( !zCreate ){
187196      rc = SQLITE_NOMEM;
187197    }else{
187198      nodeBlobReset(pRtree);
187199      rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
187200      sqlite3_free(zCreate);
187201    }
187202    if( rc==SQLITE_OK ){
187203      rtreeRelease(pRtree);
187204    }
187205  
187206    return rc;
187207  }
187208  
187209  /* 
187210  ** Rtree virtual table module xOpen method.
187211  */
187212  static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
187213    int rc = SQLITE_NOMEM;
187214    Rtree *pRtree = (Rtree *)pVTab;
187215    RtreeCursor *pCsr;
187216  
187217    pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
187218    if( pCsr ){
187219      memset(pCsr, 0, sizeof(RtreeCursor));
187220      pCsr->base.pVtab = pVTab;
187221      rc = SQLITE_OK;
187222      pRtree->nCursor++;
187223    }
187224    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
187225  
187226    return rc;
187227  }
187228  
187229  
187230  /*
187231  ** Free the RtreeCursor.aConstraint[] array and its contents.
187232  */
187233  static void freeCursorConstraints(RtreeCursor *pCsr){
187234    if( pCsr->aConstraint ){
187235      int i;                        /* Used to iterate through constraint array */
187236      for(i=0; i<pCsr->nConstraint; i++){
187237        sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
187238        if( pInfo ){
187239          if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
187240          sqlite3_free(pInfo);
187241        }
187242      }
187243      sqlite3_free(pCsr->aConstraint);
187244      pCsr->aConstraint = 0;
187245    }
187246  }
187247  
187248  /* 
187249  ** Rtree virtual table module xClose method.
187250  */
187251  static int rtreeClose(sqlite3_vtab_cursor *cur){
187252    Rtree *pRtree = (Rtree *)(cur->pVtab);
187253    int ii;
187254    RtreeCursor *pCsr = (RtreeCursor *)cur;
187255    assert( pRtree->nCursor>0 );
187256    freeCursorConstraints(pCsr);
187257    sqlite3_finalize(pCsr->pReadAux);
187258    sqlite3_free(pCsr->aPoint);
187259    for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
187260    sqlite3_free(pCsr);
187261    pRtree->nCursor--;
187262    nodeBlobReset(pRtree);
187263    return SQLITE_OK;
187264  }
187265  
187266  /*
187267  ** Rtree virtual table module xEof method.
187268  **
187269  ** Return non-zero if the cursor does not currently point to a valid 
187270  ** record (i.e if the scan has finished), or zero otherwise.
187271  */
187272  static int rtreeEof(sqlite3_vtab_cursor *cur){
187273    RtreeCursor *pCsr = (RtreeCursor *)cur;
187274    return pCsr->atEOF;
187275  }
187276  
187277  /*
187278  ** Convert raw bits from the on-disk RTree record into a coordinate value.
187279  ** The on-disk format is big-endian and needs to be converted for little-
187280  ** endian platforms.  The on-disk record stores integer coordinates if
187281  ** eInt is true and it stores 32-bit floating point records if eInt is
187282  ** false.  a[] is the four bytes of the on-disk record to be decoded.
187283  ** Store the results in "r".
187284  **
187285  ** There are five versions of this macro.  The last one is generic.  The
187286  ** other four are various architectures-specific optimizations.
187287  */
187288  #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
187289  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
187290      RtreeCoord c;    /* Coordinate decoded */                   \
187291      c.u = _byteswap_ulong(*(u32*)a);                            \
187292      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
187293  }
187294  #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
187295  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
187296      RtreeCoord c;    /* Coordinate decoded */                   \
187297      c.u = __builtin_bswap32(*(u32*)a);                          \
187298      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
187299  }
187300  #elif SQLITE_BYTEORDER==1234
187301  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
187302      RtreeCoord c;    /* Coordinate decoded */                   \
187303      memcpy(&c.u,a,4);                                           \
187304      c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
187305            ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
187306      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
187307  }
187308  #elif SQLITE_BYTEORDER==4321
187309  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
187310      RtreeCoord c;    /* Coordinate decoded */                   \
187311      memcpy(&c.u,a,4);                                           \
187312      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
187313  }
187314  #else
187315  #define RTREE_DECODE_COORD(eInt, a, r) {                        \
187316      RtreeCoord c;    /* Coordinate decoded */                   \
187317      c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
187318             +((u32)a[2]<<8) + a[3];                              \
187319      r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
187320  }
187321  #endif
187322  
187323  /*
187324  ** Check the RTree node or entry given by pCellData and p against the MATCH
187325  ** constraint pConstraint.  
187326  */
187327  static int rtreeCallbackConstraint(
187328    RtreeConstraint *pConstraint,  /* The constraint to test */
187329    int eInt,                      /* True if RTree holding integer coordinates */
187330    u8 *pCellData,                 /* Raw cell content */
187331    RtreeSearchPoint *pSearch,     /* Container of this cell */
187332    sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
187333    int *peWithin                  /* OUT: visibility of the cell */
187334  ){
187335    sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
187336    int nCoord = pInfo->nCoord;                           /* No. of coordinates */
187337    int rc;                                             /* Callback return code */
187338    RtreeCoord c;                                       /* Translator union */
187339    sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
187340  
187341    assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
187342    assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
187343  
187344    if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
187345      pInfo->iRowid = readInt64(pCellData);
187346    }
187347    pCellData += 8;
187348  #ifndef SQLITE_RTREE_INT_ONLY
187349    if( eInt==0 ){
187350      switch( nCoord ){
187351        case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
187352                  readCoord(pCellData+32, &c); aCoord[8] = c.f;
187353        case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
187354                  readCoord(pCellData+24, &c); aCoord[6] = c.f;
187355        case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
187356                  readCoord(pCellData+16, &c); aCoord[4] = c.f;
187357        case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
187358                  readCoord(pCellData+8,  &c); aCoord[2] = c.f;
187359        default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
187360                  readCoord(pCellData,    &c); aCoord[0] = c.f;
187361      }
187362    }else
187363  #endif
187364    {
187365      switch( nCoord ){
187366        case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
187367                  readCoord(pCellData+32, &c); aCoord[8] = c.i;
187368        case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
187369                  readCoord(pCellData+24, &c); aCoord[6] = c.i;
187370        case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
187371                  readCoord(pCellData+16, &c); aCoord[4] = c.i;
187372        case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
187373                  readCoord(pCellData+8,  &c); aCoord[2] = c.i;
187374        default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
187375                  readCoord(pCellData,    &c); aCoord[0] = c.i;
187376      }
187377    }
187378    if( pConstraint->op==RTREE_MATCH ){
187379      int eWithin = 0;
187380      rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
187381                                nCoord, aCoord, &eWithin);
187382      if( eWithin==0 ) *peWithin = NOT_WITHIN;
187383      *prScore = RTREE_ZERO;
187384    }else{
187385      pInfo->aCoord = aCoord;
187386      pInfo->iLevel = pSearch->iLevel - 1;
187387      pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
187388      pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
187389      rc = pConstraint->u.xQueryFunc(pInfo);
187390      if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
187391      if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
187392        *prScore = pInfo->rScore;
187393      }
187394    }
187395    return rc;
187396  }
187397  
187398  /* 
187399  ** Check the internal RTree node given by pCellData against constraint p.
187400  ** If this constraint cannot be satisfied by any child within the node,
187401  ** set *peWithin to NOT_WITHIN.
187402  */
187403  static void rtreeNonleafConstraint(
187404    RtreeConstraint *p,        /* The constraint to test */
187405    int eInt,                  /* True if RTree holds integer coordinates */
187406    u8 *pCellData,             /* Raw cell content as appears on disk */
187407    int *peWithin              /* Adjust downward, as appropriate */
187408  ){
187409    sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
187410  
187411    /* p->iCoord might point to either a lower or upper bound coordinate
187412    ** in a coordinate pair.  But make pCellData point to the lower bound.
187413    */
187414    pCellData += 8 + 4*(p->iCoord&0xfe);
187415  
187416    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
187417        || p->op==RTREE_GT || p->op==RTREE_EQ );
187418    assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
187419    switch( p->op ){
187420      case RTREE_LE:
187421      case RTREE_LT:
187422      case RTREE_EQ:
187423        RTREE_DECODE_COORD(eInt, pCellData, val);
187424        /* val now holds the lower bound of the coordinate pair */
187425        if( p->u.rValue>=val ) return;
187426        if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
187427        /* Fall through for the RTREE_EQ case */
187428  
187429      default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
187430        pCellData += 4;
187431        RTREE_DECODE_COORD(eInt, pCellData, val);
187432        /* val now holds the upper bound of the coordinate pair */
187433        if( p->u.rValue<=val ) return;
187434    }
187435    *peWithin = NOT_WITHIN;
187436  }
187437  
187438  /*
187439  ** Check the leaf RTree cell given by pCellData against constraint p.
187440  ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
187441  ** If the constraint is satisfied, leave *peWithin unchanged.
187442  **
187443  ** The constraint is of the form:  xN op $val
187444  **
187445  ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
187446  ** pCellData.  $val is given by p->u.rValue.
187447  */
187448  static void rtreeLeafConstraint(
187449    RtreeConstraint *p,        /* The constraint to test */
187450    int eInt,                  /* True if RTree holds integer coordinates */
187451    u8 *pCellData,             /* Raw cell content as appears on disk */
187452    int *peWithin              /* Adjust downward, as appropriate */
187453  ){
187454    RtreeDValue xN;      /* Coordinate value converted to a double */
187455  
187456    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
187457        || p->op==RTREE_GT || p->op==RTREE_EQ );
187458    pCellData += 8 + p->iCoord*4;
187459    assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
187460    RTREE_DECODE_COORD(eInt, pCellData, xN);
187461    switch( p->op ){
187462      case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
187463      case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
187464      case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
187465      case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
187466      default:       if( xN == p->u.rValue ) return;  break;
187467    }
187468    *peWithin = NOT_WITHIN;
187469  }
187470  
187471  /*
187472  ** One of the cells in node pNode is guaranteed to have a 64-bit 
187473  ** integer value equal to iRowid. Return the index of this cell.
187474  */
187475  static int nodeRowidIndex(
187476    Rtree *pRtree, 
187477    RtreeNode *pNode, 
187478    i64 iRowid,
187479    int *piIndex
187480  ){
187481    int ii;
187482    int nCell = NCELL(pNode);
187483    assert( nCell<200 );
187484    for(ii=0; ii<nCell; ii++){
187485      if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
187486        *piIndex = ii;
187487        return SQLITE_OK;
187488      }
187489    }
187490    RTREE_IS_CORRUPT(pRtree);
187491    return SQLITE_CORRUPT_VTAB;
187492  }
187493  
187494  /*
187495  ** Return the index of the cell containing a pointer to node pNode
187496  ** in its parent. If pNode is the root node, return -1.
187497  */
187498  static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
187499    RtreeNode *pParent = pNode->pParent;
187500    if( pParent ){
187501      return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
187502    }
187503    *piIndex = -1;
187504    return SQLITE_OK;
187505  }
187506  
187507  /*
187508  ** Compare two search points.  Return negative, zero, or positive if the first
187509  ** is less than, equal to, or greater than the second.
187510  **
187511  ** The rScore is the primary key.  Smaller rScore values come first.
187512  ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
187513  ** iLevel values coming first.  In this way, if rScore is the same for all
187514  ** SearchPoints, then iLevel becomes the deciding factor and the result
187515  ** is a depth-first search, which is the desired default behavior.
187516  */
187517  static int rtreeSearchPointCompare(
187518    const RtreeSearchPoint *pA,
187519    const RtreeSearchPoint *pB
187520  ){
187521    if( pA->rScore<pB->rScore ) return -1;
187522    if( pA->rScore>pB->rScore ) return +1;
187523    if( pA->iLevel<pB->iLevel ) return -1;
187524    if( pA->iLevel>pB->iLevel ) return +1;
187525    return 0;
187526  }
187527  
187528  /*
187529  ** Interchange two search points in a cursor.
187530  */
187531  static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
187532    RtreeSearchPoint t = p->aPoint[i];
187533    assert( i<j );
187534    p->aPoint[i] = p->aPoint[j];
187535    p->aPoint[j] = t;
187536    i++; j++;
187537    if( i<RTREE_CACHE_SZ ){
187538      if( j>=RTREE_CACHE_SZ ){
187539        nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
187540        p->aNode[i] = 0;
187541      }else{
187542        RtreeNode *pTemp = p->aNode[i];
187543        p->aNode[i] = p->aNode[j];
187544        p->aNode[j] = pTemp;
187545      }
187546    }
187547  }
187548  
187549  /*
187550  ** Return the search point with the lowest current score.
187551  */
187552  static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
187553    return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
187554  }
187555  
187556  /*
187557  ** Get the RtreeNode for the search point with the lowest score.
187558  */
187559  static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
187560    sqlite3_int64 id;
187561    int ii = 1 - pCur->bPoint;
187562    assert( ii==0 || ii==1 );
187563    assert( pCur->bPoint || pCur->nPoint );
187564    if( pCur->aNode[ii]==0 ){
187565      assert( pRC!=0 );
187566      id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
187567      *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
187568    }
187569    return pCur->aNode[ii];
187570  }
187571  
187572  /*
187573  ** Push a new element onto the priority queue
187574  */
187575  static RtreeSearchPoint *rtreeEnqueue(
187576    RtreeCursor *pCur,    /* The cursor */
187577    RtreeDValue rScore,   /* Score for the new search point */
187578    u8 iLevel             /* Level for the new search point */
187579  ){
187580    int i, j;
187581    RtreeSearchPoint *pNew;
187582    if( pCur->nPoint>=pCur->nPointAlloc ){
187583      int nNew = pCur->nPointAlloc*2 + 8;
187584      pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
187585      if( pNew==0 ) return 0;
187586      pCur->aPoint = pNew;
187587      pCur->nPointAlloc = nNew;
187588    }
187589    i = pCur->nPoint++;
187590    pNew = pCur->aPoint + i;
187591    pNew->rScore = rScore;
187592    pNew->iLevel = iLevel;
187593    assert( iLevel<=RTREE_MAX_DEPTH );
187594    while( i>0 ){
187595      RtreeSearchPoint *pParent;
187596      j = (i-1)/2;
187597      pParent = pCur->aPoint + j;
187598      if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
187599      rtreeSearchPointSwap(pCur, j, i);
187600      i = j;
187601      pNew = pParent;
187602    }
187603    return pNew;
187604  }
187605  
187606  /*
187607  ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
187608  ** NULL if malloc fails.
187609  */
187610  static RtreeSearchPoint *rtreeSearchPointNew(
187611    RtreeCursor *pCur,    /* The cursor */
187612    RtreeDValue rScore,   /* Score for the new search point */
187613    u8 iLevel             /* Level for the new search point */
187614  ){
187615    RtreeSearchPoint *pNew, *pFirst;
187616    pFirst = rtreeSearchPointFirst(pCur);
187617    pCur->anQueue[iLevel]++;
187618    if( pFirst==0
187619     || pFirst->rScore>rScore 
187620     || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
187621    ){
187622      if( pCur->bPoint ){
187623        int ii;
187624        pNew = rtreeEnqueue(pCur, rScore, iLevel);
187625        if( pNew==0 ) return 0;
187626        ii = (int)(pNew - pCur->aPoint) + 1;
187627        if( ii<RTREE_CACHE_SZ ){
187628          assert( pCur->aNode[ii]==0 );
187629          pCur->aNode[ii] = pCur->aNode[0];
187630        }else{
187631          nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
187632        }
187633        pCur->aNode[0] = 0;
187634        *pNew = pCur->sPoint;
187635      }
187636      pCur->sPoint.rScore = rScore;
187637      pCur->sPoint.iLevel = iLevel;
187638      pCur->bPoint = 1;
187639      return &pCur->sPoint;
187640    }else{
187641      return rtreeEnqueue(pCur, rScore, iLevel);
187642    }
187643  }
187644  
187645  #if 0
187646  /* Tracing routines for the RtreeSearchPoint queue */
187647  static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
187648    if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
187649    printf(" %d.%05lld.%02d %g %d",
187650      p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
187651    );
187652    idx++;
187653    if( idx<RTREE_CACHE_SZ ){
187654      printf(" %p\n", pCur->aNode[idx]);
187655    }else{
187656      printf("\n");
187657    }
187658  }
187659  static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
187660    int ii;
187661    printf("=== %9s ", zPrefix);
187662    if( pCur->bPoint ){
187663      tracePoint(&pCur->sPoint, -1, pCur);
187664    }
187665    for(ii=0; ii<pCur->nPoint; ii++){
187666      if( ii>0 || pCur->bPoint ) printf("              ");
187667      tracePoint(&pCur->aPoint[ii], ii, pCur);
187668    }
187669  }
187670  # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
187671  #else
187672  # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
187673  #endif
187674  
187675  /* Remove the search point with the lowest current score.
187676  */
187677  static void rtreeSearchPointPop(RtreeCursor *p){
187678    int i, j, k, n;
187679    i = 1 - p->bPoint;
187680    assert( i==0 || i==1 );
187681    if( p->aNode[i] ){
187682      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
187683      p->aNode[i] = 0;
187684    }
187685    if( p->bPoint ){
187686      p->anQueue[p->sPoint.iLevel]--;
187687      p->bPoint = 0;
187688    }else if( p->nPoint ){
187689      p->anQueue[p->aPoint[0].iLevel]--;
187690      n = --p->nPoint;
187691      p->aPoint[0] = p->aPoint[n];
187692      if( n<RTREE_CACHE_SZ-1 ){
187693        p->aNode[1] = p->aNode[n+1];
187694        p->aNode[n+1] = 0;
187695      }
187696      i = 0;
187697      while( (j = i*2+1)<n ){
187698        k = j+1;
187699        if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
187700          if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
187701            rtreeSearchPointSwap(p, i, k);
187702            i = k;
187703          }else{
187704            break;
187705          }
187706        }else{
187707          if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
187708            rtreeSearchPointSwap(p, i, j);
187709            i = j;
187710          }else{
187711            break;
187712          }
187713        }
187714      }
187715    }
187716  }
187717  
187718  
187719  /*
187720  ** Continue the search on cursor pCur until the front of the queue
187721  ** contains an entry suitable for returning as a result-set row,
187722  ** or until the RtreeSearchPoint queue is empty, indicating that the
187723  ** query has completed.
187724  */
187725  static int rtreeStepToLeaf(RtreeCursor *pCur){
187726    RtreeSearchPoint *p;
187727    Rtree *pRtree = RTREE_OF_CURSOR(pCur);
187728    RtreeNode *pNode;
187729    int eWithin;
187730    int rc = SQLITE_OK;
187731    int nCell;
187732    int nConstraint = pCur->nConstraint;
187733    int ii;
187734    int eInt;
187735    RtreeSearchPoint x;
187736  
187737    eInt = pRtree->eCoordType==RTREE_COORD_INT32;
187738    while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
187739      pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
187740      if( rc ) return rc;
187741      nCell = NCELL(pNode);
187742      assert( nCell<200 );
187743      while( p->iCell<nCell ){
187744        sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
187745        u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
187746        eWithin = FULLY_WITHIN;
187747        for(ii=0; ii<nConstraint; ii++){
187748          RtreeConstraint *pConstraint = pCur->aConstraint + ii;
187749          if( pConstraint->op>=RTREE_MATCH ){
187750            rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
187751                                         &rScore, &eWithin);
187752            if( rc ) return rc;
187753          }else if( p->iLevel==1 ){
187754            rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
187755          }else{
187756            rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
187757          }
187758          if( eWithin==NOT_WITHIN ) break;
187759        }
187760        p->iCell++;
187761        if( eWithin==NOT_WITHIN ) continue;
187762        x.iLevel = p->iLevel - 1;
187763        if( x.iLevel ){
187764          x.id = readInt64(pCellData);
187765          x.iCell = 0;
187766        }else{
187767          x.id = p->id;
187768          x.iCell = p->iCell - 1;
187769        }
187770        if( p->iCell>=nCell ){
187771          RTREE_QUEUE_TRACE(pCur, "POP-S:");
187772          rtreeSearchPointPop(pCur);
187773        }
187774        if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
187775        p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
187776        if( p==0 ) return SQLITE_NOMEM;
187777        p->eWithin = (u8)eWithin;
187778        p->id = x.id;
187779        p->iCell = x.iCell;
187780        RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
187781        break;
187782      }
187783      if( p->iCell>=nCell ){
187784        RTREE_QUEUE_TRACE(pCur, "POP-Se:");
187785        rtreeSearchPointPop(pCur);
187786      }
187787    }
187788    pCur->atEOF = p==0;
187789    return SQLITE_OK;
187790  }
187791  
187792  /* 
187793  ** Rtree virtual table module xNext method.
187794  */
187795  static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
187796    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
187797    int rc = SQLITE_OK;
187798  
187799    /* Move to the next entry that matches the configured constraints. */
187800    RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
187801    if( pCsr->bAuxValid ){
187802      pCsr->bAuxValid = 0;
187803      sqlite3_reset(pCsr->pReadAux);
187804    }
187805    rtreeSearchPointPop(pCsr);
187806    rc = rtreeStepToLeaf(pCsr);
187807    return rc;
187808  }
187809  
187810  /* 
187811  ** Rtree virtual table module xRowid method.
187812  */
187813  static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
187814    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
187815    RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
187816    int rc = SQLITE_OK;
187817    RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
187818    if( rc==SQLITE_OK && p ){
187819      *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
187820    }
187821    return rc;
187822  }
187823  
187824  /* 
187825  ** Rtree virtual table module xColumn method.
187826  */
187827  static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
187828    Rtree *pRtree = (Rtree *)cur->pVtab;
187829    RtreeCursor *pCsr = (RtreeCursor *)cur;
187830    RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
187831    RtreeCoord c;
187832    int rc = SQLITE_OK;
187833    RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
187834  
187835    if( rc ) return rc;
187836    if( p==0 ) return SQLITE_OK;
187837    if( i==0 ){
187838      sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
187839    }else if( i<=pRtree->nDim2 ){
187840      nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
187841  #ifndef SQLITE_RTREE_INT_ONLY
187842      if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
187843        sqlite3_result_double(ctx, c.f);
187844      }else
187845  #endif
187846      {
187847        assert( pRtree->eCoordType==RTREE_COORD_INT32 );
187848        sqlite3_result_int(ctx, c.i);
187849      }
187850    }else{
187851      if( !pCsr->bAuxValid ){
187852        if( pCsr->pReadAux==0 ){
187853          rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
187854                                  &pCsr->pReadAux, 0);
187855          if( rc ) return rc;
187856        }
187857        sqlite3_bind_int64(pCsr->pReadAux, 1, 
187858            nodeGetRowid(pRtree, pNode, p->iCell));
187859        rc = sqlite3_step(pCsr->pReadAux);
187860        if( rc==SQLITE_ROW ){
187861          pCsr->bAuxValid = 1;
187862        }else{
187863          sqlite3_reset(pCsr->pReadAux);
187864          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
187865          return rc;
187866        }
187867      }
187868      sqlite3_result_value(ctx,
187869           sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
187870    }  
187871    return SQLITE_OK;
187872  }
187873  
187874  /* 
187875  ** Use nodeAcquire() to obtain the leaf node containing the record with 
187876  ** rowid iRowid. If successful, set *ppLeaf to point to the node and
187877  ** return SQLITE_OK. If there is no such record in the table, set
187878  ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
187879  ** to zero and return an SQLite error code.
187880  */
187881  static int findLeafNode(
187882    Rtree *pRtree,              /* RTree to search */
187883    i64 iRowid,                 /* The rowid searching for */
187884    RtreeNode **ppLeaf,         /* Write the node here */
187885    sqlite3_int64 *piNode       /* Write the node-id here */
187886  ){
187887    int rc;
187888    *ppLeaf = 0;
187889    sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
187890    if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
187891      i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
187892      if( piNode ) *piNode = iNode;
187893      rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
187894      sqlite3_reset(pRtree->pReadRowid);
187895    }else{
187896      rc = sqlite3_reset(pRtree->pReadRowid);
187897    }
187898    return rc;
187899  }
187900  
187901  /*
187902  ** This function is called to configure the RtreeConstraint object passed
187903  ** as the second argument for a MATCH constraint. The value passed as the
187904  ** first argument to this function is the right-hand operand to the MATCH
187905  ** operator.
187906  */
187907  static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
187908    RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
187909    sqlite3_rtree_query_info *pInfo;   /* Callback information */
187910  
187911    pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
187912    if( pSrc==0 ) return SQLITE_ERROR;
187913    pInfo = (sqlite3_rtree_query_info*)
187914                  sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
187915    if( !pInfo ) return SQLITE_NOMEM;
187916    memset(pInfo, 0, sizeof(*pInfo));
187917    pBlob = (RtreeMatchArg*)&pInfo[1];
187918    memcpy(pBlob, pSrc, pSrc->iSize);
187919    pInfo->pContext = pBlob->cb.pContext;
187920    pInfo->nParam = pBlob->nParam;
187921    pInfo->aParam = pBlob->aParam;
187922    pInfo->apSqlParam = pBlob->apSqlParam;
187923  
187924    if( pBlob->cb.xGeom ){
187925      pCons->u.xGeom = pBlob->cb.xGeom;
187926    }else{
187927      pCons->op = RTREE_QUERY;
187928      pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
187929    }
187930    pCons->pInfo = pInfo;
187931    return SQLITE_OK;
187932  }
187933  
187934  /* 
187935  ** Rtree virtual table module xFilter method.
187936  */
187937  static int rtreeFilter(
187938    sqlite3_vtab_cursor *pVtabCursor, 
187939    int idxNum, const char *idxStr,
187940    int argc, sqlite3_value **argv
187941  ){
187942    Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
187943    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
187944    RtreeNode *pRoot = 0;
187945    int ii;
187946    int rc = SQLITE_OK;
187947    int iCell = 0;
187948    sqlite3_stmt *pStmt;
187949  
187950    rtreeReference(pRtree);
187951  
187952    /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
187953    freeCursorConstraints(pCsr);
187954    sqlite3_free(pCsr->aPoint);
187955    pStmt = pCsr->pReadAux;
187956    memset(pCsr, 0, sizeof(RtreeCursor));
187957    pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
187958    pCsr->pReadAux = pStmt;
187959  
187960    pCsr->iStrategy = idxNum;
187961    if( idxNum==1 ){
187962      /* Special case - lookup by rowid. */
187963      RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
187964      RtreeSearchPoint *p;     /* Search point for the leaf */
187965      i64 iRowid = sqlite3_value_int64(argv[0]);
187966      i64 iNode = 0;
187967      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
187968      if( rc==SQLITE_OK && pLeaf!=0 ){
187969        p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
187970        assert( p!=0 );  /* Always returns pCsr->sPoint */
187971        pCsr->aNode[0] = pLeaf;
187972        p->id = iNode;
187973        p->eWithin = PARTLY_WITHIN;
187974        rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
187975        p->iCell = (u8)iCell;
187976        RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
187977      }else{
187978        pCsr->atEOF = 1;
187979      }
187980    }else{
187981      /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
187982      ** with the configured constraints. 
187983      */
187984      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
187985      if( rc==SQLITE_OK && argc>0 ){
187986        pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
187987        pCsr->nConstraint = argc;
187988        if( !pCsr->aConstraint ){
187989          rc = SQLITE_NOMEM;
187990        }else{
187991          memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
187992          memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
187993          assert( (idxStr==0 && argc==0)
187994                  || (idxStr && (int)strlen(idxStr)==argc*2) );
187995          for(ii=0; ii<argc; ii++){
187996            RtreeConstraint *p = &pCsr->aConstraint[ii];
187997            p->op = idxStr[ii*2];
187998            p->iCoord = idxStr[ii*2+1]-'0';
187999            if( p->op>=RTREE_MATCH ){
188000              /* A MATCH operator. The right-hand-side must be a blob that
188001              ** can be cast into an RtreeMatchArg object. One created using
188002              ** an sqlite3_rtree_geometry_callback() SQL user function.
188003              */
188004              rc = deserializeGeometry(argv[ii], p);
188005              if( rc!=SQLITE_OK ){
188006                break;
188007              }
188008              p->pInfo->nCoord = pRtree->nDim2;
188009              p->pInfo->anQueue = pCsr->anQueue;
188010              p->pInfo->mxLevel = pRtree->iDepth + 1;
188011            }else{
188012  #ifdef SQLITE_RTREE_INT_ONLY
188013              p->u.rValue = sqlite3_value_int64(argv[ii]);
188014  #else
188015              p->u.rValue = sqlite3_value_double(argv[ii]);
188016  #endif
188017            }
188018          }
188019        }
188020      }
188021      if( rc==SQLITE_OK ){
188022        RtreeSearchPoint *pNew;
188023        pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
188024        if( pNew==0 ) return SQLITE_NOMEM;
188025        pNew->id = 1;
188026        pNew->iCell = 0;
188027        pNew->eWithin = PARTLY_WITHIN;
188028        assert( pCsr->bPoint==1 );
188029        pCsr->aNode[0] = pRoot;
188030        pRoot = 0;
188031        RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
188032        rc = rtreeStepToLeaf(pCsr);
188033      }
188034    }
188035  
188036    nodeRelease(pRtree, pRoot);
188037    rtreeRelease(pRtree);
188038    return rc;
188039  }
188040  
188041  /*
188042  ** Rtree virtual table module xBestIndex method. There are three
188043  ** table scan strategies to choose from (in order from most to 
188044  ** least desirable):
188045  **
188046  **   idxNum     idxStr        Strategy
188047  **   ------------------------------------------------
188048  **     1        Unused        Direct lookup by rowid.
188049  **     2        See below     R-tree query or full-table scan.
188050  **   ------------------------------------------------
188051  **
188052  ** If strategy 1 is used, then idxStr is not meaningful. If strategy
188053  ** 2 is used, idxStr is formatted to contain 2 bytes for each 
188054  ** constraint used. The first two bytes of idxStr correspond to 
188055  ** the constraint in sqlite3_index_info.aConstraintUsage[] with
188056  ** (argvIndex==1) etc.
188057  **
188058  ** The first of each pair of bytes in idxStr identifies the constraint
188059  ** operator as follows:
188060  **
188061  **   Operator    Byte Value
188062  **   ----------------------
188063  **      =        0x41 ('A')
188064  **     <=        0x42 ('B')
188065  **      <        0x43 ('C')
188066  **     >=        0x44 ('D')
188067  **      >        0x45 ('E')
188068  **   MATCH       0x46 ('F')
188069  **   ----------------------
188070  **
188071  ** The second of each pair of bytes identifies the coordinate column
188072  ** to which the constraint applies. The leftmost coordinate column
188073  ** is 'a', the second from the left 'b' etc.
188074  */
188075  static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
188076    Rtree *pRtree = (Rtree*)tab;
188077    int rc = SQLITE_OK;
188078    int ii;
188079    int bMatch = 0;                 /* True if there exists a MATCH constraint */
188080    i64 nRow;                       /* Estimated rows returned by this scan */
188081  
188082    int iIdx = 0;
188083    char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
188084    memset(zIdxStr, 0, sizeof(zIdxStr));
188085  
188086    /* Check if there exists a MATCH constraint - even an unusable one. If there
188087    ** is, do not consider the lookup-by-rowid plan as using such a plan would
188088    ** require the VDBE to evaluate the MATCH constraint, which is not currently
188089    ** possible. */
188090    for(ii=0; ii<pIdxInfo->nConstraint; ii++){
188091      if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
188092        bMatch = 1;
188093      }
188094    }
188095  
188096    assert( pIdxInfo->idxStr==0 );
188097    for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
188098      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
188099  
188100      if( bMatch==0 && p->usable 
188101       && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ 
188102      ){
188103        /* We have an equality constraint on the rowid. Use strategy 1. */
188104        int jj;
188105        for(jj=0; jj<ii; jj++){
188106          pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
188107          pIdxInfo->aConstraintUsage[jj].omit = 0;
188108        }
188109        pIdxInfo->idxNum = 1;
188110        pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
188111        pIdxInfo->aConstraintUsage[jj].omit = 1;
188112  
188113        /* This strategy involves a two rowid lookups on an B-Tree structures
188114        ** and then a linear search of an R-Tree node. This should be 
188115        ** considered almost as quick as a direct rowid lookup (for which 
188116        ** sqlite uses an internal cost of 0.0). It is expected to return
188117        ** a single row.
188118        */ 
188119        pIdxInfo->estimatedCost = 30.0;
188120        pIdxInfo->estimatedRows = 1;
188121        pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
188122        return SQLITE_OK;
188123      }
188124  
188125      if( p->usable
188126      && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
188127          || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
188128      ){
188129        u8 op;
188130        switch( p->op ){
188131          case SQLITE_INDEX_CONSTRAINT_EQ:    op = RTREE_EQ;    break;
188132          case SQLITE_INDEX_CONSTRAINT_GT:    op = RTREE_GT;    break;
188133          case SQLITE_INDEX_CONSTRAINT_LE:    op = RTREE_LE;    break;
188134          case SQLITE_INDEX_CONSTRAINT_LT:    op = RTREE_LT;    break;
188135          case SQLITE_INDEX_CONSTRAINT_GE:    op = RTREE_GE;    break;
188136          case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
188137          default:                            op = 0;           break;
188138        }
188139        if( op ){
188140          zIdxStr[iIdx++] = op;
188141          zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
188142          pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
188143          pIdxInfo->aConstraintUsage[ii].omit = 1;
188144        }
188145      }
188146    }
188147  
188148    pIdxInfo->idxNum = 2;
188149    pIdxInfo->needToFreeIdxStr = 1;
188150    if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
188151      return SQLITE_NOMEM;
188152    }
188153  
188154    nRow = pRtree->nRowEst >> (iIdx/2);
188155    pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
188156    pIdxInfo->estimatedRows = nRow;
188157  
188158    return rc;
188159  }
188160  
188161  /*
188162  ** Return the N-dimensional volumn of the cell stored in *p.
188163  */
188164  static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
188165    RtreeDValue area = (RtreeDValue)1;
188166    assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
188167  #ifndef SQLITE_RTREE_INT_ONLY
188168    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
188169      switch( pRtree->nDim ){
188170        case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
188171        case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
188172        case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
188173        case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
188174        default: area *= p->aCoord[1].f - p->aCoord[0].f;
188175      }
188176    }else
188177  #endif
188178    {
188179      switch( pRtree->nDim ){
188180        case 5:  area  = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
188181        case 4:  area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
188182        case 3:  area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
188183        case 2:  area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
188184        default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
188185      }
188186    }
188187    return area;
188188  }
188189  
188190  /*
188191  ** Return the margin length of cell p. The margin length is the sum
188192  ** of the objects size in each dimension.
188193  */
188194  static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
188195    RtreeDValue margin = 0;
188196    int ii = pRtree->nDim2 - 2;
188197    do{
188198      margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
188199      ii -= 2;
188200    }while( ii>=0 );
188201    return margin;
188202  }
188203  
188204  /*
188205  ** Store the union of cells p1 and p2 in p1.
188206  */
188207  static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
188208    int ii = 0;
188209    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
188210      do{
188211        p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
188212        p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
188213        ii += 2;
188214      }while( ii<pRtree->nDim2 );
188215    }else{
188216      do{
188217        p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
188218        p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
188219        ii += 2;
188220      }while( ii<pRtree->nDim2 );
188221    }
188222  }
188223  
188224  /*
188225  ** Return true if the area covered by p2 is a subset of the area covered
188226  ** by p1. False otherwise.
188227  */
188228  static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
188229    int ii;
188230    int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
188231    for(ii=0; ii<pRtree->nDim2; ii+=2){
188232      RtreeCoord *a1 = &p1->aCoord[ii];
188233      RtreeCoord *a2 = &p2->aCoord[ii];
188234      if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
188235       || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
188236      ){
188237        return 0;
188238      }
188239    }
188240    return 1;
188241  }
188242  
188243  /*
188244  ** Return the amount cell p would grow by if it were unioned with pCell.
188245  */
188246  static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
188247    RtreeDValue area;
188248    RtreeCell cell;
188249    memcpy(&cell, p, sizeof(RtreeCell));
188250    area = cellArea(pRtree, &cell);
188251    cellUnion(pRtree, &cell, pCell);
188252    return (cellArea(pRtree, &cell)-area);
188253  }
188254  
188255  static RtreeDValue cellOverlap(
188256    Rtree *pRtree, 
188257    RtreeCell *p, 
188258    RtreeCell *aCell, 
188259    int nCell
188260  ){
188261    int ii;
188262    RtreeDValue overlap = RTREE_ZERO;
188263    for(ii=0; ii<nCell; ii++){
188264      int jj;
188265      RtreeDValue o = (RtreeDValue)1;
188266      for(jj=0; jj<pRtree->nDim2; jj+=2){
188267        RtreeDValue x1, x2;
188268        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
188269        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
188270        if( x2<x1 ){
188271          o = (RtreeDValue)0;
188272          break;
188273        }else{
188274          o = o * (x2-x1);
188275        }
188276      }
188277      overlap += o;
188278    }
188279    return overlap;
188280  }
188281  
188282  
188283  /*
188284  ** This function implements the ChooseLeaf algorithm from Gutman[84].
188285  ** ChooseSubTree in r*tree terminology.
188286  */
188287  static int ChooseLeaf(
188288    Rtree *pRtree,               /* Rtree table */
188289    RtreeCell *pCell,            /* Cell to insert into rtree */
188290    int iHeight,                 /* Height of sub-tree rooted at pCell */
188291    RtreeNode **ppLeaf           /* OUT: Selected leaf page */
188292  ){
188293    int rc;
188294    int ii;
188295    RtreeNode *pNode = 0;
188296    rc = nodeAcquire(pRtree, 1, 0, &pNode);
188297  
188298    for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
188299      int iCell;
188300      sqlite3_int64 iBest = 0;
188301  
188302      RtreeDValue fMinGrowth = RTREE_ZERO;
188303      RtreeDValue fMinArea = RTREE_ZERO;
188304  
188305      int nCell = NCELL(pNode);
188306      RtreeCell cell;
188307      RtreeNode *pChild;
188308  
188309      RtreeCell *aCell = 0;
188310  
188311      /* Select the child node which will be enlarged the least if pCell
188312      ** is inserted into it. Resolve ties by choosing the entry with
188313      ** the smallest area.
188314      */
188315      for(iCell=0; iCell<nCell; iCell++){
188316        int bBest = 0;
188317        RtreeDValue growth;
188318        RtreeDValue area;
188319        nodeGetCell(pRtree, pNode, iCell, &cell);
188320        growth = cellGrowth(pRtree, &cell, pCell);
188321        area = cellArea(pRtree, &cell);
188322        if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
188323          bBest = 1;
188324        }
188325        if( bBest ){
188326          fMinGrowth = growth;
188327          fMinArea = area;
188328          iBest = cell.iRowid;
188329        }
188330      }
188331  
188332      sqlite3_free(aCell);
188333      rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
188334      nodeRelease(pRtree, pNode);
188335      pNode = pChild;
188336    }
188337  
188338    *ppLeaf = pNode;
188339    return rc;
188340  }
188341  
188342  /*
188343  ** A cell with the same content as pCell has just been inserted into
188344  ** the node pNode. This function updates the bounding box cells in
188345  ** all ancestor elements.
188346  */
188347  static int AdjustTree(
188348    Rtree *pRtree,                    /* Rtree table */
188349    RtreeNode *pNode,                 /* Adjust ancestry of this node. */
188350    RtreeCell *pCell                  /* This cell was just inserted */
188351  ){
188352    RtreeNode *p = pNode;
188353    int cnt = 0;
188354    while( p->pParent ){
188355      RtreeNode *pParent = p->pParent;
188356      RtreeCell cell;
188357      int iCell;
188358  
188359      if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell)  ){
188360        RTREE_IS_CORRUPT(pRtree);
188361        return SQLITE_CORRUPT_VTAB;
188362      }
188363  
188364      nodeGetCell(pRtree, pParent, iCell, &cell);
188365      if( !cellContains(pRtree, &cell, pCell) ){
188366        cellUnion(pRtree, &cell, pCell);
188367        nodeOverwriteCell(pRtree, pParent, &cell, iCell);
188368      }
188369   
188370      p = pParent;
188371    }
188372    return SQLITE_OK;
188373  }
188374  
188375  /*
188376  ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
188377  */
188378  static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
188379    sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
188380    sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
188381    sqlite3_step(pRtree->pWriteRowid);
188382    return sqlite3_reset(pRtree->pWriteRowid);
188383  }
188384  
188385  /*
188386  ** Write mapping (iNode->iPar) to the <rtree>_parent table.
188387  */
188388  static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
188389    sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
188390    sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
188391    sqlite3_step(pRtree->pWriteParent);
188392    return sqlite3_reset(pRtree->pWriteParent);
188393  }
188394  
188395  static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
188396  
188397  
188398  /*
188399  ** Arguments aIdx, aDistance and aSpare all point to arrays of size
188400  ** nIdx. The aIdx array contains the set of integers from 0 to 
188401  ** (nIdx-1) in no particular order. This function sorts the values
188402  ** in aIdx according to the indexed values in aDistance. For
188403  ** example, assuming the inputs:
188404  **
188405  **   aIdx      = { 0,   1,   2,   3 }
188406  **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
188407  **
188408  ** this function sets the aIdx array to contain:
188409  **
188410  **   aIdx      = { 0,   1,   2,   3 }
188411  **
188412  ** The aSpare array is used as temporary working space by the
188413  ** sorting algorithm.
188414  */
188415  static void SortByDistance(
188416    int *aIdx, 
188417    int nIdx, 
188418    RtreeDValue *aDistance, 
188419    int *aSpare
188420  ){
188421    if( nIdx>1 ){
188422      int iLeft = 0;
188423      int iRight = 0;
188424  
188425      int nLeft = nIdx/2;
188426      int nRight = nIdx-nLeft;
188427      int *aLeft = aIdx;
188428      int *aRight = &aIdx[nLeft];
188429  
188430      SortByDistance(aLeft, nLeft, aDistance, aSpare);
188431      SortByDistance(aRight, nRight, aDistance, aSpare);
188432  
188433      memcpy(aSpare, aLeft, sizeof(int)*nLeft);
188434      aLeft = aSpare;
188435  
188436      while( iLeft<nLeft || iRight<nRight ){
188437        if( iLeft==nLeft ){
188438          aIdx[iLeft+iRight] = aRight[iRight];
188439          iRight++;
188440        }else if( iRight==nRight ){
188441          aIdx[iLeft+iRight] = aLeft[iLeft];
188442          iLeft++;
188443        }else{
188444          RtreeDValue fLeft = aDistance[aLeft[iLeft]];
188445          RtreeDValue fRight = aDistance[aRight[iRight]];
188446          if( fLeft<fRight ){
188447            aIdx[iLeft+iRight] = aLeft[iLeft];
188448            iLeft++;
188449          }else{
188450            aIdx[iLeft+iRight] = aRight[iRight];
188451            iRight++;
188452          }
188453        }
188454      }
188455  
188456  #if 0
188457      /* Check that the sort worked */
188458      {
188459        int jj;
188460        for(jj=1; jj<nIdx; jj++){
188461          RtreeDValue left = aDistance[aIdx[jj-1]];
188462          RtreeDValue right = aDistance[aIdx[jj]];
188463          assert( left<=right );
188464        }
188465      }
188466  #endif
188467    }
188468  }
188469  
188470  /*
188471  ** Arguments aIdx, aCell and aSpare all point to arrays of size
188472  ** nIdx. The aIdx array contains the set of integers from 0 to 
188473  ** (nIdx-1) in no particular order. This function sorts the values
188474  ** in aIdx according to dimension iDim of the cells in aCell. The
188475  ** minimum value of dimension iDim is considered first, the
188476  ** maximum used to break ties.
188477  **
188478  ** The aSpare array is used as temporary working space by the
188479  ** sorting algorithm.
188480  */
188481  static void SortByDimension(
188482    Rtree *pRtree,
188483    int *aIdx, 
188484    int nIdx, 
188485    int iDim, 
188486    RtreeCell *aCell, 
188487    int *aSpare
188488  ){
188489    if( nIdx>1 ){
188490  
188491      int iLeft = 0;
188492      int iRight = 0;
188493  
188494      int nLeft = nIdx/2;
188495      int nRight = nIdx-nLeft;
188496      int *aLeft = aIdx;
188497      int *aRight = &aIdx[nLeft];
188498  
188499      SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
188500      SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
188501  
188502      memcpy(aSpare, aLeft, sizeof(int)*nLeft);
188503      aLeft = aSpare;
188504      while( iLeft<nLeft || iRight<nRight ){
188505        RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
188506        RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
188507        RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
188508        RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
188509        if( (iLeft!=nLeft) && ((iRight==nRight)
188510         || (xleft1<xright1)
188511         || (xleft1==xright1 && xleft2<xright2)
188512        )){
188513          aIdx[iLeft+iRight] = aLeft[iLeft];
188514          iLeft++;
188515        }else{
188516          aIdx[iLeft+iRight] = aRight[iRight];
188517          iRight++;
188518        }
188519      }
188520  
188521  #if 0
188522      /* Check that the sort worked */
188523      {
188524        int jj;
188525        for(jj=1; jj<nIdx; jj++){
188526          RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
188527          RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
188528          RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
188529          RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
188530          assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
188531        }
188532      }
188533  #endif
188534    }
188535  }
188536  
188537  /*
188538  ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
188539  */
188540  static int splitNodeStartree(
188541    Rtree *pRtree,
188542    RtreeCell *aCell,
188543    int nCell,
188544    RtreeNode *pLeft,
188545    RtreeNode *pRight,
188546    RtreeCell *pBboxLeft,
188547    RtreeCell *pBboxRight
188548  ){
188549    int **aaSorted;
188550    int *aSpare;
188551    int ii;
188552  
188553    int iBestDim = 0;
188554    int iBestSplit = 0;
188555    RtreeDValue fBestMargin = RTREE_ZERO;
188556  
188557    sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
188558  
188559    aaSorted = (int **)sqlite3_malloc64(nByte);
188560    if( !aaSorted ){
188561      return SQLITE_NOMEM;
188562    }
188563  
188564    aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
188565    memset(aaSorted, 0, nByte);
188566    for(ii=0; ii<pRtree->nDim; ii++){
188567      int jj;
188568      aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
188569      for(jj=0; jj<nCell; jj++){
188570        aaSorted[ii][jj] = jj;
188571      }
188572      SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
188573    }
188574  
188575    for(ii=0; ii<pRtree->nDim; ii++){
188576      RtreeDValue margin = RTREE_ZERO;
188577      RtreeDValue fBestOverlap = RTREE_ZERO;
188578      RtreeDValue fBestArea = RTREE_ZERO;
188579      int iBestLeft = 0;
188580      int nLeft;
188581  
188582      for(
188583        nLeft=RTREE_MINCELLS(pRtree); 
188584        nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
188585        nLeft++
188586      ){
188587        RtreeCell left;
188588        RtreeCell right;
188589        int kk;
188590        RtreeDValue overlap;
188591        RtreeDValue area;
188592  
188593        memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
188594        memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
188595        for(kk=1; kk<(nCell-1); kk++){
188596          if( kk<nLeft ){
188597            cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
188598          }else{
188599            cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
188600          }
188601        }
188602        margin += cellMargin(pRtree, &left);
188603        margin += cellMargin(pRtree, &right);
188604        overlap = cellOverlap(pRtree, &left, &right, 1);
188605        area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
188606        if( (nLeft==RTREE_MINCELLS(pRtree))
188607         || (overlap<fBestOverlap)
188608         || (overlap==fBestOverlap && area<fBestArea)
188609        ){
188610          iBestLeft = nLeft;
188611          fBestOverlap = overlap;
188612          fBestArea = area;
188613        }
188614      }
188615  
188616      if( ii==0 || margin<fBestMargin ){
188617        iBestDim = ii;
188618        fBestMargin = margin;
188619        iBestSplit = iBestLeft;
188620      }
188621    }
188622  
188623    memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
188624    memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
188625    for(ii=0; ii<nCell; ii++){
188626      RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
188627      RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
188628      RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
188629      nodeInsertCell(pRtree, pTarget, pCell);
188630      cellUnion(pRtree, pBbox, pCell);
188631    }
188632  
188633    sqlite3_free(aaSorted);
188634    return SQLITE_OK;
188635  }
188636  
188637  
188638  static int updateMapping(
188639    Rtree *pRtree, 
188640    i64 iRowid, 
188641    RtreeNode *pNode, 
188642    int iHeight
188643  ){
188644    int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
188645    xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
188646    if( iHeight>0 ){
188647      RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
188648      if( pChild ){
188649        nodeRelease(pRtree, pChild->pParent);
188650        nodeReference(pNode);
188651        pChild->pParent = pNode;
188652      }
188653    }
188654    return xSetMapping(pRtree, iRowid, pNode->iNode);
188655  }
188656  
188657  static int SplitNode(
188658    Rtree *pRtree,
188659    RtreeNode *pNode,
188660    RtreeCell *pCell,
188661    int iHeight
188662  ){
188663    int i;
188664    int newCellIsRight = 0;
188665  
188666    int rc = SQLITE_OK;
188667    int nCell = NCELL(pNode);
188668    RtreeCell *aCell;
188669    int *aiUsed;
188670  
188671    RtreeNode *pLeft = 0;
188672    RtreeNode *pRight = 0;
188673  
188674    RtreeCell leftbbox;
188675    RtreeCell rightbbox;
188676  
188677    /* Allocate an array and populate it with a copy of pCell and 
188678    ** all cells from node pLeft. Then zero the original node.
188679    */
188680    aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
188681    if( !aCell ){
188682      rc = SQLITE_NOMEM;
188683      goto splitnode_out;
188684    }
188685    aiUsed = (int *)&aCell[nCell+1];
188686    memset(aiUsed, 0, sizeof(int)*(nCell+1));
188687    for(i=0; i<nCell; i++){
188688      nodeGetCell(pRtree, pNode, i, &aCell[i]);
188689    }
188690    nodeZero(pRtree, pNode);
188691    memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
188692    nCell++;
188693  
188694    if( pNode->iNode==1 ){
188695      pRight = nodeNew(pRtree, pNode);
188696      pLeft = nodeNew(pRtree, pNode);
188697      pRtree->iDepth++;
188698      pNode->isDirty = 1;
188699      writeInt16(pNode->zData, pRtree->iDepth);
188700    }else{
188701      pLeft = pNode;
188702      pRight = nodeNew(pRtree, pLeft->pParent);
188703      pLeft->nRef++;
188704    }
188705  
188706    if( !pLeft || !pRight ){
188707      rc = SQLITE_NOMEM;
188708      goto splitnode_out;
188709    }
188710  
188711    memset(pLeft->zData, 0, pRtree->iNodeSize);
188712    memset(pRight->zData, 0, pRtree->iNodeSize);
188713  
188714    rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
188715                           &leftbbox, &rightbbox);
188716    if( rc!=SQLITE_OK ){
188717      goto splitnode_out;
188718    }
188719  
188720    /* Ensure both child nodes have node numbers assigned to them by calling
188721    ** nodeWrite(). Node pRight always needs a node number, as it was created
188722    ** by nodeNew() above. But node pLeft sometimes already has a node number.
188723    ** In this case avoid the all to nodeWrite().
188724    */
188725    if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
188726     || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
188727    ){
188728      goto splitnode_out;
188729    }
188730  
188731    rightbbox.iRowid = pRight->iNode;
188732    leftbbox.iRowid = pLeft->iNode;
188733  
188734    if( pNode->iNode==1 ){
188735      rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
188736      if( rc!=SQLITE_OK ){
188737        goto splitnode_out;
188738      }
188739    }else{
188740      RtreeNode *pParent = pLeft->pParent;
188741      int iCell;
188742      rc = nodeParentIndex(pRtree, pLeft, &iCell);
188743      if( rc==SQLITE_OK ){
188744        nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
188745        rc = AdjustTree(pRtree, pParent, &leftbbox);
188746      }
188747      if( rc!=SQLITE_OK ){
188748        goto splitnode_out;
188749      }
188750    }
188751    if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
188752      goto splitnode_out;
188753    }
188754  
188755    for(i=0; i<NCELL(pRight); i++){
188756      i64 iRowid = nodeGetRowid(pRtree, pRight, i);
188757      rc = updateMapping(pRtree, iRowid, pRight, iHeight);
188758      if( iRowid==pCell->iRowid ){
188759        newCellIsRight = 1;
188760      }
188761      if( rc!=SQLITE_OK ){
188762        goto splitnode_out;
188763      }
188764    }
188765    if( pNode->iNode==1 ){
188766      for(i=0; i<NCELL(pLeft); i++){
188767        i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
188768        rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
188769        if( rc!=SQLITE_OK ){
188770          goto splitnode_out;
188771        }
188772      }
188773    }else if( newCellIsRight==0 ){
188774      rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
188775    }
188776  
188777    if( rc==SQLITE_OK ){
188778      rc = nodeRelease(pRtree, pRight);
188779      pRight = 0;
188780    }
188781    if( rc==SQLITE_OK ){
188782      rc = nodeRelease(pRtree, pLeft);
188783      pLeft = 0;
188784    }
188785  
188786  splitnode_out:
188787    nodeRelease(pRtree, pRight);
188788    nodeRelease(pRtree, pLeft);
188789    sqlite3_free(aCell);
188790    return rc;
188791  }
188792  
188793  /*
188794  ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
188795  ** still NULL, load all ancestor nodes of pLeaf into memory and populate
188796  ** the pLeaf->pParent chain all the way up to the root node.
188797  **
188798  ** This operation is required when a row is deleted (or updated - an update
188799  ** is implemented as a delete followed by an insert). SQLite provides the
188800  ** rowid of the row to delete, which can be used to find the leaf on which
188801  ** the entry resides (argument pLeaf). Once the leaf is located, this 
188802  ** function is called to determine its ancestry.
188803  */
188804  static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
188805    int rc = SQLITE_OK;
188806    RtreeNode *pChild = pLeaf;
188807    while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
188808      int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
188809      sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
188810      rc = sqlite3_step(pRtree->pReadParent);
188811      if( rc==SQLITE_ROW ){
188812        RtreeNode *pTest;           /* Used to test for reference loops */
188813        i64 iNode;                  /* Node number of parent node */
188814  
188815        /* Before setting pChild->pParent, test that we are not creating a
188816        ** loop of references (as we would if, say, pChild==pParent). We don't
188817        ** want to do this as it leads to a memory leak when trying to delete
188818        ** the referenced counted node structures.
188819        */
188820        iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
188821        for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
188822        if( !pTest ){
188823          rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
188824        }
188825      }
188826      rc = sqlite3_reset(pRtree->pReadParent);
188827      if( rc==SQLITE_OK ) rc = rc2;
188828      if( rc==SQLITE_OK && !pChild->pParent ){
188829        RTREE_IS_CORRUPT(pRtree);
188830        rc = SQLITE_CORRUPT_VTAB;
188831      }
188832      pChild = pChild->pParent;
188833    }
188834    return rc;
188835  }
188836  
188837  static int deleteCell(Rtree *, RtreeNode *, int, int);
188838  
188839  static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
188840    int rc;
188841    int rc2;
188842    RtreeNode *pParent = 0;
188843    int iCell;
188844  
188845    assert( pNode->nRef==1 );
188846  
188847    /* Remove the entry in the parent cell. */
188848    rc = nodeParentIndex(pRtree, pNode, &iCell);
188849    if( rc==SQLITE_OK ){
188850      pParent = pNode->pParent;
188851      pNode->pParent = 0;
188852      rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
188853    }
188854    rc2 = nodeRelease(pRtree, pParent);
188855    if( rc==SQLITE_OK ){
188856      rc = rc2;
188857    }
188858    if( rc!=SQLITE_OK ){
188859      return rc;
188860    }
188861  
188862    /* Remove the xxx_node entry. */
188863    sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
188864    sqlite3_step(pRtree->pDeleteNode);
188865    if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
188866      return rc;
188867    }
188868  
188869    /* Remove the xxx_parent entry. */
188870    sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
188871    sqlite3_step(pRtree->pDeleteParent);
188872    if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
188873      return rc;
188874    }
188875    
188876    /* Remove the node from the in-memory hash table and link it into
188877    ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
188878    */
188879    nodeHashDelete(pRtree, pNode);
188880    pNode->iNode = iHeight;
188881    pNode->pNext = pRtree->pDeleted;
188882    pNode->nRef++;
188883    pRtree->pDeleted = pNode;
188884  
188885    return SQLITE_OK;
188886  }
188887  
188888  static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
188889    RtreeNode *pParent = pNode->pParent;
188890    int rc = SQLITE_OK; 
188891    if( pParent ){
188892      int ii; 
188893      int nCell = NCELL(pNode);
188894      RtreeCell box;                            /* Bounding box for pNode */
188895      nodeGetCell(pRtree, pNode, 0, &box);
188896      for(ii=1; ii<nCell; ii++){
188897        RtreeCell cell;
188898        nodeGetCell(pRtree, pNode, ii, &cell);
188899        cellUnion(pRtree, &box, &cell);
188900      }
188901      box.iRowid = pNode->iNode;
188902      rc = nodeParentIndex(pRtree, pNode, &ii);
188903      if( rc==SQLITE_OK ){
188904        nodeOverwriteCell(pRtree, pParent, &box, ii);
188905        rc = fixBoundingBox(pRtree, pParent);
188906      }
188907    }
188908    return rc;
188909  }
188910  
188911  /*
188912  ** Delete the cell at index iCell of node pNode. After removing the
188913  ** cell, adjust the r-tree data structure if required.
188914  */
188915  static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
188916    RtreeNode *pParent;
188917    int rc;
188918  
188919    if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
188920      return rc;
188921    }
188922  
188923    /* Remove the cell from the node. This call just moves bytes around
188924    ** the in-memory node image, so it cannot fail.
188925    */
188926    nodeDeleteCell(pRtree, pNode, iCell);
188927  
188928    /* If the node is not the tree root and now has less than the minimum
188929    ** number of cells, remove it from the tree. Otherwise, update the
188930    ** cell in the parent node so that it tightly contains the updated
188931    ** node.
188932    */
188933    pParent = pNode->pParent;
188934    assert( pParent || pNode->iNode==1 );
188935    if( pParent ){
188936      if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
188937        rc = removeNode(pRtree, pNode, iHeight);
188938      }else{
188939        rc = fixBoundingBox(pRtree, pNode);
188940      }
188941    }
188942  
188943    return rc;
188944  }
188945  
188946  static int Reinsert(
188947    Rtree *pRtree, 
188948    RtreeNode *pNode, 
188949    RtreeCell *pCell, 
188950    int iHeight
188951  ){
188952    int *aOrder;
188953    int *aSpare;
188954    RtreeCell *aCell;
188955    RtreeDValue *aDistance;
188956    int nCell;
188957    RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
188958    int iDim;
188959    int ii;
188960    int rc = SQLITE_OK;
188961    int n;
188962  
188963    memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
188964  
188965    nCell = NCELL(pNode)+1;
188966    n = (nCell+1)&(~1);
188967  
188968    /* Allocate the buffers used by this operation. The allocation is
188969    ** relinquished before this function returns.
188970    */
188971    aCell = (RtreeCell *)sqlite3_malloc64(n * (
188972      sizeof(RtreeCell)     +         /* aCell array */
188973      sizeof(int)           +         /* aOrder array */
188974      sizeof(int)           +         /* aSpare array */
188975      sizeof(RtreeDValue)             /* aDistance array */
188976    ));
188977    if( !aCell ){
188978      return SQLITE_NOMEM;
188979    }
188980    aOrder    = (int *)&aCell[n];
188981    aSpare    = (int *)&aOrder[n];
188982    aDistance = (RtreeDValue *)&aSpare[n];
188983  
188984    for(ii=0; ii<nCell; ii++){
188985      if( ii==(nCell-1) ){
188986        memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
188987      }else{
188988        nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
188989      }
188990      aOrder[ii] = ii;
188991      for(iDim=0; iDim<pRtree->nDim; iDim++){
188992        aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
188993        aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
188994      }
188995    }
188996    for(iDim=0; iDim<pRtree->nDim; iDim++){
188997      aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
188998    }
188999  
189000    for(ii=0; ii<nCell; ii++){
189001      aDistance[ii] = RTREE_ZERO;
189002      for(iDim=0; iDim<pRtree->nDim; iDim++){
189003        RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
189004                                 DCOORD(aCell[ii].aCoord[iDim*2]));
189005        aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
189006      }
189007    }
189008  
189009    SortByDistance(aOrder, nCell, aDistance, aSpare);
189010    nodeZero(pRtree, pNode);
189011  
189012    for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
189013      RtreeCell *p = &aCell[aOrder[ii]];
189014      nodeInsertCell(pRtree, pNode, p);
189015      if( p->iRowid==pCell->iRowid ){
189016        if( iHeight==0 ){
189017          rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
189018        }else{
189019          rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
189020        }
189021      }
189022    }
189023    if( rc==SQLITE_OK ){
189024      rc = fixBoundingBox(pRtree, pNode);
189025    }
189026    for(; rc==SQLITE_OK && ii<nCell; ii++){
189027      /* Find a node to store this cell in. pNode->iNode currently contains
189028      ** the height of the sub-tree headed by the cell.
189029      */
189030      RtreeNode *pInsert;
189031      RtreeCell *p = &aCell[aOrder[ii]];
189032      rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
189033      if( rc==SQLITE_OK ){
189034        int rc2;
189035        rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
189036        rc2 = nodeRelease(pRtree, pInsert);
189037        if( rc==SQLITE_OK ){
189038          rc = rc2;
189039        }
189040      }
189041    }
189042  
189043    sqlite3_free(aCell);
189044    return rc;
189045  }
189046  
189047  /*
189048  ** Insert cell pCell into node pNode. Node pNode is the head of a 
189049  ** subtree iHeight high (leaf nodes have iHeight==0).
189050  */
189051  static int rtreeInsertCell(
189052    Rtree *pRtree,
189053    RtreeNode *pNode,
189054    RtreeCell *pCell,
189055    int iHeight
189056  ){
189057    int rc = SQLITE_OK;
189058    if( iHeight>0 ){
189059      RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
189060      if( pChild ){
189061        nodeRelease(pRtree, pChild->pParent);
189062        nodeReference(pNode);
189063        pChild->pParent = pNode;
189064      }
189065    }
189066    if( nodeInsertCell(pRtree, pNode, pCell) ){
189067      if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
189068        rc = SplitNode(pRtree, pNode, pCell, iHeight);
189069      }else{
189070        pRtree->iReinsertHeight = iHeight;
189071        rc = Reinsert(pRtree, pNode, pCell, iHeight);
189072      }
189073    }else{
189074      rc = AdjustTree(pRtree, pNode, pCell);
189075      if( rc==SQLITE_OK ){
189076        if( iHeight==0 ){
189077          rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
189078        }else{
189079          rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
189080        }
189081      }
189082    }
189083    return rc;
189084  }
189085  
189086  static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
189087    int ii;
189088    int rc = SQLITE_OK;
189089    int nCell = NCELL(pNode);
189090  
189091    for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
189092      RtreeNode *pInsert;
189093      RtreeCell cell;
189094      nodeGetCell(pRtree, pNode, ii, &cell);
189095  
189096      /* Find a node to store this cell in. pNode->iNode currently contains
189097      ** the height of the sub-tree headed by the cell.
189098      */
189099      rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
189100      if( rc==SQLITE_OK ){
189101        int rc2;
189102        rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
189103        rc2 = nodeRelease(pRtree, pInsert);
189104        if( rc==SQLITE_OK ){
189105          rc = rc2;
189106        }
189107      }
189108    }
189109    return rc;
189110  }
189111  
189112  /*
189113  ** Select a currently unused rowid for a new r-tree record.
189114  */
189115  static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
189116    int rc;
189117    sqlite3_bind_null(pRtree->pWriteRowid, 1);
189118    sqlite3_bind_null(pRtree->pWriteRowid, 2);
189119    sqlite3_step(pRtree->pWriteRowid);
189120    rc = sqlite3_reset(pRtree->pWriteRowid);
189121    *piRowid = sqlite3_last_insert_rowid(pRtree->db);
189122    return rc;
189123  }
189124  
189125  /*
189126  ** Remove the entry with rowid=iDelete from the r-tree structure.
189127  */
189128  static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
189129    int rc;                         /* Return code */
189130    RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
189131    int iCell;                      /* Index of iDelete cell in pLeaf */
189132    RtreeNode *pRoot = 0;           /* Root node of rtree structure */
189133  
189134  
189135    /* Obtain a reference to the root node to initialize Rtree.iDepth */
189136    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
189137  
189138    /* Obtain a reference to the leaf node that contains the entry 
189139    ** about to be deleted. 
189140    */
189141    if( rc==SQLITE_OK ){
189142      rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
189143    }
189144  
189145  #ifdef CORRUPT_DB
189146    assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
189147  #endif
189148  
189149    /* Delete the cell in question from the leaf node. */
189150    if( rc==SQLITE_OK && pLeaf ){
189151      int rc2;
189152      rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
189153      if( rc==SQLITE_OK ){
189154        rc = deleteCell(pRtree, pLeaf, iCell, 0);
189155      }
189156      rc2 = nodeRelease(pRtree, pLeaf);
189157      if( rc==SQLITE_OK ){
189158        rc = rc2;
189159      }
189160    }
189161  
189162    /* Delete the corresponding entry in the <rtree>_rowid table. */
189163    if( rc==SQLITE_OK ){
189164      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
189165      sqlite3_step(pRtree->pDeleteRowid);
189166      rc = sqlite3_reset(pRtree->pDeleteRowid);
189167    }
189168  
189169    /* Check if the root node now has exactly one child. If so, remove
189170    ** it, schedule the contents of the child for reinsertion and 
189171    ** reduce the tree height by one.
189172    **
189173    ** This is equivalent to copying the contents of the child into
189174    ** the root node (the operation that Gutman's paper says to perform 
189175    ** in this scenario).
189176    */
189177    if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
189178      int rc2;
189179      RtreeNode *pChild = 0;
189180      i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
189181      rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
189182      if( rc==SQLITE_OK ){
189183        rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
189184      }
189185      rc2 = nodeRelease(pRtree, pChild);
189186      if( rc==SQLITE_OK ) rc = rc2;
189187      if( rc==SQLITE_OK ){
189188        pRtree->iDepth--;
189189        writeInt16(pRoot->zData, pRtree->iDepth);
189190        pRoot->isDirty = 1;
189191      }
189192    }
189193  
189194    /* Re-insert the contents of any underfull nodes removed from the tree. */
189195    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
189196      if( rc==SQLITE_OK ){
189197        rc = reinsertNodeContent(pRtree, pLeaf);
189198      }
189199      pRtree->pDeleted = pLeaf->pNext;
189200      pRtree->nNodeRef--;
189201      sqlite3_free(pLeaf);
189202    }
189203  
189204    /* Release the reference to the root node. */
189205    if( rc==SQLITE_OK ){
189206      rc = nodeRelease(pRtree, pRoot);
189207    }else{
189208      nodeRelease(pRtree, pRoot);
189209    }
189210  
189211    return rc;
189212  }
189213  
189214  /*
189215  ** Rounding constants for float->double conversion.
189216  */
189217  #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
189218  #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
189219  
189220  #if !defined(SQLITE_RTREE_INT_ONLY)
189221  /*
189222  ** Convert an sqlite3_value into an RtreeValue (presumably a float)
189223  ** while taking care to round toward negative or positive, respectively.
189224  */
189225  static RtreeValue rtreeValueDown(sqlite3_value *v){
189226    double d = sqlite3_value_double(v);
189227    float f = (float)d;
189228    if( f>d ){
189229      f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
189230    }
189231    return f;
189232  }
189233  static RtreeValue rtreeValueUp(sqlite3_value *v){
189234    double d = sqlite3_value_double(v);
189235    float f = (float)d;
189236    if( f<d ){
189237      f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
189238    }
189239    return f;
189240  }
189241  #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
189242  
189243  /*
189244  ** A constraint has failed while inserting a row into an rtree table. 
189245  ** Assuming no OOM error occurs, this function sets the error message 
189246  ** (at pRtree->base.zErrMsg) to an appropriate value and returns
189247  ** SQLITE_CONSTRAINT.
189248  **
189249  ** Parameter iCol is the index of the leftmost column involved in the
189250  ** constraint failure. If it is 0, then the constraint that failed is
189251  ** the unique constraint on the id column. Otherwise, it is the rtree
189252  ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
189253  **
189254  ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
189255  */
189256  static int rtreeConstraintError(Rtree *pRtree, int iCol){
189257    sqlite3_stmt *pStmt = 0;
189258    char *zSql; 
189259    int rc;
189260  
189261    assert( iCol==0 || iCol%2 );
189262    zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
189263    if( zSql ){
189264      rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
189265    }else{
189266      rc = SQLITE_NOMEM;
189267    }
189268    sqlite3_free(zSql);
189269  
189270    if( rc==SQLITE_OK ){
189271      if( iCol==0 ){
189272        const char *zCol = sqlite3_column_name(pStmt, 0);
189273        pRtree->base.zErrMsg = sqlite3_mprintf(
189274            "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
189275        );
189276      }else{
189277        const char *zCol1 = sqlite3_column_name(pStmt, iCol);
189278        const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
189279        pRtree->base.zErrMsg = sqlite3_mprintf(
189280            "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
189281        );
189282      }
189283    }
189284  
189285    sqlite3_finalize(pStmt);
189286    return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
189287  }
189288  
189289  
189290  
189291  /*
189292  ** The xUpdate method for rtree module virtual tables.
189293  */
189294  static int rtreeUpdate(
189295    sqlite3_vtab *pVtab, 
189296    int nData, 
189297    sqlite3_value **aData, 
189298    sqlite_int64 *pRowid
189299  ){
189300    Rtree *pRtree = (Rtree *)pVtab;
189301    int rc = SQLITE_OK;
189302    RtreeCell cell;                 /* New cell to insert if nData>1 */
189303    int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
189304  
189305    if( pRtree->nNodeRef ){
189306      /* Unable to write to the btree while another cursor is reading from it,
189307      ** since the write might do a rebalance which would disrupt the read
189308      ** cursor. */
189309      return SQLITE_LOCKED_VTAB;
189310    }
189311    rtreeReference(pRtree);
189312    assert(nData>=1);
189313  
189314    cell.iRowid = 0;  /* Used only to suppress a compiler warning */
189315  
189316    /* Constraint handling. A write operation on an r-tree table may return
189317    ** SQLITE_CONSTRAINT for two reasons:
189318    **
189319    **   1. A duplicate rowid value, or
189320    **   2. The supplied data violates the "x2>=x1" constraint.
189321    **
189322    ** In the first case, if the conflict-handling mode is REPLACE, then
189323    ** the conflicting row can be removed before proceeding. In the second
189324    ** case, SQLITE_CONSTRAINT must be returned regardless of the
189325    ** conflict-handling mode specified by the user.
189326    */
189327    if( nData>1 ){
189328      int ii;
189329      int nn = nData - 4;
189330  
189331      if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
189332      /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
189333      **
189334      ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
189335      ** with "column" that are interpreted as table constraints.
189336      ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
189337      ** This problem was discovered after years of use, so we silently ignore
189338      ** these kinds of misdeclared tables to avoid breaking any legacy.
189339      */
189340  
189341  #ifndef SQLITE_RTREE_INT_ONLY
189342      if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
189343        for(ii=0; ii<nn; ii+=2){
189344          cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
189345          cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
189346          if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
189347            rc = rtreeConstraintError(pRtree, ii+1);
189348            goto constraint;
189349          }
189350        }
189351      }else
189352  #endif
189353      {
189354        for(ii=0; ii<nn; ii+=2){
189355          cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
189356          cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
189357          if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
189358            rc = rtreeConstraintError(pRtree, ii+1);
189359            goto constraint;
189360          }
189361        }
189362      }
189363  
189364      /* If a rowid value was supplied, check if it is already present in 
189365      ** the table. If so, the constraint has failed. */
189366      if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
189367        cell.iRowid = sqlite3_value_int64(aData[2]);
189368        if( sqlite3_value_type(aData[0])==SQLITE_NULL
189369         || sqlite3_value_int64(aData[0])!=cell.iRowid
189370        ){
189371          int steprc;
189372          sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
189373          steprc = sqlite3_step(pRtree->pReadRowid);
189374          rc = sqlite3_reset(pRtree->pReadRowid);
189375          if( SQLITE_ROW==steprc ){
189376            if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
189377              rc = rtreeDeleteRowid(pRtree, cell.iRowid);
189378            }else{
189379              rc = rtreeConstraintError(pRtree, 0);
189380              goto constraint;
189381            }
189382          }
189383        }
189384        bHaveRowid = 1;
189385      }
189386    }
189387  
189388    /* If aData[0] is not an SQL NULL value, it is the rowid of a
189389    ** record to delete from the r-tree table. The following block does
189390    ** just that.
189391    */
189392    if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
189393      rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
189394    }
189395  
189396    /* If the aData[] array contains more than one element, elements
189397    ** (aData[2]..aData[argc-1]) contain a new record to insert into
189398    ** the r-tree structure.
189399    */
189400    if( rc==SQLITE_OK && nData>1 ){
189401      /* Insert the new record into the r-tree */
189402      RtreeNode *pLeaf = 0;
189403  
189404      /* Figure out the rowid of the new row. */
189405      if( bHaveRowid==0 ){
189406        rc = rtreeNewRowid(pRtree, &cell.iRowid);
189407      }
189408      *pRowid = cell.iRowid;
189409  
189410      if( rc==SQLITE_OK ){
189411        rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
189412      }
189413      if( rc==SQLITE_OK ){
189414        int rc2;
189415        pRtree->iReinsertHeight = -1;
189416        rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
189417        rc2 = nodeRelease(pRtree, pLeaf);
189418        if( rc==SQLITE_OK ){
189419          rc = rc2;
189420        }
189421      }
189422      if( rc==SQLITE_OK && pRtree->nAux ){
189423        sqlite3_stmt *pUp = pRtree->pWriteAux;
189424        int jj;
189425        sqlite3_bind_int64(pUp, 1, *pRowid);
189426        for(jj=0; jj<pRtree->nAux; jj++){
189427          sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
189428        }
189429        sqlite3_step(pUp);
189430        rc = sqlite3_reset(pUp);
189431      }
189432    }
189433  
189434  constraint:
189435    rtreeRelease(pRtree);
189436    return rc;
189437  }
189438  
189439  /*
189440  ** Called when a transaction starts.
189441  */
189442  static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
189443    Rtree *pRtree = (Rtree *)pVtab;
189444    assert( pRtree->inWrTrans==0 );
189445    pRtree->inWrTrans++;
189446    return SQLITE_OK;
189447  }
189448  
189449  /*
189450  ** Called when a transaction completes (either by COMMIT or ROLLBACK).
189451  ** The sqlite3_blob object should be released at this point.
189452  */
189453  static int rtreeEndTransaction(sqlite3_vtab *pVtab){
189454    Rtree *pRtree = (Rtree *)pVtab;
189455    pRtree->inWrTrans = 0;
189456    nodeBlobReset(pRtree);
189457    return SQLITE_OK;
189458  }
189459  
189460  /*
189461  ** The xRename method for rtree module virtual tables.
189462  */
189463  static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
189464    Rtree *pRtree = (Rtree *)pVtab;
189465    int rc = SQLITE_NOMEM;
189466    char *zSql = sqlite3_mprintf(
189467      "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
189468      "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
189469      "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
189470      , pRtree->zDb, pRtree->zName, zNewName 
189471      , pRtree->zDb, pRtree->zName, zNewName 
189472      , pRtree->zDb, pRtree->zName, zNewName
189473    );
189474    if( zSql ){
189475      nodeBlobReset(pRtree);
189476      rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
189477      sqlite3_free(zSql);
189478    }
189479    return rc;
189480  }
189481  
189482  /*
189483  ** The xSavepoint method.
189484  **
189485  ** This module does not need to do anything to support savepoints. However,
189486  ** it uses this hook to close any open blob handle. This is done because a 
189487  ** DROP TABLE command - which fortunately always opens a savepoint - cannot 
189488  ** succeed if there are any open blob handles. i.e. if the blob handle were
189489  ** not closed here, the following would fail:
189490  **
189491  **   BEGIN;
189492  **     INSERT INTO rtree...
189493  **     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
189494  **   COMMIT;
189495  */
189496  static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
189497    Rtree *pRtree = (Rtree *)pVtab;
189498    u8 iwt = pRtree->inWrTrans;
189499    UNUSED_PARAMETER(iSavepoint);
189500    pRtree->inWrTrans = 0;
189501    nodeBlobReset(pRtree);
189502    pRtree->inWrTrans = iwt;
189503    return SQLITE_OK;
189504  }
189505  
189506  /*
189507  ** This function populates the pRtree->nRowEst variable with an estimate
189508  ** of the number of rows in the virtual table. If possible, this is based
189509  ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
189510  */
189511  static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
189512    const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
189513    char *zSql;
189514    sqlite3_stmt *p;
189515    int rc;
189516    i64 nRow = 0;
189517  
189518    rc = sqlite3_table_column_metadata(
189519        db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
189520    );
189521    if( rc!=SQLITE_OK ){
189522      pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
189523      return rc==SQLITE_ERROR ? SQLITE_OK : rc;
189524    }
189525    zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
189526    if( zSql==0 ){
189527      rc = SQLITE_NOMEM;
189528    }else{
189529      rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
189530      if( rc==SQLITE_OK ){
189531        if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
189532        rc = sqlite3_finalize(p);
189533      }else if( rc!=SQLITE_NOMEM ){
189534        rc = SQLITE_OK;
189535      }
189536  
189537      if( rc==SQLITE_OK ){
189538        if( nRow==0 ){
189539          pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
189540        }else{
189541          pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
189542        }
189543      }
189544      sqlite3_free(zSql);
189545    }
189546  
189547    return rc;
189548  }
189549  
189550  
189551  /*
189552  ** Return true if zName is the extension on one of the shadow tables used
189553  ** by this module.
189554  */
189555  static int rtreeShadowName(const char *zName){
189556    static const char *azName[] = {
189557      "node", "parent", "rowid"
189558    };
189559    unsigned int i;
189560    for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
189561      if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
189562    }
189563    return 0;
189564  }
189565  
189566  static sqlite3_module rtreeModule = {
189567    3,                          /* iVersion */
189568    rtreeCreate,                /* xCreate - create a table */
189569    rtreeConnect,               /* xConnect - connect to an existing table */
189570    rtreeBestIndex,             /* xBestIndex - Determine search strategy */
189571    rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
189572    rtreeDestroy,               /* xDestroy - Drop a table */
189573    rtreeOpen,                  /* xOpen - open a cursor */
189574    rtreeClose,                 /* xClose - close a cursor */
189575    rtreeFilter,                /* xFilter - configure scan constraints */
189576    rtreeNext,                  /* xNext - advance a cursor */
189577    rtreeEof,                   /* xEof */
189578    rtreeColumn,                /* xColumn - read data */
189579    rtreeRowid,                 /* xRowid - read data */
189580    rtreeUpdate,                /* xUpdate - write data */
189581    rtreeBeginTransaction,      /* xBegin - begin transaction */
189582    rtreeEndTransaction,        /* xSync - sync transaction */
189583    rtreeEndTransaction,        /* xCommit - commit transaction */
189584    rtreeEndTransaction,        /* xRollback - rollback transaction */
189585    0,                          /* xFindFunction - function overloading */
189586    rtreeRename,                /* xRename - rename the table */
189587    rtreeSavepoint,             /* xSavepoint */
189588    0,                          /* xRelease */
189589    0,                          /* xRollbackTo */
189590    rtreeShadowName             /* xShadowName */
189591  };
189592  
189593  static int rtreeSqlInit(
189594    Rtree *pRtree, 
189595    sqlite3 *db, 
189596    const char *zDb, 
189597    const char *zPrefix, 
189598    int isCreate
189599  ){
189600    int rc = SQLITE_OK;
189601  
189602    #define N_STATEMENT 8
189603    static const char *azSql[N_STATEMENT] = {
189604      /* Write the xxx_node table */
189605      "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
189606      "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
189607  
189608      /* Read and write the xxx_rowid table */
189609      "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
189610      "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
189611      "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
189612  
189613      /* Read and write the xxx_parent table */
189614      "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
189615      "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
189616      "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
189617    };
189618    sqlite3_stmt **appStmt[N_STATEMENT];
189619    int i;
189620    const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
189621  
189622    pRtree->db = db;
189623  
189624    if( isCreate ){
189625      char *zCreate;
189626      sqlite3_str *p = sqlite3_str_new(db);
189627      int ii;
189628      sqlite3_str_appendf(p,
189629         "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
189630         zDb, zPrefix);
189631      for(ii=0; ii<pRtree->nAux; ii++){
189632        sqlite3_str_appendf(p,",a%d",ii);
189633      }
189634      sqlite3_str_appendf(p,
189635        ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
189636        zDb, zPrefix);
189637      sqlite3_str_appendf(p,
189638      "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
189639        zDb, zPrefix);
189640      sqlite3_str_appendf(p,
189641         "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
189642         zDb, zPrefix, pRtree->iNodeSize);
189643      zCreate = sqlite3_str_finish(p);
189644      if( !zCreate ){
189645        return SQLITE_NOMEM;
189646      }
189647      rc = sqlite3_exec(db, zCreate, 0, 0, 0);
189648      sqlite3_free(zCreate);
189649      if( rc!=SQLITE_OK ){
189650        return rc;
189651      }
189652    }
189653  
189654    appStmt[0] = &pRtree->pWriteNode;
189655    appStmt[1] = &pRtree->pDeleteNode;
189656    appStmt[2] = &pRtree->pReadRowid;
189657    appStmt[3] = &pRtree->pWriteRowid;
189658    appStmt[4] = &pRtree->pDeleteRowid;
189659    appStmt[5] = &pRtree->pReadParent;
189660    appStmt[6] = &pRtree->pWriteParent;
189661    appStmt[7] = &pRtree->pDeleteParent;
189662  
189663    rc = rtreeQueryStat1(db, pRtree);
189664    for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
189665      char *zSql;
189666      const char *zFormat;
189667      if( i!=3 || pRtree->nAux==0 ){
189668         zFormat = azSql[i];
189669      }else {
189670         /* An UPSERT is very slightly slower than REPLACE, but it is needed
189671         ** if there are auxiliary columns */
189672         zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
189673                    "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
189674      }
189675      zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
189676      if( zSql ){
189677        rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); 
189678      }else{
189679        rc = SQLITE_NOMEM;
189680      }
189681      sqlite3_free(zSql);
189682    }
189683    if( pRtree->nAux ){
189684      pRtree->zReadAuxSql = sqlite3_mprintf(
189685         "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
189686         zDb, zPrefix);
189687      if( pRtree->zReadAuxSql==0 ){
189688        rc = SQLITE_NOMEM;
189689      }else{
189690        sqlite3_str *p = sqlite3_str_new(db);
189691        int ii;
189692        char *zSql;
189693        sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
189694        for(ii=0; ii<pRtree->nAux; ii++){
189695          if( ii ) sqlite3_str_append(p, ",", 1);
189696          if( ii<pRtree->nAuxNotNull ){
189697            sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
189698          }else{
189699            sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
189700          }
189701        }
189702        sqlite3_str_appendf(p, " WHERE rowid=?1");
189703        zSql = sqlite3_str_finish(p);
189704        if( zSql==0 ){
189705          rc = SQLITE_NOMEM;
189706        }else{
189707          rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); 
189708          sqlite3_free(zSql);
189709        }
189710      }
189711    }
189712  
189713    return rc;
189714  }
189715  
189716  /*
189717  ** The second argument to this function contains the text of an SQL statement
189718  ** that returns a single integer value. The statement is compiled and executed
189719  ** using database connection db. If successful, the integer value returned
189720  ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
189721  ** code is returned and the value of *piVal after returning is not defined.
189722  */
189723  static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
189724    int rc = SQLITE_NOMEM;
189725    if( zSql ){
189726      sqlite3_stmt *pStmt = 0;
189727      rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
189728      if( rc==SQLITE_OK ){
189729        if( SQLITE_ROW==sqlite3_step(pStmt) ){
189730          *piVal = sqlite3_column_int(pStmt, 0);
189731        }
189732        rc = sqlite3_finalize(pStmt);
189733      }
189734    }
189735    return rc;
189736  }
189737  
189738  /*
189739  ** This function is called from within the xConnect() or xCreate() method to
189740  ** determine the node-size used by the rtree table being created or connected
189741  ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
189742  ** Otherwise, an SQLite error code is returned.
189743  **
189744  ** If this function is being called as part of an xConnect(), then the rtree
189745  ** table already exists. In this case the node-size is determined by inspecting
189746  ** the root node of the tree.
189747  **
189748  ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
189749  ** This ensures that each node is stored on a single database page. If the 
189750  ** database page-size is so large that more than RTREE_MAXCELLS entries 
189751  ** would fit in a single node, use a smaller node-size.
189752  */
189753  static int getNodeSize(
189754    sqlite3 *db,                    /* Database handle */
189755    Rtree *pRtree,                  /* Rtree handle */
189756    int isCreate,                   /* True for xCreate, false for xConnect */
189757    char **pzErr                    /* OUT: Error message, if any */
189758  ){
189759    int rc;
189760    char *zSql;
189761    if( isCreate ){
189762      int iPageSize = 0;
189763      zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
189764      rc = getIntFromStmt(db, zSql, &iPageSize);
189765      if( rc==SQLITE_OK ){
189766        pRtree->iNodeSize = iPageSize-64;
189767        if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
189768          pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
189769        }
189770      }else{
189771        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
189772      }
189773    }else{
189774      zSql = sqlite3_mprintf(
189775          "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
189776          pRtree->zDb, pRtree->zName
189777      );
189778      rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
189779      if( rc!=SQLITE_OK ){
189780        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
189781      }else if( pRtree->iNodeSize<(512-64) ){
189782        rc = SQLITE_CORRUPT_VTAB;
189783        RTREE_IS_CORRUPT(pRtree);
189784        *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
189785                                 pRtree->zName);
189786      }
189787    }
189788  
189789    sqlite3_free(zSql);
189790    return rc;
189791  }
189792  
189793  /* 
189794  ** This function is the implementation of both the xConnect and xCreate
189795  ** methods of the r-tree virtual table.
189796  **
189797  **   argv[0]   -> module name
189798  **   argv[1]   -> database name
189799  **   argv[2]   -> table name
189800  **   argv[...] -> column names...
189801  */
189802  static int rtreeInit(
189803    sqlite3 *db,                        /* Database connection */
189804    void *pAux,                         /* One of the RTREE_COORD_* constants */
189805    int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
189806    sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
189807    char **pzErr,                       /* OUT: Error message, if any */
189808    int isCreate                        /* True for xCreate, false for xConnect */
189809  ){
189810    int rc = SQLITE_OK;
189811    Rtree *pRtree;
189812    int nDb;              /* Length of string argv[1] */
189813    int nName;            /* Length of string argv[2] */
189814    int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
189815    sqlite3_str *pSql;
189816    char *zSql;
189817    int ii = 4;
189818    int iErr;
189819  
189820    const char *aErrMsg[] = {
189821      0,                                                    /* 0 */
189822      "Wrong number of columns for an rtree table",         /* 1 */
189823      "Too few columns for an rtree table",                 /* 2 */
189824      "Too many columns for an rtree table",                /* 3 */
189825      "Auxiliary rtree columns must be last"                /* 4 */
189826    };
189827  
189828    assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
189829    if( argc>RTREE_MAX_AUX_COLUMN+3 ){
189830      *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
189831      return SQLITE_ERROR;
189832    }
189833  
189834    sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
189835  
189836    /* Allocate the sqlite3_vtab structure */
189837    nDb = (int)strlen(argv[1]);
189838    nName = (int)strlen(argv[2]);
189839    pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
189840    if( !pRtree ){
189841      return SQLITE_NOMEM;
189842    }
189843    memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
189844    pRtree->nBusy = 1;
189845    pRtree->base.pModule = &rtreeModule;
189846    pRtree->zDb = (char *)&pRtree[1];
189847    pRtree->zName = &pRtree->zDb[nDb+1];
189848    pRtree->eCoordType = (u8)eCoordType;
189849    memcpy(pRtree->zDb, argv[1], nDb);
189850    memcpy(pRtree->zName, argv[2], nName);
189851  
189852  
189853    /* Create/Connect to the underlying relational database schema. If
189854    ** that is successful, call sqlite3_declare_vtab() to configure
189855    ** the r-tree table schema.
189856    */
189857    pSql = sqlite3_str_new(db);
189858    sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
189859    for(ii=4; ii<argc; ii++){
189860      if( argv[ii][0]=='+' ){
189861        pRtree->nAux++;
189862        sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
189863      }else if( pRtree->nAux>0 ){
189864        break;
189865      }else{
189866        pRtree->nDim2++;
189867        sqlite3_str_appendf(pSql, ",%s", argv[ii]);
189868      }
189869    }
189870    sqlite3_str_appendf(pSql, ");");
189871    zSql = sqlite3_str_finish(pSql);
189872    if( !zSql ){
189873      rc = SQLITE_NOMEM;
189874    }else if( ii<argc ){
189875      *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
189876      rc = SQLITE_ERROR;
189877    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
189878      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
189879    }
189880    sqlite3_free(zSql);
189881    if( rc ) goto rtreeInit_fail;
189882    pRtree->nDim = pRtree->nDim2/2;
189883    if( pRtree->nDim<1 ){
189884      iErr = 2;
189885    }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
189886      iErr = 3;
189887    }else if( pRtree->nDim2 % 2 ){
189888      iErr = 1;
189889    }else{
189890      iErr = 0;
189891    }
189892    if( iErr ){
189893      *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
189894      goto rtreeInit_fail;
189895    }
189896    pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
189897  
189898    /* Figure out the node size to use. */
189899    rc = getNodeSize(db, pRtree, isCreate, pzErr);
189900    if( rc ) goto rtreeInit_fail;
189901    rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
189902    if( rc ){
189903      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
189904      goto rtreeInit_fail;
189905    }
189906  
189907    *ppVtab = (sqlite3_vtab *)pRtree;
189908    return SQLITE_OK;
189909  
189910  rtreeInit_fail:
189911    if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
189912    assert( *ppVtab==0 );
189913    assert( pRtree->nBusy==1 );
189914    rtreeRelease(pRtree);
189915    return rc;
189916  }
189917  
189918  
189919  /*
189920  ** Implementation of a scalar function that decodes r-tree nodes to
189921  ** human readable strings. This can be used for debugging and analysis.
189922  **
189923  ** The scalar function takes two arguments: (1) the number of dimensions
189924  ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
189925  ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
189926  ** deserialize all nodes, a statement like:
189927  **
189928  **   SELECT rtreenode(2, data) FROM rt_node;
189929  **
189930  ** The human readable string takes the form of a Tcl list with one
189931  ** entry for each cell in the r-tree node. Each entry is itself a
189932  ** list, containing the 8-byte rowid/pageno followed by the 
189933  ** <num-dimension>*2 coordinates.
189934  */
189935  static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
189936    char *zText = 0;
189937    RtreeNode node;
189938    Rtree tree;
189939    int ii;
189940  
189941    UNUSED_PARAMETER(nArg);
189942    memset(&node, 0, sizeof(RtreeNode));
189943    memset(&tree, 0, sizeof(Rtree));
189944    tree.nDim = (u8)sqlite3_value_int(apArg[0]);
189945    tree.nDim2 = tree.nDim*2;
189946    tree.nBytesPerCell = 8 + 8 * tree.nDim;
189947    node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
189948  
189949    for(ii=0; ii<NCELL(&node); ii++){
189950      char zCell[512];
189951      int nCell = 0;
189952      RtreeCell cell;
189953      int jj;
189954  
189955      nodeGetCell(&tree, &node, ii, &cell);
189956      sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
189957      nCell = (int)strlen(zCell);
189958      for(jj=0; jj<tree.nDim2; jj++){
189959  #ifndef SQLITE_RTREE_INT_ONLY
189960        sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
189961                         (double)cell.aCoord[jj].f);
189962  #else
189963        sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
189964                         cell.aCoord[jj].i);
189965  #endif
189966        nCell = (int)strlen(zCell);
189967      }
189968  
189969      if( zText ){
189970        char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
189971        sqlite3_free(zText);
189972        zText = zTextNew;
189973      }else{
189974        zText = sqlite3_mprintf("{%s}", zCell);
189975      }
189976    }
189977    
189978    sqlite3_result_text(ctx, zText, -1, sqlite3_free);
189979  }
189980  
189981  /* This routine implements an SQL function that returns the "depth" parameter
189982  ** from the front of a blob that is an r-tree node.  For example:
189983  **
189984  **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
189985  **
189986  ** The depth value is 0 for all nodes other than the root node, and the root
189987  ** node always has nodeno=1, so the example above is the primary use for this
189988  ** routine.  This routine is intended for testing and analysis only.
189989  */
189990  static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
189991    UNUSED_PARAMETER(nArg);
189992    if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
189993     || sqlite3_value_bytes(apArg[0])<2
189994    ){
189995      sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
189996    }else{
189997      u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
189998      sqlite3_result_int(ctx, readInt16(zBlob));
189999    }
190000  }
190001  
190002  /*
190003  ** Context object passed between the various routines that make up the
190004  ** implementation of integrity-check function rtreecheck().
190005  */
190006  typedef struct RtreeCheck RtreeCheck;
190007  struct RtreeCheck {
190008    sqlite3 *db;                    /* Database handle */
190009    const char *zDb;                /* Database containing rtree table */
190010    const char *zTab;               /* Name of rtree table */
190011    int bInt;                       /* True for rtree_i32 table */
190012    int nDim;                       /* Number of dimensions for this rtree tbl */
190013    sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */
190014    sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
190015    int nLeaf;                      /* Number of leaf cells in table */
190016    int nNonLeaf;                   /* Number of non-leaf cells in table */
190017    int rc;                         /* Return code */
190018    char *zReport;                  /* Message to report */
190019    int nErr;                       /* Number of lines in zReport */
190020  };
190021  
190022  #define RTREE_CHECK_MAX_ERROR 100
190023  
190024  /*
190025  ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
190026  ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
190027  */
190028  static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
190029    int rc = sqlite3_reset(pStmt);
190030    if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
190031  }
190032  
190033  /*
190034  ** The second and subsequent arguments to this function are a format string
190035  ** and printf style arguments. This function formats the string and attempts
190036  ** to compile it as an SQL statement.
190037  **
190038  ** If successful, a pointer to the new SQL statement is returned. Otherwise,
190039  ** NULL is returned and an error code left in RtreeCheck.rc.
190040  */
190041  static sqlite3_stmt *rtreeCheckPrepare(
190042    RtreeCheck *pCheck,             /* RtreeCheck object */
190043    const char *zFmt, ...           /* Format string and trailing args */
190044  ){
190045    va_list ap;
190046    char *z;
190047    sqlite3_stmt *pRet = 0;
190048  
190049    va_start(ap, zFmt);
190050    z = sqlite3_vmprintf(zFmt, ap);
190051  
190052    if( pCheck->rc==SQLITE_OK ){
190053      if( z==0 ){
190054        pCheck->rc = SQLITE_NOMEM;
190055      }else{
190056        pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
190057      }
190058    }
190059  
190060    sqlite3_free(z);
190061    va_end(ap);
190062    return pRet;
190063  }
190064  
190065  /*
190066  ** The second and subsequent arguments to this function are a printf()
190067  ** style format string and arguments. This function formats the string and
190068  ** appends it to the report being accumuated in pCheck.
190069  */
190070  static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
190071    va_list ap;
190072    va_start(ap, zFmt);
190073    if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
190074      char *z = sqlite3_vmprintf(zFmt, ap);
190075      if( z==0 ){
190076        pCheck->rc = SQLITE_NOMEM;
190077      }else{
190078        pCheck->zReport = sqlite3_mprintf("%z%s%z", 
190079            pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
190080        );
190081        if( pCheck->zReport==0 ){
190082          pCheck->rc = SQLITE_NOMEM;
190083        }
190084      }
190085      pCheck->nErr++;
190086    }
190087    va_end(ap);
190088  }
190089  
190090  /*
190091  ** This function is a no-op if there is already an error code stored
190092  ** in the RtreeCheck object indicated by the first argument. NULL is
190093  ** returned in this case.
190094  **
190095  ** Otherwise, the contents of rtree table node iNode are loaded from
190096  ** the database and copied into a buffer obtained from sqlite3_malloc().
190097  ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
190098  ** is set to the size of the buffer in bytes.
190099  **
190100  ** Or, if an error does occur, NULL is returned and an error code left
190101  ** in the RtreeCheck object. The final value of *pnNode is undefined in
190102  ** this case.
190103  */
190104  static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
190105    u8 *pRet = 0;                   /* Return value */
190106  
190107    if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
190108      pCheck->pGetNode = rtreeCheckPrepare(pCheck,
190109          "SELECT data FROM %Q.'%q_node' WHERE nodeno=?", 
190110          pCheck->zDb, pCheck->zTab
190111      );
190112    }
190113  
190114    if( pCheck->rc==SQLITE_OK ){
190115      sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
190116      if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
190117        int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
190118        const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
190119        pRet = sqlite3_malloc64(nNode);
190120        if( pRet==0 ){
190121          pCheck->rc = SQLITE_NOMEM;
190122        }else{
190123          memcpy(pRet, pNode, nNode);
190124          *pnNode = nNode;
190125        }
190126      }
190127      rtreeCheckReset(pCheck, pCheck->pGetNode);
190128      if( pCheck->rc==SQLITE_OK && pRet==0 ){
190129        rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
190130      }
190131    }
190132  
190133    return pRet;
190134  }
190135  
190136  /*
190137  ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
190138  ** (if bLeaf==1) table contains a specified entry. The schemas of the
190139  ** two tables are:
190140  **
190141  **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
190142  **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
190143  **
190144  ** In both cases, this function checks that there exists an entry with
190145  ** IPK value iKey and the second column set to iVal.
190146  **
190147  */
190148  static void rtreeCheckMapping(
190149    RtreeCheck *pCheck,             /* RtreeCheck object */
190150    int bLeaf,                      /* True for a leaf cell, false for interior */
190151    i64 iKey,                       /* Key for mapping */
190152    i64 iVal                        /* Expected value for mapping */
190153  ){
190154    int rc;
190155    sqlite3_stmt *pStmt;
190156    const char *azSql[2] = {
190157      "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
190158      "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
190159    };
190160  
190161    assert( bLeaf==0 || bLeaf==1 );
190162    if( pCheck->aCheckMapping[bLeaf]==0 ){
190163      pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
190164          azSql[bLeaf], pCheck->zDb, pCheck->zTab
190165      );
190166    }
190167    if( pCheck->rc!=SQLITE_OK ) return;
190168  
190169    pStmt = pCheck->aCheckMapping[bLeaf];
190170    sqlite3_bind_int64(pStmt, 1, iKey);
190171    rc = sqlite3_step(pStmt);
190172    if( rc==SQLITE_DONE ){
190173      rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
190174          iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
190175      );
190176    }else if( rc==SQLITE_ROW ){
190177      i64 ii = sqlite3_column_int64(pStmt, 0);
190178      if( ii!=iVal ){
190179        rtreeCheckAppendMsg(pCheck, 
190180            "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
190181            iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
190182        );
190183      }
190184    }
190185    rtreeCheckReset(pCheck, pStmt);
190186  }
190187  
190188  /*
190189  ** Argument pCell points to an array of coordinates stored on an rtree page.
190190  ** This function checks that the coordinates are internally consistent (no
190191  ** x1>x2 conditions) and adds an error message to the RtreeCheck object
190192  ** if they are not.
190193  **
190194  ** Additionally, if pParent is not NULL, then it is assumed to point to
190195  ** the array of coordinates on the parent page that bound the page 
190196  ** containing pCell. In this case it is also verified that the two
190197  ** sets of coordinates are mutually consistent and an error message added
190198  ** to the RtreeCheck object if they are not.
190199  */
190200  static void rtreeCheckCellCoord(
190201    RtreeCheck *pCheck, 
190202    i64 iNode,                      /* Node id to use in error messages */
190203    int iCell,                      /* Cell number to use in error messages */
190204    u8 *pCell,                      /* Pointer to cell coordinates */
190205    u8 *pParent                     /* Pointer to parent coordinates */
190206  ){
190207    RtreeCoord c1, c2;
190208    RtreeCoord p1, p2;
190209    int i;
190210  
190211    for(i=0; i<pCheck->nDim; i++){
190212      readCoord(&pCell[4*2*i], &c1);
190213      readCoord(&pCell[4*(2*i + 1)], &c2);
190214  
190215      /* printf("%e, %e\n", c1.u.f, c2.u.f); */
190216      if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
190217        rtreeCheckAppendMsg(pCheck, 
190218            "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
190219        );
190220      }
190221  
190222      if( pParent ){
190223        readCoord(&pParent[4*2*i], &p1);
190224        readCoord(&pParent[4*(2*i + 1)], &p2);
190225  
190226        if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f) 
190227         || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
190228        ){
190229          rtreeCheckAppendMsg(pCheck, 
190230              "Dimension %d of cell %d on node %lld is corrupt relative to parent"
190231              , i, iCell, iNode
190232          );
190233        }
190234      }
190235    }
190236  }
190237  
190238  /*
190239  ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
190240  ** the r-tree structure. Argument aParent points to the array of coordinates
190241  ** that bound node iNode on the parent node.
190242  **
190243  ** If any problems are discovered, an error message is appended to the
190244  ** report accumulated in the RtreeCheck object.
190245  */
190246  static void rtreeCheckNode(
190247    RtreeCheck *pCheck,
190248    int iDepth,                     /* Depth of iNode (0==leaf) */
190249    u8 *aParent,                    /* Buffer containing parent coords */
190250    i64 iNode                       /* Node to check */
190251  ){
190252    u8 *aNode = 0;
190253    int nNode = 0;
190254  
190255    assert( iNode==1 || aParent!=0 );
190256    assert( pCheck->nDim>0 );
190257  
190258    aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
190259    if( aNode ){
190260      if( nNode<4 ){
190261        rtreeCheckAppendMsg(pCheck, 
190262            "Node %lld is too small (%d bytes)", iNode, nNode
190263        );
190264      }else{
190265        int nCell;                  /* Number of cells on page */
190266        int i;                      /* Used to iterate through cells */
190267        if( aParent==0 ){
190268          iDepth = readInt16(aNode);
190269          if( iDepth>RTREE_MAX_DEPTH ){
190270            rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
190271            sqlite3_free(aNode);
190272            return;
190273          }
190274        }
190275        nCell = readInt16(&aNode[2]);
190276        if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
190277          rtreeCheckAppendMsg(pCheck, 
190278              "Node %lld is too small for cell count of %d (%d bytes)", 
190279              iNode, nCell, nNode
190280          );
190281        }else{
190282          for(i=0; i<nCell; i++){
190283            u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
190284            i64 iVal = readInt64(pCell);
190285            rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
190286  
190287            if( iDepth>0 ){
190288              rtreeCheckMapping(pCheck, 0, iVal, iNode);
190289              rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
190290              pCheck->nNonLeaf++;
190291            }else{
190292              rtreeCheckMapping(pCheck, 1, iVal, iNode);
190293              pCheck->nLeaf++;
190294            }
190295          }
190296        }
190297      }
190298      sqlite3_free(aNode);
190299    }
190300  }
190301  
190302  /*
190303  ** The second argument to this function must be either "_rowid" or
190304  ** "_parent". This function checks that the number of entries in the
190305  ** %_rowid or %_parent table is exactly nExpect. If not, it adds
190306  ** an error message to the report in the RtreeCheck object indicated
190307  ** by the first argument.
190308  */
190309  static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
190310    if( pCheck->rc==SQLITE_OK ){
190311      sqlite3_stmt *pCount;
190312      pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
190313          pCheck->zDb, pCheck->zTab, zTbl
190314      );
190315      if( pCount ){
190316        if( sqlite3_step(pCount)==SQLITE_ROW ){
190317          i64 nActual = sqlite3_column_int64(pCount, 0);
190318          if( nActual!=nExpect ){
190319            rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
190320                " - expected %lld, actual %lld" , zTbl, nExpect, nActual
190321            );
190322          }
190323        }
190324        pCheck->rc = sqlite3_finalize(pCount);
190325      }
190326    }
190327  }
190328  
190329  /*
190330  ** This function does the bulk of the work for the rtree integrity-check.
190331  ** It is called by rtreecheck(), which is the SQL function implementation.
190332  */
190333  static int rtreeCheckTable(
190334    sqlite3 *db,                    /* Database handle to access db through */
190335    const char *zDb,                /* Name of db ("main", "temp" etc.) */
190336    const char *zTab,               /* Name of rtree table to check */
190337    char **pzReport                 /* OUT: sqlite3_malloc'd report text */
190338  ){
190339    RtreeCheck check;               /* Common context for various routines */
190340    sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
190341    int bEnd = 0;                   /* True if transaction should be closed */
190342    int nAux = 0;                   /* Number of extra columns. */
190343  
190344    /* Initialize the context object */
190345    memset(&check, 0, sizeof(check));
190346    check.db = db;
190347    check.zDb = zDb;
190348    check.zTab = zTab;
190349  
190350    /* If there is not already an open transaction, open one now. This is
190351    ** to ensure that the queries run as part of this integrity-check operate
190352    ** on a consistent snapshot.  */
190353    if( sqlite3_get_autocommit(db) ){
190354      check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
190355      bEnd = 1;
190356    }
190357  
190358    /* Find the number of auxiliary columns */
190359    if( check.rc==SQLITE_OK ){
190360      pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
190361      if( pStmt ){
190362        nAux = sqlite3_column_count(pStmt) - 2;
190363        sqlite3_finalize(pStmt);
190364      }
190365      check.rc = SQLITE_OK;
190366    }
190367  
190368    /* Find number of dimensions in the rtree table. */
190369    pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
190370    if( pStmt ){
190371      int rc;
190372      check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
190373      if( check.nDim<1 ){
190374        rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
190375      }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
190376        check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
190377      }
190378      rc = sqlite3_finalize(pStmt);
190379      if( rc!=SQLITE_CORRUPT ) check.rc = rc;
190380    }
190381  
190382    /* Do the actual integrity-check */
190383    if( check.nDim>=1 ){
190384      if( check.rc==SQLITE_OK ){
190385        rtreeCheckNode(&check, 0, 0, 1);
190386      }
190387      rtreeCheckCount(&check, "_rowid", check.nLeaf);
190388      rtreeCheckCount(&check, "_parent", check.nNonLeaf);
190389    }
190390  
190391    /* Finalize SQL statements used by the integrity-check */
190392    sqlite3_finalize(check.pGetNode);
190393    sqlite3_finalize(check.aCheckMapping[0]);
190394    sqlite3_finalize(check.aCheckMapping[1]);
190395  
190396    /* If one was opened, close the transaction */
190397    if( bEnd ){
190398      int rc = sqlite3_exec(db, "END", 0, 0, 0);
190399      if( check.rc==SQLITE_OK ) check.rc = rc;
190400    }
190401    *pzReport = check.zReport;
190402    return check.rc;
190403  }
190404  
190405  /*
190406  ** Usage:
190407  **
190408  **   rtreecheck(<rtree-table>);
190409  **   rtreecheck(<database>, <rtree-table>);
190410  **
190411  ** Invoking this SQL function runs an integrity-check on the named rtree
190412  ** table. The integrity-check verifies the following:
190413  **
190414  **   1. For each cell in the r-tree structure (%_node table), that:
190415  **
190416  **       a) for each dimension, (coord1 <= coord2).
190417  **
190418  **       b) unless the cell is on the root node, that the cell is bounded
190419  **          by the parent cell on the parent node.
190420  **
190421  **       c) for leaf nodes, that there is an entry in the %_rowid 
190422  **          table corresponding to the cell's rowid value that 
190423  **          points to the correct node.
190424  **
190425  **       d) for cells on non-leaf nodes, that there is an entry in the 
190426  **          %_parent table mapping from the cell's child node to the
190427  **          node that it resides on.
190428  **
190429  **   2. That there are the same number of entries in the %_rowid table
190430  **      as there are leaf cells in the r-tree structure, and that there
190431  **      is a leaf cell that corresponds to each entry in the %_rowid table.
190432  **
190433  **   3. That there are the same number of entries in the %_parent table
190434  **      as there are non-leaf cells in the r-tree structure, and that 
190435  **      there is a non-leaf cell that corresponds to each entry in the 
190436  **      %_parent table.
190437  */
190438  static void rtreecheck(
190439    sqlite3_context *ctx, 
190440    int nArg, 
190441    sqlite3_value **apArg
190442  ){
190443    if( nArg!=1 && nArg!=2 ){
190444      sqlite3_result_error(ctx, 
190445          "wrong number of arguments to function rtreecheck()", -1
190446      );
190447    }else{
190448      int rc;
190449      char *zReport = 0;
190450      const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
190451      const char *zTab;
190452      if( nArg==1 ){
190453        zTab = zDb;
190454        zDb = "main";
190455      }else{
190456        zTab = (const char*)sqlite3_value_text(apArg[1]);
190457      }
190458      rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
190459      if( rc==SQLITE_OK ){
190460        sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
190461      }else{
190462        sqlite3_result_error_code(ctx, rc);
190463      }
190464      sqlite3_free(zReport);
190465    }
190466  }
190467  
190468  /* Conditionally include the geopoly code */
190469  #ifdef SQLITE_ENABLE_GEOPOLY
190470  /************** Include geopoly.c in the middle of rtree.c *******************/
190471  /************** Begin file geopoly.c *****************************************/
190472  /*
190473  ** 2018-05-25
190474  **
190475  ** The author disclaims copyright to this source code.  In place of
190476  ** a legal notice, here is a blessing:
190477  **
190478  **    May you do good and not evil.
190479  **    May you find forgiveness for yourself and forgive others.
190480  **    May you share freely, never taking more than you give.
190481  **
190482  ******************************************************************************
190483  **
190484  ** This file implements an alternative R-Tree virtual table that
190485  ** uses polygons to express the boundaries of 2-dimensional objects.
190486  **
190487  ** This file is #include-ed onto the end of "rtree.c" so that it has
190488  ** access to all of the R-Tree internals.
190489  */
190490  /* #include <stdlib.h> */
190491  
190492  /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
190493  #ifdef GEOPOLY_ENABLE_DEBUG
190494    static int geo_debug = 0;
190495  # define GEODEBUG(X) if(geo_debug)printf X
190496  #else
190497  # define GEODEBUG(X)
190498  #endif
190499  
190500  #ifndef JSON_NULL   /* The following stuff repeats things found in json1 */
190501  /*
190502  ** Versions of isspace(), isalnum() and isdigit() to which it is safe
190503  ** to pass signed char values.
190504  */
190505  #ifdef sqlite3Isdigit
190506     /* Use the SQLite core versions if this routine is part of the
190507     ** SQLite amalgamation */
190508  #  define safe_isdigit(x)  sqlite3Isdigit(x)
190509  #  define safe_isalnum(x)  sqlite3Isalnum(x)
190510  #  define safe_isxdigit(x) sqlite3Isxdigit(x)
190511  #else
190512     /* Use the standard library for separate compilation */
190513  #include <ctype.h>  /* amalgamator: keep */
190514  #  define safe_isdigit(x)  isdigit((unsigned char)(x))
190515  #  define safe_isalnum(x)  isalnum((unsigned char)(x))
190516  #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
190517  #endif
190518  
190519  /*
190520  ** Growing our own isspace() routine this way is twice as fast as
190521  ** the library isspace() function.
190522  */
190523  static const char geopolyIsSpace[] = {
190524    0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
190525    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190526    1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190527    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190528    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190529    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190530    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190531    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190532    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190533    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190534    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190535    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190536    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190537    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190538    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190539    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
190540  };
190541  #define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
190542  #endif /* JSON NULL - back to original code */
190543  
190544  /* Compiler and version */
190545  #ifndef GCC_VERSION
190546  #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
190547  # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
190548  #else
190549  # define GCC_VERSION 0
190550  #endif
190551  #endif
190552  #ifndef MSVC_VERSION
190553  #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
190554  # define MSVC_VERSION _MSC_VER
190555  #else
190556  # define MSVC_VERSION 0
190557  #endif
190558  #endif
190559  
190560  /* Datatype for coordinates
190561  */
190562  typedef float GeoCoord;
190563  
190564  /*
190565  ** Internal representation of a polygon.
190566  **
190567  ** The polygon consists of a sequence of vertexes.  There is a line
190568  ** segment between each pair of vertexes, and one final segment from
190569  ** the last vertex back to the first.  (This differs from the GeoJSON
190570  ** standard in which the final vertex is a repeat of the first.)
190571  **
190572  ** The polygon follows the right-hand rule.  The area to the right of
190573  ** each segment is "outside" and the area to the left is "inside".
190574  **
190575  ** The on-disk representation consists of a 4-byte header followed by
190576  ** the values.  The 4-byte header is:
190577  **
190578  **      encoding    (1 byte)   0=big-endian, 1=little-endian
190579  **      nvertex     (3 bytes)  Number of vertexes as a big-endian integer
190580  **
190581  ** Enough space is allocated for 4 coordinates, to work around over-zealous
190582  ** warnings coming from some compiler (notably, clang). In reality, the size
190583  ** of each GeoPoly memory allocate is adjusted as necessary so that the
190584  ** GeoPoly.a[] array at the end is the appropriate size.
190585  */
190586  typedef struct GeoPoly GeoPoly;
190587  struct GeoPoly {
190588    int nVertex;          /* Number of vertexes */
190589    unsigned char hdr[4]; /* Header for on-disk representation */
190590    GeoCoord a[8];        /* 2*nVertex values. X (longitude) first, then Y */
190591  };
190592  
190593  /* The size of a memory allocation needed for a GeoPoly object sufficient
190594  ** to hold N coordinate pairs.
190595  */
190596  #define GEOPOLY_SZ(N)  (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
190597  
190598  /* Macros to access coordinates of a GeoPoly.
190599  ** We have to use these macros, rather than just say p->a[i] in order
190600  ** to silence (incorrect) UBSAN warnings if the array index is too large.
190601  */
190602  #define GeoX(P,I)  (((GeoCoord*)(P)->a)[(I)*2])
190603  #define GeoY(P,I)  (((GeoCoord*)(P)->a)[(I)*2+1])
190604  
190605  
190606  /*
190607  ** State of a parse of a GeoJSON input.
190608  */
190609  typedef struct GeoParse GeoParse;
190610  struct GeoParse {
190611    const unsigned char *z;   /* Unparsed input */
190612    int nVertex;              /* Number of vertexes in a[] */
190613    int nAlloc;               /* Space allocated to a[] */
190614    int nErr;                 /* Number of errors encountered */
190615    GeoCoord *a;          /* Array of vertexes.  From sqlite3_malloc64() */
190616  };
190617  
190618  /* Do a 4-byte byte swap */
190619  static void geopolySwab32(unsigned char *a){
190620    unsigned char t = a[0];
190621    a[0] = a[3];
190622    a[3] = t;
190623    t = a[1];
190624    a[1] = a[2];
190625    a[2] = t;
190626  }
190627  
190628  /* Skip whitespace.  Return the next non-whitespace character. */
190629  static char geopolySkipSpace(GeoParse *p){
190630    while( safe_isspace(p->z[0]) ) p->z++;
190631    return p->z[0];
190632  }
190633  
190634  /* Parse out a number.  Write the value into *pVal if pVal!=0.
190635  ** return non-zero on success and zero if the next token is not a number.
190636  */
190637  static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
190638    char c = geopolySkipSpace(p);
190639    const unsigned char *z = p->z;
190640    int j = 0;
190641    int seenDP = 0;
190642    int seenE = 0;
190643    if( c=='-' ){
190644      j = 1;
190645      c = z[j];
190646    }
190647    if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
190648    for(;; j++){
190649      c = z[j];
190650      if( safe_isdigit(c) ) continue;
190651      if( c=='.' ){
190652        if( z[j-1]=='-' ) return 0;
190653        if( seenDP ) return 0;
190654        seenDP = 1;
190655        continue;
190656      }
190657      if( c=='e' || c=='E' ){
190658        if( z[j-1]<'0' ) return 0;
190659        if( seenE ) return -1;
190660        seenDP = seenE = 1;
190661        c = z[j+1];
190662        if( c=='+' || c=='-' ){
190663          j++;
190664          c = z[j+1];
190665        }
190666        if( c<'0' || c>'9' ) return 0;
190667        continue;
190668      }
190669      break;
190670    }
190671    if( z[j-1]<'0' ) return 0;
190672    if( pVal ){
190673  #ifdef SQLITE_AMALGAMATION
190674       /* The sqlite3AtoF() routine is much much faster than atof(), if it
190675       ** is available */
190676       double r;
190677       (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
190678       *pVal = r;
190679  #else
190680       *pVal = (GeoCoord)atof((const char*)p->z);
190681  #endif
190682    }
190683    p->z += j;
190684    return 1;
190685  }
190686  
190687  /*
190688  ** If the input is a well-formed JSON array of coordinates with at least
190689  ** four coordinates and where each coordinate is itself a two-value array,
190690  ** then convert the JSON into a GeoPoly object and return a pointer to
190691  ** that object.
190692  **
190693  ** If any error occurs, return NULL.
190694  */
190695  static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
190696    GeoParse s;
190697    int rc = SQLITE_OK;
190698    memset(&s, 0, sizeof(s));
190699    s.z = z;
190700    if( geopolySkipSpace(&s)=='[' ){
190701      s.z++;
190702      while( geopolySkipSpace(&s)=='[' ){
190703        int ii = 0;
190704        char c;
190705        s.z++;
190706        if( s.nVertex>=s.nAlloc ){
190707          GeoCoord *aNew;
190708          s.nAlloc = s.nAlloc*2 + 16;
190709          aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
190710          if( aNew==0 ){
190711            rc = SQLITE_NOMEM;
190712            s.nErr++;
190713            break;
190714          }
190715          s.a = aNew;
190716        }
190717        while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
190718          ii++;
190719          if( ii==2 ) s.nVertex++;
190720          c = geopolySkipSpace(&s);
190721          s.z++;
190722          if( c==',' ) continue;
190723          if( c==']' && ii>=2 ) break;
190724          s.nErr++;
190725          rc = SQLITE_ERROR;
190726          goto parse_json_err;
190727        }
190728        if( geopolySkipSpace(&s)==',' ){
190729          s.z++;
190730          continue;
190731        }
190732        break;
190733      }
190734      if( geopolySkipSpace(&s)==']'
190735       && s.nVertex>=4
190736       && s.a[0]==s.a[s.nVertex*2-2]
190737       && s.a[1]==s.a[s.nVertex*2-1]
190738       && (s.z++, geopolySkipSpace(&s)==0)
190739      ){
190740        GeoPoly *pOut;
190741        int x = 1;
190742        s.nVertex--;  /* Remove the redundant vertex at the end */
190743        pOut = sqlite3_malloc64( GEOPOLY_SZ(s.nVertex) );
190744        x = 1;
190745        if( pOut==0 ) goto parse_json_err;
190746        pOut->nVertex = s.nVertex;
190747        memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
190748        pOut->hdr[0] = *(unsigned char*)&x;
190749        pOut->hdr[1] = (s.nVertex>>16)&0xff;
190750        pOut->hdr[2] = (s.nVertex>>8)&0xff;
190751        pOut->hdr[3] = s.nVertex&0xff;
190752        sqlite3_free(s.a);
190753        if( pRc ) *pRc = SQLITE_OK;
190754        return pOut;
190755      }else{
190756        s.nErr++;
190757        rc = SQLITE_ERROR;
190758      }
190759    }
190760  parse_json_err:
190761    if( pRc ) *pRc = rc;
190762    sqlite3_free(s.a);
190763    return 0;
190764  }
190765  
190766  /*
190767  ** Given a function parameter, try to interpret it as a polygon, either
190768  ** in the binary format or JSON text.  Compute a GeoPoly object and
190769  ** return a pointer to that object.  Or if the input is not a well-formed
190770  ** polygon, put an error message in sqlite3_context and return NULL.
190771  */
190772  static GeoPoly *geopolyFuncParam(
190773    sqlite3_context *pCtx,      /* Context for error messages */
190774    sqlite3_value *pVal,        /* The value to decode */
190775    int *pRc                    /* Write error here */
190776  ){
190777    GeoPoly *p = 0;
190778    int nByte;
190779    if( sqlite3_value_type(pVal)==SQLITE_BLOB
190780     && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
190781    ){
190782      const unsigned char *a = sqlite3_value_blob(pVal);
190783      int nVertex;
190784      nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
190785      if( (a[0]==0 || a[0]==1)
190786       && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
190787      ){
190788        p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
190789        if( p==0 ){
190790          if( pRc ) *pRc = SQLITE_NOMEM;
190791          if( pCtx ) sqlite3_result_error_nomem(pCtx);
190792        }else{
190793          int x = 1;
190794          p->nVertex = nVertex;
190795          memcpy(p->hdr, a, nByte);
190796          if( a[0] != *(unsigned char*)&x ){
190797            int ii;
190798            for(ii=0; ii<nVertex; ii++){
190799              geopolySwab32((unsigned char*)&GeoX(p,ii));
190800              geopolySwab32((unsigned char*)&GeoY(p,ii));
190801            }
190802            p->hdr[0] ^= 1;
190803          }
190804        }
190805      }
190806      if( pRc ) *pRc = SQLITE_OK;
190807      return p;
190808    }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
190809      const unsigned char *zJson = sqlite3_value_text(pVal);
190810      if( zJson==0 ){
190811        if( pRc ) *pRc = SQLITE_NOMEM;
190812        return 0;
190813      }
190814      return geopolyParseJson(zJson, pRc);
190815    }else{
190816      if( pRc ) *pRc = SQLITE_ERROR;
190817      return 0;
190818    }
190819  }
190820  
190821  /*
190822  ** Implementation of the geopoly_blob(X) function.
190823  **
190824  ** If the input is a well-formed Geopoly BLOB or JSON string
190825  ** then return the BLOB representation of the polygon.  Otherwise
190826  ** return NULL.
190827  */
190828  static void geopolyBlobFunc(
190829    sqlite3_context *context,
190830    int argc,
190831    sqlite3_value **argv
190832  ){
190833    GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
190834    if( p ){
190835      sqlite3_result_blob(context, p->hdr, 
190836         4+8*p->nVertex, SQLITE_TRANSIENT);
190837      sqlite3_free(p);
190838    }
190839  }
190840  
190841  /*
190842  ** SQL function:     geopoly_json(X)
190843  **
190844  ** Interpret X as a polygon and render it as a JSON array
190845  ** of coordinates.  Or, if X is not a valid polygon, return NULL.
190846  */
190847  static void geopolyJsonFunc(
190848    sqlite3_context *context,
190849    int argc,
190850    sqlite3_value **argv
190851  ){
190852    GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
190853    if( p ){
190854      sqlite3 *db = sqlite3_context_db_handle(context);
190855      sqlite3_str *x = sqlite3_str_new(db);
190856      int i;
190857      sqlite3_str_append(x, "[", 1);
190858      for(i=0; i<p->nVertex; i++){
190859        sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
190860      }
190861      sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
190862      sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
190863      sqlite3_free(p);
190864    }
190865  }
190866  
190867  /*
190868  ** SQL function:     geopoly_svg(X, ....)
190869  **
190870  ** Interpret X as a polygon and render it as a SVG <polyline>.
190871  ** Additional arguments are added as attributes to the <polyline>.
190872  */
190873  static void geopolySvgFunc(
190874    sqlite3_context *context,
190875    int argc,
190876    sqlite3_value **argv
190877  ){
190878    GeoPoly *p;
190879    if( argc<1 ) return;
190880    p = geopolyFuncParam(context, argv[0], 0);
190881    if( p ){
190882      sqlite3 *db = sqlite3_context_db_handle(context);
190883      sqlite3_str *x = sqlite3_str_new(db);
190884      int i;
190885      char cSep = '\'';
190886      sqlite3_str_appendf(x, "<polyline points=");
190887      for(i=0; i<p->nVertex; i++){
190888        sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
190889        cSep = ' ';
190890      }
190891      sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
190892      for(i=1; i<argc; i++){
190893        const char *z = (const char*)sqlite3_value_text(argv[i]);
190894        if( z && z[0] ){
190895          sqlite3_str_appendf(x, " %s", z);
190896        }
190897      }
190898      sqlite3_str_appendf(x, "></polyline>");
190899      sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
190900      sqlite3_free(p);
190901    }
190902  }
190903  
190904  /*
190905  ** SQL Function:      geopoly_xform(poly, A, B, C, D, E, F)
190906  **
190907  ** Transform and/or translate a polygon as follows:
190908  **
190909  **      x1 = A*x0 + B*y0 + E
190910  **      y1 = C*x0 + D*y0 + F
190911  **
190912  ** For a translation:
190913  **
190914  **      geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
190915  **
190916  ** Rotate by R around the point (0,0):
190917  **
190918  **      geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
190919  */
190920  static void geopolyXformFunc(
190921    sqlite3_context *context,
190922    int argc,
190923    sqlite3_value **argv
190924  ){
190925    GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
190926    double A = sqlite3_value_double(argv[1]);
190927    double B = sqlite3_value_double(argv[2]);
190928    double C = sqlite3_value_double(argv[3]);
190929    double D = sqlite3_value_double(argv[4]);
190930    double E = sqlite3_value_double(argv[5]);
190931    double F = sqlite3_value_double(argv[6]);
190932    GeoCoord x1, y1, x0, y0;
190933    int ii;
190934    if( p ){
190935      for(ii=0; ii<p->nVertex; ii++){
190936        x0 = GeoX(p,ii);
190937        y0 = GeoY(p,ii);
190938        x1 = (GeoCoord)(A*x0 + B*y0 + E);
190939        y1 = (GeoCoord)(C*x0 + D*y0 + F);
190940        GeoX(p,ii) = x1;
190941        GeoY(p,ii) = y1;
190942      }
190943      sqlite3_result_blob(context, p->hdr, 
190944         4+8*p->nVertex, SQLITE_TRANSIENT);
190945      sqlite3_free(p);
190946    }
190947  }
190948  
190949  /*
190950  ** Compute the area enclosed by the polygon.
190951  **
190952  ** This routine can also be used to detect polygons that rotate in
190953  ** the wrong direction.  Polygons are suppose to be counter-clockwise (CCW).
190954  ** This routine returns a negative value for clockwise (CW) polygons.
190955  */
190956  static double geopolyArea(GeoPoly *p){
190957    double rArea = 0.0;
190958    int ii;
190959    for(ii=0; ii<p->nVertex-1; ii++){
190960      rArea += (GeoX(p,ii) - GeoX(p,ii+1))           /* (x0 - x1) */
190961                * (GeoY(p,ii) + GeoY(p,ii+1))        /* (y0 + y1) */
190962                * 0.5;
190963    }
190964    rArea += (GeoX(p,ii) - GeoX(p,0))                /* (xN - x0) */
190965             * (GeoY(p,ii) + GeoY(p,0))              /* (yN + y0) */
190966             * 0.5;
190967    return rArea;
190968  }
190969  
190970  /*
190971  ** Implementation of the geopoly_area(X) function.
190972  **
190973  ** If the input is a well-formed Geopoly BLOB then return the area
190974  ** enclosed by the polygon.  If the polygon circulates clockwise instead
190975  ** of counterclockwise (as it should) then return the negative of the
190976  ** enclosed area.  Otherwise return NULL.
190977  */
190978  static void geopolyAreaFunc(
190979    sqlite3_context *context,
190980    int argc,
190981    sqlite3_value **argv
190982  ){
190983    GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
190984    if( p ){
190985      sqlite3_result_double(context, geopolyArea(p));
190986      sqlite3_free(p);
190987    }            
190988  }
190989  
190990  /*
190991  ** Implementation of the geopoly_ccw(X) function.
190992  **
190993  ** If the rotation of polygon X is clockwise (incorrect) instead of
190994  ** counter-clockwise (the correct winding order according to RFC7946)
190995  ** then reverse the order of the vertexes in polygon X.  
190996  **
190997  ** In other words, this routine returns a CCW polygon regardless of the
190998  ** winding order of its input.
190999  **
191000  ** Use this routine to sanitize historical inputs that that sometimes
191001  ** contain polygons that wind in the wrong direction.
191002  */
191003  static void geopolyCcwFunc(
191004    sqlite3_context *context,
191005    int argc,
191006    sqlite3_value **argv
191007  ){
191008    GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
191009    if( p ){
191010      if( geopolyArea(p)<0.0 ){
191011        int ii, jj;
191012        for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
191013          GeoCoord t = GeoX(p,ii);
191014          GeoX(p,ii) = GeoX(p,jj);
191015          GeoX(p,jj) = t;
191016          t = GeoY(p,ii);
191017          GeoY(p,ii) = GeoY(p,jj);
191018          GeoY(p,jj) = t;
191019        }
191020      }
191021      sqlite3_result_blob(context, p->hdr, 
191022         4+8*p->nVertex, SQLITE_TRANSIENT);
191023      sqlite3_free(p);
191024    }            
191025  }
191026  
191027  #define GEOPOLY_PI 3.1415926535897932385
191028  
191029  /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
191030  */
191031  static double geopolySine(double r){
191032    assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
191033    if( r>=1.5*GEOPOLY_PI ){
191034      r -= 2.0*GEOPOLY_PI;
191035    }
191036    if( r>=0.5*GEOPOLY_PI ){
191037      return -geopolySine(r-GEOPOLY_PI);
191038    }else{
191039      double r2 = r*r;
191040      double r3 = r2*r;
191041      double r5 = r3*r2;
191042      return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
191043    }
191044  }
191045  
191046  /*
191047  ** Function:   geopoly_regular(X,Y,R,N)
191048  **
191049  ** Construct a simple, convex, regular polygon centered at X, Y
191050  ** with circumradius R and with N sides.
191051  */
191052  static void geopolyRegularFunc(
191053    sqlite3_context *context,
191054    int argc,
191055    sqlite3_value **argv
191056  ){
191057    double x = sqlite3_value_double(argv[0]);
191058    double y = sqlite3_value_double(argv[1]);
191059    double r = sqlite3_value_double(argv[2]);
191060    int n = sqlite3_value_int(argv[3]);
191061    int i;
191062    GeoPoly *p;
191063  
191064    if( n<3 || r<=0.0 ) return;
191065    if( n>1000 ) n = 1000;
191066    p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
191067    if( p==0 ){
191068      sqlite3_result_error_nomem(context);
191069      return;
191070    }
191071    i = 1;
191072    p->hdr[0] = *(unsigned char*)&i;
191073    p->hdr[1] = 0;
191074    p->hdr[2] = (n>>8)&0xff;
191075    p->hdr[3] = n&0xff;
191076    for(i=0; i<n; i++){
191077      double rAngle = 2.0*GEOPOLY_PI*i/n;
191078      GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
191079      GeoY(p,i) = y + r*geopolySine(rAngle);
191080    }
191081    sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
191082    sqlite3_free(p);
191083  }
191084  
191085  /*
191086  ** If pPoly is a polygon, compute its bounding box. Then:
191087  **
191088  **    (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
191089  **    (2) otherwise, compute a GeoPoly for the bounding box and return the
191090  **        new GeoPoly
191091  **
191092  ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
191093  ** the bounding box in aCoord and return a pointer to that GeoPoly.
191094  */
191095  static GeoPoly *geopolyBBox(
191096    sqlite3_context *context,   /* For recording the error */
191097    sqlite3_value *pPoly,       /* The polygon */
191098    RtreeCoord *aCoord,         /* Results here */
191099    int *pRc                    /* Error code here */
191100  ){
191101    GeoPoly *pOut = 0;
191102    GeoPoly *p;
191103    float mnX, mxX, mnY, mxY;
191104    if( pPoly==0 && aCoord!=0 ){
191105      p = 0;
191106      mnX = aCoord[0].f;
191107      mxX = aCoord[1].f;
191108      mnY = aCoord[2].f;
191109      mxY = aCoord[3].f;
191110      goto geopolyBboxFill;
191111    }else{
191112      p = geopolyFuncParam(context, pPoly, pRc);
191113    }
191114    if( p ){
191115      int ii;
191116      mnX = mxX = GeoX(p,0);
191117      mnY = mxY = GeoY(p,0);
191118      for(ii=1; ii<p->nVertex; ii++){
191119        double r = GeoX(p,ii);
191120        if( r<mnX ) mnX = (float)r;
191121        else if( r>mxX ) mxX = (float)r;
191122        r = GeoY(p,ii);
191123        if( r<mnY ) mnY = (float)r;
191124        else if( r>mxY ) mxY = (float)r;
191125      }
191126      if( pRc ) *pRc = SQLITE_OK;
191127      if( aCoord==0 ){
191128        geopolyBboxFill:
191129        pOut = sqlite3_realloc(p, GEOPOLY_SZ(4));
191130        if( pOut==0 ){
191131          sqlite3_free(p);
191132          if( context ) sqlite3_result_error_nomem(context);
191133          if( pRc ) *pRc = SQLITE_NOMEM;
191134          return 0;
191135        }
191136        pOut->nVertex = 4;
191137        ii = 1;
191138        pOut->hdr[0] = *(unsigned char*)&ii;
191139        pOut->hdr[1] = 0;
191140        pOut->hdr[2] = 0;
191141        pOut->hdr[3] = 4;
191142        GeoX(pOut,0) = mnX;
191143        GeoY(pOut,0) = mnY;
191144        GeoX(pOut,1) = mxX;
191145        GeoY(pOut,1) = mnY;
191146        GeoX(pOut,2) = mxX;
191147        GeoY(pOut,2) = mxY;
191148        GeoX(pOut,3) = mnX;
191149        GeoY(pOut,3) = mxY;
191150      }else{
191151        sqlite3_free(p);
191152        aCoord[0].f = mnX;
191153        aCoord[1].f = mxX;
191154        aCoord[2].f = mnY;
191155        aCoord[3].f = mxY;
191156      }
191157    }
191158    return pOut;
191159  }
191160  
191161  /*
191162  ** Implementation of the geopoly_bbox(X) SQL function.
191163  */
191164  static void geopolyBBoxFunc(
191165    sqlite3_context *context,
191166    int argc,
191167    sqlite3_value **argv
191168  ){
191169    GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
191170    if( p ){
191171      sqlite3_result_blob(context, p->hdr, 
191172         4+8*p->nVertex, SQLITE_TRANSIENT);
191173      sqlite3_free(p);
191174    }
191175  }
191176  
191177  /*
191178  ** State vector for the geopoly_group_bbox() aggregate function.
191179  */
191180  typedef struct GeoBBox GeoBBox;
191181  struct GeoBBox {
191182    int isInit;
191183    RtreeCoord a[4];
191184  };
191185  
191186  
191187  /*
191188  ** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
191189  */
191190  static void geopolyBBoxStep(
191191    sqlite3_context *context,
191192    int argc,
191193    sqlite3_value **argv
191194  ){
191195    RtreeCoord a[4];
191196    int rc = SQLITE_OK;
191197    (void)geopolyBBox(context, argv[0], a, &rc);
191198    if( rc==SQLITE_OK ){
191199      GeoBBox *pBBox;
191200      pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
191201      if( pBBox==0 ) return;
191202      if( pBBox->isInit==0 ){
191203        pBBox->isInit = 1;
191204        memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
191205      }else{
191206        if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
191207        if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
191208        if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
191209        if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
191210      }
191211    }
191212  }
191213  static void geopolyBBoxFinal(
191214    sqlite3_context *context
191215  ){
191216    GeoPoly *p;
191217    GeoBBox *pBBox;
191218    pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
191219    if( pBBox==0 ) return;
191220    p = geopolyBBox(context, 0, pBBox->a, 0);
191221    if( p ){
191222      sqlite3_result_blob(context, p->hdr, 
191223         4+8*p->nVertex, SQLITE_TRANSIENT);
191224      sqlite3_free(p);
191225    }
191226  }
191227  
191228  
191229  /*
191230  ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
191231  ** Returns:
191232  **
191233  **    +2  x0,y0 is on the line segement
191234  **
191235  **    +1  x0,y0 is beneath line segment
191236  **
191237  **    0   x0,y0 is not on or beneath the line segment or the line segment
191238  **        is vertical and x0,y0 is not on the line segment
191239  **
191240  ** The left-most coordinate min(x1,x2) is not considered to be part of
191241  ** the line segment for the purposes of this analysis.
191242  */
191243  static int pointBeneathLine(
191244    double x0, double y0,
191245    double x1, double y1,
191246    double x2, double y2
191247  ){
191248    double y;
191249    if( x0==x1 && y0==y1 ) return 2;
191250    if( x1<x2 ){
191251      if( x0<=x1 || x0>x2 ) return 0;
191252    }else if( x1>x2 ){
191253      if( x0<=x2 || x0>x1 ) return 0;
191254    }else{
191255      /* Vertical line segment */
191256      if( x0!=x1 ) return 0;
191257      if( y0<y1 && y0<y2 ) return 0;
191258      if( y0>y1 && y0>y2 ) return 0;
191259      return 2;
191260    }
191261    y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
191262    if( y0==y ) return 2;
191263    if( y0<y ) return 1;
191264    return 0;
191265  }
191266  
191267  /*
191268  ** SQL function:    geopoly_contains_point(P,X,Y)
191269  **
191270  ** Return +2 if point X,Y is within polygon P.
191271  ** Return +1 if point X,Y is on the polygon boundary.
191272  ** Return 0 if point X,Y is outside the polygon
191273  */
191274  static void geopolyContainsPointFunc(
191275    sqlite3_context *context,
191276    int argc,
191277    sqlite3_value **argv
191278  ){
191279    GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
191280    double x0 = sqlite3_value_double(argv[1]);
191281    double y0 = sqlite3_value_double(argv[2]);
191282    int v = 0;
191283    int cnt = 0;
191284    int ii;
191285    if( p1==0 ) return;
191286    for(ii=0; ii<p1->nVertex-1; ii++){
191287      v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
191288                                 GeoX(p1,ii+1),GeoY(p1,ii+1));
191289      if( v==2 ) break;
191290      cnt += v;
191291    }
191292    if( v!=2 ){
191293      v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
191294                                 GeoX(p1,0),  GeoY(p1,0));
191295    }
191296    if( v==2 ){
191297      sqlite3_result_int(context, 1);
191298    }else if( ((v+cnt)&1)==0 ){
191299      sqlite3_result_int(context, 0);
191300    }else{
191301      sqlite3_result_int(context, 2);
191302    }
191303    sqlite3_free(p1);
191304  }
191305  
191306  /* Forward declaration */
191307  static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
191308  
191309  /*
191310  ** SQL function:    geopoly_within(P1,P2)
191311  **
191312  ** Return +2 if P1 and P2 are the same polygon
191313  ** Return +1 if P2 is contained within P1
191314  ** Return 0 if any part of P2 is on the outside of P1
191315  **
191316  */
191317  static void geopolyWithinFunc(
191318    sqlite3_context *context,
191319    int argc,
191320    sqlite3_value **argv
191321  ){
191322    GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
191323    GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
191324    if( p1 && p2 ){
191325      int x = geopolyOverlap(p1, p2);
191326      if( x<0 ){
191327        sqlite3_result_error_nomem(context);
191328      }else{
191329        sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
191330      }
191331    }
191332    sqlite3_free(p1);
191333    sqlite3_free(p2);
191334  }
191335  
191336  /* Objects used by the overlap algorihm. */
191337  typedef struct GeoEvent GeoEvent;
191338  typedef struct GeoSegment GeoSegment;
191339  typedef struct GeoOverlap GeoOverlap;
191340  struct GeoEvent {
191341    double x;              /* X coordinate at which event occurs */
191342    int eType;             /* 0 for ADD, 1 for REMOVE */
191343    GeoSegment *pSeg;      /* The segment to be added or removed */
191344    GeoEvent *pNext;       /* Next event in the sorted list */
191345  };
191346  struct GeoSegment {
191347    double C, B;           /* y = C*x + B */
191348    double y;              /* Current y value */
191349    float y0;              /* Initial y value */
191350    unsigned char side;    /* 1 for p1, 2 for p2 */
191351    unsigned int idx;      /* Which segment within the side */
191352    GeoSegment *pNext;     /* Next segment in a list sorted by y */
191353  };
191354  struct GeoOverlap {
191355    GeoEvent *aEvent;          /* Array of all events */
191356    GeoSegment *aSegment;      /* Array of all segments */
191357    int nEvent;                /* Number of events */
191358    int nSegment;              /* Number of segments */
191359  };
191360  
191361  /*
191362  ** Add a single segment and its associated events.
191363  */
191364  static void geopolyAddOneSegment(
191365    GeoOverlap *p,
191366    GeoCoord x0,
191367    GeoCoord y0,
191368    GeoCoord x1,
191369    GeoCoord y1,
191370    unsigned char side,
191371    unsigned int idx
191372  ){
191373    GeoSegment *pSeg;
191374    GeoEvent *pEvent;
191375    if( x0==x1 ) return;  /* Ignore vertical segments */
191376    if( x0>x1 ){
191377      GeoCoord t = x0;
191378      x0 = x1;
191379      x1 = t;
191380      t = y0;
191381      y0 = y1;
191382      y1 = t;
191383    }
191384    pSeg = p->aSegment + p->nSegment;
191385    p->nSegment++;
191386    pSeg->C = (y1-y0)/(x1-x0);
191387    pSeg->B = y1 - x1*pSeg->C;
191388    pSeg->y0 = y0;
191389    pSeg->side = side;
191390    pSeg->idx = idx;
191391    pEvent = p->aEvent + p->nEvent;
191392    p->nEvent++;
191393    pEvent->x = x0;
191394    pEvent->eType = 0;
191395    pEvent->pSeg = pSeg;
191396    pEvent = p->aEvent + p->nEvent;
191397    p->nEvent++;
191398    pEvent->x = x1;
191399    pEvent->eType = 1;
191400    pEvent->pSeg = pSeg;
191401  }
191402    
191403  
191404  
191405  /*
191406  ** Insert all segments and events for polygon pPoly.
191407  */
191408  static void geopolyAddSegments(
191409    GeoOverlap *p,          /* Add segments to this Overlap object */
191410    GeoPoly *pPoly,         /* Take all segments from this polygon */
191411    unsigned char side      /* The side of pPoly */
191412  ){
191413    unsigned int i;
191414    GeoCoord *x;
191415    for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
191416      x = &GeoX(pPoly,i);
191417      geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
191418    }
191419    x = &GeoX(pPoly,i);
191420    geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
191421  }
191422  
191423  /*
191424  ** Merge two lists of sorted events by X coordinate
191425  */
191426  static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
191427    GeoEvent head, *pLast;
191428    head.pNext = 0;
191429    pLast = &head;
191430    while( pRight && pLeft ){
191431      if( pRight->x <= pLeft->x ){
191432        pLast->pNext = pRight;
191433        pLast = pRight;
191434        pRight = pRight->pNext;
191435      }else{
191436        pLast->pNext = pLeft;
191437        pLast = pLeft;
191438        pLeft = pLeft->pNext;
191439      }
191440    }
191441    pLast->pNext = pRight ? pRight : pLeft;
191442    return head.pNext;  
191443  }
191444  
191445  /*
191446  ** Sort an array of nEvent event objects into a list.
191447  */
191448  static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
191449    int mx = 0;
191450    int i, j;
191451    GeoEvent *p;
191452    GeoEvent *a[50];
191453    for(i=0; i<nEvent; i++){
191454      p = &aEvent[i];
191455      p->pNext = 0;
191456      for(j=0; j<mx && a[j]; j++){
191457        p = geopolyEventMerge(a[j], p);
191458        a[j] = 0;
191459      }
191460      a[j] = p;
191461      if( j>=mx ) mx = j+1;
191462    }
191463    p = 0;
191464    for(i=0; i<mx; i++){
191465      p = geopolyEventMerge(a[i], p);
191466    }
191467    return p;
191468  }
191469  
191470  /*
191471  ** Merge two lists of sorted segments by Y, and then by C.
191472  */
191473  static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
191474    GeoSegment head, *pLast;
191475    head.pNext = 0;
191476    pLast = &head;
191477    while( pRight && pLeft ){
191478      double r = pRight->y - pLeft->y;
191479      if( r==0.0 ) r = pRight->C - pLeft->C;
191480      if( r<0.0 ){
191481        pLast->pNext = pRight;
191482        pLast = pRight;
191483        pRight = pRight->pNext;
191484      }else{
191485        pLast->pNext = pLeft;
191486        pLast = pLeft;
191487        pLeft = pLeft->pNext;
191488      }
191489    }
191490    pLast->pNext = pRight ? pRight : pLeft;
191491    return head.pNext;  
191492  }
191493  
191494  /*
191495  ** Sort a list of GeoSegments in order of increasing Y and in the event of
191496  ** a tie, increasing C (slope).
191497  */
191498  static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
191499    int mx = 0;
191500    int i;
191501    GeoSegment *p;
191502    GeoSegment *a[50];
191503    while( pList ){
191504      p = pList;
191505      pList = pList->pNext;
191506      p->pNext = 0;
191507      for(i=0; i<mx && a[i]; i++){
191508        p = geopolySegmentMerge(a[i], p);
191509        a[i] = 0;
191510      }
191511      a[i] = p;
191512      if( i>=mx ) mx = i+1;
191513    }
191514    p = 0;
191515    for(i=0; i<mx; i++){
191516      p = geopolySegmentMerge(a[i], p);
191517    }
191518    return p;
191519  }
191520  
191521  /*
191522  ** Determine the overlap between two polygons
191523  */
191524  static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
191525    int nVertex = p1->nVertex + p2->nVertex + 2;
191526    GeoOverlap *p;
191527    int nByte;
191528    GeoEvent *pThisEvent;
191529    double rX;
191530    int rc = 0;
191531    int needSort = 0;
191532    GeoSegment *pActive = 0;
191533    GeoSegment *pSeg;
191534    unsigned char aOverlap[4];
191535  
191536    nByte = sizeof(GeoEvent)*nVertex*2 
191537             + sizeof(GeoSegment)*nVertex 
191538             + sizeof(GeoOverlap);
191539    p = sqlite3_malloc( nByte );
191540    if( p==0 ) return -1;
191541    p->aEvent = (GeoEvent*)&p[1];
191542    p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
191543    p->nEvent = p->nSegment = 0;
191544    geopolyAddSegments(p, p1, 1);
191545    geopolyAddSegments(p, p2, 2);
191546    pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
191547    rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
191548    memset(aOverlap, 0, sizeof(aOverlap));
191549    while( pThisEvent ){
191550      if( pThisEvent->x!=rX ){
191551        GeoSegment *pPrev = 0;
191552        int iMask = 0;
191553        GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
191554        rX = pThisEvent->x;
191555        if( needSort ){
191556          GEODEBUG(("SORT\n"));
191557          pActive = geopolySortSegmentsByYAndC(pActive);
191558          needSort = 0;
191559        }
191560        for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
191561          if( pPrev ){
191562            if( pPrev->y!=pSeg->y ){
191563              GEODEBUG(("MASK: %d\n", iMask));
191564              aOverlap[iMask] = 1;
191565            }
191566          }
191567          iMask ^= pSeg->side;
191568          pPrev = pSeg;
191569        }
191570        pPrev = 0;
191571        for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
191572          double y = pSeg->C*rX + pSeg->B;
191573          GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
191574          pSeg->y = y;
191575          if( pPrev ){
191576            if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
191577              rc = 1;
191578              GEODEBUG(("Crossing: %d.%d and %d.%d\n",
191579                      pPrev->side, pPrev->idx,
191580                      pSeg->side, pSeg->idx));
191581              goto geopolyOverlapDone;
191582            }else if( pPrev->y!=pSeg->y ){
191583              GEODEBUG(("MASK: %d\n", iMask));
191584              aOverlap[iMask] = 1;
191585            }
191586          }
191587          iMask ^= pSeg->side;
191588          pPrev = pSeg;
191589        }
191590      }
191591      GEODEBUG(("%s %d.%d C=%g B=%g\n",
191592        pThisEvent->eType ? "RM " : "ADD",
191593        pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
191594        pThisEvent->pSeg->C,
191595        pThisEvent->pSeg->B));
191596      if( pThisEvent->eType==0 ){
191597        /* Add a segment */
191598        pSeg = pThisEvent->pSeg;
191599        pSeg->y = pSeg->y0;
191600        pSeg->pNext = pActive;
191601        pActive = pSeg;
191602        needSort = 1;
191603      }else{
191604        /* Remove a segment */
191605        if( pActive==pThisEvent->pSeg ){
191606          pActive = pActive->pNext;
191607        }else{
191608          for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
191609            if( pSeg->pNext==pThisEvent->pSeg ){
191610              pSeg->pNext = pSeg->pNext->pNext;
191611              break;
191612            }
191613          }
191614        }
191615      }
191616      pThisEvent = pThisEvent->pNext;
191617    }
191618    if( aOverlap[3]==0 ){
191619      rc = 0;
191620    }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
191621      rc = 3;
191622    }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
191623      rc = 2;
191624    }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
191625      rc = 4;
191626    }else{
191627      rc = 1;
191628    }
191629  
191630  geopolyOverlapDone:
191631    sqlite3_free(p);
191632    return rc;
191633  }
191634  
191635  /*
191636  ** SQL function:    geopoly_overlap(P1,P2)
191637  **
191638  ** Determine whether or not P1 and P2 overlap. Return value:
191639  **
191640  **   0     The two polygons are disjoint
191641  **   1     They overlap
191642  **   2     P1 is completely contained within P2
191643  **   3     P2 is completely contained within P1
191644  **   4     P1 and P2 are the same polygon
191645  **   NULL  Either P1 or P2 or both are not valid polygons
191646  */
191647  static void geopolyOverlapFunc(
191648    sqlite3_context *context,
191649    int argc,
191650    sqlite3_value **argv
191651  ){
191652    GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
191653    GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
191654    if( p1 && p2 ){
191655      int x = geopolyOverlap(p1, p2);
191656      if( x<0 ){
191657        sqlite3_result_error_nomem(context);
191658      }else{
191659        sqlite3_result_int(context, x);
191660      }
191661    }
191662    sqlite3_free(p1);
191663    sqlite3_free(p2);
191664  }
191665  
191666  /*
191667  ** Enable or disable debugging output
191668  */
191669  static void geopolyDebugFunc(
191670    sqlite3_context *context,
191671    int argc,
191672    sqlite3_value **argv
191673  ){
191674  #ifdef GEOPOLY_ENABLE_DEBUG
191675    geo_debug = sqlite3_value_int(argv[0]);
191676  #endif
191677  }
191678  
191679  /* 
191680  ** This function is the implementation of both the xConnect and xCreate
191681  ** methods of the geopoly virtual table.
191682  **
191683  **   argv[0]   -> module name
191684  **   argv[1]   -> database name
191685  **   argv[2]   -> table name
191686  **   argv[...] -> column names...
191687  */
191688  static int geopolyInit(
191689    sqlite3 *db,                        /* Database connection */
191690    void *pAux,                         /* One of the RTREE_COORD_* constants */
191691    int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
191692    sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
191693    char **pzErr,                       /* OUT: Error message, if any */
191694    int isCreate                        /* True for xCreate, false for xConnect */
191695  ){
191696    int rc = SQLITE_OK;
191697    Rtree *pRtree;
191698    int nDb;              /* Length of string argv[1] */
191699    int nName;            /* Length of string argv[2] */
191700    sqlite3_str *pSql;
191701    char *zSql;
191702    int ii;
191703  
191704    sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
191705  
191706    /* Allocate the sqlite3_vtab structure */
191707    nDb = (int)strlen(argv[1]);
191708    nName = (int)strlen(argv[2]);
191709    pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
191710    if( !pRtree ){
191711      return SQLITE_NOMEM;
191712    }
191713    memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
191714    pRtree->nBusy = 1;
191715    pRtree->base.pModule = &rtreeModule;
191716    pRtree->zDb = (char *)&pRtree[1];
191717    pRtree->zName = &pRtree->zDb[nDb+1];
191718    pRtree->eCoordType = RTREE_COORD_REAL32;
191719    pRtree->nDim = 2;
191720    pRtree->nDim2 = 4;
191721    memcpy(pRtree->zDb, argv[1], nDb);
191722    memcpy(pRtree->zName, argv[2], nName);
191723  
191724  
191725    /* Create/Connect to the underlying relational database schema. If
191726    ** that is successful, call sqlite3_declare_vtab() to configure
191727    ** the r-tree table schema.
191728    */
191729    pSql = sqlite3_str_new(db);
191730    sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
191731    pRtree->nAux = 1;         /* Add one for _shape */
191732    pRtree->nAuxNotNull = 1;  /* The _shape column is always not-null */
191733    for(ii=3; ii<argc; ii++){
191734      pRtree->nAux++;
191735      sqlite3_str_appendf(pSql, ",%s", argv[ii]);
191736    }
191737    sqlite3_str_appendf(pSql, ");");
191738    zSql = sqlite3_str_finish(pSql);
191739    if( !zSql ){
191740      rc = SQLITE_NOMEM;
191741    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
191742      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
191743    }
191744    sqlite3_free(zSql);
191745    if( rc ) goto geopolyInit_fail;
191746    pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
191747  
191748    /* Figure out the node size to use. */
191749    rc = getNodeSize(db, pRtree, isCreate, pzErr);
191750    if( rc ) goto geopolyInit_fail;
191751    rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
191752    if( rc ){
191753      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
191754      goto geopolyInit_fail;
191755    }
191756  
191757    *ppVtab = (sqlite3_vtab *)pRtree;
191758    return SQLITE_OK;
191759  
191760  geopolyInit_fail:
191761    if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
191762    assert( *ppVtab==0 );
191763    assert( pRtree->nBusy==1 );
191764    rtreeRelease(pRtree);
191765    return rc;
191766  }
191767  
191768  
191769  /* 
191770  ** GEOPOLY virtual table module xCreate method.
191771  */
191772  static int geopolyCreate(
191773    sqlite3 *db,
191774    void *pAux,
191775    int argc, const char *const*argv,
191776    sqlite3_vtab **ppVtab,
191777    char **pzErr
191778  ){
191779    return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
191780  }
191781  
191782  /* 
191783  ** GEOPOLY virtual table module xConnect method.
191784  */
191785  static int geopolyConnect(
191786    sqlite3 *db,
191787    void *pAux,
191788    int argc, const char *const*argv,
191789    sqlite3_vtab **ppVtab,
191790    char **pzErr
191791  ){
191792    return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
191793  }
191794  
191795  
191796  /* 
191797  ** GEOPOLY virtual table module xFilter method.
191798  **
191799  ** Query plans:
191800  **
191801  **      1         rowid lookup
191802  **      2         search for objects overlapping the same bounding box
191803  **                that contains polygon argv[0]
191804  **      3         search for objects overlapping the same bounding box
191805  **                that contains polygon argv[0]
191806  **      4         full table scan
191807  */
191808  static int geopolyFilter(
191809    sqlite3_vtab_cursor *pVtabCursor,     /* The cursor to initialize */
191810    int idxNum,                           /* Query plan */
191811    const char *idxStr,                   /* Not Used */
191812    int argc, sqlite3_value **argv        /* Parameters to the query plan */
191813  ){
191814    Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
191815    RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
191816    RtreeNode *pRoot = 0;
191817    int rc = SQLITE_OK;
191818    int iCell = 0;
191819    sqlite3_stmt *pStmt;
191820  
191821    rtreeReference(pRtree);
191822  
191823    /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
191824    freeCursorConstraints(pCsr);
191825    sqlite3_free(pCsr->aPoint);
191826    pStmt = pCsr->pReadAux;
191827    memset(pCsr, 0, sizeof(RtreeCursor));
191828    pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
191829    pCsr->pReadAux = pStmt;
191830  
191831    pCsr->iStrategy = idxNum;
191832    if( idxNum==1 ){
191833      /* Special case - lookup by rowid. */
191834      RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
191835      RtreeSearchPoint *p;     /* Search point for the leaf */
191836      i64 iRowid = sqlite3_value_int64(argv[0]);
191837      i64 iNode = 0;
191838      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
191839      if( rc==SQLITE_OK && pLeaf!=0 ){
191840        p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
191841        assert( p!=0 );  /* Always returns pCsr->sPoint */
191842        pCsr->aNode[0] = pLeaf;
191843        p->id = iNode;
191844        p->eWithin = PARTLY_WITHIN;
191845        rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
191846        p->iCell = (u8)iCell;
191847        RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
191848      }else{
191849        pCsr->atEOF = 1;
191850      }
191851    }else{
191852      /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
191853      ** with the configured constraints. 
191854      */
191855      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
191856      if( rc==SQLITE_OK && idxNum<=3 ){
191857        RtreeCoord bbox[4];
191858        RtreeConstraint *p;
191859        assert( argc==1 );
191860        geopolyBBox(0, argv[0], bbox, &rc);
191861        if( rc ){
191862          goto geopoly_filter_end;
191863        }
191864        pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
191865        pCsr->nConstraint = 4;
191866        if( p==0 ){
191867          rc = SQLITE_NOMEM;
191868        }else{
191869          memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
191870          memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
191871          if( idxNum==2 ){
191872            /* Overlap query */
191873            p->op = 'B';
191874            p->iCoord = 0;
191875            p->u.rValue = bbox[1].f;
191876            p++;
191877            p->op = 'D';
191878            p->iCoord = 1;
191879            p->u.rValue = bbox[0].f;
191880            p++;
191881            p->op = 'B';
191882            p->iCoord = 2;
191883            p->u.rValue = bbox[3].f;
191884            p++;
191885            p->op = 'D';
191886            p->iCoord = 3;
191887            p->u.rValue = bbox[2].f;
191888          }else{
191889            /* Within query */
191890            p->op = 'D';
191891            p->iCoord = 0;
191892            p->u.rValue = bbox[0].f;
191893            p++;
191894            p->op = 'B';
191895            p->iCoord = 1;
191896            p->u.rValue = bbox[1].f;
191897            p++;
191898            p->op = 'D';
191899            p->iCoord = 2;
191900            p->u.rValue = bbox[2].f;
191901            p++;
191902            p->op = 'B';
191903            p->iCoord = 3;
191904            p->u.rValue = bbox[3].f;
191905          }
191906        }
191907      }
191908      if( rc==SQLITE_OK ){
191909        RtreeSearchPoint *pNew;
191910        pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
191911        if( pNew==0 ){
191912          rc = SQLITE_NOMEM;
191913          goto geopoly_filter_end;
191914        }
191915        pNew->id = 1;
191916        pNew->iCell = 0;
191917        pNew->eWithin = PARTLY_WITHIN;
191918        assert( pCsr->bPoint==1 );
191919        pCsr->aNode[0] = pRoot;
191920        pRoot = 0;
191921        RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
191922        rc = rtreeStepToLeaf(pCsr);
191923      }
191924    }
191925  
191926  geopoly_filter_end:
191927    nodeRelease(pRtree, pRoot);
191928    rtreeRelease(pRtree);
191929    return rc;
191930  }
191931  
191932  /*
191933  ** Rtree virtual table module xBestIndex method. There are three
191934  ** table scan strategies to choose from (in order from most to 
191935  ** least desirable):
191936  **
191937  **   idxNum     idxStr        Strategy
191938  **   ------------------------------------------------
191939  **     1        "rowid"       Direct lookup by rowid.
191940  **     2        "rtree"       R-tree overlap query using geopoly_overlap()
191941  **     3        "rtree"       R-tree within query using geopoly_within()
191942  **     4        "fullscan"    full-table scan.
191943  **   ------------------------------------------------
191944  */
191945  static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
191946    int ii;
191947    int iRowidTerm = -1;
191948    int iFuncTerm = -1;
191949    int idxNum = 0;
191950  
191951    for(ii=0; ii<pIdxInfo->nConstraint; ii++){
191952      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
191953      if( !p->usable ) continue;
191954      if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ  ){
191955        iRowidTerm = ii;
191956        break;
191957      }
191958      if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
191959        /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
191960        ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
191961        ** See geopolyFindFunction() */
191962        iFuncTerm = ii;
191963        idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
191964      }
191965    }
191966  
191967    if( iRowidTerm>=0 ){
191968      pIdxInfo->idxNum = 1;
191969      pIdxInfo->idxStr = "rowid";
191970      pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
191971      pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
191972      pIdxInfo->estimatedCost = 30.0;
191973      pIdxInfo->estimatedRows = 1;
191974      pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
191975      return SQLITE_OK;
191976    }
191977    if( iFuncTerm>=0 ){
191978      pIdxInfo->idxNum = idxNum;
191979      pIdxInfo->idxStr = "rtree";
191980      pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
191981      pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
191982      pIdxInfo->estimatedCost = 300.0;
191983      pIdxInfo->estimatedRows = 10;
191984      return SQLITE_OK;
191985    }
191986    pIdxInfo->idxNum = 4;
191987    pIdxInfo->idxStr = "fullscan";
191988    pIdxInfo->estimatedCost = 3000000.0;
191989    pIdxInfo->estimatedRows = 100000;
191990    return SQLITE_OK;
191991  }
191992  
191993  
191994  /* 
191995  ** GEOPOLY virtual table module xColumn method.
191996  */
191997  static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
191998    Rtree *pRtree = (Rtree *)cur->pVtab;
191999    RtreeCursor *pCsr = (RtreeCursor *)cur;
192000    RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
192001    int rc = SQLITE_OK;
192002    RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
192003  
192004    if( rc ) return rc;
192005    if( p==0 ) return SQLITE_OK;
192006    if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
192007    if( i<=pRtree->nAux ){
192008      if( !pCsr->bAuxValid ){
192009        if( pCsr->pReadAux==0 ){
192010          rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
192011                                  &pCsr->pReadAux, 0);
192012          if( rc ) return rc;
192013        }
192014        sqlite3_bind_int64(pCsr->pReadAux, 1, 
192015            nodeGetRowid(pRtree, pNode, p->iCell));
192016        rc = sqlite3_step(pCsr->pReadAux);
192017        if( rc==SQLITE_ROW ){
192018          pCsr->bAuxValid = 1;
192019        }else{
192020          sqlite3_reset(pCsr->pReadAux);
192021          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
192022          return rc;
192023        }
192024      }
192025      sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
192026    }
192027    return SQLITE_OK;
192028  }
192029  
192030  
192031  /*
192032  ** The xUpdate method for GEOPOLY module virtual tables.
192033  **
192034  ** For DELETE:
192035  **
192036  **     argv[0] = the rowid to be deleted
192037  **
192038  ** For INSERT:
192039  **
192040  **     argv[0] = SQL NULL
192041  **     argv[1] = rowid to insert, or an SQL NULL to select automatically
192042  **     argv[2] = _shape column
192043  **     argv[3] = first application-defined column....
192044  **
192045  ** For UPDATE:
192046  **
192047  **     argv[0] = rowid to modify.  Never NULL
192048  **     argv[1] = rowid after the change.  Never NULL
192049  **     argv[2] = new value for _shape
192050  **     argv[3] = new value for first application-defined column....
192051  */
192052  static int geopolyUpdate(
192053    sqlite3_vtab *pVtab, 
192054    int nData, 
192055    sqlite3_value **aData, 
192056    sqlite_int64 *pRowid
192057  ){
192058    Rtree *pRtree = (Rtree *)pVtab;
192059    int rc = SQLITE_OK;
192060    RtreeCell cell;                 /* New cell to insert if nData>1 */
192061    i64 oldRowid;                   /* The old rowid */
192062    int oldRowidValid;              /* True if oldRowid is valid */
192063    i64 newRowid;                   /* The new rowid */
192064    int newRowidValid;              /* True if newRowid is valid */
192065    int coordChange = 0;            /* Change in coordinates */
192066  
192067    if( pRtree->nNodeRef ){
192068      /* Unable to write to the btree while another cursor is reading from it,
192069      ** since the write might do a rebalance which would disrupt the read
192070      ** cursor. */
192071      return SQLITE_LOCKED_VTAB;
192072    }
192073    rtreeReference(pRtree);
192074    assert(nData>=1);
192075  
192076    oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
192077    oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
192078    newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
192079    newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
192080    cell.iRowid = newRowid;
192081  
192082    if( nData>1                                 /* not a DELETE */
192083     && (!oldRowidValid                         /* INSERT */
192084          || !sqlite3_value_nochange(aData[2])  /* UPDATE _shape */
192085          || oldRowid!=newRowid)                /* Rowid change */
192086    ){
192087      geopolyBBox(0, aData[2], cell.aCoord, &rc);
192088      if( rc ){
192089        if( rc==SQLITE_ERROR ){
192090          pVtab->zErrMsg =
192091            sqlite3_mprintf("_shape does not contain a valid polygon");
192092        }
192093        goto geopoly_update_end;
192094      }
192095      coordChange = 1;
192096  
192097      /* If a rowid value was supplied, check if it is already present in 
192098      ** the table. If so, the constraint has failed. */
192099      if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
192100        int steprc;
192101        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
192102        steprc = sqlite3_step(pRtree->pReadRowid);
192103        rc = sqlite3_reset(pRtree->pReadRowid);
192104        if( SQLITE_ROW==steprc ){
192105          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
192106            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
192107          }else{
192108            rc = rtreeConstraintError(pRtree, 0);
192109          }
192110        }
192111      }
192112    }
192113  
192114    /* If aData[0] is not an SQL NULL value, it is the rowid of a
192115    ** record to delete from the r-tree table. The following block does
192116    ** just that.
192117    */
192118    if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
192119      rc = rtreeDeleteRowid(pRtree, oldRowid);
192120    }
192121  
192122    /* If the aData[] array contains more than one element, elements
192123    ** (aData[2]..aData[argc-1]) contain a new record to insert into
192124    ** the r-tree structure.
192125    */
192126    if( rc==SQLITE_OK && nData>1 && coordChange ){
192127      /* Insert the new record into the r-tree */
192128      RtreeNode *pLeaf = 0;
192129      if( !newRowidValid ){
192130        rc = rtreeNewRowid(pRtree, &cell.iRowid);
192131      }
192132      *pRowid = cell.iRowid;
192133      if( rc==SQLITE_OK ){
192134        rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
192135      }
192136      if( rc==SQLITE_OK ){
192137        int rc2;
192138        pRtree->iReinsertHeight = -1;
192139        rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
192140        rc2 = nodeRelease(pRtree, pLeaf);
192141        if( rc==SQLITE_OK ){
192142          rc = rc2;
192143        }
192144      }
192145    }
192146  
192147    /* Change the data */
192148    if( rc==SQLITE_OK && nData>1 ){
192149      sqlite3_stmt *pUp = pRtree->pWriteAux;
192150      int jj;
192151      int nChange = 0;
192152      sqlite3_bind_int64(pUp, 1, cell.iRowid);
192153      assert( pRtree->nAux>=1 );
192154      if( sqlite3_value_nochange(aData[2]) ){
192155        sqlite3_bind_null(pUp, 2);
192156      }else{
192157        GeoPoly *p = 0;
192158        if( sqlite3_value_type(aData[2])==SQLITE_TEXT
192159         && (p = geopolyFuncParam(0, aData[2], &rc))!=0
192160         && rc==SQLITE_OK
192161        ){
192162          sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
192163        }else{
192164          sqlite3_bind_value(pUp, 2, aData[2]);
192165        }
192166        sqlite3_free(p);
192167        nChange = 1;
192168      }
192169      for(jj=1; jj<pRtree->nAux; jj++){
192170        nChange++;
192171        sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
192172      }
192173      if( nChange ){
192174        sqlite3_step(pUp);
192175        rc = sqlite3_reset(pUp);
192176      }
192177    }
192178  
192179  geopoly_update_end:
192180    rtreeRelease(pRtree);
192181    return rc;
192182  }
192183  
192184  /*
192185  ** Report that geopoly_overlap() is an overloaded function suitable
192186  ** for use in xBestIndex.
192187  */
192188  static int geopolyFindFunction(
192189    sqlite3_vtab *pVtab,
192190    int nArg,
192191    const char *zName,
192192    void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
192193    void **ppArg
192194  ){
192195    if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
192196      *pxFunc = geopolyOverlapFunc;
192197      *ppArg = 0;
192198      return SQLITE_INDEX_CONSTRAINT_FUNCTION;
192199    }
192200    if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
192201      *pxFunc = geopolyWithinFunc;
192202      *ppArg = 0;
192203      return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
192204    }
192205    return 0;
192206  }
192207  
192208  
192209  static sqlite3_module geopolyModule = {
192210    3,                          /* iVersion */
192211    geopolyCreate,              /* xCreate - create a table */
192212    geopolyConnect,             /* xConnect - connect to an existing table */
192213    geopolyBestIndex,           /* xBestIndex - Determine search strategy */
192214    rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
192215    rtreeDestroy,               /* xDestroy - Drop a table */
192216    rtreeOpen,                  /* xOpen - open a cursor */
192217    rtreeClose,                 /* xClose - close a cursor */
192218    geopolyFilter,              /* xFilter - configure scan constraints */
192219    rtreeNext,                  /* xNext - advance a cursor */
192220    rtreeEof,                   /* xEof */
192221    geopolyColumn,              /* xColumn - read data */
192222    rtreeRowid,                 /* xRowid - read data */
192223    geopolyUpdate,              /* xUpdate - write data */
192224    rtreeBeginTransaction,      /* xBegin - begin transaction */
192225    rtreeEndTransaction,        /* xSync - sync transaction */
192226    rtreeEndTransaction,        /* xCommit - commit transaction */
192227    rtreeEndTransaction,        /* xRollback - rollback transaction */
192228    geopolyFindFunction,        /* xFindFunction - function overloading */
192229    rtreeRename,                /* xRename - rename the table */
192230    rtreeSavepoint,             /* xSavepoint */
192231    0,                          /* xRelease */
192232    0,                          /* xRollbackTo */
192233    rtreeShadowName             /* xShadowName */
192234  };
192235  
192236  static int sqlite3_geopoly_init(sqlite3 *db){
192237    int rc = SQLITE_OK;
192238    static const struct {
192239      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
192240      signed char nArg;
192241      unsigned char bPure;
192242      const char *zName;
192243    } aFunc[] = {
192244       { geopolyAreaFunc,          1, 1,    "geopoly_area"             },
192245       { geopolyBlobFunc,          1, 1,    "geopoly_blob"             },
192246       { geopolyJsonFunc,          1, 1,    "geopoly_json"             },
192247       { geopolySvgFunc,          -1, 1,    "geopoly_svg"              },
192248       { geopolyWithinFunc,        2, 1,    "geopoly_within"           },
192249       { geopolyContainsPointFunc, 3, 1,    "geopoly_contains_point"   },
192250       { geopolyOverlapFunc,       2, 1,    "geopoly_overlap"          },
192251       { geopolyDebugFunc,         1, 0,    "geopoly_debug"            },
192252       { geopolyBBoxFunc,          1, 1,    "geopoly_bbox"             },
192253       { geopolyXformFunc,         7, 1,    "geopoly_xform"            },
192254       { geopolyRegularFunc,       4, 1,    "geopoly_regular"          },
192255       { geopolyCcwFunc,           1, 1,    "geopoly_ccw"              },
192256    };
192257    static const struct {
192258      void (*xStep)(sqlite3_context*,int,sqlite3_value**);
192259      void (*xFinal)(sqlite3_context*);
192260      const char *zName;
192261    } aAgg[] = {
192262       { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox"    },
192263    };
192264    int i;
192265    for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
192266      int enc = aFunc[i].bPure ? SQLITE_UTF8|SQLITE_DETERMINISTIC : SQLITE_UTF8;
192267      rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
192268                                   enc, 0,
192269                                   aFunc[i].xFunc, 0, 0);
192270    }
192271    for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
192272      rc = sqlite3_create_function(db, aAgg[i].zName, 1, SQLITE_UTF8, 0,
192273                                   0, aAgg[i].xStep, aAgg[i].xFinal);
192274    }
192275    if( rc==SQLITE_OK ){
192276      rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
192277    }
192278    return rc;
192279  }
192280  
192281  /************** End of geopoly.c *********************************************/
192282  /************** Continuing where we left off in rtree.c **********************/
192283  #endif
192284  
192285  /*
192286  ** Register the r-tree module with database handle db. This creates the
192287  ** virtual table module "rtree" and the debugging/analysis scalar 
192288  ** function "rtreenode".
192289  */
192290  SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
192291    const int utf8 = SQLITE_UTF8;
192292    int rc;
192293  
192294    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
192295    if( rc==SQLITE_OK ){
192296      rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
192297    }
192298    if( rc==SQLITE_OK ){
192299      rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
192300    }
192301    if( rc==SQLITE_OK ){
192302  #ifdef SQLITE_RTREE_INT_ONLY
192303      void *c = (void *)RTREE_COORD_INT32;
192304  #else
192305      void *c = (void *)RTREE_COORD_REAL32;
192306  #endif
192307      rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
192308    }
192309    if( rc==SQLITE_OK ){
192310      void *c = (void *)RTREE_COORD_INT32;
192311      rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
192312    }
192313  #ifdef SQLITE_ENABLE_GEOPOLY
192314    if( rc==SQLITE_OK ){
192315      rc = sqlite3_geopoly_init(db);
192316    }
192317  #endif
192318  
192319    return rc;
192320  }
192321  
192322  /*
192323  ** This routine deletes the RtreeGeomCallback object that was attached
192324  ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
192325  ** or sqlite3_rtree_query_callback().  In other words, this routine is the
192326  ** destructor for an RtreeGeomCallback objecct.  This routine is called when
192327  ** the corresponding SQL function is deleted.
192328  */
192329  static void rtreeFreeCallback(void *p){
192330    RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
192331    if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
192332    sqlite3_free(p);
192333  }
192334  
192335  /*
192336  ** This routine frees the BLOB that is returned by geomCallback().
192337  */
192338  static void rtreeMatchArgFree(void *pArg){
192339    int i;
192340    RtreeMatchArg *p = (RtreeMatchArg*)pArg;
192341    for(i=0; i<p->nParam; i++){
192342      sqlite3_value_free(p->apSqlParam[i]);
192343    }
192344    sqlite3_free(p);
192345  }
192346  
192347  /*
192348  ** Each call to sqlite3_rtree_geometry_callback() or
192349  ** sqlite3_rtree_query_callback() creates an ordinary SQLite
192350  ** scalar function that is implemented by this routine.
192351  **
192352  ** All this function does is construct an RtreeMatchArg object that
192353  ** contains the geometry-checking callback routines and a list of
192354  ** parameters to this function, then return that RtreeMatchArg object
192355  ** as a BLOB.
192356  **
192357  ** The R-Tree MATCH operator will read the returned BLOB, deserialize
192358  ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
192359  ** out which elements of the R-Tree should be returned by the query.
192360  */
192361  static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
192362    RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
192363    RtreeMatchArg *pBlob;
192364    sqlite3_int64 nBlob;
192365    int memErr = 0;
192366  
192367    nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
192368             + nArg*sizeof(sqlite3_value*);
192369    pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
192370    if( !pBlob ){
192371      sqlite3_result_error_nomem(ctx);
192372    }else{
192373      int i;
192374      pBlob->iSize = nBlob;
192375      pBlob->cb = pGeomCtx[0];
192376      pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
192377      pBlob->nParam = nArg;
192378      for(i=0; i<nArg; i++){
192379        pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
192380        if( pBlob->apSqlParam[i]==0 ) memErr = 1;
192381  #ifdef SQLITE_RTREE_INT_ONLY
192382        pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
192383  #else
192384        pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
192385  #endif
192386      }
192387      if( memErr ){
192388        sqlite3_result_error_nomem(ctx);
192389        rtreeMatchArgFree(pBlob);
192390      }else{
192391        sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
192392      }
192393    }
192394  }
192395  
192396  /*
192397  ** Register a new geometry function for use with the r-tree MATCH operator.
192398  */
192399  SQLITE_API int sqlite3_rtree_geometry_callback(
192400    sqlite3 *db,                  /* Register SQL function on this connection */
192401    const char *zGeom,            /* Name of the new SQL function */
192402    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
192403    void *pContext                /* Extra data associated with the callback */
192404  ){
192405    RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
192406  
192407    /* Allocate and populate the context object. */
192408    pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
192409    if( !pGeomCtx ) return SQLITE_NOMEM;
192410    pGeomCtx->xGeom = xGeom;
192411    pGeomCtx->xQueryFunc = 0;
192412    pGeomCtx->xDestructor = 0;
192413    pGeomCtx->pContext = pContext;
192414    return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
192415        (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
192416    );
192417  }
192418  
192419  /*
192420  ** Register a new 2nd-generation geometry function for use with the
192421  ** r-tree MATCH operator.
192422  */
192423  SQLITE_API int sqlite3_rtree_query_callback(
192424    sqlite3 *db,                 /* Register SQL function on this connection */
192425    const char *zQueryFunc,      /* Name of new SQL function */
192426    int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
192427    void *pContext,              /* Extra data passed into the callback */
192428    void (*xDestructor)(void*)   /* Destructor for the extra data */
192429  ){
192430    RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
192431  
192432    /* Allocate and populate the context object. */
192433    pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
192434    if( !pGeomCtx ) return SQLITE_NOMEM;
192435    pGeomCtx->xGeom = 0;
192436    pGeomCtx->xQueryFunc = xQueryFunc;
192437    pGeomCtx->xDestructor = xDestructor;
192438    pGeomCtx->pContext = pContext;
192439    return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 
192440        (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
192441    );
192442  }
192443  
192444  #if !SQLITE_CORE
192445  #ifdef _WIN32
192446  __declspec(dllexport)
192447  #endif
192448  SQLITE_API int sqlite3_rtree_init(
192449    sqlite3 *db,
192450    char **pzErrMsg,
192451    const sqlite3_api_routines *pApi
192452  ){
192453    SQLITE_EXTENSION_INIT2(pApi)
192454    return sqlite3RtreeInit(db);
192455  }
192456  #endif
192457  
192458  #endif
192459  
192460  /************** End of rtree.c ***********************************************/
192461  /************** Begin file icu.c *********************************************/
192462  /*
192463  ** 2007 May 6
192464  **
192465  ** The author disclaims copyright to this source code.  In place of
192466  ** a legal notice, here is a blessing:
192467  **
192468  **    May you do good and not evil.
192469  **    May you find forgiveness for yourself and forgive others.
192470  **    May you share freely, never taking more than you give.
192471  **
192472  *************************************************************************
192473  ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
192474  **
192475  ** This file implements an integration between the ICU library 
192476  ** ("International Components for Unicode", an open-source library 
192477  ** for handling unicode data) and SQLite. The integration uses 
192478  ** ICU to provide the following to SQLite:
192479  **
192480  **   * An implementation of the SQL regexp() function (and hence REGEXP
192481  **     operator) using the ICU uregex_XX() APIs.
192482  **
192483  **   * Implementations of the SQL scalar upper() and lower() functions
192484  **     for case mapping.
192485  **
192486  **   * Integration of ICU and SQLite collation sequences.
192487  **
192488  **   * An implementation of the LIKE operator that uses ICU to 
192489  **     provide case-independent matching.
192490  */
192491  
192492  #if !defined(SQLITE_CORE)                  \
192493   || defined(SQLITE_ENABLE_ICU)             \
192494   || defined(SQLITE_ENABLE_ICU_COLLATIONS)
192495  
192496  /* Include ICU headers */
192497  #include <unicode/utypes.h>
192498  #include <unicode/uregex.h>
192499  #include <unicode/ustring.h>
192500  #include <unicode/ucol.h>
192501  
192502  /* #include <assert.h> */
192503  
192504  #ifndef SQLITE_CORE
192505  /*   #include "sqlite3ext.h" */
192506    SQLITE_EXTENSION_INIT1
192507  #else
192508  /*   #include "sqlite3.h" */
192509  #endif
192510  
192511  /*
192512  ** This function is called when an ICU function called from within
192513  ** the implementation of an SQL scalar function returns an error.
192514  **
192515  ** The scalar function context passed as the first argument is 
192516  ** loaded with an error message based on the following two args.
192517  */
192518  static void icuFunctionError(
192519    sqlite3_context *pCtx,       /* SQLite scalar function context */
192520    const char *zName,           /* Name of ICU function that failed */
192521    UErrorCode e                 /* Error code returned by ICU function */
192522  ){
192523    char zBuf[128];
192524    sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
192525    zBuf[127] = '\0';
192526    sqlite3_result_error(pCtx, zBuf, -1);
192527  }
192528  
192529  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
192530  
192531  /*
192532  ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
192533  ** operator.
192534  */
192535  #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
192536  # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
192537  #endif
192538  
192539  /*
192540  ** Version of sqlite3_free() that is always a function, never a macro.
192541  */
192542  static void xFree(void *p){
192543    sqlite3_free(p);
192544  }
192545  
192546  /*
192547  ** This lookup table is used to help decode the first byte of
192548  ** a multi-byte UTF8 character. It is copied here from SQLite source
192549  ** code file utf8.c.
192550  */
192551  static const unsigned char icuUtf8Trans1[] = {
192552    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
192553    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
192554    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
192555    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
192556    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
192557    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
192558    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
192559    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
192560  };
192561  
192562  #define SQLITE_ICU_READ_UTF8(zIn, c)                       \
192563    c = *(zIn++);                                            \
192564    if( c>=0xc0 ){                                           \
192565      c = icuUtf8Trans1[c-0xc0];                             \
192566      while( (*zIn & 0xc0)==0x80 ){                          \
192567        c = (c<<6) + (0x3f & *(zIn++));                      \
192568      }                                                      \
192569    }
192570  
192571  #define SQLITE_ICU_SKIP_UTF8(zIn)                          \
192572    assert( *zIn );                                          \
192573    if( *(zIn++)>=0xc0 ){                                    \
192574      while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
192575    }
192576  
192577  
192578  /*
192579  ** Compare two UTF-8 strings for equality where the first string is
192580  ** a "LIKE" expression. Return true (1) if they are the same and 
192581  ** false (0) if they are different.
192582  */
192583  static int icuLikeCompare(
192584    const uint8_t *zPattern,   /* LIKE pattern */
192585    const uint8_t *zString,    /* The UTF-8 string to compare against */
192586    const UChar32 uEsc         /* The escape character */
192587  ){
192588    static const uint32_t MATCH_ONE = (uint32_t)'_';
192589    static const uint32_t MATCH_ALL = (uint32_t)'%';
192590  
192591    int prevEscape = 0;     /* True if the previous character was uEsc */
192592  
192593    while( 1 ){
192594  
192595      /* Read (and consume) the next character from the input pattern. */
192596      uint32_t uPattern;
192597      SQLITE_ICU_READ_UTF8(zPattern, uPattern);
192598      if( uPattern==0 ) break;
192599  
192600      /* There are now 4 possibilities:
192601      **
192602      **     1. uPattern is an unescaped match-all character "%",
192603      **     2. uPattern is an unescaped match-one character "_",
192604      **     3. uPattern is an unescaped escape character, or
192605      **     4. uPattern is to be handled as an ordinary character
192606      */
192607      if( !prevEscape && uPattern==MATCH_ALL ){
192608        /* Case 1. */
192609        uint8_t c;
192610  
192611        /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
192612        ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
192613        ** test string.
192614        */
192615        while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
192616          if( c==MATCH_ONE ){
192617            if( *zString==0 ) return 0;
192618            SQLITE_ICU_SKIP_UTF8(zString);
192619          }
192620          zPattern++;
192621        }
192622  
192623        if( *zPattern==0 ) return 1;
192624  
192625        while( *zString ){
192626          if( icuLikeCompare(zPattern, zString, uEsc) ){
192627            return 1;
192628          }
192629          SQLITE_ICU_SKIP_UTF8(zString);
192630        }
192631        return 0;
192632  
192633      }else if( !prevEscape && uPattern==MATCH_ONE ){
192634        /* Case 2. */
192635        if( *zString==0 ) return 0;
192636        SQLITE_ICU_SKIP_UTF8(zString);
192637  
192638      }else if( !prevEscape && uPattern==(uint32_t)uEsc){
192639        /* Case 3. */
192640        prevEscape = 1;
192641  
192642      }else{
192643        /* Case 4. */
192644        uint32_t uString;
192645        SQLITE_ICU_READ_UTF8(zString, uString);
192646        uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
192647        uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
192648        if( uString!=uPattern ){
192649          return 0;
192650        }
192651        prevEscape = 0;
192652      }
192653    }
192654  
192655    return *zString==0;
192656  }
192657  
192658  /*
192659  ** Implementation of the like() SQL function.  This function implements
192660  ** the build-in LIKE operator.  The first argument to the function is the
192661  ** pattern and the second argument is the string.  So, the SQL statements:
192662  **
192663  **       A LIKE B
192664  **
192665  ** is implemented as like(B, A). If there is an escape character E, 
192666  **
192667  **       A LIKE B ESCAPE E
192668  **
192669  ** is mapped to like(B, A, E).
192670  */
192671  static void icuLikeFunc(
192672    sqlite3_context *context, 
192673    int argc, 
192674    sqlite3_value **argv
192675  ){
192676    const unsigned char *zA = sqlite3_value_text(argv[0]);
192677    const unsigned char *zB = sqlite3_value_text(argv[1]);
192678    UChar32 uEsc = 0;
192679  
192680    /* Limit the length of the LIKE or GLOB pattern to avoid problems
192681    ** of deep recursion and N*N behavior in patternCompare().
192682    */
192683    if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
192684      sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
192685      return;
192686    }
192687  
192688  
192689    if( argc==3 ){
192690      /* The escape character string must consist of a single UTF-8 character.
192691      ** Otherwise, return an error.
192692      */
192693      int nE= sqlite3_value_bytes(argv[2]);
192694      const unsigned char *zE = sqlite3_value_text(argv[2]);
192695      int i = 0;
192696      if( zE==0 ) return;
192697      U8_NEXT(zE, i, nE, uEsc);
192698      if( i!=nE){
192699        sqlite3_result_error(context, 
192700            "ESCAPE expression must be a single character", -1);
192701        return;
192702      }
192703    }
192704  
192705    if( zA && zB ){
192706      sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
192707    }
192708  }
192709  
192710  /*
192711  ** Function to delete compiled regexp objects. Registered as
192712  ** a destructor function with sqlite3_set_auxdata().
192713  */
192714  static void icuRegexpDelete(void *p){
192715    URegularExpression *pExpr = (URegularExpression *)p;
192716    uregex_close(pExpr);
192717  }
192718  
192719  /*
192720  ** Implementation of SQLite REGEXP operator. This scalar function takes
192721  ** two arguments. The first is a regular expression pattern to compile
192722  ** the second is a string to match against that pattern. If either 
192723  ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
192724  ** is 1 if the string matches the pattern, or 0 otherwise.
192725  **
192726  ** SQLite maps the regexp() function to the regexp() operator such
192727  ** that the following two are equivalent:
192728  **
192729  **     zString REGEXP zPattern
192730  **     regexp(zPattern, zString)
192731  **
192732  ** Uses the following ICU regexp APIs:
192733  **
192734  **     uregex_open()
192735  **     uregex_matches()
192736  **     uregex_close()
192737  */
192738  static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
192739    UErrorCode status = U_ZERO_ERROR;
192740    URegularExpression *pExpr;
192741    UBool res;
192742    const UChar *zString = sqlite3_value_text16(apArg[1]);
192743  
192744    (void)nArg;  /* Unused parameter */
192745  
192746    /* If the left hand side of the regexp operator is NULL, 
192747    ** then the result is also NULL. 
192748    */
192749    if( !zString ){
192750      return;
192751    }
192752  
192753    pExpr = sqlite3_get_auxdata(p, 0);
192754    if( !pExpr ){
192755      const UChar *zPattern = sqlite3_value_text16(apArg[0]);
192756      if( !zPattern ){
192757        return;
192758      }
192759      pExpr = uregex_open(zPattern, -1, 0, 0, &status);
192760  
192761      if( U_SUCCESS(status) ){
192762        sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
192763      }else{
192764        assert(!pExpr);
192765        icuFunctionError(p, "uregex_open", status);
192766        return;
192767      }
192768    }
192769  
192770    /* Configure the text that the regular expression operates on. */
192771    uregex_setText(pExpr, zString, -1, &status);
192772    if( !U_SUCCESS(status) ){
192773      icuFunctionError(p, "uregex_setText", status);
192774      return;
192775    }
192776  
192777    /* Attempt the match */
192778    res = uregex_matches(pExpr, 0, &status);
192779    if( !U_SUCCESS(status) ){
192780      icuFunctionError(p, "uregex_matches", status);
192781      return;
192782    }
192783  
192784    /* Set the text that the regular expression operates on to a NULL
192785    ** pointer. This is not really necessary, but it is tidier than 
192786    ** leaving the regular expression object configured with an invalid
192787    ** pointer after this function returns.
192788    */
192789    uregex_setText(pExpr, 0, 0, &status);
192790  
192791    /* Return 1 or 0. */
192792    sqlite3_result_int(p, res ? 1 : 0);
192793  }
192794  
192795  /*
192796  ** Implementations of scalar functions for case mapping - upper() and 
192797  ** lower(). Function upper() converts its input to upper-case (ABC).
192798  ** Function lower() converts to lower-case (abc).
192799  **
192800  ** ICU provides two types of case mapping, "general" case mapping and
192801  ** "language specific". Refer to ICU documentation for the differences
192802  ** between the two.
192803  **
192804  ** To utilise "general" case mapping, the upper() or lower() scalar 
192805  ** functions are invoked with one argument:
192806  **
192807  **     upper('ABC') -> 'abc'
192808  **     lower('abc') -> 'ABC'
192809  **
192810  ** To access ICU "language specific" case mapping, upper() or lower()
192811  ** should be invoked with two arguments. The second argument is the name
192812  ** of the locale to use. Passing an empty string ("") or SQL NULL value
192813  ** as the second argument is the same as invoking the 1 argument version
192814  ** of upper() or lower().
192815  **
192816  **     lower('I', 'en_us') -> 'i'
192817  **     lower('I', 'tr_tr') -> '\u131' (small dotless i)
192818  **
192819  ** http://www.icu-project.org/userguide/posix.html#case_mappings
192820  */
192821  static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
192822    const UChar *zInput;            /* Pointer to input string */
192823    UChar *zOutput = 0;             /* Pointer to output buffer */
192824    int nInput;                     /* Size of utf-16 input string in bytes */
192825    int nOut;                       /* Size of output buffer in bytes */
192826    int cnt;
192827    int bToUpper;                   /* True for toupper(), false for tolower() */
192828    UErrorCode status;
192829    const char *zLocale = 0;
192830  
192831    assert(nArg==1 || nArg==2);
192832    bToUpper = (sqlite3_user_data(p)!=0);
192833    if( nArg==2 ){
192834      zLocale = (const char *)sqlite3_value_text(apArg[1]);
192835    }
192836  
192837    zInput = sqlite3_value_text16(apArg[0]);
192838    if( !zInput ){
192839      return;
192840    }
192841    nOut = nInput = sqlite3_value_bytes16(apArg[0]);
192842    if( nOut==0 ){
192843      sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
192844      return;
192845    }
192846  
192847    for(cnt=0; cnt<2; cnt++){
192848      UChar *zNew = sqlite3_realloc(zOutput, nOut);
192849      if( zNew==0 ){
192850        sqlite3_free(zOutput);
192851        sqlite3_result_error_nomem(p);
192852        return;
192853      }
192854      zOutput = zNew;
192855      status = U_ZERO_ERROR;
192856      if( bToUpper ){
192857        nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
192858      }else{
192859        nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
192860      }
192861  
192862      if( U_SUCCESS(status) ){
192863        sqlite3_result_text16(p, zOutput, nOut, xFree);
192864      }else if( status==U_BUFFER_OVERFLOW_ERROR ){
192865        assert( cnt==0 );
192866        continue;
192867      }else{
192868        icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
192869      }
192870      return;
192871    }
192872    assert( 0 );     /* Unreachable */
192873  }
192874  
192875  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
192876  
192877  /*
192878  ** Collation sequence destructor function. The pCtx argument points to
192879  ** a UCollator structure previously allocated using ucol_open().
192880  */
192881  static void icuCollationDel(void *pCtx){
192882    UCollator *p = (UCollator *)pCtx;
192883    ucol_close(p);
192884  }
192885  
192886  /*
192887  ** Collation sequence comparison function. The pCtx argument points to
192888  ** a UCollator structure previously allocated using ucol_open().
192889  */
192890  static int icuCollationColl(
192891    void *pCtx,
192892    int nLeft,
192893    const void *zLeft,
192894    int nRight,
192895    const void *zRight
192896  ){
192897    UCollationResult res;
192898    UCollator *p = (UCollator *)pCtx;
192899    res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
192900    switch( res ){
192901      case UCOL_LESS:    return -1;
192902      case UCOL_GREATER: return +1;
192903      case UCOL_EQUAL:   return 0;
192904    }
192905    assert(!"Unexpected return value from ucol_strcoll()");
192906    return 0;
192907  }
192908  
192909  /*
192910  ** Implementation of the scalar function icu_load_collation().
192911  **
192912  ** This scalar function is used to add ICU collation based collation 
192913  ** types to an SQLite database connection. It is intended to be called
192914  ** as follows:
192915  **
192916  **     SELECT icu_load_collation(<locale>, <collation-name>);
192917  **
192918  ** Where <locale> is a string containing an ICU locale identifier (i.e.
192919  ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
192920  ** collation sequence to create.
192921  */
192922  static void icuLoadCollation(
192923    sqlite3_context *p, 
192924    int nArg, 
192925    sqlite3_value **apArg
192926  ){
192927    sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
192928    UErrorCode status = U_ZERO_ERROR;
192929    const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
192930    const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
192931    UCollator *pUCollator;    /* ICU library collation object */
192932    int rc;                   /* Return code from sqlite3_create_collation_x() */
192933  
192934    assert(nArg==2);
192935    (void)nArg; /* Unused parameter */
192936    zLocale = (const char *)sqlite3_value_text(apArg[0]);
192937    zName = (const char *)sqlite3_value_text(apArg[1]);
192938  
192939    if( !zLocale || !zName ){
192940      return;
192941    }
192942  
192943    pUCollator = ucol_open(zLocale, &status);
192944    if( !U_SUCCESS(status) ){
192945      icuFunctionError(p, "ucol_open", status);
192946      return;
192947    }
192948    assert(p);
192949  
192950    rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
192951        icuCollationColl, icuCollationDel
192952    );
192953    if( rc!=SQLITE_OK ){
192954      ucol_close(pUCollator);
192955      sqlite3_result_error(p, "Error registering collation function", -1);
192956    }
192957  }
192958  
192959  /*
192960  ** Register the ICU extension functions with database db.
192961  */
192962  SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
192963    static const struct IcuScalar {
192964      const char *zName;                        /* Function name */
192965      unsigned char nArg;                       /* Number of arguments */
192966      unsigned short enc;                       /* Optimal text encoding */
192967      unsigned char iContext;                   /* sqlite3_user_data() context */
192968      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
192969    } scalars[] = {
192970      {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
192971  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
192972      {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
192973      {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
192974      {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
192975      {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
192976      {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
192977      {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
192978      {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
192979      {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
192980      {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
192981      {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
192982      {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
192983  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
192984    };
192985    int rc = SQLITE_OK;
192986    int i;
192987    
192988    for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
192989      const struct IcuScalar *p = &scalars[i];
192990      rc = sqlite3_create_function(
192991          db, p->zName, p->nArg, p->enc, 
192992          p->iContext ? (void*)db : (void*)0,
192993          p->xFunc, 0, 0
192994      );
192995    }
192996  
192997    return rc;
192998  }
192999  
193000  #if !SQLITE_CORE
193001  #ifdef _WIN32
193002  __declspec(dllexport)
193003  #endif
193004  SQLITE_API int sqlite3_icu_init(
193005    sqlite3 *db, 
193006    char **pzErrMsg,
193007    const sqlite3_api_routines *pApi
193008  ){
193009    SQLITE_EXTENSION_INIT2(pApi)
193010    return sqlite3IcuInit(db);
193011  }
193012  #endif
193013  
193014  #endif
193015  
193016  /************** End of icu.c *************************************************/
193017  /************** Begin file fts3_icu.c ****************************************/
193018  /*
193019  ** 2007 June 22
193020  **
193021  ** The author disclaims copyright to this source code.  In place of
193022  ** a legal notice, here is a blessing:
193023  **
193024  **    May you do good and not evil.
193025  **    May you find forgiveness for yourself and forgive others.
193026  **    May you share freely, never taking more than you give.
193027  **
193028  *************************************************************************
193029  ** This file implements a tokenizer for fts3 based on the ICU library.
193030  */
193031  /* #include "fts3Int.h" */
193032  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
193033  #ifdef SQLITE_ENABLE_ICU
193034  
193035  /* #include <assert.h> */
193036  /* #include <string.h> */
193037  /* #include "fts3_tokenizer.h" */
193038  
193039  #include <unicode/ubrk.h>
193040  /* #include <unicode/ucol.h> */
193041  /* #include <unicode/ustring.h> */
193042  #include <unicode/utf16.h>
193043  
193044  typedef struct IcuTokenizer IcuTokenizer;
193045  typedef struct IcuCursor IcuCursor;
193046  
193047  struct IcuTokenizer {
193048    sqlite3_tokenizer base;
193049    char *zLocale;
193050  };
193051  
193052  struct IcuCursor {
193053    sqlite3_tokenizer_cursor base;
193054  
193055    UBreakIterator *pIter;      /* ICU break-iterator object */
193056    int nChar;                  /* Number of UChar elements in pInput */
193057    UChar *aChar;               /* Copy of input using utf-16 encoding */
193058    int *aOffset;               /* Offsets of each character in utf-8 input */
193059  
193060    int nBuffer;
193061    char *zBuffer;
193062  
193063    int iToken;
193064  };
193065  
193066  /*
193067  ** Create a new tokenizer instance.
193068  */
193069  static int icuCreate(
193070    int argc,                            /* Number of entries in argv[] */
193071    const char * const *argv,            /* Tokenizer creation arguments */
193072    sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
193073  ){
193074    IcuTokenizer *p;
193075    int n = 0;
193076  
193077    if( argc>0 ){
193078      n = strlen(argv[0])+1;
193079    }
193080    p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
193081    if( !p ){
193082      return SQLITE_NOMEM;
193083    }
193084    memset(p, 0, sizeof(IcuTokenizer));
193085  
193086    if( n ){
193087      p->zLocale = (char *)&p[1];
193088      memcpy(p->zLocale, argv[0], n);
193089    }
193090  
193091    *ppTokenizer = (sqlite3_tokenizer *)p;
193092  
193093    return SQLITE_OK;
193094  }
193095  
193096  /*
193097  ** Destroy a tokenizer
193098  */
193099  static int icuDestroy(sqlite3_tokenizer *pTokenizer){
193100    IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
193101    sqlite3_free(p);
193102    return SQLITE_OK;
193103  }
193104  
193105  /*
193106  ** Prepare to begin tokenizing a particular string.  The input
193107  ** string to be tokenized is pInput[0..nBytes-1].  A cursor
193108  ** used to incrementally tokenize this string is returned in 
193109  ** *ppCursor.
193110  */
193111  static int icuOpen(
193112    sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
193113    const char *zInput,                    /* Input string */
193114    int nInput,                            /* Length of zInput in bytes */
193115    sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
193116  ){
193117    IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
193118    IcuCursor *pCsr;
193119  
193120    const int32_t opt = U_FOLD_CASE_DEFAULT;
193121    UErrorCode status = U_ZERO_ERROR;
193122    int nChar;
193123  
193124    UChar32 c;
193125    int iInput = 0;
193126    int iOut = 0;
193127  
193128    *ppCursor = 0;
193129  
193130    if( zInput==0 ){
193131      nInput = 0;
193132      zInput = "";
193133    }else if( nInput<0 ){
193134      nInput = strlen(zInput);
193135    }
193136    nChar = nInput+1;
193137    pCsr = (IcuCursor *)sqlite3_malloc64(
193138        sizeof(IcuCursor) +                /* IcuCursor */
193139        ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
193140        (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
193141    );
193142    if( !pCsr ){
193143      return SQLITE_NOMEM;
193144    }
193145    memset(pCsr, 0, sizeof(IcuCursor));
193146    pCsr->aChar = (UChar *)&pCsr[1];
193147    pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
193148  
193149    pCsr->aOffset[iOut] = iInput;
193150    U8_NEXT(zInput, iInput, nInput, c); 
193151    while( c>0 ){
193152      int isError = 0;
193153      c = u_foldCase(c, opt);
193154      U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
193155      if( isError ){
193156        sqlite3_free(pCsr);
193157        return SQLITE_ERROR;
193158      }
193159      pCsr->aOffset[iOut] = iInput;
193160  
193161      if( iInput<nInput ){
193162        U8_NEXT(zInput, iInput, nInput, c);
193163      }else{
193164        c = 0;
193165      }
193166    }
193167  
193168    pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
193169    if( !U_SUCCESS(status) ){
193170      sqlite3_free(pCsr);
193171      return SQLITE_ERROR;
193172    }
193173    pCsr->nChar = iOut;
193174  
193175    ubrk_first(pCsr->pIter);
193176    *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
193177    return SQLITE_OK;
193178  }
193179  
193180  /*
193181  ** Close a tokenization cursor previously opened by a call to icuOpen().
193182  */
193183  static int icuClose(sqlite3_tokenizer_cursor *pCursor){
193184    IcuCursor *pCsr = (IcuCursor *)pCursor;
193185    ubrk_close(pCsr->pIter);
193186    sqlite3_free(pCsr->zBuffer);
193187    sqlite3_free(pCsr);
193188    return SQLITE_OK;
193189  }
193190  
193191  /*
193192  ** Extract the next token from a tokenization cursor.
193193  */
193194  static int icuNext(
193195    sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
193196    const char **ppToken,               /* OUT: *ppToken is the token text */
193197    int *pnBytes,                       /* OUT: Number of bytes in token */
193198    int *piStartOffset,                 /* OUT: Starting offset of token */
193199    int *piEndOffset,                   /* OUT: Ending offset of token */
193200    int *piPosition                     /* OUT: Position integer of token */
193201  ){
193202    IcuCursor *pCsr = (IcuCursor *)pCursor;
193203  
193204    int iStart = 0;
193205    int iEnd = 0;
193206    int nByte = 0;
193207  
193208    while( iStart==iEnd ){
193209      UChar32 c;
193210  
193211      iStart = ubrk_current(pCsr->pIter);
193212      iEnd = ubrk_next(pCsr->pIter);
193213      if( iEnd==UBRK_DONE ){
193214        return SQLITE_DONE;
193215      }
193216  
193217      while( iStart<iEnd ){
193218        int iWhite = iStart;
193219        U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
193220        if( u_isspace(c) ){
193221          iStart = iWhite;
193222        }else{
193223          break;
193224        }
193225      }
193226      assert(iStart<=iEnd);
193227    }
193228  
193229    do {
193230      UErrorCode status = U_ZERO_ERROR;
193231      if( nByte ){
193232        char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
193233        if( !zNew ){
193234          return SQLITE_NOMEM;
193235        }
193236        pCsr->zBuffer = zNew;
193237        pCsr->nBuffer = nByte;
193238      }
193239  
193240      u_strToUTF8(
193241          pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
193242          &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
193243          &status                                  /* Output success/failure */
193244      );
193245    } while( nByte>pCsr->nBuffer );
193246  
193247    *ppToken = pCsr->zBuffer;
193248    *pnBytes = nByte;
193249    *piStartOffset = pCsr->aOffset[iStart];
193250    *piEndOffset = pCsr->aOffset[iEnd];
193251    *piPosition = pCsr->iToken++;
193252  
193253    return SQLITE_OK;
193254  }
193255  
193256  /*
193257  ** The set of routines that implement the simple tokenizer
193258  */
193259  static const sqlite3_tokenizer_module icuTokenizerModule = {
193260    0,                           /* iVersion    */
193261    icuCreate,                   /* xCreate     */
193262    icuDestroy,                  /* xCreate     */
193263    icuOpen,                     /* xOpen       */
193264    icuClose,                    /* xClose      */
193265    icuNext,                     /* xNext       */
193266    0,                           /* xLanguageid */
193267  };
193268  
193269  /*
193270  ** Set *ppModule to point at the implementation of the ICU tokenizer.
193271  */
193272  SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
193273    sqlite3_tokenizer_module const**ppModule
193274  ){
193275    *ppModule = &icuTokenizerModule;
193276  }
193277  
193278  #endif /* defined(SQLITE_ENABLE_ICU) */
193279  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
193280  
193281  /************** End of fts3_icu.c ********************************************/
193282  /************** Begin file sqlite3rbu.c **************************************/
193283  /*
193284  ** 2014 August 30
193285  **
193286  ** The author disclaims copyright to this source code.  In place of
193287  ** a legal notice, here is a blessing:
193288  **
193289  **    May you do good and not evil.
193290  **    May you find forgiveness for yourself and forgive others.
193291  **    May you share freely, never taking more than you give.
193292  **
193293  *************************************************************************
193294  **
193295  **
193296  ** OVERVIEW 
193297  **
193298  **  The RBU extension requires that the RBU update be packaged as an
193299  **  SQLite database. The tables it expects to find are described in
193300  **  sqlite3rbu.h.  Essentially, for each table xyz in the target database
193301  **  that the user wishes to write to, a corresponding data_xyz table is
193302  **  created in the RBU database and populated with one row for each row to
193303  **  update, insert or delete from the target table.
193304  ** 
193305  **  The update proceeds in three stages:
193306  ** 
193307  **  1) The database is updated. The modified database pages are written
193308  **     to a *-oal file. A *-oal file is just like a *-wal file, except
193309  **     that it is named "<database>-oal" instead of "<database>-wal".
193310  **     Because regular SQLite clients do not look for file named
193311  **     "<database>-oal", they go on using the original database in
193312  **     rollback mode while the *-oal file is being generated.
193313  ** 
193314  **     During this stage RBU does not update the database by writing
193315  **     directly to the target tables. Instead it creates "imposter"
193316  **     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
193317  **     to update each b-tree individually. All updates required by each
193318  **     b-tree are completed before moving on to the next, and all
193319  **     updates are done in sorted key order.
193320  ** 
193321  **  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
193322  **     location using a call to rename(2). Before doing this the RBU
193323  **     module takes an EXCLUSIVE lock on the database file, ensuring
193324  **     that there are no other active readers.
193325  ** 
193326  **     Once the EXCLUSIVE lock is released, any other database readers
193327  **     detect the new *-wal file and read the database in wal mode. At
193328  **     this point they see the new version of the database - including
193329  **     the updates made as part of the RBU update.
193330  ** 
193331  **  3) The new *-wal file is checkpointed. This proceeds in the same way 
193332  **     as a regular database checkpoint, except that a single frame is
193333  **     checkpointed each time sqlite3rbu_step() is called. If the RBU
193334  **     handle is closed before the entire *-wal file is checkpointed,
193335  **     the checkpoint progress is saved in the RBU database and the
193336  **     checkpoint can be resumed by another RBU client at some point in
193337  **     the future.
193338  **
193339  ** POTENTIAL PROBLEMS
193340  ** 
193341  **  The rename() call might not be portable. And RBU is not currently
193342  **  syncing the directory after renaming the file.
193343  **
193344  **  When state is saved, any commit to the *-oal file and the commit to
193345  **  the RBU update database are not atomic. So if the power fails at the
193346  **  wrong moment they might get out of sync. As the main database will be
193347  **  committed before the RBU update database this will likely either just
193348  **  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
193349  **  constraint violations).
193350  **
193351  **  If some client does modify the target database mid RBU update, or some
193352  **  other error occurs, the RBU extension will keep throwing errors. It's
193353  **  not really clear how to get out of this state. The system could just
193354  **  by delete the RBU update database and *-oal file and have the device
193355  **  download the update again and start over.
193356  **
193357  **  At present, for an UPDATE, both the new.* and old.* records are
193358  **  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
193359  **  fields are collected.  This means we're probably writing a lot more
193360  **  data to disk when saving the state of an ongoing update to the RBU
193361  **  update database than is strictly necessary.
193362  ** 
193363  */
193364  
193365  /* #include <assert.h> */
193366  /* #include <string.h> */
193367  /* #include <stdio.h> */
193368  
193369  /* #include "sqlite3.h" */
193370  
193371  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
193372  /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
193373  /************** Begin file sqlite3rbu.h **************************************/
193374  /*
193375  ** 2014 August 30
193376  **
193377  ** The author disclaims copyright to this source code.  In place of
193378  ** a legal notice, here is a blessing:
193379  **
193380  **    May you do good and not evil.
193381  **    May you find forgiveness for yourself and forgive others.
193382  **    May you share freely, never taking more than you give.
193383  **
193384  *************************************************************************
193385  **
193386  ** This file contains the public interface for the RBU extension. 
193387  */
193388  
193389  /*
193390  ** SUMMARY
193391  **
193392  ** Writing a transaction containing a large number of operations on 
193393  ** b-tree indexes that are collectively larger than the available cache
193394  ** memory can be very inefficient. 
193395  **
193396  ** The problem is that in order to update a b-tree, the leaf page (at least)
193397  ** containing the entry being inserted or deleted must be modified. If the
193398  ** working set of leaves is larger than the available cache memory, then a 
193399  ** single leaf that is modified more than once as part of the transaction 
193400  ** may be loaded from or written to the persistent media multiple times.
193401  ** Additionally, because the index updates are likely to be applied in
193402  ** random order, access to pages within the database is also likely to be in 
193403  ** random order, which is itself quite inefficient.
193404  **
193405  ** One way to improve the situation is to sort the operations on each index
193406  ** by index key before applying them to the b-tree. This leads to an IO
193407  ** pattern that resembles a single linear scan through the index b-tree,
193408  ** and all but guarantees each modified leaf page is loaded and stored 
193409  ** exactly once. SQLite uses this trick to improve the performance of
193410  ** CREATE INDEX commands. This extension allows it to be used to improve
193411  ** the performance of large transactions on existing databases.
193412  **
193413  ** Additionally, this extension allows the work involved in writing the 
193414  ** large transaction to be broken down into sub-transactions performed 
193415  ** sequentially by separate processes. This is useful if the system cannot 
193416  ** guarantee that a single update process will run for long enough to apply 
193417  ** the entire update, for example because the update is being applied on a 
193418  ** mobile device that is frequently rebooted. Even after the writer process 
193419  ** has committed one or more sub-transactions, other database clients continue
193420  ** to read from the original database snapshot. In other words, partially 
193421  ** applied transactions are not visible to other clients. 
193422  **
193423  ** "RBU" stands for "Resumable Bulk Update". As in a large database update
193424  ** transmitted via a wireless network to a mobile device. A transaction
193425  ** applied using this extension is hence refered to as an "RBU update".
193426  **
193427  **
193428  ** LIMITATIONS
193429  **
193430  ** An "RBU update" transaction is subject to the following limitations:
193431  **
193432  **   * The transaction must consist of INSERT, UPDATE and DELETE operations
193433  **     only.
193434  **
193435  **   * INSERT statements may not use any default values.
193436  **
193437  **   * UPDATE and DELETE statements must identify their target rows by 
193438  **     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
193439  **     KEY fields may not be updated or deleted. If the table being written 
193440  **     has no PRIMARY KEY, affected rows must be identified by rowid.
193441  **
193442  **   * UPDATE statements may not modify PRIMARY KEY columns.
193443  **
193444  **   * No triggers will be fired.
193445  **
193446  **   * No foreign key violations are detected or reported.
193447  **
193448  **   * CHECK constraints are not enforced.
193449  **
193450  **   * No constraint handling mode except for "OR ROLLBACK" is supported.
193451  **
193452  **
193453  ** PREPARATION
193454  **
193455  ** An "RBU update" is stored as a separate SQLite database. A database
193456  ** containing an RBU update is an "RBU database". For each table in the 
193457  ** target database to be updated, the RBU database should contain a table
193458  ** named "data_<target name>" containing the same set of columns as the
193459  ** target table, and one more - "rbu_control". The data_% table should 
193460  ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
193461  ** the same type as the corresponding column in the target database.
193462  ** The "rbu_control" column should have no type at all. For example, if
193463  ** the target database contains:
193464  **
193465  **   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
193466  **
193467  ** Then the RBU database should contain:
193468  **
193469  **   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
193470  **
193471  ** The order of the columns in the data_% table does not matter.
193472  **
193473  ** Instead of a regular table, the RBU database may also contain virtual
193474  ** tables or view named using the data_<target> naming scheme. 
193475  **
193476  ** Instead of the plain data_<target> naming scheme, RBU database tables 
193477  ** may also be named data<integer>_<target>, where <integer> is any sequence
193478  ** of zero or more numeric characters (0-9). This can be significant because
193479  ** tables within the RBU database are always processed in order sorted by 
193480  ** name. By judicious selection of the <integer> portion of the names
193481  ** of the RBU tables the user can therefore control the order in which they
193482  ** are processed. This can be useful, for example, to ensure that "external
193483  ** content" FTS4 tables are updated before their underlying content tables.
193484  **
193485  ** If the target database table is a virtual table or a table that has no
193486  ** PRIMARY KEY declaration, the data_% table must also contain a column 
193487  ** named "rbu_rowid". This column is mapped to the tables implicit primary 
193488  ** key column - "rowid". Virtual tables for which the "rowid" column does 
193489  ** not function like a primary key value cannot be updated using RBU. For 
193490  ** example, if the target db contains either of the following:
193491  **
193492  **   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
193493  **   CREATE TABLE x1(a, b)
193494  **
193495  ** then the RBU database should contain:
193496  **
193497  **   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
193498  **
193499  ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
193500  ** target table must be present in the input table. For virtual tables,
193501  ** hidden columns are optional - they are updated by RBU if present in
193502  ** the input table, or not otherwise. For example, to write to an fts4
193503  ** table with a hidden languageid column such as:
193504  **
193505  **   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
193506  **
193507  ** Either of the following input table schemas may be used:
193508  **
193509  **   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
193510  **   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
193511  **
193512  ** For each row to INSERT into the target database as part of the RBU 
193513  ** update, the corresponding data_% table should contain a single record
193514  ** with the "rbu_control" column set to contain integer value 0. The
193515  ** other columns should be set to the values that make up the new record 
193516  ** to insert. 
193517  **
193518  ** If the target database table has an INTEGER PRIMARY KEY, it is not 
193519  ** possible to insert a NULL value into the IPK column. Attempting to 
193520  ** do so results in an SQLITE_MISMATCH error.
193521  **
193522  ** For each row to DELETE from the target database as part of the RBU 
193523  ** update, the corresponding data_% table should contain a single record
193524  ** with the "rbu_control" column set to contain integer value 1. The
193525  ** real primary key values of the row to delete should be stored in the
193526  ** corresponding columns of the data_% table. The values stored in the
193527  ** other columns are not used.
193528  **
193529  ** For each row to UPDATE from the target database as part of the RBU 
193530  ** update, the corresponding data_% table should contain a single record
193531  ** with the "rbu_control" column set to contain a value of type text.
193532  ** The real primary key values identifying the row to update should be 
193533  ** stored in the corresponding columns of the data_% table row, as should
193534  ** the new values of all columns being update. The text value in the 
193535  ** "rbu_control" column must contain the same number of characters as
193536  ** there are columns in the target database table, and must consist entirely
193537  ** of 'x' and '.' characters (or in some special cases 'd' - see below). For 
193538  ** each column that is being updated, the corresponding character is set to
193539  ** 'x'. For those that remain as they are, the corresponding character of the
193540  ** rbu_control value should be set to '.'. For example, given the tables 
193541  ** above, the update statement:
193542  **
193543  **   UPDATE t1 SET c = 'usa' WHERE a = 4;
193544  **
193545  ** is represented by the data_t1 row created by:
193546  **
193547  **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
193548  **
193549  ** Instead of an 'x' character, characters of the rbu_control value specified
193550  ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
193551  ** target table with the value stored in the corresponding data_% column, the
193552  ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
193553  ** the target table column. rbu_delta() is invoked with two arguments - the
193554  ** original value currently stored in the target table column and the 
193555  ** value specified in the data_xxx table.
193556  **
193557  ** For example, this row:
193558  **
193559  **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
193560  **
193561  ** is similar to an UPDATE statement such as: 
193562  **
193563  **   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
193564  **
193565  ** Finally, if an 'f' character appears in place of a 'd' or 's' in an 
193566  ** ota_control string, the contents of the data_xxx table column is assumed
193567  ** to be a "fossil delta" - a patch to be applied to a blob value in the
193568  ** format used by the fossil source-code management system. In this case
193569  ** the existing value within the target database table must be of type BLOB. 
193570  ** It is replaced by the result of applying the specified fossil delta to
193571  ** itself.
193572  **
193573  ** If the target database table is a virtual table or a table with no PRIMARY
193574  ** KEY, the rbu_control value should not include a character corresponding 
193575  ** to the rbu_rowid value. For example, this:
193576  **
193577  **   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) 
193578  **       VALUES(NULL, 'usa', 12, '.x');
193579  **
193580  ** causes a result similar to:
193581  **
193582  **   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
193583  **
193584  ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
193585  ** However, RBU is more efficient if reading the rows in from each data_xxx
193586  ** table in "rowid" order is roughly the same as reading them sorted by
193587  ** the PRIMARY KEY of the corresponding target database table. In other 
193588  ** words, rows should be sorted using the destination table PRIMARY KEY 
193589  ** fields before they are inserted into the data_xxx tables.
193590  **
193591  ** USAGE
193592  **
193593  ** The API declared below allows an application to apply an RBU update 
193594  ** stored on disk to an existing target database. Essentially, the 
193595  ** application:
193596  **
193597  **     1) Opens an RBU handle using the sqlite3rbu_open() function.
193598  **
193599  **     2) Registers any required virtual table modules with the database
193600  **        handle returned by sqlite3rbu_db(). Also, if required, register
193601  **        the rbu_delta() implementation.
193602  **
193603  **     3) Calls the sqlite3rbu_step() function one or more times on
193604  **        the new handle. Each call to sqlite3rbu_step() performs a single
193605  **        b-tree operation, so thousands of calls may be required to apply 
193606  **        a complete update.
193607  **
193608  **     4) Calls sqlite3rbu_close() to close the RBU update handle. If
193609  **        sqlite3rbu_step() has been called enough times to completely
193610  **        apply the update to the target database, then the RBU database
193611  **        is marked as fully applied. Otherwise, the state of the RBU 
193612  **        update application is saved in the RBU database for later 
193613  **        resumption.
193614  **
193615  ** See comments below for more detail on APIs.
193616  **
193617  ** If an update is only partially applied to the target database by the
193618  ** time sqlite3rbu_close() is called, various state information is saved 
193619  ** within the RBU database. This allows subsequent processes to automatically
193620  ** resume the RBU update from where it left off.
193621  **
193622  ** To remove all RBU extension state information, returning an RBU database 
193623  ** to its original contents, it is sufficient to drop all tables that begin
193624  ** with the prefix "rbu_"
193625  **
193626  ** DATABASE LOCKING
193627  **
193628  ** An RBU update may not be applied to a database in WAL mode. Attempting
193629  ** to do so is an error (SQLITE_ERROR).
193630  **
193631  ** While an RBU handle is open, a SHARED lock may be held on the target
193632  ** database file. This means it is possible for other clients to read the
193633  ** database, but not to write it.
193634  **
193635  ** If an RBU update is started and then suspended before it is completed,
193636  ** then an external client writes to the database, then attempting to resume
193637  ** the suspended RBU update is also an error (SQLITE_BUSY).
193638  */
193639  
193640  #ifndef _SQLITE3RBU_H
193641  #define _SQLITE3RBU_H
193642  
193643  /* #include "sqlite3.h"              ** Required for error code definitions ** */
193644  
193645  #if 0
193646  extern "C" {
193647  #endif
193648  
193649  typedef struct sqlite3rbu sqlite3rbu;
193650  
193651  /*
193652  ** Open an RBU handle.
193653  **
193654  ** Argument zTarget is the path to the target database. Argument zRbu is
193655  ** the path to the RBU database. Each call to this function must be matched
193656  ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
193657  ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
193658  ** or zRbu begin with "file:", it will be interpreted as an SQLite 
193659  ** database URI, not a regular file name.
193660  **
193661  ** If the zState argument is passed a NULL value, the RBU extension stores 
193662  ** the current state of the update (how many rows have been updated, which 
193663  ** indexes are yet to be updated etc.) within the RBU database itself. This
193664  ** can be convenient, as it means that the RBU application does not need to
193665  ** organize removing a separate state file after the update is concluded. 
193666  ** Or, if zState is non-NULL, it must be a path to a database file in which 
193667  ** the RBU extension can store the state of the update.
193668  **
193669  ** When resuming an RBU update, the zState argument must be passed the same
193670  ** value as when the RBU update was started.
193671  **
193672  ** Once the RBU update is finished, the RBU extension does not 
193673  ** automatically remove any zState database file, even if it created it.
193674  **
193675  ** By default, RBU uses the default VFS to access the files on disk. To
193676  ** use a VFS other than the default, an SQLite "file:" URI containing a
193677  ** "vfs=..." option may be passed as the zTarget option.
193678  **
193679  ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
193680  ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
193681  ** not work out of the box with zipvfs. Refer to the comment describing
193682  ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
193683  */
193684  SQLITE_API sqlite3rbu *sqlite3rbu_open(
193685    const char *zTarget, 
193686    const char *zRbu,
193687    const char *zState
193688  );
193689  
193690  /*
193691  ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
193692  ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
193693  ** that it can be suspended and resumed like an RBU update.
193694  **
193695  ** The second argument to this function identifies a database in which 
193696  ** to store the state of the RBU vacuum operation if it is suspended. The 
193697  ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
193698  ** operation, the state database should either not exist or be empty
193699  ** (contain no tables). If an RBU vacuum is suspended by calling 
193700  ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
193701  ** returned SQLITE_DONE, the vacuum state is stored in the state database. 
193702  ** The vacuum can be resumed by calling this function to open a new RBU
193703  ** handle specifying the same target and state databases.
193704  **
193705  ** If the second argument passed to this function is NULL, then the
193706  ** name of the state database is "<database>-vacuum", where <database>
193707  ** is the name of the target database file. In this case, on UNIX, if the
193708  ** state database is not already present in the file-system, it is created
193709  ** with the same permissions as the target db is made. 
193710  **
193711  ** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the 
193712  ** state database ends with "-vactmp". This name is reserved for internal 
193713  ** use.
193714  **
193715  ** This function does not delete the state database after an RBU vacuum
193716  ** is completed, even if it created it. However, if the call to
193717  ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
193718  ** of the state tables within the state database are zeroed. This way,
193719  ** the next call to sqlite3rbu_vacuum() opens a handle that starts a 
193720  ** new RBU vacuum operation.
193721  **
193722  ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
193723  ** describing the sqlite3rbu_create_vfs() API function below for 
193724  ** a description of the complications associated with using RBU with 
193725  ** zipvfs databases.
193726  */
193727  SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
193728    const char *zTarget, 
193729    const char *zState
193730  );
193731  
193732  /*
193733  ** Configure a limit for the amount of temp space that may be used by
193734  ** the RBU handle passed as the first argument. The new limit is specified
193735  ** in bytes by the second parameter. If it is positive, the limit is updated.
193736  ** If the second parameter to this function is passed zero, then the limit
193737  ** is removed entirely. If the second parameter is negative, the limit is
193738  ** not modified (this is useful for querying the current limit).
193739  **
193740  ** In all cases the returned value is the current limit in bytes (zero 
193741  ** indicates unlimited).
193742  **
193743  ** If the temp space limit is exceeded during operation, an SQLITE_FULL
193744  ** error is returned.
193745  */
193746  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
193747  
193748  /*
193749  ** Return the current amount of temp file space, in bytes, currently used by 
193750  ** the RBU handle passed as the only argument.
193751  */
193752  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
193753  
193754  /*
193755  ** Internally, each RBU connection uses a separate SQLite database 
193756  ** connection to access the target and rbu update databases. This
193757  ** API allows the application direct access to these database handles.
193758  **
193759  ** The first argument passed to this function must be a valid, open, RBU
193760  ** handle. The second argument should be passed zero to access the target
193761  ** database handle, or non-zero to access the rbu update database handle.
193762  ** Accessing the underlying database handles may be useful in the
193763  ** following scenarios:
193764  **
193765  **   * If any target tables are virtual tables, it may be necessary to
193766  **     call sqlite3_create_module() on the target database handle to 
193767  **     register the required virtual table implementations.
193768  **
193769  **   * If the data_xxx tables in the RBU source database are virtual 
193770  **     tables, the application may need to call sqlite3_create_module() on
193771  **     the rbu update db handle to any required virtual table
193772  **     implementations.
193773  **
193774  **   * If the application uses the "rbu_delta()" feature described above,
193775  **     it must use sqlite3_create_function() or similar to register the
193776  **     rbu_delta() implementation with the target database handle.
193777  **
193778  ** If an error has occurred, either while opening or stepping the RBU object,
193779  ** this function may return NULL. The error code and message may be collected
193780  ** when sqlite3rbu_close() is called.
193781  **
193782  ** Database handles returned by this function remain valid until the next
193783  ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
193784  */
193785  SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
193786  
193787  /*
193788  ** Do some work towards applying the RBU update to the target db. 
193789  **
193790  ** Return SQLITE_DONE if the update has been completely applied, or 
193791  ** SQLITE_OK if no error occurs but there remains work to do to apply
193792  ** the RBU update. If an error does occur, some other error code is 
193793  ** returned. 
193794  **
193795  ** Once a call to sqlite3rbu_step() has returned a value other than
193796  ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
193797  ** that immediately return the same value.
193798  */
193799  SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
193800  
193801  /*
193802  ** Force RBU to save its state to disk.
193803  **
193804  ** If a power failure or application crash occurs during an update, following
193805  ** system recovery RBU may resume the update from the point at which the state
193806  ** was last saved. In other words, from the most recent successful call to 
193807  ** sqlite3rbu_close() or this function.
193808  **
193809  ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
193810  */
193811  SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
193812  
193813  /*
193814  ** Close an RBU handle. 
193815  **
193816  ** If the RBU update has been completely applied, mark the RBU database
193817  ** as fully applied. Otherwise, assuming no error has occurred, save the
193818  ** current state of the RBU update appliation to the RBU database.
193819  **
193820  ** If an error has already occurred as part of an sqlite3rbu_step()
193821  ** or sqlite3rbu_open() call, or if one occurs within this function, an
193822  ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
193823  ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
193824  ** English language error message. It is the responsibility of the caller to
193825  ** eventually free any such buffer using sqlite3_free().
193826  **
193827  ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
193828  ** update has been partially applied, or SQLITE_DONE if it has been 
193829  ** completely applied.
193830  */
193831  SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
193832  
193833  /*
193834  ** Return the total number of key-value operations (inserts, deletes or 
193835  ** updates) that have been performed on the target database since the
193836  ** current RBU update was started.
193837  */
193838  SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
193839  
193840  /*
193841  ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) 
193842  ** progress indications for the two stages of an RBU update. This API may
193843  ** be useful for driving GUI progress indicators and similar.
193844  **
193845  ** An RBU update is divided into two stages:
193846  **
193847  **   * Stage 1, in which changes are accumulated in an oal/wal file, and
193848  **   * Stage 2, in which the contents of the wal file are copied into the
193849  **     main database.
193850  **
193851  ** The update is visible to non-RBU clients during stage 2. During stage 1
193852  ** non-RBU reader clients may see the original database.
193853  **
193854  ** If this API is called during stage 2 of the update, output variable 
193855  ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
193856  ** to a value between 0 and 10000 to indicate the permyriadage progress of
193857  ** stage 2. A value of 5000 indicates that stage 2 is half finished, 
193858  ** 9000 indicates that it is 90% finished, and so on.
193859  **
193860  ** If this API is called during stage 1 of the update, output variable 
193861  ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
193862  ** value to which (*pnOne) is set depends on whether or not the RBU 
193863  ** database contains an "rbu_count" table. The rbu_count table, if it 
193864  ** exists, must contain the same columns as the following:
193865  **
193866  **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
193867  **
193868  ** There must be one row in the table for each source (data_xxx) table within
193869  ** the RBU database. The 'tbl' column should contain the name of the source
193870  ** table. The 'cnt' column should contain the number of rows within the
193871  ** source table.
193872  **
193873  ** If the rbu_count table is present and populated correctly and this
193874  ** API is called during stage 1, the *pnOne output variable is set to the
193875  ** permyriadage progress of the same stage. If the rbu_count table does
193876  ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
193877  ** table exists but is not correctly populated, the value of the *pnOne
193878  ** output variable during stage 1 is undefined.
193879  */
193880  SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
193881  
193882  /*
193883  ** Obtain an indication as to the current stage of an RBU update or vacuum.
193884  ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
193885  ** defined in this file. Return values should be interpreted as follows:
193886  **
193887  ** SQLITE_RBU_STATE_OAL:
193888  **   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
193889  **   may either add further data to the *-oal file, or compute data that will
193890  **   be added by a subsequent call.
193891  **
193892  ** SQLITE_RBU_STATE_MOVE:
193893  **   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
193894  **   will move the *-oal file to the equivalent *-wal path. If the current
193895  **   operation is an RBU update, then the updated version of the database
193896  **   file will become visible to ordinary SQLite clients following the next
193897  **   call to sqlite3rbu_step().
193898  **
193899  ** SQLITE_RBU_STATE_CHECKPOINT:
193900  **   RBU is currently performing an incremental checkpoint. The next call to
193901  **   sqlite3rbu_step() will copy a page of data from the *-wal file into
193902  **   the target database file.
193903  **
193904  ** SQLITE_RBU_STATE_DONE:
193905  **   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
193906  **   will immediately return SQLITE_DONE.
193907  **
193908  ** SQLITE_RBU_STATE_ERROR:
193909  **   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
193910  **   immediately return the SQLite error code associated with the error.
193911  */
193912  #define SQLITE_RBU_STATE_OAL        1
193913  #define SQLITE_RBU_STATE_MOVE       2
193914  #define SQLITE_RBU_STATE_CHECKPOINT 3
193915  #define SQLITE_RBU_STATE_DONE       4
193916  #define SQLITE_RBU_STATE_ERROR      5
193917  
193918  SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
193919  
193920  /*
193921  ** Create an RBU VFS named zName that accesses the underlying file-system
193922  ** via existing VFS zParent. Or, if the zParent parameter is passed NULL, 
193923  ** then the new RBU VFS uses the default system VFS to access the file-system.
193924  ** The new object is registered as a non-default VFS with SQLite before 
193925  ** returning.
193926  **
193927  ** Part of the RBU implementation uses a custom VFS object. Usually, this
193928  ** object is created and deleted automatically by RBU. 
193929  **
193930  ** The exception is for applications that also use zipvfs. In this case,
193931  ** the custom VFS must be explicitly created by the user before the RBU
193932  ** handle is opened. The RBU VFS should be installed so that the zipvfs
193933  ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use 
193934  ** (for example multiplexor) to access the file-system. For example,
193935  ** to assemble an RBU enabled VFS stack that uses both zipvfs and 
193936  ** multiplexor (error checking omitted):
193937  **
193938  **     // Create a VFS named "multiplex" (not the default).
193939  **     sqlite3_multiplex_initialize(0, 0);
193940  **
193941  **     // Create an rbu VFS named "rbu" that uses multiplexor. If the
193942  **     // second argument were replaced with NULL, the "rbu" VFS would
193943  **     // access the file-system via the system default VFS, bypassing the
193944  **     // multiplexor.
193945  **     sqlite3rbu_create_vfs("rbu", "multiplex");
193946  **
193947  **     // Create a zipvfs VFS named "zipvfs" that uses rbu.
193948  **     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
193949  **
193950  **     // Make zipvfs the default VFS.
193951  **     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
193952  **
193953  ** Because the default VFS created above includes a RBU functionality, it
193954  ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
193955  ** that does not include the RBU layer results in an error.
193956  **
193957  ** The overhead of adding the "rbu" VFS to the system is negligible for 
193958  ** non-RBU users. There is no harm in an application accessing the 
193959  ** file-system via "rbu" all the time, even if it only uses RBU functionality 
193960  ** occasionally.
193961  */
193962  SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
193963  
193964  /*
193965  ** Deregister and destroy an RBU vfs created by an earlier call to
193966  ** sqlite3rbu_create_vfs().
193967  **
193968  ** VFS objects are not reference counted. If a VFS object is destroyed
193969  ** before all database handles that use it have been closed, the results
193970  ** are undefined.
193971  */
193972  SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
193973  
193974  #if 0
193975  }  /* end of the 'extern "C"' block */
193976  #endif
193977  
193978  #endif /* _SQLITE3RBU_H */
193979  
193980  /************** End of sqlite3rbu.h ******************************************/
193981  /************** Continuing where we left off in sqlite3rbu.c *****************/
193982  
193983  #if defined(_WIN32_WCE)
193984  /* #include "windows.h" */
193985  #endif
193986  
193987  /* Maximum number of prepared UPDATE statements held by this module */
193988  #define SQLITE_RBU_UPDATE_CACHESIZE 16
193989  
193990  /* Delta checksums disabled by default.  Compile with -DRBU_ENABLE_DELTA_CKSUM
193991  ** to enable checksum verification.
193992  */
193993  #ifndef RBU_ENABLE_DELTA_CKSUM
193994  # define RBU_ENABLE_DELTA_CKSUM 0
193995  #endif
193996  
193997  /*
193998  ** Swap two objects of type TYPE.
193999  */
194000  #if !defined(SQLITE_AMALGAMATION)
194001  # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
194002  #endif
194003  
194004  /*
194005  ** The rbu_state table is used to save the state of a partially applied
194006  ** update so that it can be resumed later. The table consists of integer
194007  ** keys mapped to values as follows:
194008  **
194009  ** RBU_STATE_STAGE:
194010  **   May be set to integer values 1, 2, 4 or 5. As follows:
194011  **       1: the *-rbu file is currently under construction.
194012  **       2: the *-rbu file has been constructed, but not yet moved 
194013  **          to the *-wal path.
194014  **       4: the checkpoint is underway.
194015  **       5: the rbu update has been checkpointed.
194016  **
194017  ** RBU_STATE_TBL:
194018  **   Only valid if STAGE==1. The target database name of the table 
194019  **   currently being written.
194020  **
194021  ** RBU_STATE_IDX:
194022  **   Only valid if STAGE==1. The target database name of the index 
194023  **   currently being written, or NULL if the main table is currently being
194024  **   updated.
194025  **
194026  ** RBU_STATE_ROW:
194027  **   Only valid if STAGE==1. Number of rows already processed for the current
194028  **   table/index.
194029  **
194030  ** RBU_STATE_PROGRESS:
194031  **   Trbul number of sqlite3rbu_step() calls made so far as part of this
194032  **   rbu update.
194033  **
194034  ** RBU_STATE_CKPT:
194035  **   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
194036  **   header created by recovering the *-wal file. This is used to detect
194037  **   cases when another client appends frames to the *-wal file in the
194038  **   middle of an incremental checkpoint (an incremental checkpoint cannot
194039  **   be continued if this happens).
194040  **
194041  ** RBU_STATE_COOKIE:
194042  **   Valid if STAGE==1. The current change-counter cookie value in the 
194043  **   target db file.
194044  **
194045  ** RBU_STATE_OALSZ:
194046  **   Valid if STAGE==1. The size in bytes of the *-oal file.
194047  **
194048  ** RBU_STATE_DATATBL:
194049  **   Only valid if STAGE==1. The RBU database name of the table 
194050  **   currently being read.
194051  */
194052  #define RBU_STATE_STAGE        1
194053  #define RBU_STATE_TBL          2
194054  #define RBU_STATE_IDX          3
194055  #define RBU_STATE_ROW          4
194056  #define RBU_STATE_PROGRESS     5
194057  #define RBU_STATE_CKPT         6
194058  #define RBU_STATE_COOKIE       7
194059  #define RBU_STATE_OALSZ        8
194060  #define RBU_STATE_PHASEONESTEP 9
194061  #define RBU_STATE_DATATBL     10
194062  
194063  #define RBU_STAGE_OAL         1
194064  #define RBU_STAGE_MOVE        2
194065  #define RBU_STAGE_CAPTURE     3
194066  #define RBU_STAGE_CKPT        4
194067  #define RBU_STAGE_DONE        5
194068  
194069  
194070  #define RBU_CREATE_STATE \
194071    "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
194072  
194073  typedef struct RbuFrame RbuFrame;
194074  typedef struct RbuObjIter RbuObjIter;
194075  typedef struct RbuState RbuState;
194076  typedef struct rbu_vfs rbu_vfs;
194077  typedef struct rbu_file rbu_file;
194078  typedef struct RbuUpdateStmt RbuUpdateStmt;
194079  
194080  #if !defined(SQLITE_AMALGAMATION)
194081  typedef unsigned int u32;
194082  typedef unsigned short u16;
194083  typedef unsigned char u8;
194084  typedef sqlite3_int64 i64;
194085  #endif
194086  
194087  /*
194088  ** These values must match the values defined in wal.c for the equivalent
194089  ** locks. These are not magic numbers as they are part of the SQLite file
194090  ** format.
194091  */
194092  #define WAL_LOCK_WRITE  0
194093  #define WAL_LOCK_CKPT   1
194094  #define WAL_LOCK_READ0  3
194095  
194096  #define SQLITE_FCNTL_RBUCNT    5149216
194097  
194098  /*
194099  ** A structure to store values read from the rbu_state table in memory.
194100  */
194101  struct RbuState {
194102    int eStage;
194103    char *zTbl;
194104    char *zDataTbl;
194105    char *zIdx;
194106    i64 iWalCksum;
194107    int nRow;
194108    i64 nProgress;
194109    u32 iCookie;
194110    i64 iOalSz;
194111    i64 nPhaseOneStep;
194112  };
194113  
194114  struct RbuUpdateStmt {
194115    char *zMask;                    /* Copy of update mask used with pUpdate */
194116    sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
194117    RbuUpdateStmt *pNext;
194118  };
194119  
194120  /*
194121  ** An iterator of this type is used to iterate through all objects in
194122  ** the target database that require updating. For each such table, the
194123  ** iterator visits, in order:
194124  **
194125  **     * the table itself, 
194126  **     * each index of the table (zero or more points to visit), and
194127  **     * a special "cleanup table" state.
194128  **
194129  ** abIndexed:
194130  **   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
194131  **   it points to an array of flags nTblCol elements in size. The flag is
194132  **   set for each column that is either a part of the PK or a part of an
194133  **   index. Or clear otherwise.
194134  **   
194135  */
194136  struct RbuObjIter {
194137    sqlite3_stmt *pTblIter;         /* Iterate through tables */
194138    sqlite3_stmt *pIdxIter;         /* Index iterator */
194139    int nTblCol;                    /* Size of azTblCol[] array */
194140    char **azTblCol;                /* Array of unquoted target column names */
194141    char **azTblType;               /* Array of target column types */
194142    int *aiSrcOrder;                /* src table col -> target table col */
194143    u8 *abTblPk;                    /* Array of flags, set on target PK columns */
194144    u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
194145    u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
194146    int eType;                      /* Table type - an RBU_PK_XXX value */
194147  
194148    /* Output variables. zTbl==0 implies EOF. */
194149    int bCleanup;                   /* True in "cleanup" state */
194150    const char *zTbl;               /* Name of target db table */
194151    const char *zDataTbl;           /* Name of rbu db table (or null) */
194152    const char *zIdx;               /* Name of target db index (or null) */
194153    int iTnum;                      /* Root page of current object */
194154    int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
194155    int bUnique;                    /* Current index is unique */
194156    int nIndex;                     /* Number of aux. indexes on table zTbl */
194157  
194158    /* Statements created by rbuObjIterPrepareAll() */
194159    int nCol;                       /* Number of columns in current object */
194160    sqlite3_stmt *pSelect;          /* Source data */
194161    sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
194162    sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
194163    sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
194164  
194165    /* Last UPDATE used (for PK b-tree updates only), or NULL. */
194166    RbuUpdateStmt *pRbuUpdate;
194167  };
194168  
194169  /*
194170  ** Values for RbuObjIter.eType
194171  **
194172  **     0: Table does not exist (error)
194173  **     1: Table has an implicit rowid.
194174  **     2: Table has an explicit IPK column.
194175  **     3: Table has an external PK index.
194176  **     4: Table is WITHOUT ROWID.
194177  **     5: Table is a virtual table.
194178  */
194179  #define RBU_PK_NOTABLE        0
194180  #define RBU_PK_NONE           1
194181  #define RBU_PK_IPK            2
194182  #define RBU_PK_EXTERNAL       3
194183  #define RBU_PK_WITHOUT_ROWID  4
194184  #define RBU_PK_VTAB           5
194185  
194186  
194187  /*
194188  ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
194189  ** one of the following operations.
194190  */
194191  #define RBU_INSERT     1          /* Insert on a main table b-tree */
194192  #define RBU_DELETE     2          /* Delete a row from a main table b-tree */
194193  #define RBU_REPLACE    3          /* Delete and then insert a row */
194194  #define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
194195  #define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
194196  
194197  #define RBU_UPDATE     6          /* Update a row in a main table b-tree */
194198  
194199  /*
194200  ** A single step of an incremental checkpoint - frame iWalFrame of the wal
194201  ** file should be copied to page iDbPage of the database file.
194202  */
194203  struct RbuFrame {
194204    u32 iDbPage;
194205    u32 iWalFrame;
194206  };
194207  
194208  /*
194209  ** RBU handle.
194210  **
194211  ** nPhaseOneStep:
194212  **   If the RBU database contains an rbu_count table, this value is set to
194213  **   a running estimate of the number of b-tree operations required to 
194214  **   finish populating the *-oal file. This allows the sqlite3_bp_progress()
194215  **   API to calculate the permyriadage progress of populating the *-oal file
194216  **   using the formula:
194217  **
194218  **     permyriadage = (10000 * nProgress) / nPhaseOneStep
194219  **
194220  **   nPhaseOneStep is initialized to the sum of:
194221  **
194222  **     nRow * (nIndex + 1)
194223  **
194224  **   for all source tables in the RBU database, where nRow is the number
194225  **   of rows in the source table and nIndex the number of indexes on the
194226  **   corresponding target database table.
194227  **
194228  **   This estimate is accurate if the RBU update consists entirely of
194229  **   INSERT operations. However, it is inaccurate if:
194230  **
194231  **     * the RBU update contains any UPDATE operations. If the PK specified
194232  **       for an UPDATE operation does not exist in the target table, then
194233  **       no b-tree operations are required on index b-trees. Or if the 
194234  **       specified PK does exist, then (nIndex*2) such operations are
194235  **       required (one delete and one insert on each index b-tree).
194236  **
194237  **     * the RBU update contains any DELETE operations for which the specified
194238  **       PK does not exist. In this case no operations are required on index
194239  **       b-trees.
194240  **
194241  **     * the RBU update contains REPLACE operations. These are similar to
194242  **       UPDATE operations.
194243  **
194244  **   nPhaseOneStep is updated to account for the conditions above during the
194245  **   first pass of each source table. The updated nPhaseOneStep value is
194246  **   stored in the rbu_state table if the RBU update is suspended.
194247  */
194248  struct sqlite3rbu {
194249    int eStage;                     /* Value of RBU_STATE_STAGE field */
194250    sqlite3 *dbMain;                /* target database handle */
194251    sqlite3 *dbRbu;                 /* rbu database handle */
194252    char *zTarget;                  /* Path to target db */
194253    char *zRbu;                     /* Path to rbu db */
194254    char *zState;                   /* Path to state db (or NULL if zRbu) */
194255    char zStateDb[5];               /* Db name for state ("stat" or "main") */
194256    int rc;                         /* Value returned by last rbu_step() call */
194257    char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
194258    int nStep;                      /* Rows processed for current object */
194259    int nProgress;                  /* Rows processed for all objects */
194260    RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
194261    const char *zVfsName;           /* Name of automatically created rbu vfs */
194262    rbu_file *pTargetFd;            /* File handle open on target db */
194263    int nPagePerSector;             /* Pages per sector for pTargetFd */
194264    i64 iOalSz;
194265    i64 nPhaseOneStep;
194266  
194267    /* The following state variables are used as part of the incremental
194268    ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
194269    ** function rbuSetupCheckpoint() for details.  */
194270    u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
194271    u32 mLock;
194272    int nFrame;                     /* Entries in aFrame[] array */
194273    int nFrameAlloc;                /* Allocated size of aFrame[] array */
194274    RbuFrame *aFrame;
194275    int pgsz;
194276    u8 *aBuf;
194277    i64 iWalCksum;
194278    i64 szTemp;                     /* Current size of all temp files in use */
194279    i64 szTempLimit;                /* Total size limit for temp files */
194280  
194281    /* Used in RBU vacuum mode only */
194282    int nRbu;                       /* Number of RBU VFS in the stack */
194283    rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
194284  };
194285  
194286  /*
194287  ** An rbu VFS is implemented using an instance of this structure.
194288  **
194289  ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
194290  ** It is NULL for RBU VFS objects created explicitly using
194291  ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
194292  ** space used by the RBU handle.
194293  */
194294  struct rbu_vfs {
194295    sqlite3_vfs base;               /* rbu VFS shim methods */
194296    sqlite3_vfs *pRealVfs;          /* Underlying VFS */
194297    sqlite3_mutex *mutex;           /* Mutex to protect pMain */
194298    sqlite3rbu *pRbu;               /* Owner RBU object */
194299    rbu_file *pMain;                /* List of main db files */
194300    rbu_file *pMainRbu;             /* List of main db files with pRbu!=0 */
194301  };
194302  
194303  /*
194304  ** Each file opened by an rbu VFS is represented by an instance of
194305  ** the following structure.
194306  **
194307  ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
194308  ** "sz" is set to the current size of the database file.
194309  */
194310  struct rbu_file {
194311    sqlite3_file base;              /* sqlite3_file methods */
194312    sqlite3_file *pReal;            /* Underlying file handle */
194313    rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
194314    sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
194315    i64 sz;                         /* Size of file in bytes (temp only) */
194316  
194317    int openFlags;                  /* Flags this file was opened with */
194318    u32 iCookie;                    /* Cookie value for main db files */
194319    u8 iWriteVer;                   /* "write-version" value for main db files */
194320    u8 bNolock;                     /* True to fail EXCLUSIVE locks */
194321  
194322    int nShm;                       /* Number of entries in apShm[] array */
194323    char **apShm;                   /* Array of mmap'd *-shm regions */
194324    char *zDel;                     /* Delete this when closing file */
194325  
194326    const char *zWal;               /* Wal filename for this main db file */
194327    rbu_file *pWalFd;               /* Wal file descriptor for this main db */
194328    rbu_file *pMainNext;            /* Next MAIN_DB file */
194329    rbu_file *pMainRbuNext;         /* Next MAIN_DB file with pRbu!=0 */
194330  };
194331  
194332  /*
194333  ** True for an RBU vacuum handle, or false otherwise.
194334  */
194335  #define rbuIsVacuum(p) ((p)->zTarget==0)
194336  
194337  
194338  /*************************************************************************
194339  ** The following three functions, found below:
194340  **
194341  **   rbuDeltaGetInt()
194342  **   rbuDeltaChecksum()
194343  **   rbuDeltaApply()
194344  **
194345  ** are lifted from the fossil source code (http://fossil-scm.org). They
194346  ** are used to implement the scalar SQL function rbu_fossil_delta().
194347  */
194348  
194349  /*
194350  ** Read bytes from *pz and convert them into a positive integer.  When
194351  ** finished, leave *pz pointing to the first character past the end of
194352  ** the integer.  The *pLen parameter holds the length of the string
194353  ** in *pz and is decremented once for each character in the integer.
194354  */
194355  static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
194356    static const signed char zValue[] = {
194357      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
194358      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
194359      -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
194360       0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
194361      -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
194362      25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
194363      -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
194364      52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
194365    };
194366    unsigned int v = 0;
194367    int c;
194368    unsigned char *z = (unsigned char*)*pz;
194369    unsigned char *zStart = z;
194370    while( (c = zValue[0x7f&*(z++)])>=0 ){
194371       v = (v<<6) + c;
194372    }
194373    z--;
194374    *pLen -= z - zStart;
194375    *pz = (char*)z;
194376    return v;
194377  }
194378  
194379  #if RBU_ENABLE_DELTA_CKSUM
194380  /*
194381  ** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
194382  */
194383  static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
194384    const unsigned char *z = (const unsigned char *)zIn;
194385    unsigned sum0 = 0;
194386    unsigned sum1 = 0;
194387    unsigned sum2 = 0;
194388    unsigned sum3 = 0;
194389    while(N >= 16){
194390      sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
194391      sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
194392      sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
194393      sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
194394      z += 16;
194395      N -= 16;
194396    }
194397    while(N >= 4){
194398      sum0 += z[0];
194399      sum1 += z[1];
194400      sum2 += z[2];
194401      sum3 += z[3];
194402      z += 4;
194403      N -= 4;
194404    }
194405    sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
194406    switch(N){
194407      case 3:   sum3 += (z[2] << 8);
194408      case 2:   sum3 += (z[1] << 16);
194409      case 1:   sum3 += (z[0] << 24);
194410      default:  ;
194411    }
194412    return sum3;
194413  }
194414  #endif
194415  
194416  /*
194417  ** Apply a delta.
194418  **
194419  ** The output buffer should be big enough to hold the whole output
194420  ** file and a NUL terminator at the end.  The delta_output_size()
194421  ** routine will determine this size for you.
194422  **
194423  ** The delta string should be null-terminated.  But the delta string
194424  ** may contain embedded NUL characters (if the input and output are
194425  ** binary files) so we also have to pass in the length of the delta in
194426  ** the lenDelta parameter.
194427  **
194428  ** This function returns the size of the output file in bytes (excluding
194429  ** the final NUL terminator character).  Except, if the delta string is
194430  ** malformed or intended for use with a source file other than zSrc,
194431  ** then this routine returns -1.
194432  **
194433  ** Refer to the delta_create() documentation above for a description
194434  ** of the delta file format.
194435  */
194436  static int rbuDeltaApply(
194437    const char *zSrc,      /* The source or pattern file */
194438    int lenSrc,            /* Length of the source file */
194439    const char *zDelta,    /* Delta to apply to the pattern */
194440    int lenDelta,          /* Length of the delta */
194441    char *zOut             /* Write the output into this preallocated buffer */
194442  ){
194443    unsigned int limit;
194444    unsigned int total = 0;
194445  #if RBU_ENABLE_DELTA_CKSUM
194446    char *zOrigOut = zOut;
194447  #endif
194448  
194449    limit = rbuDeltaGetInt(&zDelta, &lenDelta);
194450    if( *zDelta!='\n' ){
194451      /* ERROR: size integer not terminated by "\n" */
194452      return -1;
194453    }
194454    zDelta++; lenDelta--;
194455    while( *zDelta && lenDelta>0 ){
194456      unsigned int cnt, ofst;
194457      cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
194458      switch( zDelta[0] ){
194459        case '@': {
194460          zDelta++; lenDelta--;
194461          ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
194462          if( lenDelta>0 && zDelta[0]!=',' ){
194463            /* ERROR: copy command not terminated by ',' */
194464            return -1;
194465          }
194466          zDelta++; lenDelta--;
194467          total += cnt;
194468          if( total>limit ){
194469            /* ERROR: copy exceeds output file size */
194470            return -1;
194471          }
194472          if( (int)(ofst+cnt) > lenSrc ){
194473            /* ERROR: copy extends past end of input */
194474            return -1;
194475          }
194476          memcpy(zOut, &zSrc[ofst], cnt);
194477          zOut += cnt;
194478          break;
194479        }
194480        case ':': {
194481          zDelta++; lenDelta--;
194482          total += cnt;
194483          if( total>limit ){
194484            /* ERROR:  insert command gives an output larger than predicted */
194485            return -1;
194486          }
194487          if( (int)cnt>lenDelta ){
194488            /* ERROR: insert count exceeds size of delta */
194489            return -1;
194490          }
194491          memcpy(zOut, zDelta, cnt);
194492          zOut += cnt;
194493          zDelta += cnt;
194494          lenDelta -= cnt;
194495          break;
194496        }
194497        case ';': {
194498          zDelta++; lenDelta--;
194499          zOut[0] = 0;
194500  #if RBU_ENABLE_DELTA_CKSUM
194501          if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
194502            /* ERROR:  bad checksum */
194503            return -1;
194504          }
194505  #endif
194506          if( total!=limit ){
194507            /* ERROR: generated size does not match predicted size */
194508            return -1;
194509          }
194510          return total;
194511        }
194512        default: {
194513          /* ERROR: unknown delta operator */
194514          return -1;
194515        }
194516      }
194517    }
194518    /* ERROR: unterminated delta */
194519    return -1;
194520  }
194521  
194522  static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
194523    int size;
194524    size = rbuDeltaGetInt(&zDelta, &lenDelta);
194525    if( *zDelta!='\n' ){
194526      /* ERROR: size integer not terminated by "\n" */
194527      return -1;
194528    }
194529    return size;
194530  }
194531  
194532  /*
194533  ** End of code taken from fossil.
194534  *************************************************************************/
194535  
194536  /*
194537  ** Implementation of SQL scalar function rbu_fossil_delta().
194538  **
194539  ** This function applies a fossil delta patch to a blob. Exactly two
194540  ** arguments must be passed to this function. The first is the blob to
194541  ** patch and the second the patch to apply. If no error occurs, this
194542  ** function returns the patched blob.
194543  */
194544  static void rbuFossilDeltaFunc(
194545    sqlite3_context *context,
194546    int argc,
194547    sqlite3_value **argv
194548  ){
194549    const char *aDelta;
194550    int nDelta;
194551    const char *aOrig;
194552    int nOrig;
194553  
194554    int nOut;
194555    int nOut2;
194556    char *aOut;
194557  
194558    assert( argc==2 );
194559  
194560    nOrig = sqlite3_value_bytes(argv[0]);
194561    aOrig = (const char*)sqlite3_value_blob(argv[0]);
194562    nDelta = sqlite3_value_bytes(argv[1]);
194563    aDelta = (const char*)sqlite3_value_blob(argv[1]);
194564  
194565    /* Figure out the size of the output */
194566    nOut = rbuDeltaOutputSize(aDelta, nDelta);
194567    if( nOut<0 ){
194568      sqlite3_result_error(context, "corrupt fossil delta", -1);
194569      return;
194570    }
194571  
194572    aOut = sqlite3_malloc(nOut+1);
194573    if( aOut==0 ){
194574      sqlite3_result_error_nomem(context);
194575    }else{
194576      nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
194577      if( nOut2!=nOut ){
194578        sqlite3_result_error(context, "corrupt fossil delta", -1);
194579      }else{
194580        sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
194581      }
194582    }
194583  }
194584  
194585  
194586  /*
194587  ** Prepare the SQL statement in buffer zSql against database handle db.
194588  ** If successful, set *ppStmt to point to the new statement and return
194589  ** SQLITE_OK. 
194590  **
194591  ** Otherwise, if an error does occur, set *ppStmt to NULL and return
194592  ** an SQLite error code. Additionally, set output variable *pzErrmsg to
194593  ** point to a buffer containing an error message. It is the responsibility
194594  ** of the caller to (eventually) free this buffer using sqlite3_free().
194595  */
194596  static int prepareAndCollectError(
194597    sqlite3 *db, 
194598    sqlite3_stmt **ppStmt,
194599    char **pzErrmsg,
194600    const char *zSql
194601  ){
194602    int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
194603    if( rc!=SQLITE_OK ){
194604      *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
194605      *ppStmt = 0;
194606    }
194607    return rc;
194608  }
194609  
194610  /*
194611  ** Reset the SQL statement passed as the first argument. Return a copy
194612  ** of the value returned by sqlite3_reset().
194613  **
194614  ** If an error has occurred, then set *pzErrmsg to point to a buffer
194615  ** containing an error message. It is the responsibility of the caller
194616  ** to eventually free this buffer using sqlite3_free().
194617  */
194618  static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
194619    int rc = sqlite3_reset(pStmt);
194620    if( rc!=SQLITE_OK ){
194621      *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
194622    }
194623    return rc;
194624  }
194625  
194626  /*
194627  ** Unless it is NULL, argument zSql points to a buffer allocated using
194628  ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
194629  ** statement against database db and frees the buffer. If statement 
194630  ** compilation is successful, *ppStmt is set to point to the new statement 
194631  ** handle and SQLITE_OK is returned. 
194632  **
194633  ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
194634  ** returned. In this case, *pzErrmsg may also be set to point to an error
194635  ** message. It is the responsibility of the caller to free this error message
194636  ** buffer using sqlite3_free().
194637  **
194638  ** If argument zSql is NULL, this function assumes that an OOM has occurred.
194639  ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
194640  */
194641  static int prepareFreeAndCollectError(
194642    sqlite3 *db, 
194643    sqlite3_stmt **ppStmt,
194644    char **pzErrmsg,
194645    char *zSql
194646  ){
194647    int rc;
194648    assert( *pzErrmsg==0 );
194649    if( zSql==0 ){
194650      rc = SQLITE_NOMEM;
194651      *ppStmt = 0;
194652    }else{
194653      rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
194654      sqlite3_free(zSql);
194655    }
194656    return rc;
194657  }
194658  
194659  /*
194660  ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
194661  ** by an earlier call to rbuObjIterCacheTableInfo().
194662  */
194663  static void rbuObjIterFreeCols(RbuObjIter *pIter){
194664    int i;
194665    for(i=0; i<pIter->nTblCol; i++){
194666      sqlite3_free(pIter->azTblCol[i]);
194667      sqlite3_free(pIter->azTblType[i]);
194668    }
194669    sqlite3_free(pIter->azTblCol);
194670    pIter->azTblCol = 0;
194671    pIter->azTblType = 0;
194672    pIter->aiSrcOrder = 0;
194673    pIter->abTblPk = 0;
194674    pIter->abNotNull = 0;
194675    pIter->nTblCol = 0;
194676    pIter->eType = 0;               /* Invalid value */
194677  }
194678  
194679  /*
194680  ** Finalize all statements and free all allocations that are specific to
194681  ** the current object (table/index pair).
194682  */
194683  static void rbuObjIterClearStatements(RbuObjIter *pIter){
194684    RbuUpdateStmt *pUp;
194685  
194686    sqlite3_finalize(pIter->pSelect);
194687    sqlite3_finalize(pIter->pInsert);
194688    sqlite3_finalize(pIter->pDelete);
194689    sqlite3_finalize(pIter->pTmpInsert);
194690    pUp = pIter->pRbuUpdate;
194691    while( pUp ){
194692      RbuUpdateStmt *pTmp = pUp->pNext;
194693      sqlite3_finalize(pUp->pUpdate);
194694      sqlite3_free(pUp);
194695      pUp = pTmp;
194696    }
194697    
194698    pIter->pSelect = 0;
194699    pIter->pInsert = 0;
194700    pIter->pDelete = 0;
194701    pIter->pRbuUpdate = 0;
194702    pIter->pTmpInsert = 0;
194703    pIter->nCol = 0;
194704  }
194705  
194706  /*
194707  ** Clean up any resources allocated as part of the iterator object passed
194708  ** as the only argument.
194709  */
194710  static void rbuObjIterFinalize(RbuObjIter *pIter){
194711    rbuObjIterClearStatements(pIter);
194712    sqlite3_finalize(pIter->pTblIter);
194713    sqlite3_finalize(pIter->pIdxIter);
194714    rbuObjIterFreeCols(pIter);
194715    memset(pIter, 0, sizeof(RbuObjIter));
194716  }
194717  
194718  /*
194719  ** Advance the iterator to the next position.
194720  **
194721  ** If no error occurs, SQLITE_OK is returned and the iterator is left 
194722  ** pointing to the next entry. Otherwise, an error code and message is 
194723  ** left in the RBU handle passed as the first argument. A copy of the 
194724  ** error code is returned.
194725  */
194726  static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
194727    int rc = p->rc;
194728    if( rc==SQLITE_OK ){
194729  
194730      /* Free any SQLite statements used while processing the previous object */ 
194731      rbuObjIterClearStatements(pIter);
194732      if( pIter->zIdx==0 ){
194733        rc = sqlite3_exec(p->dbMain,
194734            "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
194735            "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
194736            "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
194737            "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
194738            , 0, 0, &p->zErrmsg
194739        );
194740      }
194741  
194742      if( rc==SQLITE_OK ){
194743        if( pIter->bCleanup ){
194744          rbuObjIterFreeCols(pIter);
194745          pIter->bCleanup = 0;
194746          rc = sqlite3_step(pIter->pTblIter);
194747          if( rc!=SQLITE_ROW ){
194748            rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
194749            pIter->zTbl = 0;
194750          }else{
194751            pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
194752            pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
194753            rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
194754          }
194755        }else{
194756          if( pIter->zIdx==0 ){
194757            sqlite3_stmt *pIdx = pIter->pIdxIter;
194758            rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
194759          }
194760          if( rc==SQLITE_OK ){
194761            rc = sqlite3_step(pIter->pIdxIter);
194762            if( rc!=SQLITE_ROW ){
194763              rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
194764              pIter->bCleanup = 1;
194765              pIter->zIdx = 0;
194766            }else{
194767              pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
194768              pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
194769              pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
194770              rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
194771            }
194772          }
194773        }
194774      }
194775    }
194776  
194777    if( rc!=SQLITE_OK ){
194778      rbuObjIterFinalize(pIter);
194779      p->rc = rc;
194780    }
194781    return rc;
194782  }
194783  
194784  
194785  /*
194786  ** The implementation of the rbu_target_name() SQL function. This function
194787  ** accepts one or two arguments. The first argument is the name of a table -
194788  ** the name of a table in the RBU database.  The second, if it is present, is 1
194789  ** for a view or 0 for a table. 
194790  **
194791  ** For a non-vacuum RBU handle, if the table name matches the pattern:
194792  **
194793  **     data[0-9]_<name>
194794  **
194795  ** where <name> is any sequence of 1 or more characters, <name> is returned.
194796  ** Otherwise, if the only argument does not match the above pattern, an SQL
194797  ** NULL is returned.
194798  **
194799  **     "data_t1"     -> "t1"
194800  **     "data0123_t2" -> "t2"
194801  **     "dataAB_t3"   -> NULL
194802  **
194803  ** For an rbu vacuum handle, a copy of the first argument is returned if
194804  ** the second argument is either missing or 0 (not a view).
194805  */
194806  static void rbuTargetNameFunc(
194807    sqlite3_context *pCtx,
194808    int argc,
194809    sqlite3_value **argv
194810  ){
194811    sqlite3rbu *p = sqlite3_user_data(pCtx);
194812    const char *zIn;
194813    assert( argc==1 || argc==2 );
194814  
194815    zIn = (const char*)sqlite3_value_text(argv[0]);
194816    if( zIn ){
194817      if( rbuIsVacuum(p) ){
194818        if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
194819          sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
194820        }
194821      }else{
194822        if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
194823          int i;
194824          for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
194825          if( zIn[i]=='_' && zIn[i+1] ){
194826            sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
194827          }
194828        }
194829      }
194830    }
194831  }
194832  
194833  /*
194834  ** Initialize the iterator structure passed as the second argument.
194835  **
194836  ** If no error occurs, SQLITE_OK is returned and the iterator is left 
194837  ** pointing to the first entry. Otherwise, an error code and message is 
194838  ** left in the RBU handle passed as the first argument. A copy of the 
194839  ** error code is returned.
194840  */
194841  static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
194842    int rc;
194843    memset(pIter, 0, sizeof(RbuObjIter));
194844  
194845    rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, 
194846      sqlite3_mprintf(
194847        "SELECT rbu_target_name(name, type='view') AS target, name "
194848        "FROM sqlite_master "
194849        "WHERE type IN ('table', 'view') AND target IS NOT NULL "
194850        " %s "
194851        "ORDER BY name"
194852    , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
194853  
194854    if( rc==SQLITE_OK ){
194855      rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
194856          "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
194857          "  FROM main.sqlite_master "
194858          "  WHERE type='index' AND tbl_name = ?"
194859      );
194860    }
194861  
194862    pIter->bCleanup = 1;
194863    p->rc = rc;
194864    return rbuObjIterNext(p, pIter);
194865  }
194866  
194867  /*
194868  ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
194869  ** an error code is stored in the RBU handle passed as the first argument.
194870  **
194871  ** If an error has already occurred (p->rc is already set to something other
194872  ** than SQLITE_OK), then this function returns NULL without modifying the
194873  ** stored error code. In this case it still calls sqlite3_free() on any 
194874  ** printf() parameters associated with %z conversions.
194875  */
194876  static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
194877    char *zSql = 0;
194878    va_list ap;
194879    va_start(ap, zFmt);
194880    zSql = sqlite3_vmprintf(zFmt, ap);
194881    if( p->rc==SQLITE_OK ){
194882      if( zSql==0 ) p->rc = SQLITE_NOMEM;
194883    }else{
194884      sqlite3_free(zSql);
194885      zSql = 0;
194886    }
194887    va_end(ap);
194888    return zSql;
194889  }
194890  
194891  /*
194892  ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
194893  ** arguments are the usual subsitution values. This function performs
194894  ** the printf() style substitutions and executes the result as an SQL
194895  ** statement on the RBU handles database.
194896  **
194897  ** If an error occurs, an error code and error message is stored in the
194898  ** RBU handle. If an error has already occurred when this function is
194899  ** called, it is a no-op.
194900  */
194901  static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
194902    va_list ap;
194903    char *zSql;
194904    va_start(ap, zFmt);
194905    zSql = sqlite3_vmprintf(zFmt, ap);
194906    if( p->rc==SQLITE_OK ){
194907      if( zSql==0 ){
194908        p->rc = SQLITE_NOMEM;
194909      }else{
194910        p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
194911      }
194912    }
194913    sqlite3_free(zSql);
194914    va_end(ap);
194915    return p->rc;
194916  }
194917  
194918  /*
194919  ** Attempt to allocate and return a pointer to a zeroed block of nByte 
194920  ** bytes. 
194921  **
194922  ** If an error (i.e. an OOM condition) occurs, return NULL and leave an 
194923  ** error code in the rbu handle passed as the first argument. Or, if an 
194924  ** error has already occurred when this function is called, return NULL 
194925  ** immediately without attempting the allocation or modifying the stored
194926  ** error code.
194927  */
194928  static void *rbuMalloc(sqlite3rbu *p, int nByte){
194929    void *pRet = 0;
194930    if( p->rc==SQLITE_OK ){
194931      assert( nByte>0 );
194932      pRet = sqlite3_malloc64(nByte);
194933      if( pRet==0 ){
194934        p->rc = SQLITE_NOMEM;
194935      }else{
194936        memset(pRet, 0, nByte);
194937      }
194938    }
194939    return pRet;
194940  }
194941  
194942  
194943  /*
194944  ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
194945  ** there is room for at least nCol elements. If an OOM occurs, store an
194946  ** error code in the RBU handle passed as the first argument.
194947  */
194948  static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
194949    int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
194950    char **azNew;
194951  
194952    azNew = (char**)rbuMalloc(p, nByte);
194953    if( azNew ){
194954      pIter->azTblCol = azNew;
194955      pIter->azTblType = &azNew[nCol];
194956      pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
194957      pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
194958      pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
194959      pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
194960    }
194961  }
194962  
194963  /*
194964  ** The first argument must be a nul-terminated string. This function
194965  ** returns a copy of the string in memory obtained from sqlite3_malloc().
194966  ** It is the responsibility of the caller to eventually free this memory
194967  ** using sqlite3_free().
194968  **
194969  ** If an OOM condition is encountered when attempting to allocate memory,
194970  ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
194971  ** if the allocation succeeds, (*pRc) is left unchanged.
194972  */
194973  static char *rbuStrndup(const char *zStr, int *pRc){
194974    char *zRet = 0;
194975  
194976    assert( *pRc==SQLITE_OK );
194977    if( zStr ){
194978      size_t nCopy = strlen(zStr) + 1;
194979      zRet = (char*)sqlite3_malloc64(nCopy);
194980      if( zRet ){
194981        memcpy(zRet, zStr, nCopy);
194982      }else{
194983        *pRc = SQLITE_NOMEM;
194984      }
194985    }
194986  
194987    return zRet;
194988  }
194989  
194990  /*
194991  ** Finalize the statement passed as the second argument.
194992  **
194993  ** If the sqlite3_finalize() call indicates that an error occurs, and the
194994  ** rbu handle error code is not already set, set the error code and error
194995  ** message accordingly.
194996  */
194997  static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
194998    sqlite3 *db = sqlite3_db_handle(pStmt);
194999    int rc = sqlite3_finalize(pStmt);
195000    if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
195001      p->rc = rc;
195002      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
195003    }
195004  }
195005  
195006  /* Determine the type of a table.
195007  **
195008  **   peType is of type (int*), a pointer to an output parameter of type
195009  **   (int). This call sets the output parameter as follows, depending
195010  **   on the type of the table specified by parameters dbName and zTbl.
195011  **
195012  **     RBU_PK_NOTABLE:       No such table.
195013  **     RBU_PK_NONE:          Table has an implicit rowid.
195014  **     RBU_PK_IPK:           Table has an explicit IPK column.
195015  **     RBU_PK_EXTERNAL:      Table has an external PK index.
195016  **     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
195017  **     RBU_PK_VTAB:          Table is a virtual table.
195018  **
195019  **   Argument *piPk is also of type (int*), and also points to an output
195020  **   parameter. Unless the table has an external primary key index 
195021  **   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
195022  **   if the table does have an external primary key index, then *piPk
195023  **   is set to the root page number of the primary key index before
195024  **   returning.
195025  **
195026  ** ALGORITHM:
195027  **
195028  **   if( no entry exists in sqlite_master ){
195029  **     return RBU_PK_NOTABLE
195030  **   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
195031  **     return RBU_PK_VTAB
195032  **   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
195033  **     if( the index that is the pk exists in sqlite_master ){
195034  **       *piPK = rootpage of that index.
195035  **       return RBU_PK_EXTERNAL
195036  **     }else{
195037  **       return RBU_PK_WITHOUT_ROWID
195038  **     }
195039  **   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
195040  **     return RBU_PK_IPK
195041  **   }else{
195042  **     return RBU_PK_NONE
195043  **   }
195044  */
195045  static void rbuTableType(
195046    sqlite3rbu *p,
195047    const char *zTab,
195048    int *peType,
195049    int *piTnum,
195050    int *piPk
195051  ){
195052    /*
195053    ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
195054    ** 1) PRAGMA index_list = ?
195055    ** 2) SELECT count(*) FROM sqlite_master where name=%Q 
195056    ** 3) PRAGMA table_info = ?
195057    */
195058    sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
195059  
195060    *peType = RBU_PK_NOTABLE;
195061    *piPk = 0;
195062  
195063    assert( p->rc==SQLITE_OK );
195064    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, 
195065      sqlite3_mprintf(
195066            "SELECT (sql LIKE 'create virtual%%'), rootpage"
195067            "  FROM sqlite_master"
195068            " WHERE name=%Q", zTab
195069    ));
195070    if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
195071      /* Either an error, or no such table. */
195072      goto rbuTableType_end;
195073    }
195074    if( sqlite3_column_int(aStmt[0], 0) ){
195075      *peType = RBU_PK_VTAB;                     /* virtual table */
195076      goto rbuTableType_end;
195077    }
195078    *piTnum = sqlite3_column_int(aStmt[0], 1);
195079  
195080    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, 
195081      sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
195082    );
195083    if( p->rc ) goto rbuTableType_end;
195084    while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
195085      const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
195086      const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
195087      if( zOrig && zIdx && zOrig[0]=='p' ){
195088        p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, 
195089            sqlite3_mprintf(
195090              "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
195091        ));
195092        if( p->rc==SQLITE_OK ){
195093          if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
195094            *piPk = sqlite3_column_int(aStmt[2], 0);
195095            *peType = RBU_PK_EXTERNAL;
195096          }else{
195097            *peType = RBU_PK_WITHOUT_ROWID;
195098          }
195099        }
195100        goto rbuTableType_end;
195101      }
195102    }
195103  
195104    p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, 
195105      sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
195106    );
195107    if( p->rc==SQLITE_OK ){
195108      while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
195109        if( sqlite3_column_int(aStmt[3],5)>0 ){
195110          *peType = RBU_PK_IPK;                /* explicit IPK column */
195111          goto rbuTableType_end;
195112        }
195113      }
195114      *peType = RBU_PK_NONE;
195115    }
195116  
195117  rbuTableType_end: {
195118      unsigned int i;
195119      for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
195120        rbuFinalize(p, aStmt[i]);
195121      }
195122    }
195123  }
195124  
195125  /*
195126  ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
195127  ** the pIter->abIndexed[] array.
195128  */
195129  static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
195130    sqlite3_stmt *pList = 0;
195131    int bIndex = 0;
195132  
195133    if( p->rc==SQLITE_OK ){
195134      memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
195135      p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
195136          sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
195137      );
195138    }
195139  
195140    pIter->nIndex = 0;
195141    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
195142      const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
195143      sqlite3_stmt *pXInfo = 0;
195144      if( zIdx==0 ) break;
195145      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
195146          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
195147      );
195148      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
195149        int iCid = sqlite3_column_int(pXInfo, 1);
195150        if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
195151      }
195152      rbuFinalize(p, pXInfo);
195153      bIndex = 1;
195154      pIter->nIndex++;
195155    }
195156  
195157    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
195158      /* "PRAGMA index_list" includes the main PK b-tree */
195159      pIter->nIndex--;
195160    }
195161  
195162    rbuFinalize(p, pList);
195163    if( bIndex==0 ) pIter->abIndexed = 0;
195164  }
195165  
195166  
195167  /*
195168  ** If they are not already populated, populate the pIter->azTblCol[],
195169  ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
195170  ** the table (not index) that the iterator currently points to.
195171  **
195172  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
195173  ** an error does occur, an error code and error message are also left in 
195174  ** the RBU handle.
195175  */
195176  static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
195177    if( pIter->azTblCol==0 ){
195178      sqlite3_stmt *pStmt = 0;
195179      int nCol = 0;
195180      int i;                        /* for() loop iterator variable */
195181      int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
195182      int iOrder = 0;
195183      int iTnum = 0;
195184  
195185      /* Figure out the type of table this step will deal with. */
195186      assert( pIter->eType==0 );
195187      rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
195188      if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
195189        p->rc = SQLITE_ERROR;
195190        p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
195191      }
195192      if( p->rc ) return p->rc;
195193      if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
195194  
195195      assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK 
195196           || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
195197           || pIter->eType==RBU_PK_VTAB
195198      );
195199  
195200      /* Populate the azTblCol[] and nTblCol variables based on the columns
195201      ** of the input table. Ignore any input table columns that begin with
195202      ** "rbu_".  */
195203      p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
195204          sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
195205      );
195206      if( p->rc==SQLITE_OK ){
195207        nCol = sqlite3_column_count(pStmt);
195208        rbuAllocateIterArrays(p, pIter, nCol);
195209      }
195210      for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
195211        const char *zName = (const char*)sqlite3_column_name(pStmt, i);
195212        if( sqlite3_strnicmp("rbu_", zName, 4) ){
195213          char *zCopy = rbuStrndup(zName, &p->rc);
195214          pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
195215          pIter->azTblCol[pIter->nTblCol++] = zCopy;
195216        }
195217        else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
195218          bRbuRowid = 1;
195219        }
195220      }
195221      sqlite3_finalize(pStmt);
195222      pStmt = 0;
195223  
195224      if( p->rc==SQLITE_OK
195225       && rbuIsVacuum(p)==0
195226       && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
195227      ){
195228        p->rc = SQLITE_ERROR;
195229        p->zErrmsg = sqlite3_mprintf(
195230            "table %q %s rbu_rowid column", pIter->zDataTbl,
195231            (bRbuRowid ? "may not have" : "requires")
195232        );
195233      }
195234  
195235      /* Check that all non-HIDDEN columns in the destination table are also
195236      ** present in the input table. Populate the abTblPk[], azTblType[] and
195237      ** aiTblOrder[] arrays at the same time.  */
195238      if( p->rc==SQLITE_OK ){
195239        p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 
195240            sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
195241        );
195242      }
195243      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
195244        const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
195245        if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
195246        for(i=iOrder; i<pIter->nTblCol; i++){
195247          if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
195248        }
195249        if( i==pIter->nTblCol ){
195250          p->rc = SQLITE_ERROR;
195251          p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
195252              pIter->zDataTbl, zName
195253          );
195254        }else{
195255          int iPk = sqlite3_column_int(pStmt, 5);
195256          int bNotNull = sqlite3_column_int(pStmt, 3);
195257          const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
195258  
195259          if( i!=iOrder ){
195260            SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
195261            SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
195262          }
195263  
195264          pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
195265          pIter->abTblPk[iOrder] = (iPk!=0);
195266          pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
195267          iOrder++;
195268        }
195269      }
195270  
195271      rbuFinalize(p, pStmt);
195272      rbuObjIterCacheIndexedCols(p, pIter);
195273      assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
195274      assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
195275    }
195276  
195277    return p->rc;
195278  }
195279  
195280  /*
195281  ** This function constructs and returns a pointer to a nul-terminated 
195282  ** string containing some SQL clause or list based on one or more of the 
195283  ** column names currently stored in the pIter->azTblCol[] array.
195284  */
195285  static char *rbuObjIterGetCollist(
195286    sqlite3rbu *p,                  /* RBU object */
195287    RbuObjIter *pIter               /* Object iterator for column names */
195288  ){
195289    char *zList = 0;
195290    const char *zSep = "";
195291    int i;
195292    for(i=0; i<pIter->nTblCol; i++){
195293      const char *z = pIter->azTblCol[i];
195294      zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
195295      zSep = ", ";
195296    }
195297    return zList;
195298  }
195299  
195300  /*
195301  ** This function is used to create a SELECT list (the list of SQL 
195302  ** expressions that follows a SELECT keyword) for a SELECT statement 
195303  ** used to read from an data_xxx or rbu_tmp_xxx table while updating the 
195304  ** index object currently indicated by the iterator object passed as the 
195305  ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used 
195306  ** to obtain the required information.
195307  **
195308  ** If the index is of the following form:
195309  **
195310  **   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
195311  **
195312  ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column 
195313  ** "ipk", the returned string is:
195314  **
195315  **   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
195316  **
195317  ** As well as the returned string, three other malloc'd strings are 
195318  ** returned via output parameters. As follows:
195319  **
195320  **   pzImposterCols: ...
195321  **   pzImposterPk: ...
195322  **   pzWhere: ...
195323  */
195324  static char *rbuObjIterGetIndexCols(
195325    sqlite3rbu *p,                  /* RBU object */
195326    RbuObjIter *pIter,              /* Object iterator for column names */
195327    char **pzImposterCols,          /* OUT: Columns for imposter table */
195328    char **pzImposterPk,            /* OUT: Imposter PK clause */
195329    char **pzWhere,                 /* OUT: WHERE clause */
195330    int *pnBind                     /* OUT: Trbul number of columns */
195331  ){
195332    int rc = p->rc;                 /* Error code */
195333    int rc2;                        /* sqlite3_finalize() return code */
195334    char *zRet = 0;                 /* String to return */
195335    char *zImpCols = 0;             /* String to return via *pzImposterCols */
195336    char *zImpPK = 0;               /* String to return via *pzImposterPK */
195337    char *zWhere = 0;               /* String to return via *pzWhere */
195338    int nBind = 0;                  /* Value to return via *pnBind */
195339    const char *zCom = "";          /* Set to ", " later on */
195340    const char *zAnd = "";          /* Set to " AND " later on */
195341    sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
195342  
195343    if( rc==SQLITE_OK ){
195344      assert( p->zErrmsg==0 );
195345      rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
195346          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
195347      );
195348    }
195349  
195350    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
195351      int iCid = sqlite3_column_int(pXInfo, 1);
195352      int bDesc = sqlite3_column_int(pXInfo, 3);
195353      const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
195354      const char *zCol;
195355      const char *zType;
195356  
195357      if( iCid<0 ){
195358        /* An integer primary key. If the table has an explicit IPK, use
195359        ** its name. Otherwise, use "rbu_rowid".  */
195360        if( pIter->eType==RBU_PK_IPK ){
195361          int i;
195362          for(i=0; pIter->abTblPk[i]==0; i++);
195363          assert( i<pIter->nTblCol );
195364          zCol = pIter->azTblCol[i];
195365        }else if( rbuIsVacuum(p) ){
195366          zCol = "_rowid_";
195367        }else{
195368          zCol = "rbu_rowid";
195369        }
195370        zType = "INTEGER";
195371      }else{
195372        zCol = pIter->azTblCol[iCid];
195373        zType = pIter->azTblType[iCid];
195374      }
195375  
195376      zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
195377      if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
195378        const char *zOrder = (bDesc ? " DESC" : "");
195379        zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", 
195380            zImpPK, zCom, nBind, zCol, zOrder
195381        );
195382      }
195383      zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", 
195384          zImpCols, zCom, nBind, zCol, zType, zCollate
195385      );
195386      zWhere = sqlite3_mprintf(
195387          "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
195388      );
195389      if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
195390      zCom = ", ";
195391      zAnd = " AND ";
195392      nBind++;
195393    }
195394  
195395    rc2 = sqlite3_finalize(pXInfo);
195396    if( rc==SQLITE_OK ) rc = rc2;
195397  
195398    if( rc!=SQLITE_OK ){
195399      sqlite3_free(zRet);
195400      sqlite3_free(zImpCols);
195401      sqlite3_free(zImpPK);
195402      sqlite3_free(zWhere);
195403      zRet = 0;
195404      zImpCols = 0;
195405      zImpPK = 0;
195406      zWhere = 0;
195407      p->rc = rc;
195408    }
195409  
195410    *pzImposterCols = zImpCols;
195411    *pzImposterPk = zImpPK;
195412    *pzWhere = zWhere;
195413    *pnBind = nBind;
195414    return zRet;
195415  }
195416  
195417  /*
195418  ** Assuming the current table columns are "a", "b" and "c", and the zObj
195419  ** paramter is passed "old", return a string of the form:
195420  **
195421  **     "old.a, old.b, old.b"
195422  **
195423  ** With the column names escaped.
195424  **
195425  ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
195426  ** the text ", old._rowid_" to the returned value.
195427  */
195428  static char *rbuObjIterGetOldlist(
195429    sqlite3rbu *p, 
195430    RbuObjIter *pIter,
195431    const char *zObj
195432  ){
195433    char *zList = 0;
195434    if( p->rc==SQLITE_OK && pIter->abIndexed ){
195435      const char *zS = "";
195436      int i;
195437      for(i=0; i<pIter->nTblCol; i++){
195438        if( pIter->abIndexed[i] ){
195439          const char *zCol = pIter->azTblCol[i];
195440          zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
195441        }else{
195442          zList = sqlite3_mprintf("%z%sNULL", zList, zS);
195443        }
195444        zS = ", ";
195445        if( zList==0 ){
195446          p->rc = SQLITE_NOMEM;
195447          break;
195448        }
195449      }
195450  
195451      /* For a table with implicit rowids, append "old._rowid_" to the list. */
195452      if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
195453        zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
195454      }
195455    }
195456    return zList;
195457  }
195458  
195459  /*
195460  ** Return an expression that can be used in a WHERE clause to match the
195461  ** primary key of the current table. For example, if the table is:
195462  **
195463  **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
195464  **
195465  ** Return the string:
195466  **
195467  **   "b = ?1 AND c = ?2"
195468  */
195469  static char *rbuObjIterGetWhere(
195470    sqlite3rbu *p, 
195471    RbuObjIter *pIter
195472  ){
195473    char *zList = 0;
195474    if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
195475      zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
195476    }else if( pIter->eType==RBU_PK_EXTERNAL ){
195477      const char *zSep = "";
195478      int i;
195479      for(i=0; i<pIter->nTblCol; i++){
195480        if( pIter->abTblPk[i] ){
195481          zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
195482          zSep = " AND ";
195483        }
195484      }
195485      zList = rbuMPrintf(p, 
195486          "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
195487      );
195488  
195489    }else{
195490      const char *zSep = "";
195491      int i;
195492      for(i=0; i<pIter->nTblCol; i++){
195493        if( pIter->abTblPk[i] ){
195494          const char *zCol = pIter->azTblCol[i];
195495          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
195496          zSep = " AND ";
195497        }
195498      }
195499    }
195500    return zList;
195501  }
195502  
195503  /*
195504  ** The SELECT statement iterating through the keys for the current object
195505  ** (p->objiter.pSelect) currently points to a valid row. However, there
195506  ** is something wrong with the rbu_control value in the rbu_control value
195507  ** stored in the (p->nCol+1)'th column. Set the error code and error message
195508  ** of the RBU handle to something reflecting this.
195509  */
195510  static void rbuBadControlError(sqlite3rbu *p){
195511    p->rc = SQLITE_ERROR;
195512    p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
195513  }
195514  
195515  
195516  /*
195517  ** Return a nul-terminated string containing the comma separated list of
195518  ** assignments that should be included following the "SET" keyword of
195519  ** an UPDATE statement used to update the table object that the iterator
195520  ** passed as the second argument currently points to if the rbu_control
195521  ** column of the data_xxx table entry is set to zMask.
195522  **
195523  ** The memory for the returned string is obtained from sqlite3_malloc().
195524  ** It is the responsibility of the caller to eventually free it using
195525  ** sqlite3_free(). 
195526  **
195527  ** If an OOM error is encountered when allocating space for the new
195528  ** string, an error code is left in the rbu handle passed as the first
195529  ** argument and NULL is returned. Or, if an error has already occurred
195530  ** when this function is called, NULL is returned immediately, without
195531  ** attempting the allocation or modifying the stored error code.
195532  */
195533  static char *rbuObjIterGetSetlist(
195534    sqlite3rbu *p,
195535    RbuObjIter *pIter,
195536    const char *zMask
195537  ){
195538    char *zList = 0;
195539    if( p->rc==SQLITE_OK ){
195540      int i;
195541  
195542      if( (int)strlen(zMask)!=pIter->nTblCol ){
195543        rbuBadControlError(p);
195544      }else{
195545        const char *zSep = "";
195546        for(i=0; i<pIter->nTblCol; i++){
195547          char c = zMask[pIter->aiSrcOrder[i]];
195548          if( c=='x' ){
195549            zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", 
195550                zList, zSep, pIter->azTblCol[i], i+1
195551            );
195552            zSep = ", ";
195553          }
195554          else if( c=='d' ){
195555            zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", 
195556                zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
195557            );
195558            zSep = ", ";
195559          }
195560          else if( c=='f' ){
195561            zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", 
195562                zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
195563            );
195564            zSep = ", ";
195565          }
195566        }
195567      }
195568    }
195569    return zList;
195570  }
195571  
195572  /*
195573  ** Return a nul-terminated string consisting of nByte comma separated
195574  ** "?" expressions. For example, if nByte is 3, return a pointer to
195575  ** a buffer containing the string "?,?,?".
195576  **
195577  ** The memory for the returned string is obtained from sqlite3_malloc().
195578  ** It is the responsibility of the caller to eventually free it using
195579  ** sqlite3_free(). 
195580  **
195581  ** If an OOM error is encountered when allocating space for the new
195582  ** string, an error code is left in the rbu handle passed as the first
195583  ** argument and NULL is returned. Or, if an error has already occurred
195584  ** when this function is called, NULL is returned immediately, without
195585  ** attempting the allocation or modifying the stored error code.
195586  */
195587  static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
195588    char *zRet = 0;
195589    int nByte = nBind*2 + 1;
195590  
195591    zRet = (char*)rbuMalloc(p, nByte);
195592    if( zRet ){
195593      int i;
195594      for(i=0; i<nBind; i++){
195595        zRet[i*2] = '?';
195596        zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
195597      }
195598    }
195599    return zRet;
195600  }
195601  
195602  /*
195603  ** The iterator currently points to a table (not index) of type 
195604  ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY 
195605  ** declaration for the corresponding imposter table. For example,
195606  ** if the iterator points to a table created as:
195607  **
195608  **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
195609  **
195610  ** this function returns:
195611  **
195612  **   PRIMARY KEY("b", "a" DESC)
195613  */
195614  static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
195615    char *z = 0;
195616    assert( pIter->zIdx==0 );
195617    if( p->rc==SQLITE_OK ){
195618      const char *zSep = "PRIMARY KEY(";
195619      sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
195620      sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
195621     
195622      p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
195623          sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
195624      );
195625      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
195626        const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
195627        if( zOrig && strcmp(zOrig, "pk")==0 ){
195628          const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
195629          if( zIdx ){
195630            p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
195631                sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
195632            );
195633          }
195634          break;
195635        }
195636      }
195637      rbuFinalize(p, pXList);
195638  
195639      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
195640        if( sqlite3_column_int(pXInfo, 5) ){
195641          /* int iCid = sqlite3_column_int(pXInfo, 0); */
195642          const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
195643          const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
195644          z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
195645          zSep = ", ";
195646        }
195647      }
195648      z = rbuMPrintf(p, "%z)", z);
195649      rbuFinalize(p, pXInfo);
195650    }
195651    return z;
195652  }
195653  
195654  /*
195655  ** This function creates the second imposter table used when writing to
195656  ** a table b-tree where the table has an external primary key. If the
195657  ** iterator passed as the second argument does not currently point to
195658  ** a table (not index) with an external primary key, this function is a
195659  ** no-op. 
195660  **
195661  ** Assuming the iterator does point to a table with an external PK, this
195662  ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
195663  ** used to access that PK index. For example, if the target table is
195664  ** declared as follows:
195665  **
195666  **   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
195667  **
195668  ** then the imposter table schema is:
195669  **
195670  **   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
195671  **
195672  */
195673  static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
195674    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
195675      int tnum = pIter->iPkTnum;    /* Root page of PK index */
195676      sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
195677      const char *zIdx = 0;         /* Name of PK index */
195678      sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
195679      const char *zComma = "";
195680      char *zCols = 0;              /* Used to build up list of table cols */
195681      char *zPk = 0;                /* Used to build up table PK declaration */
195682  
195683      /* Figure out the name of the primary key index for the current table.
195684      ** This is needed for the argument to "PRAGMA index_xinfo". Set
195685      ** zIdx to point to a nul-terminated string containing this name. */
195686      p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, 
195687          "SELECT name FROM sqlite_master WHERE rootpage = ?"
195688      );
195689      if( p->rc==SQLITE_OK ){
195690        sqlite3_bind_int(pQuery, 1, tnum);
195691        if( SQLITE_ROW==sqlite3_step(pQuery) ){
195692          zIdx = (const char*)sqlite3_column_text(pQuery, 0);
195693        }
195694      }
195695      if( zIdx ){
195696        p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
195697            sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
195698        );
195699      }
195700      rbuFinalize(p, pQuery);
195701  
195702      while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
195703        int bKey = sqlite3_column_int(pXInfo, 5);
195704        if( bKey ){
195705          int iCid = sqlite3_column_int(pXInfo, 1);
195706          int bDesc = sqlite3_column_int(pXInfo, 3);
195707          const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
195708          zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma, 
195709              iCid, pIter->azTblType[iCid], zCollate
195710          );
195711          zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
195712          zComma = ", ";
195713        }
195714      }
195715      zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
195716      rbuFinalize(p, pXInfo);
195717  
195718      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
195719      rbuMPrintfExec(p, p->dbMain,
195720          "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", 
195721          zCols, zPk
195722      );
195723      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
195724    }
195725  }
195726  
195727  /*
195728  ** If an error has already occurred when this function is called, it 
195729  ** immediately returns zero (without doing any work). Or, if an error
195730  ** occurs during the execution of this function, it sets the error code
195731  ** in the sqlite3rbu object indicated by the first argument and returns
195732  ** zero.
195733  **
195734  ** The iterator passed as the second argument is guaranteed to point to
195735  ** a table (not an index) when this function is called. This function
195736  ** attempts to create any imposter table required to write to the main
195737  ** table b-tree of the table before returning. Non-zero is returned if
195738  ** an imposter table are created, or zero otherwise.
195739  **
195740  ** An imposter table is required in all cases except RBU_PK_VTAB. Only
195741  ** virtual tables are written to directly. The imposter table has the 
195742  ** same schema as the actual target table (less any UNIQUE constraints). 
195743  ** More precisely, the "same schema" means the same columns, types, 
195744  ** collation sequences. For tables that do not have an external PRIMARY
195745  ** KEY, it also means the same PRIMARY KEY declaration.
195746  */
195747  static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
195748    if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
195749      int tnum = pIter->iTnum;
195750      const char *zComma = "";
195751      char *zSql = 0;
195752      int iCol;
195753      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
195754  
195755      for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
195756        const char *zPk = "";
195757        const char *zCol = pIter->azTblCol[iCol];
195758        const char *zColl = 0;
195759  
195760        p->rc = sqlite3_table_column_metadata(
195761            p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
195762        );
195763  
195764        if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
195765          /* If the target table column is an "INTEGER PRIMARY KEY", add
195766          ** "PRIMARY KEY" to the imposter table column declaration. */
195767          zPk = "PRIMARY KEY ";
195768        }
195769        zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s", 
195770            zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
195771            (pIter->abNotNull[iCol] ? " NOT NULL" : "")
195772        );
195773        zComma = ", ";
195774      }
195775  
195776      if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
195777        char *zPk = rbuWithoutRowidPK(p, pIter);
195778        if( zPk ){
195779          zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
195780        }
195781      }
195782  
195783      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
195784      rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", 
195785          pIter->zTbl, zSql, 
195786          (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
195787      );
195788      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
195789    }
195790  }
195791  
195792  /*
195793  ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
195794  ** Specifically a statement of the form:
195795  **
195796  **     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
195797  **
195798  ** The number of bound variables is equal to the number of columns in
195799  ** the target table, plus one (for the rbu_control column), plus one more 
195800  ** (for the rbu_rowid column) if the target table is an implicit IPK or 
195801  ** virtual table.
195802  */
195803  static void rbuObjIterPrepareTmpInsert(
195804    sqlite3rbu *p, 
195805    RbuObjIter *pIter,
195806    const char *zCollist,
195807    const char *zRbuRowid
195808  ){
195809    int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
195810    char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
195811    if( zBind ){
195812      assert( pIter->pTmpInsert==0 );
195813      p->rc = prepareFreeAndCollectError(
195814          p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
195815            "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", 
195816            p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
195817      ));
195818    }
195819  }
195820  
195821  static void rbuTmpInsertFunc(
195822    sqlite3_context *pCtx, 
195823    int nVal,
195824    sqlite3_value **apVal
195825  ){
195826    sqlite3rbu *p = sqlite3_user_data(pCtx);
195827    int rc = SQLITE_OK;
195828    int i;
195829  
195830    assert( sqlite3_value_int(apVal[0])!=0
195831        || p->objiter.eType==RBU_PK_EXTERNAL 
195832        || p->objiter.eType==RBU_PK_NONE 
195833    );
195834    if( sqlite3_value_int(apVal[0])!=0 ){
195835      p->nPhaseOneStep += p->objiter.nIndex;
195836    }
195837  
195838    for(i=0; rc==SQLITE_OK && i<nVal; i++){
195839      rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
195840    }
195841    if( rc==SQLITE_OK ){
195842      sqlite3_step(p->objiter.pTmpInsert);
195843      rc = sqlite3_reset(p->objiter.pTmpInsert);
195844    }
195845  
195846    if( rc!=SQLITE_OK ){
195847      sqlite3_result_error_code(pCtx, rc);
195848    }
195849  }
195850  
195851  /*
195852  ** Ensure that the SQLite statement handles required to update the 
195853  ** target database object currently indicated by the iterator passed 
195854  ** as the second argument are available.
195855  */
195856  static int rbuObjIterPrepareAll(
195857    sqlite3rbu *p, 
195858    RbuObjIter *pIter,
195859    int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
195860  ){
195861    assert( pIter->bCleanup==0 );
195862    if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
195863      const int tnum = pIter->iTnum;
195864      char *zCollist = 0;           /* List of indexed columns */
195865      char **pz = &p->zErrmsg;
195866      const char *zIdx = pIter->zIdx;
195867      char *zLimit = 0;
195868  
195869      if( nOffset ){
195870        zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
195871        if( !zLimit ) p->rc = SQLITE_NOMEM;
195872      }
195873  
195874      if( zIdx ){
195875        const char *zTbl = pIter->zTbl;
195876        char *zImposterCols = 0;    /* Columns for imposter table */
195877        char *zImposterPK = 0;      /* Primary key declaration for imposter */
195878        char *zWhere = 0;           /* WHERE clause on PK columns */
195879        char *zBind = 0;
195880        int nBind = 0;
195881  
195882        assert( pIter->eType!=RBU_PK_VTAB );
195883        zCollist = rbuObjIterGetIndexCols(
195884            p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
195885        );
195886        zBind = rbuObjIterGetBindlist(p, nBind);
195887  
195888        /* Create the imposter table used to write to this index. */
195889        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
195890        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
195891        rbuMPrintfExec(p, p->dbMain,
195892            "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
195893            zTbl, zImposterCols, zImposterPK
195894        );
195895        sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
195896  
195897        /* Create the statement to insert index entries */
195898        pIter->nCol = nBind;
195899        if( p->rc==SQLITE_OK ){
195900          p->rc = prepareFreeAndCollectError(
195901              p->dbMain, &pIter->pInsert, &p->zErrmsg,
195902            sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
195903          );
195904        }
195905  
195906        /* And to delete index entries */
195907        if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
195908          p->rc = prepareFreeAndCollectError(
195909              p->dbMain, &pIter->pDelete, &p->zErrmsg,
195910            sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
195911          );
195912        }
195913  
195914        /* Create the SELECT statement to read keys in sorted order */
195915        if( p->rc==SQLITE_OK ){
195916          char *zSql;
195917          if( rbuIsVacuum(p) ){
195918            zSql = sqlite3_mprintf(
195919                "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
195920                zCollist, 
195921                pIter->zDataTbl,
195922                zCollist, zLimit
195923            );
195924          }else
195925  
195926          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
195927            zSql = sqlite3_mprintf(
195928                "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
195929                zCollist, p->zStateDb, pIter->zDataTbl,
195930                zCollist, zLimit
195931            );
195932          }else{
195933            zSql = sqlite3_mprintf(
195934                "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
195935                "UNION ALL "
195936                "SELECT %s, rbu_control FROM '%q' "
195937                "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
195938                "ORDER BY %s%s",
195939                zCollist, p->zStateDb, pIter->zDataTbl, 
195940                zCollist, pIter->zDataTbl, 
195941                zCollist, zLimit
195942            );
195943          }
195944          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
195945        }
195946  
195947        sqlite3_free(zImposterCols);
195948        sqlite3_free(zImposterPK);
195949        sqlite3_free(zWhere);
195950        sqlite3_free(zBind);
195951      }else{
195952        int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
195953                      ||(pIter->eType==RBU_PK_NONE)
195954                      ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
195955        const char *zTbl = pIter->zTbl;       /* Table this step applies to */
195956        const char *zWrite;                   /* Imposter table name */
195957  
195958        char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
195959        char *zWhere = rbuObjIterGetWhere(p, pIter);
195960        char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
195961        char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
195962  
195963        zCollist = rbuObjIterGetCollist(p, pIter);
195964        pIter->nCol = pIter->nTblCol;
195965  
195966        /* Create the imposter table or tables (if required). */
195967        rbuCreateImposterTable(p, pIter);
195968        rbuCreateImposterTable2(p, pIter);
195969        zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
195970  
195971        /* Create the INSERT statement to write to the target PK b-tree */
195972        if( p->rc==SQLITE_OK ){
195973          p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
195974              sqlite3_mprintf(
195975                "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", 
195976                zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
195977              )
195978          );
195979        }
195980  
195981        /* Create the DELETE statement to write to the target PK b-tree.
195982        ** Because it only performs INSERT operations, this is not required for
195983        ** an rbu vacuum handle.  */
195984        if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
195985          p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
195986              sqlite3_mprintf(
195987                "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
195988              )
195989          );
195990        }
195991  
195992        if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
195993          const char *zRbuRowid = "";
195994          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
195995            zRbuRowid = ", rbu_rowid";
195996          }
195997  
195998          /* Create the rbu_tmp_xxx table and the triggers to populate it. */
195999          rbuMPrintfExec(p, p->dbRbu,
196000              "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
196001              "SELECT *%s FROM '%q' WHERE 0;"
196002              , p->zStateDb, pIter->zDataTbl
196003              , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
196004              , pIter->zDataTbl
196005          );
196006  
196007          rbuMPrintfExec(p, p->dbMain,
196008              "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
196009              "BEGIN "
196010              "  SELECT rbu_tmp_insert(3, %s);"
196011              "END;"
196012  
196013              "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
196014              "BEGIN "
196015              "  SELECT rbu_tmp_insert(3, %s);"
196016              "END;"
196017  
196018              "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
196019              "BEGIN "
196020              "  SELECT rbu_tmp_insert(4, %s);"
196021              "END;",
196022              zWrite, zTbl, zOldlist,
196023              zWrite, zTbl, zOldlist,
196024              zWrite, zTbl, zNewlist
196025          );
196026  
196027          if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
196028            rbuMPrintfExec(p, p->dbMain,
196029                "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
196030                "BEGIN "
196031                "  SELECT rbu_tmp_insert(0, %s);"
196032                "END;",
196033                zWrite, zTbl, zNewlist
196034            );
196035          }
196036  
196037          rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
196038        }
196039  
196040        /* Create the SELECT statement to read keys from data_xxx */
196041        if( p->rc==SQLITE_OK ){
196042          const char *zRbuRowid = "";
196043          if( bRbuRowid ){
196044            zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
196045          }
196046          p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
196047              sqlite3_mprintf(
196048                "SELECT %s,%s rbu_control%s FROM '%q'%s", 
196049                zCollist, 
196050                (rbuIsVacuum(p) ? "0 AS " : ""),
196051                zRbuRowid,
196052                pIter->zDataTbl, zLimit
196053              )
196054          );
196055        }
196056  
196057        sqlite3_free(zWhere);
196058        sqlite3_free(zOldlist);
196059        sqlite3_free(zNewlist);
196060        sqlite3_free(zBindings);
196061      }
196062      sqlite3_free(zCollist);
196063      sqlite3_free(zLimit);
196064    }
196065    
196066    return p->rc;
196067  }
196068  
196069  /*
196070  ** Set output variable *ppStmt to point to an UPDATE statement that may
196071  ** be used to update the imposter table for the main table b-tree of the
196072  ** table object that pIter currently points to, assuming that the 
196073  ** rbu_control column of the data_xyz table contains zMask.
196074  ** 
196075  ** If the zMask string does not specify any columns to update, then this
196076  ** is not an error. Output variable *ppStmt is set to NULL in this case.
196077  */
196078  static int rbuGetUpdateStmt(
196079    sqlite3rbu *p,                  /* RBU handle */
196080    RbuObjIter *pIter,              /* Object iterator */
196081    const char *zMask,              /* rbu_control value ('x.x.') */
196082    sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
196083  ){
196084    RbuUpdateStmt **pp;
196085    RbuUpdateStmt *pUp = 0;
196086    int nUp = 0;
196087  
196088    /* In case an error occurs */
196089    *ppStmt = 0;
196090  
196091    /* Search for an existing statement. If one is found, shift it to the front
196092    ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
196093    ** to the number of statements currently in the cache and pUp to the
196094    ** last object in the list.  */
196095    for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
196096      pUp = *pp;
196097      if( strcmp(pUp->zMask, zMask)==0 ){
196098        *pp = pUp->pNext;
196099        pUp->pNext = pIter->pRbuUpdate;
196100        pIter->pRbuUpdate = pUp;
196101        *ppStmt = pUp->pUpdate; 
196102        return SQLITE_OK;
196103      }
196104      nUp++;
196105    }
196106    assert( pUp==0 || pUp->pNext==0 );
196107  
196108    if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
196109      for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
196110      *pp = 0;
196111      sqlite3_finalize(pUp->pUpdate);
196112      pUp->pUpdate = 0;
196113    }else{
196114      pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
196115    }
196116  
196117    if( pUp ){
196118      char *zWhere = rbuObjIterGetWhere(p, pIter);
196119      char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
196120      char *zUpdate = 0;
196121  
196122      pUp->zMask = (char*)&pUp[1];
196123      memcpy(pUp->zMask, zMask, pIter->nTblCol);
196124      pUp->pNext = pIter->pRbuUpdate;
196125      pIter->pRbuUpdate = pUp;
196126  
196127      if( zSet ){
196128        const char *zPrefix = "";
196129  
196130        if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
196131        zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", 
196132            zPrefix, pIter->zTbl, zSet, zWhere
196133        );
196134        p->rc = prepareFreeAndCollectError(
196135            p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
196136        );
196137        *ppStmt = pUp->pUpdate;
196138      }
196139      sqlite3_free(zWhere);
196140      sqlite3_free(zSet);
196141    }
196142  
196143    return p->rc;
196144  }
196145  
196146  static sqlite3 *rbuOpenDbhandle(
196147    sqlite3rbu *p, 
196148    const char *zName, 
196149    int bUseVfs
196150  ){
196151    sqlite3 *db = 0;
196152    if( p->rc==SQLITE_OK ){
196153      const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
196154      p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
196155      if( p->rc ){
196156        p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
196157        sqlite3_close(db);
196158        db = 0;
196159      }
196160    }
196161    return db;
196162  }
196163  
196164  /*
196165  ** Free an RbuState object allocated by rbuLoadState().
196166  */
196167  static void rbuFreeState(RbuState *p){
196168    if( p ){
196169      sqlite3_free(p->zTbl);
196170      sqlite3_free(p->zDataTbl);
196171      sqlite3_free(p->zIdx);
196172      sqlite3_free(p);
196173    }
196174  }
196175  
196176  /*
196177  ** Allocate an RbuState object and load the contents of the rbu_state 
196178  ** table into it. Return a pointer to the new object. It is the 
196179  ** responsibility of the caller to eventually free the object using
196180  ** sqlite3_free().
196181  **
196182  ** If an error occurs, leave an error code and message in the rbu handle
196183  ** and return NULL.
196184  */
196185  static RbuState *rbuLoadState(sqlite3rbu *p){
196186    RbuState *pRet = 0;
196187    sqlite3_stmt *pStmt = 0;
196188    int rc;
196189    int rc2;
196190  
196191    pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
196192    if( pRet==0 ) return 0;
196193  
196194    rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
196195        sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
196196    );
196197    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
196198      switch( sqlite3_column_int(pStmt, 0) ){
196199        case RBU_STATE_STAGE:
196200          pRet->eStage = sqlite3_column_int(pStmt, 1);
196201          if( pRet->eStage!=RBU_STAGE_OAL
196202           && pRet->eStage!=RBU_STAGE_MOVE
196203           && pRet->eStage!=RBU_STAGE_CKPT
196204          ){
196205            p->rc = SQLITE_CORRUPT;
196206          }
196207          break;
196208  
196209        case RBU_STATE_TBL:
196210          pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
196211          break;
196212  
196213        case RBU_STATE_IDX:
196214          pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
196215          break;
196216  
196217        case RBU_STATE_ROW:
196218          pRet->nRow = sqlite3_column_int(pStmt, 1);
196219          break;
196220  
196221        case RBU_STATE_PROGRESS:
196222          pRet->nProgress = sqlite3_column_int64(pStmt, 1);
196223          break;
196224  
196225        case RBU_STATE_CKPT:
196226          pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
196227          break;
196228  
196229        case RBU_STATE_COOKIE:
196230          pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
196231          break;
196232  
196233        case RBU_STATE_OALSZ:
196234          pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
196235          break;
196236  
196237        case RBU_STATE_PHASEONESTEP:
196238          pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
196239          break;
196240  
196241        case RBU_STATE_DATATBL:
196242          pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
196243          break;
196244  
196245        default:
196246          rc = SQLITE_CORRUPT;
196247          break;
196248      }
196249    }
196250    rc2 = sqlite3_finalize(pStmt);
196251    if( rc==SQLITE_OK ) rc = rc2;
196252  
196253    p->rc = rc;
196254    return pRet;
196255  }
196256  
196257  
196258  /*
196259  ** Open the database handle and attach the RBU database as "rbu". If an
196260  ** error occurs, leave an error code and message in the RBU handle.
196261  */
196262  static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
196263    assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
196264    assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
196265  
196266    /* Open the RBU database */
196267    p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
196268  
196269    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
196270      sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
196271      if( p->zState==0 ){
196272        const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
196273        p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
196274      }
196275    }
196276  
196277    /* If using separate RBU and state databases, attach the state database to
196278    ** the RBU db handle now.  */
196279    if( p->zState ){
196280      rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
196281      memcpy(p->zStateDb, "stat", 4);
196282    }else{
196283      memcpy(p->zStateDb, "main", 4);
196284    }
196285  
196286  #if 0
196287    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
196288      p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
196289    }
196290  #endif
196291  
196292    /* If it has not already been created, create the rbu_state table */
196293    rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
196294  
196295  #if 0
196296    if( rbuIsVacuum(p) ){
196297      if( p->rc==SQLITE_OK ){
196298        int rc2;
196299        int bOk = 0;
196300        sqlite3_stmt *pCnt = 0;
196301        p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
196302            "SELECT count(*) FROM stat.sqlite_master"
196303        );
196304        if( p->rc==SQLITE_OK 
196305         && sqlite3_step(pCnt)==SQLITE_ROW
196306         && 1==sqlite3_column_int(pCnt, 0)
196307        ){
196308          bOk = 1;
196309        }
196310        rc2 = sqlite3_finalize(pCnt);
196311        if( p->rc==SQLITE_OK ) p->rc = rc2;
196312  
196313        if( p->rc==SQLITE_OK && bOk==0 ){
196314          p->rc = SQLITE_ERROR;
196315          p->zErrmsg = sqlite3_mprintf("invalid state database");
196316        }
196317      
196318        if( p->rc==SQLITE_OK ){
196319          p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
196320        }
196321      }
196322    }
196323  #endif
196324  
196325    if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
196326      int bOpen = 0;
196327      int rc;
196328      p->nRbu = 0;
196329      p->pRbuFd = 0;
196330      rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
196331      if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
196332      if( p->eStage>=RBU_STAGE_MOVE ){
196333        bOpen = 1;
196334      }else{
196335        RbuState *pState = rbuLoadState(p);
196336        if( pState ){
196337          bOpen = (pState->eStage>=RBU_STAGE_MOVE);
196338          rbuFreeState(pState);
196339        }
196340      }
196341      if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
196342    }
196343  
196344    p->eStage = 0;
196345    if( p->rc==SQLITE_OK && p->dbMain==0 ){
196346      if( !rbuIsVacuum(p) ){
196347        p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
196348      }else if( p->pRbuFd->pWalFd ){
196349        if( pbRetry ){
196350          p->pRbuFd->bNolock = 0;
196351          sqlite3_close(p->dbRbu);
196352          sqlite3_close(p->dbMain);
196353          p->dbMain = 0;
196354          p->dbRbu = 0;
196355          *pbRetry = 1;
196356          return;
196357        }
196358        p->rc = SQLITE_ERROR;
196359        p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
196360      }else{
196361        char *zTarget;
196362        char *zExtra = 0;
196363        if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
196364          zExtra = &p->zRbu[5];
196365          while( *zExtra ){
196366            if( *zExtra++=='?' ) break;
196367          }
196368          if( *zExtra=='\0' ) zExtra = 0;
196369        }
196370  
196371        zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s", 
196372            sqlite3_db_filename(p->dbRbu, "main"),
196373            (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
196374        );
196375  
196376        if( zTarget==0 ){
196377          p->rc = SQLITE_NOMEM;
196378          return;
196379        }
196380        p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
196381        sqlite3_free(zTarget);
196382      }
196383    }
196384  
196385    if( p->rc==SQLITE_OK ){
196386      p->rc = sqlite3_create_function(p->dbMain, 
196387          "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
196388      );
196389    }
196390  
196391    if( p->rc==SQLITE_OK ){
196392      p->rc = sqlite3_create_function(p->dbMain, 
196393          "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
196394      );
196395    }
196396  
196397    if( p->rc==SQLITE_OK ){
196398      p->rc = sqlite3_create_function(p->dbRbu, 
196399          "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
196400      );
196401    }
196402  
196403    if( p->rc==SQLITE_OK ){
196404      p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
196405    }
196406    rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
196407  
196408    /* Mark the database file just opened as an RBU target database. If 
196409    ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
196410    ** This is an error.  */
196411    if( p->rc==SQLITE_OK ){
196412      p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
196413    }
196414  
196415    if( p->rc==SQLITE_NOTFOUND ){
196416      p->rc = SQLITE_ERROR;
196417      p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
196418    }
196419  }
196420  
196421  /*
196422  ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
196423  ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
196424  **
196425  ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
196426  ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
196427  ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
196428  ** three characters, then shorten the suffix on z[] to be the last three
196429  ** characters of the original suffix.
196430  **
196431  ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
196432  ** do the suffix shortening regardless of URI parameter.
196433  **
196434  ** Examples:
196435  **
196436  **     test.db-journal    =>   test.nal
196437  **     test.db-wal        =>   test.wal
196438  **     test.db-shm        =>   test.shm
196439  **     test.db-mj7f3319fa =>   test.9fa
196440  */
196441  static void rbuFileSuffix3(const char *zBase, char *z){
196442  #ifdef SQLITE_ENABLE_8_3_NAMES
196443  #if SQLITE_ENABLE_8_3_NAMES<2
196444    if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
196445  #endif
196446    {
196447      int i, sz;
196448      sz = (int)strlen(z)&0xffffff;
196449      for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
196450      if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
196451    }
196452  #endif
196453  }
196454  
196455  /*
196456  ** Return the current wal-index header checksum for the target database 
196457  ** as a 64-bit integer.
196458  **
196459  ** The checksum is store in the first page of xShmMap memory as an 8-byte 
196460  ** blob starting at byte offset 40.
196461  */
196462  static i64 rbuShmChecksum(sqlite3rbu *p){
196463    i64 iRet = 0;
196464    if( p->rc==SQLITE_OK ){
196465      sqlite3_file *pDb = p->pTargetFd->pReal;
196466      u32 volatile *ptr;
196467      p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
196468      if( p->rc==SQLITE_OK ){
196469        iRet = ((i64)ptr[10] << 32) + ptr[11];
196470      }
196471    }
196472    return iRet;
196473  }
196474  
196475  /*
196476  ** This function is called as part of initializing or reinitializing an
196477  ** incremental checkpoint. 
196478  **
196479  ** It populates the sqlite3rbu.aFrame[] array with the set of 
196480  ** (wal frame -> db page) copy operations required to checkpoint the 
196481  ** current wal file, and obtains the set of shm locks required to safely 
196482  ** perform the copy operations directly on the file-system.
196483  **
196484  ** If argument pState is not NULL, then the incremental checkpoint is
196485  ** being resumed. In this case, if the checksum of the wal-index-header
196486  ** following recovery is not the same as the checksum saved in the RbuState
196487  ** object, then the rbu handle is set to DONE state. This occurs if some
196488  ** other client appends a transaction to the wal file in the middle of
196489  ** an incremental checkpoint.
196490  */
196491  static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
196492  
196493    /* If pState is NULL, then the wal file may not have been opened and
196494    ** recovered. Running a read-statement here to ensure that doing so
196495    ** does not interfere with the "capture" process below.  */
196496    if( pState==0 ){
196497      p->eStage = 0;
196498      if( p->rc==SQLITE_OK ){
196499        p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
196500      }
196501    }
196502  
196503    /* Assuming no error has occurred, run a "restart" checkpoint with the
196504    ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
196505    ** special behaviour in the rbu VFS:
196506    **
196507    **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
196508    **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
196509    **     proceed with running a passive checkpoint instead of failing).
196510    **
196511    **   * Attempts to read from the *-wal file or write to the database file
196512    **     do not perform any IO. Instead, the frame/page combinations that
196513    **     would be read/written are recorded in the sqlite3rbu.aFrame[]
196514    **     array.
196515    **
196516    **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, 
196517    **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
196518    **     no-ops. These locks will not be released until the connection
196519    **     is closed.
196520    **
196521    **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL 
196522    **     error.
196523    **
196524    ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
196525    ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
196526    ** array populated with a set of (frame -> page) mappings. Because the 
196527    ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy 
196528    ** data from the wal file into the database file according to the 
196529    ** contents of aFrame[].
196530    */
196531    if( p->rc==SQLITE_OK ){
196532      int rc2;
196533      p->eStage = RBU_STAGE_CAPTURE;
196534      rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
196535      if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
196536    }
196537  
196538    if( p->rc==SQLITE_OK && p->nFrame>0 ){
196539      p->eStage = RBU_STAGE_CKPT;
196540      p->nStep = (pState ? pState->nRow : 0);
196541      p->aBuf = rbuMalloc(p, p->pgsz);
196542      p->iWalCksum = rbuShmChecksum(p);
196543    }
196544  
196545    if( p->rc==SQLITE_OK ){
196546      if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
196547        p->rc = SQLITE_DONE;
196548        p->eStage = RBU_STAGE_DONE;
196549      }else{
196550        int nSectorSize;
196551        sqlite3_file *pDb = p->pTargetFd->pReal;
196552        sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
196553        assert( p->nPagePerSector==0 );
196554        nSectorSize = pDb->pMethods->xSectorSize(pDb);
196555        if( nSectorSize>p->pgsz ){
196556          p->nPagePerSector = nSectorSize / p->pgsz;
196557        }else{
196558          p->nPagePerSector = 1;
196559        }
196560  
196561        /* Call xSync() on the wal file. This causes SQLite to sync the 
196562        ** directory in which the target database and the wal file reside, in 
196563        ** case it has not been synced since the rename() call in 
196564        ** rbuMoveOalFile(). */
196565        p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
196566      }
196567    }
196568  }
196569  
196570  /*
196571  ** Called when iAmt bytes are read from offset iOff of the wal file while
196572  ** the rbu object is in capture mode. Record the frame number of the frame
196573  ** being read in the aFrame[] array.
196574  */
196575  static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
196576    const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
196577    u32 iFrame;
196578  
196579    if( pRbu->mLock!=mReq ){
196580      pRbu->rc = SQLITE_BUSY;
196581      return SQLITE_INTERNAL;
196582    }
196583  
196584    pRbu->pgsz = iAmt;
196585    if( pRbu->nFrame==pRbu->nFrameAlloc ){
196586      int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
196587      RbuFrame *aNew;
196588      aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
196589      if( aNew==0 ) return SQLITE_NOMEM;
196590      pRbu->aFrame = aNew;
196591      pRbu->nFrameAlloc = nNew;
196592    }
196593  
196594    iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
196595    if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
196596    pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
196597    pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
196598    pRbu->nFrame++;
196599    return SQLITE_OK;
196600  }
196601  
196602  /*
196603  ** Called when a page of data is written to offset iOff of the database
196604  ** file while the rbu handle is in capture mode. Record the page number 
196605  ** of the page being written in the aFrame[] array.
196606  */
196607  static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
196608    pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
196609    return SQLITE_OK;
196610  }
196611  
196612  /*
196613  ** This is called as part of an incremental checkpoint operation. Copy
196614  ** a single frame of data from the wal file into the database file, as
196615  ** indicated by the RbuFrame object.
196616  */
196617  static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
196618    sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
196619    sqlite3_file *pDb = p->pTargetFd->pReal;
196620    i64 iOff;
196621  
196622    assert( p->rc==SQLITE_OK );
196623    iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
196624    p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
196625    if( p->rc ) return;
196626  
196627    iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
196628    p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
196629  }
196630  
196631  
196632  /*
196633  ** Take an EXCLUSIVE lock on the database file.
196634  */
196635  static void rbuLockDatabase(sqlite3rbu *p){
196636    sqlite3_file *pReal = p->pTargetFd->pReal;
196637    assert( p->rc==SQLITE_OK );
196638    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
196639    if( p->rc==SQLITE_OK ){
196640      p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
196641    }
196642  }
196643  
196644  #if defined(_WIN32_WCE)
196645  static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
196646    int nChar;
196647    LPWSTR zWideFilename;
196648  
196649    nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
196650    if( nChar==0 ){
196651      return 0;
196652    }
196653    zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
196654    if( zWideFilename==0 ){
196655      return 0;
196656    }
196657    memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
196658    nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
196659                                  nChar);
196660    if( nChar==0 ){
196661      sqlite3_free(zWideFilename);
196662      zWideFilename = 0;
196663    }
196664    return zWideFilename;
196665  }
196666  #endif
196667  
196668  /*
196669  ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
196670  ** on the database file. This proc moves the *-oal file to the *-wal path,
196671  ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
196672  ** If an error occurs, leave an error code and error message in the rbu 
196673  ** handle.
196674  */
196675  static void rbuMoveOalFile(sqlite3rbu *p){
196676    const char *zBase = sqlite3_db_filename(p->dbMain, "main");
196677    const char *zMove = zBase;
196678    char *zOal;
196679    char *zWal;
196680  
196681    if( rbuIsVacuum(p) ){
196682      zMove = sqlite3_db_filename(p->dbRbu, "main");
196683    }
196684    zOal = sqlite3_mprintf("%s-oal", zMove);
196685    zWal = sqlite3_mprintf("%s-wal", zMove);
196686  
196687    assert( p->eStage==RBU_STAGE_MOVE );
196688    assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
196689    if( zWal==0 || zOal==0 ){
196690      p->rc = SQLITE_NOMEM;
196691    }else{
196692      /* Move the *-oal file to *-wal. At this point connection p->db is
196693      ** holding a SHARED lock on the target database file (because it is
196694      ** in WAL mode). So no other connection may be writing the db. 
196695      **
196696      ** In order to ensure that there are no database readers, an EXCLUSIVE
196697      ** lock is obtained here before the *-oal is moved to *-wal.
196698      */
196699      rbuLockDatabase(p);
196700      if( p->rc==SQLITE_OK ){
196701        rbuFileSuffix3(zBase, zWal);
196702        rbuFileSuffix3(zBase, zOal);
196703  
196704        /* Re-open the databases. */
196705        rbuObjIterFinalize(&p->objiter);
196706        sqlite3_close(p->dbRbu);
196707        sqlite3_close(p->dbMain);
196708        p->dbMain = 0;
196709        p->dbRbu = 0;
196710  
196711  #if defined(_WIN32_WCE)
196712        {
196713          LPWSTR zWideOal;
196714          LPWSTR zWideWal;
196715  
196716          zWideOal = rbuWinUtf8ToUnicode(zOal);
196717          if( zWideOal ){
196718            zWideWal = rbuWinUtf8ToUnicode(zWal);
196719            if( zWideWal ){
196720              if( MoveFileW(zWideOal, zWideWal) ){
196721                p->rc = SQLITE_OK;
196722              }else{
196723                p->rc = SQLITE_IOERR;
196724              }
196725              sqlite3_free(zWideWal);
196726            }else{
196727              p->rc = SQLITE_IOERR_NOMEM;
196728            }
196729            sqlite3_free(zWideOal);
196730          }else{
196731            p->rc = SQLITE_IOERR_NOMEM;
196732          }
196733        }
196734  #else
196735        p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
196736  #endif
196737  
196738        if( p->rc==SQLITE_OK ){
196739          rbuOpenDatabase(p, 0);
196740          rbuSetupCheckpoint(p, 0);
196741        }
196742      }
196743    }
196744  
196745    sqlite3_free(zWal);
196746    sqlite3_free(zOal);
196747  }
196748  
196749  /*
196750  ** The SELECT statement iterating through the keys for the current object
196751  ** (p->objiter.pSelect) currently points to a valid row. This function
196752  ** determines the type of operation requested by this row and returns
196753  ** one of the following values to indicate the result:
196754  **
196755  **     * RBU_INSERT
196756  **     * RBU_DELETE
196757  **     * RBU_IDX_DELETE
196758  **     * RBU_UPDATE
196759  **
196760  ** If RBU_UPDATE is returned, then output variable *pzMask is set to
196761  ** point to the text value indicating the columns to update.
196762  **
196763  ** If the rbu_control field contains an invalid value, an error code and
196764  ** message are left in the RBU handle and zero returned.
196765  */
196766  static int rbuStepType(sqlite3rbu *p, const char **pzMask){
196767    int iCol = p->objiter.nCol;     /* Index of rbu_control column */
196768    int res = 0;                    /* Return value */
196769  
196770    switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
196771      case SQLITE_INTEGER: {
196772        int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
196773        switch( iVal ){
196774          case 0: res = RBU_INSERT;     break;
196775          case 1: res = RBU_DELETE;     break;
196776          case 2: res = RBU_REPLACE;    break;
196777          case 3: res = RBU_IDX_DELETE; break;
196778          case 4: res = RBU_IDX_INSERT; break;
196779        }
196780        break;
196781      }
196782  
196783      case SQLITE_TEXT: {
196784        const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
196785        if( z==0 ){
196786          p->rc = SQLITE_NOMEM;
196787        }else{
196788          *pzMask = (const char*)z;
196789        }
196790        res = RBU_UPDATE;
196791  
196792        break;
196793      }
196794  
196795      default:
196796        break;
196797    }
196798  
196799    if( res==0 ){
196800      rbuBadControlError(p);
196801    }
196802    return res;
196803  }
196804  
196805  #ifdef SQLITE_DEBUG
196806  /*
196807  ** Assert that column iCol of statement pStmt is named zName.
196808  */
196809  static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
196810    const char *zCol = sqlite3_column_name(pStmt, iCol);
196811    assert( 0==sqlite3_stricmp(zName, zCol) );
196812  }
196813  #else
196814  # define assertColumnName(x,y,z)
196815  #endif
196816  
196817  /*
196818  ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
196819  ** RBU_IDX_DELETE. This function performs the work of a single
196820  ** sqlite3rbu_step() call for the type of operation specified by eType.
196821  */
196822  static void rbuStepOneOp(sqlite3rbu *p, int eType){
196823    RbuObjIter *pIter = &p->objiter;
196824    sqlite3_value *pVal;
196825    sqlite3_stmt *pWriter;
196826    int i;
196827  
196828    assert( p->rc==SQLITE_OK );
196829    assert( eType!=RBU_DELETE || pIter->zIdx==0 );
196830    assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
196831         || eType==RBU_INSERT || eType==RBU_IDX_INSERT
196832    );
196833  
196834    /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
196835    ** statement below does actually delete a row, nPhaseOneStep will be
196836    ** incremented by the same amount when SQL function rbu_tmp_insert()
196837    ** is invoked by the trigger.  */
196838    if( eType==RBU_DELETE ){
196839      p->nPhaseOneStep -= p->objiter.nIndex;
196840    }
196841  
196842    if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
196843      pWriter = pIter->pDelete;
196844    }else{
196845      pWriter = pIter->pInsert;
196846    }
196847  
196848    for(i=0; i<pIter->nCol; i++){
196849      /* If this is an INSERT into a table b-tree and the table has an
196850      ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
196851      ** to write a NULL into the IPK column. That is not permitted.  */
196852      if( eType==RBU_INSERT 
196853       && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] 
196854       && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
196855      ){
196856        p->rc = SQLITE_MISMATCH;
196857        p->zErrmsg = sqlite3_mprintf("datatype mismatch");
196858        return;
196859      }
196860  
196861      if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
196862        continue;
196863      }
196864  
196865      pVal = sqlite3_column_value(pIter->pSelect, i);
196866      p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
196867      if( p->rc ) return;
196868    }
196869    if( pIter->zIdx==0 ){
196870      if( pIter->eType==RBU_PK_VTAB 
196871       || pIter->eType==RBU_PK_NONE 
196872       || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) 
196873      ){
196874        /* For a virtual table, or a table with no primary key, the 
196875        ** SELECT statement is:
196876        **
196877        **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
196878        **
196879        ** Hence column_value(pIter->nCol+1).
196880        */
196881        assertColumnName(pIter->pSelect, pIter->nCol+1, 
196882            rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
196883        );
196884        pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
196885        p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
196886      }
196887    }
196888    if( p->rc==SQLITE_OK ){
196889      sqlite3_step(pWriter);
196890      p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
196891    }
196892  }
196893  
196894  /*
196895  ** This function does the work for an sqlite3rbu_step() call.
196896  **
196897  ** The object-iterator (p->objiter) currently points to a valid object,
196898  ** and the input cursor (p->objiter.pSelect) currently points to a valid
196899  ** input row. Perform whatever processing is required and return.
196900  **
196901  ** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
196902  ** and message is left in the RBU handle and a copy of the error code
196903  ** returned.
196904  */
196905  static int rbuStep(sqlite3rbu *p){
196906    RbuObjIter *pIter = &p->objiter;
196907    const char *zMask = 0;
196908    int eType = rbuStepType(p, &zMask);
196909  
196910    if( eType ){
196911      assert( eType==RBU_INSERT     || eType==RBU_DELETE
196912           || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
196913           || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
196914      );
196915      assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
196916  
196917      if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
196918        rbuBadControlError(p);
196919      }
196920      else if( eType==RBU_REPLACE ){
196921        if( pIter->zIdx==0 ){
196922          p->nPhaseOneStep += p->objiter.nIndex;
196923          rbuStepOneOp(p, RBU_DELETE);
196924        }
196925        if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
196926      }
196927      else if( eType!=RBU_UPDATE ){
196928        rbuStepOneOp(p, eType);
196929      }
196930      else{
196931        sqlite3_value *pVal;
196932        sqlite3_stmt *pUpdate = 0;
196933        assert( eType==RBU_UPDATE );
196934        p->nPhaseOneStep -= p->objiter.nIndex;
196935        rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
196936        if( pUpdate ){
196937          int i;
196938          for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
196939            char c = zMask[pIter->aiSrcOrder[i]];
196940            pVal = sqlite3_column_value(pIter->pSelect, i);
196941            if( pIter->abTblPk[i] || c!='.' ){
196942              p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
196943            }
196944          }
196945          if( p->rc==SQLITE_OK 
196946           && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) 
196947          ){
196948            /* Bind the rbu_rowid value to column _rowid_ */
196949            assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
196950            pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
196951            p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
196952          }
196953          if( p->rc==SQLITE_OK ){
196954            sqlite3_step(pUpdate);
196955            p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
196956          }
196957        }
196958      }
196959    }
196960    return p->rc;
196961  }
196962  
196963  /*
196964  ** Increment the schema cookie of the main database opened by p->dbMain.
196965  **
196966  ** Or, if this is an RBU vacuum, set the schema cookie of the main db
196967  ** opened by p->dbMain to one more than the schema cookie of the main
196968  ** db opened by p->dbRbu.
196969  */
196970  static void rbuIncrSchemaCookie(sqlite3rbu *p){
196971    if( p->rc==SQLITE_OK ){
196972      sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
196973      int iCookie = 1000000;
196974      sqlite3_stmt *pStmt;
196975  
196976      p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, 
196977          "PRAGMA schema_version"
196978      );
196979      if( p->rc==SQLITE_OK ){
196980        /* Coverage: it may be that this sqlite3_step() cannot fail. There
196981        ** is already a transaction open, so the prepared statement cannot
196982        ** throw an SQLITE_SCHEMA exception. The only database page the
196983        ** statement reads is page 1, which is guaranteed to be in the cache.
196984        ** And no memory allocations are required.  */
196985        if( SQLITE_ROW==sqlite3_step(pStmt) ){
196986          iCookie = sqlite3_column_int(pStmt, 0);
196987        }
196988        rbuFinalize(p, pStmt);
196989      }
196990      if( p->rc==SQLITE_OK ){
196991        rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
196992      }
196993    }
196994  }
196995  
196996  /*
196997  ** Update the contents of the rbu_state table within the rbu database. The
196998  ** value stored in the RBU_STATE_STAGE column is eStage. All other values
196999  ** are determined by inspecting the rbu handle passed as the first argument.
197000  */
197001  static void rbuSaveState(sqlite3rbu *p, int eStage){
197002    if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
197003      sqlite3_stmt *pInsert = 0;
197004      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
197005      int rc;
197006  
197007      assert( p->zErrmsg==0 );
197008      rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, 
197009          sqlite3_mprintf(
197010            "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
197011            "(%d, %d), "
197012            "(%d, %Q), "
197013            "(%d, %Q), "
197014            "(%d, %d), "
197015            "(%d, %d), "
197016            "(%d, %lld), "
197017            "(%d, %lld), "
197018            "(%d, %lld), "
197019            "(%d, %lld), "
197020            "(%d, %Q)  ",
197021            p->zStateDb,
197022            RBU_STATE_STAGE, eStage,
197023            RBU_STATE_TBL, p->objiter.zTbl, 
197024            RBU_STATE_IDX, p->objiter.zIdx, 
197025            RBU_STATE_ROW, p->nStep, 
197026            RBU_STATE_PROGRESS, p->nProgress,
197027            RBU_STATE_CKPT, p->iWalCksum,
197028            RBU_STATE_COOKIE, (i64)pFd->iCookie,
197029            RBU_STATE_OALSZ, p->iOalSz,
197030            RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
197031            RBU_STATE_DATATBL, p->objiter.zDataTbl
197032        )
197033      );
197034      assert( pInsert==0 || rc==SQLITE_OK );
197035  
197036      if( rc==SQLITE_OK ){
197037        sqlite3_step(pInsert);
197038        rc = sqlite3_finalize(pInsert);
197039      }
197040      if( rc!=SQLITE_OK ) p->rc = rc;
197041    }
197042  }
197043  
197044  
197045  /*
197046  ** The second argument passed to this function is the name of a PRAGMA 
197047  ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
197048  ** This function executes the following on sqlite3rbu.dbRbu:
197049  **
197050  **   "PRAGMA main.$zPragma"
197051  **
197052  ** where $zPragma is the string passed as the second argument, then
197053  ** on sqlite3rbu.dbMain:
197054  **
197055  **   "PRAGMA main.$zPragma = $val"
197056  **
197057  ** where $val is the value returned by the first PRAGMA invocation.
197058  **
197059  ** In short, it copies the value  of the specified PRAGMA setting from
197060  ** dbRbu to dbMain.
197061  */
197062  static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
197063    if( p->rc==SQLITE_OK ){
197064      sqlite3_stmt *pPragma = 0;
197065      p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, 
197066          sqlite3_mprintf("PRAGMA main.%s", zPragma)
197067      );
197068      if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
197069        p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
197070            zPragma, sqlite3_column_int(pPragma, 0)
197071        );
197072      }
197073      rbuFinalize(p, pPragma);
197074    }
197075  }
197076  
197077  /*
197078  ** The RBU handle passed as the only argument has just been opened and 
197079  ** the state database is empty. If this RBU handle was opened for an
197080  ** RBU vacuum operation, create the schema in the target db.
197081  */
197082  static void rbuCreateTargetSchema(sqlite3rbu *p){
197083    sqlite3_stmt *pSql = 0;
197084    sqlite3_stmt *pInsert = 0;
197085  
197086    assert( rbuIsVacuum(p) );
197087    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
197088    if( p->rc==SQLITE_OK ){
197089      p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
197090        "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
197091        " AND name!='sqlite_sequence' "
197092        " ORDER BY type DESC"
197093      );
197094    }
197095  
197096    while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
197097      const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
197098      p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
197099    }
197100    rbuFinalize(p, pSql);
197101    if( p->rc!=SQLITE_OK ) return;
197102  
197103    if( p->rc==SQLITE_OK ){
197104      p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
197105          "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" 
197106      );
197107    }
197108  
197109    if( p->rc==SQLITE_OK ){
197110      p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, 
197111          "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
197112      );
197113    }
197114  
197115    while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
197116      int i;
197117      for(i=0; i<5; i++){
197118        sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
197119      }
197120      sqlite3_step(pInsert);
197121      p->rc = sqlite3_reset(pInsert);
197122    }
197123    if( p->rc==SQLITE_OK ){
197124      p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
197125    }
197126  
197127    rbuFinalize(p, pSql);
197128    rbuFinalize(p, pInsert);
197129  }
197130  
197131  /*
197132  ** Step the RBU object.
197133  */
197134  SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
197135    if( p ){
197136      switch( p->eStage ){
197137        case RBU_STAGE_OAL: {
197138          RbuObjIter *pIter = &p->objiter;
197139  
197140          /* If this is an RBU vacuum operation and the state table was empty
197141          ** when this handle was opened, create the target database schema. */
197142          if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
197143            rbuCreateTargetSchema(p);
197144            rbuCopyPragma(p, "user_version");
197145            rbuCopyPragma(p, "application_id");
197146          }
197147  
197148          while( p->rc==SQLITE_OK && pIter->zTbl ){
197149  
197150            if( pIter->bCleanup ){
197151              /* Clean up the rbu_tmp_xxx table for the previous table. It 
197152              ** cannot be dropped as there are currently active SQL statements.
197153              ** But the contents can be deleted.  */
197154              if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
197155                rbuMPrintfExec(p, p->dbRbu, 
197156                    "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
197157                );
197158              }
197159            }else{
197160              rbuObjIterPrepareAll(p, pIter, 0);
197161  
197162              /* Advance to the next row to process. */
197163              if( p->rc==SQLITE_OK ){
197164                int rc = sqlite3_step(pIter->pSelect);
197165                if( rc==SQLITE_ROW ){
197166                  p->nProgress++;
197167                  p->nStep++;
197168                  return rbuStep(p);
197169                }
197170                p->rc = sqlite3_reset(pIter->pSelect);
197171                p->nStep = 0;
197172              }
197173            }
197174  
197175            rbuObjIterNext(p, pIter);
197176          }
197177  
197178          if( p->rc==SQLITE_OK ){
197179            assert( pIter->zTbl==0 );
197180            rbuSaveState(p, RBU_STAGE_MOVE);
197181            rbuIncrSchemaCookie(p);
197182            if( p->rc==SQLITE_OK ){
197183              p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
197184            }
197185            if( p->rc==SQLITE_OK ){
197186              p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
197187            }
197188            p->eStage = RBU_STAGE_MOVE;
197189          }
197190          break;
197191        }
197192  
197193        case RBU_STAGE_MOVE: {
197194          if( p->rc==SQLITE_OK ){
197195            rbuMoveOalFile(p);
197196            p->nProgress++;
197197          }
197198          break;
197199        }
197200  
197201        case RBU_STAGE_CKPT: {
197202          if( p->rc==SQLITE_OK ){
197203            if( p->nStep>=p->nFrame ){
197204              sqlite3_file *pDb = p->pTargetFd->pReal;
197205    
197206              /* Sync the db file */
197207              p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
197208    
197209              /* Update nBackfill */
197210              if( p->rc==SQLITE_OK ){
197211                void volatile *ptr;
197212                p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
197213                if( p->rc==SQLITE_OK ){
197214                  ((u32 volatile*)ptr)[24] = p->iMaxFrame;
197215                }
197216              }
197217    
197218              if( p->rc==SQLITE_OK ){
197219                p->eStage = RBU_STAGE_DONE;
197220                p->rc = SQLITE_DONE;
197221              }
197222            }else{
197223              /* At one point the following block copied a single frame from the
197224              ** wal file to the database file. So that one call to sqlite3rbu_step()
197225              ** checkpointed a single frame. 
197226              **
197227              ** However, if the sector-size is larger than the page-size, and the
197228              ** application calls sqlite3rbu_savestate() or close() immediately
197229              ** after this step, then rbu_step() again, then a power failure occurs,
197230              ** then the database page written here may be damaged. Work around
197231              ** this by checkpointing frames until the next page in the aFrame[]
197232              ** lies on a different disk sector to the current one. */
197233              u32 iSector;
197234              do{
197235                RbuFrame *pFrame = &p->aFrame[p->nStep];
197236                iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
197237                rbuCheckpointFrame(p, pFrame);
197238                p->nStep++;
197239              }while( p->nStep<p->nFrame 
197240                   && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
197241                   && p->rc==SQLITE_OK
197242              );
197243            }
197244            p->nProgress++;
197245          }
197246          break;
197247        }
197248  
197249        default:
197250          break;
197251      }
197252      return p->rc;
197253    }else{
197254      return SQLITE_NOMEM;
197255    }
197256  }
197257  
197258  /*
197259  ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
197260  ** otherwise. Either or both argument may be NULL. Two NULL values are
197261  ** considered equal, and NULL is considered distinct from all other values.
197262  */
197263  static int rbuStrCompare(const char *z1, const char *z2){
197264    if( z1==0 && z2==0 ) return 0;
197265    if( z1==0 || z2==0 ) return 1;
197266    return (sqlite3_stricmp(z1, z2)!=0);
197267  }
197268  
197269  /*
197270  ** This function is called as part of sqlite3rbu_open() when initializing
197271  ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
197272  ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
197273  ** things so that the next call to sqlite3rbu_step() continues on from
197274  ** where the previous rbu handle left off.
197275  **
197276  ** If an error occurs, an error code and error message are left in the
197277  ** rbu handle passed as the first argument.
197278  */
197279  static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
197280    assert( p->rc==SQLITE_OK );
197281    if( pState->zTbl ){
197282      RbuObjIter *pIter = &p->objiter;
197283      int rc = SQLITE_OK;
197284  
197285      while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup 
197286         || rbuStrCompare(pIter->zIdx, pState->zIdx)
197287         || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
197288         || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
197289      )){
197290        rc = rbuObjIterNext(p, pIter);
197291      }
197292  
197293      if( rc==SQLITE_OK && !pIter->zTbl ){
197294        rc = SQLITE_ERROR;
197295        p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
197296      }
197297  
197298      if( rc==SQLITE_OK ){
197299        p->nStep = pState->nRow;
197300        rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
197301      }
197302  
197303      p->rc = rc;
197304    }
197305  }
197306  
197307  /*
197308  ** If there is a "*-oal" file in the file-system corresponding to the
197309  ** target database in the file-system, delete it. If an error occurs,
197310  ** leave an error code and error message in the rbu handle.
197311  */
197312  static void rbuDeleteOalFile(sqlite3rbu *p){
197313    char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
197314    if( zOal ){
197315      sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
197316      assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
197317      pVfs->xDelete(pVfs, zOal, 0);
197318      sqlite3_free(zOal);
197319    }
197320  }
197321  
197322  /*
197323  ** Allocate a private rbu VFS for the rbu handle passed as the only
197324  ** argument. This VFS will be used unless the call to sqlite3rbu_open()
197325  ** specified a URI with a vfs=? option in place of a target database
197326  ** file name.
197327  */
197328  static void rbuCreateVfs(sqlite3rbu *p){
197329    int rnd;
197330    char zRnd[64];
197331  
197332    assert( p->rc==SQLITE_OK );
197333    sqlite3_randomness(sizeof(int), (void*)&rnd);
197334    sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
197335    p->rc = sqlite3rbu_create_vfs(zRnd, 0);
197336    if( p->rc==SQLITE_OK ){
197337      sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
197338      assert( pVfs );
197339      p->zVfsName = pVfs->zName;
197340      ((rbu_vfs*)pVfs)->pRbu = p;
197341    }
197342  }
197343  
197344  /*
197345  ** Destroy the private VFS created for the rbu handle passed as the only
197346  ** argument by an earlier call to rbuCreateVfs().
197347  */
197348  static void rbuDeleteVfs(sqlite3rbu *p){
197349    if( p->zVfsName ){
197350      sqlite3rbu_destroy_vfs(p->zVfsName);
197351      p->zVfsName = 0;
197352    }
197353  }
197354  
197355  /*
197356  ** This user-defined SQL function is invoked with a single argument - the
197357  ** name of a table expected to appear in the target database. It returns
197358  ** the number of auxilliary indexes on the table.
197359  */
197360  static void rbuIndexCntFunc(
197361    sqlite3_context *pCtx, 
197362    int nVal,
197363    sqlite3_value **apVal
197364  ){
197365    sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
197366    sqlite3_stmt *pStmt = 0;
197367    char *zErrmsg = 0;
197368    int rc;
197369  
197370    assert( nVal==1 );
197371    
197372    rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, 
197373        sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
197374          "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
197375    );
197376    if( rc!=SQLITE_OK ){
197377      sqlite3_result_error(pCtx, zErrmsg, -1);
197378    }else{
197379      int nIndex = 0;
197380      if( SQLITE_ROW==sqlite3_step(pStmt) ){
197381        nIndex = sqlite3_column_int(pStmt, 0);
197382      }
197383      rc = sqlite3_finalize(pStmt);
197384      if( rc==SQLITE_OK ){
197385        sqlite3_result_int(pCtx, nIndex);
197386      }else{
197387        sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
197388      }
197389    }
197390  
197391    sqlite3_free(zErrmsg);
197392  }
197393  
197394  /*
197395  ** If the RBU database contains the rbu_count table, use it to initialize
197396  ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
197397  ** is assumed to contain the same columns as:
197398  **
197399  **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
197400  **
197401  ** There should be one row in the table for each data_xxx table in the
197402  ** database. The 'tbl' column should contain the name of a data_xxx table,
197403  ** and the cnt column the number of rows it contains.
197404  **
197405  ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
197406  ** for all rows in the rbu_count table, where nIndex is the number of 
197407  ** indexes on the corresponding target database table.
197408  */
197409  static void rbuInitPhaseOneSteps(sqlite3rbu *p){
197410    if( p->rc==SQLITE_OK ){
197411      sqlite3_stmt *pStmt = 0;
197412      int bExists = 0;                /* True if rbu_count exists */
197413  
197414      p->nPhaseOneStep = -1;
197415  
197416      p->rc = sqlite3_create_function(p->dbRbu, 
197417          "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
197418      );
197419    
197420      /* Check for the rbu_count table. If it does not exist, or if an error
197421      ** occurs, nPhaseOneStep will be left set to -1. */
197422      if( p->rc==SQLITE_OK ){
197423        p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
197424            "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
197425        );
197426      }
197427      if( p->rc==SQLITE_OK ){
197428        if( SQLITE_ROW==sqlite3_step(pStmt) ){
197429          bExists = 1;
197430        }
197431        p->rc = sqlite3_finalize(pStmt);
197432      }
197433    
197434      if( p->rc==SQLITE_OK && bExists ){
197435        p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
197436            "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
197437            "FROM rbu_count"
197438        );
197439        if( p->rc==SQLITE_OK ){
197440          if( SQLITE_ROW==sqlite3_step(pStmt) ){
197441            p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
197442          }
197443          p->rc = sqlite3_finalize(pStmt);
197444        }
197445      }
197446    }
197447  }
197448  
197449  
197450  static sqlite3rbu *openRbuHandle(
197451    const char *zTarget, 
197452    const char *zRbu,
197453    const char *zState
197454  ){
197455    sqlite3rbu *p;
197456    size_t nTarget = zTarget ? strlen(zTarget) : 0;
197457    size_t nRbu = strlen(zRbu);
197458    size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
197459  
197460    p = (sqlite3rbu*)sqlite3_malloc64(nByte);
197461    if( p ){
197462      RbuState *pState = 0;
197463  
197464      /* Create the custom VFS. */
197465      memset(p, 0, sizeof(sqlite3rbu));
197466      rbuCreateVfs(p);
197467  
197468      /* Open the target, RBU and state databases */
197469      if( p->rc==SQLITE_OK ){
197470        char *pCsr = (char*)&p[1];
197471        int bRetry = 0;
197472        if( zTarget ){
197473          p->zTarget = pCsr;
197474          memcpy(p->zTarget, zTarget, nTarget+1);
197475          pCsr += nTarget+1;
197476        }
197477        p->zRbu = pCsr;
197478        memcpy(p->zRbu, zRbu, nRbu+1);
197479        pCsr += nRbu+1;
197480        if( zState ){
197481          p->zState = rbuMPrintf(p, "%s", zState);
197482        }
197483  
197484        /* If the first attempt to open the database file fails and the bRetry
197485        ** flag it set, this means that the db was not opened because it seemed
197486        ** to be a wal-mode db. But, this may have happened due to an earlier
197487        ** RBU vacuum operation leaving an old wal file in the directory.
197488        ** If this is the case, it will have been checkpointed and deleted
197489        ** when the handle was closed and a second attempt to open the 
197490        ** database may succeed.  */
197491        rbuOpenDatabase(p, &bRetry);
197492        if( bRetry ){
197493          rbuOpenDatabase(p, 0);
197494        }
197495      }
197496  
197497      if( p->rc==SQLITE_OK ){
197498        pState = rbuLoadState(p);
197499        assert( pState || p->rc!=SQLITE_OK );
197500        if( p->rc==SQLITE_OK ){
197501  
197502          if( pState->eStage==0 ){ 
197503            rbuDeleteOalFile(p);
197504            rbuInitPhaseOneSteps(p);
197505            p->eStage = RBU_STAGE_OAL;
197506          }else{
197507            p->eStage = pState->eStage;
197508            p->nPhaseOneStep = pState->nPhaseOneStep;
197509          }
197510          p->nProgress = pState->nProgress;
197511          p->iOalSz = pState->iOalSz;
197512        }
197513      }
197514      assert( p->rc!=SQLITE_OK || p->eStage!=0 );
197515  
197516      if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
197517        if( p->eStage==RBU_STAGE_OAL ){
197518          p->rc = SQLITE_ERROR;
197519          p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
197520        }else if( p->eStage==RBU_STAGE_MOVE ){
197521          p->eStage = RBU_STAGE_CKPT;
197522          p->nStep = 0;
197523        }
197524      }
197525  
197526      if( p->rc==SQLITE_OK 
197527       && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
197528       && pState->eStage!=0
197529      ){
197530        rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
197531        if( pFd->iCookie!=pState->iCookie ){   
197532          /* At this point (pTargetFd->iCookie) contains the value of the
197533          ** change-counter cookie (the thing that gets incremented when a 
197534          ** transaction is committed in rollback mode) currently stored on 
197535          ** page 1 of the database file. */
197536          p->rc = SQLITE_BUSY;
197537          p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
197538              (rbuIsVacuum(p) ? "vacuum" : "update")
197539          );
197540        }
197541      }
197542  
197543      if( p->rc==SQLITE_OK ){
197544        if( p->eStage==RBU_STAGE_OAL ){
197545          sqlite3 *db = p->dbMain;
197546          p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
197547  
197548          /* Point the object iterator at the first object */
197549          if( p->rc==SQLITE_OK ){
197550            p->rc = rbuObjIterFirst(p, &p->objiter);
197551          }
197552  
197553          /* If the RBU database contains no data_xxx tables, declare the RBU
197554          ** update finished.  */
197555          if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
197556            p->rc = SQLITE_DONE;
197557            p->eStage = RBU_STAGE_DONE;
197558          }else{
197559            if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
197560              rbuCopyPragma(p, "page_size");
197561              rbuCopyPragma(p, "auto_vacuum");
197562            }
197563  
197564            /* Open transactions both databases. The *-oal file is opened or
197565            ** created at this point. */
197566            if( p->rc==SQLITE_OK ){
197567              p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
197568            }
197569  
197570            /* Check if the main database is a zipvfs db. If it is, set the upper
197571            ** level pager to use "journal_mode=off". This prevents it from 
197572            ** generating a large journal using a temp file.  */
197573            if( p->rc==SQLITE_OK ){
197574              int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
197575              if( frc==SQLITE_OK ){
197576                p->rc = sqlite3_exec(
197577                  db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
197578              }
197579            }
197580  
197581            if( p->rc==SQLITE_OK ){
197582              rbuSetupOal(p, pState);
197583            }
197584          }
197585        }else if( p->eStage==RBU_STAGE_MOVE ){
197586          /* no-op */
197587        }else if( p->eStage==RBU_STAGE_CKPT ){
197588          rbuSetupCheckpoint(p, pState);
197589        }else if( p->eStage==RBU_STAGE_DONE ){
197590          p->rc = SQLITE_DONE;
197591        }else{
197592          p->rc = SQLITE_CORRUPT;
197593        }
197594      }
197595  
197596      rbuFreeState(pState);
197597    }
197598  
197599    return p;
197600  }
197601  
197602  /*
197603  ** Allocate and return an RBU handle with all fields zeroed except for the
197604  ** error code, which is set to SQLITE_MISUSE.
197605  */
197606  static sqlite3rbu *rbuMisuseError(void){
197607    sqlite3rbu *pRet;
197608    pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
197609    if( pRet ){
197610      memset(pRet, 0, sizeof(sqlite3rbu));
197611      pRet->rc = SQLITE_MISUSE;
197612    }
197613    return pRet;
197614  }
197615  
197616  /*
197617  ** Open and return a new RBU handle. 
197618  */
197619  SQLITE_API sqlite3rbu *sqlite3rbu_open(
197620    const char *zTarget, 
197621    const char *zRbu,
197622    const char *zState
197623  ){
197624    if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
197625    /* TODO: Check that zTarget and zRbu are non-NULL */
197626    return openRbuHandle(zTarget, zRbu, zState);
197627  }
197628  
197629  /*
197630  ** Open a handle to begin or resume an RBU VACUUM operation.
197631  */
197632  SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
197633    const char *zTarget, 
197634    const char *zState
197635  ){
197636    if( zTarget==0 ){ return rbuMisuseError(); }
197637    if( zState ){
197638      int n = strlen(zState);
197639      if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
197640        return rbuMisuseError();
197641      }
197642    }
197643    /* TODO: Check that both arguments are non-NULL */
197644    return openRbuHandle(0, zTarget, zState);
197645  }
197646  
197647  /*
197648  ** Return the database handle used by pRbu.
197649  */
197650  SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
197651    sqlite3 *db = 0;
197652    if( pRbu ){
197653      db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
197654    }
197655    return db;
197656  }
197657  
197658  
197659  /*
197660  ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
197661  ** then edit any error message string so as to remove all occurrences of
197662  ** the pattern "rbu_imp_[0-9]*".
197663  */
197664  static void rbuEditErrmsg(sqlite3rbu *p){
197665    if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
197666      unsigned int i;
197667      size_t nErrmsg = strlen(p->zErrmsg);
197668      for(i=0; i<(nErrmsg-8); i++){
197669        if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
197670          int nDel = 8;
197671          while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
197672          memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
197673          nErrmsg -= nDel;
197674        }
197675      }
197676    }
197677  }
197678  
197679  /*
197680  ** Close the RBU handle.
197681  */
197682  SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
197683    int rc;
197684    if( p ){
197685  
197686      /* Commit the transaction to the *-oal file. */
197687      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
197688        p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
197689      }
197690  
197691      /* Sync the db file if currently doing an incremental checkpoint */
197692      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
197693        sqlite3_file *pDb = p->pTargetFd->pReal;
197694        p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
197695      }
197696  
197697      rbuSaveState(p, p->eStage);
197698  
197699      if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
197700        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
197701      }
197702  
197703      /* Close any open statement handles. */
197704      rbuObjIterFinalize(&p->objiter);
197705  
197706      /* If this is an RBU vacuum handle and the vacuum has either finished
197707      ** successfully or encountered an error, delete the contents of the 
197708      ** state table. This causes the next call to sqlite3rbu_vacuum() 
197709      ** specifying the current target and state databases to start a new
197710      ** vacuum from scratch.  */
197711      if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
197712        int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
197713        if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
197714      }
197715  
197716      /* Close the open database handle and VFS object. */
197717      sqlite3_close(p->dbRbu);
197718      sqlite3_close(p->dbMain);
197719      assert( p->szTemp==0 );
197720      rbuDeleteVfs(p);
197721      sqlite3_free(p->aBuf);
197722      sqlite3_free(p->aFrame);
197723  
197724      rbuEditErrmsg(p);
197725      rc = p->rc;
197726      if( pzErrmsg ){
197727        *pzErrmsg = p->zErrmsg;
197728      }else{
197729        sqlite3_free(p->zErrmsg);
197730      }
197731      sqlite3_free(p->zState);
197732      sqlite3_free(p);
197733    }else{
197734      rc = SQLITE_NOMEM;
197735      *pzErrmsg = 0;
197736    }
197737    return rc;
197738  }
197739  
197740  /*
197741  ** Return the total number of key-value operations (inserts, deletes or 
197742  ** updates) that have been performed on the target database since the
197743  ** current RBU update was started.
197744  */
197745  SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
197746    return pRbu->nProgress;
197747  }
197748  
197749  /*
197750  ** Return permyriadage progress indications for the two main stages of
197751  ** an RBU update.
197752  */
197753  SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
197754    const int MAX_PROGRESS = 10000;
197755    switch( p->eStage ){
197756      case RBU_STAGE_OAL:
197757        if( p->nPhaseOneStep>0 ){
197758          *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
197759        }else{
197760          *pnOne = -1;
197761        }
197762        *pnTwo = 0;
197763        break;
197764  
197765      case RBU_STAGE_MOVE:
197766        *pnOne = MAX_PROGRESS;
197767        *pnTwo = 0;
197768        break;
197769  
197770      case RBU_STAGE_CKPT:
197771        *pnOne = MAX_PROGRESS;
197772        *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
197773        break;
197774  
197775      case RBU_STAGE_DONE:
197776        *pnOne = MAX_PROGRESS;
197777        *pnTwo = MAX_PROGRESS;
197778        break;
197779  
197780      default:
197781        assert( 0 );
197782    }
197783  }
197784  
197785  /*
197786  ** Return the current state of the RBU vacuum or update operation.
197787  */
197788  SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
197789    int aRes[] = {
197790      0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
197791      0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
197792    };
197793  
197794    assert( RBU_STAGE_OAL==1 );
197795    assert( RBU_STAGE_MOVE==2 );
197796    assert( RBU_STAGE_CKPT==4 );
197797    assert( RBU_STAGE_DONE==5 );
197798    assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
197799    assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
197800    assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
197801    assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
197802  
197803    if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
197804      return SQLITE_RBU_STATE_ERROR;
197805    }else{
197806      assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
197807      assert( p->eStage==RBU_STAGE_OAL
197808           || p->eStage==RBU_STAGE_MOVE
197809           || p->eStage==RBU_STAGE_CKPT
197810           || p->eStage==RBU_STAGE_DONE
197811      );
197812      return aRes[p->eStage];
197813    }
197814  }
197815  
197816  SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
197817    int rc = p->rc;
197818    if( rc==SQLITE_DONE ) return SQLITE_OK;
197819  
197820    assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
197821    if( p->eStage==RBU_STAGE_OAL ){
197822      assert( rc!=SQLITE_DONE );
197823      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
197824    }
197825  
197826    /* Sync the db file */
197827    if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
197828      sqlite3_file *pDb = p->pTargetFd->pReal;
197829      rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
197830    }
197831  
197832    p->rc = rc;
197833    rbuSaveState(p, p->eStage);
197834    rc = p->rc;
197835  
197836    if( p->eStage==RBU_STAGE_OAL ){
197837      assert( rc!=SQLITE_DONE );
197838      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
197839      if( rc==SQLITE_OK ){ 
197840        const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
197841        rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
197842      }
197843      if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
197844    }
197845  
197846    p->rc = rc;
197847    return rc;
197848  }
197849  
197850  /**************************************************************************
197851  ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
197852  ** of a standard VFS in the following ways:
197853  **
197854  ** 1. Whenever the first page of a main database file is read or 
197855  **    written, the value of the change-counter cookie is stored in
197856  **    rbu_file.iCookie. Similarly, the value of the "write-version"
197857  **    database header field is stored in rbu_file.iWriteVer. This ensures
197858  **    that the values are always trustworthy within an open transaction.
197859  **
197860  ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
197861  **    member variable of the associated database file descriptor is set
197862  **    to point to the new file. A mutex protected linked list of all main 
197863  **    db fds opened using a particular RBU VFS is maintained at 
197864  **    rbu_vfs.pMain to facilitate this.
197865  **
197866  ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file 
197867  **    object can be marked as the target database of an RBU update. This
197868  **    turns on the following extra special behaviour:
197869  **
197870  ** 3a. If xAccess() is called to check if there exists a *-wal file 
197871  **     associated with an RBU target database currently in RBU_STAGE_OAL
197872  **     stage (preparing the *-oal file), the following special handling
197873  **     applies:
197874  **
197875  **      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
197876  **        target database may not be in wal mode already.
197877  **
197878  **      * if the *-wal file does not exist, set the output parameter to
197879  **        non-zero (to tell SQLite that it does exist) anyway.
197880  **
197881  **     Then, when xOpen() is called to open the *-wal file associated with
197882  **     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
197883  **     file, the rbu vfs opens the corresponding *-oal file instead. 
197884  **
197885  ** 3b. The *-shm pages returned by xShmMap() for a target db file in
197886  **     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
197887  **     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
197888  **     are no-ops on target database files in RBU_STAGE_OAL mode. This is
197889  **     because assert() statements in some VFS implementations fail if 
197890  **     xShmLock() is called before xShmMap().
197891  **
197892  ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
197893  **     mode except RBU_STAGE_DONE (all work completed and checkpointed), it 
197894  **     fails with an SQLITE_BUSY error. This is to stop RBU connections
197895  **     from automatically checkpointing a *-wal (or *-oal) file from within
197896  **     sqlite3_close().
197897  **
197898  ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
197899  **     all xWrite() calls on the target database file perform no IO. 
197900  **     Instead the frame and page numbers that would be read and written
197901  **     are recorded. Additionally, successful attempts to obtain exclusive
197902  **     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target 
197903  **     database file are recorded. xShmLock() calls to unlock the same
197904  **     locks are no-ops (so that once obtained, these locks are never
197905  **     relinquished). Finally, calls to xSync() on the target database
197906  **     file fail with SQLITE_INTERNAL errors.
197907  */
197908  
197909  static void rbuUnlockShm(rbu_file *p){
197910    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
197911    if( p->pRbu ){
197912      int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
197913      int i;
197914      for(i=0; i<SQLITE_SHM_NLOCK;i++){
197915        if( (1<<i) & p->pRbu->mLock ){
197916          xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
197917        }
197918      }
197919      p->pRbu->mLock = 0;
197920    }
197921  }
197922  
197923  /*
197924  */
197925  static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
197926    sqlite3rbu *pRbu = pFd->pRbu;
197927    i64 nDiff = nNew - pFd->sz;
197928    pRbu->szTemp += nDiff;
197929    pFd->sz = nNew;
197930    assert( pRbu->szTemp>=0 );
197931    if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
197932    return SQLITE_OK;
197933  }
197934  
197935  /*
197936  ** Add an item to the main-db lists, if it is not already present.
197937  **
197938  ** There are two main-db lists. One for all file descriptors, and one
197939  ** for all file descriptors with rbu_file.pDb!=0. If the argument has
197940  ** rbu_file.pDb!=0, then it is assumed to already be present on the
197941  ** main list and is only added to the pDb!=0 list.
197942  */
197943  static void rbuMainlistAdd(rbu_file *p){
197944    rbu_vfs *pRbuVfs = p->pRbuVfs;
197945    rbu_file *pIter;
197946    assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
197947    sqlite3_mutex_enter(pRbuVfs->mutex);
197948    if( p->pRbu==0 ){
197949      for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
197950      p->pMainNext = pRbuVfs->pMain;
197951      pRbuVfs->pMain = p;
197952    }else{
197953      for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
197954      if( pIter==0 ){
197955        p->pMainRbuNext = pRbuVfs->pMainRbu;
197956        pRbuVfs->pMainRbu = p;
197957      }
197958    }
197959    sqlite3_mutex_leave(pRbuVfs->mutex);
197960  }
197961  
197962  /*
197963  ** Remove an item from the main-db lists.
197964  */
197965  static void rbuMainlistRemove(rbu_file *p){
197966    rbu_file **pp;
197967    sqlite3_mutex_enter(p->pRbuVfs->mutex);
197968    for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
197969    if( *pp ) *pp = p->pMainNext;
197970    p->pMainNext = 0;
197971    for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
197972    if( *pp ) *pp = p->pMainRbuNext;
197973    p->pMainRbuNext = 0;
197974    sqlite3_mutex_leave(p->pRbuVfs->mutex);
197975  }
197976  
197977  /*
197978  ** Given that zWal points to a buffer containing a wal file name passed to 
197979  ** either the xOpen() or xAccess() VFS method, search the main-db list for
197980  ** a file-handle opened by the same database connection on the corresponding
197981  ** database file.
197982  **
197983  ** If parameter bRbu is true, only search for file-descriptors with
197984  ** rbu_file.pDb!=0.
197985  */
197986  static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
197987    rbu_file *pDb;
197988    sqlite3_mutex_enter(pRbuVfs->mutex);
197989    if( bRbu ){
197990      for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
197991    }else{
197992      for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
197993    }
197994    sqlite3_mutex_leave(pRbuVfs->mutex);
197995    return pDb;
197996  }
197997  
197998  /*
197999  ** Close an rbu file.
198000  */
198001  static int rbuVfsClose(sqlite3_file *pFile){
198002    rbu_file *p = (rbu_file*)pFile;
198003    int rc;
198004    int i;
198005  
198006    /* Free the contents of the apShm[] array. And the array itself. */
198007    for(i=0; i<p->nShm; i++){
198008      sqlite3_free(p->apShm[i]);
198009    }
198010    sqlite3_free(p->apShm);
198011    p->apShm = 0;
198012    sqlite3_free(p->zDel);
198013  
198014    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
198015      rbuMainlistRemove(p);
198016      rbuUnlockShm(p);
198017      p->pReal->pMethods->xShmUnmap(p->pReal, 0);
198018    }
198019    else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
198020      rbuUpdateTempSize(p, 0);
198021    }
198022    assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
198023  
198024    /* Close the underlying file handle */
198025    rc = p->pReal->pMethods->xClose(p->pReal);
198026    return rc;
198027  }
198028  
198029  
198030  /*
198031  ** Read and return an unsigned 32-bit big-endian integer from the buffer 
198032  ** passed as the only argument.
198033  */
198034  static u32 rbuGetU32(u8 *aBuf){
198035    return ((u32)aBuf[0] << 24)
198036         + ((u32)aBuf[1] << 16)
198037         + ((u32)aBuf[2] <<  8)
198038         + ((u32)aBuf[3]);
198039  }
198040  
198041  /*
198042  ** Write an unsigned 32-bit value in big-endian format to the supplied
198043  ** buffer.
198044  */
198045  static void rbuPutU32(u8 *aBuf, u32 iVal){
198046    aBuf[0] = (iVal >> 24) & 0xFF;
198047    aBuf[1] = (iVal >> 16) & 0xFF;
198048    aBuf[2] = (iVal >>  8) & 0xFF;
198049    aBuf[3] = (iVal >>  0) & 0xFF;
198050  }
198051  
198052  static void rbuPutU16(u8 *aBuf, u16 iVal){
198053    aBuf[0] = (iVal >>  8) & 0xFF;
198054    aBuf[1] = (iVal >>  0) & 0xFF;
198055  }
198056  
198057  /*
198058  ** Read data from an rbuVfs-file.
198059  */
198060  static int rbuVfsRead(
198061    sqlite3_file *pFile, 
198062    void *zBuf, 
198063    int iAmt, 
198064    sqlite_int64 iOfst
198065  ){
198066    rbu_file *p = (rbu_file*)pFile;
198067    sqlite3rbu *pRbu = p->pRbu;
198068    int rc;
198069  
198070    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
198071      assert( p->openFlags & SQLITE_OPEN_WAL );
198072      rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
198073    }else{
198074      if( pRbu && pRbu->eStage==RBU_STAGE_OAL 
198075       && (p->openFlags & SQLITE_OPEN_WAL) 
198076       && iOfst>=pRbu->iOalSz 
198077      ){
198078        rc = SQLITE_OK;
198079        memset(zBuf, 0, iAmt);
198080      }else{
198081        rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
198082  #if 1
198083        /* If this is being called to read the first page of the target 
198084        ** database as part of an rbu vacuum operation, synthesize the 
198085        ** contents of the first page if it does not yet exist. Otherwise,
198086        ** SQLite will not check for a *-wal file.  */
198087        if( pRbu && rbuIsVacuum(pRbu) 
198088            && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
198089            && (p->openFlags & SQLITE_OPEN_MAIN_DB)
198090            && pRbu->rc==SQLITE_OK
198091        ){
198092          sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
198093          rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
198094          if( rc==SQLITE_OK ){
198095            u8 *aBuf = (u8*)zBuf;
198096            u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
198097            rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
198098            rbuPutU32(&aBuf[36], 0);          /* number of free pages */
198099            rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
198100            rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
198101            rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
198102  
198103            if( iAmt>100 ){
198104              memset(&aBuf[100], 0, iAmt-100);
198105              rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
198106              aBuf[100] = 0x0D;
198107            }
198108          }
198109        }
198110  #endif
198111      }
198112      if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
198113        /* These look like magic numbers. But they are stable, as they are part
198114         ** of the definition of the SQLite file format, which may not change. */
198115        u8 *pBuf = (u8*)zBuf;
198116        p->iCookie = rbuGetU32(&pBuf[24]);
198117        p->iWriteVer = pBuf[19];
198118      }
198119    }
198120    return rc;
198121  }
198122  
198123  /*
198124  ** Write data to an rbuVfs-file.
198125  */
198126  static int rbuVfsWrite(
198127    sqlite3_file *pFile, 
198128    const void *zBuf, 
198129    int iAmt, 
198130    sqlite_int64 iOfst
198131  ){
198132    rbu_file *p = (rbu_file*)pFile;
198133    sqlite3rbu *pRbu = p->pRbu;
198134    int rc;
198135  
198136    if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
198137      assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
198138      rc = rbuCaptureDbWrite(p->pRbu, iOfst);
198139    }else{
198140      if( pRbu ){
198141        if( pRbu->eStage==RBU_STAGE_OAL 
198142         && (p->openFlags & SQLITE_OPEN_WAL) 
198143         && iOfst>=pRbu->iOalSz
198144        ){
198145          pRbu->iOalSz = iAmt + iOfst;
198146        }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
198147          i64 szNew = iAmt+iOfst;
198148          if( szNew>p->sz ){
198149            rc = rbuUpdateTempSize(p, szNew);
198150            if( rc!=SQLITE_OK ) return rc;
198151          }
198152        }
198153      }
198154      rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
198155      if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
198156        /* These look like magic numbers. But they are stable, as they are part
198157        ** of the definition of the SQLite file format, which may not change. */
198158        u8 *pBuf = (u8*)zBuf;
198159        p->iCookie = rbuGetU32(&pBuf[24]);
198160        p->iWriteVer = pBuf[19];
198161      }
198162    }
198163    return rc;
198164  }
198165  
198166  /*
198167  ** Truncate an rbuVfs-file.
198168  */
198169  static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
198170    rbu_file *p = (rbu_file*)pFile;
198171    if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
198172      int rc = rbuUpdateTempSize(p, size);
198173      if( rc!=SQLITE_OK ) return rc;
198174    }
198175    return p->pReal->pMethods->xTruncate(p->pReal, size);
198176  }
198177  
198178  /*
198179  ** Sync an rbuVfs-file.
198180  */
198181  static int rbuVfsSync(sqlite3_file *pFile, int flags){
198182    rbu_file *p = (rbu_file *)pFile;
198183    if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
198184      if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
198185        return SQLITE_INTERNAL;
198186      }
198187      return SQLITE_OK;
198188    }
198189    return p->pReal->pMethods->xSync(p->pReal, flags);
198190  }
198191  
198192  /*
198193  ** Return the current file-size of an rbuVfs-file.
198194  */
198195  static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
198196    rbu_file *p = (rbu_file *)pFile;
198197    int rc;
198198    rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
198199  
198200    /* If this is an RBU vacuum operation and this is the target database,
198201    ** pretend that it has at least one page. Otherwise, SQLite will not
198202    ** check for the existance of a *-wal file. rbuVfsRead() contains 
198203    ** similar logic.  */
198204    if( rc==SQLITE_OK && *pSize==0 
198205     && p->pRbu && rbuIsVacuum(p->pRbu) 
198206     && (p->openFlags & SQLITE_OPEN_MAIN_DB)
198207    ){
198208      *pSize = 1024;
198209    }
198210    return rc;
198211  }
198212  
198213  /*
198214  ** Lock an rbuVfs-file.
198215  */
198216  static int rbuVfsLock(sqlite3_file *pFile, int eLock){
198217    rbu_file *p = (rbu_file*)pFile;
198218    sqlite3rbu *pRbu = p->pRbu;
198219    int rc = SQLITE_OK;
198220  
198221    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
198222    if( eLock==SQLITE_LOCK_EXCLUSIVE 
198223     && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
198224    ){
198225      /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this 
198226      ** prevents it from checkpointing the database from sqlite3_close(). */
198227      rc = SQLITE_BUSY;
198228    }else{
198229      rc = p->pReal->pMethods->xLock(p->pReal, eLock);
198230    }
198231  
198232    return rc;
198233  }
198234  
198235  /*
198236  ** Unlock an rbuVfs-file.
198237  */
198238  static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
198239    rbu_file *p = (rbu_file *)pFile;
198240    return p->pReal->pMethods->xUnlock(p->pReal, eLock);
198241  }
198242  
198243  /*
198244  ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
198245  */
198246  static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
198247    rbu_file *p = (rbu_file *)pFile;
198248    return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
198249  }
198250  
198251  /*
198252  ** File control method. For custom operations on an rbuVfs-file.
198253  */
198254  static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
198255    rbu_file *p = (rbu_file *)pFile;
198256    int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
198257    int rc;
198258  
198259    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
198260         || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
198261    );
198262    if( op==SQLITE_FCNTL_RBU ){
198263      sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
198264  
198265      /* First try to find another RBU vfs lower down in the vfs stack. If
198266      ** one is found, this vfs will operate in pass-through mode. The lower
198267      ** level vfs will do the special RBU handling.  */
198268      rc = xControl(p->pReal, op, pArg);
198269  
198270      if( rc==SQLITE_NOTFOUND ){
198271        /* Now search for a zipvfs instance lower down in the VFS stack. If
198272        ** one is found, this is an error.  */
198273        void *dummy = 0;
198274        rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
198275        if( rc==SQLITE_OK ){
198276          rc = SQLITE_ERROR;
198277          pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
198278        }else if( rc==SQLITE_NOTFOUND ){
198279          pRbu->pTargetFd = p;
198280          p->pRbu = pRbu;
198281          if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
198282            rbuMainlistAdd(p);
198283          }
198284          if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
198285          rc = SQLITE_OK;
198286        }
198287      }
198288      return rc;
198289    }
198290    else if( op==SQLITE_FCNTL_RBUCNT ){
198291      sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
198292      pRbu->nRbu++;
198293      pRbu->pRbuFd = p;
198294      p->bNolock = 1;
198295    }
198296  
198297    rc = xControl(p->pReal, op, pArg);
198298    if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
198299      rbu_vfs *pRbuVfs = p->pRbuVfs;
198300      char *zIn = *(char**)pArg;
198301      char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
198302      *(char**)pArg = zOut;
198303      if( zOut==0 ) rc = SQLITE_NOMEM;
198304    }
198305  
198306    return rc;
198307  }
198308  
198309  /*
198310  ** Return the sector-size in bytes for an rbuVfs-file.
198311  */
198312  static int rbuVfsSectorSize(sqlite3_file *pFile){
198313    rbu_file *p = (rbu_file *)pFile;
198314    return p->pReal->pMethods->xSectorSize(p->pReal);
198315  }
198316  
198317  /*
198318  ** Return the device characteristic flags supported by an rbuVfs-file.
198319  */
198320  static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
198321    rbu_file *p = (rbu_file *)pFile;
198322    return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
198323  }
198324  
198325  /*
198326  ** Take or release a shared-memory lock.
198327  */
198328  static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
198329    rbu_file *p = (rbu_file*)pFile;
198330    sqlite3rbu *pRbu = p->pRbu;
198331    int rc = SQLITE_OK;
198332  
198333  #ifdef SQLITE_AMALGAMATION
198334      assert( WAL_CKPT_LOCK==1 );
198335  #endif
198336  
198337    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
198338    if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
198339      /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
198340      ** taking this lock also prevents any checkpoints from occurring. 
198341      ** todo: really, it's not clear why this might occur, as 
198342      ** wal_autocheckpoint ought to be turned off.  */
198343      if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
198344    }else{
198345      int bCapture = 0;
198346      if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
198347       && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
198348       && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
198349      ){
198350        bCapture = 1;
198351      }
198352  
198353      if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
198354        rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
198355        if( bCapture && rc==SQLITE_OK ){
198356          pRbu->mLock |= (1 << ofst);
198357        }
198358      }
198359    }
198360  
198361    return rc;
198362  }
198363  
198364  /*
198365  ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
198366  */
198367  static int rbuVfsShmMap(
198368    sqlite3_file *pFile, 
198369    int iRegion, 
198370    int szRegion, 
198371    int isWrite, 
198372    void volatile **pp
198373  ){
198374    rbu_file *p = (rbu_file*)pFile;
198375    int rc = SQLITE_OK;
198376    int eStage = (p->pRbu ? p->pRbu->eStage : 0);
198377  
198378    /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
198379    ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space 
198380    ** instead of a file on disk.  */
198381    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
198382    if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
198383      if( iRegion<=p->nShm ){
198384        int nByte = (iRegion+1) * sizeof(char*);
198385        char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
198386        if( apNew==0 ){
198387          rc = SQLITE_NOMEM;
198388        }else{
198389          memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
198390          p->apShm = apNew;
198391          p->nShm = iRegion+1;
198392        }
198393      }
198394  
198395      if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
198396        char *pNew = (char*)sqlite3_malloc64(szRegion);
198397        if( pNew==0 ){
198398          rc = SQLITE_NOMEM;
198399        }else{
198400          memset(pNew, 0, szRegion);
198401          p->apShm[iRegion] = pNew;
198402        }
198403      }
198404  
198405      if( rc==SQLITE_OK ){
198406        *pp = p->apShm[iRegion];
198407      }else{
198408        *pp = 0;
198409      }
198410    }else{
198411      assert( p->apShm==0 );
198412      rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
198413    }
198414  
198415    return rc;
198416  }
198417  
198418  /*
198419  ** Memory barrier.
198420  */
198421  static void rbuVfsShmBarrier(sqlite3_file *pFile){
198422    rbu_file *p = (rbu_file *)pFile;
198423    p->pReal->pMethods->xShmBarrier(p->pReal);
198424  }
198425  
198426  /*
198427  ** The xShmUnmap method.
198428  */
198429  static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
198430    rbu_file *p = (rbu_file*)pFile;
198431    int rc = SQLITE_OK;
198432    int eStage = (p->pRbu ? p->pRbu->eStage : 0);
198433  
198434    assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
198435    if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
198436      /* no-op */
198437    }else{
198438      /* Release the checkpointer and writer locks */
198439      rbuUnlockShm(p);
198440      rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
198441    }
198442    return rc;
198443  }
198444  
198445  /* 
198446  ** A main database named zName has just been opened. The following 
198447  ** function returns a pointer to a buffer owned by SQLite that contains
198448  ** the name of the *-wal file this db connection will use. SQLite
198449  ** happens to pass a pointer to this buffer when using xAccess()
198450  ** or xOpen() to operate on the *-wal file.  
198451  */
198452  static const char *rbuMainToWal(const char *zName, int flags){
198453    int n = (int)strlen(zName);
198454    const char *z = &zName[n];
198455    if( flags & SQLITE_OPEN_URI ){
198456      int odd = 0;
198457      while( 1 ){
198458        if( z[0]==0 ){
198459          odd = 1 - odd;
198460          if( odd && z[1]==0 ) break;
198461        }
198462        z++;
198463      }
198464      z += 2;
198465    }else{
198466      while( *z==0 ) z++;
198467    }
198468    z += (n + 8 + 1);
198469    return z;
198470  }
198471  
198472  /*
198473  ** Open an rbu file handle.
198474  */
198475  static int rbuVfsOpen(
198476    sqlite3_vfs *pVfs,
198477    const char *zName,
198478    sqlite3_file *pFile,
198479    int flags,
198480    int *pOutFlags
198481  ){
198482    static sqlite3_io_methods rbuvfs_io_methods = {
198483      2,                            /* iVersion */
198484      rbuVfsClose,                  /* xClose */
198485      rbuVfsRead,                   /* xRead */
198486      rbuVfsWrite,                  /* xWrite */
198487      rbuVfsTruncate,               /* xTruncate */
198488      rbuVfsSync,                   /* xSync */
198489      rbuVfsFileSize,               /* xFileSize */
198490      rbuVfsLock,                   /* xLock */
198491      rbuVfsUnlock,                 /* xUnlock */
198492      rbuVfsCheckReservedLock,      /* xCheckReservedLock */
198493      rbuVfsFileControl,            /* xFileControl */
198494      rbuVfsSectorSize,             /* xSectorSize */
198495      rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
198496      rbuVfsShmMap,                 /* xShmMap */
198497      rbuVfsShmLock,                /* xShmLock */
198498      rbuVfsShmBarrier,             /* xShmBarrier */
198499      rbuVfsShmUnmap,               /* xShmUnmap */
198500      0, 0                          /* xFetch, xUnfetch */
198501    };
198502    rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
198503    sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
198504    rbu_file *pFd = (rbu_file *)pFile;
198505    int rc = SQLITE_OK;
198506    const char *zOpen = zName;
198507    int oflags = flags;
198508  
198509    memset(pFd, 0, sizeof(rbu_file));
198510    pFd->pReal = (sqlite3_file*)&pFd[1];
198511    pFd->pRbuVfs = pRbuVfs;
198512    pFd->openFlags = flags;
198513    if( zName ){
198514      if( flags & SQLITE_OPEN_MAIN_DB ){
198515        /* A main database has just been opened. The following block sets
198516        ** (pFd->zWal) to point to a buffer owned by SQLite that contains
198517        ** the name of the *-wal file this db connection will use. SQLite
198518        ** happens to pass a pointer to this buffer when using xAccess()
198519        ** or xOpen() to operate on the *-wal file.  */
198520        pFd->zWal = rbuMainToWal(zName, flags);
198521      }
198522      else if( flags & SQLITE_OPEN_WAL ){
198523        rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
198524        if( pDb ){
198525          if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
198526            /* This call is to open a *-wal file. Intead, open the *-oal. This
198527            ** code ensures that the string passed to xOpen() is terminated by a
198528            ** pair of '\0' bytes in case the VFS attempts to extract a URI 
198529            ** parameter from it.  */
198530            const char *zBase = zName;
198531            size_t nCopy;
198532            char *zCopy;
198533            if( rbuIsVacuum(pDb->pRbu) ){
198534              zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
198535              zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
198536            }
198537            nCopy = strlen(zBase);
198538            zCopy = sqlite3_malloc64(nCopy+2);
198539            if( zCopy ){
198540              memcpy(zCopy, zBase, nCopy);
198541              zCopy[nCopy-3] = 'o';
198542              zCopy[nCopy] = '\0';
198543              zCopy[nCopy+1] = '\0';
198544              zOpen = (const char*)(pFd->zDel = zCopy);
198545            }else{
198546              rc = SQLITE_NOMEM;
198547            }
198548            pFd->pRbu = pDb->pRbu;
198549          }
198550          pDb->pWalFd = pFd;
198551        }
198552      }
198553    }else{
198554      pFd->pRbu = pRbuVfs->pRbu;
198555    }
198556  
198557    if( oflags & SQLITE_OPEN_MAIN_DB 
198558     && sqlite3_uri_boolean(zName, "rbu_memory", 0) 
198559    ){
198560      assert( oflags & SQLITE_OPEN_MAIN_DB );
198561      oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
198562                SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
198563      zOpen = 0;
198564    }
198565  
198566    if( rc==SQLITE_OK ){
198567      rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
198568    }
198569    if( pFd->pReal->pMethods ){
198570      /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
198571      ** pointer and, if the file is a main database file, link it into the
198572      ** mutex protected linked list of all such files.  */
198573      pFile->pMethods = &rbuvfs_io_methods;
198574      if( flags & SQLITE_OPEN_MAIN_DB ){
198575        rbuMainlistAdd(pFd);
198576      }
198577    }else{
198578      sqlite3_free(pFd->zDel);
198579    }
198580  
198581    return rc;
198582  }
198583  
198584  /*
198585  ** Delete the file located at zPath.
198586  */
198587  static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
198588    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198589    return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
198590  }
198591  
198592  /*
198593  ** Test for access permissions. Return true if the requested permission
198594  ** is available, or false otherwise.
198595  */
198596  static int rbuVfsAccess(
198597    sqlite3_vfs *pVfs, 
198598    const char *zPath, 
198599    int flags, 
198600    int *pResOut
198601  ){
198602    rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
198603    sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
198604    int rc;
198605  
198606    rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
198607  
198608    /* If this call is to check if a *-wal file associated with an RBU target
198609    ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
198610    ** the following special handling is activated:
198611    **
198612    **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
198613    **      ensures that the RBU extension never tries to update a database
198614    **      in wal mode, even if the first page of the database file has
198615    **      been damaged. 
198616    **
198617    **   b) if the *-wal file does not exist, claim that it does anyway,
198618    **      causing SQLite to call xOpen() to open it. This call will also
198619    **      be intercepted (see the rbuVfsOpen() function) and the *-oal
198620    **      file opened instead.
198621    */
198622    if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
198623      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
198624      if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
198625        if( *pResOut ){
198626          rc = SQLITE_CANTOPEN;
198627        }else{
198628          sqlite3_int64 sz = 0;
198629          rc = rbuVfsFileSize(&pDb->base, &sz);
198630          *pResOut = (sz>0);
198631        }
198632      }
198633    }
198634  
198635    return rc;
198636  }
198637  
198638  /*
198639  ** Populate buffer zOut with the full canonical pathname corresponding
198640  ** to the pathname in zPath. zOut is guaranteed to point to a buffer
198641  ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
198642  */
198643  static int rbuVfsFullPathname(
198644    sqlite3_vfs *pVfs, 
198645    const char *zPath, 
198646    int nOut, 
198647    char *zOut
198648  ){
198649    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198650    return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
198651  }
198652  
198653  #ifndef SQLITE_OMIT_LOAD_EXTENSION
198654  /*
198655  ** Open the dynamic library located at zPath and return a handle.
198656  */
198657  static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
198658    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198659    return pRealVfs->xDlOpen(pRealVfs, zPath);
198660  }
198661  
198662  /*
198663  ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
198664  ** utf-8 string describing the most recent error encountered associated 
198665  ** with dynamic libraries.
198666  */
198667  static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
198668    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198669    pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
198670  }
198671  
198672  /*
198673  ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
198674  */
198675  static void (*rbuVfsDlSym(
198676    sqlite3_vfs *pVfs, 
198677    void *pArg, 
198678    const char *zSym
198679  ))(void){
198680    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198681    return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
198682  }
198683  
198684  /*
198685  ** Close the dynamic library handle pHandle.
198686  */
198687  static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
198688    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198689    pRealVfs->xDlClose(pRealVfs, pHandle);
198690  }
198691  #endif /* SQLITE_OMIT_LOAD_EXTENSION */
198692  
198693  /*
198694  ** Populate the buffer pointed to by zBufOut with nByte bytes of 
198695  ** random data.
198696  */
198697  static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
198698    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198699    return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
198700  }
198701  
198702  /*
198703  ** Sleep for nMicro microseconds. Return the number of microseconds 
198704  ** actually slept.
198705  */
198706  static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
198707    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198708    return pRealVfs->xSleep(pRealVfs, nMicro);
198709  }
198710  
198711  /*
198712  ** Return the current time as a Julian Day number in *pTimeOut.
198713  */
198714  static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
198715    sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
198716    return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
198717  }
198718  
198719  /*
198720  ** No-op.
198721  */
198722  static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
198723    return 0;
198724  }
198725  
198726  /*
198727  ** Deregister and destroy an RBU vfs created by an earlier call to
198728  ** sqlite3rbu_create_vfs().
198729  */
198730  SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
198731    sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
198732    if( pVfs && pVfs->xOpen==rbuVfsOpen ){
198733      sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
198734      sqlite3_vfs_unregister(pVfs);
198735      sqlite3_free(pVfs);
198736    }
198737  }
198738  
198739  /*
198740  ** Create an RBU VFS named zName that accesses the underlying file-system
198741  ** via existing VFS zParent. The new object is registered as a non-default
198742  ** VFS with SQLite before returning.
198743  */
198744  SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
198745  
198746    /* Template for VFS */
198747    static sqlite3_vfs vfs_template = {
198748      1,                            /* iVersion */
198749      0,                            /* szOsFile */
198750      0,                            /* mxPathname */
198751      0,                            /* pNext */
198752      0,                            /* zName */
198753      0,                            /* pAppData */
198754      rbuVfsOpen,                   /* xOpen */
198755      rbuVfsDelete,                 /* xDelete */
198756      rbuVfsAccess,                 /* xAccess */
198757      rbuVfsFullPathname,           /* xFullPathname */
198758  
198759  #ifndef SQLITE_OMIT_LOAD_EXTENSION
198760      rbuVfsDlOpen,                 /* xDlOpen */
198761      rbuVfsDlError,                /* xDlError */
198762      rbuVfsDlSym,                  /* xDlSym */
198763      rbuVfsDlClose,                /* xDlClose */
198764  #else
198765      0, 0, 0, 0,
198766  #endif
198767  
198768      rbuVfsRandomness,             /* xRandomness */
198769      rbuVfsSleep,                  /* xSleep */
198770      rbuVfsCurrentTime,            /* xCurrentTime */
198771      rbuVfsGetLastError,           /* xGetLastError */
198772      0,                            /* xCurrentTimeInt64 (version 2) */
198773      0, 0, 0                       /* Unimplemented version 3 methods */
198774    };
198775  
198776    rbu_vfs *pNew = 0;              /* Newly allocated VFS */
198777    int rc = SQLITE_OK;
198778    size_t nName;
198779    size_t nByte;
198780  
198781    nName = strlen(zName);
198782    nByte = sizeof(rbu_vfs) + nName + 1;
198783    pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
198784    if( pNew==0 ){
198785      rc = SQLITE_NOMEM;
198786    }else{
198787      sqlite3_vfs *pParent;           /* Parent VFS */
198788      memset(pNew, 0, nByte);
198789      pParent = sqlite3_vfs_find(zParent);
198790      if( pParent==0 ){
198791        rc = SQLITE_NOTFOUND;
198792      }else{
198793        char *zSpace;
198794        memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
198795        pNew->base.mxPathname = pParent->mxPathname;
198796        pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
198797        pNew->pRealVfs = pParent;
198798        pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
198799        memcpy(zSpace, zName, nName);
198800  
198801        /* Allocate the mutex and register the new VFS (not as the default) */
198802        pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
198803        if( pNew->mutex==0 ){
198804          rc = SQLITE_NOMEM;
198805        }else{
198806          rc = sqlite3_vfs_register(&pNew->base, 0);
198807        }
198808      }
198809  
198810      if( rc!=SQLITE_OK ){
198811        sqlite3_mutex_free(pNew->mutex);
198812        sqlite3_free(pNew);
198813      }
198814    }
198815  
198816    return rc;
198817  }
198818  
198819  /*
198820  ** Configure the aggregate temp file size limit for this RBU handle.
198821  */
198822  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
198823    if( n>=0 ){
198824      pRbu->szTempLimit = n;
198825    }
198826    return pRbu->szTempLimit;
198827  }
198828  
198829  SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
198830    return pRbu->szTemp;
198831  }
198832  
198833  
198834  /**************************************************************************/
198835  
198836  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
198837  
198838  /************** End of sqlite3rbu.c ******************************************/
198839  /************** Begin file dbstat.c ******************************************/
198840  /*
198841  ** 2010 July 12
198842  **
198843  ** The author disclaims copyright to this source code.  In place of
198844  ** a legal notice, here is a blessing:
198845  **
198846  **    May you do good and not evil.
198847  **    May you find forgiveness for yourself and forgive others.
198848  **    May you share freely, never taking more than you give.
198849  **
198850  ******************************************************************************
198851  **
198852  ** This file contains an implementation of the "dbstat" virtual table.
198853  **
198854  ** The dbstat virtual table is used to extract low-level formatting
198855  ** information from an SQLite database in order to implement the
198856  ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
198857  ** for an example implementation.
198858  **
198859  ** Additional information is available on the "dbstat.html" page of the
198860  ** official SQLite documentation.
198861  */
198862  
198863  /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
198864  #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
198865      && !defined(SQLITE_OMIT_VIRTUALTABLE)
198866  
198867  /*
198868  ** Page paths:
198869  ** 
198870  **   The value of the 'path' column describes the path taken from the 
198871  **   root-node of the b-tree structure to each page. The value of the 
198872  **   root-node path is '/'.
198873  **
198874  **   The value of the path for the left-most child page of the root of
198875  **   a b-tree is '/000/'. (Btrees store content ordered from left to right
198876  **   so the pages to the left have smaller keys than the pages to the right.)
198877  **   The next to left-most child of the root page is
198878  **   '/001', and so on, each sibling page identified by a 3-digit hex 
198879  **   value. The children of the 451st left-most sibling have paths such
198880  **   as '/1c2/000/, '/1c2/001/' etc.
198881  **
198882  **   Overflow pages are specified by appending a '+' character and a 
198883  **   six-digit hexadecimal value to the path to the cell they are linked
198884  **   from. For example, the three overflow pages in a chain linked from 
198885  **   the left-most cell of the 450th child of the root page are identified
198886  **   by the paths:
198887  **
198888  **      '/1c2/000+000000'         // First page in overflow chain
198889  **      '/1c2/000+000001'         // Second page in overflow chain
198890  **      '/1c2/000+000002'         // Third page in overflow chain
198891  **
198892  **   If the paths are sorted using the BINARY collation sequence, then
198893  **   the overflow pages associated with a cell will appear earlier in the
198894  **   sort-order than its child page:
198895  **
198896  **      '/1c2/000/'               // Left-most child of 451st child of root
198897  */
198898  #define VTAB_SCHEMA                                                         \
198899    "CREATE TABLE xx( "                                                       \
198900    "  name       TEXT,             /* Name of table or index */"             \
198901    "  path       TEXT,             /* Path to page from root */"             \
198902    "  pageno     INTEGER,          /* Page number */"                        \
198903    "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
198904    "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
198905    "  payload    INTEGER,          /* Bytes of payload on this page */"      \
198906    "  unused     INTEGER,          /* Bytes of unused space on this page */" \
198907    "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
198908    "  pgoffset   INTEGER,          /* Offset of page in file */"             \
198909    "  pgsize     INTEGER,          /* Size of the page */"                   \
198910    "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
198911    ");"
198912  
198913  
198914  typedef struct StatTable StatTable;
198915  typedef struct StatCursor StatCursor;
198916  typedef struct StatPage StatPage;
198917  typedef struct StatCell StatCell;
198918  
198919  struct StatCell {
198920    int nLocal;                     /* Bytes of local payload */
198921    u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
198922    int nOvfl;                      /* Entries in aOvfl[] */
198923    u32 *aOvfl;                     /* Array of overflow page numbers */
198924    int nLastOvfl;                  /* Bytes of payload on final overflow page */
198925    int iOvfl;                      /* Iterates through aOvfl[] */
198926  };
198927  
198928  struct StatPage {
198929    u32 iPgno;
198930    DbPage *pPg;
198931    int iCell;
198932  
198933    char *zPath;                    /* Path to this page */
198934  
198935    /* Variables populated by statDecodePage(): */
198936    u8 flags;                       /* Copy of flags byte */
198937    int nCell;                      /* Number of cells on page */
198938    int nUnused;                    /* Number of unused bytes on page */
198939    StatCell *aCell;                /* Array of parsed cells */
198940    u32 iRightChildPg;              /* Right-child page number (or 0) */
198941    int nMxPayload;                 /* Largest payload of any cell on this page */
198942  };
198943  
198944  struct StatCursor {
198945    sqlite3_vtab_cursor base;
198946    sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
198947    int isEof;                      /* After pStmt has returned SQLITE_DONE */
198948    int iDb;                        /* Schema used for this query */
198949  
198950    StatPage aPage[32];
198951    int iPage;                      /* Current entry in aPage[] */
198952  
198953    /* Values to return. */
198954    char *zName;                    /* Value of 'name' column */
198955    char *zPath;                    /* Value of 'path' column */
198956    u32 iPageno;                    /* Value of 'pageno' column */
198957    char *zPagetype;                /* Value of 'pagetype' column */
198958    int nCell;                      /* Value of 'ncell' column */
198959    int nPayload;                   /* Value of 'payload' column */
198960    int nUnused;                    /* Value of 'unused' column */
198961    int nMxPayload;                 /* Value of 'mx_payload' column */
198962    i64 iOffset;                    /* Value of 'pgOffset' column */
198963    int szPage;                     /* Value of 'pgSize' column */
198964  };
198965  
198966  struct StatTable {
198967    sqlite3_vtab base;
198968    sqlite3 *db;
198969    int iDb;                        /* Index of database to analyze */
198970  };
198971  
198972  #ifndef get2byte
198973  # define get2byte(x)   ((x)[0]<<8 | (x)[1])
198974  #endif
198975  
198976  /*
198977  ** Connect to or create a statvfs virtual table.
198978  */
198979  static int statConnect(
198980    sqlite3 *db,
198981    void *pAux,
198982    int argc, const char *const*argv,
198983    sqlite3_vtab **ppVtab,
198984    char **pzErr
198985  ){
198986    StatTable *pTab = 0;
198987    int rc = SQLITE_OK;
198988    int iDb;
198989  
198990    if( argc>=4 ){
198991      Token nm;
198992      sqlite3TokenInit(&nm, (char*)argv[3]);
198993      iDb = sqlite3FindDb(db, &nm);
198994      if( iDb<0 ){
198995        *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
198996        return SQLITE_ERROR;
198997      }
198998    }else{
198999      iDb = 0;
199000    }
199001    rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
199002    if( rc==SQLITE_OK ){
199003      pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
199004      if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
199005    }
199006  
199007    assert( rc==SQLITE_OK || pTab==0 );
199008    if( rc==SQLITE_OK ){
199009      memset(pTab, 0, sizeof(StatTable));
199010      pTab->db = db;
199011      pTab->iDb = iDb;
199012    }
199013  
199014    *ppVtab = (sqlite3_vtab*)pTab;
199015    return rc;
199016  }
199017  
199018  /*
199019  ** Disconnect from or destroy a statvfs virtual table.
199020  */
199021  static int statDisconnect(sqlite3_vtab *pVtab){
199022    sqlite3_free(pVtab);
199023    return SQLITE_OK;
199024  }
199025  
199026  /*
199027  ** There is no "best-index". This virtual table always does a linear
199028  ** scan.  However, a schema=? constraint should cause this table to
199029  ** operate on a different database schema, so check for it.
199030  **
199031  ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
199032  */
199033  static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
199034    int i;
199035  
199036    /* Look for a valid schema=? constraint.  If found, change the idxNum to
199037    ** 1 and request the value of that constraint be sent to xFilter.  And
199038    ** lower the cost estimate to encourage the constrained version to be
199039    ** used.
199040    */
199041    for(i=0; i<pIdxInfo->nConstraint; i++){
199042      if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
199043      if( pIdxInfo->aConstraint[i].usable==0 ) return SQLITE_CONSTRAINT;
199044      if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
199045      pIdxInfo->idxNum = 1;
199046      pIdxInfo->estimatedCost = 1.0;
199047      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
199048      pIdxInfo->aConstraintUsage[i].omit = 1;
199049      break;
199050    }
199051  
199052  
199053    /* Records are always returned in ascending order of (name, path). 
199054    ** If this will satisfy the client, set the orderByConsumed flag so that 
199055    ** SQLite does not do an external sort.
199056    */
199057    if( ( pIdxInfo->nOrderBy==1
199058       && pIdxInfo->aOrderBy[0].iColumn==0
199059       && pIdxInfo->aOrderBy[0].desc==0
199060       ) ||
199061        ( pIdxInfo->nOrderBy==2
199062       && pIdxInfo->aOrderBy[0].iColumn==0
199063       && pIdxInfo->aOrderBy[0].desc==0
199064       && pIdxInfo->aOrderBy[1].iColumn==1
199065       && pIdxInfo->aOrderBy[1].desc==0
199066       )
199067    ){
199068      pIdxInfo->orderByConsumed = 1;
199069    }
199070  
199071    return SQLITE_OK;
199072  }
199073  
199074  /*
199075  ** Open a new statvfs cursor.
199076  */
199077  static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
199078    StatTable *pTab = (StatTable *)pVTab;
199079    StatCursor *pCsr;
199080  
199081    pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
199082    if( pCsr==0 ){
199083      return SQLITE_NOMEM_BKPT;
199084    }else{
199085      memset(pCsr, 0, sizeof(StatCursor));
199086      pCsr->base.pVtab = pVTab;
199087      pCsr->iDb = pTab->iDb;
199088    }
199089  
199090    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
199091    return SQLITE_OK;
199092  }
199093  
199094  static void statClearCells(StatPage *p){
199095    int i;
199096    if( p->aCell ){
199097      for(i=0; i<p->nCell; i++){
199098        sqlite3_free(p->aCell[i].aOvfl);
199099      }
199100      sqlite3_free(p->aCell);
199101    }
199102    p->nCell = 0;
199103    p->aCell = 0;
199104  }
199105  
199106  static void statClearPage(StatPage *p){
199107    statClearCells(p);
199108    sqlite3PagerUnref(p->pPg);
199109    sqlite3_free(p->zPath);
199110    memset(p, 0, sizeof(StatPage));
199111  }
199112  
199113  static void statResetCsr(StatCursor *pCsr){
199114    int i;
199115    sqlite3_reset(pCsr->pStmt);
199116    for(i=0; i<ArraySize(pCsr->aPage); i++){
199117      statClearPage(&pCsr->aPage[i]);
199118    }
199119    pCsr->iPage = 0;
199120    sqlite3_free(pCsr->zPath);
199121    pCsr->zPath = 0;
199122    pCsr->isEof = 0;
199123  }
199124  
199125  /*
199126  ** Close a statvfs cursor.
199127  */
199128  static int statClose(sqlite3_vtab_cursor *pCursor){
199129    StatCursor *pCsr = (StatCursor *)pCursor;
199130    statResetCsr(pCsr);
199131    sqlite3_finalize(pCsr->pStmt);
199132    sqlite3_free(pCsr);
199133    return SQLITE_OK;
199134  }
199135  
199136  static void getLocalPayload(
199137    int nUsable,                    /* Usable bytes per page */
199138    u8 flags,                       /* Page flags */
199139    int nTotal,                     /* Total record (payload) size */
199140    int *pnLocal                    /* OUT: Bytes stored locally */
199141  ){
199142    int nLocal;
199143    int nMinLocal;
199144    int nMaxLocal;
199145   
199146    if( flags==0x0D ){              /* Table leaf node */
199147      nMinLocal = (nUsable - 12) * 32 / 255 - 23;
199148      nMaxLocal = nUsable - 35;
199149    }else{                          /* Index interior and leaf nodes */
199150      nMinLocal = (nUsable - 12) * 32 / 255 - 23;
199151      nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
199152    }
199153  
199154    nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
199155    if( nLocal>nMaxLocal ) nLocal = nMinLocal;
199156    *pnLocal = nLocal;
199157  }
199158  
199159  static int statDecodePage(Btree *pBt, StatPage *p){
199160    int nUnused;
199161    int iOff;
199162    int nHdr;
199163    int isLeaf;
199164    int szPage;
199165  
199166    u8 *aData = sqlite3PagerGetData(p->pPg);
199167    u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
199168  
199169    p->flags = aHdr[0];
199170    if( p->flags==0x0A || p->flags==0x0D ){
199171      isLeaf = 1;
199172      nHdr = 8;
199173    }else if( p->flags==0x05 || p->flags==0x02 ){
199174      isLeaf = 0;
199175      nHdr = 12;
199176    }else{
199177      goto statPageIsCorrupt;
199178    }
199179    if( p->iPgno==1 ) nHdr += 100;
199180    p->nCell = get2byte(&aHdr[3]);
199181    p->nMxPayload = 0;
199182    szPage = sqlite3BtreeGetPageSize(pBt);
199183  
199184    nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
199185    nUnused += (int)aHdr[7];
199186    iOff = get2byte(&aHdr[1]);
199187    while( iOff ){
199188      int iNext;
199189      if( iOff>=szPage ) goto statPageIsCorrupt;
199190      nUnused += get2byte(&aData[iOff+2]);
199191      iNext = get2byte(&aData[iOff]);
199192      if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
199193      iOff = iNext;
199194    }
199195    p->nUnused = nUnused;
199196    p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
199197  
199198    if( p->nCell ){
199199      int i;                        /* Used to iterate through cells */
199200      int nUsable;                  /* Usable bytes per page */
199201  
199202      sqlite3BtreeEnter(pBt);
199203      nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
199204      sqlite3BtreeLeave(pBt);
199205      p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
199206      if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
199207      memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
199208  
199209      for(i=0; i<p->nCell; i++){
199210        StatCell *pCell = &p->aCell[i];
199211  
199212        iOff = get2byte(&aData[nHdr+i*2]);
199213        if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
199214        if( !isLeaf ){
199215          pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
199216          iOff += 4;
199217        }
199218        if( p->flags==0x05 ){
199219          /* A table interior node. nPayload==0. */
199220        }else{
199221          u32 nPayload;             /* Bytes of payload total (local+overflow) */
199222          int nLocal;               /* Bytes of payload stored locally */
199223          iOff += getVarint32(&aData[iOff], nPayload);
199224          if( p->flags==0x0D ){
199225            u64 dummy;
199226            iOff += sqlite3GetVarint(&aData[iOff], &dummy);
199227          }
199228          if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
199229          getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
199230          if( nLocal<0 ) goto statPageIsCorrupt;
199231          pCell->nLocal = nLocal;
199232          assert( nPayload>=(u32)nLocal );
199233          assert( nLocal<=(nUsable-35) );
199234          if( nPayload>(u32)nLocal ){
199235            int j;
199236            int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
199237            if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
199238            pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
199239            pCell->nOvfl = nOvfl;
199240            pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
199241            if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
199242            pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
199243            for(j=1; j<nOvfl; j++){
199244              int rc;
199245              u32 iPrev = pCell->aOvfl[j-1];
199246              DbPage *pPg = 0;
199247              rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
199248              if( rc!=SQLITE_OK ){
199249                assert( pPg==0 );
199250                return rc;
199251              } 
199252              pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
199253              sqlite3PagerUnref(pPg);
199254            }
199255          }
199256        }
199257      }
199258    }
199259  
199260    return SQLITE_OK;
199261  
199262  statPageIsCorrupt:
199263    p->flags = 0;
199264    statClearCells(p);
199265    return SQLITE_OK;
199266  }
199267  
199268  /*
199269  ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
199270  ** the current value of pCsr->iPageno.
199271  */
199272  static void statSizeAndOffset(StatCursor *pCsr){
199273    StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
199274    Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
199275    Pager *pPager = sqlite3BtreePager(pBt);
199276    sqlite3_file *fd;
199277    sqlite3_int64 x[2];
199278  
199279    /* The default page size and offset */
199280    pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
199281    pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
199282  
199283    /* If connected to a ZIPVFS backend, override the page size and
199284    ** offset with actual values obtained from ZIPVFS.
199285    */
199286    fd = sqlite3PagerFile(pPager);
199287    x[0] = pCsr->iPageno;
199288    if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
199289      pCsr->iOffset = x[0];
199290      pCsr->szPage = (int)x[1];
199291    }
199292  }
199293  
199294  /*
199295  ** Move a statvfs cursor to the next entry in the file.
199296  */
199297  static int statNext(sqlite3_vtab_cursor *pCursor){
199298    int rc;
199299    int nPayload;
199300    char *z;
199301    StatCursor *pCsr = (StatCursor *)pCursor;
199302    StatTable *pTab = (StatTable *)pCursor->pVtab;
199303    Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
199304    Pager *pPager = sqlite3BtreePager(pBt);
199305  
199306    sqlite3_free(pCsr->zPath);
199307    pCsr->zPath = 0;
199308  
199309  statNextRestart:
199310    if( pCsr->aPage[0].pPg==0 ){
199311      rc = sqlite3_step(pCsr->pStmt);
199312      if( rc==SQLITE_ROW ){
199313        int nPage;
199314        u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
199315        sqlite3PagerPagecount(pPager, &nPage);
199316        if( nPage==0 ){
199317          pCsr->isEof = 1;
199318          return sqlite3_reset(pCsr->pStmt);
199319        }
199320        rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
199321        pCsr->aPage[0].iPgno = iRoot;
199322        pCsr->aPage[0].iCell = 0;
199323        pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
199324        pCsr->iPage = 0;
199325        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
199326      }else{
199327        pCsr->isEof = 1;
199328        return sqlite3_reset(pCsr->pStmt);
199329      }
199330    }else{
199331  
199332      /* Page p itself has already been visited. */
199333      StatPage *p = &pCsr->aPage[pCsr->iPage];
199334  
199335      while( p->iCell<p->nCell ){
199336        StatCell *pCell = &p->aCell[p->iCell];
199337        if( pCell->iOvfl<pCell->nOvfl ){
199338          int nUsable;
199339          sqlite3BtreeEnter(pBt);
199340          nUsable = sqlite3BtreeGetPageSize(pBt) - 
199341                          sqlite3BtreeGetReserveNoMutex(pBt);
199342          sqlite3BtreeLeave(pBt);
199343          pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
199344          pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
199345          pCsr->zPagetype = "overflow";
199346          pCsr->nCell = 0;
199347          pCsr->nMxPayload = 0;
199348          pCsr->zPath = z = sqlite3_mprintf(
199349              "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
199350          );
199351          if( pCell->iOvfl<pCell->nOvfl-1 ){
199352            pCsr->nUnused = 0;
199353            pCsr->nPayload = nUsable - 4;
199354          }else{
199355            pCsr->nPayload = pCell->nLastOvfl;
199356            pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
199357          }
199358          pCell->iOvfl++;
199359          statSizeAndOffset(pCsr);
199360          return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
199361        }
199362        if( p->iRightChildPg ) break;
199363        p->iCell++;
199364      }
199365  
199366      if( !p->iRightChildPg || p->iCell>p->nCell ){
199367        statClearPage(p);
199368        if( pCsr->iPage==0 ) return statNext(pCursor);
199369        pCsr->iPage--;
199370        goto statNextRestart; /* Tail recursion */
199371      }
199372      pCsr->iPage++;
199373      if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
199374        statResetCsr(pCsr);
199375        return SQLITE_CORRUPT_BKPT;
199376      }
199377      assert( p==&pCsr->aPage[pCsr->iPage-1] );
199378  
199379      if( p->iCell==p->nCell ){
199380        p[1].iPgno = p->iRightChildPg;
199381      }else{
199382        p[1].iPgno = p->aCell[p->iCell].iChildPg;
199383      }
199384      rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
199385      p[1].iCell = 0;
199386      p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
199387      p->iCell++;
199388      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
199389    }
199390  
199391  
199392    /* Populate the StatCursor fields with the values to be returned
199393    ** by the xColumn() and xRowid() methods.
199394    */
199395    if( rc==SQLITE_OK ){
199396      int i;
199397      StatPage *p = &pCsr->aPage[pCsr->iPage];
199398      pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
199399      pCsr->iPageno = p->iPgno;
199400  
199401      rc = statDecodePage(pBt, p);
199402      if( rc==SQLITE_OK ){
199403        statSizeAndOffset(pCsr);
199404  
199405        switch( p->flags ){
199406          case 0x05:             /* table internal */
199407          case 0x02:             /* index internal */
199408            pCsr->zPagetype = "internal";
199409            break;
199410          case 0x0D:             /* table leaf */
199411          case 0x0A:             /* index leaf */
199412            pCsr->zPagetype = "leaf";
199413            break;
199414          default:
199415            pCsr->zPagetype = "corrupted";
199416            break;
199417        }
199418        pCsr->nCell = p->nCell;
199419        pCsr->nUnused = p->nUnused;
199420        pCsr->nMxPayload = p->nMxPayload;
199421        pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
199422        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
199423        nPayload = 0;
199424        for(i=0; i<p->nCell; i++){
199425          nPayload += p->aCell[i].nLocal;
199426        }
199427        pCsr->nPayload = nPayload;
199428      }
199429    }
199430  
199431    return rc;
199432  }
199433  
199434  static int statEof(sqlite3_vtab_cursor *pCursor){
199435    StatCursor *pCsr = (StatCursor *)pCursor;
199436    return pCsr->isEof;
199437  }
199438  
199439  static int statFilter(
199440    sqlite3_vtab_cursor *pCursor, 
199441    int idxNum, const char *idxStr,
199442    int argc, sqlite3_value **argv
199443  ){
199444    StatCursor *pCsr = (StatCursor *)pCursor;
199445    StatTable *pTab = (StatTable*)(pCursor->pVtab);
199446    char *zSql;
199447    int rc = SQLITE_OK;
199448  
199449    if( idxNum==1 ){
199450      const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
199451      pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
199452      if( pCsr->iDb<0 ){
199453        sqlite3_free(pCursor->pVtab->zErrMsg);
199454        pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
199455        return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
199456      }
199457    }else{
199458      pCsr->iDb = pTab->iDb;
199459    }
199460    statResetCsr(pCsr);
199461    sqlite3_finalize(pCsr->pStmt);
199462    pCsr->pStmt = 0;
199463    zSql = sqlite3_mprintf(
199464        "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
199465        "  UNION ALL  "
199466        "SELECT name, rootpage, type"
199467        "  FROM \"%w\".sqlite_master WHERE rootpage!=0"
199468        "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName);
199469    if( zSql==0 ){
199470      return SQLITE_NOMEM_BKPT;
199471    }else{
199472      rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
199473      sqlite3_free(zSql);
199474    }
199475  
199476    if( rc==SQLITE_OK ){
199477      rc = statNext(pCursor);
199478    }
199479    return rc;
199480  }
199481  
199482  static int statColumn(
199483    sqlite3_vtab_cursor *pCursor, 
199484    sqlite3_context *ctx, 
199485    int i
199486  ){
199487    StatCursor *pCsr = (StatCursor *)pCursor;
199488    switch( i ){
199489      case 0:            /* name */
199490        sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
199491        break;
199492      case 1:            /* path */
199493        sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
199494        break;
199495      case 2:            /* pageno */
199496        sqlite3_result_int64(ctx, pCsr->iPageno);
199497        break;
199498      case 3:            /* pagetype */
199499        sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
199500        break;
199501      case 4:            /* ncell */
199502        sqlite3_result_int(ctx, pCsr->nCell);
199503        break;
199504      case 5:            /* payload */
199505        sqlite3_result_int(ctx, pCsr->nPayload);
199506        break;
199507      case 6:            /* unused */
199508        sqlite3_result_int(ctx, pCsr->nUnused);
199509        break;
199510      case 7:            /* mx_payload */
199511        sqlite3_result_int(ctx, pCsr->nMxPayload);
199512        break;
199513      case 8:            /* pgoffset */
199514        sqlite3_result_int64(ctx, pCsr->iOffset);
199515        break;
199516      case 9:            /* pgsize */
199517        sqlite3_result_int(ctx, pCsr->szPage);
199518        break;
199519      default: {          /* schema */
199520        sqlite3 *db = sqlite3_context_db_handle(ctx);
199521        int iDb = pCsr->iDb;
199522        sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
199523        break;
199524      }
199525    }
199526    return SQLITE_OK;
199527  }
199528  
199529  static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
199530    StatCursor *pCsr = (StatCursor *)pCursor;
199531    *pRowid = pCsr->iPageno;
199532    return SQLITE_OK;
199533  }
199534  
199535  /*
199536  ** Invoke this routine to register the "dbstat" virtual table module
199537  */
199538  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
199539    static sqlite3_module dbstat_module = {
199540      0,                            /* iVersion */
199541      statConnect,                  /* xCreate */
199542      statConnect,                  /* xConnect */
199543      statBestIndex,                /* xBestIndex */
199544      statDisconnect,               /* xDisconnect */
199545      statDisconnect,               /* xDestroy */
199546      statOpen,                     /* xOpen - open a cursor */
199547      statClose,                    /* xClose - close a cursor */
199548      statFilter,                   /* xFilter - configure scan constraints */
199549      statNext,                     /* xNext - advance a cursor */
199550      statEof,                      /* xEof - check for end of scan */
199551      statColumn,                   /* xColumn - read data */
199552      statRowid,                    /* xRowid - read data */
199553      0,                            /* xUpdate */
199554      0,                            /* xBegin */
199555      0,                            /* xSync */
199556      0,                            /* xCommit */
199557      0,                            /* xRollback */
199558      0,                            /* xFindMethod */
199559      0,                            /* xRename */
199560      0,                            /* xSavepoint */
199561      0,                            /* xRelease */
199562      0,                            /* xRollbackTo */
199563      0                             /* xShadowName */
199564    };
199565    return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
199566  }
199567  #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
199568  SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
199569  #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
199570  
199571  /************** End of dbstat.c **********************************************/
199572  /************** Begin file dbpage.c ******************************************/
199573  /*
199574  ** 2017-10-11
199575  **
199576  ** The author disclaims copyright to this source code.  In place of
199577  ** a legal notice, here is a blessing:
199578  **
199579  **    May you do good and not evil.
199580  **    May you find forgiveness for yourself and forgive others.
199581  **    May you share freely, never taking more than you give.
199582  **
199583  ******************************************************************************
199584  **
199585  ** This file contains an implementation of the "sqlite_dbpage" virtual table.
199586  **
199587  ** The sqlite_dbpage virtual table is used to read or write whole raw
199588  ** pages of the database file.  The pager interface is used so that 
199589  ** uncommitted changes and changes recorded in the WAL file are correctly
199590  ** retrieved.
199591  **
199592  ** Usage example:
199593  **
199594  **    SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
199595  **
199596  ** This is an eponymous virtual table so it does not need to be created before
199597  ** use.  The optional argument to the sqlite_dbpage() table name is the
199598  ** schema for the database file that is to be read.  The default schema is
199599  ** "main".
199600  **
199601  ** The data field of sqlite_dbpage table can be updated.  The new
199602  ** value must be a BLOB which is the correct page size, otherwise the
199603  ** update fails.  Rows may not be deleted or inserted.
199604  */
199605  
199606  /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
199607  #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
199608      && !defined(SQLITE_OMIT_VIRTUALTABLE)
199609  
199610  typedef struct DbpageTable DbpageTable;
199611  typedef struct DbpageCursor DbpageCursor;
199612  
199613  struct DbpageCursor {
199614    sqlite3_vtab_cursor base;       /* Base class.  Must be first */
199615    int pgno;                       /* Current page number */
199616    int mxPgno;                     /* Last page to visit on this scan */
199617    Pager *pPager;                  /* Pager being read/written */
199618    DbPage *pPage1;                 /* Page 1 of the database */
199619    int iDb;                        /* Index of database to analyze */
199620    int szPage;                     /* Size of each page in bytes */
199621  };
199622  
199623  struct DbpageTable {
199624    sqlite3_vtab base;              /* Base class.  Must be first */
199625    sqlite3 *db;                    /* The database */
199626  };
199627  
199628  /* Columns */
199629  #define DBPAGE_COLUMN_PGNO    0
199630  #define DBPAGE_COLUMN_DATA    1
199631  #define DBPAGE_COLUMN_SCHEMA  2
199632  
199633  
199634  
199635  /*
199636  ** Connect to or create a dbpagevfs virtual table.
199637  */
199638  static int dbpageConnect(
199639    sqlite3 *db,
199640    void *pAux,
199641    int argc, const char *const*argv,
199642    sqlite3_vtab **ppVtab,
199643    char **pzErr
199644  ){
199645    DbpageTable *pTab = 0;
199646    int rc = SQLITE_OK;
199647  
199648    rc = sqlite3_declare_vtab(db, 
199649            "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
199650    if( rc==SQLITE_OK ){
199651      pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
199652      if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
199653    }
199654  
199655    assert( rc==SQLITE_OK || pTab==0 );
199656    if( rc==SQLITE_OK ){
199657      memset(pTab, 0, sizeof(DbpageTable));
199658      pTab->db = db;
199659    }
199660  
199661    *ppVtab = (sqlite3_vtab*)pTab;
199662    return rc;
199663  }
199664  
199665  /*
199666  ** Disconnect from or destroy a dbpagevfs virtual table.
199667  */
199668  static int dbpageDisconnect(sqlite3_vtab *pVtab){
199669    sqlite3_free(pVtab);
199670    return SQLITE_OK;
199671  }
199672  
199673  /*
199674  ** idxNum:
199675  **
199676  **     0     schema=main, full table scan
199677  **     1     schema=main, pgno=?1
199678  **     2     schema=?1, full table scan
199679  **     3     schema=?1, pgno=?2
199680  */
199681  static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
199682    int i;
199683    int iPlan = 0;
199684  
199685    /* If there is a schema= constraint, it must be honored.  Report a
199686    ** ridiculously large estimated cost if the schema= constraint is
199687    ** unavailable
199688    */
199689    for(i=0; i<pIdxInfo->nConstraint; i++){
199690      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
199691      if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
199692      if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
199693      if( !p->usable ){
199694        /* No solution. */
199695        return SQLITE_CONSTRAINT;
199696      }
199697      iPlan = 2;
199698      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
199699      pIdxInfo->aConstraintUsage[i].omit = 1;
199700      break;
199701    }
199702  
199703    /* If we reach this point, it means that either there is no schema=
199704    ** constraint (in which case we use the "main" schema) or else the
199705    ** schema constraint was accepted.  Lower the estimated cost accordingly
199706    */
199707    pIdxInfo->estimatedCost = 1.0e6;
199708  
199709    /* Check for constraints against pgno */
199710    for(i=0; i<pIdxInfo->nConstraint; i++){
199711      struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
199712      if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
199713        pIdxInfo->estimatedRows = 1;
199714        pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
199715        pIdxInfo->estimatedCost = 1.0;
199716        pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
199717        pIdxInfo->aConstraintUsage[i].omit = 1;
199718        iPlan |= 1;
199719        break;
199720      }
199721    }
199722    pIdxInfo->idxNum = iPlan;
199723  
199724    if( pIdxInfo->nOrderBy>=1
199725     && pIdxInfo->aOrderBy[0].iColumn<=0
199726     && pIdxInfo->aOrderBy[0].desc==0
199727    ){
199728      pIdxInfo->orderByConsumed = 1;
199729    }
199730    return SQLITE_OK;
199731  }
199732  
199733  /*
199734  ** Open a new dbpagevfs cursor.
199735  */
199736  static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
199737    DbpageCursor *pCsr;
199738  
199739    pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
199740    if( pCsr==0 ){
199741      return SQLITE_NOMEM_BKPT;
199742    }else{
199743      memset(pCsr, 0, sizeof(DbpageCursor));
199744      pCsr->base.pVtab = pVTab;
199745      pCsr->pgno = -1;
199746    }
199747  
199748    *ppCursor = (sqlite3_vtab_cursor *)pCsr;
199749    return SQLITE_OK;
199750  }
199751  
199752  /*
199753  ** Close a dbpagevfs cursor.
199754  */
199755  static int dbpageClose(sqlite3_vtab_cursor *pCursor){
199756    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199757    if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
199758    sqlite3_free(pCsr);
199759    return SQLITE_OK;
199760  }
199761  
199762  /*
199763  ** Move a dbpagevfs cursor to the next entry in the file.
199764  */
199765  static int dbpageNext(sqlite3_vtab_cursor *pCursor){
199766    int rc = SQLITE_OK;
199767    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199768    pCsr->pgno++;
199769    return rc;
199770  }
199771  
199772  static int dbpageEof(sqlite3_vtab_cursor *pCursor){
199773    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199774    return pCsr->pgno > pCsr->mxPgno;
199775  }
199776  
199777  /*
199778  ** idxNum:
199779  **
199780  **     0     schema=main, full table scan
199781  **     1     schema=main, pgno=?1
199782  **     2     schema=?1, full table scan
199783  **     3     schema=?1, pgno=?2
199784  **
199785  ** idxStr is not used
199786  */
199787  static int dbpageFilter(
199788    sqlite3_vtab_cursor *pCursor, 
199789    int idxNum, const char *idxStr,
199790    int argc, sqlite3_value **argv
199791  ){
199792    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199793    DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
199794    int rc;
199795    sqlite3 *db = pTab->db;
199796    Btree *pBt;
199797  
199798    /* Default setting is no rows of result */
199799    pCsr->pgno = 1; 
199800    pCsr->mxPgno = 0;
199801  
199802    if( idxNum & 2 ){
199803      const char *zSchema;
199804      assert( argc>=1 );
199805      zSchema = (const char*)sqlite3_value_text(argv[0]);
199806      pCsr->iDb = sqlite3FindDbName(db, zSchema);
199807      if( pCsr->iDb<0 ) return SQLITE_OK;
199808    }else{
199809      pCsr->iDb = 0;
199810    }
199811    pBt = db->aDb[pCsr->iDb].pBt;
199812    if( pBt==0 ) return SQLITE_OK;
199813    pCsr->pPager = sqlite3BtreePager(pBt);
199814    pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
199815    pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
199816    if( idxNum & 1 ){
199817      assert( argc>(idxNum>>1) );
199818      pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
199819      if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
199820        pCsr->pgno = 1;
199821        pCsr->mxPgno = 0;
199822      }else{
199823        pCsr->mxPgno = pCsr->pgno;
199824      }
199825    }else{
199826      assert( pCsr->pgno==1 );
199827    }
199828    if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
199829    rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
199830    return rc;
199831  }
199832  
199833  static int dbpageColumn(
199834    sqlite3_vtab_cursor *pCursor, 
199835    sqlite3_context *ctx, 
199836    int i
199837  ){
199838    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199839    int rc = SQLITE_OK;
199840    switch( i ){
199841      case 0: {           /* pgno */
199842        sqlite3_result_int(ctx, pCsr->pgno);
199843        break;
199844      }
199845      case 1: {           /* data */
199846        DbPage *pDbPage = 0;
199847        rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
199848        if( rc==SQLITE_OK ){
199849          sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
199850                              SQLITE_TRANSIENT);
199851        }
199852        sqlite3PagerUnref(pDbPage);
199853        break;
199854      }
199855      default: {          /* schema */
199856        sqlite3 *db = sqlite3_context_db_handle(ctx);
199857        sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
199858        break;
199859      }
199860    }
199861    return SQLITE_OK;
199862  }
199863  
199864  static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
199865    DbpageCursor *pCsr = (DbpageCursor *)pCursor;
199866    *pRowid = pCsr->pgno;
199867    return SQLITE_OK;
199868  }
199869  
199870  static int dbpageUpdate(
199871    sqlite3_vtab *pVtab,
199872    int argc,
199873    sqlite3_value **argv,
199874    sqlite_int64 *pRowid
199875  ){
199876    DbpageTable *pTab = (DbpageTable *)pVtab;
199877    Pgno pgno;
199878    DbPage *pDbPage = 0;
199879    int rc = SQLITE_OK;
199880    char *zErr = 0;
199881    const char *zSchema;
199882    int iDb;
199883    Btree *pBt;
199884    Pager *pPager;
199885    int szPage;
199886  
199887    if( pTab->db->flags & SQLITE_Defensive ){
199888      zErr = "read-only";
199889      goto update_fail;
199890    }
199891    if( argc==1 ){
199892      zErr = "cannot delete";
199893      goto update_fail;
199894    }
199895    pgno = sqlite3_value_int(argv[0]);
199896    if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
199897      zErr = "cannot insert";
199898      goto update_fail;
199899    }
199900    zSchema = (const char*)sqlite3_value_text(argv[4]);
199901    iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
199902    if( iDb<0 ){
199903      zErr = "no such schema";
199904      goto update_fail;
199905    }
199906    pBt = pTab->db->aDb[iDb].pBt;
199907    if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
199908      zErr = "bad page number";
199909      goto update_fail;
199910    }
199911    szPage = sqlite3BtreeGetPageSize(pBt);
199912    if( sqlite3_value_type(argv[3])!=SQLITE_BLOB 
199913     || sqlite3_value_bytes(argv[3])!=szPage
199914    ){
199915      zErr = "bad page value";
199916      goto update_fail;
199917    }
199918    pPager = sqlite3BtreePager(pBt);
199919    rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
199920    if( rc==SQLITE_OK ){
199921      rc = sqlite3PagerWrite(pDbPage);
199922      if( rc==SQLITE_OK ){
199923        memcpy(sqlite3PagerGetData(pDbPage),
199924               sqlite3_value_blob(argv[3]),
199925               szPage);
199926      }
199927    }
199928    sqlite3PagerUnref(pDbPage);
199929    return rc;
199930  
199931  update_fail:
199932    sqlite3_free(pVtab->zErrMsg);
199933    pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
199934    return SQLITE_ERROR;
199935  }
199936  
199937  /* Since we do not know in advance which database files will be
199938  ** written by the sqlite_dbpage virtual table, start a write transaction
199939  ** on them all.
199940  */
199941  static int dbpageBegin(sqlite3_vtab *pVtab){
199942    DbpageTable *pTab = (DbpageTable *)pVtab;
199943    sqlite3 *db = pTab->db;
199944    int i;
199945    for(i=0; i<db->nDb; i++){
199946      Btree *pBt = db->aDb[i].pBt;
199947      if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
199948    }
199949    return SQLITE_OK;
199950  }
199951  
199952  
199953  /*
199954  ** Invoke this routine to register the "dbpage" virtual table module
199955  */
199956  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
199957    static sqlite3_module dbpage_module = {
199958      0,                            /* iVersion */
199959      dbpageConnect,                /* xCreate */
199960      dbpageConnect,                /* xConnect */
199961      dbpageBestIndex,              /* xBestIndex */
199962      dbpageDisconnect,             /* xDisconnect */
199963      dbpageDisconnect,             /* xDestroy */
199964      dbpageOpen,                   /* xOpen - open a cursor */
199965      dbpageClose,                  /* xClose - close a cursor */
199966      dbpageFilter,                 /* xFilter - configure scan constraints */
199967      dbpageNext,                   /* xNext - advance a cursor */
199968      dbpageEof,                    /* xEof - check for end of scan */
199969      dbpageColumn,                 /* xColumn - read data */
199970      dbpageRowid,                  /* xRowid - read data */
199971      dbpageUpdate,                 /* xUpdate */
199972      dbpageBegin,                  /* xBegin */
199973      0,                            /* xSync */
199974      0,                            /* xCommit */
199975      0,                            /* xRollback */
199976      0,                            /* xFindMethod */
199977      0,                            /* xRename */
199978      0,                            /* xSavepoint */
199979      0,                            /* xRelease */
199980      0,                            /* xRollbackTo */
199981      0                             /* xShadowName */
199982    };
199983    return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
199984  }
199985  #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
199986  SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
199987  #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
199988  
199989  /************** End of dbpage.c **********************************************/
199990  /************** Begin file sqlite3session.c **********************************/
199991  
199992  #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
199993  /* #include "sqlite3session.h" */
199994  /* #include <assert.h> */
199995  /* #include <string.h> */
199996  
199997  #ifndef SQLITE_AMALGAMATION
199998  /* # include "sqliteInt.h" */
199999  /* # include "vdbeInt.h" */
200000  #endif
200001  
200002  typedef struct SessionTable SessionTable;
200003  typedef struct SessionChange SessionChange;
200004  typedef struct SessionBuffer SessionBuffer;
200005  typedef struct SessionInput SessionInput;
200006  
200007  /*
200008  ** Minimum chunk size used by streaming versions of functions.
200009  */
200010  #ifndef SESSIONS_STRM_CHUNK_SIZE
200011  # ifdef SQLITE_TEST
200012  #   define SESSIONS_STRM_CHUNK_SIZE 64
200013  # else
200014  #   define SESSIONS_STRM_CHUNK_SIZE 1024
200015  # endif
200016  #endif
200017  
200018  static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
200019  
200020  typedef struct SessionHook SessionHook;
200021  struct SessionHook {
200022    void *pCtx;
200023    int (*xOld)(void*,int,sqlite3_value**);
200024    int (*xNew)(void*,int,sqlite3_value**);
200025    int (*xCount)(void*);
200026    int (*xDepth)(void*);
200027  };
200028  
200029  /*
200030  ** Session handle structure.
200031  */
200032  struct sqlite3_session {
200033    sqlite3 *db;                    /* Database handle session is attached to */
200034    char *zDb;                      /* Name of database session is attached to */
200035    int bEnable;                    /* True if currently recording */
200036    int bIndirect;                  /* True if all changes are indirect */
200037    int bAutoAttach;                /* True to auto-attach tables */
200038    int rc;                         /* Non-zero if an error has occurred */
200039    void *pFilterCtx;               /* First argument to pass to xTableFilter */
200040    int (*xTableFilter)(void *pCtx, const char *zTab);
200041    sqlite3_value *pZeroBlob;       /* Value containing X'' */
200042    sqlite3_session *pNext;         /* Next session object on same db. */
200043    SessionTable *pTable;           /* List of attached tables */
200044    SessionHook hook;               /* APIs to grab new and old data with */
200045  };
200046  
200047  /*
200048  ** Instances of this structure are used to build strings or binary records.
200049  */
200050  struct SessionBuffer {
200051    u8 *aBuf;                       /* Pointer to changeset buffer */
200052    int nBuf;                       /* Size of buffer aBuf */
200053    int nAlloc;                     /* Size of allocation containing aBuf */
200054  };
200055  
200056  /*
200057  ** An object of this type is used internally as an abstraction for 
200058  ** input data. Input data may be supplied either as a single large buffer
200059  ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
200060  **  sqlite3changeset_start_strm()).
200061  */
200062  struct SessionInput {
200063    int bNoDiscard;                 /* If true, do not discard in InputBuffer() */
200064    int iCurrent;                   /* Offset in aData[] of current change */
200065    int iNext;                      /* Offset in aData[] of next change */
200066    u8 *aData;                      /* Pointer to buffer containing changeset */
200067    int nData;                      /* Number of bytes in aData */
200068  
200069    SessionBuffer buf;              /* Current read buffer */
200070    int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
200071    void *pIn;                                /* First argument to xInput */
200072    int bEof;                       /* Set to true after xInput finished */
200073  };
200074  
200075  /*
200076  ** Structure for changeset iterators.
200077  */
200078  struct sqlite3_changeset_iter {
200079    SessionInput in;                /* Input buffer or stream */
200080    SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
200081    int bPatchset;                  /* True if this is a patchset */
200082    int bInvert;                    /* True to invert changeset */
200083    int rc;                         /* Iterator error code */
200084    sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
200085    char *zTab;                     /* Current table */
200086    int nCol;                       /* Number of columns in zTab */
200087    int op;                         /* Current operation */
200088    int bIndirect;                  /* True if current change was indirect */
200089    u8 *abPK;                       /* Primary key array */
200090    sqlite3_value **apValue;        /* old.* and new.* values */
200091  };
200092  
200093  /*
200094  ** Each session object maintains a set of the following structures, one
200095  ** for each table the session object is monitoring. The structures are
200096  ** stored in a linked list starting at sqlite3_session.pTable.
200097  **
200098  ** The keys of the SessionTable.aChange[] hash table are all rows that have
200099  ** been modified in any way since the session object was attached to the
200100  ** table.
200101  **
200102  ** The data associated with each hash-table entry is a structure containing
200103  ** a subset of the initial values that the modified row contained at the
200104  ** start of the session. Or no initial values if the row was inserted.
200105  */
200106  struct SessionTable {
200107    SessionTable *pNext;
200108    char *zName;                    /* Local name of table */
200109    int nCol;                       /* Number of columns in table zName */
200110    int bStat1;                     /* True if this is sqlite_stat1 */
200111    const char **azCol;             /* Column names */
200112    u8 *abPK;                       /* Array of primary key flags */
200113    int nEntry;                     /* Total number of entries in hash table */
200114    int nChange;                    /* Size of apChange[] array */
200115    SessionChange **apChange;       /* Hash table buckets */
200116  };
200117  
200118  /* 
200119  ** RECORD FORMAT:
200120  **
200121  ** The following record format is similar to (but not compatible with) that 
200122  ** used in SQLite database files. This format is used as part of the 
200123  ** change-set binary format, and so must be architecture independent.
200124  **
200125  ** Unlike the SQLite database record format, each field is self-contained -
200126  ** there is no separation of header and data. Each field begins with a
200127  ** single byte describing its type, as follows:
200128  **
200129  **       0x00: Undefined value.
200130  **       0x01: Integer value.
200131  **       0x02: Real value.
200132  **       0x03: Text value.
200133  **       0x04: Blob value.
200134  **       0x05: SQL NULL value.
200135  **
200136  ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
200137  ** and so on in sqlite3.h. For undefined and NULL values, the field consists
200138  ** only of the single type byte. For other types of values, the type byte
200139  ** is followed by:
200140  **
200141  **   Text values:
200142  **     A varint containing the number of bytes in the value (encoded using
200143  **     UTF-8). Followed by a buffer containing the UTF-8 representation
200144  **     of the text value. There is no nul terminator.
200145  **
200146  **   Blob values:
200147  **     A varint containing the number of bytes in the value, followed by
200148  **     a buffer containing the value itself.
200149  **
200150  **   Integer values:
200151  **     An 8-byte big-endian integer value.
200152  **
200153  **   Real values:
200154  **     An 8-byte big-endian IEEE 754-2008 real value.
200155  **
200156  ** Varint values are encoded in the same way as varints in the SQLite 
200157  ** record format.
200158  **
200159  ** CHANGESET FORMAT:
200160  **
200161  ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
200162  ** one or more tables. Operations on a single table are grouped together,
200163  ** but may occur in any order (i.e. deletes, updates and inserts are all
200164  ** mixed together).
200165  **
200166  ** Each group of changes begins with a table header:
200167  **
200168  **   1 byte: Constant 0x54 (capital 'T')
200169  **   Varint: Number of columns in the table.
200170  **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
200171  **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
200172  **
200173  ** Followed by one or more changes to the table.
200174  **
200175  **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
200176  **   1 byte: The "indirect-change" flag.
200177  **   old.* record: (delete and update only)
200178  **   new.* record: (insert and update only)
200179  **
200180  ** The "old.*" and "new.*" records, if present, are N field records in the
200181  ** format described above under "RECORD FORMAT", where N is the number of
200182  ** columns in the table. The i'th field of each record is associated with
200183  ** the i'th column of the table, counting from left to right in the order
200184  ** in which columns were declared in the CREATE TABLE statement.
200185  **
200186  ** The new.* record that is part of each INSERT change contains the values
200187  ** that make up the new row. Similarly, the old.* record that is part of each
200188  ** DELETE change contains the values that made up the row that was deleted 
200189  ** from the database. In the changeset format, the records that are part
200190  ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
200191  ** fields.
200192  **
200193  ** Within the old.* record associated with an UPDATE change, all fields
200194  ** associated with table columns that are not PRIMARY KEY columns and are
200195  ** not modified by the UPDATE change are set to "undefined". Other fields
200196  ** are set to the values that made up the row before the UPDATE that the
200197  ** change records took place. Within the new.* record, fields associated 
200198  ** with table columns modified by the UPDATE change contain the new 
200199  ** values. Fields associated with table columns that are not modified
200200  ** are set to "undefined".
200201  **
200202  ** PATCHSET FORMAT:
200203  **
200204  ** A patchset is also a collection of changes. It is similar to a changeset,
200205  ** but leaves undefined those fields that are not useful if no conflict
200206  ** resolution is required when applying the changeset.
200207  **
200208  ** Each group of changes begins with a table header:
200209  **
200210  **   1 byte: Constant 0x50 (capital 'P')
200211  **   Varint: Number of columns in the table.
200212  **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
200213  **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
200214  **
200215  ** Followed by one or more changes to the table.
200216  **
200217  **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
200218  **   1 byte: The "indirect-change" flag.
200219  **   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
200220  **                   full record for INSERT).
200221  **
200222  ** As in the changeset format, each field of the single record that is part
200223  ** of a patchset change is associated with the correspondingly positioned
200224  ** table column, counting from left to right within the CREATE TABLE 
200225  ** statement.
200226  **
200227  ** For a DELETE change, all fields within the record except those associated
200228  ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
200229  ** values identifying the row to delete.
200230  **
200231  ** For an UPDATE change, all fields except those associated with PRIMARY KEY
200232  ** columns and columns that are modified by the UPDATE are set to "undefined".
200233  ** PRIMARY KEY fields contain the values identifying the table row to update,
200234  ** and fields associated with modified columns contain the new column values.
200235  **
200236  ** The records associated with INSERT changes are in the same format as for
200237  ** changesets. It is not possible for a record associated with an INSERT
200238  ** change to contain a field set to "undefined".
200239  **
200240  ** REBASE BLOB FORMAT:
200241  **
200242  ** A rebase blob may be output by sqlite3changeset_apply_v2() and its 
200243  ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
200244  ** existing changesets. A rebase blob contains one entry for each conflict
200245  ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
200246  ** call.
200247  **
200248  ** The format used for a rebase blob is very similar to that used for
200249  ** changesets. All entries related to a single table are grouped together.
200250  **
200251  ** Each group of entries begins with a table header in changeset format:
200252  **
200253  **   1 byte: Constant 0x54 (capital 'T')
200254  **   Varint: Number of columns in the table.
200255  **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
200256  **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
200257  **
200258  ** Followed by one or more entries associated with the table.
200259  **
200260  **   1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
200261  **   1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
200262  **   record: (in the record format defined above).
200263  **
200264  ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
200265  ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
200266  ** it was a DELETE. The second field is set to 0x01 if the conflict 
200267  ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
200268  **
200269  ** If the change that caused the conflict was a DELETE, then the single
200270  ** record is a copy of the old.* record from the original changeset. If it
200271  ** was an INSERT, then the single record is a copy of the new.* record. If
200272  ** the conflicting change was an UPDATE, then the single record is a copy
200273  ** of the new.* record with the PK fields filled in based on the original
200274  ** old.* record.
200275  */
200276  
200277  /*
200278  ** For each row modified during a session, there exists a single instance of
200279  ** this structure stored in a SessionTable.aChange[] hash table.
200280  */
200281  struct SessionChange {
200282    int op;                         /* One of UPDATE, DELETE, INSERT */
200283    int bIndirect;                  /* True if this change is "indirect" */
200284    int nRecord;                    /* Number of bytes in buffer aRecord[] */
200285    u8 *aRecord;                    /* Buffer containing old.* record */
200286    SessionChange *pNext;           /* For hash-table collisions */
200287  };
200288  
200289  /*
200290  ** Write a varint with value iVal into the buffer at aBuf. Return the 
200291  ** number of bytes written.
200292  */
200293  static int sessionVarintPut(u8 *aBuf, int iVal){
200294    return putVarint32(aBuf, iVal);
200295  }
200296  
200297  /*
200298  ** Return the number of bytes required to store value iVal as a varint.
200299  */
200300  static int sessionVarintLen(int iVal){
200301    return sqlite3VarintLen(iVal);
200302  }
200303  
200304  /*
200305  ** Read a varint value from aBuf[] into *piVal. Return the number of 
200306  ** bytes read.
200307  */
200308  static int sessionVarintGet(u8 *aBuf, int *piVal){
200309    return getVarint32(aBuf, *piVal);
200310  }
200311  
200312  /* Load an unaligned and unsigned 32-bit integer */
200313  #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
200314  
200315  /*
200316  ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
200317  ** the value read.
200318  */
200319  static sqlite3_int64 sessionGetI64(u8 *aRec){
200320    u64 x = SESSION_UINT32(aRec);
200321    u32 y = SESSION_UINT32(aRec+4);
200322    x = (x<<32) + y;
200323    return (sqlite3_int64)x;
200324  }
200325  
200326  /*
200327  ** Write a 64-bit big-endian integer value to the buffer aBuf[].
200328  */
200329  static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
200330    aBuf[0] = (i>>56) & 0xFF;
200331    aBuf[1] = (i>>48) & 0xFF;
200332    aBuf[2] = (i>>40) & 0xFF;
200333    aBuf[3] = (i>>32) & 0xFF;
200334    aBuf[4] = (i>>24) & 0xFF;
200335    aBuf[5] = (i>>16) & 0xFF;
200336    aBuf[6] = (i>> 8) & 0xFF;
200337    aBuf[7] = (i>> 0) & 0xFF;
200338  }
200339  
200340  /*
200341  ** This function is used to serialize the contents of value pValue (see
200342  ** comment titled "RECORD FORMAT" above).
200343  **
200344  ** If it is non-NULL, the serialized form of the value is written to 
200345  ** buffer aBuf. *pnWrite is set to the number of bytes written before
200346  ** returning. Or, if aBuf is NULL, the only thing this function does is
200347  ** set *pnWrite.
200348  **
200349  ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
200350  ** within a call to sqlite3_value_text() (may fail if the db is utf-16)) 
200351  ** SQLITE_NOMEM is returned.
200352  */
200353  static int sessionSerializeValue(
200354    u8 *aBuf,                       /* If non-NULL, write serialized value here */
200355    sqlite3_value *pValue,          /* Value to serialize */
200356    sqlite3_int64 *pnWrite          /* IN/OUT: Increment by bytes written */
200357  ){
200358    int nByte;                      /* Size of serialized value in bytes */
200359  
200360    if( pValue ){
200361      int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
200362    
200363      eType = sqlite3_value_type(pValue);
200364      if( aBuf ) aBuf[0] = eType;
200365    
200366      switch( eType ){
200367        case SQLITE_NULL: 
200368          nByte = 1;
200369          break;
200370    
200371        case SQLITE_INTEGER: 
200372        case SQLITE_FLOAT:
200373          if( aBuf ){
200374            /* TODO: SQLite does something special to deal with mixed-endian
200375            ** floating point values (e.g. ARM7). This code probably should
200376            ** too.  */
200377            u64 i;
200378            if( eType==SQLITE_INTEGER ){
200379              i = (u64)sqlite3_value_int64(pValue);
200380            }else{
200381              double r;
200382              assert( sizeof(double)==8 && sizeof(u64)==8 );
200383              r = sqlite3_value_double(pValue);
200384              memcpy(&i, &r, 8);
200385            }
200386            sessionPutI64(&aBuf[1], i);
200387          }
200388          nByte = 9; 
200389          break;
200390    
200391        default: {
200392          u8 *z;
200393          int n;
200394          int nVarint;
200395    
200396          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
200397          if( eType==SQLITE_TEXT ){
200398            z = (u8 *)sqlite3_value_text(pValue);
200399          }else{
200400            z = (u8 *)sqlite3_value_blob(pValue);
200401          }
200402          n = sqlite3_value_bytes(pValue);
200403          if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
200404          nVarint = sessionVarintLen(n);
200405    
200406          if( aBuf ){
200407            sessionVarintPut(&aBuf[1], n);
200408            if( n ) memcpy(&aBuf[nVarint + 1], z, n);
200409          }
200410    
200411          nByte = 1 + nVarint + n;
200412          break;
200413        }
200414      }
200415    }else{
200416      nByte = 1;
200417      if( aBuf ) aBuf[0] = '\0';
200418    }
200419  
200420    if( pnWrite ) *pnWrite += nByte;
200421    return SQLITE_OK;
200422  }
200423  
200424  
200425  /*
200426  ** This macro is used to calculate hash key values for data structures. In
200427  ** order to use this macro, the entire data structure must be represented
200428  ** as a series of unsigned integers. In order to calculate a hash-key value
200429  ** for a data structure represented as three such integers, the macro may
200430  ** then be used as follows:
200431  **
200432  **    int hash_key_value;
200433  **    hash_key_value = HASH_APPEND(0, <value 1>);
200434  **    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
200435  **    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
200436  **
200437  ** In practice, the data structures this macro is used for are the primary
200438  ** key values of modified rows.
200439  */
200440  #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
200441  
200442  /*
200443  ** Append the hash of the 64-bit integer passed as the second argument to the
200444  ** hash-key value passed as the first. Return the new hash-key value.
200445  */
200446  static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
200447    h = HASH_APPEND(h, i & 0xFFFFFFFF);
200448    return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
200449  }
200450  
200451  /*
200452  ** Append the hash of the blob passed via the second and third arguments to 
200453  ** the hash-key value passed as the first. Return the new hash-key value.
200454  */
200455  static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
200456    int i;
200457    for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
200458    return h;
200459  }
200460  
200461  /*
200462  ** Append the hash of the data type passed as the second argument to the
200463  ** hash-key value passed as the first. Return the new hash-key value.
200464  */
200465  static unsigned int sessionHashAppendType(unsigned int h, int eType){
200466    return HASH_APPEND(h, eType);
200467  }
200468  
200469  /*
200470  ** This function may only be called from within a pre-update callback.
200471  ** It calculates a hash based on the primary key values of the old.* or 
200472  ** new.* row currently available and, assuming no error occurs, writes it to
200473  ** *piHash before returning. If the primary key contains one or more NULL
200474  ** values, *pbNullPK is set to true before returning.
200475  **
200476  ** If an error occurs, an SQLite error code is returned and the final values
200477  ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
200478  ** and the output variables are set as described above.
200479  */
200480  static int sessionPreupdateHash(
200481    sqlite3_session *pSession,      /* Session object that owns pTab */
200482    SessionTable *pTab,             /* Session table handle */
200483    int bNew,                       /* True to hash the new.* PK */
200484    int *piHash,                    /* OUT: Hash value */
200485    int *pbNullPK                   /* OUT: True if there are NULL values in PK */
200486  ){
200487    unsigned int h = 0;             /* Hash value to return */
200488    int i;                          /* Used to iterate through columns */
200489  
200490    assert( *pbNullPK==0 );
200491    assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
200492    for(i=0; i<pTab->nCol; i++){
200493      if( pTab->abPK[i] ){
200494        int rc;
200495        int eType;
200496        sqlite3_value *pVal;
200497  
200498        if( bNew ){
200499          rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
200500        }else{
200501          rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
200502        }
200503        if( rc!=SQLITE_OK ) return rc;
200504  
200505        eType = sqlite3_value_type(pVal);
200506        h = sessionHashAppendType(h, eType);
200507        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
200508          i64 iVal;
200509          if( eType==SQLITE_INTEGER ){
200510            iVal = sqlite3_value_int64(pVal);
200511          }else{
200512            double rVal = sqlite3_value_double(pVal);
200513            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
200514            memcpy(&iVal, &rVal, 8);
200515          }
200516          h = sessionHashAppendI64(h, iVal);
200517        }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
200518          const u8 *z;
200519          int n;
200520          if( eType==SQLITE_TEXT ){
200521            z = (const u8 *)sqlite3_value_text(pVal);
200522          }else{
200523            z = (const u8 *)sqlite3_value_blob(pVal);
200524          }
200525          n = sqlite3_value_bytes(pVal);
200526          if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
200527          h = sessionHashAppendBlob(h, n, z);
200528        }else{
200529          assert( eType==SQLITE_NULL );
200530          assert( pTab->bStat1==0 || i!=1 );
200531          *pbNullPK = 1;
200532        }
200533      }
200534    }
200535  
200536    *piHash = (h % pTab->nChange);
200537    return SQLITE_OK;
200538  }
200539  
200540  /*
200541  ** The buffer that the argument points to contains a serialized SQL value.
200542  ** Return the number of bytes of space occupied by the value (including
200543  ** the type byte).
200544  */
200545  static int sessionSerialLen(u8 *a){
200546    int e = *a;
200547    int n;
200548    if( e==0 || e==0xFF ) return 1;
200549    if( e==SQLITE_NULL ) return 1;
200550    if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
200551    return sessionVarintGet(&a[1], &n) + 1 + n;
200552  }
200553  
200554  /*
200555  ** Based on the primary key values stored in change aRecord, calculate a
200556  ** hash key. Assume the has table has nBucket buckets. The hash keys
200557  ** calculated by this function are compatible with those calculated by
200558  ** sessionPreupdateHash().
200559  **
200560  ** The bPkOnly argument is non-zero if the record at aRecord[] is from
200561  ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
200562  */
200563  static unsigned int sessionChangeHash(
200564    SessionTable *pTab,             /* Table handle */
200565    int bPkOnly,                    /* Record consists of PK fields only */
200566    u8 *aRecord,                    /* Change record */
200567    int nBucket                     /* Assume this many buckets in hash table */
200568  ){
200569    unsigned int h = 0;             /* Value to return */
200570    int i;                          /* Used to iterate through columns */
200571    u8 *a = aRecord;                /* Used to iterate through change record */
200572  
200573    for(i=0; i<pTab->nCol; i++){
200574      int eType = *a;
200575      int isPK = pTab->abPK[i];
200576      if( bPkOnly && isPK==0 ) continue;
200577  
200578      /* It is not possible for eType to be SQLITE_NULL here. The session 
200579      ** module does not record changes for rows with NULL values stored in
200580      ** primary key columns. */
200581      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT 
200582           || eType==SQLITE_TEXT || eType==SQLITE_BLOB 
200583           || eType==SQLITE_NULL || eType==0 
200584      );
200585      assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
200586  
200587      if( isPK ){
200588        a++;
200589        h = sessionHashAppendType(h, eType);
200590        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
200591          h = sessionHashAppendI64(h, sessionGetI64(a));
200592          a += 8;
200593        }else{
200594          int n; 
200595          a += sessionVarintGet(a, &n);
200596          h = sessionHashAppendBlob(h, n, a);
200597          a += n;
200598        }
200599      }else{
200600        a += sessionSerialLen(a);
200601      }
200602    }
200603    return (h % nBucket);
200604  }
200605  
200606  /*
200607  ** Arguments aLeft and aRight are pointers to change records for table pTab.
200608  ** This function returns true if the two records apply to the same row (i.e.
200609  ** have the same values stored in the primary key columns), or false 
200610  ** otherwise.
200611  */
200612  static int sessionChangeEqual(
200613    SessionTable *pTab,             /* Table used for PK definition */
200614    int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
200615    u8 *aLeft,                      /* Change record */
200616    int bRightPkOnly,               /* True if aRight[] contains PK fields only */
200617    u8 *aRight                      /* Change record */
200618  ){
200619    u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
200620    u8 *a2 = aRight;                /* Cursor to iterate through aRight */
200621    int iCol;                       /* Used to iterate through table columns */
200622  
200623    for(iCol=0; iCol<pTab->nCol; iCol++){
200624      if( pTab->abPK[iCol] ){
200625        int n1 = sessionSerialLen(a1);
200626        int n2 = sessionSerialLen(a2);
200627  
200628        if( n1!=n2 || memcmp(a1, a2, n1) ){
200629          return 0;
200630        }
200631        a1 += n1;
200632        a2 += n2;
200633      }else{
200634        if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
200635        if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
200636      }
200637    }
200638  
200639    return 1;
200640  }
200641  
200642  /*
200643  ** Arguments aLeft and aRight both point to buffers containing change
200644  ** records with nCol columns. This function "merges" the two records into
200645  ** a single records which is written to the buffer at *paOut. *paOut is
200646  ** then set to point to one byte after the last byte written before 
200647  ** returning.
200648  **
200649  ** The merging of records is done as follows: For each column, if the 
200650  ** aRight record contains a value for the column, copy the value from
200651  ** their. Otherwise, if aLeft contains a value, copy it. If neither
200652  ** record contains a value for a given column, then neither does the
200653  ** output record.
200654  */
200655  static void sessionMergeRecord(
200656    u8 **paOut, 
200657    int nCol,
200658    u8 *aLeft,
200659    u8 *aRight
200660  ){
200661    u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
200662    u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
200663    u8 *aOut = *paOut;              /* Output cursor */
200664    int iCol;                       /* Used to iterate from 0 to nCol */
200665  
200666    for(iCol=0; iCol<nCol; iCol++){
200667      int n1 = sessionSerialLen(a1);
200668      int n2 = sessionSerialLen(a2);
200669      if( *a2 ){
200670        memcpy(aOut, a2, n2);
200671        aOut += n2;
200672      }else{
200673        memcpy(aOut, a1, n1);
200674        aOut += n1;
200675      }
200676      a1 += n1;
200677      a2 += n2;
200678    }
200679  
200680    *paOut = aOut;
200681  }
200682  
200683  /*
200684  ** This is a helper function used by sessionMergeUpdate().
200685  **
200686  ** When this function is called, both *paOne and *paTwo point to a value 
200687  ** within a change record. Before it returns, both have been advanced so 
200688  ** as to point to the next value in the record.
200689  **
200690  ** If, when this function is called, *paTwo points to a valid value (i.e.
200691  ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
200692  ** pointer is returned and *pnVal is set to the number of bytes in the 
200693  ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
200694  ** set to the number of bytes in the value at *paOne. If *paOne points
200695  ** to the "no value" placeholder, *pnVal is set to 1. In other words:
200696  **
200697  **   if( *paTwo is valid ) return *paTwo;
200698  **   return *paOne;
200699  **
200700  */
200701  static u8 *sessionMergeValue(
200702    u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
200703    u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
200704    int *pnVal                      /* OUT: Bytes in returned value */
200705  ){
200706    u8 *a1 = *paOne;
200707    u8 *a2 = *paTwo;
200708    u8 *pRet = 0;
200709    int n1;
200710  
200711    assert( a1 );
200712    if( a2 ){
200713      int n2 = sessionSerialLen(a2);
200714      if( *a2 ){
200715        *pnVal = n2;
200716        pRet = a2;
200717      }
200718      *paTwo = &a2[n2];
200719    }
200720  
200721    n1 = sessionSerialLen(a1);
200722    if( pRet==0 ){
200723      *pnVal = n1;
200724      pRet = a1;
200725    }
200726    *paOne = &a1[n1];
200727  
200728    return pRet;
200729  }
200730  
200731  /*
200732  ** This function is used by changeset_concat() to merge two UPDATE changes
200733  ** on the same row.
200734  */
200735  static int sessionMergeUpdate(
200736    u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
200737    SessionTable *pTab,             /* Table change pertains to */
200738    int bPatchset,                  /* True if records are patchset records */
200739    u8 *aOldRecord1,                /* old.* record for first change */
200740    u8 *aOldRecord2,                /* old.* record for second change */
200741    u8 *aNewRecord1,                /* new.* record for first change */
200742    u8 *aNewRecord2                 /* new.* record for second change */
200743  ){
200744    u8 *aOld1 = aOldRecord1;
200745    u8 *aOld2 = aOldRecord2;
200746    u8 *aNew1 = aNewRecord1;
200747    u8 *aNew2 = aNewRecord2;
200748  
200749    u8 *aOut = *paOut;
200750    int i;
200751  
200752    if( bPatchset==0 ){
200753      int bRequired = 0;
200754  
200755      assert( aOldRecord1 && aNewRecord1 );
200756  
200757      /* Write the old.* vector first. */
200758      for(i=0; i<pTab->nCol; i++){
200759        int nOld;
200760        u8 *aOld;
200761        int nNew;
200762        u8 *aNew;
200763  
200764        aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
200765        aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
200766        if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
200767          if( pTab->abPK[i]==0 ) bRequired = 1;
200768          memcpy(aOut, aOld, nOld);
200769          aOut += nOld;
200770        }else{
200771          *(aOut++) = '\0';
200772        }
200773      }
200774  
200775      if( !bRequired ) return 0;
200776    }
200777  
200778    /* Write the new.* vector */
200779    aOld1 = aOldRecord1;
200780    aOld2 = aOldRecord2;
200781    aNew1 = aNewRecord1;
200782    aNew2 = aNewRecord2;
200783    for(i=0; i<pTab->nCol; i++){
200784      int nOld;
200785      u8 *aOld;
200786      int nNew;
200787      u8 *aNew;
200788  
200789      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
200790      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
200791      if( bPatchset==0 
200792       && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) 
200793      ){
200794        *(aOut++) = '\0';
200795      }else{
200796        memcpy(aOut, aNew, nNew);
200797        aOut += nNew;
200798      }
200799    }
200800  
200801    *paOut = aOut;
200802    return 1;
200803  }
200804  
200805  /*
200806  ** This function is only called from within a pre-update-hook callback.
200807  ** It determines if the current pre-update-hook change affects the same row
200808  ** as the change stored in argument pChange. If so, it returns true. Otherwise
200809  ** if the pre-update-hook does not affect the same row as pChange, it returns
200810  ** false.
200811  */
200812  static int sessionPreupdateEqual(
200813    sqlite3_session *pSession,      /* Session object that owns SessionTable */
200814    SessionTable *pTab,             /* Table associated with change */
200815    SessionChange *pChange,         /* Change to compare to */
200816    int op                          /* Current pre-update operation */
200817  ){
200818    int iCol;                       /* Used to iterate through columns */
200819    u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
200820  
200821    assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
200822    for(iCol=0; iCol<pTab->nCol; iCol++){
200823      if( !pTab->abPK[iCol] ){
200824        a += sessionSerialLen(a);
200825      }else{
200826        sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
200827        int rc;                     /* Error code from preupdate_new/old */
200828        int eType = *a++;           /* Type of value from change record */
200829  
200830        /* The following calls to preupdate_new() and preupdate_old() can not
200831        ** fail. This is because they cache their return values, and by the
200832        ** time control flows to here they have already been called once from
200833        ** within sessionPreupdateHash(). The first two asserts below verify
200834        ** this (that the method has already been called). */
200835        if( op==SQLITE_INSERT ){
200836          /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
200837          rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
200838        }else{
200839          /* assert( db->pPreUpdate->pUnpacked ); */
200840          rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
200841        }
200842        assert( rc==SQLITE_OK );
200843        if( sqlite3_value_type(pVal)!=eType ) return 0;
200844  
200845        /* A SessionChange object never has a NULL value in a PK column */
200846        assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
200847             || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
200848        );
200849  
200850        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
200851          i64 iVal = sessionGetI64(a);
200852          a += 8;
200853          if( eType==SQLITE_INTEGER ){
200854            if( sqlite3_value_int64(pVal)!=iVal ) return 0;
200855          }else{
200856            double rVal;
200857            assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
200858            memcpy(&rVal, &iVal, 8);
200859            if( sqlite3_value_double(pVal)!=rVal ) return 0;
200860          }
200861        }else{
200862          int n;
200863          const u8 *z;
200864          a += sessionVarintGet(a, &n);
200865          if( sqlite3_value_bytes(pVal)!=n ) return 0;
200866          if( eType==SQLITE_TEXT ){
200867            z = sqlite3_value_text(pVal);
200868          }else{
200869            z = sqlite3_value_blob(pVal);
200870          }
200871          if( n>0 && memcmp(a, z, n) ) return 0;
200872          a += n;
200873        }
200874      }
200875    }
200876  
200877    return 1;
200878  }
200879  
200880  /*
200881  ** If required, grow the hash table used to store changes on table pTab 
200882  ** (part of the session pSession). If a fatal OOM error occurs, set the
200883  ** session object to failed and return SQLITE_ERROR. Otherwise, return
200884  ** SQLITE_OK.
200885  **
200886  ** It is possible that a non-fatal OOM error occurs in this function. In
200887  ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
200888  ** Growing the hash table in this case is a performance optimization only,
200889  ** it is not required for correct operation.
200890  */
200891  static int sessionGrowHash(int bPatchset, SessionTable *pTab){
200892    if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
200893      int i;
200894      SessionChange **apNew;
200895      int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
200896  
200897      apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);
200898      if( apNew==0 ){
200899        if( pTab->nChange==0 ){
200900          return SQLITE_ERROR;
200901        }
200902        return SQLITE_OK;
200903      }
200904      memset(apNew, 0, sizeof(SessionChange *) * nNew);
200905  
200906      for(i=0; i<pTab->nChange; i++){
200907        SessionChange *p;
200908        SessionChange *pNext;
200909        for(p=pTab->apChange[i]; p; p=pNext){
200910          int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
200911          int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
200912          pNext = p->pNext;
200913          p->pNext = apNew[iHash];
200914          apNew[iHash] = p;
200915        }
200916      }
200917  
200918      sqlite3_free(pTab->apChange);
200919      pTab->nChange = nNew;
200920      pTab->apChange = apNew;
200921    }
200922  
200923    return SQLITE_OK;
200924  }
200925  
200926  /*
200927  ** This function queries the database for the names of the columns of table
200928  ** zThis, in schema zDb.
200929  **
200930  ** Otherwise, if they are not NULL, variable *pnCol is set to the number
200931  ** of columns in the database table and variable *pzTab is set to point to a
200932  ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
200933  ** point to an array of pointers to column names. And *pabPK (again, if not
200934  ** NULL) is set to point to an array of booleans - true if the corresponding
200935  ** column is part of the primary key.
200936  **
200937  ** For example, if the table is declared as:
200938  **
200939  **     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
200940  **
200941  ** Then the four output variables are populated as follows:
200942  **
200943  **     *pnCol  = 4
200944  **     *pzTab  = "tbl1"
200945  **     *pazCol = {"w", "x", "y", "z"}
200946  **     *pabPK  = {1, 0, 0, 1}
200947  **
200948  ** All returned buffers are part of the same single allocation, which must
200949  ** be freed using sqlite3_free() by the caller
200950  */
200951  static int sessionTableInfo(
200952    sqlite3 *db,                    /* Database connection */
200953    const char *zDb,                /* Name of attached database (e.g. "main") */
200954    const char *zThis,              /* Table name */
200955    int *pnCol,                     /* OUT: number of columns */
200956    const char **pzTab,             /* OUT: Copy of zThis */
200957    const char ***pazCol,           /* OUT: Array of column names for table */
200958    u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
200959  ){
200960    char *zPragma;
200961    sqlite3_stmt *pStmt;
200962    int rc;
200963    sqlite3_int64 nByte;
200964    int nDbCol = 0;
200965    int nThis;
200966    int i;
200967    u8 *pAlloc = 0;
200968    char **azCol = 0;
200969    u8 *abPK = 0;
200970  
200971    assert( pazCol && pabPK );
200972  
200973    nThis = sqlite3Strlen30(zThis);
200974    if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
200975      rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
200976      if( rc==SQLITE_OK ){
200977        /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
200978        zPragma = sqlite3_mprintf(
200979            "SELECT 0, 'tbl',  '', 0, '', 1     UNION ALL "
200980            "SELECT 1, 'idx',  '', 0, '', 2     UNION ALL "
200981            "SELECT 2, 'stat', '', 0, '', 0"
200982        );
200983      }else if( rc==SQLITE_ERROR ){
200984        zPragma = sqlite3_mprintf("");
200985      }else{
200986        return rc;
200987      }
200988    }else{
200989      zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
200990    }
200991    if( !zPragma ) return SQLITE_NOMEM;
200992  
200993    rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
200994    sqlite3_free(zPragma);
200995    if( rc!=SQLITE_OK ) return rc;
200996  
200997    nByte = nThis + 1;
200998    while( SQLITE_ROW==sqlite3_step(pStmt) ){
200999      nByte += sqlite3_column_bytes(pStmt, 1);
201000      nDbCol++;
201001    }
201002    rc = sqlite3_reset(pStmt);
201003  
201004    if( rc==SQLITE_OK ){
201005      nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
201006      pAlloc = sqlite3_malloc64(nByte);
201007      if( pAlloc==0 ){
201008        rc = SQLITE_NOMEM;
201009      }
201010    }
201011    if( rc==SQLITE_OK ){
201012      azCol = (char **)pAlloc;
201013      pAlloc = (u8 *)&azCol[nDbCol];
201014      abPK = (u8 *)pAlloc;
201015      pAlloc = &abPK[nDbCol];
201016      if( pzTab ){
201017        memcpy(pAlloc, zThis, nThis+1);
201018        *pzTab = (char *)pAlloc;
201019        pAlloc += nThis+1;
201020      }
201021    
201022      i = 0;
201023      while( SQLITE_ROW==sqlite3_step(pStmt) ){
201024        int nName = sqlite3_column_bytes(pStmt, 1);
201025        const unsigned char *zName = sqlite3_column_text(pStmt, 1);
201026        if( zName==0 ) break;
201027        memcpy(pAlloc, zName, nName+1);
201028        azCol[i] = (char *)pAlloc;
201029        pAlloc += nName+1;
201030        abPK[i] = sqlite3_column_int(pStmt, 5);
201031        i++;
201032      }
201033      rc = sqlite3_reset(pStmt);
201034    
201035    }
201036  
201037    /* If successful, populate the output variables. Otherwise, zero them and
201038    ** free any allocation made. An error code will be returned in this case.
201039    */
201040    if( rc==SQLITE_OK ){
201041      *pazCol = (const char **)azCol;
201042      *pabPK = abPK;
201043      *pnCol = nDbCol;
201044    }else{
201045      *pazCol = 0;
201046      *pabPK = 0;
201047      *pnCol = 0;
201048      if( pzTab ) *pzTab = 0;
201049      sqlite3_free(azCol);
201050    }
201051    sqlite3_finalize(pStmt);
201052    return rc;
201053  }
201054  
201055  /*
201056  ** This function is only called from within a pre-update handler for a
201057  ** write to table pTab, part of session pSession. If this is the first
201058  ** write to this table, initalize the SessionTable.nCol, azCol[] and
201059  ** abPK[] arrays accordingly.
201060  **
201061  ** If an error occurs, an error code is stored in sqlite3_session.rc and
201062  ** non-zero returned. Or, if no error occurs but the table has no primary
201063  ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
201064  ** indicate that updates on this table should be ignored. SessionTable.abPK 
201065  ** is set to NULL in this case.
201066  */
201067  static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
201068    if( pTab->nCol==0 ){
201069      u8 *abPK;
201070      assert( pTab->azCol==0 || pTab->abPK==0 );
201071      pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, 
201072          pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
201073      );
201074      if( pSession->rc==SQLITE_OK ){
201075        int i;
201076        for(i=0; i<pTab->nCol; i++){
201077          if( abPK[i] ){
201078            pTab->abPK = abPK;
201079            break;
201080          }
201081        }
201082        if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
201083          pTab->bStat1 = 1;
201084        }
201085      }
201086    }
201087    return (pSession->rc || pTab->abPK==0);
201088  }
201089  
201090  /*
201091  ** Versions of the four methods in object SessionHook for use with the
201092  ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
201093  ** blob each time a NULL value is read from the "idx" column of the
201094  ** sqlite_stat1 table.
201095  */
201096  typedef struct SessionStat1Ctx SessionStat1Ctx;
201097  struct SessionStat1Ctx {
201098    SessionHook hook;
201099    sqlite3_session *pSession;
201100  };
201101  static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
201102    SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
201103    sqlite3_value *pVal = 0;
201104    int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
201105    if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
201106      pVal = p->pSession->pZeroBlob;
201107    }
201108    *ppVal = pVal;
201109    return rc;
201110  }
201111  static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
201112    SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
201113    sqlite3_value *pVal = 0;
201114    int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
201115    if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
201116      pVal = p->pSession->pZeroBlob;
201117    }
201118    *ppVal = pVal;
201119    return rc;
201120  }
201121  static int sessionStat1Count(void *pCtx){
201122    SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
201123    return p->hook.xCount(p->hook.pCtx);
201124  }
201125  static int sessionStat1Depth(void *pCtx){
201126    SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
201127    return p->hook.xDepth(p->hook.pCtx);
201128  }
201129  
201130  
201131  /*
201132  ** This function is only called from with a pre-update-hook reporting a 
201133  ** change on table pTab (attached to session pSession). The type of change
201134  ** (UPDATE, INSERT, DELETE) is specified by the first argument.
201135  **
201136  ** Unless one is already present or an error occurs, an entry is added
201137  ** to the changed-rows hash table associated with table pTab.
201138  */
201139  static void sessionPreupdateOneChange(
201140    int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
201141    sqlite3_session *pSession,      /* Session object pTab is attached to */
201142    SessionTable *pTab              /* Table that change applies to */
201143  ){
201144    int iHash; 
201145    int bNull = 0; 
201146    int rc = SQLITE_OK;
201147    SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
201148  
201149    if( pSession->rc ) return;
201150  
201151    /* Load table details if required */
201152    if( sessionInitTable(pSession, pTab) ) return;
201153  
201154    /* Check the number of columns in this xPreUpdate call matches the 
201155    ** number of columns in the table.  */
201156    if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
201157      pSession->rc = SQLITE_SCHEMA;
201158      return;
201159    }
201160  
201161    /* Grow the hash table if required */
201162    if( sessionGrowHash(0, pTab) ){
201163      pSession->rc = SQLITE_NOMEM;
201164      return;
201165    }
201166  
201167    if( pTab->bStat1 ){
201168      stat1.hook = pSession->hook;
201169      stat1.pSession = pSession;
201170      pSession->hook.pCtx = (void*)&stat1;
201171      pSession->hook.xNew = sessionStat1New;
201172      pSession->hook.xOld = sessionStat1Old;
201173      pSession->hook.xCount = sessionStat1Count;
201174      pSession->hook.xDepth = sessionStat1Depth;
201175      if( pSession->pZeroBlob==0 ){
201176        sqlite3_value *p = sqlite3ValueNew(0);
201177        if( p==0 ){
201178          rc = SQLITE_NOMEM;
201179          goto error_out;
201180        }
201181        sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
201182        pSession->pZeroBlob = p;
201183      }
201184    }
201185  
201186    /* Calculate the hash-key for this change. If the primary key of the row
201187    ** includes a NULL value, exit early. Such changes are ignored by the
201188    ** session module. */
201189    rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
201190    if( rc!=SQLITE_OK ) goto error_out;
201191  
201192    if( bNull==0 ){
201193      /* Search the hash table for an existing record for this row. */
201194      SessionChange *pC;
201195      for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
201196        if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
201197      }
201198  
201199      if( pC==0 ){
201200        /* Create a new change object containing all the old values (if
201201        ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
201202        ** values (if this is an INSERT). */
201203        SessionChange *pChange; /* New change object */
201204        sqlite3_int64 nByte;    /* Number of bytes to allocate */
201205        int i;                  /* Used to iterate through columns */
201206    
201207        assert( rc==SQLITE_OK );
201208        pTab->nEntry++;
201209    
201210        /* Figure out how large an allocation is required */
201211        nByte = sizeof(SessionChange);
201212        for(i=0; i<pTab->nCol; i++){
201213          sqlite3_value *p = 0;
201214          if( op!=SQLITE_INSERT ){
201215            TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
201216            assert( trc==SQLITE_OK );
201217          }else if( pTab->abPK[i] ){
201218            TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
201219            assert( trc==SQLITE_OK );
201220          }
201221  
201222          /* This may fail if SQLite value p contains a utf-16 string that must
201223          ** be converted to utf-8 and an OOM error occurs while doing so. */
201224          rc = sessionSerializeValue(0, p, &nByte);
201225          if( rc!=SQLITE_OK ) goto error_out;
201226        }
201227    
201228        /* Allocate the change object */
201229        pChange = (SessionChange *)sqlite3_malloc64(nByte);
201230        if( !pChange ){
201231          rc = SQLITE_NOMEM;
201232          goto error_out;
201233        }else{
201234          memset(pChange, 0, sizeof(SessionChange));
201235          pChange->aRecord = (u8 *)&pChange[1];
201236        }
201237    
201238        /* Populate the change object. None of the preupdate_old(),
201239        ** preupdate_new() or SerializeValue() calls below may fail as all
201240        ** required values and encodings have already been cached in memory.
201241        ** It is not possible for an OOM to occur in this block. */
201242        nByte = 0;
201243        for(i=0; i<pTab->nCol; i++){
201244          sqlite3_value *p = 0;
201245          if( op!=SQLITE_INSERT ){
201246            pSession->hook.xOld(pSession->hook.pCtx, i, &p);
201247          }else if( pTab->abPK[i] ){
201248            pSession->hook.xNew(pSession->hook.pCtx, i, &p);
201249          }
201250          sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
201251        }
201252  
201253        /* Add the change to the hash-table */
201254        if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
201255          pChange->bIndirect = 1;
201256        }
201257        pChange->nRecord = nByte;
201258        pChange->op = op;
201259        pChange->pNext = pTab->apChange[iHash];
201260        pTab->apChange[iHash] = pChange;
201261  
201262      }else if( pC->bIndirect ){
201263        /* If the existing change is considered "indirect", but this current
201264        ** change is "direct", mark the change object as direct. */
201265        if( pSession->hook.xDepth(pSession->hook.pCtx)==0 
201266         && pSession->bIndirect==0 
201267        ){
201268          pC->bIndirect = 0;
201269        }
201270      }
201271    }
201272  
201273    /* If an error has occurred, mark the session object as failed. */
201274   error_out:
201275    if( pTab->bStat1 ){
201276      pSession->hook = stat1.hook;
201277    }
201278    if( rc!=SQLITE_OK ){
201279      pSession->rc = rc;
201280    }
201281  }
201282  
201283  static int sessionFindTable(
201284    sqlite3_session *pSession, 
201285    const char *zName,
201286    SessionTable **ppTab
201287  ){
201288    int rc = SQLITE_OK;
201289    int nName = sqlite3Strlen30(zName);
201290    SessionTable *pRet;
201291  
201292    /* Search for an existing table */
201293    for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
201294      if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
201295    }
201296  
201297    if( pRet==0 && pSession->bAutoAttach ){
201298      /* If there is a table-filter configured, invoke it. If it returns 0,
201299      ** do not automatically add the new table. */
201300      if( pSession->xTableFilter==0
201301       || pSession->xTableFilter(pSession->pFilterCtx, zName) 
201302      ){
201303        rc = sqlite3session_attach(pSession, zName);
201304        if( rc==SQLITE_OK ){
201305          for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
201306          assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
201307        }
201308      }
201309    }
201310  
201311    assert( rc==SQLITE_OK || pRet==0 );
201312    *ppTab = pRet;
201313    return rc;
201314  }
201315  
201316  /*
201317  ** The 'pre-update' hook registered by this module with SQLite databases.
201318  */
201319  static void xPreUpdate(
201320    void *pCtx,                     /* Copy of third arg to preupdate_hook() */
201321    sqlite3 *db,                    /* Database handle */
201322    int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
201323    char const *zDb,                /* Database name */
201324    char const *zName,              /* Table name */
201325    sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
201326    sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
201327  ){
201328    sqlite3_session *pSession;
201329    int nDb = sqlite3Strlen30(zDb);
201330  
201331    assert( sqlite3_mutex_held(db->mutex) );
201332  
201333    for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
201334      SessionTable *pTab;
201335  
201336      /* If this session is attached to a different database ("main", "temp" 
201337      ** etc.), or if it is not currently enabled, there is nothing to do. Skip 
201338      ** to the next session object attached to this database. */
201339      if( pSession->bEnable==0 ) continue;
201340      if( pSession->rc ) continue;
201341      if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
201342  
201343      pSession->rc = sessionFindTable(pSession, zName, &pTab);
201344      if( pTab ){
201345        assert( pSession->rc==SQLITE_OK );
201346        sessionPreupdateOneChange(op, pSession, pTab);
201347        if( op==SQLITE_UPDATE ){
201348          sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
201349        }
201350      }
201351    }
201352  }
201353  
201354  /*
201355  ** The pre-update hook implementations.
201356  */
201357  static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
201358    return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
201359  }
201360  static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
201361    return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
201362  }
201363  static int sessionPreupdateCount(void *pCtx){
201364    return sqlite3_preupdate_count((sqlite3*)pCtx);
201365  }
201366  static int sessionPreupdateDepth(void *pCtx){
201367    return sqlite3_preupdate_depth((sqlite3*)pCtx);
201368  }
201369  
201370  /*
201371  ** Install the pre-update hooks on the session object passed as the only
201372  ** argument.
201373  */
201374  static void sessionPreupdateHooks(
201375    sqlite3_session *pSession
201376  ){
201377    pSession->hook.pCtx = (void*)pSession->db;
201378    pSession->hook.xOld = sessionPreupdateOld;
201379    pSession->hook.xNew = sessionPreupdateNew;
201380    pSession->hook.xCount = sessionPreupdateCount;
201381    pSession->hook.xDepth = sessionPreupdateDepth;
201382  }
201383  
201384  typedef struct SessionDiffCtx SessionDiffCtx;
201385  struct SessionDiffCtx {
201386    sqlite3_stmt *pStmt;
201387    int nOldOff;
201388  };
201389  
201390  /*
201391  ** The diff hook implementations.
201392  */
201393  static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
201394    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
201395    *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
201396    return SQLITE_OK;
201397  }
201398  static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
201399    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
201400    *ppVal = sqlite3_column_value(p->pStmt, iVal);
201401     return SQLITE_OK;
201402  }
201403  static int sessionDiffCount(void *pCtx){
201404    SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
201405    return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
201406  }
201407  static int sessionDiffDepth(void *pCtx){
201408    return 0;
201409  }
201410  
201411  /*
201412  ** Install the diff hooks on the session object passed as the only
201413  ** argument.
201414  */
201415  static void sessionDiffHooks(
201416    sqlite3_session *pSession,
201417    SessionDiffCtx *pDiffCtx
201418  ){
201419    pSession->hook.pCtx = (void*)pDiffCtx;
201420    pSession->hook.xOld = sessionDiffOld;
201421    pSession->hook.xNew = sessionDiffNew;
201422    pSession->hook.xCount = sessionDiffCount;
201423    pSession->hook.xDepth = sessionDiffDepth;
201424  }
201425  
201426  static char *sessionExprComparePK(
201427    int nCol,
201428    const char *zDb1, const char *zDb2, 
201429    const char *zTab,
201430    const char **azCol, u8 *abPK
201431  ){
201432    int i;
201433    const char *zSep = "";
201434    char *zRet = 0;
201435  
201436    for(i=0; i<nCol; i++){
201437      if( abPK[i] ){
201438        zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
201439            zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
201440        );
201441        zSep = " AND ";
201442        if( zRet==0 ) break;
201443      }
201444    }
201445  
201446    return zRet;
201447  }
201448  
201449  static char *sessionExprCompareOther(
201450    int nCol,
201451    const char *zDb1, const char *zDb2, 
201452    const char *zTab,
201453    const char **azCol, u8 *abPK
201454  ){
201455    int i;
201456    const char *zSep = "";
201457    char *zRet = 0;
201458    int bHave = 0;
201459  
201460    for(i=0; i<nCol; i++){
201461      if( abPK[i]==0 ){
201462        bHave = 1;
201463        zRet = sqlite3_mprintf(
201464            "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
201465            zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
201466        );
201467        zSep = " OR ";
201468        if( zRet==0 ) break;
201469      }
201470    }
201471  
201472    if( bHave==0 ){
201473      assert( zRet==0 );
201474      zRet = sqlite3_mprintf("0");
201475    }
201476  
201477    return zRet;
201478  }
201479  
201480  static char *sessionSelectFindNew(
201481    int nCol,
201482    const char *zDb1,      /* Pick rows in this db only */
201483    const char *zDb2,      /* But not in this one */
201484    const char *zTbl,      /* Table name */
201485    const char *zExpr
201486  ){
201487    char *zRet = sqlite3_mprintf(
201488        "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
201489        "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
201490        ")",
201491        zDb1, zTbl, zDb2, zTbl, zExpr
201492    );
201493    return zRet;
201494  }
201495  
201496  static int sessionDiffFindNew(
201497    int op,
201498    sqlite3_session *pSession,
201499    SessionTable *pTab,
201500    const char *zDb1,
201501    const char *zDb2,
201502    char *zExpr
201503  ){
201504    int rc = SQLITE_OK;
201505    char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
201506  
201507    if( zStmt==0 ){
201508      rc = SQLITE_NOMEM;
201509    }else{
201510      sqlite3_stmt *pStmt;
201511      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
201512      if( rc==SQLITE_OK ){
201513        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
201514        pDiffCtx->pStmt = pStmt;
201515        pDiffCtx->nOldOff = 0;
201516        while( SQLITE_ROW==sqlite3_step(pStmt) ){
201517          sessionPreupdateOneChange(op, pSession, pTab);
201518        }
201519        rc = sqlite3_finalize(pStmt);
201520      }
201521      sqlite3_free(zStmt);
201522    }
201523  
201524    return rc;
201525  }
201526  
201527  static int sessionDiffFindModified(
201528    sqlite3_session *pSession, 
201529    SessionTable *pTab, 
201530    const char *zFrom, 
201531    const char *zExpr
201532  ){
201533    int rc = SQLITE_OK;
201534  
201535    char *zExpr2 = sessionExprCompareOther(pTab->nCol,
201536        pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
201537    );
201538    if( zExpr2==0 ){
201539      rc = SQLITE_NOMEM;
201540    }else{
201541      char *zStmt = sqlite3_mprintf(
201542          "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
201543          pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
201544      );
201545      if( zStmt==0 ){
201546        rc = SQLITE_NOMEM;
201547      }else{
201548        sqlite3_stmt *pStmt;
201549        rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
201550  
201551        if( rc==SQLITE_OK ){
201552          SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
201553          pDiffCtx->pStmt = pStmt;
201554          pDiffCtx->nOldOff = pTab->nCol;
201555          while( SQLITE_ROW==sqlite3_step(pStmt) ){
201556            sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
201557          }
201558          rc = sqlite3_finalize(pStmt);
201559        }
201560        sqlite3_free(zStmt);
201561      }
201562    }
201563  
201564    return rc;
201565  }
201566  
201567  SQLITE_API int sqlite3session_diff(
201568    sqlite3_session *pSession,
201569    const char *zFrom,
201570    const char *zTbl,
201571    char **pzErrMsg
201572  ){
201573    const char *zDb = pSession->zDb;
201574    int rc = pSession->rc;
201575    SessionDiffCtx d;
201576  
201577    memset(&d, 0, sizeof(d));
201578    sessionDiffHooks(pSession, &d);
201579  
201580    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
201581    if( pzErrMsg ) *pzErrMsg = 0;
201582    if( rc==SQLITE_OK ){
201583      char *zExpr = 0;
201584      sqlite3 *db = pSession->db;
201585      SessionTable *pTo;            /* Table zTbl */
201586  
201587      /* Locate and if necessary initialize the target table object */
201588      rc = sessionFindTable(pSession, zTbl, &pTo);
201589      if( pTo==0 ) goto diff_out;
201590      if( sessionInitTable(pSession, pTo) ){
201591        rc = pSession->rc;
201592        goto diff_out;
201593      }
201594  
201595      /* Check the table schemas match */
201596      if( rc==SQLITE_OK ){
201597        int bHasPk = 0;
201598        int bMismatch = 0;
201599        int nCol;                   /* Columns in zFrom.zTbl */
201600        u8 *abPK;
201601        const char **azCol = 0;
201602        rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
201603        if( rc==SQLITE_OK ){
201604          if( pTo->nCol!=nCol ){
201605            bMismatch = 1;
201606          }else{
201607            int i;
201608            for(i=0; i<nCol; i++){
201609              if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
201610              if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
201611              if( abPK[i] ) bHasPk = 1;
201612            }
201613          }
201614        }
201615        sqlite3_free((char*)azCol);
201616        if( bMismatch ){
201617          *pzErrMsg = sqlite3_mprintf("table schemas do not match");
201618          rc = SQLITE_SCHEMA;
201619        }
201620        if( bHasPk==0 ){
201621          /* Ignore tables with no primary keys */
201622          goto diff_out;
201623        }
201624      }
201625  
201626      if( rc==SQLITE_OK ){
201627        zExpr = sessionExprComparePK(pTo->nCol, 
201628            zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
201629        );
201630      }
201631  
201632      /* Find new rows */
201633      if( rc==SQLITE_OK ){
201634        rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
201635      }
201636  
201637      /* Find old rows */
201638      if( rc==SQLITE_OK ){
201639        rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
201640      }
201641  
201642      /* Find modified rows */
201643      if( rc==SQLITE_OK ){
201644        rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
201645      }
201646  
201647      sqlite3_free(zExpr);
201648    }
201649  
201650   diff_out:
201651    sessionPreupdateHooks(pSession);
201652    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
201653    return rc;
201654  }
201655  
201656  /*
201657  ** Create a session object. This session object will record changes to
201658  ** database zDb attached to connection db.
201659  */
201660  SQLITE_API int sqlite3session_create(
201661    sqlite3 *db,                    /* Database handle */
201662    const char *zDb,                /* Name of db (e.g. "main") */
201663    sqlite3_session **ppSession     /* OUT: New session object */
201664  ){
201665    sqlite3_session *pNew;          /* Newly allocated session object */
201666    sqlite3_session *pOld;          /* Session object already attached to db */
201667    int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
201668  
201669    /* Zero the output value in case an error occurs. */
201670    *ppSession = 0;
201671  
201672    /* Allocate and populate the new session object. */
201673    pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
201674    if( !pNew ) return SQLITE_NOMEM;
201675    memset(pNew, 0, sizeof(sqlite3_session));
201676    pNew->db = db;
201677    pNew->zDb = (char *)&pNew[1];
201678    pNew->bEnable = 1;
201679    memcpy(pNew->zDb, zDb, nDb+1);
201680    sessionPreupdateHooks(pNew);
201681  
201682    /* Add the new session object to the linked list of session objects 
201683    ** attached to database handle $db. Do this under the cover of the db
201684    ** handle mutex.  */
201685    sqlite3_mutex_enter(sqlite3_db_mutex(db));
201686    pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
201687    pNew->pNext = pOld;
201688    sqlite3_mutex_leave(sqlite3_db_mutex(db));
201689  
201690    *ppSession = pNew;
201691    return SQLITE_OK;
201692  }
201693  
201694  /*
201695  ** Free the list of table objects passed as the first argument. The contents
201696  ** of the changed-rows hash tables are also deleted.
201697  */
201698  static void sessionDeleteTable(SessionTable *pList){
201699    SessionTable *pNext;
201700    SessionTable *pTab;
201701  
201702    for(pTab=pList; pTab; pTab=pNext){
201703      int i;
201704      pNext = pTab->pNext;
201705      for(i=0; i<pTab->nChange; i++){
201706        SessionChange *p;
201707        SessionChange *pNextChange;
201708        for(p=pTab->apChange[i]; p; p=pNextChange){
201709          pNextChange = p->pNext;
201710          sqlite3_free(p);
201711        }
201712      }
201713      sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
201714      sqlite3_free(pTab->apChange);
201715      sqlite3_free(pTab);
201716    }
201717  }
201718  
201719  /*
201720  ** Delete a session object previously allocated using sqlite3session_create().
201721  */
201722  SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
201723    sqlite3 *db = pSession->db;
201724    sqlite3_session *pHead;
201725    sqlite3_session **pp;
201726  
201727    /* Unlink the session from the linked list of sessions attached to the
201728    ** database handle. Hold the db mutex while doing so.  */
201729    sqlite3_mutex_enter(sqlite3_db_mutex(db));
201730    pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
201731    for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
201732      if( (*pp)==pSession ){
201733        *pp = (*pp)->pNext;
201734        if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
201735        break;
201736      }
201737    }
201738    sqlite3_mutex_leave(sqlite3_db_mutex(db));
201739    sqlite3ValueFree(pSession->pZeroBlob);
201740  
201741    /* Delete all attached table objects. And the contents of their 
201742    ** associated hash-tables. */
201743    sessionDeleteTable(pSession->pTable);
201744  
201745    /* Free the session object itself. */
201746    sqlite3_free(pSession);
201747  }
201748  
201749  /*
201750  ** Set a table filter on a Session Object.
201751  */
201752  SQLITE_API void sqlite3session_table_filter(
201753    sqlite3_session *pSession, 
201754    int(*xFilter)(void*, const char*),
201755    void *pCtx                      /* First argument passed to xFilter */
201756  ){
201757    pSession->bAutoAttach = 1;
201758    pSession->pFilterCtx = pCtx;
201759    pSession->xTableFilter = xFilter;
201760  }
201761  
201762  /*
201763  ** Attach a table to a session. All subsequent changes made to the table
201764  ** while the session object is enabled will be recorded.
201765  **
201766  ** Only tables that have a PRIMARY KEY defined may be attached. It does
201767  ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
201768  ** or not.
201769  */
201770  SQLITE_API int sqlite3session_attach(
201771    sqlite3_session *pSession,      /* Session object */
201772    const char *zName               /* Table name */
201773  ){
201774    int rc = SQLITE_OK;
201775    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
201776  
201777    if( !zName ){
201778      pSession->bAutoAttach = 1;
201779    }else{
201780      SessionTable *pTab;           /* New table object (if required) */
201781      int nName;                    /* Number of bytes in string zName */
201782  
201783      /* First search for an existing entry. If one is found, this call is
201784      ** a no-op. Return early. */
201785      nName = sqlite3Strlen30(zName);
201786      for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
201787        if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
201788      }
201789  
201790      if( !pTab ){
201791        /* Allocate new SessionTable object. */
201792        pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);
201793        if( !pTab ){
201794          rc = SQLITE_NOMEM;
201795        }else{
201796          /* Populate the new SessionTable object and link it into the list.
201797          ** The new object must be linked onto the end of the list, not 
201798          ** simply added to the start of it in order to ensure that tables
201799          ** appear in the correct order when a changeset or patchset is
201800          ** eventually generated. */
201801          SessionTable **ppTab;
201802          memset(pTab, 0, sizeof(SessionTable));
201803          pTab->zName = (char *)&pTab[1];
201804          memcpy(pTab->zName, zName, nName+1);
201805          for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
201806          *ppTab = pTab;
201807        }
201808      }
201809    }
201810  
201811    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
201812    return rc;
201813  }
201814  
201815  /*
201816  ** Ensure that there is room in the buffer to append nByte bytes of data.
201817  ** If not, use sqlite3_realloc() to grow the buffer so that there is.
201818  **
201819  ** If successful, return zero. Otherwise, if an OOM condition is encountered,
201820  ** set *pRc to SQLITE_NOMEM and return non-zero.
201821  */
201822  static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
201823    if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
201824      u8 *aNew;
201825      i64 nNew = p->nAlloc ? p->nAlloc : 128;
201826      do {
201827        nNew = nNew*2;
201828      }while( (nNew-p->nBuf)<nByte );
201829  
201830      aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
201831      if( 0==aNew ){
201832        *pRc = SQLITE_NOMEM;
201833      }else{
201834        p->aBuf = aNew;
201835        p->nAlloc = nNew;
201836      }
201837    }
201838    return (*pRc!=SQLITE_OK);
201839  }
201840  
201841  /*
201842  ** Append the value passed as the second argument to the buffer passed
201843  ** as the first.
201844  **
201845  ** This function is a no-op if *pRc is non-zero when it is called.
201846  ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
201847  ** before returning.
201848  */
201849  static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
201850    int rc = *pRc;
201851    if( rc==SQLITE_OK ){
201852      sqlite3_int64 nByte = 0;
201853      rc = sessionSerializeValue(0, pVal, &nByte);
201854      sessionBufferGrow(p, nByte, &rc);
201855      if( rc==SQLITE_OK ){
201856        rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
201857        p->nBuf += nByte;
201858      }else{
201859        *pRc = rc;
201860      }
201861    }
201862  }
201863  
201864  /*
201865  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201866  ** called. Otherwise, append a single byte to the buffer. 
201867  **
201868  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201869  ** returning.
201870  */
201871  static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
201872    if( 0==sessionBufferGrow(p, 1, pRc) ){
201873      p->aBuf[p->nBuf++] = v;
201874    }
201875  }
201876  
201877  /*
201878  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201879  ** called. Otherwise, append a single varint to the buffer. 
201880  **
201881  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201882  ** returning.
201883  */
201884  static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
201885    if( 0==sessionBufferGrow(p, 9, pRc) ){
201886      p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
201887    }
201888  }
201889  
201890  /*
201891  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201892  ** called. Otherwise, append a blob of data to the buffer. 
201893  **
201894  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201895  ** returning.
201896  */
201897  static void sessionAppendBlob(
201898    SessionBuffer *p, 
201899    const u8 *aBlob, 
201900    int nBlob, 
201901    int *pRc
201902  ){
201903    if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
201904      memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
201905      p->nBuf += nBlob;
201906    }
201907  }
201908  
201909  /*
201910  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201911  ** called. Otherwise, append a string to the buffer. All bytes in the string
201912  ** up to (but not including) the nul-terminator are written to the buffer.
201913  **
201914  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201915  ** returning.
201916  */
201917  static void sessionAppendStr(
201918    SessionBuffer *p, 
201919    const char *zStr, 
201920    int *pRc
201921  ){
201922    int nStr = sqlite3Strlen30(zStr);
201923    if( 0==sessionBufferGrow(p, nStr, pRc) ){
201924      memcpy(&p->aBuf[p->nBuf], zStr, nStr);
201925      p->nBuf += nStr;
201926    }
201927  }
201928  
201929  /*
201930  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201931  ** called. Otherwise, append the string representation of integer iVal
201932  ** to the buffer. No nul-terminator is written.
201933  **
201934  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201935  ** returning.
201936  */
201937  static void sessionAppendInteger(
201938    SessionBuffer *p,               /* Buffer to append to */
201939    int iVal,                       /* Value to write the string rep. of */
201940    int *pRc                        /* IN/OUT: Error code */
201941  ){
201942    char aBuf[24];
201943    sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
201944    sessionAppendStr(p, aBuf, pRc);
201945  }
201946  
201947  /*
201948  ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
201949  ** called. Otherwise, append the string zStr enclosed in quotes (") and
201950  ** with any embedded quote characters escaped to the buffer. No 
201951  ** nul-terminator byte is written.
201952  **
201953  ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
201954  ** returning.
201955  */
201956  static void sessionAppendIdent(
201957    SessionBuffer *p,               /* Buffer to a append to */
201958    const char *zStr,               /* String to quote, escape and append */
201959    int *pRc                        /* IN/OUT: Error code */
201960  ){
201961    int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
201962    if( 0==sessionBufferGrow(p, nStr, pRc) ){
201963      char *zOut = (char *)&p->aBuf[p->nBuf];
201964      const char *zIn = zStr;
201965      *zOut++ = '"';
201966      while( *zIn ){
201967        if( *zIn=='"' ) *zOut++ = '"';
201968        *zOut++ = *(zIn++);
201969      }
201970      *zOut++ = '"';
201971      p->nBuf = (int)((u8 *)zOut - p->aBuf);
201972    }
201973  }
201974  
201975  /*
201976  ** This function is a no-op if *pRc is other than SQLITE_OK when it is
201977  ** called. Otherwse, it appends the serialized version of the value stored
201978  ** in column iCol of the row that SQL statement pStmt currently points
201979  ** to to the buffer.
201980  */
201981  static void sessionAppendCol(
201982    SessionBuffer *p,               /* Buffer to append to */
201983    sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
201984    int iCol,                       /* Column to read value from */
201985    int *pRc                        /* IN/OUT: Error code */
201986  ){
201987    if( *pRc==SQLITE_OK ){
201988      int eType = sqlite3_column_type(pStmt, iCol);
201989      sessionAppendByte(p, (u8)eType, pRc);
201990      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
201991        sqlite3_int64 i;
201992        u8 aBuf[8];
201993        if( eType==SQLITE_INTEGER ){
201994          i = sqlite3_column_int64(pStmt, iCol);
201995        }else{
201996          double r = sqlite3_column_double(pStmt, iCol);
201997          memcpy(&i, &r, 8);
201998        }
201999        sessionPutI64(aBuf, i);
202000        sessionAppendBlob(p, aBuf, 8, pRc);
202001      }
202002      if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
202003        u8 *z;
202004        int nByte;
202005        if( eType==SQLITE_BLOB ){
202006          z = (u8 *)sqlite3_column_blob(pStmt, iCol);
202007        }else{
202008          z = (u8 *)sqlite3_column_text(pStmt, iCol);
202009        }
202010        nByte = sqlite3_column_bytes(pStmt, iCol);
202011        if( z || (eType==SQLITE_BLOB && nByte==0) ){
202012          sessionAppendVarint(p, nByte, pRc);
202013          sessionAppendBlob(p, z, nByte, pRc);
202014        }else{
202015          *pRc = SQLITE_NOMEM;
202016        }
202017      }
202018    }
202019  }
202020  
202021  /*
202022  **
202023  ** This function appends an update change to the buffer (see the comments 
202024  ** under "CHANGESET FORMAT" at the top of the file). An update change 
202025  ** consists of:
202026  **
202027  **   1 byte:  SQLITE_UPDATE (0x17)
202028  **   n bytes: old.* record (see RECORD FORMAT)
202029  **   m bytes: new.* record (see RECORD FORMAT)
202030  **
202031  ** The SessionChange object passed as the third argument contains the
202032  ** values that were stored in the row when the session began (the old.*
202033  ** values). The statement handle passed as the second argument points
202034  ** at the current version of the row (the new.* values).
202035  **
202036  ** If all of the old.* values are equal to their corresponding new.* value
202037  ** (i.e. nothing has changed), then no data at all is appended to the buffer.
202038  **
202039  ** Otherwise, the old.* record contains all primary key values and the 
202040  ** original values of any fields that have been modified. The new.* record 
202041  ** contains the new values of only those fields that have been modified.
202042  */ 
202043  static int sessionAppendUpdate(
202044    SessionBuffer *pBuf,            /* Buffer to append to */
202045    int bPatchset,                  /* True for "patchset", 0 for "changeset" */
202046    sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
202047    SessionChange *p,               /* Object containing old values */
202048    u8 *abPK                        /* Boolean array - true for PK columns */
202049  ){
202050    int rc = SQLITE_OK;
202051    SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
202052    int bNoop = 1;                /* Set to zero if any values are modified */
202053    int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
202054    int i;                        /* Used to iterate through columns */
202055    u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
202056  
202057    sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
202058    sessionAppendByte(pBuf, p->bIndirect, &rc);
202059    for(i=0; i<sqlite3_column_count(pStmt); i++){
202060      int bChanged = 0;
202061      int nAdvance;
202062      int eType = *pCsr;
202063      switch( eType ){
202064        case SQLITE_NULL:
202065          nAdvance = 1;
202066          if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
202067            bChanged = 1;
202068          }
202069          break;
202070  
202071        case SQLITE_FLOAT:
202072        case SQLITE_INTEGER: {
202073          nAdvance = 9;
202074          if( eType==sqlite3_column_type(pStmt, i) ){
202075            sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
202076            if( eType==SQLITE_INTEGER ){
202077              if( iVal==sqlite3_column_int64(pStmt, i) ) break;
202078            }else{
202079              double dVal;
202080              memcpy(&dVal, &iVal, 8);
202081              if( dVal==sqlite3_column_double(pStmt, i) ) break;
202082            }
202083          }
202084          bChanged = 1;
202085          break;
202086        }
202087  
202088        default: {
202089          int n;
202090          int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
202091          assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
202092          nAdvance = nHdr + n;
202093          if( eType==sqlite3_column_type(pStmt, i) 
202094           && n==sqlite3_column_bytes(pStmt, i) 
202095           && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
202096          ){
202097            break;
202098          }
202099          bChanged = 1;
202100        }
202101      }
202102  
202103      /* If at least one field has been modified, this is not a no-op. */
202104      if( bChanged ) bNoop = 0;
202105  
202106      /* Add a field to the old.* record. This is omitted if this modules is
202107      ** currently generating a patchset. */
202108      if( bPatchset==0 ){
202109        if( bChanged || abPK[i] ){
202110          sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
202111        }else{
202112          sessionAppendByte(pBuf, 0, &rc);
202113        }
202114      }
202115  
202116      /* Add a field to the new.* record. Or the only record if currently
202117      ** generating a patchset.  */
202118      if( bChanged || (bPatchset && abPK[i]) ){
202119        sessionAppendCol(&buf2, pStmt, i, &rc);
202120      }else{
202121        sessionAppendByte(&buf2, 0, &rc);
202122      }
202123  
202124      pCsr += nAdvance;
202125    }
202126  
202127    if( bNoop ){
202128      pBuf->nBuf = nRewind;
202129    }else{
202130      sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
202131    }
202132    sqlite3_free(buf2.aBuf);
202133  
202134    return rc;
202135  }
202136  
202137  /*
202138  ** Append a DELETE change to the buffer passed as the first argument. Use
202139  ** the changeset format if argument bPatchset is zero, or the patchset
202140  ** format otherwise.
202141  */
202142  static int sessionAppendDelete(
202143    SessionBuffer *pBuf,            /* Buffer to append to */
202144    int bPatchset,                  /* True for "patchset", 0 for "changeset" */
202145    SessionChange *p,               /* Object containing old values */
202146    int nCol,                       /* Number of columns in table */
202147    u8 *abPK                        /* Boolean array - true for PK columns */
202148  ){
202149    int rc = SQLITE_OK;
202150  
202151    sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
202152    sessionAppendByte(pBuf, p->bIndirect, &rc);
202153  
202154    if( bPatchset==0 ){
202155      sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
202156    }else{
202157      int i;
202158      u8 *a = p->aRecord;
202159      for(i=0; i<nCol; i++){
202160        u8 *pStart = a;
202161        int eType = *a++;
202162  
202163        switch( eType ){
202164          case 0:
202165          case SQLITE_NULL:
202166            assert( abPK[i]==0 );
202167            break;
202168  
202169          case SQLITE_FLOAT:
202170          case SQLITE_INTEGER:
202171            a += 8;
202172            break;
202173  
202174          default: {
202175            int n;
202176            a += sessionVarintGet(a, &n);
202177            a += n;
202178            break;
202179          }
202180        }
202181        if( abPK[i] ){
202182          sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
202183        }
202184      }
202185      assert( (a - p->aRecord)==p->nRecord );
202186    }
202187  
202188    return rc;
202189  }
202190  
202191  /*
202192  ** Formulate and prepare a SELECT statement to retrieve a row from table
202193  ** zTab in database zDb based on its primary key. i.e.
202194  **
202195  **   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
202196  */
202197  static int sessionSelectStmt(
202198    sqlite3 *db,                    /* Database handle */
202199    const char *zDb,                /* Database name */
202200    const char *zTab,               /* Table name */
202201    int nCol,                       /* Number of columns in table */
202202    const char **azCol,             /* Names of table columns */
202203    u8 *abPK,                       /* PRIMARY KEY  array */
202204    sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
202205  ){
202206    int rc = SQLITE_OK;
202207    char *zSql = 0;
202208    int nSql = -1;
202209  
202210    if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
202211      zSql = sqlite3_mprintf(
202212          "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
202213          "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
202214      );
202215      if( zSql==0 ) rc = SQLITE_NOMEM;
202216    }else{
202217      int i;
202218      const char *zSep = "";
202219      SessionBuffer buf = {0, 0, 0};
202220  
202221      sessionAppendStr(&buf, "SELECT * FROM ", &rc);
202222      sessionAppendIdent(&buf, zDb, &rc);
202223      sessionAppendStr(&buf, ".", &rc);
202224      sessionAppendIdent(&buf, zTab, &rc);
202225      sessionAppendStr(&buf, " WHERE ", &rc);
202226      for(i=0; i<nCol; i++){
202227        if( abPK[i] ){
202228          sessionAppendStr(&buf, zSep, &rc);
202229          sessionAppendIdent(&buf, azCol[i], &rc);
202230          sessionAppendStr(&buf, " IS ?", &rc);
202231          sessionAppendInteger(&buf, i+1, &rc);
202232          zSep = " AND ";
202233        }
202234      }
202235      zSql = (char*)buf.aBuf;
202236      nSql = buf.nBuf;
202237    }
202238  
202239    if( rc==SQLITE_OK ){
202240      rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
202241    }
202242    sqlite3_free(zSql);
202243    return rc;
202244  }
202245  
202246  /*
202247  ** Bind the PRIMARY KEY values from the change passed in argument pChange
202248  ** to the SELECT statement passed as the first argument. The SELECT statement
202249  ** is as prepared by function sessionSelectStmt().
202250  **
202251  ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
202252  ** error code (e.g. SQLITE_NOMEM) otherwise.
202253  */
202254  static int sessionSelectBind(
202255    sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
202256    int nCol,                       /* Number of columns in table */
202257    u8 *abPK,                       /* PRIMARY KEY array */
202258    SessionChange *pChange          /* Change structure */
202259  ){
202260    int i;
202261    int rc = SQLITE_OK;
202262    u8 *a = pChange->aRecord;
202263  
202264    for(i=0; i<nCol && rc==SQLITE_OK; i++){
202265      int eType = *a++;
202266  
202267      switch( eType ){
202268        case 0:
202269        case SQLITE_NULL:
202270          assert( abPK[i]==0 );
202271          break;
202272  
202273        case SQLITE_INTEGER: {
202274          if( abPK[i] ){
202275            i64 iVal = sessionGetI64(a);
202276            rc = sqlite3_bind_int64(pSelect, i+1, iVal);
202277          }
202278          a += 8;
202279          break;
202280        }
202281  
202282        case SQLITE_FLOAT: {
202283          if( abPK[i] ){
202284            double rVal;
202285            i64 iVal = sessionGetI64(a);
202286            memcpy(&rVal, &iVal, 8);
202287            rc = sqlite3_bind_double(pSelect, i+1, rVal);
202288          }
202289          a += 8;
202290          break;
202291        }
202292  
202293        case SQLITE_TEXT: {
202294          int n;
202295          a += sessionVarintGet(a, &n);
202296          if( abPK[i] ){
202297            rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
202298          }
202299          a += n;
202300          break;
202301        }
202302  
202303        default: {
202304          int n;
202305          assert( eType==SQLITE_BLOB );
202306          a += sessionVarintGet(a, &n);
202307          if( abPK[i] ){
202308            rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
202309          }
202310          a += n;
202311          break;
202312        }
202313      }
202314    }
202315  
202316    return rc;
202317  }
202318  
202319  /*
202320  ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
202321  ** is called. Otherwise, append a serialized table header (part of the binary 
202322  ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
202323  ** SQLite error code before returning.
202324  */
202325  static void sessionAppendTableHdr(
202326    SessionBuffer *pBuf,            /* Append header to this buffer */
202327    int bPatchset,                  /* Use the patchset format if true */
202328    SessionTable *pTab,             /* Table object to append header for */
202329    int *pRc                        /* IN/OUT: Error code */
202330  ){
202331    /* Write a table header */
202332    sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
202333    sessionAppendVarint(pBuf, pTab->nCol, pRc);
202334    sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
202335    sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
202336  }
202337  
202338  /*
202339  ** Generate either a changeset (if argument bPatchset is zero) or a patchset
202340  ** (if it is non-zero) based on the current contents of the session object
202341  ** passed as the first argument.
202342  **
202343  ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
202344  ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
202345  ** occurs, an SQLite error code is returned and both output variables set 
202346  ** to 0.
202347  */
202348  static int sessionGenerateChangeset(
202349    sqlite3_session *pSession,      /* Session object */
202350    int bPatchset,                  /* True for patchset, false for changeset */
202351    int (*xOutput)(void *pOut, const void *pData, int nData),
202352    void *pOut,                     /* First argument for xOutput */
202353    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
202354    void **ppChangeset              /* OUT: Buffer containing changeset */
202355  ){
202356    sqlite3 *db = pSession->db;     /* Source database handle */
202357    SessionTable *pTab;             /* Used to iterate through attached tables */
202358    SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
202359    int rc;                         /* Return code */
202360  
202361    assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
202362  
202363    /* Zero the output variables in case an error occurs. If this session
202364    ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
202365    ** this call will be a no-op.  */
202366    if( xOutput==0 ){
202367      *pnChangeset = 0;
202368      *ppChangeset = 0;
202369    }
202370  
202371    if( pSession->rc ) return pSession->rc;
202372    rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
202373    if( rc!=SQLITE_OK ) return rc;
202374  
202375    sqlite3_mutex_enter(sqlite3_db_mutex(db));
202376  
202377    for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
202378      if( pTab->nEntry ){
202379        const char *zName = pTab->zName;
202380        int nCol;                   /* Number of columns in table */
202381        u8 *abPK;                   /* Primary key array */
202382        const char **azCol = 0;     /* Table columns */
202383        int i;                      /* Used to iterate through hash buckets */
202384        sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
202385        int nRewind = buf.nBuf;     /* Initial size of write buffer */
202386        int nNoop;                  /* Size of buffer after writing tbl header */
202387  
202388        /* Check the table schema is still Ok. */
202389        rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
202390        if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
202391          rc = SQLITE_SCHEMA;
202392        }
202393  
202394        /* Write a table header */
202395        sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
202396  
202397        /* Build and compile a statement to execute: */
202398        if( rc==SQLITE_OK ){
202399          rc = sessionSelectStmt(
202400              db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
202401        }
202402  
202403        nNoop = buf.nBuf;
202404        for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
202405          SessionChange *p;         /* Used to iterate through changes */
202406  
202407          for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
202408            rc = sessionSelectBind(pSel, nCol, abPK, p);
202409            if( rc!=SQLITE_OK ) continue;
202410            if( sqlite3_step(pSel)==SQLITE_ROW ){
202411              if( p->op==SQLITE_INSERT ){
202412                int iCol;
202413                sessionAppendByte(&buf, SQLITE_INSERT, &rc);
202414                sessionAppendByte(&buf, p->bIndirect, &rc);
202415                for(iCol=0; iCol<nCol; iCol++){
202416                  sessionAppendCol(&buf, pSel, iCol, &rc);
202417                }
202418              }else{
202419                rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
202420              }
202421            }else if( p->op!=SQLITE_INSERT ){
202422              rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
202423            }
202424            if( rc==SQLITE_OK ){
202425              rc = sqlite3_reset(pSel);
202426            }
202427  
202428            /* If the buffer is now larger than sessions_strm_chunk_size, pass
202429            ** its contents to the xOutput() callback. */
202430            if( xOutput 
202431             && rc==SQLITE_OK 
202432             && buf.nBuf>nNoop 
202433             && buf.nBuf>sessions_strm_chunk_size 
202434            ){
202435              rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
202436              nNoop = -1;
202437              buf.nBuf = 0;
202438            }
202439  
202440          }
202441        }
202442  
202443        sqlite3_finalize(pSel);
202444        if( buf.nBuf==nNoop ){
202445          buf.nBuf = nRewind;
202446        }
202447        sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
202448      }
202449    }
202450  
202451    if( rc==SQLITE_OK ){
202452      if( xOutput==0 ){
202453        *pnChangeset = buf.nBuf;
202454        *ppChangeset = buf.aBuf;
202455        buf.aBuf = 0;
202456      }else if( buf.nBuf>0 ){
202457        rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
202458      }
202459    }
202460  
202461    sqlite3_free(buf.aBuf);
202462    sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
202463    sqlite3_mutex_leave(sqlite3_db_mutex(db));
202464    return rc;
202465  }
202466  
202467  /*
202468  ** Obtain a changeset object containing all changes recorded by the 
202469  ** session object passed as the first argument.
202470  **
202471  ** It is the responsibility of the caller to eventually free the buffer 
202472  ** using sqlite3_free().
202473  */
202474  SQLITE_API int sqlite3session_changeset(
202475    sqlite3_session *pSession,      /* Session object */
202476    int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
202477    void **ppChangeset              /* OUT: Buffer containing changeset */
202478  ){
202479    return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
202480  }
202481  
202482  /*
202483  ** Streaming version of sqlite3session_changeset().
202484  */
202485  SQLITE_API int sqlite3session_changeset_strm(
202486    sqlite3_session *pSession,
202487    int (*xOutput)(void *pOut, const void *pData, int nData),
202488    void *pOut
202489  ){
202490    return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
202491  }
202492  
202493  /*
202494  ** Streaming version of sqlite3session_patchset().
202495  */
202496  SQLITE_API int sqlite3session_patchset_strm(
202497    sqlite3_session *pSession,
202498    int (*xOutput)(void *pOut, const void *pData, int nData),
202499    void *pOut
202500  ){
202501    return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
202502  }
202503  
202504  /*
202505  ** Obtain a patchset object containing all changes recorded by the 
202506  ** session object passed as the first argument.
202507  **
202508  ** It is the responsibility of the caller to eventually free the buffer 
202509  ** using sqlite3_free().
202510  */
202511  SQLITE_API int sqlite3session_patchset(
202512    sqlite3_session *pSession,      /* Session object */
202513    int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
202514    void **ppPatchset               /* OUT: Buffer containing changeset */
202515  ){
202516    return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
202517  }
202518  
202519  /*
202520  ** Enable or disable the session object passed as the first argument.
202521  */
202522  SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
202523    int ret;
202524    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
202525    if( bEnable>=0 ){
202526      pSession->bEnable = bEnable;
202527    }
202528    ret = pSession->bEnable;
202529    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
202530    return ret;
202531  }
202532  
202533  /*
202534  ** Enable or disable the session object passed as the first argument.
202535  */
202536  SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
202537    int ret;
202538    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
202539    if( bIndirect>=0 ){
202540      pSession->bIndirect = bIndirect;
202541    }
202542    ret = pSession->bIndirect;
202543    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
202544    return ret;
202545  }
202546  
202547  /*
202548  ** Return true if there have been no changes to monitored tables recorded
202549  ** by the session object passed as the only argument.
202550  */
202551  SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
202552    int ret = 0;
202553    SessionTable *pTab;
202554  
202555    sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
202556    for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
202557      ret = (pTab->nEntry>0);
202558    }
202559    sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
202560  
202561    return (ret==0);
202562  }
202563  
202564  /*
202565  ** Do the work for either sqlite3changeset_start() or start_strm().
202566  */
202567  static int sessionChangesetStart(
202568    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
202569    int (*xInput)(void *pIn, void *pData, int *pnData),
202570    void *pIn,
202571    int nChangeset,                 /* Size of buffer pChangeset in bytes */
202572    void *pChangeset,               /* Pointer to buffer containing changeset */
202573    int bInvert                     /* True to invert changeset */
202574  ){
202575    sqlite3_changeset_iter *pRet;   /* Iterator to return */
202576    int nByte;                      /* Number of bytes to allocate for iterator */
202577  
202578    assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
202579  
202580    /* Zero the output variable in case an error occurs. */
202581    *pp = 0;
202582  
202583    /* Allocate and initialize the iterator structure. */
202584    nByte = sizeof(sqlite3_changeset_iter);
202585    pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
202586    if( !pRet ) return SQLITE_NOMEM;
202587    memset(pRet, 0, sizeof(sqlite3_changeset_iter));
202588    pRet->in.aData = (u8 *)pChangeset;
202589    pRet->in.nData = nChangeset;
202590    pRet->in.xInput = xInput;
202591    pRet->in.pIn = pIn;
202592    pRet->in.bEof = (xInput ? 0 : 1);
202593    pRet->bInvert = bInvert;
202594  
202595    /* Populate the output variable and return success. */
202596    *pp = pRet;
202597    return SQLITE_OK;
202598  }
202599  
202600  /*
202601  ** Create an iterator used to iterate through the contents of a changeset.
202602  */
202603  SQLITE_API int sqlite3changeset_start(
202604    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
202605    int nChangeset,                 /* Size of buffer pChangeset in bytes */
202606    void *pChangeset                /* Pointer to buffer containing changeset */
202607  ){
202608    return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
202609  }
202610  SQLITE_API int sqlite3changeset_start_v2(
202611    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
202612    int nChangeset,                 /* Size of buffer pChangeset in bytes */
202613    void *pChangeset,               /* Pointer to buffer containing changeset */
202614    int flags
202615  ){
202616    int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
202617    return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
202618  }
202619  
202620  /*
202621  ** Streaming version of sqlite3changeset_start().
202622  */
202623  SQLITE_API int sqlite3changeset_start_strm(
202624    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
202625    int (*xInput)(void *pIn, void *pData, int *pnData),
202626    void *pIn
202627  ){
202628    return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
202629  }
202630  SQLITE_API int sqlite3changeset_start_v2_strm(
202631    sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
202632    int (*xInput)(void *pIn, void *pData, int *pnData),
202633    void *pIn,
202634    int flags
202635  ){
202636    int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
202637    return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
202638  }
202639  
202640  /*
202641  ** If the SessionInput object passed as the only argument is a streaming
202642  ** object and the buffer is full, discard some data to free up space.
202643  */
202644  static void sessionDiscardData(SessionInput *pIn){
202645    if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
202646      int nMove = pIn->buf.nBuf - pIn->iNext;
202647      assert( nMove>=0 );
202648      if( nMove>0 ){
202649        memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
202650      }
202651      pIn->buf.nBuf -= pIn->iNext;
202652      pIn->iNext = 0;
202653      pIn->nData = pIn->buf.nBuf;
202654    }
202655  }
202656  
202657  /*
202658  ** Ensure that there are at least nByte bytes available in the buffer. Or,
202659  ** if there are not nByte bytes remaining in the input, that all available
202660  ** data is in the buffer.
202661  **
202662  ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
202663  */
202664  static int sessionInputBuffer(SessionInput *pIn, int nByte){
202665    int rc = SQLITE_OK;
202666    if( pIn->xInput ){
202667      while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
202668        int nNew = sessions_strm_chunk_size;
202669  
202670        if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
202671        if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
202672          rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
202673          if( nNew==0 ){
202674            pIn->bEof = 1;
202675          }else{
202676            pIn->buf.nBuf += nNew;
202677          }
202678        }
202679  
202680        pIn->aData = pIn->buf.aBuf;
202681        pIn->nData = pIn->buf.nBuf;
202682      }
202683    }
202684    return rc;
202685  }
202686  
202687  /*
202688  ** When this function is called, *ppRec points to the start of a record
202689  ** that contains nCol values. This function advances the pointer *ppRec
202690  ** until it points to the byte immediately following that record.
202691  */
202692  static void sessionSkipRecord(
202693    u8 **ppRec,                     /* IN/OUT: Record pointer */
202694    int nCol                        /* Number of values in record */
202695  ){
202696    u8 *aRec = *ppRec;
202697    int i;
202698    for(i=0; i<nCol; i++){
202699      int eType = *aRec++;
202700      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
202701        int nByte;
202702        aRec += sessionVarintGet((u8*)aRec, &nByte);
202703        aRec += nByte;
202704      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
202705        aRec += 8;
202706      }
202707    }
202708  
202709    *ppRec = aRec;
202710  }
202711  
202712  /*
202713  ** This function sets the value of the sqlite3_value object passed as the
202714  ** first argument to a copy of the string or blob held in the aData[] 
202715  ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
202716  ** error occurs.
202717  */
202718  static int sessionValueSetStr(
202719    sqlite3_value *pVal,            /* Set the value of this object */
202720    u8 *aData,                      /* Buffer containing string or blob data */
202721    int nData,                      /* Size of buffer aData[] in bytes */
202722    u8 enc                          /* String encoding (0 for blobs) */
202723  ){
202724    /* In theory this code could just pass SQLITE_TRANSIENT as the final
202725    ** argument to sqlite3ValueSetStr() and have the copy created 
202726    ** automatically. But doing so makes it difficult to detect any OOM
202727    ** error. Hence the code to create the copy externally. */
202728    u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
202729    if( aCopy==0 ) return SQLITE_NOMEM;
202730    memcpy(aCopy, aData, nData);
202731    sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
202732    return SQLITE_OK;
202733  }
202734  
202735  /*
202736  ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
202737  ** for details.
202738  **
202739  ** When this function is called, *paChange points to the start of the record
202740  ** to deserialize. Assuming no error occurs, *paChange is set to point to
202741  ** one byte after the end of the same record before this function returns.
202742  ** If the argument abPK is NULL, then the record contains nCol values. Or,
202743  ** if abPK is other than NULL, then the record contains only the PK fields
202744  ** (in other words, it is a patchset DELETE record).
202745  **
202746  ** If successful, each element of the apOut[] array (allocated by the caller)
202747  ** is set to point to an sqlite3_value object containing the value read
202748  ** from the corresponding position in the record. If that value is not
202749  ** included in the record (i.e. because the record is part of an UPDATE change
202750  ** and the field was not modified), the corresponding element of apOut[] is
202751  ** set to NULL.
202752  **
202753  ** It is the responsibility of the caller to free all sqlite_value structures
202754  ** using sqlite3_free().
202755  **
202756  ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
202757  ** The apOut[] array may have been partially populated in this case.
202758  */
202759  static int sessionReadRecord(
202760    SessionInput *pIn,              /* Input data */
202761    int nCol,                       /* Number of values in record */
202762    u8 *abPK,                       /* Array of primary key flags, or NULL */
202763    sqlite3_value **apOut           /* Write values to this array */
202764  ){
202765    int i;                          /* Used to iterate through columns */
202766    int rc = SQLITE_OK;
202767  
202768    for(i=0; i<nCol && rc==SQLITE_OK; i++){
202769      int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
202770      if( abPK && abPK[i]==0 ) continue;
202771      rc = sessionInputBuffer(pIn, 9);
202772      if( rc==SQLITE_OK ){
202773        if( pIn->iNext>=pIn->nData ){
202774          rc = SQLITE_CORRUPT_BKPT;
202775        }else{
202776          eType = pIn->aData[pIn->iNext++];
202777          assert( apOut[i]==0 );
202778          if( eType ){
202779            apOut[i] = sqlite3ValueNew(0);
202780            if( !apOut[i] ) rc = SQLITE_NOMEM;
202781          }
202782        }
202783      }
202784  
202785      if( rc==SQLITE_OK ){
202786        u8 *aVal = &pIn->aData[pIn->iNext];
202787        if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
202788          int nByte;
202789          pIn->iNext += sessionVarintGet(aVal, &nByte);
202790          rc = sessionInputBuffer(pIn, nByte);
202791          if( rc==SQLITE_OK ){
202792            if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
202793              rc = SQLITE_CORRUPT_BKPT;
202794            }else{
202795              u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
202796              rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
202797              pIn->iNext += nByte;
202798            }
202799          }
202800        }
202801        if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
202802          sqlite3_int64 v = sessionGetI64(aVal);
202803          if( eType==SQLITE_INTEGER ){
202804            sqlite3VdbeMemSetInt64(apOut[i], v);
202805          }else{
202806            double d;
202807            memcpy(&d, &v, 8);
202808            sqlite3VdbeMemSetDouble(apOut[i], d);
202809          }
202810          pIn->iNext += 8;
202811        }
202812      }
202813    }
202814  
202815    return rc;
202816  }
202817  
202818  /*
202819  ** The input pointer currently points to the second byte of a table-header.
202820  ** Specifically, to the following:
202821  **
202822  **   + number of columns in table (varint)
202823  **   + array of PK flags (1 byte per column),
202824  **   + table name (nul terminated).
202825  **
202826  ** This function ensures that all of the above is present in the input 
202827  ** buffer (i.e. that it can be accessed without any calls to xInput()).
202828  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
202829  ** The input pointer is not moved.
202830  */
202831  static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
202832    int rc = SQLITE_OK;
202833    int nCol = 0;
202834    int nRead = 0;
202835  
202836    rc = sessionInputBuffer(pIn, 9);
202837    if( rc==SQLITE_OK ){
202838      nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
202839      /* The hard upper limit for the number of columns in an SQLite
202840      ** database table is, according to sqliteLimit.h, 32676. So 
202841      ** consider any table-header that purports to have more than 65536 
202842      ** columns to be corrupt. This is convenient because otherwise, 
202843      ** if the (nCol>65536) condition below were omitted, a sufficiently 
202844      ** large value for nCol may cause nRead to wrap around and become 
202845      ** negative. Leading to a crash. */
202846      if( nCol<0 || nCol>65536 ){
202847        rc = SQLITE_CORRUPT_BKPT;
202848      }else{
202849        rc = sessionInputBuffer(pIn, nRead+nCol+100);
202850        nRead += nCol;
202851      }
202852    }
202853  
202854    while( rc==SQLITE_OK ){
202855      while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
202856        nRead++;
202857      }
202858      if( (pIn->iNext + nRead)<pIn->nData ) break;
202859      rc = sessionInputBuffer(pIn, nRead + 100);
202860    }
202861    *pnByte = nRead+1;
202862    return rc;
202863  }
202864  
202865  /*
202866  ** The input pointer currently points to the first byte of the first field
202867  ** of a record consisting of nCol columns. This function ensures the entire
202868  ** record is buffered. It does not move the input pointer.
202869  **
202870  ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
202871  ** the record in bytes. Otherwise, an SQLite error code is returned. The
202872  ** final value of *pnByte is undefined in this case.
202873  */
202874  static int sessionChangesetBufferRecord(
202875    SessionInput *pIn,              /* Input data */
202876    int nCol,                       /* Number of columns in record */
202877    int *pnByte                     /* OUT: Size of record in bytes */
202878  ){
202879    int rc = SQLITE_OK;
202880    int nByte = 0;
202881    int i;
202882    for(i=0; rc==SQLITE_OK && i<nCol; i++){
202883      int eType;
202884      rc = sessionInputBuffer(pIn, nByte + 10);
202885      if( rc==SQLITE_OK ){
202886        eType = pIn->aData[pIn->iNext + nByte++];
202887        if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
202888          int n;
202889          nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
202890          nByte += n;
202891          rc = sessionInputBuffer(pIn, nByte);
202892        }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
202893          nByte += 8;
202894        }
202895      }
202896    }
202897    *pnByte = nByte;
202898    return rc;
202899  }
202900  
202901  /*
202902  ** The input pointer currently points to the second byte of a table-header.
202903  ** Specifically, to the following:
202904  **
202905  **   + number of columns in table (varint)
202906  **   + array of PK flags (1 byte per column),
202907  **   + table name (nul terminated).
202908  **
202909  ** This function decodes the table-header and populates the p->nCol, 
202910  ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is 
202911  ** also allocated or resized according to the new value of p->nCol. The
202912  ** input pointer is left pointing to the byte following the table header.
202913  **
202914  ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
202915  ** is returned and the final values of the various fields enumerated above
202916  ** are undefined.
202917  */
202918  static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
202919    int rc;
202920    int nCopy;
202921    assert( p->rc==SQLITE_OK );
202922  
202923    rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
202924    if( rc==SQLITE_OK ){
202925      int nByte;
202926      int nVarint;
202927      nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
202928      if( p->nCol>0 ){
202929        nCopy -= nVarint;
202930        p->in.iNext += nVarint;
202931        nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
202932        p->tblhdr.nBuf = 0;
202933        sessionBufferGrow(&p->tblhdr, nByte, &rc);
202934      }else{
202935        rc = SQLITE_CORRUPT_BKPT;
202936      }
202937    }
202938  
202939    if( rc==SQLITE_OK ){
202940      int iPK = sizeof(sqlite3_value*)*p->nCol*2;
202941      memset(p->tblhdr.aBuf, 0, iPK);
202942      memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
202943      p->in.iNext += nCopy;
202944    }
202945  
202946    p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
202947    p->abPK = (u8*)&p->apValue[p->nCol*2];
202948    p->zTab = (char*)&p->abPK[p->nCol];
202949    return (p->rc = rc);
202950  }
202951  
202952  /*
202953  ** Advance the changeset iterator to the next change.
202954  **
202955  ** If both paRec and pnRec are NULL, then this function works like the public
202956  ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
202957  ** sqlite3changeset_new() and old() APIs may be used to query for values.
202958  **
202959  ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
202960  ** record is written to *paRec before returning and the number of bytes in
202961  ** the record to *pnRec.
202962  **
202963  ** Either way, this function returns SQLITE_ROW if the iterator is 
202964  ** successfully advanced to the next change in the changeset, an SQLite 
202965  ** error code if an error occurs, or SQLITE_DONE if there are no further 
202966  ** changes in the changeset.
202967  */
202968  static int sessionChangesetNext(
202969    sqlite3_changeset_iter *p,      /* Changeset iterator */
202970    u8 **paRec,                     /* If non-NULL, store record pointer here */
202971    int *pnRec,                     /* If non-NULL, store size of record here */
202972    int *pbNew                      /* If non-NULL, true if new table */
202973  ){
202974    int i;
202975    u8 op;
202976  
202977    assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
202978  
202979    /* If the iterator is in the error-state, return immediately. */
202980    if( p->rc!=SQLITE_OK ) return p->rc;
202981  
202982    /* Free the current contents of p->apValue[], if any. */
202983    if( p->apValue ){
202984      for(i=0; i<p->nCol*2; i++){
202985        sqlite3ValueFree(p->apValue[i]);
202986      }
202987      memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
202988    }
202989  
202990    /* Make sure the buffer contains at least 10 bytes of input data, or all
202991    ** remaining data if there are less than 10 bytes available. This is
202992    ** sufficient either for the 'T' or 'P' byte and the varint that follows
202993    ** it, or for the two single byte values otherwise. */
202994    p->rc = sessionInputBuffer(&p->in, 2);
202995    if( p->rc!=SQLITE_OK ) return p->rc;
202996  
202997    /* If the iterator is already at the end of the changeset, return DONE. */
202998    if( p->in.iNext>=p->in.nData ){
202999      return SQLITE_DONE;
203000    }
203001  
203002    sessionDiscardData(&p->in);
203003    p->in.iCurrent = p->in.iNext;
203004  
203005    op = p->in.aData[p->in.iNext++];
203006    while( op=='T' || op=='P' ){
203007      if( pbNew ) *pbNew = 1;
203008      p->bPatchset = (op=='P');
203009      if( sessionChangesetReadTblhdr(p) ) return p->rc;
203010      if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
203011      p->in.iCurrent = p->in.iNext;
203012      if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
203013      op = p->in.aData[p->in.iNext++];
203014    }
203015  
203016    if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
203017      /* The first record in the changeset is not a table header. Must be a
203018      ** corrupt changeset. */
203019      assert( p->in.iNext==1 || p->zTab );
203020      return (p->rc = SQLITE_CORRUPT_BKPT);
203021    }
203022  
203023    p->op = op;
203024    p->bIndirect = p->in.aData[p->in.iNext++];
203025    if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
203026      return (p->rc = SQLITE_CORRUPT_BKPT);
203027    }
203028  
203029    if( paRec ){ 
203030      int nVal;                     /* Number of values to buffer */
203031      if( p->bPatchset==0 && op==SQLITE_UPDATE ){
203032        nVal = p->nCol * 2;
203033      }else if( p->bPatchset && op==SQLITE_DELETE ){
203034        nVal = 0;
203035        for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
203036      }else{
203037        nVal = p->nCol;
203038      }
203039      p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
203040      if( p->rc!=SQLITE_OK ) return p->rc;
203041      *paRec = &p->in.aData[p->in.iNext];
203042      p->in.iNext += *pnRec;
203043    }else{
203044      sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
203045      sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
203046  
203047      /* If this is an UPDATE or DELETE, read the old.* record. */
203048      if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
203049        u8 *abPK = p->bPatchset ? p->abPK : 0;
203050        p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
203051        if( p->rc!=SQLITE_OK ) return p->rc;
203052      }
203053  
203054      /* If this is an INSERT or UPDATE, read the new.* record. */
203055      if( p->op!=SQLITE_DELETE ){
203056        p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
203057        if( p->rc!=SQLITE_OK ) return p->rc;
203058      }
203059  
203060      if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
203061        /* If this is an UPDATE that is part of a patchset, then all PK and
203062        ** modified fields are present in the new.* record. The old.* record
203063        ** is currently completely empty. This block shifts the PK fields from
203064        ** new.* to old.*, to accommodate the code that reads these arrays.  */
203065        for(i=0; i<p->nCol; i++){
203066          assert( p->bPatchset==0 || p->apValue[i]==0 );
203067          if( p->abPK[i] ){
203068            assert( p->apValue[i]==0 );
203069            p->apValue[i] = p->apValue[i+p->nCol];
203070            if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
203071            p->apValue[i+p->nCol] = 0;
203072          }
203073        }
203074      }else if( p->bInvert ){
203075        if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
203076        else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
203077      }
203078    }
203079  
203080    return SQLITE_ROW;
203081  }
203082  
203083  /*
203084  ** Advance an iterator created by sqlite3changeset_start() to the next
203085  ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
203086  ** or SQLITE_CORRUPT.
203087  **
203088  ** This function may not be called on iterators passed to a conflict handler
203089  ** callback by changeset_apply().
203090  */
203091  SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
203092    return sessionChangesetNext(p, 0, 0, 0);
203093  }
203094  
203095  /*
203096  ** The following function extracts information on the current change
203097  ** from a changeset iterator. It may only be called after changeset_next()
203098  ** has returned SQLITE_ROW.
203099  */
203100  SQLITE_API int sqlite3changeset_op(
203101    sqlite3_changeset_iter *pIter,  /* Iterator handle */
203102    const char **pzTab,             /* OUT: Pointer to table name */
203103    int *pnCol,                     /* OUT: Number of columns in table */
203104    int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
203105    int *pbIndirect                 /* OUT: True if change is indirect */
203106  ){
203107    *pOp = pIter->op;
203108    *pnCol = pIter->nCol;
203109    *pzTab = pIter->zTab;
203110    if( pbIndirect ) *pbIndirect = pIter->bIndirect;
203111    return SQLITE_OK;
203112  }
203113  
203114  /*
203115  ** Return information regarding the PRIMARY KEY and number of columns in
203116  ** the database table affected by the change that pIter currently points
203117  ** to. This function may only be called after changeset_next() returns
203118  ** SQLITE_ROW.
203119  */
203120  SQLITE_API int sqlite3changeset_pk(
203121    sqlite3_changeset_iter *pIter,  /* Iterator object */
203122    unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
203123    int *pnCol                      /* OUT: Number of entries in output array */
203124  ){
203125    *pabPK = pIter->abPK;
203126    if( pnCol ) *pnCol = pIter->nCol;
203127    return SQLITE_OK;
203128  }
203129  
203130  /*
203131  ** This function may only be called while the iterator is pointing to an
203132  ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
203133  ** Otherwise, SQLITE_MISUSE is returned.
203134  **
203135  ** It sets *ppValue to point to an sqlite3_value structure containing the
203136  ** iVal'th value in the old.* record. Or, if that particular value is not
203137  ** included in the record (because the change is an UPDATE and the field
203138  ** was not modified and is not a PK column), set *ppValue to NULL.
203139  **
203140  ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
203141  ** not modified. Otherwise, SQLITE_OK.
203142  */
203143  SQLITE_API int sqlite3changeset_old(
203144    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203145    int iVal,                       /* Index of old.* value to retrieve */
203146    sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
203147  ){
203148    if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
203149      return SQLITE_MISUSE;
203150    }
203151    if( iVal<0 || iVal>=pIter->nCol ){
203152      return SQLITE_RANGE;
203153    }
203154    *ppValue = pIter->apValue[iVal];
203155    return SQLITE_OK;
203156  }
203157  
203158  /*
203159  ** This function may only be called while the iterator is pointing to an
203160  ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
203161  ** Otherwise, SQLITE_MISUSE is returned.
203162  **
203163  ** It sets *ppValue to point to an sqlite3_value structure containing the
203164  ** iVal'th value in the new.* record. Or, if that particular value is not
203165  ** included in the record (because the change is an UPDATE and the field
203166  ** was not modified), set *ppValue to NULL.
203167  **
203168  ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
203169  ** not modified. Otherwise, SQLITE_OK.
203170  */
203171  SQLITE_API int sqlite3changeset_new(
203172    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203173    int iVal,                       /* Index of new.* value to retrieve */
203174    sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
203175  ){
203176    if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
203177      return SQLITE_MISUSE;
203178    }
203179    if( iVal<0 || iVal>=pIter->nCol ){
203180      return SQLITE_RANGE;
203181    }
203182    *ppValue = pIter->apValue[pIter->nCol+iVal];
203183    return SQLITE_OK;
203184  }
203185  
203186  /*
203187  ** The following two macros are used internally. They are similar to the
203188  ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
203189  ** they omit all error checking and return a pointer to the requested value.
203190  */
203191  #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
203192  #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
203193  
203194  /*
203195  ** This function may only be called with a changeset iterator that has been
203196  ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT 
203197  ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
203198  **
203199  ** If successful, *ppValue is set to point to an sqlite3_value structure
203200  ** containing the iVal'th value of the conflicting record.
203201  **
203202  ** If value iVal is out-of-range or some other error occurs, an SQLite error
203203  ** code is returned. Otherwise, SQLITE_OK.
203204  */
203205  SQLITE_API int sqlite3changeset_conflict(
203206    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203207    int iVal,                       /* Index of conflict record value to fetch */
203208    sqlite3_value **ppValue         /* OUT: Value from conflicting row */
203209  ){
203210    if( !pIter->pConflict ){
203211      return SQLITE_MISUSE;
203212    }
203213    if( iVal<0 || iVal>=pIter->nCol ){
203214      return SQLITE_RANGE;
203215    }
203216    *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
203217    return SQLITE_OK;
203218  }
203219  
203220  /*
203221  ** This function may only be called with an iterator passed to an
203222  ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
203223  ** it sets the output variable to the total number of known foreign key
203224  ** violations in the destination database and returns SQLITE_OK.
203225  **
203226  ** In all other cases this function returns SQLITE_MISUSE.
203227  */
203228  SQLITE_API int sqlite3changeset_fk_conflicts(
203229    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203230    int *pnOut                      /* OUT: Number of FK violations */
203231  ){
203232    if( pIter->pConflict || pIter->apValue ){
203233      return SQLITE_MISUSE;
203234    }
203235    *pnOut = pIter->nCol;
203236    return SQLITE_OK;
203237  }
203238  
203239  
203240  /*
203241  ** Finalize an iterator allocated with sqlite3changeset_start().
203242  **
203243  ** This function may not be called on iterators passed to a conflict handler
203244  ** callback by changeset_apply().
203245  */
203246  SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
203247    int rc = SQLITE_OK;
203248    if( p ){
203249      int i;                        /* Used to iterate through p->apValue[] */
203250      rc = p->rc;
203251      if( p->apValue ){
203252        for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
203253      }
203254      sqlite3_free(p->tblhdr.aBuf);
203255      sqlite3_free(p->in.buf.aBuf);
203256      sqlite3_free(p);
203257    }
203258    return rc;
203259  }
203260  
203261  static int sessionChangesetInvert(
203262    SessionInput *pInput,           /* Input changeset */
203263    int (*xOutput)(void *pOut, const void *pData, int nData),
203264    void *pOut,
203265    int *pnInverted,                /* OUT: Number of bytes in output changeset */
203266    void **ppInverted               /* OUT: Inverse of pChangeset */
203267  ){
203268    int rc = SQLITE_OK;             /* Return value */
203269    SessionBuffer sOut;             /* Output buffer */
203270    int nCol = 0;                   /* Number of cols in current table */
203271    u8 *abPK = 0;                   /* PK array for current table */
203272    sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
203273    SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
203274  
203275    /* Initialize the output buffer */
203276    memset(&sOut, 0, sizeof(SessionBuffer));
203277  
203278    /* Zero the output variables in case an error occurs. */
203279    if( ppInverted ){
203280      *ppInverted = 0;
203281      *pnInverted = 0;
203282    }
203283  
203284    while( 1 ){
203285      u8 eType;
203286  
203287      /* Test for EOF. */
203288      if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
203289      if( pInput->iNext>=pInput->nData ) break;
203290      eType = pInput->aData[pInput->iNext];
203291  
203292      switch( eType ){
203293        case 'T': {
203294          /* A 'table' record consists of:
203295          **
203296          **   * A constant 'T' character,
203297          **   * Number of columns in said table (a varint),
203298          **   * An array of nCol bytes (sPK),
203299          **   * A nul-terminated table name.
203300          */
203301          int nByte;
203302          int nVar;
203303          pInput->iNext++;
203304          if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
203305            goto finished_invert;
203306          }
203307          nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
203308          sPK.nBuf = 0;
203309          sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
203310          sessionAppendByte(&sOut, eType, &rc);
203311          sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
203312          if( rc ) goto finished_invert;
203313  
203314          pInput->iNext += nByte;
203315          sqlite3_free(apVal);
203316          apVal = 0;
203317          abPK = sPK.aBuf;
203318          break;
203319        }
203320  
203321        case SQLITE_INSERT:
203322        case SQLITE_DELETE: {
203323          int nByte;
203324          int bIndirect = pInput->aData[pInput->iNext+1];
203325          int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
203326          pInput->iNext += 2;
203327          assert( rc==SQLITE_OK );
203328          rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
203329          sessionAppendByte(&sOut, eType2, &rc);
203330          sessionAppendByte(&sOut, bIndirect, &rc);
203331          sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
203332          pInput->iNext += nByte;
203333          if( rc ) goto finished_invert;
203334          break;
203335        }
203336  
203337        case SQLITE_UPDATE: {
203338          int iCol;
203339  
203340          if( 0==apVal ){
203341            apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
203342            if( 0==apVal ){
203343              rc = SQLITE_NOMEM;
203344              goto finished_invert;
203345            }
203346            memset(apVal, 0, sizeof(apVal[0])*nCol*2);
203347          }
203348  
203349          /* Write the header for the new UPDATE change. Same as the original. */
203350          sessionAppendByte(&sOut, eType, &rc);
203351          sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
203352  
203353          /* Read the old.* and new.* records for the update change. */
203354          pInput->iNext += 2;
203355          rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
203356          if( rc==SQLITE_OK ){
203357            rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
203358          }
203359  
203360          /* Write the new old.* record. Consists of the PK columns from the
203361          ** original old.* record, and the other values from the original
203362          ** new.* record. */
203363          for(iCol=0; iCol<nCol; iCol++){
203364            sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
203365            sessionAppendValue(&sOut, pVal, &rc);
203366          }
203367  
203368          /* Write the new new.* record. Consists of a copy of all values
203369          ** from the original old.* record, except for the PK columns, which
203370          ** are set to "undefined". */
203371          for(iCol=0; iCol<nCol; iCol++){
203372            sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
203373            sessionAppendValue(&sOut, pVal, &rc);
203374          }
203375  
203376          for(iCol=0; iCol<nCol*2; iCol++){
203377            sqlite3ValueFree(apVal[iCol]);
203378          }
203379          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
203380          if( rc!=SQLITE_OK ){
203381            goto finished_invert;
203382          }
203383  
203384          break;
203385        }
203386  
203387        default:
203388          rc = SQLITE_CORRUPT_BKPT;
203389          goto finished_invert;
203390      }
203391  
203392      assert( rc==SQLITE_OK );
203393      if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
203394        rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
203395        sOut.nBuf = 0;
203396        if( rc!=SQLITE_OK ) goto finished_invert;
203397      }
203398    }
203399  
203400    assert( rc==SQLITE_OK );
203401    if( pnInverted ){
203402      *pnInverted = sOut.nBuf;
203403      *ppInverted = sOut.aBuf;
203404      sOut.aBuf = 0;
203405    }else if( sOut.nBuf>0 ){
203406      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
203407    }
203408  
203409   finished_invert:
203410    sqlite3_free(sOut.aBuf);
203411    sqlite3_free(apVal);
203412    sqlite3_free(sPK.aBuf);
203413    return rc;
203414  }
203415  
203416  
203417  /*
203418  ** Invert a changeset object.
203419  */
203420  SQLITE_API int sqlite3changeset_invert(
203421    int nChangeset,                 /* Number of bytes in input */
203422    const void *pChangeset,         /* Input changeset */
203423    int *pnInverted,                /* OUT: Number of bytes in output changeset */
203424    void **ppInverted               /* OUT: Inverse of pChangeset */
203425  ){
203426    SessionInput sInput;
203427  
203428    /* Set up the input stream */
203429    memset(&sInput, 0, sizeof(SessionInput));
203430    sInput.nData = nChangeset;
203431    sInput.aData = (u8*)pChangeset;
203432  
203433    return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
203434  }
203435  
203436  /*
203437  ** Streaming version of sqlite3changeset_invert().
203438  */
203439  SQLITE_API int sqlite3changeset_invert_strm(
203440    int (*xInput)(void *pIn, void *pData, int *pnData),
203441    void *pIn,
203442    int (*xOutput)(void *pOut, const void *pData, int nData),
203443    void *pOut
203444  ){
203445    SessionInput sInput;
203446    int rc;
203447  
203448    /* Set up the input stream */
203449    memset(&sInput, 0, sizeof(SessionInput));
203450    sInput.xInput = xInput;
203451    sInput.pIn = pIn;
203452  
203453    rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
203454    sqlite3_free(sInput.buf.aBuf);
203455    return rc;
203456  }
203457  
203458  typedef struct SessionApplyCtx SessionApplyCtx;
203459  struct SessionApplyCtx {
203460    sqlite3 *db;
203461    sqlite3_stmt *pDelete;          /* DELETE statement */
203462    sqlite3_stmt *pUpdate;          /* UPDATE statement */
203463    sqlite3_stmt *pInsert;          /* INSERT statement */
203464    sqlite3_stmt *pSelect;          /* SELECT statement */
203465    int nCol;                       /* Size of azCol[] and abPK[] arrays */
203466    const char **azCol;             /* Array of column names */
203467    u8 *abPK;                       /* Boolean array - true if column is in PK */
203468    int bStat1;                     /* True if table is sqlite_stat1 */
203469    int bDeferConstraints;          /* True to defer constraints */
203470    SessionBuffer constraints;      /* Deferred constraints are stored here */
203471    SessionBuffer rebase;           /* Rebase information (if any) here */
203472    u8 bRebaseStarted;              /* If table header is already in rebase */
203473    u8 bRebase;                     /* True to collect rebase information */
203474  };
203475  
203476  /*
203477  ** Formulate a statement to DELETE a row from database db. Assuming a table
203478  ** structure like this:
203479  **
203480  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
203481  **
203482  ** The DELETE statement looks like this:
203483  **
203484  **     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
203485  **
203486  ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
203487  ** matching b and d values, or 1 otherwise. The second case comes up if the
203488  ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
203489  **
203490  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
203491  ** pointing to the prepared version of the SQL statement.
203492  */
203493  static int sessionDeleteRow(
203494    sqlite3 *db,                    /* Database handle */
203495    const char *zTab,               /* Table name */
203496    SessionApplyCtx *p              /* Session changeset-apply context */
203497  ){
203498    int i;
203499    const char *zSep = "";
203500    int rc = SQLITE_OK;
203501    SessionBuffer buf = {0, 0, 0};
203502    int nPk = 0;
203503  
203504    sessionAppendStr(&buf, "DELETE FROM ", &rc);
203505    sessionAppendIdent(&buf, zTab, &rc);
203506    sessionAppendStr(&buf, " WHERE ", &rc);
203507  
203508    for(i=0; i<p->nCol; i++){
203509      if( p->abPK[i] ){
203510        nPk++;
203511        sessionAppendStr(&buf, zSep, &rc);
203512        sessionAppendIdent(&buf, p->azCol[i], &rc);
203513        sessionAppendStr(&buf, " = ?", &rc);
203514        sessionAppendInteger(&buf, i+1, &rc);
203515        zSep = " AND ";
203516      }
203517    }
203518  
203519    if( nPk<p->nCol ){
203520      sessionAppendStr(&buf, " AND (?", &rc);
203521      sessionAppendInteger(&buf, p->nCol+1, &rc);
203522      sessionAppendStr(&buf, " OR ", &rc);
203523  
203524      zSep = "";
203525      for(i=0; i<p->nCol; i++){
203526        if( !p->abPK[i] ){
203527          sessionAppendStr(&buf, zSep, &rc);
203528          sessionAppendIdent(&buf, p->azCol[i], &rc);
203529          sessionAppendStr(&buf, " IS ?", &rc);
203530          sessionAppendInteger(&buf, i+1, &rc);
203531          zSep = "AND ";
203532        }
203533      }
203534      sessionAppendStr(&buf, ")", &rc);
203535    }
203536  
203537    if( rc==SQLITE_OK ){
203538      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
203539    }
203540    sqlite3_free(buf.aBuf);
203541  
203542    return rc;
203543  }
203544  
203545  /*
203546  ** Formulate and prepare a statement to UPDATE a row from database db. 
203547  ** Assuming a table structure like this:
203548  **
203549  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
203550  **
203551  ** The UPDATE statement looks like this:
203552  **
203553  **     UPDATE x SET
203554  **     a = CASE WHEN ?2  THEN ?3  ELSE a END,
203555  **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
203556  **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
203557  **     d = CASE WHEN ?11 THEN ?12 ELSE d END
203558  **     WHERE a = ?1 AND c = ?7 AND (?13 OR 
203559  **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
203560  **     )
203561  **
203562  ** For each column in the table, there are three variables to bind:
203563  **
203564  **     ?(i*3+1)    The old.* value of the column, if any.
203565  **     ?(i*3+2)    A boolean flag indicating that the value is being modified.
203566  **     ?(i*3+3)    The new.* value of the column, if any.
203567  **
203568  ** Also, a boolean flag that, if set to true, causes the statement to update
203569  ** a row even if the non-PK values do not match. This is required if the
203570  ** conflict-handler is invoked with CHANGESET_DATA and returns
203571  ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
203572  **
203573  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
203574  ** pointing to the prepared version of the SQL statement.
203575  */
203576  static int sessionUpdateRow(
203577    sqlite3 *db,                    /* Database handle */
203578    const char *zTab,               /* Table name */
203579    SessionApplyCtx *p              /* Session changeset-apply context */
203580  ){
203581    int rc = SQLITE_OK;
203582    int i;
203583    const char *zSep = "";
203584    SessionBuffer buf = {0, 0, 0};
203585  
203586    /* Append "UPDATE tbl SET " */
203587    sessionAppendStr(&buf, "UPDATE ", &rc);
203588    sessionAppendIdent(&buf, zTab, &rc);
203589    sessionAppendStr(&buf, " SET ", &rc);
203590  
203591    /* Append the assignments */
203592    for(i=0; i<p->nCol; i++){
203593      sessionAppendStr(&buf, zSep, &rc);
203594      sessionAppendIdent(&buf, p->azCol[i], &rc);
203595      sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
203596      sessionAppendInteger(&buf, i*3+2, &rc);
203597      sessionAppendStr(&buf, " THEN ?", &rc);
203598      sessionAppendInteger(&buf, i*3+3, &rc);
203599      sessionAppendStr(&buf, " ELSE ", &rc);
203600      sessionAppendIdent(&buf, p->azCol[i], &rc);
203601      sessionAppendStr(&buf, " END", &rc);
203602      zSep = ", ";
203603    }
203604  
203605    /* Append the PK part of the WHERE clause */
203606    sessionAppendStr(&buf, " WHERE ", &rc);
203607    for(i=0; i<p->nCol; i++){
203608      if( p->abPK[i] ){
203609        sessionAppendIdent(&buf, p->azCol[i], &rc);
203610        sessionAppendStr(&buf, " = ?", &rc);
203611        sessionAppendInteger(&buf, i*3+1, &rc);
203612        sessionAppendStr(&buf, " AND ", &rc);
203613      }
203614    }
203615  
203616    /* Append the non-PK part of the WHERE clause */
203617    sessionAppendStr(&buf, " (?", &rc);
203618    sessionAppendInteger(&buf, p->nCol*3+1, &rc);
203619    sessionAppendStr(&buf, " OR 1", &rc);
203620    for(i=0; i<p->nCol; i++){
203621      if( !p->abPK[i] ){
203622        sessionAppendStr(&buf, " AND (?", &rc);
203623        sessionAppendInteger(&buf, i*3+2, &rc);
203624        sessionAppendStr(&buf, "=0 OR ", &rc);
203625        sessionAppendIdent(&buf, p->azCol[i], &rc);
203626        sessionAppendStr(&buf, " IS ?", &rc);
203627        sessionAppendInteger(&buf, i*3+1, &rc);
203628        sessionAppendStr(&buf, ")", &rc);
203629      }
203630    }
203631    sessionAppendStr(&buf, ")", &rc);
203632  
203633    if( rc==SQLITE_OK ){
203634      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
203635    }
203636    sqlite3_free(buf.aBuf);
203637  
203638    return rc;
203639  }
203640  
203641  
203642  /*
203643  ** Formulate and prepare an SQL statement to query table zTab by primary
203644  ** key. Assuming the following table structure:
203645  **
203646  **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
203647  **
203648  ** The SELECT statement looks like this:
203649  **
203650  **     SELECT * FROM x WHERE a = ?1 AND c = ?3
203651  **
203652  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
203653  ** pointing to the prepared version of the SQL statement.
203654  */
203655  static int sessionSelectRow(
203656    sqlite3 *db,                    /* Database handle */
203657    const char *zTab,               /* Table name */
203658    SessionApplyCtx *p              /* Session changeset-apply context */
203659  ){
203660    return sessionSelectStmt(
203661        db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
203662  }
203663  
203664  /*
203665  ** Formulate and prepare an INSERT statement to add a record to table zTab.
203666  ** For example:
203667  **
203668  **     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
203669  **
203670  ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
203671  ** pointing to the prepared version of the SQL statement.
203672  */
203673  static int sessionInsertRow(
203674    sqlite3 *db,                    /* Database handle */
203675    const char *zTab,               /* Table name */
203676    SessionApplyCtx *p              /* Session changeset-apply context */
203677  ){
203678    int rc = SQLITE_OK;
203679    int i;
203680    SessionBuffer buf = {0, 0, 0};
203681  
203682    sessionAppendStr(&buf, "INSERT INTO main.", &rc);
203683    sessionAppendIdent(&buf, zTab, &rc);
203684    sessionAppendStr(&buf, "(", &rc);
203685    for(i=0; i<p->nCol; i++){
203686      if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
203687      sessionAppendIdent(&buf, p->azCol[i], &rc);
203688    }
203689  
203690    sessionAppendStr(&buf, ") VALUES(?", &rc);
203691    for(i=1; i<p->nCol; i++){
203692      sessionAppendStr(&buf, ", ?", &rc);
203693    }
203694    sessionAppendStr(&buf, ")", &rc);
203695  
203696    if( rc==SQLITE_OK ){
203697      rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
203698    }
203699    sqlite3_free(buf.aBuf);
203700    return rc;
203701  }
203702  
203703  static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
203704    return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
203705  }
203706  
203707  /*
203708  ** Prepare statements for applying changes to the sqlite_stat1 table.
203709  ** These are similar to those created by sessionSelectRow(),
203710  ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for 
203711  ** other tables.
203712  */
203713  static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
203714    int rc = sessionSelectRow(db, "sqlite_stat1", p);
203715    if( rc==SQLITE_OK ){
203716      rc = sessionPrepare(db, &p->pInsert,
203717          "INSERT INTO main.sqlite_stat1 VALUES(?1, "
203718          "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
203719          "?3)"
203720      );
203721    }
203722    if( rc==SQLITE_OK ){
203723      rc = sessionPrepare(db, &p->pUpdate,
203724          "UPDATE main.sqlite_stat1 SET "
203725          "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
203726          "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
203727          "stat = CASE WHEN ?8 THEN ?9 ELSE stat END  "
203728          "WHERE tbl=?1 AND idx IS "
203729          "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
203730          "AND (?10 OR ?8=0 OR stat IS ?7)"
203731      );
203732    }
203733    if( rc==SQLITE_OK ){
203734      rc = sessionPrepare(db, &p->pDelete,
203735          "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
203736          "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
203737          "AND (?4 OR stat IS ?3)"
203738      );
203739    }
203740    return rc;
203741  }
203742  
203743  /*
203744  ** A wrapper around sqlite3_bind_value() that detects an extra problem. 
203745  ** See comments in the body of this function for details.
203746  */
203747  static int sessionBindValue(
203748    sqlite3_stmt *pStmt,            /* Statement to bind value to */
203749    int i,                          /* Parameter number to bind to */
203750    sqlite3_value *pVal             /* Value to bind */
203751  ){
203752    int eType = sqlite3_value_type(pVal);
203753    /* COVERAGE: The (pVal->z==0) branch is never true using current versions
203754    ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
203755    ** the (pVal->z) variable remains as it was or the type of the value is
203756    ** set to SQLITE_NULL.  */
203757    if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
203758      /* This condition occurs when an earlier OOM in a call to
203759      ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
203760      ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
203761      return SQLITE_NOMEM;
203762    }
203763    return sqlite3_bind_value(pStmt, i, pVal);
203764  }
203765  
203766  /*
203767  ** Iterator pIter must point to an SQLITE_INSERT entry. This function 
203768  ** transfers new.* values from the current iterator entry to statement
203769  ** pStmt. The table being inserted into has nCol columns.
203770  **
203771  ** New.* value $i from the iterator is bound to variable ($i+1) of 
203772  ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
203773  ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
203774  ** to an array nCol elements in size. In this case only those values for 
203775  ** which abPK[$i] is true are read from the iterator and bound to the 
203776  ** statement.
203777  **
203778  ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
203779  */
203780  static int sessionBindRow(
203781    sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
203782    int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
203783    int nCol,                       /* Number of columns */
203784    u8 *abPK,                       /* If not NULL, bind only if true */
203785    sqlite3_stmt *pStmt             /* Bind values to this statement */
203786  ){
203787    int i;
203788    int rc = SQLITE_OK;
203789  
203790    /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
203791    ** argument iterator points to a suitable entry. Make sure that xValue 
203792    ** is one of these to guarantee that it is safe to ignore the return 
203793    ** in the code below. */
203794    assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
203795  
203796    for(i=0; rc==SQLITE_OK && i<nCol; i++){
203797      if( !abPK || abPK[i] ){
203798        sqlite3_value *pVal;
203799        (void)xValue(pIter, i, &pVal);
203800        if( pVal==0 ){
203801          /* The value in the changeset was "undefined". This indicates a
203802          ** corrupt changeset blob.  */
203803          rc = SQLITE_CORRUPT_BKPT;
203804        }else{
203805          rc = sessionBindValue(pStmt, i+1, pVal);
203806        }
203807      }
203808    }
203809    return rc;
203810  }
203811  
203812  /*
203813  ** SQL statement pSelect is as generated by the sessionSelectRow() function.
203814  ** This function binds the primary key values from the change that changeset
203815  ** iterator pIter points to to the SELECT and attempts to seek to the table
203816  ** entry. If a row is found, the SELECT statement left pointing at the row 
203817  ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
203818  ** has occured, the statement is reset and SQLITE_OK is returned. If an
203819  ** error occurs, the statement is reset and an SQLite error code is returned.
203820  **
203821  ** If this function returns SQLITE_ROW, the caller must eventually reset() 
203822  ** statement pSelect. If any other value is returned, the statement does
203823  ** not require a reset().
203824  **
203825  ** If the iterator currently points to an INSERT record, bind values from the
203826  ** new.* record to the SELECT statement. Or, if it points to a DELETE or
203827  ** UPDATE, bind values from the old.* record. 
203828  */
203829  static int sessionSeekToRow(
203830    sqlite3 *db,                    /* Database handle */
203831    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203832    u8 *abPK,                       /* Primary key flags array */
203833    sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
203834  ){
203835    int rc;                         /* Return code */
203836    int nCol;                       /* Number of columns in table */
203837    int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
203838    const char *zDummy;             /* Unused */
203839  
203840    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
203841    rc = sessionBindRow(pIter, 
203842        op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
203843        nCol, abPK, pSelect
203844    );
203845  
203846    if( rc==SQLITE_OK ){
203847      rc = sqlite3_step(pSelect);
203848      if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
203849    }
203850  
203851    return rc;
203852  }
203853  
203854  /*
203855  ** This function is called from within sqlite3changset_apply_v2() when
203856  ** a conflict is encountered and resolved using conflict resolution
203857  ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
203858  ** It adds a conflict resolution record to the buffer in 
203859  ** SessionApplyCtx.rebase, which will eventually be returned to the caller
203860  ** of apply_v2() as the "rebase" buffer.
203861  **
203862  ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
203863  */
203864  static int sessionRebaseAdd(
203865    SessionApplyCtx *p,             /* Apply context */
203866    int eType,                      /* Conflict resolution (OMIT or REPLACE) */
203867    sqlite3_changeset_iter *pIter   /* Iterator pointing at current change */
203868  ){
203869    int rc = SQLITE_OK;
203870    if( p->bRebase ){
203871      int i;
203872      int eOp = pIter->op;
203873      if( p->bRebaseStarted==0 ){
203874        /* Append a table-header to the rebase buffer */
203875        const char *zTab = pIter->zTab;
203876        sessionAppendByte(&p->rebase, 'T', &rc);
203877        sessionAppendVarint(&p->rebase, p->nCol, &rc);
203878        sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
203879        sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
203880        p->bRebaseStarted = 1;
203881      }
203882  
203883      assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
203884      assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
203885  
203886      sessionAppendByte(&p->rebase, 
203887          (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
203888          );
203889      sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
203890      for(i=0; i<p->nCol; i++){
203891        sqlite3_value *pVal = 0;
203892        if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
203893          sqlite3changeset_old(pIter, i, &pVal);
203894        }else{
203895          sqlite3changeset_new(pIter, i, &pVal);
203896        }
203897        sessionAppendValue(&p->rebase, pVal, &rc);
203898      }
203899    }
203900    return rc;
203901  }
203902  
203903  /*
203904  ** Invoke the conflict handler for the change that the changeset iterator
203905  ** currently points to.
203906  **
203907  ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
203908  ** If argument pbReplace is NULL, then the type of conflict handler invoked
203909  ** depends solely on eType, as follows:
203910  **
203911  **    eType value                 Value passed to xConflict
203912  **    -------------------------------------------------
203913  **    CHANGESET_DATA              CHANGESET_NOTFOUND
203914  **    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
203915  **
203916  ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
203917  ** record with the same primary key as the record about to be deleted, updated
203918  ** or inserted. If such a record can be found, it is available to the conflict
203919  ** handler as the "conflicting" record. In this case the type of conflict
203920  ** handler invoked is as follows:
203921  **
203922  **    eType value         PK Record found?   Value passed to xConflict
203923  **    ----------------------------------------------------------------
203924  **    CHANGESET_DATA      Yes                CHANGESET_DATA
203925  **    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
203926  **    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
203927  **    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
203928  **
203929  ** If pbReplace is not NULL, and a record with a matching PK is found, and
203930  ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
203931  ** is set to non-zero before returning SQLITE_OK.
203932  **
203933  ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
203934  ** returned. Or, if the conflict handler returns an invalid value, 
203935  ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
203936  ** this function returns SQLITE_OK.
203937  */
203938  static int sessionConflictHandler(
203939    int eType,                      /* Either CHANGESET_DATA or CONFLICT */
203940    SessionApplyCtx *p,             /* changeset_apply() context */
203941    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
203942    int(*xConflict)(void *, int, sqlite3_changeset_iter*),
203943    void *pCtx,                     /* First argument for conflict handler */
203944    int *pbReplace                  /* OUT: Set to true if PK row is found */
203945  ){
203946    int res = 0;                    /* Value returned by conflict handler */
203947    int rc;
203948    int nCol;
203949    int op;
203950    const char *zDummy;
203951  
203952    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
203953  
203954    assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
203955    assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
203956    assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
203957  
203958    /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
203959    if( pbReplace ){
203960      rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
203961    }else{
203962      rc = SQLITE_OK;
203963    }
203964  
203965    if( rc==SQLITE_ROW ){
203966      /* There exists another row with the new.* primary key. */
203967      pIter->pConflict = p->pSelect;
203968      res = xConflict(pCtx, eType, pIter);
203969      pIter->pConflict = 0;
203970      rc = sqlite3_reset(p->pSelect);
203971    }else if( rc==SQLITE_OK ){
203972      if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
203973        /* Instead of invoking the conflict handler, append the change blob
203974        ** to the SessionApplyCtx.constraints buffer. */
203975        u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
203976        int nBlob = pIter->in.iNext - pIter->in.iCurrent;
203977        sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
203978        return SQLITE_OK;
203979      }else{
203980        /* No other row with the new.* primary key. */
203981        res = xConflict(pCtx, eType+1, pIter);
203982        if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
203983      }
203984    }
203985  
203986    if( rc==SQLITE_OK ){
203987      switch( res ){
203988        case SQLITE_CHANGESET_REPLACE:
203989          assert( pbReplace );
203990          *pbReplace = 1;
203991          break;
203992  
203993        case SQLITE_CHANGESET_OMIT:
203994          break;
203995  
203996        case SQLITE_CHANGESET_ABORT:
203997          rc = SQLITE_ABORT;
203998          break;
203999  
204000        default:
204001          rc = SQLITE_MISUSE;
204002          break;
204003      }
204004      if( rc==SQLITE_OK ){
204005        rc = sessionRebaseAdd(p, res, pIter);
204006      }
204007    }
204008  
204009    return rc;
204010  }
204011  
204012  /*
204013  ** Attempt to apply the change that the iterator passed as the first argument
204014  ** currently points to to the database. If a conflict is encountered, invoke
204015  ** the conflict handler callback.
204016  **
204017  ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
204018  ** one is encountered, update or delete the row with the matching primary key
204019  ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
204020  ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
204021  ** to true before returning. In this case the caller will invoke this function
204022  ** again, this time with pbRetry set to NULL.
204023  **
204024  ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is 
204025  ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
204026  ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
204027  ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
204028  ** before retrying. In this case the caller attempts to remove the conflicting
204029  ** row before invoking this function again, this time with pbReplace set 
204030  ** to NULL.
204031  **
204032  ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
204033  ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is 
204034  ** returned.
204035  */
204036  static int sessionApplyOneOp(
204037    sqlite3_changeset_iter *pIter,  /* Changeset iterator */
204038    SessionApplyCtx *p,             /* changeset_apply() context */
204039    int(*xConflict)(void *, int, sqlite3_changeset_iter *),
204040    void *pCtx,                     /* First argument for the conflict handler */
204041    int *pbReplace,                 /* OUT: True to remove PK row and retry */
204042    int *pbRetry                    /* OUT: True to retry. */
204043  ){
204044    const char *zDummy;
204045    int op;
204046    int nCol;
204047    int rc = SQLITE_OK;
204048  
204049    assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
204050    assert( p->azCol && p->abPK );
204051    assert( !pbReplace || *pbReplace==0 );
204052  
204053    sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
204054  
204055    if( op==SQLITE_DELETE ){
204056  
204057      /* Bind values to the DELETE statement. If conflict handling is required,
204058      ** bind values for all columns and set bound variable (nCol+1) to true.
204059      ** Or, if conflict handling is not required, bind just the PK column
204060      ** values and, if it exists, set (nCol+1) to false. Conflict handling
204061      ** is not required if:
204062      **
204063      **   * this is a patchset, or
204064      **   * (pbRetry==0), or
204065      **   * all columns of the table are PK columns (in this case there is
204066      **     no (nCol+1) variable to bind to).
204067      */
204068      u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
204069      rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
204070      if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
204071        rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
204072      }
204073      if( rc!=SQLITE_OK ) return rc;
204074  
204075      sqlite3_step(p->pDelete);
204076      rc = sqlite3_reset(p->pDelete);
204077      if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
204078        rc = sessionConflictHandler(
204079            SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
204080        );
204081      }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
204082        rc = sessionConflictHandler(
204083            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
204084        );
204085      }
204086  
204087    }else if( op==SQLITE_UPDATE ){
204088      int i;
204089  
204090      /* Bind values to the UPDATE statement. */
204091      for(i=0; rc==SQLITE_OK && i<nCol; i++){
204092        sqlite3_value *pOld = sessionChangesetOld(pIter, i);
204093        sqlite3_value *pNew = sessionChangesetNew(pIter, i);
204094  
204095        sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
204096        if( pOld ){
204097          rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
204098        }
204099        if( rc==SQLITE_OK && pNew ){
204100          rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
204101        }
204102      }
204103      if( rc==SQLITE_OK ){
204104        sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
204105      }
204106      if( rc!=SQLITE_OK ) return rc;
204107  
204108      /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
204109      ** the result will be SQLITE_OK with 0 rows modified. */
204110      sqlite3_step(p->pUpdate);
204111      rc = sqlite3_reset(p->pUpdate);
204112  
204113      if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
204114        /* A NOTFOUND or DATA error. Search the table to see if it contains
204115        ** a row with a matching primary key. If so, this is a DATA conflict.
204116        ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
204117  
204118        rc = sessionConflictHandler(
204119            SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
204120        );
204121  
204122      }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
204123        /* This is always a CONSTRAINT conflict. */
204124        rc = sessionConflictHandler(
204125            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
204126        );
204127      }
204128  
204129    }else{
204130      assert( op==SQLITE_INSERT );
204131      if( p->bStat1 ){
204132        /* Check if there is a conflicting row. For sqlite_stat1, this needs
204133        ** to be done using a SELECT, as there is no PRIMARY KEY in the 
204134        ** database schema to throw an exception if a duplicate is inserted.  */
204135        rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
204136        if( rc==SQLITE_ROW ){
204137          rc = SQLITE_CONSTRAINT;
204138          sqlite3_reset(p->pSelect);
204139        }
204140      }
204141  
204142      if( rc==SQLITE_OK ){
204143        rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
204144        if( rc!=SQLITE_OK ) return rc;
204145  
204146        sqlite3_step(p->pInsert);
204147        rc = sqlite3_reset(p->pInsert);
204148      }
204149  
204150      if( (rc&0xff)==SQLITE_CONSTRAINT ){
204151        rc = sessionConflictHandler(
204152            SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
204153        );
204154      }
204155    }
204156  
204157    return rc;
204158  }
204159  
204160  /*
204161  ** Attempt to apply the change that the iterator passed as the first argument
204162  ** currently points to to the database. If a conflict is encountered, invoke
204163  ** the conflict handler callback.
204164  **
204165  ** The difference between this function and sessionApplyOne() is that this
204166  ** function handles the case where the conflict-handler is invoked and 
204167  ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
204168  ** retried in some manner.
204169  */
204170  static int sessionApplyOneWithRetry(
204171    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204172    sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
204173    SessionApplyCtx *pApply,        /* Apply context */
204174    int(*xConflict)(void*, int, sqlite3_changeset_iter*),
204175    void *pCtx                      /* First argument passed to xConflict */
204176  ){
204177    int bReplace = 0;
204178    int bRetry = 0;
204179    int rc;
204180  
204181    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
204182    if( rc==SQLITE_OK ){
204183      /* If the bRetry flag is set, the change has not been applied due to an
204184      ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
204185      ** a row with the correct PK is present in the db, but one or more other
204186      ** fields do not contain the expected values) and the conflict handler 
204187      ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
204188      ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
204189      ** the SQLITE_CHANGESET_DATA problem.  */
204190      if( bRetry ){
204191        assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
204192        rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
204193      }
204194  
204195      /* If the bReplace flag is set, the change is an INSERT that has not
204196      ** been performed because the database already contains a row with the
204197      ** specified primary key and the conflict handler returned
204198      ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
204199      ** before reattempting the INSERT.  */
204200      else if( bReplace ){
204201        assert( pIter->op==SQLITE_INSERT );
204202        rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
204203        if( rc==SQLITE_OK ){
204204          rc = sessionBindRow(pIter, 
204205              sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
204206          sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
204207        }
204208        if( rc==SQLITE_OK ){
204209          sqlite3_step(pApply->pDelete);
204210          rc = sqlite3_reset(pApply->pDelete);
204211        }
204212        if( rc==SQLITE_OK ){
204213          rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
204214        }
204215        if( rc==SQLITE_OK ){
204216          rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
204217        }
204218      }
204219    }
204220  
204221    return rc;
204222  }
204223  
204224  /*
204225  ** Retry the changes accumulated in the pApply->constraints buffer.
204226  */
204227  static int sessionRetryConstraints(
204228    sqlite3 *db, 
204229    int bPatchset,
204230    const char *zTab,
204231    SessionApplyCtx *pApply,
204232    int(*xConflict)(void*, int, sqlite3_changeset_iter*),
204233    void *pCtx                      /* First argument passed to xConflict */
204234  ){
204235    int rc = SQLITE_OK;
204236  
204237    while( pApply->constraints.nBuf ){
204238      sqlite3_changeset_iter *pIter2 = 0;
204239      SessionBuffer cons = pApply->constraints;
204240      memset(&pApply->constraints, 0, sizeof(SessionBuffer));
204241  
204242      rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
204243      if( rc==SQLITE_OK ){
204244        int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
204245        int rc2;
204246        pIter2->bPatchset = bPatchset;
204247        pIter2->zTab = (char*)zTab;
204248        pIter2->nCol = pApply->nCol;
204249        pIter2->abPK = pApply->abPK;
204250        sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
204251        pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
204252        if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
204253  
204254        while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
204255          rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
204256        }
204257  
204258        rc2 = sqlite3changeset_finalize(pIter2);
204259        if( rc==SQLITE_OK ) rc = rc2;
204260      }
204261      assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
204262  
204263      sqlite3_free(cons.aBuf);
204264      if( rc!=SQLITE_OK ) break;
204265      if( pApply->constraints.nBuf>=cons.nBuf ){
204266        /* No progress was made on the last round. */
204267        pApply->bDeferConstraints = 0;
204268      }
204269    }
204270  
204271    return rc;
204272  }
204273  
204274  /*
204275  ** Argument pIter is a changeset iterator that has been initialized, but
204276  ** not yet passed to sqlite3changeset_next(). This function applies the 
204277  ** changeset to the main database attached to handle "db". The supplied
204278  ** conflict handler callback is invoked to resolve any conflicts encountered
204279  ** while applying the change.
204280  */
204281  static int sessionChangesetApply(
204282    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204283    sqlite3_changeset_iter *pIter,  /* Changeset to apply */
204284    int(*xFilter)(
204285      void *pCtx,                   /* Copy of sixth arg to _apply() */
204286      const char *zTab              /* Table name */
204287    ),
204288    int(*xConflict)(
204289      void *pCtx,                   /* Copy of fifth arg to _apply() */
204290      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
204291      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
204292    ),
204293    void *pCtx,                     /* First argument passed to xConflict */
204294    void **ppRebase, int *pnRebase, /* OUT: Rebase information */
204295    int flags                       /* SESSION_APPLY_XXX flags */
204296  ){
204297    int schemaMismatch = 0;
204298    int rc = SQLITE_OK;             /* Return code */
204299    const char *zTab = 0;           /* Name of current table */
204300    int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
204301    SessionApplyCtx sApply;         /* changeset_apply() context object */
204302    int bPatchset;
204303  
204304    assert( xConflict!=0 );
204305  
204306    pIter->in.bNoDiscard = 1;
204307    memset(&sApply, 0, sizeof(sApply));
204308    sApply.bRebase = (ppRebase && pnRebase);
204309    sqlite3_mutex_enter(sqlite3_db_mutex(db));
204310    if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
204311      rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
204312    }
204313    if( rc==SQLITE_OK ){
204314      rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
204315    }
204316    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
204317      int nCol;
204318      int op;
204319      const char *zNew;
204320      
204321      sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
204322  
204323      if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
204324        u8 *abPK;
204325  
204326        rc = sessionRetryConstraints(
204327            db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
204328        );
204329        if( rc!=SQLITE_OK ) break;
204330  
204331        sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
204332        sqlite3_finalize(sApply.pDelete);
204333        sqlite3_finalize(sApply.pUpdate); 
204334        sqlite3_finalize(sApply.pInsert);
204335        sqlite3_finalize(sApply.pSelect);
204336        sApply.db = db;
204337        sApply.pDelete = 0;
204338        sApply.pUpdate = 0;
204339        sApply.pInsert = 0;
204340        sApply.pSelect = 0;
204341        sApply.nCol = 0;
204342        sApply.azCol = 0;
204343        sApply.abPK = 0;
204344        sApply.bStat1 = 0;
204345        sApply.bDeferConstraints = 1;
204346        sApply.bRebaseStarted = 0;
204347        memset(&sApply.constraints, 0, sizeof(SessionBuffer));
204348  
204349        /* If an xFilter() callback was specified, invoke it now. If the 
204350        ** xFilter callback returns zero, skip this table. If it returns
204351        ** non-zero, proceed. */
204352        schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
204353        if( schemaMismatch ){
204354          zTab = sqlite3_mprintf("%s", zNew);
204355          if( zTab==0 ){
204356            rc = SQLITE_NOMEM;
204357            break;
204358          }
204359          nTab = (int)strlen(zTab);
204360          sApply.azCol = (const char **)zTab;
204361        }else{
204362          int nMinCol = 0;
204363          int i;
204364  
204365          sqlite3changeset_pk(pIter, &abPK, 0);
204366          rc = sessionTableInfo(
204367              db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
204368          );
204369          if( rc!=SQLITE_OK ) break;
204370          for(i=0; i<sApply.nCol; i++){
204371            if( sApply.abPK[i] ) nMinCol = i+1;
204372          }
204373    
204374          if( sApply.nCol==0 ){
204375            schemaMismatch = 1;
204376            sqlite3_log(SQLITE_SCHEMA, 
204377                "sqlite3changeset_apply(): no such table: %s", zTab
204378            );
204379          }
204380          else if( sApply.nCol<nCol ){
204381            schemaMismatch = 1;
204382            sqlite3_log(SQLITE_SCHEMA, 
204383                "sqlite3changeset_apply(): table %s has %d columns, "
204384                "expected %d or more", 
204385                zTab, sApply.nCol, nCol
204386            );
204387          }
204388          else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
204389            schemaMismatch = 1;
204390            sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
204391                "primary key mismatch for table %s", zTab
204392            );
204393          }
204394          else{
204395            sApply.nCol = nCol;
204396            if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
204397              if( (rc = sessionStat1Sql(db, &sApply) ) ){
204398                break;
204399              }
204400              sApply.bStat1 = 1;
204401            }else{
204402              if((rc = sessionSelectRow(db, zTab, &sApply))
204403                  || (rc = sessionUpdateRow(db, zTab, &sApply))
204404                  || (rc = sessionDeleteRow(db, zTab, &sApply))
204405                  || (rc = sessionInsertRow(db, zTab, &sApply))
204406                ){
204407                break;
204408              }
204409              sApply.bStat1 = 0;
204410            }
204411          }
204412          nTab = sqlite3Strlen30(zTab);
204413        }
204414      }
204415  
204416      /* If there is a schema mismatch on the current table, proceed to the
204417      ** next change. A log message has already been issued. */
204418      if( schemaMismatch ) continue;
204419  
204420      rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
204421    }
204422  
204423    bPatchset = pIter->bPatchset;
204424    if( rc==SQLITE_OK ){
204425      rc = sqlite3changeset_finalize(pIter);
204426    }else{
204427      sqlite3changeset_finalize(pIter);
204428    }
204429  
204430    if( rc==SQLITE_OK ){
204431      rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
204432    }
204433  
204434    if( rc==SQLITE_OK ){
204435      int nFk, notUsed;
204436      sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
204437      if( nFk!=0 ){
204438        int res = SQLITE_CHANGESET_ABORT;
204439        sqlite3_changeset_iter sIter;
204440        memset(&sIter, 0, sizeof(sIter));
204441        sIter.nCol = nFk;
204442        res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
204443        if( res!=SQLITE_CHANGESET_OMIT ){
204444          rc = SQLITE_CONSTRAINT;
204445        }
204446      }
204447    }
204448    sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
204449  
204450    if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
204451      if( rc==SQLITE_OK ){
204452        rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
204453      }else{
204454        sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
204455        sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
204456      }
204457    }
204458  
204459    assert( sApply.bRebase || sApply.rebase.nBuf==0 );
204460    if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
204461      *ppRebase = (void*)sApply.rebase.aBuf;
204462      *pnRebase = sApply.rebase.nBuf;
204463      sApply.rebase.aBuf = 0;
204464    }
204465    sqlite3_finalize(sApply.pInsert);
204466    sqlite3_finalize(sApply.pDelete);
204467    sqlite3_finalize(sApply.pUpdate);
204468    sqlite3_finalize(sApply.pSelect);
204469    sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
204470    sqlite3_free((char*)sApply.constraints.aBuf);
204471    sqlite3_free((char*)sApply.rebase.aBuf);
204472    sqlite3_mutex_leave(sqlite3_db_mutex(db));
204473    return rc;
204474  }
204475  
204476  /*
204477  ** Apply the changeset passed via pChangeset/nChangeset to the main 
204478  ** database attached to handle "db".
204479  */
204480  SQLITE_API int sqlite3changeset_apply_v2(
204481    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204482    int nChangeset,                 /* Size of changeset in bytes */
204483    void *pChangeset,               /* Changeset blob */
204484    int(*xFilter)(
204485      void *pCtx,                   /* Copy of sixth arg to _apply() */
204486      const char *zTab              /* Table name */
204487    ),
204488    int(*xConflict)(
204489      void *pCtx,                   /* Copy of sixth arg to _apply() */
204490      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
204491      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
204492    ),
204493    void *pCtx,                     /* First argument passed to xConflict */
204494    void **ppRebase, int *pnRebase,
204495    int flags
204496  ){
204497    sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
204498    int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
204499    int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
204500    if( rc==SQLITE_OK ){
204501      rc = sessionChangesetApply(
204502          db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
204503      );
204504    }
204505    return rc;
204506  }
204507  
204508  /*
204509  ** Apply the changeset passed via pChangeset/nChangeset to the main database
204510  ** attached to handle "db". Invoke the supplied conflict handler callback
204511  ** to resolve any conflicts encountered while applying the change.
204512  */
204513  SQLITE_API int sqlite3changeset_apply(
204514    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204515    int nChangeset,                 /* Size of changeset in bytes */
204516    void *pChangeset,               /* Changeset blob */
204517    int(*xFilter)(
204518      void *pCtx,                   /* Copy of sixth arg to _apply() */
204519      const char *zTab              /* Table name */
204520    ),
204521    int(*xConflict)(
204522      void *pCtx,                   /* Copy of fifth arg to _apply() */
204523      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
204524      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
204525    ),
204526    void *pCtx                      /* First argument passed to xConflict */
204527  ){
204528    return sqlite3changeset_apply_v2(
204529        db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
204530    );
204531  }
204532  
204533  /*
204534  ** Apply the changeset passed via xInput/pIn to the main database
204535  ** attached to handle "db". Invoke the supplied conflict handler callback
204536  ** to resolve any conflicts encountered while applying the change.
204537  */
204538  SQLITE_API int sqlite3changeset_apply_v2_strm(
204539    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204540    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
204541    void *pIn,                                          /* First arg for xInput */
204542    int(*xFilter)(
204543      void *pCtx,                   /* Copy of sixth arg to _apply() */
204544      const char *zTab              /* Table name */
204545    ),
204546    int(*xConflict)(
204547      void *pCtx,                   /* Copy of sixth arg to _apply() */
204548      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
204549      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
204550    ),
204551    void *pCtx,                     /* First argument passed to xConflict */
204552    void **ppRebase, int *pnRebase,
204553    int flags
204554  ){
204555    sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
204556    int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
204557    int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
204558    if( rc==SQLITE_OK ){
204559      rc = sessionChangesetApply(
204560          db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
204561      );
204562    }
204563    return rc;
204564  }
204565  SQLITE_API int sqlite3changeset_apply_strm(
204566    sqlite3 *db,                    /* Apply change to "main" db of this handle */
204567    int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
204568    void *pIn,                                          /* First arg for xInput */
204569    int(*xFilter)(
204570      void *pCtx,                   /* Copy of sixth arg to _apply() */
204571      const char *zTab              /* Table name */
204572    ),
204573    int(*xConflict)(
204574      void *pCtx,                   /* Copy of sixth arg to _apply() */
204575      int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
204576      sqlite3_changeset_iter *p     /* Handle describing change and conflict */
204577    ),
204578    void *pCtx                      /* First argument passed to xConflict */
204579  ){
204580    return sqlite3changeset_apply_v2_strm(
204581        db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
204582    );
204583  }
204584  
204585  /*
204586  ** sqlite3_changegroup handle.
204587  */
204588  struct sqlite3_changegroup {
204589    int rc;                         /* Error code */
204590    int bPatch;                     /* True to accumulate patchsets */
204591    SessionTable *pList;            /* List of tables in current patch */
204592  };
204593  
204594  /*
204595  ** This function is called to merge two changes to the same row together as
204596  ** part of an sqlite3changeset_concat() operation. A new change object is
204597  ** allocated and a pointer to it stored in *ppNew.
204598  */
204599  static int sessionChangeMerge(
204600    SessionTable *pTab,             /* Table structure */
204601    int bRebase,                    /* True for a rebase hash-table */
204602    int bPatchset,                  /* True for patchsets */
204603    SessionChange *pExist,          /* Existing change */
204604    int op2,                        /* Second change operation */
204605    int bIndirect,                  /* True if second change is indirect */
204606    u8 *aRec,                       /* Second change record */
204607    int nRec,                       /* Number of bytes in aRec */
204608    SessionChange **ppNew           /* OUT: Merged change */
204609  ){
204610    SessionChange *pNew = 0;
204611    int rc = SQLITE_OK;
204612  
204613    if( !pExist ){
204614      pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
204615      if( !pNew ){
204616        return SQLITE_NOMEM;
204617      }
204618      memset(pNew, 0, sizeof(SessionChange));
204619      pNew->op = op2;
204620      pNew->bIndirect = bIndirect;
204621      pNew->aRecord = (u8*)&pNew[1];
204622      if( bIndirect==0 || bRebase==0 ){
204623        pNew->nRecord = nRec;
204624        memcpy(pNew->aRecord, aRec, nRec);
204625      }else{
204626        int i;
204627        u8 *pIn = aRec;
204628        u8 *pOut = pNew->aRecord;
204629        for(i=0; i<pTab->nCol; i++){
204630          int nIn = sessionSerialLen(pIn);
204631          if( *pIn==0 ){
204632            *pOut++ = 0;
204633          }else if( pTab->abPK[i]==0 ){
204634            *pOut++ = 0xFF;
204635          }else{
204636            memcpy(pOut, pIn, nIn);
204637            pOut += nIn;
204638          }
204639          pIn += nIn;
204640        }
204641        pNew->nRecord = pOut - pNew->aRecord;
204642      }
204643    }else if( bRebase ){
204644      if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
204645        *ppNew = pExist;
204646      }else{
204647        sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
204648        pNew = (SessionChange*)sqlite3_malloc64(nByte);
204649        if( pNew==0 ){
204650          rc = SQLITE_NOMEM;
204651        }else{
204652          int i;
204653          u8 *a1 = pExist->aRecord;
204654          u8 *a2 = aRec;
204655          u8 *pOut;
204656  
204657          memset(pNew, 0, nByte);
204658          pNew->bIndirect = bIndirect || pExist->bIndirect;
204659          pNew->op = op2;
204660          pOut = pNew->aRecord = (u8*)&pNew[1];
204661  
204662          for(i=0; i<pTab->nCol; i++){
204663            int n1 = sessionSerialLen(a1);
204664            int n2 = sessionSerialLen(a2);
204665            if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
204666              *pOut++ = 0xFF;
204667            }else if( *a2==0 ){
204668              memcpy(pOut, a1, n1);
204669              pOut += n1;
204670            }else{
204671              memcpy(pOut, a2, n2);
204672              pOut += n2;
204673            }
204674            a1 += n1;
204675            a2 += n2;
204676          }
204677          pNew->nRecord = pOut - pNew->aRecord;
204678        }
204679        sqlite3_free(pExist);
204680      }
204681    }else{
204682      int op1 = pExist->op;
204683  
204684      /* 
204685      **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
204686      **   op1=INSERT, op2=UPDATE      ->      INSERT.
204687      **   op1=INSERT, op2=DELETE      ->      (none)
204688      **
204689      **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
204690      **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
204691      **   op1=UPDATE, op2=DELETE      ->      DELETE.
204692      **
204693      **   op1=DELETE, op2=INSERT      ->      UPDATE.
204694      **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
204695      **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
204696      */   
204697      if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
204698       || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
204699       || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
204700       || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
204701      ){
204702        pNew = pExist;
204703      }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
204704        sqlite3_free(pExist);
204705        assert( pNew==0 );
204706      }else{
204707        u8 *aExist = pExist->aRecord;
204708        sqlite3_int64 nByte;
204709        u8 *aCsr;
204710  
204711        /* Allocate a new SessionChange object. Ensure that the aRecord[]
204712        ** buffer of the new object is large enough to hold any record that
204713        ** may be generated by combining the input records.  */
204714        nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
204715        pNew = (SessionChange *)sqlite3_malloc64(nByte);
204716        if( !pNew ){
204717          sqlite3_free(pExist);
204718          return SQLITE_NOMEM;
204719        }
204720        memset(pNew, 0, sizeof(SessionChange));
204721        pNew->bIndirect = (bIndirect && pExist->bIndirect);
204722        aCsr = pNew->aRecord = (u8 *)&pNew[1];
204723  
204724        if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
204725          u8 *a1 = aRec;
204726          assert( op2==SQLITE_UPDATE );
204727          pNew->op = SQLITE_INSERT;
204728          if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
204729          sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
204730        }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
204731          assert( op2==SQLITE_INSERT );
204732          pNew->op = SQLITE_UPDATE;
204733          if( bPatchset ){
204734            memcpy(aCsr, aRec, nRec);
204735            aCsr += nRec;
204736          }else{
204737            if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
204738              sqlite3_free(pNew);
204739              pNew = 0;
204740            }
204741          }
204742        }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
204743          u8 *a1 = aExist;
204744          u8 *a2 = aRec;
204745          assert( op1==SQLITE_UPDATE );
204746          if( bPatchset==0 ){
204747            sessionSkipRecord(&a1, pTab->nCol);
204748            sessionSkipRecord(&a2, pTab->nCol);
204749          }
204750          pNew->op = SQLITE_UPDATE;
204751          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
204752            sqlite3_free(pNew);
204753            pNew = 0;
204754          }
204755        }else{                                /* UPDATE + DELETE */
204756          assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
204757          pNew->op = SQLITE_DELETE;
204758          if( bPatchset ){
204759            memcpy(aCsr, aRec, nRec);
204760            aCsr += nRec;
204761          }else{
204762            sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
204763          }
204764        }
204765  
204766        if( pNew ){
204767          pNew->nRecord = (int)(aCsr - pNew->aRecord);
204768        }
204769        sqlite3_free(pExist);
204770      }
204771    }
204772  
204773    *ppNew = pNew;
204774    return rc;
204775  }
204776  
204777  /*
204778  ** Add all changes in the changeset traversed by the iterator passed as
204779  ** the first argument to the changegroup hash tables.
204780  */
204781  static int sessionChangesetToHash(
204782    sqlite3_changeset_iter *pIter,   /* Iterator to read from */
204783    sqlite3_changegroup *pGrp,       /* Changegroup object to add changeset to */
204784    int bRebase                      /* True if hash table is for rebasing */
204785  ){
204786    u8 *aRec;
204787    int nRec;
204788    int rc = SQLITE_OK;
204789    SessionTable *pTab = 0;
204790  
204791    while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
204792      const char *zNew;
204793      int nCol;
204794      int op;
204795      int iHash;
204796      int bIndirect;
204797      SessionChange *pChange;
204798      SessionChange *pExist = 0;
204799      SessionChange **pp;
204800  
204801      if( pGrp->pList==0 ){
204802        pGrp->bPatch = pIter->bPatchset;
204803      }else if( pIter->bPatchset!=pGrp->bPatch ){
204804        rc = SQLITE_ERROR;
204805        break;
204806      }
204807  
204808      sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
204809      if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
204810        /* Search the list for a matching table */
204811        int nNew = (int)strlen(zNew);
204812        u8 *abPK;
204813  
204814        sqlite3changeset_pk(pIter, &abPK, 0);
204815        for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
204816          if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
204817        }
204818        if( !pTab ){
204819          SessionTable **ppTab;
204820  
204821          pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
204822          if( !pTab ){
204823            rc = SQLITE_NOMEM;
204824            break;
204825          }
204826          memset(pTab, 0, sizeof(SessionTable));
204827          pTab->nCol = nCol;
204828          pTab->abPK = (u8*)&pTab[1];
204829          memcpy(pTab->abPK, abPK, nCol);
204830          pTab->zName = (char*)&pTab->abPK[nCol];
204831          memcpy(pTab->zName, zNew, nNew+1);
204832  
204833          /* The new object must be linked on to the end of the list, not
204834          ** simply added to the start of it. This is to ensure that the
204835          ** tables within the output of sqlite3changegroup_output() are in 
204836          ** the right order.  */
204837          for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
204838          *ppTab = pTab;
204839        }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
204840          rc = SQLITE_SCHEMA;
204841          break;
204842        }
204843      }
204844  
204845      if( sessionGrowHash(pIter->bPatchset, pTab) ){
204846        rc = SQLITE_NOMEM;
204847        break;
204848      }
204849      iHash = sessionChangeHash(
204850          pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
204851      );
204852  
204853      /* Search for existing entry. If found, remove it from the hash table. 
204854      ** Code below may link it back in.
204855      */
204856      for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
204857        int bPkOnly1 = 0;
204858        int bPkOnly2 = 0;
204859        if( pIter->bPatchset ){
204860          bPkOnly1 = (*pp)->op==SQLITE_DELETE;
204861          bPkOnly2 = op==SQLITE_DELETE;
204862        }
204863        if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
204864          pExist = *pp;
204865          *pp = (*pp)->pNext;
204866          pTab->nEntry--;
204867          break;
204868        }
204869      }
204870  
204871      rc = sessionChangeMerge(pTab, bRebase, 
204872          pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
204873      );
204874      if( rc ) break;
204875      if( pChange ){
204876        pChange->pNext = pTab->apChange[iHash];
204877        pTab->apChange[iHash] = pChange;
204878        pTab->nEntry++;
204879      }
204880    }
204881  
204882    if( rc==SQLITE_OK ) rc = pIter->rc;
204883    return rc;
204884  }
204885  
204886  /*
204887  ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
204888  ** added to the changegroup object passed as the first argument.
204889  **
204890  ** If xOutput is not NULL, then the changeset/patchset is returned to the
204891  ** user via one or more calls to xOutput, as with the other streaming
204892  ** interfaces. 
204893  **
204894  ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
204895  ** buffer containing the output changeset before this function returns. In
204896  ** this case (*pnOut) is set to the size of the output buffer in bytes. It
204897  ** is the responsibility of the caller to free the output buffer using
204898  ** sqlite3_free() when it is no longer required.
204899  **
204900  ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
204901  ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
204902  ** are both set to 0 before returning.
204903  */
204904  static int sessionChangegroupOutput(
204905    sqlite3_changegroup *pGrp,
204906    int (*xOutput)(void *pOut, const void *pData, int nData),
204907    void *pOut,
204908    int *pnOut,
204909    void **ppOut
204910  ){
204911    int rc = SQLITE_OK;
204912    SessionBuffer buf = {0, 0, 0};
204913    SessionTable *pTab;
204914    assert( xOutput==0 || (ppOut==0 && pnOut==0) );
204915  
204916    /* Create the serialized output changeset based on the contents of the
204917    ** hash tables attached to the SessionTable objects in list p->pList. 
204918    */
204919    for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
204920      int i;
204921      if( pTab->nEntry==0 ) continue;
204922  
204923      sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
204924      for(i=0; i<pTab->nChange; i++){
204925        SessionChange *p;
204926        for(p=pTab->apChange[i]; p; p=p->pNext){
204927          sessionAppendByte(&buf, p->op, &rc);
204928          sessionAppendByte(&buf, p->bIndirect, &rc);
204929          sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
204930          if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
204931            rc = xOutput(pOut, buf.aBuf, buf.nBuf);
204932            buf.nBuf = 0;
204933          }
204934        }
204935      }
204936    }
204937  
204938    if( rc==SQLITE_OK ){
204939      if( xOutput ){
204940        if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
204941      }else{
204942        *ppOut = buf.aBuf;
204943        *pnOut = buf.nBuf;
204944        buf.aBuf = 0;
204945      }
204946    }
204947    sqlite3_free(buf.aBuf);
204948  
204949    return rc;
204950  }
204951  
204952  /*
204953  ** Allocate a new, empty, sqlite3_changegroup.
204954  */
204955  SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
204956    int rc = SQLITE_OK;             /* Return code */
204957    sqlite3_changegroup *p;         /* New object */
204958    p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
204959    if( p==0 ){
204960      rc = SQLITE_NOMEM;
204961    }else{
204962      memset(p, 0, sizeof(sqlite3_changegroup));
204963    }
204964    *pp = p;
204965    return rc;
204966  }
204967  
204968  /*
204969  ** Add the changeset currently stored in buffer pData, size nData bytes,
204970  ** to changeset-group p.
204971  */
204972  SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
204973    sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
204974    int rc;                         /* Return code */
204975  
204976    rc = sqlite3changeset_start(&pIter, nData, pData);
204977    if( rc==SQLITE_OK ){
204978      rc = sessionChangesetToHash(pIter, pGrp, 0);
204979    }
204980    sqlite3changeset_finalize(pIter);
204981    return rc;
204982  }
204983  
204984  /*
204985  ** Obtain a buffer containing a changeset representing the concatenation
204986  ** of all changesets added to the group so far.
204987  */
204988  SQLITE_API int sqlite3changegroup_output(
204989      sqlite3_changegroup *pGrp,
204990      int *pnData,
204991      void **ppData
204992  ){
204993    return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
204994  }
204995  
204996  /*
204997  ** Streaming versions of changegroup_add().
204998  */
204999  SQLITE_API int sqlite3changegroup_add_strm(
205000    sqlite3_changegroup *pGrp,
205001    int (*xInput)(void *pIn, void *pData, int *pnData),
205002    void *pIn
205003  ){
205004    sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
205005    int rc;                         /* Return code */
205006  
205007    rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
205008    if( rc==SQLITE_OK ){
205009      rc = sessionChangesetToHash(pIter, pGrp, 0);
205010    }
205011    sqlite3changeset_finalize(pIter);
205012    return rc;
205013  }
205014  
205015  /*
205016  ** Streaming versions of changegroup_output().
205017  */
205018  SQLITE_API int sqlite3changegroup_output_strm(
205019    sqlite3_changegroup *pGrp,
205020    int (*xOutput)(void *pOut, const void *pData, int nData), 
205021    void *pOut
205022  ){
205023    return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
205024  }
205025  
205026  /*
205027  ** Delete a changegroup object.
205028  */
205029  SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
205030    if( pGrp ){
205031      sessionDeleteTable(pGrp->pList);
205032      sqlite3_free(pGrp);
205033    }
205034  }
205035  
205036  /* 
205037  ** Combine two changesets together.
205038  */
205039  SQLITE_API int sqlite3changeset_concat(
205040    int nLeft,                      /* Number of bytes in lhs input */
205041    void *pLeft,                    /* Lhs input changeset */
205042    int nRight                      /* Number of bytes in rhs input */,
205043    void *pRight,                   /* Rhs input changeset */
205044    int *pnOut,                     /* OUT: Number of bytes in output changeset */
205045    void **ppOut                    /* OUT: changeset (left <concat> right) */
205046  ){
205047    sqlite3_changegroup *pGrp;
205048    int rc;
205049  
205050    rc = sqlite3changegroup_new(&pGrp);
205051    if( rc==SQLITE_OK ){
205052      rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
205053    }
205054    if( rc==SQLITE_OK ){
205055      rc = sqlite3changegroup_add(pGrp, nRight, pRight);
205056    }
205057    if( rc==SQLITE_OK ){
205058      rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
205059    }
205060    sqlite3changegroup_delete(pGrp);
205061  
205062    return rc;
205063  }
205064  
205065  /*
205066  ** Streaming version of sqlite3changeset_concat().
205067  */
205068  SQLITE_API int sqlite3changeset_concat_strm(
205069    int (*xInputA)(void *pIn, void *pData, int *pnData),
205070    void *pInA,
205071    int (*xInputB)(void *pIn, void *pData, int *pnData),
205072    void *pInB,
205073    int (*xOutput)(void *pOut, const void *pData, int nData),
205074    void *pOut
205075  ){
205076    sqlite3_changegroup *pGrp;
205077    int rc;
205078  
205079    rc = sqlite3changegroup_new(&pGrp);
205080    if( rc==SQLITE_OK ){
205081      rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
205082    }
205083    if( rc==SQLITE_OK ){
205084      rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
205085    }
205086    if( rc==SQLITE_OK ){
205087      rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
205088    }
205089    sqlite3changegroup_delete(pGrp);
205090  
205091    return rc;
205092  }
205093  
205094  /*
205095  ** Changeset rebaser handle.
205096  */
205097  struct sqlite3_rebaser {
205098    sqlite3_changegroup grp;        /* Hash table */
205099  };
205100  
205101  /*
205102  ** Buffers a1 and a2 must both contain a sessions module record nCol
205103  ** fields in size. This function appends an nCol sessions module 
205104  ** record to buffer pBuf that is a copy of a1, except that for
205105  ** each field that is undefined in a1[], swap in the field from a2[].
205106  */
205107  static void sessionAppendRecordMerge(
205108    SessionBuffer *pBuf,            /* Buffer to append to */
205109    int nCol,                       /* Number of columns in each record */
205110    u8 *a1, int n1,                 /* Record 1 */
205111    u8 *a2, int n2,                 /* Record 2 */
205112    int *pRc                        /* IN/OUT: error code */
205113  ){
205114    sessionBufferGrow(pBuf, n1+n2, pRc);
205115    if( *pRc==SQLITE_OK ){
205116      int i;
205117      u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
205118      for(i=0; i<nCol; i++){
205119        int nn1 = sessionSerialLen(a1);
205120        int nn2 = sessionSerialLen(a2);
205121        if( *a1==0 || *a1==0xFF ){
205122          memcpy(pOut, a2, nn2);
205123          pOut += nn2;
205124        }else{
205125          memcpy(pOut, a1, nn1);
205126          pOut += nn1;
205127        }
205128        a1 += nn1;
205129        a2 += nn2;
205130      }
205131  
205132      pBuf->nBuf = pOut-pBuf->aBuf;
205133      assert( pBuf->nBuf<=pBuf->nAlloc );
205134    }
205135  }
205136  
205137  /*
205138  ** This function is called when rebasing a local UPDATE change against one 
205139  ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
205140  ** old.* and new.* records for the change. The rebase buffer (a single
205141  ** record) is in aChange/nChange. The rebased change is appended to buffer
205142  ** pBuf.
205143  **
205144  ** Rebasing the UPDATE involves: 
205145  **
205146  **   * Removing any changes to fields for which the corresponding field
205147  **     in the rebase buffer is set to "replaced" (type 0xFF). If this
205148  **     means the UPDATE change updates no fields, nothing is appended
205149  **     to the output buffer.
205150  **
205151  **   * For each field modified by the local change for which the 
205152  **     corresponding field in the rebase buffer is not "undefined" (0x00)
205153  **     or "replaced" (0xFF), the old.* value is replaced by the value
205154  **     in the rebase buffer.
205155  */
205156  static void sessionAppendPartialUpdate(
205157    SessionBuffer *pBuf,            /* Append record here */
205158    sqlite3_changeset_iter *pIter,  /* Iterator pointed at local change */
205159    u8 *aRec, int nRec,             /* Local change */
205160    u8 *aChange, int nChange,       /* Record to rebase against */
205161    int *pRc                        /* IN/OUT: Return Code */
205162  ){
205163    sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
205164    if( *pRc==SQLITE_OK ){
205165      int bData = 0;
205166      u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
205167      int i;
205168      u8 *a1 = aRec;
205169      u8 *a2 = aChange;
205170  
205171      *pOut++ = SQLITE_UPDATE;
205172      *pOut++ = pIter->bIndirect;
205173      for(i=0; i<pIter->nCol; i++){
205174        int n1 = sessionSerialLen(a1);
205175        int n2 = sessionSerialLen(a2);
205176        if( pIter->abPK[i] || a2[0]==0 ){
205177          if( !pIter->abPK[i] ) bData = 1;
205178          memcpy(pOut, a1, n1);
205179          pOut += n1;
205180        }else if( a2[0]!=0xFF ){
205181          bData = 1;
205182          memcpy(pOut, a2, n2);
205183          pOut += n2;
205184        }else{
205185          *pOut++ = '\0';
205186        }
205187        a1 += n1;
205188        a2 += n2;
205189      }
205190      if( bData ){
205191        a2 = aChange;
205192        for(i=0; i<pIter->nCol; i++){
205193          int n1 = sessionSerialLen(a1);
205194          int n2 = sessionSerialLen(a2);
205195          if( pIter->abPK[i] || a2[0]!=0xFF ){
205196            memcpy(pOut, a1, n1);
205197            pOut += n1;
205198          }else{
205199            *pOut++ = '\0';
205200          }
205201          a1 += n1;
205202          a2 += n2;
205203        }
205204        pBuf->nBuf = (pOut - pBuf->aBuf);
205205      }
205206    }
205207  }
205208  
205209  /*
205210  ** pIter is configured to iterate through a changeset. This function rebases 
205211  ** that changeset according to the current configuration of the rebaser 
205212  ** object passed as the first argument. If no error occurs and argument xOutput
205213  ** is not NULL, then the changeset is returned to the caller by invoking
205214  ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
205215  ** then (*ppOut) is set to point to a buffer containing the rebased changeset
205216  ** before this function returns. In this case (*pnOut) is set to the size of
205217  ** the buffer in bytes.  It is the responsibility of the caller to eventually
205218  ** free the (*ppOut) buffer using sqlite3_free(). 
205219  **
205220  ** If an error occurs, an SQLite error code is returned. If ppOut and
205221  ** pnOut are not NULL, then the two output parameters are set to 0 before
205222  ** returning.
205223  */
205224  static int sessionRebase(
205225    sqlite3_rebaser *p,             /* Rebaser hash table */
205226    sqlite3_changeset_iter *pIter,  /* Input data */
205227    int (*xOutput)(void *pOut, const void *pData, int nData),
205228    void *pOut,                     /* Context for xOutput callback */
205229    int *pnOut,                     /* OUT: Number of bytes in output changeset */
205230    void **ppOut                    /* OUT: Inverse of pChangeset */
205231  ){
205232    int rc = SQLITE_OK;
205233    u8 *aRec = 0;
205234    int nRec = 0;
205235    int bNew = 0;
205236    SessionTable *pTab = 0;
205237    SessionBuffer sOut = {0,0,0};
205238  
205239    while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
205240      SessionChange *pChange = 0;
205241      int bDone = 0;
205242  
205243      if( bNew ){
205244        const char *zTab = pIter->zTab;
205245        for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
205246          if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
205247        }
205248        bNew = 0;
205249  
205250        /* A patchset may not be rebased */
205251        if( pIter->bPatchset ){
205252          rc = SQLITE_ERROR;
205253        }
205254  
205255        /* Append a table header to the output for this new table */
205256        sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
205257        sessionAppendVarint(&sOut, pIter->nCol, &rc);
205258        sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
205259        sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
205260      }
205261  
205262      if( pTab && rc==SQLITE_OK ){
205263        int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
205264  
205265        for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
205266          if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
205267            break;
205268          }
205269        }
205270      }
205271  
205272      if( pChange ){
205273        assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
205274        switch( pIter->op ){
205275          case SQLITE_INSERT:
205276            if( pChange->op==SQLITE_INSERT ){
205277              bDone = 1;
205278              if( pChange->bIndirect==0 ){
205279                sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
205280                sessionAppendByte(&sOut, pIter->bIndirect, &rc);
205281                sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
205282                sessionAppendBlob(&sOut, aRec, nRec, &rc);
205283              }
205284            }
205285            break;
205286  
205287          case SQLITE_UPDATE:
205288            bDone = 1;
205289            if( pChange->op==SQLITE_DELETE ){
205290              if( pChange->bIndirect==0 ){
205291                u8 *pCsr = aRec;
205292                sessionSkipRecord(&pCsr, pIter->nCol);
205293                sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
205294                sessionAppendByte(&sOut, pIter->bIndirect, &rc);
205295                sessionAppendRecordMerge(&sOut, pIter->nCol,
205296                    pCsr, nRec-(pCsr-aRec), 
205297                    pChange->aRecord, pChange->nRecord, &rc
205298                );
205299              }
205300            }else{
205301              sessionAppendPartialUpdate(&sOut, pIter,
205302                  aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
205303              );
205304            }
205305            break;
205306  
205307          default:
205308            assert( pIter->op==SQLITE_DELETE );
205309            bDone = 1;
205310            if( pChange->op==SQLITE_INSERT ){
205311              sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
205312              sessionAppendByte(&sOut, pIter->bIndirect, &rc);
205313              sessionAppendRecordMerge(&sOut, pIter->nCol,
205314                  pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
205315              );
205316            }
205317            break;
205318        }
205319      }
205320  
205321      if( bDone==0 ){
205322        sessionAppendByte(&sOut, pIter->op, &rc);
205323        sessionAppendByte(&sOut, pIter->bIndirect, &rc);
205324        sessionAppendBlob(&sOut, aRec, nRec, &rc);
205325      }
205326      if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
205327        rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
205328        sOut.nBuf = 0;
205329      }
205330      if( rc ) break;
205331    }
205332  
205333    if( rc!=SQLITE_OK ){
205334      sqlite3_free(sOut.aBuf);
205335      memset(&sOut, 0, sizeof(sOut));
205336    }
205337  
205338    if( rc==SQLITE_OK ){
205339      if( xOutput ){
205340        if( sOut.nBuf>0 ){
205341          rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
205342        }
205343      }else{
205344        *ppOut = (void*)sOut.aBuf;
205345        *pnOut = sOut.nBuf;
205346        sOut.aBuf = 0;
205347      }
205348    }
205349    sqlite3_free(sOut.aBuf);
205350    return rc;
205351  }
205352  
205353  /* 
205354  ** Create a new rebaser object.
205355  */
205356  SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
205357    int rc = SQLITE_OK;
205358    sqlite3_rebaser *pNew;
205359  
205360    pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
205361    if( pNew==0 ){
205362      rc = SQLITE_NOMEM;
205363    }else{
205364      memset(pNew, 0, sizeof(sqlite3_rebaser));
205365    }
205366    *ppNew = pNew;
205367    return rc;
205368  }
205369  
205370  /* 
205371  ** Call this one or more times to configure a rebaser.
205372  */
205373  SQLITE_API int sqlite3rebaser_configure(
205374    sqlite3_rebaser *p, 
205375    int nRebase, const void *pRebase
205376  ){
205377    sqlite3_changeset_iter *pIter = 0;   /* Iterator opened on pData/nData */
205378    int rc;                              /* Return code */
205379    rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
205380    if( rc==SQLITE_OK ){
205381      rc = sessionChangesetToHash(pIter, &p->grp, 1);
205382    }
205383    sqlite3changeset_finalize(pIter);
205384    return rc;
205385  }
205386  
205387  /* 
205388  ** Rebase a changeset according to current rebaser configuration 
205389  */
205390  SQLITE_API int sqlite3rebaser_rebase(
205391    sqlite3_rebaser *p,
205392    int nIn, const void *pIn, 
205393    int *pnOut, void **ppOut 
205394  ){
205395    sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  
205396    int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
205397  
205398    if( rc==SQLITE_OK ){
205399      rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
205400      sqlite3changeset_finalize(pIter);
205401    }
205402  
205403    return rc;
205404  }
205405  
205406  /* 
205407  ** Rebase a changeset according to current rebaser configuration 
205408  */
205409  SQLITE_API int sqlite3rebaser_rebase_strm(
205410    sqlite3_rebaser *p,
205411    int (*xInput)(void *pIn, void *pData, int *pnData),
205412    void *pIn,
205413    int (*xOutput)(void *pOut, const void *pData, int nData),
205414    void *pOut
205415  ){
205416    sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  
205417    int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
205418  
205419    if( rc==SQLITE_OK ){
205420      rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
205421      sqlite3changeset_finalize(pIter);
205422    }
205423  
205424    return rc;
205425  }
205426  
205427  /* 
205428  ** Destroy a rebaser object 
205429  */
205430  SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
205431    if( p ){
205432      sessionDeleteTable(p->grp.pList);
205433      sqlite3_free(p);
205434    }
205435  }
205436  
205437  /* 
205438  ** Global configuration
205439  */
205440  SQLITE_API int sqlite3session_config(int op, void *pArg){
205441    int rc = SQLITE_OK;
205442    switch( op ){
205443      case SQLITE_SESSION_CONFIG_STRMSIZE: {
205444        int *pInt = (int*)pArg;
205445        if( *pInt>0 ){
205446          sessions_strm_chunk_size = *pInt;
205447        }
205448        *pInt = sessions_strm_chunk_size;
205449        break;
205450      }
205451      default:
205452        rc = SQLITE_MISUSE;
205453        break;
205454    }
205455    return rc;
205456  }
205457  
205458  #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
205459  
205460  /************** End of sqlite3session.c **************************************/
205461  /************** Begin file fts5.c ********************************************/
205462  
205463  
205464  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) 
205465  
205466  #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
205467  # define NDEBUG 1
205468  #endif
205469  #if defined(NDEBUG) && defined(SQLITE_DEBUG)
205470  # undef NDEBUG
205471  #endif
205472  
205473  /*
205474  ** 2014 May 31
205475  **
205476  ** The author disclaims copyright to this source code.  In place of
205477  ** a legal notice, here is a blessing:
205478  **
205479  **    May you do good and not evil.
205480  **    May you find forgiveness for yourself and forgive others.
205481  **    May you share freely, never taking more than you give.
205482  **
205483  ******************************************************************************
205484  **
205485  ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
205486  ** FTS5 may be extended with:
205487  **
205488  **     * custom tokenizers, and
205489  **     * custom auxiliary functions.
205490  */
205491  
205492  
205493  #ifndef _FTS5_H
205494  #define _FTS5_H
205495  
205496  /* #include "sqlite3.h" */
205497  
205498  #if 0
205499  extern "C" {
205500  #endif
205501  
205502  /*************************************************************************
205503  ** CUSTOM AUXILIARY FUNCTIONS
205504  **
205505  ** Virtual table implementations may overload SQL functions by implementing
205506  ** the sqlite3_module.xFindFunction() method.
205507  */
205508  
205509  typedef struct Fts5ExtensionApi Fts5ExtensionApi;
205510  typedef struct Fts5Context Fts5Context;
205511  typedef struct Fts5PhraseIter Fts5PhraseIter;
205512  
205513  typedef void (*fts5_extension_function)(
205514    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
205515    Fts5Context *pFts,              /* First arg to pass to pApi functions */
205516    sqlite3_context *pCtx,          /* Context for returning result/error */
205517    int nVal,                       /* Number of values in apVal[] array */
205518    sqlite3_value **apVal           /* Array of trailing arguments */
205519  );
205520  
205521  struct Fts5PhraseIter {
205522    const unsigned char *a;
205523    const unsigned char *b;
205524  };
205525  
205526  /*
205527  ** EXTENSION API FUNCTIONS
205528  **
205529  ** xUserData(pFts):
205530  **   Return a copy of the context pointer the extension function was 
205531  **   registered with.
205532  **
205533  ** xColumnTotalSize(pFts, iCol, pnToken):
205534  **   If parameter iCol is less than zero, set output variable *pnToken
205535  **   to the total number of tokens in the FTS5 table. Or, if iCol is
205536  **   non-negative but less than the number of columns in the table, return
205537  **   the total number of tokens in column iCol, considering all rows in 
205538  **   the FTS5 table.
205539  **
205540  **   If parameter iCol is greater than or equal to the number of columns
205541  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
205542  **   an OOM condition or IO error), an appropriate SQLite error code is 
205543  **   returned.
205544  **
205545  ** xColumnCount(pFts):
205546  **   Return the number of columns in the table.
205547  **
205548  ** xColumnSize(pFts, iCol, pnToken):
205549  **   If parameter iCol is less than zero, set output variable *pnToken
205550  **   to the total number of tokens in the current row. Or, if iCol is
205551  **   non-negative but less than the number of columns in the table, set
205552  **   *pnToken to the number of tokens in column iCol of the current row.
205553  **
205554  **   If parameter iCol is greater than or equal to the number of columns
205555  **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
205556  **   an OOM condition or IO error), an appropriate SQLite error code is 
205557  **   returned.
205558  **
205559  **   This function may be quite inefficient if used with an FTS5 table
205560  **   created with the "columnsize=0" option.
205561  **
205562  ** xColumnText:
205563  **   This function attempts to retrieve the text of column iCol of the
205564  **   current document. If successful, (*pz) is set to point to a buffer
205565  **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
205566  **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
205567  **   if an error occurs, an SQLite error code is returned and the final values
205568  **   of (*pz) and (*pn) are undefined.
205569  **
205570  ** xPhraseCount:
205571  **   Returns the number of phrases in the current query expression.
205572  **
205573  ** xPhraseSize:
205574  **   Returns the number of tokens in phrase iPhrase of the query. Phrases
205575  **   are numbered starting from zero.
205576  **
205577  ** xInstCount:
205578  **   Set *pnInst to the total number of occurrences of all phrases within
205579  **   the query within the current row. Return SQLITE_OK if successful, or
205580  **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
205581  **
205582  **   This API can be quite slow if used with an FTS5 table created with the
205583  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
205584  **   with either "detail=none" or "detail=column" and "content=" option 
205585  **   (i.e. if it is a contentless table), then this API always returns 0.
205586  **
205587  ** xInst:
205588  **   Query for the details of phrase match iIdx within the current row.
205589  **   Phrase matches are numbered starting from zero, so the iIdx argument
205590  **   should be greater than or equal to zero and smaller than the value
205591  **   output by xInstCount().
205592  **
205593  **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
205594  **   to the column in which it occurs and *piOff the token offset of the
205595  **   first token of the phrase. Returns SQLITE_OK if successful, or an error
205596  **   code (i.e. SQLITE_NOMEM) if an error occurs.
205597  **
205598  **   This API can be quite slow if used with an FTS5 table created with the
205599  **   "detail=none" or "detail=column" option. 
205600  **
205601  ** xRowid:
205602  **   Returns the rowid of the current row.
205603  **
205604  ** xTokenize:
205605  **   Tokenize text using the tokenizer belonging to the FTS5 table.
205606  **
205607  ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
205608  **   This API function is used to query the FTS table for phrase iPhrase
205609  **   of the current query. Specifically, a query equivalent to:
205610  **
205611  **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
205612  **
205613  **   with $p set to a phrase equivalent to the phrase iPhrase of the
205614  **   current query is executed. Any column filter that applies to
205615  **   phrase iPhrase of the current query is included in $p. For each 
205616  **   row visited, the callback function passed as the fourth argument 
205617  **   is invoked. The context and API objects passed to the callback 
205618  **   function may be used to access the properties of each matched row.
205619  **   Invoking Api.xUserData() returns a copy of the pointer passed as 
205620  **   the third argument to pUserData.
205621  **
205622  **   If the callback function returns any value other than SQLITE_OK, the
205623  **   query is abandoned and the xQueryPhrase function returns immediately.
205624  **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
205625  **   Otherwise, the error code is propagated upwards.
205626  **
205627  **   If the query runs to completion without incident, SQLITE_OK is returned.
205628  **   Or, if some error occurs before the query completes or is aborted by
205629  **   the callback, an SQLite error code is returned.
205630  **
205631  **
205632  ** xSetAuxdata(pFts5, pAux, xDelete)
205633  **
205634  **   Save the pointer passed as the second argument as the extension functions 
205635  **   "auxiliary data". The pointer may then be retrieved by the current or any
205636  **   future invocation of the same fts5 extension function made as part of
205637  **   of the same MATCH query using the xGetAuxdata() API.
205638  **
205639  **   Each extension function is allocated a single auxiliary data slot for
205640  **   each FTS query (MATCH expression). If the extension function is invoked 
205641  **   more than once for a single FTS query, then all invocations share a 
205642  **   single auxiliary data context.
205643  **
205644  **   If there is already an auxiliary data pointer when this function is
205645  **   invoked, then it is replaced by the new pointer. If an xDelete callback
205646  **   was specified along with the original pointer, it is invoked at this
205647  **   point.
205648  **
205649  **   The xDelete callback, if one is specified, is also invoked on the
205650  **   auxiliary data pointer after the FTS5 query has finished.
205651  **
205652  **   If an error (e.g. an OOM condition) occurs within this function, an
205653  **   the auxiliary data is set to NULL and an error code returned. If the
205654  **   xDelete parameter was not NULL, it is invoked on the auxiliary data
205655  **   pointer before returning.
205656  **
205657  **
205658  ** xGetAuxdata(pFts5, bClear)
205659  **
205660  **   Returns the current auxiliary data pointer for the fts5 extension 
205661  **   function. See the xSetAuxdata() method for details.
205662  **
205663  **   If the bClear argument is non-zero, then the auxiliary data is cleared
205664  **   (set to NULL) before this function returns. In this case the xDelete,
205665  **   if any, is not invoked.
205666  **
205667  **
205668  ** xRowCount(pFts5, pnRow)
205669  **
205670  **   This function is used to retrieve the total number of rows in the table.
205671  **   In other words, the same value that would be returned by:
205672  **
205673  **        SELECT count(*) FROM ftstable;
205674  **
205675  ** xPhraseFirst()
205676  **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
205677  **   method, to iterate through all instances of a single query phrase within
205678  **   the current row. This is the same information as is accessible via the
205679  **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
205680  **   to use, this API may be faster under some circumstances. To iterate 
205681  **   through instances of phrase iPhrase, use the following code:
205682  **
205683  **       Fts5PhraseIter iter;
205684  **       int iCol, iOff;
205685  **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
205686  **           iCol>=0;
205687  **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
205688  **       ){
205689  **         // An instance of phrase iPhrase at offset iOff of column iCol
205690  **       }
205691  **
205692  **   The Fts5PhraseIter structure is defined above. Applications should not
205693  **   modify this structure directly - it should only be used as shown above
205694  **   with the xPhraseFirst() and xPhraseNext() API methods (and by
205695  **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
205696  **
205697  **   This API can be quite slow if used with an FTS5 table created with the
205698  **   "detail=none" or "detail=column" option. If the FTS5 table is created 
205699  **   with either "detail=none" or "detail=column" and "content=" option 
205700  **   (i.e. if it is a contentless table), then this API always iterates
205701  **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
205702  **
205703  ** xPhraseNext()
205704  **   See xPhraseFirst above.
205705  **
205706  ** xPhraseFirstColumn()
205707  **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
205708  **   and xPhraseNext() APIs described above. The difference is that instead
205709  **   of iterating through all instances of a phrase in the current row, these
205710  **   APIs are used to iterate through the set of columns in the current row
205711  **   that contain one or more instances of a specified phrase. For example:
205712  **
205713  **       Fts5PhraseIter iter;
205714  **       int iCol;
205715  **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
205716  **           iCol>=0;
205717  **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
205718  **       ){
205719  **         // Column iCol contains at least one instance of phrase iPhrase
205720  **       }
205721  **
205722  **   This API can be quite slow if used with an FTS5 table created with the
205723  **   "detail=none" option. If the FTS5 table is created with either 
205724  **   "detail=none" "content=" option (i.e. if it is a contentless table), 
205725  **   then this API always iterates through an empty set (all calls to 
205726  **   xPhraseFirstColumn() set iCol to -1).
205727  **
205728  **   The information accessed using this API and its companion
205729  **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
205730  **   (or xInst/xInstCount). The chief advantage of this API is that it is
205731  **   significantly more efficient than those alternatives when used with
205732  **   "detail=column" tables.  
205733  **
205734  ** xPhraseNextColumn()
205735  **   See xPhraseFirstColumn above.
205736  */
205737  struct Fts5ExtensionApi {
205738    int iVersion;                   /* Currently always set to 3 */
205739  
205740    void *(*xUserData)(Fts5Context*);
205741  
205742    int (*xColumnCount)(Fts5Context*);
205743    int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
205744    int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
205745  
205746    int (*xTokenize)(Fts5Context*, 
205747      const char *pText, int nText, /* Text to tokenize */
205748      void *pCtx,                   /* Context passed to xToken() */
205749      int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
205750    );
205751  
205752    int (*xPhraseCount)(Fts5Context*);
205753    int (*xPhraseSize)(Fts5Context*, int iPhrase);
205754  
205755    int (*xInstCount)(Fts5Context*, int *pnInst);
205756    int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
205757  
205758    sqlite3_int64 (*xRowid)(Fts5Context*);
205759    int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
205760    int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
205761  
205762    int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
205763      int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
205764    );
205765    int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
205766    void *(*xGetAuxdata)(Fts5Context*, int bClear);
205767  
205768    int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
205769    void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
205770  
205771    int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
205772    void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
205773  };
205774  
205775  /* 
205776  ** CUSTOM AUXILIARY FUNCTIONS
205777  *************************************************************************/
205778  
205779  /*************************************************************************
205780  ** CUSTOM TOKENIZERS
205781  **
205782  ** Applications may also register custom tokenizer types. A tokenizer 
205783  ** is registered by providing fts5 with a populated instance of the 
205784  ** following structure. All structure methods must be defined, setting
205785  ** any member of the fts5_tokenizer struct to NULL leads to undefined
205786  ** behaviour. The structure methods are expected to function as follows:
205787  **
205788  ** xCreate:
205789  **   This function is used to allocate and initialize a tokenizer instance.
205790  **   A tokenizer instance is required to actually tokenize text.
205791  **
205792  **   The first argument passed to this function is a copy of the (void*)
205793  **   pointer provided by the application when the fts5_tokenizer object
205794  **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
205795  **   The second and third arguments are an array of nul-terminated strings
205796  **   containing the tokenizer arguments, if any, specified following the
205797  **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
205798  **   to create the FTS5 table.
205799  **
205800  **   The final argument is an output variable. If successful, (*ppOut) 
205801  **   should be set to point to the new tokenizer handle and SQLITE_OK
205802  **   returned. If an error occurs, some value other than SQLITE_OK should
205803  **   be returned. In this case, fts5 assumes that the final value of *ppOut 
205804  **   is undefined.
205805  **
205806  ** xDelete:
205807  **   This function is invoked to delete a tokenizer handle previously
205808  **   allocated using xCreate(). Fts5 guarantees that this function will
205809  **   be invoked exactly once for each successful call to xCreate().
205810  **
205811  ** xTokenize:
205812  **   This function is expected to tokenize the nText byte string indicated 
205813  **   by argument pText. pText may or may not be nul-terminated. The first
205814  **   argument passed to this function is a pointer to an Fts5Tokenizer object
205815  **   returned by an earlier call to xCreate().
205816  **
205817  **   The second argument indicates the reason that FTS5 is requesting
205818  **   tokenization of the supplied text. This is always one of the following
205819  **   four values:
205820  **
205821  **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
205822  **            or removed from the FTS table. The tokenizer is being invoked to
205823  **            determine the set of tokens to add to (or delete from) the
205824  **            FTS index.
205825  **
205826  **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
205827  **            against the FTS index. The tokenizer is being called to tokenize 
205828  **            a bareword or quoted string specified as part of the query.
205829  **
205830  **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
205831  **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
205832  **            followed by a "*" character, indicating that the last token
205833  **            returned by the tokenizer will be treated as a token prefix.
205834  **
205835  **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
205836  **            satisfy an fts5_api.xTokenize() request made by an auxiliary
205837  **            function. Or an fts5_api.xColumnSize() request made by the same
205838  **            on a columnsize=0 database.  
205839  **   </ul>
205840  **
205841  **   For each token in the input string, the supplied callback xToken() must
205842  **   be invoked. The first argument to it should be a copy of the pointer
205843  **   passed as the second argument to xTokenize(). The third and fourth
205844  **   arguments are a pointer to a buffer containing the token text, and the
205845  **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
205846  **   of the first byte of and first byte immediately following the text from
205847  **   which the token is derived within the input.
205848  **
205849  **   The second argument passed to the xToken() callback ("tflags") should
205850  **   normally be set to 0. The exception is if the tokenizer supports 
205851  **   synonyms. In this case see the discussion below for details.
205852  **
205853  **   FTS5 assumes the xToken() callback is invoked for each token in the 
205854  **   order that they occur within the input text.
205855  **
205856  **   If an xToken() callback returns any value other than SQLITE_OK, then
205857  **   the tokenization should be abandoned and the xTokenize() method should
205858  **   immediately return a copy of the xToken() return value. Or, if the
205859  **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
205860  **   if an error occurs with the xTokenize() implementation itself, it
205861  **   may abandon the tokenization and return any error code other than
205862  **   SQLITE_OK or SQLITE_DONE.
205863  **
205864  ** SYNONYM SUPPORT
205865  **
205866  **   Custom tokenizers may also support synonyms. Consider a case in which a
205867  **   user wishes to query for a phrase such as "first place". Using the 
205868  **   built-in tokenizers, the FTS5 query 'first + place' will match instances
205869  **   of "first place" within the document set, but not alternative forms
205870  **   such as "1st place". In some applications, it would be better to match
205871  **   all instances of "first place" or "1st place" regardless of which form
205872  **   the user specified in the MATCH query text.
205873  **
205874  **   There are several ways to approach this in FTS5:
205875  **
205876  **   <ol><li> By mapping all synonyms to a single token. In this case, the 
205877  **            In the above example, this means that the tokenizer returns the
205878  **            same token for inputs "first" and "1st". Say that token is in
205879  **            fact "first", so that when the user inserts the document "I won
205880  **            1st place" entries are added to the index for tokens "i", "won",
205881  **            "first" and "place". If the user then queries for '1st + place',
205882  **            the tokenizer substitutes "first" for "1st" and the query works
205883  **            as expected.
205884  **
205885  **       <li> By querying the index for all synonyms of each query term
205886  **            separately. In this case, when tokenizing query text, the
205887  **            tokenizer may provide multiple synonyms for a single term 
205888  **            within the document. FTS5 then queries the index for each 
205889  **            synonym individually. For example, faced with the query:
205890  **
205891  **   <codeblock>
205892  **     ... MATCH 'first place'</codeblock>
205893  **
205894  **            the tokenizer offers both "1st" and "first" as synonyms for the
205895  **            first token in the MATCH query and FTS5 effectively runs a query 
205896  **            similar to:
205897  **
205898  **   <codeblock>
205899  **     ... MATCH '(first OR 1st) place'</codeblock>
205900  **
205901  **            except that, for the purposes of auxiliary functions, the query
205902  **            still appears to contain just two phrases - "(first OR 1st)" 
205903  **            being treated as a single phrase.
205904  **
205905  **       <li> By adding multiple synonyms for a single term to the FTS index.
205906  **            Using this method, when tokenizing document text, the tokenizer
205907  **            provides multiple synonyms for each token. So that when a 
205908  **            document such as "I won first place" is tokenized, entries are
205909  **            added to the FTS index for "i", "won", "first", "1st" and
205910  **            "place".
205911  **
205912  **            This way, even if the tokenizer does not provide synonyms
205913  **            when tokenizing query text (it should not - to do so would be
205914  **            inefficient), it doesn't matter if the user queries for 
205915  **            'first + place' or '1st + place', as there are entries in the
205916  **            FTS index corresponding to both forms of the first token.
205917  **   </ol>
205918  **
205919  **   Whether it is parsing document or query text, any call to xToken that
205920  **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
205921  **   is considered to supply a synonym for the previous token. For example,
205922  **   when parsing the document "I won first place", a tokenizer that supports
205923  **   synonyms would call xToken() 5 times, as follows:
205924  **
205925  **   <codeblock>
205926  **       xToken(pCtx, 0, "i",                      1,  0,  1);
205927  **       xToken(pCtx, 0, "won",                    3,  2,  5);
205928  **       xToken(pCtx, 0, "first",                  5,  6, 11);
205929  **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
205930  **       xToken(pCtx, 0, "place",                  5, 12, 17);
205931  **</codeblock>
205932  **
205933  **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
205934  **   xToken() is called. Multiple synonyms may be specified for a single token
205935  **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
205936  **   There is no limit to the number of synonyms that may be provided for a
205937  **   single token.
205938  **
205939  **   In many cases, method (1) above is the best approach. It does not add 
205940  **   extra data to the FTS index or require FTS5 to query for multiple terms,
205941  **   so it is efficient in terms of disk space and query speed. However, it
205942  **   does not support prefix queries very well. If, as suggested above, the
205943  **   token "first" is substituted for "1st" by the tokenizer, then the query:
205944  **
205945  **   <codeblock>
205946  **     ... MATCH '1s*'</codeblock>
205947  **
205948  **   will not match documents that contain the token "1st" (as the tokenizer
205949  **   will probably not map "1s" to any prefix of "first").
205950  **
205951  **   For full prefix support, method (3) may be preferred. In this case, 
205952  **   because the index contains entries for both "first" and "1st", prefix
205953  **   queries such as 'fi*' or '1s*' will match correctly. However, because
205954  **   extra entries are added to the FTS index, this method uses more space
205955  **   within the database.
205956  **
205957  **   Method (2) offers a midpoint between (1) and (3). Using this method,
205958  **   a query such as '1s*' will match documents that contain the literal 
205959  **   token "1st", but not "first" (assuming the tokenizer is not able to
205960  **   provide synonyms for prefixes). However, a non-prefix query like '1st'
205961  **   will match against "1st" and "first". This method does not require
205962  **   extra disk space, as no extra entries are added to the FTS index. 
205963  **   On the other hand, it may require more CPU cycles to run MATCH queries,
205964  **   as separate queries of the FTS index are required for each synonym.
205965  **
205966  **   When using methods (2) or (3), it is important that the tokenizer only
205967  **   provide synonyms when tokenizing document text (method (2)) or query
205968  **   text (method (3)), not both. Doing so will not cause any errors, but is
205969  **   inefficient.
205970  */
205971  typedef struct Fts5Tokenizer Fts5Tokenizer;
205972  typedef struct fts5_tokenizer fts5_tokenizer;
205973  struct fts5_tokenizer {
205974    int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
205975    void (*xDelete)(Fts5Tokenizer*);
205976    int (*xTokenize)(Fts5Tokenizer*, 
205977        void *pCtx,
205978        int flags,            /* Mask of FTS5_TOKENIZE_* flags */
205979        const char *pText, int nText, 
205980        int (*xToken)(
205981          void *pCtx,         /* Copy of 2nd argument to xTokenize() */
205982          int tflags,         /* Mask of FTS5_TOKEN_* flags */
205983          const char *pToken, /* Pointer to buffer containing token */
205984          int nToken,         /* Size of token in bytes */
205985          int iStart,         /* Byte offset of token within input text */
205986          int iEnd            /* Byte offset of end of token within input text */
205987        )
205988    );
205989  };
205990  
205991  /* Flags that may be passed as the third argument to xTokenize() */
205992  #define FTS5_TOKENIZE_QUERY     0x0001
205993  #define FTS5_TOKENIZE_PREFIX    0x0002
205994  #define FTS5_TOKENIZE_DOCUMENT  0x0004
205995  #define FTS5_TOKENIZE_AUX       0x0008
205996  
205997  /* Flags that may be passed by the tokenizer implementation back to FTS5
205998  ** as the third argument to the supplied xToken callback. */
205999  #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
206000  
206001  /*
206002  ** END OF CUSTOM TOKENIZERS
206003  *************************************************************************/
206004  
206005  /*************************************************************************
206006  ** FTS5 EXTENSION REGISTRATION API
206007  */
206008  typedef struct fts5_api fts5_api;
206009  struct fts5_api {
206010    int iVersion;                   /* Currently always set to 2 */
206011  
206012    /* Create a new tokenizer */
206013    int (*xCreateTokenizer)(
206014      fts5_api *pApi,
206015      const char *zName,
206016      void *pContext,
206017      fts5_tokenizer *pTokenizer,
206018      void (*xDestroy)(void*)
206019    );
206020  
206021    /* Find an existing tokenizer */
206022    int (*xFindTokenizer)(
206023      fts5_api *pApi,
206024      const char *zName,
206025      void **ppContext,
206026      fts5_tokenizer *pTokenizer
206027    );
206028  
206029    /* Create a new auxiliary function */
206030    int (*xCreateFunction)(
206031      fts5_api *pApi,
206032      const char *zName,
206033      void *pContext,
206034      fts5_extension_function xFunction,
206035      void (*xDestroy)(void*)
206036    );
206037  };
206038  
206039  /*
206040  ** END OF REGISTRATION API
206041  *************************************************************************/
206042  
206043  #if 0
206044  }  /* end of the 'extern "C"' block */
206045  #endif
206046  
206047  #endif /* _FTS5_H */
206048  
206049  /*
206050  ** 2014 May 31
206051  **
206052  ** The author disclaims copyright to this source code.  In place of
206053  ** a legal notice, here is a blessing:
206054  **
206055  **    May you do good and not evil.
206056  **    May you find forgiveness for yourself and forgive others.
206057  **    May you share freely, never taking more than you give.
206058  **
206059  ******************************************************************************
206060  **
206061  */
206062  #ifndef _FTS5INT_H
206063  #define _FTS5INT_H
206064  
206065  /* #include "fts5.h" */
206066  /* #include "sqlite3ext.h" */
206067  SQLITE_EXTENSION_INIT1
206068  
206069  /* #include <string.h> */
206070  /* #include <assert.h> */
206071  
206072  #ifndef SQLITE_AMALGAMATION
206073  
206074  typedef unsigned char  u8;
206075  typedef unsigned int   u32;
206076  typedef unsigned short u16;
206077  typedef short i16;
206078  typedef sqlite3_int64 i64;
206079  typedef sqlite3_uint64 u64;
206080  
206081  #ifndef ArraySize
206082  # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
206083  #endif
206084  
206085  #define testcase(x)
206086  #define ALWAYS(x) 1
206087  #define NEVER(x) 0
206088  
206089  #define MIN(x,y) (((x) < (y)) ? (x) : (y))
206090  #define MAX(x,y) (((x) > (y)) ? (x) : (y))
206091  
206092  /*
206093  ** Constants for the largest and smallest possible 64-bit signed integers.
206094  */
206095  # define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
206096  # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
206097  
206098  #endif
206099  
206100  /* Truncate very long tokens to this many bytes. Hard limit is 
206101  ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
206102  ** field that occurs at the start of each leaf page (see fts5_index.c). */
206103  #define FTS5_MAX_TOKEN_SIZE 32768
206104  
206105  /*
206106  ** Maximum number of prefix indexes on single FTS5 table. This must be
206107  ** less than 32. If it is set to anything large than that, an #error
206108  ** directive in fts5_index.c will cause the build to fail.
206109  */
206110  #define FTS5_MAX_PREFIX_INDEXES 31
206111  
206112  #define FTS5_DEFAULT_NEARDIST 10
206113  #define FTS5_DEFAULT_RANK     "bm25"
206114  
206115  /* Name of rank and rowid columns */
206116  #define FTS5_RANK_NAME "rank"
206117  #define FTS5_ROWID_NAME "rowid"
206118  
206119  #ifdef SQLITE_DEBUG
206120  # define FTS5_CORRUPT sqlite3Fts5Corrupt()
206121  static int sqlite3Fts5Corrupt(void);
206122  #else
206123  # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
206124  #endif
206125  
206126  /*
206127  ** The assert_nc() macro is similar to the assert() macro, except that it
206128  ** is used for assert() conditions that are true only if it can be 
206129  ** guranteed that the database is not corrupt.
206130  */
206131  #ifdef SQLITE_DEBUG
206132  SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
206133  # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
206134  #else
206135  # define assert_nc(x) assert(x)
206136  #endif
206137  
206138  /*
206139  ** A version of memcmp() that does not cause asan errors if one of the pointer
206140  ** parameters is NULL and the number of bytes to compare is zero.
206141  */
206142  #define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
206143  
206144  /* Mark a function parameter as unused, to suppress nuisance compiler
206145  ** warnings. */
206146  #ifndef UNUSED_PARAM
206147  # define UNUSED_PARAM(X)  (void)(X)
206148  #endif
206149  
206150  #ifndef UNUSED_PARAM2
206151  # define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
206152  #endif
206153  
206154  typedef struct Fts5Global Fts5Global;
206155  typedef struct Fts5Colset Fts5Colset;
206156  
206157  /* If a NEAR() clump or phrase may only match a specific set of columns, 
206158  ** then an object of the following type is used to record the set of columns.
206159  ** Each entry in the aiCol[] array is a column that may be matched.
206160  **
206161  ** This object is used by fts5_expr.c and fts5_index.c.
206162  */
206163  struct Fts5Colset {
206164    int nCol;
206165    int aiCol[1];
206166  };
206167  
206168  
206169  
206170  /**************************************************************************
206171  ** Interface to code in fts5_config.c. fts5_config.c contains contains code
206172  ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
206173  */
206174  
206175  typedef struct Fts5Config Fts5Config;
206176  
206177  /*
206178  ** An instance of the following structure encodes all information that can
206179  ** be gleaned from the CREATE VIRTUAL TABLE statement.
206180  **
206181  ** And all information loaded from the %_config table.
206182  **
206183  ** nAutomerge:
206184  **   The minimum number of segments that an auto-merge operation should
206185  **   attempt to merge together. A value of 1 sets the object to use the 
206186  **   compile time default. Zero disables auto-merge altogether.
206187  **
206188  ** zContent:
206189  **
206190  ** zContentRowid:
206191  **   The value of the content_rowid= option, if one was specified. Or 
206192  **   the string "rowid" otherwise. This text is not quoted - if it is
206193  **   used as part of an SQL statement it needs to be quoted appropriately.
206194  **
206195  ** zContentExprlist:
206196  **
206197  ** pzErrmsg:
206198  **   This exists in order to allow the fts5_index.c module to return a 
206199  **   decent error message if it encounters a file-format version it does
206200  **   not understand.
206201  **
206202  ** bColumnsize:
206203  **   True if the %_docsize table is created.
206204  **
206205  ** bPrefixIndex:
206206  **   This is only used for debugging. If set to false, any prefix indexes
206207  **   are ignored. This value is configured using:
206208  **
206209  **       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
206210  **
206211  */
206212  struct Fts5Config {
206213    sqlite3 *db;                    /* Database handle */
206214    char *zDb;                      /* Database holding FTS index (e.g. "main") */
206215    char *zName;                    /* Name of FTS index */
206216    int nCol;                       /* Number of columns */
206217    char **azCol;                   /* Column names */
206218    u8 *abUnindexed;                /* True for unindexed columns */
206219    int nPrefix;                    /* Number of prefix indexes */
206220    int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
206221    int eContent;                   /* An FTS5_CONTENT value */
206222    char *zContent;                 /* content table */ 
206223    char *zContentRowid;            /* "content_rowid=" option value */ 
206224    int bColumnsize;                /* "columnsize=" option value (dflt==1) */
206225    int eDetail;                    /* FTS5_DETAIL_XXX value */
206226    char *zContentExprlist;
206227    Fts5Tokenizer *pTok;
206228    fts5_tokenizer *pTokApi;
206229  
206230    /* Values loaded from the %_config table */
206231    int iCookie;                    /* Incremented when %_config is modified */
206232    int pgsz;                       /* Approximate page size used in %_data */
206233    int nAutomerge;                 /* 'automerge' setting */
206234    int nCrisisMerge;               /* Maximum allowed segments per level */
206235    int nUsermerge;                 /* 'usermerge' setting */
206236    int nHashSize;                  /* Bytes of memory for in-memory hash */
206237    char *zRank;                    /* Name of rank function */
206238    char *zRankArgs;                /* Arguments to rank function */
206239  
206240    /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
206241    char **pzErrmsg;
206242  
206243  #ifdef SQLITE_DEBUG
206244    int bPrefixIndex;               /* True to use prefix-indexes */
206245  #endif
206246  };
206247  
206248  /* Current expected value of %_config table 'version' field */
206249  #define FTS5_CURRENT_VERSION 4
206250  
206251  #define FTS5_CONTENT_NORMAL   0
206252  #define FTS5_CONTENT_NONE     1
206253  #define FTS5_CONTENT_EXTERNAL 2
206254  
206255  #define FTS5_DETAIL_FULL    0
206256  #define FTS5_DETAIL_NONE    1
206257  #define FTS5_DETAIL_COLUMNS 2
206258  
206259  
206260  
206261  static int sqlite3Fts5ConfigParse(
206262      Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
206263  );
206264  static void sqlite3Fts5ConfigFree(Fts5Config*);
206265  
206266  static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
206267  
206268  static int sqlite3Fts5Tokenize(
206269    Fts5Config *pConfig,            /* FTS5 Configuration object */
206270    int flags,                      /* FTS5_TOKENIZE_* flags */
206271    const char *pText, int nText,   /* Text to tokenize */
206272    void *pCtx,                     /* Context passed to xToken() */
206273    int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
206274  );
206275  
206276  static void sqlite3Fts5Dequote(char *z);
206277  
206278  /* Load the contents of the %_config table */
206279  static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
206280  
206281  /* Set the value of a single config attribute */
206282  static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
206283  
206284  static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
206285  
206286  /*
206287  ** End of interface to code in fts5_config.c.
206288  **************************************************************************/
206289  
206290  /**************************************************************************
206291  ** Interface to code in fts5_buffer.c.
206292  */
206293  
206294  /*
206295  ** Buffer object for the incremental building of string data.
206296  */
206297  typedef struct Fts5Buffer Fts5Buffer;
206298  struct Fts5Buffer {
206299    u8 *p;
206300    int n;
206301    int nSpace;
206302  };
206303  
206304  static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
206305  static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
206306  static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
206307  static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
206308  static void sqlite3Fts5BufferFree(Fts5Buffer*);
206309  static void sqlite3Fts5BufferZero(Fts5Buffer*);
206310  static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
206311  static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
206312  
206313  static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
206314  
206315  #define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
206316  #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
206317  #define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
206318  #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
206319  #define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
206320  
206321  #define fts5BufferGrow(pRc,pBuf,nn) ( \
206322    (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
206323      sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
206324  )
206325  
206326  /* Write and decode big-endian 32-bit integer values */
206327  static void sqlite3Fts5Put32(u8*, int);
206328  static int sqlite3Fts5Get32(const u8*);
206329  
206330  #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
206331  #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
206332  
206333  typedef struct Fts5PoslistReader Fts5PoslistReader;
206334  struct Fts5PoslistReader {
206335    /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
206336    const u8 *a;                    /* Position list to iterate through */
206337    int n;                          /* Size of buffer at a[] in bytes */
206338    int i;                          /* Current offset in a[] */
206339  
206340    u8 bFlag;                       /* For client use (any custom purpose) */
206341  
206342    /* Output variables */
206343    u8 bEof;                        /* Set to true at EOF */
206344    i64 iPos;                       /* (iCol<<32) + iPos */
206345  };
206346  static int sqlite3Fts5PoslistReaderInit(
206347    const u8 *a, int n,             /* Poslist buffer to iterate through */
206348    Fts5PoslistReader *pIter        /* Iterator object to initialize */
206349  );
206350  static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
206351  
206352  typedef struct Fts5PoslistWriter Fts5PoslistWriter;
206353  struct Fts5PoslistWriter {
206354    i64 iPrev;
206355  };
206356  static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
206357  static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
206358  
206359  static int sqlite3Fts5PoslistNext64(
206360    const u8 *a, int n,             /* Buffer containing poslist */
206361    int *pi,                        /* IN/OUT: Offset within a[] */
206362    i64 *piOff                      /* IN/OUT: Current offset */
206363  );
206364  
206365  /* Malloc utility */
206366  static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
206367  static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
206368  
206369  /* Character set tests (like isspace(), isalpha() etc.) */
206370  static int sqlite3Fts5IsBareword(char t);
206371  
206372  
206373  /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
206374  typedef struct Fts5Termset Fts5Termset;
206375  static int sqlite3Fts5TermsetNew(Fts5Termset**);
206376  static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
206377  static void sqlite3Fts5TermsetFree(Fts5Termset*);
206378  
206379  /*
206380  ** End of interface to code in fts5_buffer.c.
206381  **************************************************************************/
206382  
206383  /**************************************************************************
206384  ** Interface to code in fts5_index.c. fts5_index.c contains contains code
206385  ** to access the data stored in the %_data table.
206386  */
206387  
206388  typedef struct Fts5Index Fts5Index;
206389  typedef struct Fts5IndexIter Fts5IndexIter;
206390  
206391  struct Fts5IndexIter {
206392    i64 iRowid;
206393    const u8 *pData;
206394    int nData;
206395    u8 bEof;
206396  };
206397  
206398  #define sqlite3Fts5IterEof(x) ((x)->bEof)
206399  
206400  /*
206401  ** Values used as part of the flags argument passed to IndexQuery().
206402  */
206403  #define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
206404  #define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
206405  #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
206406  #define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
206407  
206408  /* The following are used internally by the fts5_index.c module. They are
206409  ** defined here only to make it easier to avoid clashes with the flags
206410  ** above. */
206411  #define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
206412  #define FTS5INDEX_QUERY_NOOUTPUT   0x0020
206413  
206414  /*
206415  ** Create/destroy an Fts5Index object.
206416  */
206417  static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
206418  static int sqlite3Fts5IndexClose(Fts5Index *p);
206419  
206420  /*
206421  ** Return a simple checksum value based on the arguments.
206422  */
206423  static u64 sqlite3Fts5IndexEntryCksum(
206424    i64 iRowid, 
206425    int iCol, 
206426    int iPos, 
206427    int iIdx,
206428    const char *pTerm,
206429    int nTerm
206430  );
206431  
206432  /*
206433  ** Argument p points to a buffer containing utf-8 text that is n bytes in 
206434  ** size. Return the number of bytes in the nChar character prefix of the
206435  ** buffer, or 0 if there are less than nChar characters in total.
206436  */
206437  static int sqlite3Fts5IndexCharlenToBytelen(
206438    const char *p, 
206439    int nByte, 
206440    int nChar
206441  );
206442  
206443  /*
206444  ** Open a new iterator to iterate though all rowids that match the 
206445  ** specified token or token prefix.
206446  */
206447  static int sqlite3Fts5IndexQuery(
206448    Fts5Index *p,                   /* FTS index to query */
206449    const char *pToken, int nToken, /* Token (or prefix) to query for */
206450    int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
206451    Fts5Colset *pColset,            /* Match these columns only */
206452    Fts5IndexIter **ppIter          /* OUT: New iterator object */
206453  );
206454  
206455  /*
206456  ** The various operations on open token or token prefix iterators opened
206457  ** using sqlite3Fts5IndexQuery().
206458  */
206459  static int sqlite3Fts5IterNext(Fts5IndexIter*);
206460  static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
206461  
206462  /*
206463  ** Close an iterator opened by sqlite3Fts5IndexQuery().
206464  */
206465  static void sqlite3Fts5IterClose(Fts5IndexIter*);
206466  
206467  /*
206468  ** This interface is used by the fts5vocab module.
206469  */
206470  static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
206471  static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
206472  
206473  
206474  /*
206475  ** Insert or remove data to or from the index. Each time a document is 
206476  ** added to or removed from the index, this function is called one or more
206477  ** times.
206478  **
206479  ** For an insert, it must be called once for each token in the new document.
206480  ** If the operation is a delete, it must be called (at least) once for each
206481  ** unique token in the document with an iCol value less than zero. The iPos
206482  ** argument is ignored for a delete.
206483  */
206484  static int sqlite3Fts5IndexWrite(
206485    Fts5Index *p,                   /* Index to write to */
206486    int iCol,                       /* Column token appears in (-ve -> delete) */
206487    int iPos,                       /* Position of token within column */
206488    const char *pToken, int nToken  /* Token to add or remove to or from index */
206489  );
206490  
206491  /*
206492  ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
206493  ** document iDocid.
206494  */
206495  static int sqlite3Fts5IndexBeginWrite(
206496    Fts5Index *p,                   /* Index to write to */
206497    int bDelete,                    /* True if current operation is a delete */
206498    i64 iDocid                      /* Docid to add or remove data from */
206499  );
206500  
206501  /*
206502  ** Flush any data stored in the in-memory hash tables to the database.
206503  ** Also close any open blob handles.
206504  */
206505  static int sqlite3Fts5IndexSync(Fts5Index *p);
206506  
206507  /*
206508  ** Discard any data stored in the in-memory hash tables. Do not write it
206509  ** to the database. Additionally, assume that the contents of the %_data
206510  ** table may have changed on disk. So any in-memory caches of %_data 
206511  ** records must be invalidated.
206512  */
206513  static int sqlite3Fts5IndexRollback(Fts5Index *p);
206514  
206515  /*
206516  ** Get or set the "averages" values.
206517  */
206518  static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
206519  static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
206520  
206521  /*
206522  ** Functions called by the storage module as part of integrity-check.
206523  */
206524  static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
206525  
206526  /* 
206527  ** Called during virtual module initialization to register UDF 
206528  ** fts5_decode() with SQLite 
206529  */
206530  static int sqlite3Fts5IndexInit(sqlite3*);
206531  
206532  static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
206533  
206534  /*
206535  ** Return the total number of entries read from the %_data table by 
206536  ** this connection since it was created.
206537  */
206538  static int sqlite3Fts5IndexReads(Fts5Index *p);
206539  
206540  static int sqlite3Fts5IndexReinit(Fts5Index *p);
206541  static int sqlite3Fts5IndexOptimize(Fts5Index *p);
206542  static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
206543  static int sqlite3Fts5IndexReset(Fts5Index *p);
206544  
206545  static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
206546  
206547  /*
206548  ** End of interface to code in fts5_index.c.
206549  **************************************************************************/
206550  
206551  /**************************************************************************
206552  ** Interface to code in fts5_varint.c. 
206553  */
206554  static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
206555  static int sqlite3Fts5GetVarintLen(u32 iVal);
206556  static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
206557  static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
206558  
206559  #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
206560  #define fts5GetVarint    sqlite3Fts5GetVarint
206561  
206562  #define fts5FastGetVarint32(a, iOff, nVal) {      \
206563    nVal = (a)[iOff++];                             \
206564    if( nVal & 0x80 ){                              \
206565      iOff--;                                       \
206566      iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
206567    }                                               \
206568  }
206569  
206570  
206571  /*
206572  ** End of interface to code in fts5_varint.c.
206573  **************************************************************************/
206574  
206575  
206576  /**************************************************************************
206577  ** Interface to code in fts5_main.c. 
206578  */
206579  
206580  /*
206581  ** Virtual-table object.
206582  */
206583  typedef struct Fts5Table Fts5Table;
206584  struct Fts5Table {
206585    sqlite3_vtab base;              /* Base class used by SQLite core */
206586    Fts5Config *pConfig;            /* Virtual table configuration */
206587    Fts5Index *pIndex;              /* Full-text index */
206588  };
206589  
206590  static int sqlite3Fts5GetTokenizer(
206591    Fts5Global*, 
206592    const char **azArg,
206593    int nArg,
206594    Fts5Tokenizer**,
206595    fts5_tokenizer**,
206596    char **pzErr
206597  );
206598  
206599  static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
206600  
206601  static int sqlite3Fts5FlushToDisk(Fts5Table*);
206602  
206603  /*
206604  ** End of interface to code in fts5.c.
206605  **************************************************************************/
206606  
206607  /**************************************************************************
206608  ** Interface to code in fts5_hash.c. 
206609  */
206610  typedef struct Fts5Hash Fts5Hash;
206611  
206612  /*
206613  ** Create a hash table, free a hash table.
206614  */
206615  static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
206616  static void sqlite3Fts5HashFree(Fts5Hash*);
206617  
206618  static int sqlite3Fts5HashWrite(
206619    Fts5Hash*,
206620    i64 iRowid,                     /* Rowid for this entry */
206621    int iCol,                       /* Column token appears in (-ve -> delete) */
206622    int iPos,                       /* Position of token within column */
206623    char bByte,
206624    const char *pToken, int nToken  /* Token to add or remove to or from index */
206625  );
206626  
206627  /*
206628  ** Empty (but do not delete) a hash table.
206629  */
206630  static void sqlite3Fts5HashClear(Fts5Hash*);
206631  
206632  static int sqlite3Fts5HashQuery(
206633    Fts5Hash*,                      /* Hash table to query */
206634    const char *pTerm, int nTerm,   /* Query term */
206635    const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
206636    int *pnDoclist                  /* OUT: Size of doclist in bytes */
206637  );
206638  
206639  static int sqlite3Fts5HashScanInit(
206640    Fts5Hash*,                      /* Hash table to query */
206641    const char *pTerm, int nTerm    /* Query prefix */
206642  );
206643  static void sqlite3Fts5HashScanNext(Fts5Hash*);
206644  static int sqlite3Fts5HashScanEof(Fts5Hash*);
206645  static void sqlite3Fts5HashScanEntry(Fts5Hash *,
206646    const char **pzTerm,            /* OUT: term (nul-terminated) */
206647    const u8 **ppDoclist,           /* OUT: pointer to doclist */
206648    int *pnDoclist                  /* OUT: size of doclist in bytes */
206649  );
206650  
206651  
206652  /*
206653  ** End of interface to code in fts5_hash.c.
206654  **************************************************************************/
206655  
206656  /**************************************************************************
206657  ** Interface to code in fts5_storage.c. fts5_storage.c contains contains 
206658  ** code to access the data stored in the %_content and %_docsize tables.
206659  */
206660  
206661  #define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
206662  #define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
206663  #define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
206664  
206665  typedef struct Fts5Storage Fts5Storage;
206666  
206667  static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
206668  static int sqlite3Fts5StorageClose(Fts5Storage *p);
206669  static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
206670  
206671  static int sqlite3Fts5DropAll(Fts5Config*);
206672  static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
206673  
206674  static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
206675  static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
206676  static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
206677  
206678  static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
206679  
206680  static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
206681  static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
206682  
206683  static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
206684  static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
206685  static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
206686  
206687  static int sqlite3Fts5StorageSync(Fts5Storage *p);
206688  static int sqlite3Fts5StorageRollback(Fts5Storage *p);
206689  
206690  static int sqlite3Fts5StorageConfigValue(
206691      Fts5Storage *p, const char*, sqlite3_value*, int
206692  );
206693  
206694  static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
206695  static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
206696  static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
206697  static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
206698  static int sqlite3Fts5StorageReset(Fts5Storage *p);
206699  
206700  /*
206701  ** End of interface to code in fts5_storage.c.
206702  **************************************************************************/
206703  
206704  
206705  /**************************************************************************
206706  ** Interface to code in fts5_expr.c. 
206707  */
206708  typedef struct Fts5Expr Fts5Expr;
206709  typedef struct Fts5ExprNode Fts5ExprNode;
206710  typedef struct Fts5Parse Fts5Parse;
206711  typedef struct Fts5Token Fts5Token;
206712  typedef struct Fts5ExprPhrase Fts5ExprPhrase;
206713  typedef struct Fts5ExprNearset Fts5ExprNearset;
206714  
206715  struct Fts5Token {
206716    const char *p;                  /* Token text (not NULL terminated) */
206717    int n;                          /* Size of buffer p in bytes */
206718  };
206719  
206720  /* Parse a MATCH expression. */
206721  static int sqlite3Fts5ExprNew(
206722    Fts5Config *pConfig, 
206723    int iCol,                       /* Column on LHS of MATCH operator */
206724    const char *zExpr,
206725    Fts5Expr **ppNew, 
206726    char **pzErr
206727  );
206728  
206729  /*
206730  ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
206731  **     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
206732  **     rc = sqlite3Fts5ExprNext(pExpr)
206733  ** ){
206734  **   // The document with rowid iRowid matches the expression!
206735  **   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
206736  ** }
206737  */
206738  static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
206739  static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
206740  static int sqlite3Fts5ExprEof(Fts5Expr*);
206741  static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
206742  
206743  static void sqlite3Fts5ExprFree(Fts5Expr*);
206744  
206745  /* Called during startup to register a UDF with SQLite */
206746  static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
206747  
206748  static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
206749  static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
206750  static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
206751  
206752  typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
206753  static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
206754  static int sqlite3Fts5ExprPopulatePoslists(
206755      Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
206756  );
206757  static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
206758  
206759  static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
206760  
206761  static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
206762  
206763  /*******************************************
206764  ** The fts5_expr.c API above this point is used by the other hand-written
206765  ** C code in this module. The interfaces below this point are called by
206766  ** the parser code in fts5parse.y.  */
206767  
206768  static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
206769  
206770  static Fts5ExprNode *sqlite3Fts5ParseNode(
206771    Fts5Parse *pParse,
206772    int eType,
206773    Fts5ExprNode *pLeft,
206774    Fts5ExprNode *pRight,
206775    Fts5ExprNearset *pNear
206776  );
206777  
206778  static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
206779    Fts5Parse *pParse,
206780    Fts5ExprNode *pLeft,
206781    Fts5ExprNode *pRight
206782  );
206783  
206784  static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
206785    Fts5Parse *pParse, 
206786    Fts5ExprPhrase *pPhrase, 
206787    Fts5Token *pToken,
206788    int bPrefix
206789  );
206790  
206791  static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
206792  
206793  static Fts5ExprNearset *sqlite3Fts5ParseNearset(
206794    Fts5Parse*, 
206795    Fts5ExprNearset*,
206796    Fts5ExprPhrase* 
206797  );
206798  
206799  static Fts5Colset *sqlite3Fts5ParseColset(
206800    Fts5Parse*, 
206801    Fts5Colset*, 
206802    Fts5Token *
206803  );
206804  
206805  static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
206806  static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
206807  static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
206808  
206809  static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
206810  static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
206811  static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
206812  static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
206813  static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
206814  
206815  /*
206816  ** End of interface to code in fts5_expr.c.
206817  **************************************************************************/
206818  
206819  
206820  
206821  /**************************************************************************
206822  ** Interface to code in fts5_aux.c. 
206823  */
206824  
206825  static int sqlite3Fts5AuxInit(fts5_api*);
206826  /*
206827  ** End of interface to code in fts5_aux.c.
206828  **************************************************************************/
206829  
206830  /**************************************************************************
206831  ** Interface to code in fts5_tokenizer.c. 
206832  */
206833  
206834  static int sqlite3Fts5TokenizerInit(fts5_api*);
206835  /*
206836  ** End of interface to code in fts5_tokenizer.c.
206837  **************************************************************************/
206838  
206839  /**************************************************************************
206840  ** Interface to code in fts5_vocab.c. 
206841  */
206842  
206843  static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
206844  
206845  /*
206846  ** End of interface to code in fts5_vocab.c.
206847  **************************************************************************/
206848  
206849  
206850  /**************************************************************************
206851  ** Interface to automatically generated code in fts5_unicode2.c. 
206852  */
206853  static int sqlite3Fts5UnicodeIsdiacritic(int c);
206854  static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
206855  
206856  static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
206857  static int sqlite3Fts5UnicodeCategory(u32 iCode);
206858  static void sqlite3Fts5UnicodeAscii(u8*, u8*);
206859  /*
206860  ** End of interface to code in fts5_unicode2.c.
206861  **************************************************************************/
206862  
206863  #endif
206864  
206865  #define FTS5_OR                               1
206866  #define FTS5_AND                              2
206867  #define FTS5_NOT                              3
206868  #define FTS5_TERM                             4
206869  #define FTS5_COLON                            5
206870  #define FTS5_MINUS                            6
206871  #define FTS5_LCP                              7
206872  #define FTS5_RCP                              8
206873  #define FTS5_STRING                           9
206874  #define FTS5_LP                              10
206875  #define FTS5_RP                              11
206876  #define FTS5_CARET                           12
206877  #define FTS5_COMMA                           13
206878  #define FTS5_PLUS                            14
206879  #define FTS5_STAR                            15
206880  
206881  /*
206882  ** 2000-05-29
206883  **
206884  ** The author disclaims copyright to this source code.  In place of
206885  ** a legal notice, here is a blessing:
206886  **
206887  **    May you do good and not evil.
206888  **    May you find forgiveness for yourself and forgive others.
206889  **    May you share freely, never taking more than you give.
206890  **
206891  *************************************************************************
206892  ** Driver template for the LEMON parser generator.
206893  **
206894  ** The "lemon" program processes an LALR(1) input grammar file, then uses
206895  ** this template to construct a parser.  The "lemon" program inserts text
206896  ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
206897  ** interstitial "-" characters) contained in this template is changed into
206898  ** the value of the %name directive from the grammar.  Otherwise, the content
206899  ** of this template is copied straight through into the generate parser
206900  ** source file.
206901  **
206902  ** The following is the concatenation of all %include directives from the
206903  ** input grammar file:
206904  */
206905  /* #include <stdio.h> */
206906  /* #include <assert.h> */
206907  /************ Begin %include sections from the grammar ************************/
206908  
206909  /* #include "fts5Int.h" */
206910  /* #include "fts5parse.h" */
206911  
206912  /*
206913  ** Disable all error recovery processing in the parser push-down
206914  ** automaton.
206915  */
206916  #define fts5YYNOERRORRECOVERY 1
206917  
206918  /*
206919  ** Make fts5yytestcase() the same as testcase()
206920  */
206921  #define fts5yytestcase(X) testcase(X)
206922  
206923  /*
206924  ** Indicate that sqlite3ParserFree() will never be called with a null
206925  ** pointer.
206926  */
206927  #define fts5YYPARSEFREENOTNULL 1
206928  
206929  /*
206930  ** Alternative datatype for the argument to the malloc() routine passed
206931  ** into sqlite3ParserAlloc().  The default is size_t.
206932  */
206933  #define fts5YYMALLOCARGTYPE  u64
206934  
206935  /**************** End of %include directives **********************************/
206936  /* These constants specify the various numeric values for terminal symbols
206937  ** in a format understandable to "makeheaders".  This section is blank unless
206938  ** "lemon" is run with the "-m" command-line option.
206939  ***************** Begin makeheaders token definitions *************************/
206940  /**************** End makeheaders token definitions ***************************/
206941  
206942  /* The next sections is a series of control #defines.
206943  ** various aspects of the generated parser.
206944  **    fts5YYCODETYPE         is the data type used to store the integer codes
206945  **                       that represent terminal and non-terminal symbols.
206946  **                       "unsigned char" is used if there are fewer than
206947  **                       256 symbols.  Larger types otherwise.
206948  **    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
206949  **                       any terminal or nonterminal symbol.
206950  **    fts5YYFALLBACK         If defined, this indicates that one or more tokens
206951  **                       (also known as: "terminal symbols") have fall-back
206952  **                       values which should be used if the original symbol
206953  **                       would not parse.  This permits keywords to sometimes
206954  **                       be used as identifiers, for example.
206955  **    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
206956  **                       that indicate what to do in response to the next
206957  **                       token.
206958  **    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
206959  **                       symbols.  Background: A "minor type" is a semantic
206960  **                       value associated with a terminal or non-terminal
206961  **                       symbols.  For example, for an "ID" terminal symbol,
206962  **                       the minor type might be the name of the identifier.
206963  **                       Each non-terminal can have a different minor type.
206964  **                       Terminal symbols all have the same minor type, though.
206965  **                       This macros defines the minor type for terminal 
206966  **                       symbols.
206967  **    fts5YYMINORTYPE        is the data type used for all minor types.
206968  **                       This is typically a union of many types, one of
206969  **                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
206970  **                       for terminal symbols is called "fts5yy0".
206971  **    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
206972  **                       zero the stack is dynamically sized using realloc()
206973  **    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
206974  **    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
206975  **    sqlite3Fts5ParserARG_PARAM     Code to pass %extra_argument as a subroutine parameter
206976  **    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
206977  **    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
206978  **    sqlite3Fts5ParserCTX_*         As sqlite3Fts5ParserARG_ except for %extra_context
206979  **    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
206980  **                       defined, then do no error processing.
206981  **    fts5YYNSTATE           the combined number of states.
206982  **    fts5YYNRULE            the number of rules in the grammar
206983  **    fts5YYNFTS5TOKEN           Number of terminal symbols
206984  **    fts5YY_MAX_SHIFT       Maximum value for shift actions
206985  **    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
206986  **    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
206987  **    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
206988  **    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
206989  **    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
206990  **    fts5YY_MIN_REDUCE      Minimum value for reduce actions
206991  **    fts5YY_MAX_REDUCE      Maximum value for reduce actions
206992  */
206993  #ifndef INTERFACE
206994  # define INTERFACE 1
206995  #endif
206996  /************* Begin control #defines *****************************************/
206997  #define fts5YYCODETYPE unsigned char
206998  #define fts5YYNOCODE 27
206999  #define fts5YYACTIONTYPE unsigned char
207000  #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
207001  typedef union {
207002    int fts5yyinit;
207003    sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
207004    int fts5yy4;
207005    Fts5Colset* fts5yy11;
207006    Fts5ExprNode* fts5yy24;
207007    Fts5ExprNearset* fts5yy46;
207008    Fts5ExprPhrase* fts5yy53;
207009  } fts5YYMINORTYPE;
207010  #ifndef fts5YYSTACKDEPTH
207011  #define fts5YYSTACKDEPTH 100
207012  #endif
207013  #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
207014  #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
207015  #define sqlite3Fts5ParserARG_PARAM ,pParse
207016  #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
207017  #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
207018  #define sqlite3Fts5ParserCTX_SDECL
207019  #define sqlite3Fts5ParserCTX_PDECL
207020  #define sqlite3Fts5ParserCTX_PARAM
207021  #define sqlite3Fts5ParserCTX_FETCH
207022  #define sqlite3Fts5ParserCTX_STORE
207023  #define fts5YYNSTATE             35
207024  #define fts5YYNRULE              28
207025  #define fts5YYNFTS5TOKEN             16
207026  #define fts5YY_MAX_SHIFT         34
207027  #define fts5YY_MIN_SHIFTREDUCE   52
207028  #define fts5YY_MAX_SHIFTREDUCE   79
207029  #define fts5YY_ERROR_ACTION      80
207030  #define fts5YY_ACCEPT_ACTION     81
207031  #define fts5YY_NO_ACTION         82
207032  #define fts5YY_MIN_REDUCE        83
207033  #define fts5YY_MAX_REDUCE        110
207034  /************* End control #defines *******************************************/
207035  #define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
207036  
207037  /* Define the fts5yytestcase() macro to be a no-op if is not already defined
207038  ** otherwise.
207039  **
207040  ** Applications can choose to define fts5yytestcase() in the %include section
207041  ** to a macro that can assist in verifying code coverage.  For production
207042  ** code the fts5yytestcase() macro should be turned off.  But it is useful
207043  ** for testing.
207044  */
207045  #ifndef fts5yytestcase
207046  # define fts5yytestcase(X)
207047  #endif
207048  
207049  
207050  /* Next are the tables used to determine what action to take based on the
207051  ** current state and lookahead token.  These tables are used to implement
207052  ** functions that take a state number and lookahead value and return an
207053  ** action integer.  
207054  **
207055  ** Suppose the action integer is N.  Then the action is determined as
207056  ** follows
207057  **
207058  **   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
207059  **                                      token onto the stack and goto state N.
207060  **
207061  **   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
207062  **     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
207063  **
207064  **   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
207065  **
207066  **   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
207067  **
207068  **   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
207069  **                                      slots in the fts5yy_action[] table.
207070  **
207071  **   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
207072  **     and fts5YY_MAX_REDUCE
207073  **
207074  ** The action table is constructed as a single large table named fts5yy_action[].
207075  ** Given state S and lookahead X, the action is computed as either:
207076  **
207077  **    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
207078  **    (B)   N = fts5yy_default[S]
207079  **
207080  ** The (A) formula is preferred.  The B formula is used instead if
207081  ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
207082  **
207083  ** The formulas above are for computing the action when the lookahead is
207084  ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
207085  ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
207086  ** the fts5yy_shift_ofst[] array.
207087  **
207088  ** The following are the tables generated in this section:
207089  **
207090  **  fts5yy_action[]        A single table containing all actions.
207091  **  fts5yy_lookahead[]     A table containing the lookahead for each entry in
207092  **                     fts5yy_action.  Used to detect hash collisions.
207093  **  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
207094  **                     shifting terminals.
207095  **  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
207096  **                     shifting non-terminals after a reduce.
207097  **  fts5yy_default[]       Default action for each state.
207098  **
207099  *********** Begin parsing tables **********************************************/
207100  #define fts5YY_ACTTAB_COUNT (105)
207101  static const fts5YYACTIONTYPE fts5yy_action[] = {
207102   /*     0 */    81,   20,   96,    6,   28,   99,   98,   26,   26,   18,
207103   /*    10 */    96,    6,   28,   17,   98,   56,   26,   19,   96,    6,
207104   /*    20 */    28,   14,   98,   14,   26,   31,   92,   96,    6,   28,
207105   /*    30 */   108,   98,   25,   26,   21,   96,    6,   28,   78,   98,
207106   /*    40 */    58,   26,   29,   96,    6,   28,  107,   98,   22,   26,
207107   /*    50 */    24,   16,   12,   11,    1,   13,   13,   24,   16,   23,
207108   /*    60 */    11,   33,   34,   13,   97,    8,   27,   32,   98,    7,
207109   /*    70 */    26,    3,    4,    5,    3,    4,    5,    3,   83,    4,
207110   /*    80 */     5,    3,   63,    5,    3,   62,   12,    2,   86,   13,
207111   /*    90 */     9,   30,   10,   10,   54,   57,   75,   78,   78,   53,
207112   /*   100 */    57,   15,   82,   82,   71,
207113  };
207114  static const fts5YYCODETYPE fts5yy_lookahead[] = {
207115   /*     0 */    16,   17,   18,   19,   20,   22,   22,   24,   24,   17,
207116   /*    10 */    18,   19,   20,    7,   22,    9,   24,   17,   18,   19,
207117   /*    20 */    20,    9,   22,    9,   24,   13,   17,   18,   19,   20,
207118   /*    30 */    26,   22,   24,   24,   17,   18,   19,   20,   15,   22,
207119   /*    40 */     9,   24,   17,   18,   19,   20,   26,   22,   21,   24,
207120   /*    50 */     6,    7,    9,    9,   10,   12,   12,    6,    7,   21,
207121   /*    60 */     9,   24,   25,   12,   18,    5,   20,   14,   22,    5,
207122   /*    70 */    24,    3,    1,    2,    3,    1,    2,    3,    0,    1,
207123   /*    80 */     2,    3,   11,    2,    3,   11,    9,   10,    5,   12,
207124   /*    90 */    23,   24,   10,   10,    8,    9,    9,   15,   15,    8,
207125   /*   100 */     9,    9,   27,   27,   11,   27,   27,   27,   27,   27,
207126   /*   110 */    27,   27,   27,   27,   27,   27,   27,   27,   27,   27,
207127   /*   120 */    27,
207128  };
207129  #define fts5YY_SHIFT_COUNT    (34)
207130  #define fts5YY_SHIFT_MIN      (0)
207131  #define fts5YY_SHIFT_MAX      (93)
207132  static const unsigned char fts5yy_shift_ofst[] = {
207133   /*     0 */    44,   44,   44,   44,   44,   44,   51,   77,   43,   12,
207134   /*    10 */    14,   83,   82,   14,   23,   23,   31,   31,   71,   74,
207135   /*    20 */    78,   81,   86,   91,    6,   53,   53,   60,   64,   68,
207136   /*    30 */    53,   87,   92,   53,   93,
207137  };
207138  #define fts5YY_REDUCE_COUNT (17)
207139  #define fts5YY_REDUCE_MIN   (-17)
207140  #define fts5YY_REDUCE_MAX   (67)
207141  static const signed char fts5yy_reduce_ofst[] = {
207142   /*     0 */   -16,   -8,    0,    9,   17,   25,   46,  -17,  -17,   37,
207143   /*    10 */    67,    4,    4,    8,    4,   20,   27,   38,
207144  };
207145  static const fts5YYACTIONTYPE fts5yy_default[] = {
207146   /*     0 */    80,   80,   80,   80,   80,   80,   95,   80,   80,  105,
207147   /*    10 */    80,  110,  110,   80,  110,  110,   80,   80,   80,   80,
207148   /*    20 */    80,   91,   80,   80,   80,  101,  100,   80,   80,   90,
207149   /*    30 */   103,   80,   80,  104,   80,
207150  };
207151  /********** End of lemon-generated parsing tables *****************************/
207152  
207153  /* The next table maps tokens (terminal symbols) into fallback tokens.  
207154  ** If a construct like the following:
207155  ** 
207156  **      %fallback ID X Y Z.
207157  **
207158  ** appears in the grammar, then ID becomes a fallback token for X, Y,
207159  ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
207160  ** but it does not parse, the type of the token is changed to ID and
207161  ** the parse is retried before an error is thrown.
207162  **
207163  ** This feature can be used, for example, to cause some keywords in a language
207164  ** to revert to identifiers if they keyword does not apply in the context where
207165  ** it appears.
207166  */
207167  #ifdef fts5YYFALLBACK
207168  static const fts5YYCODETYPE fts5yyFallback[] = {
207169  };
207170  #endif /* fts5YYFALLBACK */
207171  
207172  /* The following structure represents a single element of the
207173  ** parser's stack.  Information stored includes:
207174  **
207175  **   +  The state number for the parser at this level of the stack.
207176  **
207177  **   +  The value of the token stored at this level of the stack.
207178  **      (In other words, the "major" token.)
207179  **
207180  **   +  The semantic value stored at this level of the stack.  This is
207181  **      the information used by the action routines in the grammar.
207182  **      It is sometimes called the "minor" token.
207183  **
207184  ** After the "shift" half of a SHIFTREDUCE action, the stateno field
207185  ** actually contains the reduce action for the second half of the
207186  ** SHIFTREDUCE.
207187  */
207188  struct fts5yyStackEntry {
207189    fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
207190    fts5YYCODETYPE major;      /* The major token value.  This is the code
207191                           ** number for the token at this stack level */
207192    fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
207193                           ** is the value of the token  */
207194  };
207195  typedef struct fts5yyStackEntry fts5yyStackEntry;
207196  
207197  /* The state of the parser is completely contained in an instance of
207198  ** the following structure */
207199  struct fts5yyParser {
207200    fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
207201  #ifdef fts5YYTRACKMAXSTACKDEPTH
207202    int fts5yyhwm;                    /* High-water mark of the stack */
207203  #endif
207204  #ifndef fts5YYNOERRORRECOVERY
207205    int fts5yyerrcnt;                 /* Shifts left before out of the error */
207206  #endif
207207    sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
207208    sqlite3Fts5ParserCTX_SDECL                /* A place to hold %extra_context */
207209  #if fts5YYSTACKDEPTH<=0
207210    int fts5yystksz;                  /* Current side of the stack */
207211    fts5yyStackEntry *fts5yystack;        /* The parser's stack */
207212    fts5yyStackEntry fts5yystk0;          /* First stack entry */
207213  #else
207214    fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
207215    fts5yyStackEntry *fts5yystackEnd;            /* Last entry in the stack */
207216  #endif
207217  };
207218  typedef struct fts5yyParser fts5yyParser;
207219  
207220  #ifndef NDEBUG
207221  /* #include <stdio.h> */
207222  static FILE *fts5yyTraceFILE = 0;
207223  static char *fts5yyTracePrompt = 0;
207224  #endif /* NDEBUG */
207225  
207226  #ifndef NDEBUG
207227  /* 
207228  ** Turn parser tracing on by giving a stream to which to write the trace
207229  ** and a prompt to preface each trace message.  Tracing is turned off
207230  ** by making either argument NULL 
207231  **
207232  ** Inputs:
207233  ** <ul>
207234  ** <li> A FILE* to which trace output should be written.
207235  **      If NULL, then tracing is turned off.
207236  ** <li> A prefix string written at the beginning of every
207237  **      line of trace output.  If NULL, then tracing is
207238  **      turned off.
207239  ** </ul>
207240  **
207241  ** Outputs:
207242  ** None.
207243  */
207244  static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
207245    fts5yyTraceFILE = TraceFILE;
207246    fts5yyTracePrompt = zTracePrompt;
207247    if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
207248    else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
207249  }
207250  #endif /* NDEBUG */
207251  
207252  #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
207253  /* For tracing shifts, the names of all terminals and nonterminals
207254  ** are required.  The following table supplies these names */
207255  static const char *const fts5yyTokenName[] = { 
207256    /*    0 */ "$",
207257    /*    1 */ "OR",
207258    /*    2 */ "AND",
207259    /*    3 */ "NOT",
207260    /*    4 */ "TERM",
207261    /*    5 */ "COLON",
207262    /*    6 */ "MINUS",
207263    /*    7 */ "LCP",
207264    /*    8 */ "RCP",
207265    /*    9 */ "STRING",
207266    /*   10 */ "LP",
207267    /*   11 */ "RP",
207268    /*   12 */ "CARET",
207269    /*   13 */ "COMMA",
207270    /*   14 */ "PLUS",
207271    /*   15 */ "STAR",
207272    /*   16 */ "input",
207273    /*   17 */ "expr",
207274    /*   18 */ "cnearset",
207275    /*   19 */ "exprlist",
207276    /*   20 */ "colset",
207277    /*   21 */ "colsetlist",
207278    /*   22 */ "nearset",
207279    /*   23 */ "nearphrases",
207280    /*   24 */ "phrase",
207281    /*   25 */ "neardist_opt",
207282    /*   26 */ "star_opt",
207283  };
207284  #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
207285  
207286  #ifndef NDEBUG
207287  /* For tracing reduce actions, the names of all rules are required.
207288  */
207289  static const char *const fts5yyRuleName[] = {
207290   /*   0 */ "input ::= expr",
207291   /*   1 */ "colset ::= MINUS LCP colsetlist RCP",
207292   /*   2 */ "colset ::= LCP colsetlist RCP",
207293   /*   3 */ "colset ::= STRING",
207294   /*   4 */ "colset ::= MINUS STRING",
207295   /*   5 */ "colsetlist ::= colsetlist STRING",
207296   /*   6 */ "colsetlist ::= STRING",
207297   /*   7 */ "expr ::= expr AND expr",
207298   /*   8 */ "expr ::= expr OR expr",
207299   /*   9 */ "expr ::= expr NOT expr",
207300   /*  10 */ "expr ::= colset COLON LP expr RP",
207301   /*  11 */ "expr ::= LP expr RP",
207302   /*  12 */ "expr ::= exprlist",
207303   /*  13 */ "exprlist ::= cnearset",
207304   /*  14 */ "exprlist ::= exprlist cnearset",
207305   /*  15 */ "cnearset ::= nearset",
207306   /*  16 */ "cnearset ::= colset COLON nearset",
207307   /*  17 */ "nearset ::= phrase",
207308   /*  18 */ "nearset ::= CARET phrase",
207309   /*  19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
207310   /*  20 */ "nearphrases ::= phrase",
207311   /*  21 */ "nearphrases ::= nearphrases phrase",
207312   /*  22 */ "neardist_opt ::=",
207313   /*  23 */ "neardist_opt ::= COMMA STRING",
207314   /*  24 */ "phrase ::= phrase PLUS STRING star_opt",
207315   /*  25 */ "phrase ::= STRING star_opt",
207316   /*  26 */ "star_opt ::= STAR",
207317   /*  27 */ "star_opt ::=",
207318  };
207319  #endif /* NDEBUG */
207320  
207321  
207322  #if fts5YYSTACKDEPTH<=0
207323  /*
207324  ** Try to increase the size of the parser stack.  Return the number
207325  ** of errors.  Return 0 on success.
207326  */
207327  static int fts5yyGrowStack(fts5yyParser *p){
207328    int newSize;
207329    int idx;
207330    fts5yyStackEntry *pNew;
207331  
207332    newSize = p->fts5yystksz*2 + 100;
207333    idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
207334    if( p->fts5yystack==&p->fts5yystk0 ){
207335      pNew = malloc(newSize*sizeof(pNew[0]));
207336      if( pNew ) pNew[0] = p->fts5yystk0;
207337    }else{
207338      pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
207339    }
207340    if( pNew ){
207341      p->fts5yystack = pNew;
207342      p->fts5yytos = &p->fts5yystack[idx];
207343  #ifndef NDEBUG
207344      if( fts5yyTraceFILE ){
207345        fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
207346                fts5yyTracePrompt, p->fts5yystksz, newSize);
207347      }
207348  #endif
207349      p->fts5yystksz = newSize;
207350    }
207351    return pNew==0; 
207352  }
207353  #endif
207354  
207355  /* Datatype of the argument to the memory allocated passed as the
207356  ** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
207357  ** putting an appropriate #define in the %include section of the input
207358  ** grammar.
207359  */
207360  #ifndef fts5YYMALLOCARGTYPE
207361  # define fts5YYMALLOCARGTYPE size_t
207362  #endif
207363  
207364  /* Initialize a new parser that has already been allocated.
207365  */
207366  static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
207367    fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
207368    sqlite3Fts5ParserCTX_STORE
207369  #ifdef fts5YYTRACKMAXSTACKDEPTH
207370    fts5yypParser->fts5yyhwm = 0;
207371  #endif
207372  #if fts5YYSTACKDEPTH<=0
207373    fts5yypParser->fts5yytos = NULL;
207374    fts5yypParser->fts5yystack = NULL;
207375    fts5yypParser->fts5yystksz = 0;
207376    if( fts5yyGrowStack(fts5yypParser) ){
207377      fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
207378      fts5yypParser->fts5yystksz = 1;
207379    }
207380  #endif
207381  #ifndef fts5YYNOERRORRECOVERY
207382    fts5yypParser->fts5yyerrcnt = -1;
207383  #endif
207384    fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
207385    fts5yypParser->fts5yystack[0].stateno = 0;
207386    fts5yypParser->fts5yystack[0].major = 0;
207387  #if fts5YYSTACKDEPTH>0
207388    fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
207389  #endif
207390  }
207391  
207392  #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
207393  /* 
207394  ** This function allocates a new parser.
207395  ** The only argument is a pointer to a function which works like
207396  ** malloc.
207397  **
207398  ** Inputs:
207399  ** A pointer to the function used to allocate memory.
207400  **
207401  ** Outputs:
207402  ** A pointer to a parser.  This pointer is used in subsequent calls
207403  ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
207404  */
207405  static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
207406    fts5yyParser *fts5yypParser;
207407    fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
207408    if( fts5yypParser ){
207409      sqlite3Fts5ParserCTX_STORE
207410      sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
207411    }
207412    return (void*)fts5yypParser;
207413  }
207414  #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
207415  
207416  
207417  /* The following function deletes the "minor type" or semantic value
207418  ** associated with a symbol.  The symbol can be either a terminal
207419  ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
207420  ** a pointer to the value to be deleted.  The code used to do the 
207421  ** deletions is derived from the %destructor and/or %token_destructor
207422  ** directives of the input grammar.
207423  */
207424  static void fts5yy_destructor(
207425    fts5yyParser *fts5yypParser,    /* The parser */
207426    fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
207427    fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
207428  ){
207429    sqlite3Fts5ParserARG_FETCH
207430    sqlite3Fts5ParserCTX_FETCH
207431    switch( fts5yymajor ){
207432      /* Here is inserted the actions which take place when a
207433      ** terminal or non-terminal is destroyed.  This can happen
207434      ** when the symbol is popped from the stack during a
207435      ** reduce or during error processing or when a parser is 
207436      ** being destroyed before it is finished parsing.
207437      **
207438      ** Note: during a reduce, the only symbols destroyed are those
207439      ** which appear on the RHS of the rule, but which are *not* used
207440      ** inside the C code.
207441      */
207442  /********* Begin destructor definitions ***************************************/
207443      case 16: /* input */
207444  {
207445   (void)pParse; 
207446  }
207447        break;
207448      case 17: /* expr */
207449      case 18: /* cnearset */
207450      case 19: /* exprlist */
207451  {
207452   sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); 
207453  }
207454        break;
207455      case 20: /* colset */
207456      case 21: /* colsetlist */
207457  {
207458   sqlite3_free((fts5yypminor->fts5yy11)); 
207459  }
207460        break;
207461      case 22: /* nearset */
207462      case 23: /* nearphrases */
207463  {
207464   sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); 
207465  }
207466        break;
207467      case 24: /* phrase */
207468  {
207469   sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); 
207470  }
207471        break;
207472  /********* End destructor definitions *****************************************/
207473      default:  break;   /* If no destructor action specified: do nothing */
207474    }
207475  }
207476  
207477  /*
207478  ** Pop the parser's stack once.
207479  **
207480  ** If there is a destructor routine associated with the token which
207481  ** is popped from the stack, then call it.
207482  */
207483  static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
207484    fts5yyStackEntry *fts5yytos;
207485    assert( pParser->fts5yytos!=0 );
207486    assert( pParser->fts5yytos > pParser->fts5yystack );
207487    fts5yytos = pParser->fts5yytos--;
207488  #ifndef NDEBUG
207489    if( fts5yyTraceFILE ){
207490      fprintf(fts5yyTraceFILE,"%sPopping %s\n",
207491        fts5yyTracePrompt,
207492        fts5yyTokenName[fts5yytos->major]);
207493    }
207494  #endif
207495    fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
207496  }
207497  
207498  /*
207499  ** Clear all secondary memory allocations from the parser
207500  */
207501  static void sqlite3Fts5ParserFinalize(void *p){
207502    fts5yyParser *pParser = (fts5yyParser*)p;
207503    while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
207504  #if fts5YYSTACKDEPTH<=0
207505    if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
207506  #endif
207507  }
207508  
207509  #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
207510  /* 
207511  ** Deallocate and destroy a parser.  Destructors are called for
207512  ** all stack elements before shutting the parser down.
207513  **
207514  ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
207515  ** is defined in a %include section of the input grammar) then it is
207516  ** assumed that the input pointer is never NULL.
207517  */
207518  static void sqlite3Fts5ParserFree(
207519    void *p,                    /* The parser to be deleted */
207520    void (*freeProc)(void*)     /* Function used to reclaim memory */
207521  ){
207522  #ifndef fts5YYPARSEFREENEVERNULL
207523    if( p==0 ) return;
207524  #endif
207525    sqlite3Fts5ParserFinalize(p);
207526    (*freeProc)(p);
207527  }
207528  #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
207529  
207530  /*
207531  ** Return the peak depth of the stack for a parser.
207532  */
207533  #ifdef fts5YYTRACKMAXSTACKDEPTH
207534  static int sqlite3Fts5ParserStackPeak(void *p){
207535    fts5yyParser *pParser = (fts5yyParser*)p;
207536    return pParser->fts5yyhwm;
207537  }
207538  #endif
207539  
207540  /* This array of booleans keeps track of the parser statement
207541  ** coverage.  The element fts5yycoverage[X][Y] is set when the parser
207542  ** is in state X and has a lookahead token Y.  In a well-tested
207543  ** systems, every element of this matrix should end up being set.
207544  */
207545  #if defined(fts5YYCOVERAGE)
207546  static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
207547  #endif
207548  
207549  /*
207550  ** Write into out a description of every state/lookahead combination that
207551  **
207552  **   (1)  has not been used by the parser, and
207553  **   (2)  is not a syntax error.
207554  **
207555  ** Return the number of missed state/lookahead combinations.
207556  */
207557  #if defined(fts5YYCOVERAGE)
207558  static int sqlite3Fts5ParserCoverage(FILE *out){
207559    int stateno, iLookAhead, i;
207560    int nMissed = 0;
207561    for(stateno=0; stateno<fts5YYNSTATE; stateno++){
207562      i = fts5yy_shift_ofst[stateno];
207563      for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
207564        if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
207565        if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
207566        if( out ){
207567          fprintf(out,"State %d lookahead %s %s\n", stateno,
207568                  fts5yyTokenName[iLookAhead],
207569                  fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
207570        }
207571      }
207572    }
207573    return nMissed;
207574  }
207575  #endif
207576  
207577  /*
207578  ** Find the appropriate action for a parser given the terminal
207579  ** look-ahead token iLookAhead.
207580  */
207581  static fts5YYACTIONTYPE fts5yy_find_shift_action(
207582    fts5YYCODETYPE iLookAhead,    /* The look-ahead token */
207583    fts5YYACTIONTYPE stateno      /* Current state number */
207584  ){
207585    int i;
207586  
207587    if( stateno>fts5YY_MAX_SHIFT ) return stateno;
207588    assert( stateno <= fts5YY_SHIFT_COUNT );
207589  #if defined(fts5YYCOVERAGE)
207590    fts5yycoverage[stateno][iLookAhead] = 1;
207591  #endif
207592    do{
207593      i = fts5yy_shift_ofst[stateno];
207594      assert( i>=0 );
207595      /* assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD ); */
207596      assert( iLookAhead!=fts5YYNOCODE );
207597      assert( iLookAhead < fts5YYNFTS5TOKEN );
207598      i += iLookAhead;
207599      if( i>=fts5YY_NLOOKAHEAD || fts5yy_lookahead[i]!=iLookAhead ){
207600  #ifdef fts5YYFALLBACK
207601        fts5YYCODETYPE iFallback;            /* Fallback token */
207602        if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
207603               && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
207604  #ifndef NDEBUG
207605          if( fts5yyTraceFILE ){
207606            fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
207607               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
207608          }
207609  #endif
207610          assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
207611          iLookAhead = iFallback;
207612          continue;
207613        }
207614  #endif
207615  #ifdef fts5YYWILDCARD
207616        {
207617          int j = i - iLookAhead + fts5YYWILDCARD;
207618          if( 
207619  #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
207620            j>=0 &&
207621  #endif
207622  #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
207623            j<fts5YY_ACTTAB_COUNT &&
207624  #endif
207625            j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) &&
207626            fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
207627          ){
207628  #ifndef NDEBUG
207629            if( fts5yyTraceFILE ){
207630              fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
207631                 fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
207632                 fts5yyTokenName[fts5YYWILDCARD]);
207633            }
207634  #endif /* NDEBUG */
207635            return fts5yy_action[j];
207636          }
207637        }
207638  #endif /* fts5YYWILDCARD */
207639        return fts5yy_default[stateno];
207640      }else{
207641        return fts5yy_action[i];
207642      }
207643    }while(1);
207644  }
207645  
207646  /*
207647  ** Find the appropriate action for a parser given the non-terminal
207648  ** look-ahead token iLookAhead.
207649  */
207650  static fts5YYACTIONTYPE fts5yy_find_reduce_action(
207651    fts5YYACTIONTYPE stateno,     /* Current state number */
207652    fts5YYCODETYPE iLookAhead     /* The look-ahead token */
207653  ){
207654    int i;
207655  #ifdef fts5YYERRORSYMBOL
207656    if( stateno>fts5YY_REDUCE_COUNT ){
207657      return fts5yy_default[stateno];
207658    }
207659  #else
207660    assert( stateno<=fts5YY_REDUCE_COUNT );
207661  #endif
207662    i = fts5yy_reduce_ofst[stateno];
207663    assert( iLookAhead!=fts5YYNOCODE );
207664    i += iLookAhead;
207665  #ifdef fts5YYERRORSYMBOL
207666    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
207667      return fts5yy_default[stateno];
207668    }
207669  #else
207670    assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
207671    assert( fts5yy_lookahead[i]==iLookAhead );
207672  #endif
207673    return fts5yy_action[i];
207674  }
207675  
207676  /*
207677  ** The following routine is called if the stack overflows.
207678  */
207679  static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
207680     sqlite3Fts5ParserARG_FETCH
207681     sqlite3Fts5ParserCTX_FETCH
207682  #ifndef NDEBUG
207683     if( fts5yyTraceFILE ){
207684       fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
207685     }
207686  #endif
207687     while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
207688     /* Here code is inserted which will execute if the parser
207689     ** stack every overflows */
207690  /******** Begin %stack_overflow code ******************************************/
207691  
207692    sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
207693  /******** End %stack_overflow code ********************************************/
207694     sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
207695     sqlite3Fts5ParserCTX_STORE
207696  }
207697  
207698  /*
207699  ** Print tracing information for a SHIFT action
207700  */
207701  #ifndef NDEBUG
207702  static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
207703    if( fts5yyTraceFILE ){
207704      if( fts5yyNewState<fts5YYNSTATE ){
207705        fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
207706           fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
207707           fts5yyNewState);
207708      }else{
207709        fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
207710           fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
207711           fts5yyNewState - fts5YY_MIN_REDUCE);
207712      }
207713    }
207714  }
207715  #else
207716  # define fts5yyTraceShift(X,Y,Z)
207717  #endif
207718  
207719  /*
207720  ** Perform a shift action.
207721  */
207722  static void fts5yy_shift(
207723    fts5yyParser *fts5yypParser,          /* The parser to be shifted */
207724    fts5YYACTIONTYPE fts5yyNewState,      /* The new state to shift in */
207725    fts5YYCODETYPE fts5yyMajor,           /* The major token to shift in */
207726    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
207727  ){
207728    fts5yyStackEntry *fts5yytos;
207729    fts5yypParser->fts5yytos++;
207730  #ifdef fts5YYTRACKMAXSTACKDEPTH
207731    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
207732      fts5yypParser->fts5yyhwm++;
207733      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
207734    }
207735  #endif
207736  #if fts5YYSTACKDEPTH>0 
207737    if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
207738      fts5yypParser->fts5yytos--;
207739      fts5yyStackOverflow(fts5yypParser);
207740      return;
207741    }
207742  #else
207743    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
207744      if( fts5yyGrowStack(fts5yypParser) ){
207745        fts5yypParser->fts5yytos--;
207746        fts5yyStackOverflow(fts5yypParser);
207747        return;
207748      }
207749    }
207750  #endif
207751    if( fts5yyNewState > fts5YY_MAX_SHIFT ){
207752      fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
207753    }
207754    fts5yytos = fts5yypParser->fts5yytos;
207755    fts5yytos->stateno = fts5yyNewState;
207756    fts5yytos->major = fts5yyMajor;
207757    fts5yytos->minor.fts5yy0 = fts5yyMinor;
207758    fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
207759  }
207760  
207761  /* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
207762  ** of that rule */
207763  static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
207764      16,  /* (0) input ::= expr */
207765      20,  /* (1) colset ::= MINUS LCP colsetlist RCP */
207766      20,  /* (2) colset ::= LCP colsetlist RCP */
207767      20,  /* (3) colset ::= STRING */
207768      20,  /* (4) colset ::= MINUS STRING */
207769      21,  /* (5) colsetlist ::= colsetlist STRING */
207770      21,  /* (6) colsetlist ::= STRING */
207771      17,  /* (7) expr ::= expr AND expr */
207772      17,  /* (8) expr ::= expr OR expr */
207773      17,  /* (9) expr ::= expr NOT expr */
207774      17,  /* (10) expr ::= colset COLON LP expr RP */
207775      17,  /* (11) expr ::= LP expr RP */
207776      17,  /* (12) expr ::= exprlist */
207777      19,  /* (13) exprlist ::= cnearset */
207778      19,  /* (14) exprlist ::= exprlist cnearset */
207779      18,  /* (15) cnearset ::= nearset */
207780      18,  /* (16) cnearset ::= colset COLON nearset */
207781      22,  /* (17) nearset ::= phrase */
207782      22,  /* (18) nearset ::= CARET phrase */
207783      22,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
207784      23,  /* (20) nearphrases ::= phrase */
207785      23,  /* (21) nearphrases ::= nearphrases phrase */
207786      25,  /* (22) neardist_opt ::= */
207787      25,  /* (23) neardist_opt ::= COMMA STRING */
207788      24,  /* (24) phrase ::= phrase PLUS STRING star_opt */
207789      24,  /* (25) phrase ::= STRING star_opt */
207790      26,  /* (26) star_opt ::= STAR */
207791      26,  /* (27) star_opt ::= */
207792  };
207793  
207794  /* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
207795  ** of symbols on the right-hand side of that rule. */
207796  static const signed char fts5yyRuleInfoNRhs[] = {
207797     -1,  /* (0) input ::= expr */
207798     -4,  /* (1) colset ::= MINUS LCP colsetlist RCP */
207799     -3,  /* (2) colset ::= LCP colsetlist RCP */
207800     -1,  /* (3) colset ::= STRING */
207801     -2,  /* (4) colset ::= MINUS STRING */
207802     -2,  /* (5) colsetlist ::= colsetlist STRING */
207803     -1,  /* (6) colsetlist ::= STRING */
207804     -3,  /* (7) expr ::= expr AND expr */
207805     -3,  /* (8) expr ::= expr OR expr */
207806     -3,  /* (9) expr ::= expr NOT expr */
207807     -5,  /* (10) expr ::= colset COLON LP expr RP */
207808     -3,  /* (11) expr ::= LP expr RP */
207809     -1,  /* (12) expr ::= exprlist */
207810     -1,  /* (13) exprlist ::= cnearset */
207811     -2,  /* (14) exprlist ::= exprlist cnearset */
207812     -1,  /* (15) cnearset ::= nearset */
207813     -3,  /* (16) cnearset ::= colset COLON nearset */
207814     -1,  /* (17) nearset ::= phrase */
207815     -2,  /* (18) nearset ::= CARET phrase */
207816     -5,  /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
207817     -1,  /* (20) nearphrases ::= phrase */
207818     -2,  /* (21) nearphrases ::= nearphrases phrase */
207819      0,  /* (22) neardist_opt ::= */
207820     -2,  /* (23) neardist_opt ::= COMMA STRING */
207821     -4,  /* (24) phrase ::= phrase PLUS STRING star_opt */
207822     -2,  /* (25) phrase ::= STRING star_opt */
207823     -1,  /* (26) star_opt ::= STAR */
207824      0,  /* (27) star_opt ::= */
207825  };
207826  
207827  static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
207828  
207829  /*
207830  ** Perform a reduce action and the shift that must immediately
207831  ** follow the reduce.
207832  **
207833  ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
207834  ** access to the lookahead token (if any).  The fts5yyLookahead will be fts5YYNOCODE
207835  ** if the lookahead token has already been consumed.  As this procedure is
207836  ** only called from one place, optimizing compilers will in-line it, which
207837  ** means that the extra parameters have no performance impact.
207838  */
207839  static fts5YYACTIONTYPE fts5yy_reduce(
207840    fts5yyParser *fts5yypParser,         /* The parser */
207841    unsigned int fts5yyruleno,       /* Number of the rule by which to reduce */
207842    int fts5yyLookahead,             /* Lookahead token, or fts5YYNOCODE if none */
207843    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken  /* Value of the lookahead token */
207844    sqlite3Fts5ParserCTX_PDECL                   /* %extra_context */
207845  ){
207846    int fts5yygoto;                     /* The next state */
207847    fts5YYACTIONTYPE fts5yyact;             /* The next action */
207848    fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
207849    int fts5yysize;                     /* Amount to pop the stack */
207850    sqlite3Fts5ParserARG_FETCH
207851    (void)fts5yyLookahead;
207852    (void)fts5yyLookaheadToken;
207853    fts5yymsp = fts5yypParser->fts5yytos;
207854  #ifndef NDEBUG
207855    if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
207856      fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
207857      if( fts5yysize ){
207858        fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
207859          fts5yyTracePrompt,
207860          fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
207861      }else{
207862        fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
207863          fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
207864      }
207865    }
207866  #endif /* NDEBUG */
207867  
207868    /* Check that the stack is large enough to grow by a single entry
207869    ** if the RHS of the rule is empty.  This ensures that there is room
207870    ** enough on the stack to push the LHS value */
207871    if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
207872  #ifdef fts5YYTRACKMAXSTACKDEPTH
207873      if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
207874        fts5yypParser->fts5yyhwm++;
207875        assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
207876      }
207877  #endif
207878  #if fts5YYSTACKDEPTH>0 
207879      if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
207880        fts5yyStackOverflow(fts5yypParser);
207881        /* The call to fts5yyStackOverflow() above pops the stack until it is
207882        ** empty, causing the main parser loop to exit.  So the return value
207883        ** is never used and does not matter. */
207884        return 0;
207885      }
207886  #else
207887      if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
207888        if( fts5yyGrowStack(fts5yypParser) ){
207889          fts5yyStackOverflow(fts5yypParser);
207890          /* The call to fts5yyStackOverflow() above pops the stack until it is
207891          ** empty, causing the main parser loop to exit.  So the return value
207892          ** is never used and does not matter. */
207893          return 0;
207894        }
207895        fts5yymsp = fts5yypParser->fts5yytos;
207896      }
207897  #endif
207898    }
207899  
207900    switch( fts5yyruleno ){
207901    /* Beginning here are the reduction cases.  A typical example
207902    ** follows:
207903    **   case 0:
207904    **  #line <lineno> <grammarfile>
207905    **     { ... }           // User supplied code
207906    **  #line <lineno> <thisfile>
207907    **     break;
207908    */
207909  /********** Begin reduce actions **********************************************/
207910          fts5YYMINORTYPE fts5yylhsminor;
207911        case 0: /* input ::= expr */
207912  { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
207913          break;
207914        case 1: /* colset ::= MINUS LCP colsetlist RCP */
207915  { 
207916      fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
207917  }
207918          break;
207919        case 2: /* colset ::= LCP colsetlist RCP */
207920  { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
207921          break;
207922        case 3: /* colset ::= STRING */
207923  {
207924    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
207925  }
207926    fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
207927          break;
207928        case 4: /* colset ::= MINUS STRING */
207929  {
207930    fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
207931    fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
207932  }
207933          break;
207934        case 5: /* colsetlist ::= colsetlist STRING */
207935  { 
207936    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
207937    fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
207938          break;
207939        case 6: /* colsetlist ::= STRING */
207940  { 
207941    fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); 
207942  }
207943    fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
207944          break;
207945        case 7: /* expr ::= expr AND expr */
207946  {
207947    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
207948  }
207949    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207950          break;
207951        case 8: /* expr ::= expr OR expr */
207952  {
207953    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
207954  }
207955    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207956          break;
207957        case 9: /* expr ::= expr NOT expr */
207958  {
207959    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
207960  }
207961    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207962          break;
207963        case 10: /* expr ::= colset COLON LP expr RP */
207964  {
207965    sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
207966    fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
207967  }
207968    fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207969          break;
207970        case 11: /* expr ::= LP expr RP */
207971  {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
207972          break;
207973        case 12: /* expr ::= exprlist */
207974        case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
207975  {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
207976    fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207977          break;
207978        case 14: /* exprlist ::= exprlist cnearset */
207979  {
207980    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
207981  }
207982    fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207983          break;
207984        case 15: /* cnearset ::= nearset */
207985  { 
207986    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
207987  }
207988    fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207989          break;
207990        case 16: /* cnearset ::= colset COLON nearset */
207991  { 
207992    fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
207993    sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
207994  }
207995    fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
207996          break;
207997        case 17: /* nearset ::= phrase */
207998  { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
207999    fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
208000          break;
208001        case 18: /* nearset ::= CARET phrase */
208002  { 
208003    sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
208004    fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); 
208005  }
208006          break;
208007        case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
208008  {
208009    sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
208010    sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
208011    fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
208012  }
208013    fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
208014          break;
208015        case 20: /* nearphrases ::= phrase */
208016  { 
208017    fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); 
208018  }
208019    fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
208020          break;
208021        case 21: /* nearphrases ::= nearphrases phrase */
208022  {
208023    fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
208024  }
208025    fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
208026          break;
208027        case 22: /* neardist_opt ::= */
208028  { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
208029          break;
208030        case 23: /* neardist_opt ::= COMMA STRING */
208031  { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
208032          break;
208033        case 24: /* phrase ::= phrase PLUS STRING star_opt */
208034  { 
208035    fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
208036  }
208037    fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
208038          break;
208039        case 25: /* phrase ::= STRING star_opt */
208040  { 
208041    fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
208042  }
208043    fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
208044          break;
208045        case 26: /* star_opt ::= STAR */
208046  { fts5yymsp[0].minor.fts5yy4 = 1; }
208047          break;
208048        case 27: /* star_opt ::= */
208049  { fts5yymsp[1].minor.fts5yy4 = 0; }
208050          break;
208051        default:
208052          break;
208053  /********** End reduce actions ************************************************/
208054    };
208055    assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
208056    fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
208057    fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
208058    fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
208059  
208060    /* There are no SHIFTREDUCE actions on nonterminals because the table
208061    ** generator has simplified them to pure REDUCE actions. */
208062    assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
208063  
208064    /* It is not possible for a REDUCE to be followed by an error */
208065    assert( fts5yyact!=fts5YY_ERROR_ACTION );
208066  
208067    fts5yymsp += fts5yysize+1;
208068    fts5yypParser->fts5yytos = fts5yymsp;
208069    fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
208070    fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
208071    fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
208072    return fts5yyact;
208073  }
208074  
208075  /*
208076  ** The following code executes when the parse fails
208077  */
208078  #ifndef fts5YYNOERRORRECOVERY
208079  static void fts5yy_parse_failed(
208080    fts5yyParser *fts5yypParser           /* The parser */
208081  ){
208082    sqlite3Fts5ParserARG_FETCH
208083    sqlite3Fts5ParserCTX_FETCH
208084  #ifndef NDEBUG
208085    if( fts5yyTraceFILE ){
208086      fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
208087    }
208088  #endif
208089    while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
208090    /* Here code is inserted which will be executed whenever the
208091    ** parser fails */
208092  /************ Begin %parse_failure code ***************************************/
208093  /************ End %parse_failure code *****************************************/
208094    sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
208095    sqlite3Fts5ParserCTX_STORE
208096  }
208097  #endif /* fts5YYNOERRORRECOVERY */
208098  
208099  /*
208100  ** The following code executes when a syntax error first occurs.
208101  */
208102  static void fts5yy_syntax_error(
208103    fts5yyParser *fts5yypParser,           /* The parser */
208104    int fts5yymajor,                   /* The major type of the error token */
208105    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
208106  ){
208107    sqlite3Fts5ParserARG_FETCH
208108    sqlite3Fts5ParserCTX_FETCH
208109  #define FTS5TOKEN fts5yyminor
208110  /************ Begin %syntax_error code ****************************************/
208111  
208112    UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
208113    sqlite3Fts5ParseError(
208114      pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
208115    );
208116  /************ End %syntax_error code ******************************************/
208117    sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
208118    sqlite3Fts5ParserCTX_STORE
208119  }
208120  
208121  /*
208122  ** The following is executed when the parser accepts
208123  */
208124  static void fts5yy_accept(
208125    fts5yyParser *fts5yypParser           /* The parser */
208126  ){
208127    sqlite3Fts5ParserARG_FETCH
208128    sqlite3Fts5ParserCTX_FETCH
208129  #ifndef NDEBUG
208130    if( fts5yyTraceFILE ){
208131      fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
208132    }
208133  #endif
208134  #ifndef fts5YYNOERRORRECOVERY
208135    fts5yypParser->fts5yyerrcnt = -1;
208136  #endif
208137    assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
208138    /* Here code is inserted which will be executed whenever the
208139    ** parser accepts */
208140  /*********** Begin %parse_accept code *****************************************/
208141  /*********** End %parse_accept code *******************************************/
208142    sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
208143    sqlite3Fts5ParserCTX_STORE
208144  }
208145  
208146  /* The main parser program.
208147  ** The first argument is a pointer to a structure obtained from
208148  ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
208149  ** The second argument is the major token number.  The third is
208150  ** the minor token.  The fourth optional argument is whatever the
208151  ** user wants (and specified in the grammar) and is available for
208152  ** use by the action routines.
208153  **
208154  ** Inputs:
208155  ** <ul>
208156  ** <li> A pointer to the parser (an opaque structure.)
208157  ** <li> The major token number.
208158  ** <li> The minor token number.
208159  ** <li> An option argument of a grammar-specified type.
208160  ** </ul>
208161  **
208162  ** Outputs:
208163  ** None.
208164  */
208165  static void sqlite3Fts5Parser(
208166    void *fts5yyp,                   /* The parser */
208167    int fts5yymajor,                 /* The major token code number */
208168    sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
208169    sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
208170  ){
208171    fts5YYMINORTYPE fts5yyminorunion;
208172    fts5YYACTIONTYPE fts5yyact;   /* The parser action. */
208173  #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
208174    int fts5yyendofinput;     /* True if we are at the end of input */
208175  #endif
208176  #ifdef fts5YYERRORSYMBOL
208177    int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
208178  #endif
208179    fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp;  /* The parser */
208180    sqlite3Fts5ParserCTX_FETCH
208181    sqlite3Fts5ParserARG_STORE
208182  
208183    assert( fts5yypParser->fts5yytos!=0 );
208184  #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
208185    fts5yyendofinput = (fts5yymajor==0);
208186  #endif
208187  
208188    fts5yyact = fts5yypParser->fts5yytos->stateno;
208189  #ifndef NDEBUG
208190    if( fts5yyTraceFILE ){
208191      if( fts5yyact < fts5YY_MIN_REDUCE ){
208192        fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
208193                fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
208194      }else{
208195        fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
208196                fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
208197      }
208198    }
208199  #endif
208200  
208201    do{
208202      assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
208203      fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
208204      if( fts5yyact >= fts5YY_MIN_REDUCE ){
208205        fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
208206                          fts5yyminor sqlite3Fts5ParserCTX_PARAM);
208207      }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
208208        fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
208209  #ifndef fts5YYNOERRORRECOVERY
208210        fts5yypParser->fts5yyerrcnt--;
208211  #endif
208212        break;
208213      }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
208214        fts5yypParser->fts5yytos--;
208215        fts5yy_accept(fts5yypParser);
208216        return;
208217      }else{
208218        assert( fts5yyact == fts5YY_ERROR_ACTION );
208219        fts5yyminorunion.fts5yy0 = fts5yyminor;
208220  #ifdef fts5YYERRORSYMBOL
208221        int fts5yymx;
208222  #endif
208223  #ifndef NDEBUG
208224        if( fts5yyTraceFILE ){
208225          fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
208226        }
208227  #endif
208228  #ifdef fts5YYERRORSYMBOL
208229        /* A syntax error has occurred.
208230        ** The response to an error depends upon whether or not the
208231        ** grammar defines an error token "ERROR".  
208232        **
208233        ** This is what we do if the grammar does define ERROR:
208234        **
208235        **  * Call the %syntax_error function.
208236        **
208237        **  * Begin popping the stack until we enter a state where
208238        **    it is legal to shift the error symbol, then shift
208239        **    the error symbol.
208240        **
208241        **  * Set the error count to three.
208242        **
208243        **  * Begin accepting and shifting new tokens.  No new error
208244        **    processing will occur until three tokens have been
208245        **    shifted successfully.
208246        **
208247        */
208248        if( fts5yypParser->fts5yyerrcnt<0 ){
208249          fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
208250        }
208251        fts5yymx = fts5yypParser->fts5yytos->major;
208252        if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
208253  #ifndef NDEBUG
208254          if( fts5yyTraceFILE ){
208255            fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
208256               fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
208257          }
208258  #endif
208259          fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
208260          fts5yymajor = fts5YYNOCODE;
208261        }else{
208262          while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
208263              && (fts5yyact = fts5yy_find_reduce_action(
208264                          fts5yypParser->fts5yytos->stateno,
208265                          fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
208266          ){
208267            fts5yy_pop_parser_stack(fts5yypParser);
208268          }
208269          if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
208270            fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
208271            fts5yy_parse_failed(fts5yypParser);
208272  #ifndef fts5YYNOERRORRECOVERY
208273            fts5yypParser->fts5yyerrcnt = -1;
208274  #endif
208275            fts5yymajor = fts5YYNOCODE;
208276          }else if( fts5yymx!=fts5YYERRORSYMBOL ){
208277            fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
208278          }
208279        }
208280        fts5yypParser->fts5yyerrcnt = 3;
208281        fts5yyerrorhit = 1;
208282        if( fts5yymajor==fts5YYNOCODE ) break;
208283        fts5yyact = fts5yypParser->fts5yytos->stateno;
208284  #elif defined(fts5YYNOERRORRECOVERY)
208285        /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
208286        ** do any kind of error recovery.  Instead, simply invoke the syntax
208287        ** error routine and continue going as if nothing had happened.
208288        **
208289        ** Applications can set this macro (for example inside %include) if
208290        ** they intend to abandon the parse upon the first syntax error seen.
208291        */
208292        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
208293        fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
208294        break;
208295  #else  /* fts5YYERRORSYMBOL is not defined */
208296        /* This is what we do if the grammar does not define ERROR:
208297        **
208298        **  * Report an error message, and throw away the input token.
208299        **
208300        **  * If the input token is $, then fail the parse.
208301        **
208302        ** As before, subsequent error messages are suppressed until
208303        ** three input tokens have been successfully shifted.
208304        */
208305        if( fts5yypParser->fts5yyerrcnt<=0 ){
208306          fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
208307        }
208308        fts5yypParser->fts5yyerrcnt = 3;
208309        fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
208310        if( fts5yyendofinput ){
208311          fts5yy_parse_failed(fts5yypParser);
208312  #ifndef fts5YYNOERRORRECOVERY
208313          fts5yypParser->fts5yyerrcnt = -1;
208314  #endif
208315        }
208316        break;
208317  #endif
208318      }
208319    }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
208320  #ifndef NDEBUG
208321    if( fts5yyTraceFILE ){
208322      fts5yyStackEntry *i;
208323      char cDiv = '[';
208324      fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
208325      for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
208326        fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
208327        cDiv = ' ';
208328      }
208329      fprintf(fts5yyTraceFILE,"]\n");
208330    }
208331  #endif
208332    return;
208333  }
208334  
208335  /*
208336  ** Return the fallback token corresponding to canonical token iToken, or
208337  ** 0 if iToken has no fallback.
208338  */
208339  static int sqlite3Fts5ParserFallback(int iToken){
208340  #ifdef fts5YYFALLBACK
208341    if( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) ){
208342      return fts5yyFallback[iToken];
208343    }
208344  #else
208345    (void)iToken;
208346  #endif
208347    return 0;
208348  }
208349  
208350  /*
208351  ** 2014 May 31
208352  **
208353  ** The author disclaims copyright to this source code.  In place of
208354  ** a legal notice, here is a blessing:
208355  **
208356  **    May you do good and not evil.
208357  **    May you find forgiveness for yourself and forgive others.
208358  **    May you share freely, never taking more than you give.
208359  **
208360  ******************************************************************************
208361  */
208362  
208363  
208364  /* #include "fts5Int.h" */
208365  #include <math.h>                 /* amalgamator: keep */
208366  
208367  /*
208368  ** Object used to iterate through all "coalesced phrase instances" in 
208369  ** a single column of the current row. If the phrase instances in the
208370  ** column being considered do not overlap, this object simply iterates
208371  ** through them. Or, if they do overlap (share one or more tokens in
208372  ** common), each set of overlapping instances is treated as a single
208373  ** match. See documentation for the highlight() auxiliary function for
208374  ** details.
208375  **
208376  ** Usage is:
208377  **
208378  **   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
208379  **      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
208380  **      rc = fts5CInstIterNext(&iter)
208381  **   ){
208382  **     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
208383  **   }
208384  **
208385  */
208386  typedef struct CInstIter CInstIter;
208387  struct CInstIter {
208388    const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
208389    Fts5Context *pFts;              /* First arg to pass to pApi functions */
208390    int iCol;                       /* Column to search */
208391    int iInst;                      /* Next phrase instance index */
208392    int nInst;                      /* Total number of phrase instances */
208393  
208394    /* Output variables */
208395    int iStart;                     /* First token in coalesced phrase instance */
208396    int iEnd;                       /* Last token in coalesced phrase instance */
208397  };
208398  
208399  /*
208400  ** Advance the iterator to the next coalesced phrase instance. Return
208401  ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
208402  */
208403  static int fts5CInstIterNext(CInstIter *pIter){
208404    int rc = SQLITE_OK;
208405    pIter->iStart = -1;
208406    pIter->iEnd = -1;
208407  
208408    while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
208409      int ip; int ic; int io;
208410      rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
208411      if( rc==SQLITE_OK ){
208412        if( ic==pIter->iCol ){
208413          int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
208414          if( pIter->iStart<0 ){
208415            pIter->iStart = io;
208416            pIter->iEnd = iEnd;
208417          }else if( io<=pIter->iEnd ){
208418            if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
208419          }else{
208420            break;
208421          }
208422        }
208423        pIter->iInst++;
208424      }
208425    }
208426  
208427    return rc;
208428  }
208429  
208430  /*
208431  ** Initialize the iterator object indicated by the final parameter to 
208432  ** iterate through coalesced phrase instances in column iCol.
208433  */
208434  static int fts5CInstIterInit(
208435    const Fts5ExtensionApi *pApi,
208436    Fts5Context *pFts,
208437    int iCol,
208438    CInstIter *pIter
208439  ){
208440    int rc;
208441  
208442    memset(pIter, 0, sizeof(CInstIter));
208443    pIter->pApi = pApi;
208444    pIter->pFts = pFts;
208445    pIter->iCol = iCol;
208446    rc = pApi->xInstCount(pFts, &pIter->nInst);
208447  
208448    if( rc==SQLITE_OK ){
208449      rc = fts5CInstIterNext(pIter);
208450    }
208451  
208452    return rc;
208453  }
208454  
208455  
208456  
208457  /*************************************************************************
208458  ** Start of highlight() implementation.
208459  */
208460  typedef struct HighlightContext HighlightContext;
208461  struct HighlightContext {
208462    CInstIter iter;                 /* Coalesced Instance Iterator */
208463    int iPos;                       /* Current token offset in zIn[] */
208464    int iRangeStart;                /* First token to include */
208465    int iRangeEnd;                  /* If non-zero, last token to include */
208466    const char *zOpen;              /* Opening highlight */
208467    const char *zClose;             /* Closing highlight */
208468    const char *zIn;                /* Input text */
208469    int nIn;                        /* Size of input text in bytes */
208470    int iOff;                       /* Current offset within zIn[] */
208471    char *zOut;                     /* Output value */
208472  };
208473  
208474  /*
208475  ** Append text to the HighlightContext output string - p->zOut. Argument
208476  ** z points to a buffer containing n bytes of text to append. If n is 
208477  ** negative, everything up until the first '\0' is appended to the output.
208478  **
208479  ** If *pRc is set to any value other than SQLITE_OK when this function is 
208480  ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, 
208481  ** *pRc is set to an error code before returning. 
208482  */
208483  static void fts5HighlightAppend(
208484    int *pRc, 
208485    HighlightContext *p, 
208486    const char *z, int n
208487  ){
208488    if( *pRc==SQLITE_OK && z ){
208489      if( n<0 ) n = (int)strlen(z);
208490      p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
208491      if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
208492    }
208493  }
208494  
208495  /*
208496  ** Tokenizer callback used by implementation of highlight() function.
208497  */
208498  static int fts5HighlightCb(
208499    void *pContext,                 /* Pointer to HighlightContext object */
208500    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
208501    const char *pToken,             /* Buffer containing token */
208502    int nToken,                     /* Size of token in bytes */
208503    int iStartOff,                  /* Start offset of token */
208504    int iEndOff                     /* End offset of token */
208505  ){
208506    HighlightContext *p = (HighlightContext*)pContext;
208507    int rc = SQLITE_OK;
208508    int iPos;
208509  
208510    UNUSED_PARAM2(pToken, nToken);
208511  
208512    if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
208513    iPos = p->iPos++;
208514  
208515    if( p->iRangeEnd>0 ){
208516      if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
208517      if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
208518    }
208519  
208520    if( iPos==p->iter.iStart ){
208521      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
208522      fts5HighlightAppend(&rc, p, p->zOpen, -1);
208523      p->iOff = iStartOff;
208524    }
208525  
208526    if( iPos==p->iter.iEnd ){
208527      if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
208528        fts5HighlightAppend(&rc, p, p->zOpen, -1);
208529      }
208530      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
208531      fts5HighlightAppend(&rc, p, p->zClose, -1);
208532      p->iOff = iEndOff;
208533      if( rc==SQLITE_OK ){
208534        rc = fts5CInstIterNext(&p->iter);
208535      }
208536    }
208537  
208538    if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
208539      fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
208540      p->iOff = iEndOff;
208541      if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
208542        fts5HighlightAppend(&rc, p, p->zClose, -1);
208543      }
208544    }
208545  
208546    return rc;
208547  }
208548  
208549  /*
208550  ** Implementation of highlight() function.
208551  */
208552  static void fts5HighlightFunction(
208553    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
208554    Fts5Context *pFts,              /* First arg to pass to pApi functions */
208555    sqlite3_context *pCtx,          /* Context for returning result/error */
208556    int nVal,                       /* Number of values in apVal[] array */
208557    sqlite3_value **apVal           /* Array of trailing arguments */
208558  ){
208559    HighlightContext ctx;
208560    int rc;
208561    int iCol;
208562  
208563    if( nVal!=3 ){
208564      const char *zErr = "wrong number of arguments to function highlight()";
208565      sqlite3_result_error(pCtx, zErr, -1);
208566      return;
208567    }
208568  
208569    iCol = sqlite3_value_int(apVal[0]);
208570    memset(&ctx, 0, sizeof(HighlightContext));
208571    ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
208572    ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
208573    rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
208574  
208575    if( ctx.zIn ){
208576      if( rc==SQLITE_OK ){
208577        rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
208578      }
208579  
208580      if( rc==SQLITE_OK ){
208581        rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
208582      }
208583      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
208584  
208585      if( rc==SQLITE_OK ){
208586        sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
208587      }
208588      sqlite3_free(ctx.zOut);
208589    }
208590    if( rc!=SQLITE_OK ){
208591      sqlite3_result_error_code(pCtx, rc);
208592    }
208593  }
208594  /*
208595  ** End of highlight() implementation.
208596  **************************************************************************/
208597  
208598  /*
208599  ** Context object passed to the fts5SentenceFinderCb() function.
208600  */
208601  typedef struct Fts5SFinder Fts5SFinder;
208602  struct Fts5SFinder {
208603    int iPos;                       /* Current token position */
208604    int nFirstAlloc;                /* Allocated size of aFirst[] */
208605    int nFirst;                     /* Number of entries in aFirst[] */
208606    int *aFirst;                    /* Array of first token in each sentence */
208607    const char *zDoc;               /* Document being tokenized */
208608  };
208609  
208610  /*
208611  ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
208612  ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
208613  ** error occurs.
208614  */
208615  static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
208616    if( p->nFirstAlloc==p->nFirst ){
208617      int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
208618      int *aNew;
208619  
208620      aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
208621      if( aNew==0 ) return SQLITE_NOMEM;
208622      p->aFirst = aNew;
208623      p->nFirstAlloc = nNew;
208624    }
208625    p->aFirst[p->nFirst++] = iAdd;
208626    return SQLITE_OK;
208627  }
208628  
208629  /*
208630  ** This function is an xTokenize() callback used by the auxiliary snippet()
208631  ** function. Its job is to identify tokens that are the first in a sentence.
208632  ** For each such token, an entry is added to the SFinder.aFirst[] array.
208633  */
208634  static int fts5SentenceFinderCb(
208635    void *pContext,                 /* Pointer to HighlightContext object */
208636    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
208637    const char *pToken,             /* Buffer containing token */
208638    int nToken,                     /* Size of token in bytes */
208639    int iStartOff,                  /* Start offset of token */
208640    int iEndOff                     /* End offset of token */
208641  ){
208642    int rc = SQLITE_OK;
208643  
208644    UNUSED_PARAM2(pToken, nToken);
208645    UNUSED_PARAM(iEndOff);
208646  
208647    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
208648      Fts5SFinder *p = (Fts5SFinder*)pContext;
208649      if( p->iPos>0 ){
208650        int i;
208651        char c = 0;
208652        for(i=iStartOff-1; i>=0; i--){
208653          c = p->zDoc[i];
208654          if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
208655        }
208656        if( i!=iStartOff-1 && (c=='.' || c==':') ){
208657          rc = fts5SentenceFinderAdd(p, p->iPos);
208658        }
208659      }else{
208660        rc = fts5SentenceFinderAdd(p, 0);
208661      }
208662      p->iPos++;
208663    }
208664    return rc;
208665  }
208666  
208667  static int fts5SnippetScore(
208668    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
208669    Fts5Context *pFts,              /* First arg to pass to pApi functions */
208670    int nDocsize,                   /* Size of column in tokens */
208671    unsigned char *aSeen,           /* Array with one element per query phrase */
208672    int iCol,                       /* Column to score */
208673    int iPos,                       /* Starting offset to score */
208674    int nToken,                     /* Max tokens per snippet */
208675    int *pnScore,                   /* OUT: Score */
208676    int *piPos                      /* OUT: Adjusted offset */
208677  ){
208678    int rc;
208679    int i;
208680    int ip = 0;
208681    int ic = 0;
208682    int iOff = 0;
208683    int iFirst = -1;
208684    int nInst;
208685    int nScore = 0;
208686    int iLast = 0;
208687    sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
208688  
208689    rc = pApi->xInstCount(pFts, &nInst);
208690    for(i=0; i<nInst && rc==SQLITE_OK; i++){
208691      rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
208692      if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
208693        nScore += (aSeen[ip] ? 1 : 1000);
208694        aSeen[ip] = 1;
208695        if( iFirst<0 ) iFirst = iOff;
208696        iLast = iOff + pApi->xPhraseSize(pFts, ip);
208697      }
208698    }
208699  
208700    *pnScore = nScore;
208701    if( piPos ){
208702      sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
208703      if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
208704      if( iAdj<0 ) iAdj = 0;
208705      *piPos = iAdj;
208706    }
208707  
208708    return rc;
208709  }
208710  
208711  /*
208712  ** Return the value in pVal interpreted as utf-8 text. Except, if pVal 
208713  ** contains a NULL value, return a pointer to a static string zero
208714  ** bytes in length instead of a NULL pointer.
208715  */
208716  static const char *fts5ValueToText(sqlite3_value *pVal){
208717    const char *zRet = (const char*)sqlite3_value_text(pVal);
208718    return zRet ? zRet : "";
208719  }
208720  
208721  /*
208722  ** Implementation of snippet() function.
208723  */
208724  static void fts5SnippetFunction(
208725    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
208726    Fts5Context *pFts,              /* First arg to pass to pApi functions */
208727    sqlite3_context *pCtx,          /* Context for returning result/error */
208728    int nVal,                       /* Number of values in apVal[] array */
208729    sqlite3_value **apVal           /* Array of trailing arguments */
208730  ){
208731    HighlightContext ctx;
208732    int rc = SQLITE_OK;             /* Return code */
208733    int iCol;                       /* 1st argument to snippet() */
208734    const char *zEllips;            /* 4th argument to snippet() */
208735    int nToken;                     /* 5th argument to snippet() */
208736    int nInst = 0;                  /* Number of instance matches this row */
208737    int i;                          /* Used to iterate through instances */
208738    int nPhrase;                    /* Number of phrases in query */
208739    unsigned char *aSeen;           /* Array of "seen instance" flags */
208740    int iBestCol;                   /* Column containing best snippet */
208741    int iBestStart = 0;             /* First token of best snippet */
208742    int nBestScore = 0;             /* Score of best snippet */
208743    int nColSize = 0;               /* Total size of iBestCol in tokens */
208744    Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
208745    int nCol;
208746  
208747    if( nVal!=5 ){
208748      const char *zErr = "wrong number of arguments to function snippet()";
208749      sqlite3_result_error(pCtx, zErr, -1);
208750      return;
208751    }
208752  
208753    nCol = pApi->xColumnCount(pFts);
208754    memset(&ctx, 0, sizeof(HighlightContext));
208755    iCol = sqlite3_value_int(apVal[0]);
208756    ctx.zOpen = fts5ValueToText(apVal[1]);
208757    ctx.zClose = fts5ValueToText(apVal[2]);
208758    zEllips = fts5ValueToText(apVal[3]);
208759    nToken = sqlite3_value_int(apVal[4]);
208760  
208761    iBestCol = (iCol>=0 ? iCol : 0);
208762    nPhrase = pApi->xPhraseCount(pFts);
208763    aSeen = sqlite3_malloc(nPhrase);
208764    if( aSeen==0 ){
208765      rc = SQLITE_NOMEM;
208766    }
208767    if( rc==SQLITE_OK ){
208768      rc = pApi->xInstCount(pFts, &nInst);
208769    }
208770  
208771    memset(&sFinder, 0, sizeof(Fts5SFinder));
208772    for(i=0; i<nCol; i++){
208773      if( iCol<0 || iCol==i ){
208774        int nDoc;
208775        int nDocsize;
208776        int ii;
208777        sFinder.iPos = 0;
208778        sFinder.nFirst = 0;
208779        rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
208780        if( rc!=SQLITE_OK ) break;
208781        rc = pApi->xTokenize(pFts, 
208782            sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
208783        );
208784        if( rc!=SQLITE_OK ) break;
208785        rc = pApi->xColumnSize(pFts, i, &nDocsize);
208786        if( rc!=SQLITE_OK ) break;
208787  
208788        for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
208789          int ip, ic, io;
208790          int iAdj;
208791          int nScore;
208792          int jj;
208793  
208794          rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
208795          if( ic!=i ) continue;
208796          if( io>nDocsize ) rc = FTS5_CORRUPT;
208797          if( rc!=SQLITE_OK ) continue;
208798          memset(aSeen, 0, nPhrase);
208799          rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
208800              io, nToken, &nScore, &iAdj
208801          );
208802          if( rc==SQLITE_OK && nScore>nBestScore ){
208803            nBestScore = nScore;
208804            iBestCol = i;
208805            iBestStart = iAdj;
208806            nColSize = nDocsize;
208807          }
208808  
208809          if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
208810            for(jj=0; jj<(sFinder.nFirst-1); jj++){
208811              if( sFinder.aFirst[jj+1]>io ) break;
208812            }
208813  
208814            if( sFinder.aFirst[jj]<io ){
208815              memset(aSeen, 0, nPhrase);
208816              rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, 
208817                sFinder.aFirst[jj], nToken, &nScore, 0
208818              );
208819  
208820              nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
208821              if( rc==SQLITE_OK && nScore>nBestScore ){
208822                nBestScore = nScore;
208823                iBestCol = i;
208824                iBestStart = sFinder.aFirst[jj];
208825                nColSize = nDocsize;
208826              }
208827            }
208828          }
208829        }
208830      }
208831    }
208832  
208833    if( rc==SQLITE_OK ){
208834      rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
208835    }
208836    if( rc==SQLITE_OK && nColSize==0 ){
208837      rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
208838    }
208839    if( ctx.zIn ){
208840      if( rc==SQLITE_OK ){
208841        rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
208842      }
208843  
208844      ctx.iRangeStart = iBestStart;
208845      ctx.iRangeEnd = iBestStart + nToken - 1;
208846  
208847      if( iBestStart>0 ){
208848        fts5HighlightAppend(&rc, &ctx, zEllips, -1);
208849      }
208850  
208851      /* Advance iterator ctx.iter so that it points to the first coalesced
208852      ** phrase instance at or following position iBestStart. */
208853      while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
208854        rc = fts5CInstIterNext(&ctx.iter);
208855      }
208856  
208857      if( rc==SQLITE_OK ){
208858        rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
208859      }
208860      if( ctx.iRangeEnd>=(nColSize-1) ){
208861        fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
208862      }else{
208863        fts5HighlightAppend(&rc, &ctx, zEllips, -1);
208864      }
208865    }
208866    if( rc==SQLITE_OK ){
208867      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
208868    }else{
208869      sqlite3_result_error_code(pCtx, rc);
208870    }
208871    sqlite3_free(ctx.zOut);
208872    sqlite3_free(aSeen);
208873    sqlite3_free(sFinder.aFirst);
208874  }
208875  
208876  /************************************************************************/
208877  
208878  /*
208879  ** The first time the bm25() function is called for a query, an instance
208880  ** of the following structure is allocated and populated.
208881  */
208882  typedef struct Fts5Bm25Data Fts5Bm25Data;
208883  struct Fts5Bm25Data {
208884    int nPhrase;                    /* Number of phrases in query */
208885    double avgdl;                   /* Average number of tokens in each row */
208886    double *aIDF;                   /* IDF for each phrase */
208887    double *aFreq;                  /* Array used to calculate phrase freq. */
208888  };
208889  
208890  /*
208891  ** Callback used by fts5Bm25GetData() to count the number of rows in the
208892  ** table matched by each individual phrase within the query.
208893  */
208894  static int fts5CountCb(
208895    const Fts5ExtensionApi *pApi, 
208896    Fts5Context *pFts,
208897    void *pUserData                 /* Pointer to sqlite3_int64 variable */
208898  ){
208899    sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
208900    UNUSED_PARAM2(pApi, pFts);
208901    (*pn)++;
208902    return SQLITE_OK;
208903  }
208904  
208905  /*
208906  ** Set *ppData to point to the Fts5Bm25Data object for the current query. 
208907  ** If the object has not already been allocated, allocate and populate it
208908  ** now.
208909  */
208910  static int fts5Bm25GetData(
208911    const Fts5ExtensionApi *pApi, 
208912    Fts5Context *pFts,
208913    Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
208914  ){
208915    int rc = SQLITE_OK;             /* Return code */
208916    Fts5Bm25Data *p;                /* Object to return */
208917  
208918    p = pApi->xGetAuxdata(pFts, 0);
208919    if( p==0 ){
208920      int nPhrase;                  /* Number of phrases in query */
208921      sqlite3_int64 nRow = 0;       /* Number of rows in table */
208922      sqlite3_int64 nToken = 0;     /* Number of tokens in table */
208923      sqlite3_int64 nByte;          /* Bytes of space to allocate */
208924      int i;
208925  
208926      /* Allocate the Fts5Bm25Data object */
208927      nPhrase = pApi->xPhraseCount(pFts);
208928      nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
208929      p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
208930      if( p==0 ){
208931        rc = SQLITE_NOMEM;
208932      }else{
208933        memset(p, 0, nByte);
208934        p->nPhrase = nPhrase;
208935        p->aIDF = (double*)&p[1];
208936        p->aFreq = &p->aIDF[nPhrase];
208937      }
208938  
208939      /* Calculate the average document length for this FTS5 table */
208940      if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
208941      assert( rc!=SQLITE_OK || nRow>0 );
208942      if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
208943      if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
208944  
208945      /* Calculate an IDF for each phrase in the query */
208946      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
208947        sqlite3_int64 nHit = 0;
208948        rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
208949        if( rc==SQLITE_OK ){
208950          /* Calculate the IDF (Inverse Document Frequency) for phrase i.
208951          ** This is done using the standard BM25 formula as found on wikipedia:
208952          **
208953          **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
208954          **
208955          ** where "N" is the total number of documents in the set and nHit
208956          ** is the number that contain at least one instance of the phrase
208957          ** under consideration.
208958          **
208959          ** The problem with this is that if (N < 2*nHit), the IDF is 
208960          ** negative. Which is undesirable. So the mimimum allowable IDF is
208961          ** (1e-6) - roughly the same as a term that appears in just over
208962          ** half of set of 5,000,000 documents.  */
208963          double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
208964          if( idf<=0.0 ) idf = 1e-6;
208965          p->aIDF[i] = idf;
208966        }
208967      }
208968  
208969      if( rc!=SQLITE_OK ){
208970        sqlite3_free(p);
208971      }else{
208972        rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
208973      }
208974      if( rc!=SQLITE_OK ) p = 0;
208975    }
208976    *ppData = p;
208977    return rc;
208978  }
208979  
208980  /*
208981  ** Implementation of bm25() function.
208982  */
208983  static void fts5Bm25Function(
208984    const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
208985    Fts5Context *pFts,              /* First arg to pass to pApi functions */
208986    sqlite3_context *pCtx,          /* Context for returning result/error */
208987    int nVal,                       /* Number of values in apVal[] array */
208988    sqlite3_value **apVal           /* Array of trailing arguments */
208989  ){
208990    const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
208991    const double b = 0.75;          /* Constant "b" from BM25 formula */
208992    int rc = SQLITE_OK;             /* Error code */
208993    double score = 0.0;             /* SQL function return value */
208994    Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
208995    int i;                          /* Iterator variable */
208996    int nInst = 0;                  /* Value returned by xInstCount() */
208997    double D = 0.0;                 /* Total number of tokens in row */
208998    double *aFreq = 0;              /* Array of phrase freq. for current row */
208999  
209000    /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
209001    ** for each phrase in the query for the current row. */
209002    rc = fts5Bm25GetData(pApi, pFts, &pData);
209003    if( rc==SQLITE_OK ){
209004      aFreq = pData->aFreq;
209005      memset(aFreq, 0, sizeof(double) * pData->nPhrase);
209006      rc = pApi->xInstCount(pFts, &nInst);
209007    }
209008    for(i=0; rc==SQLITE_OK && i<nInst; i++){
209009      int ip; int ic; int io;
209010      rc = pApi->xInst(pFts, i, &ip, &ic, &io);
209011      if( rc==SQLITE_OK ){
209012        double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
209013        aFreq[ip] += w;
209014      }
209015    }
209016  
209017    /* Figure out the total size of the current row in tokens. */
209018    if( rc==SQLITE_OK ){
209019      int nTok;
209020      rc = pApi->xColumnSize(pFts, -1, &nTok);
209021      D = (double)nTok;
209022    }
209023  
209024    /* Determine the BM25 score for the current row. */
209025    for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
209026      score += pData->aIDF[i] * (
209027        ( aFreq[i] * (k1 + 1.0) ) / 
209028        ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
209029      );
209030    }
209031    
209032    /* If no error has occurred, return the calculated score. Otherwise,
209033    ** throw an SQL exception.  */
209034    if( rc==SQLITE_OK ){
209035      sqlite3_result_double(pCtx, -1.0 * score);
209036    }else{
209037      sqlite3_result_error_code(pCtx, rc);
209038    }
209039  }
209040  
209041  static int sqlite3Fts5AuxInit(fts5_api *pApi){
209042    struct Builtin {
209043      const char *zFunc;            /* Function name (nul-terminated) */
209044      void *pUserData;              /* User-data pointer */
209045      fts5_extension_function xFunc;/* Callback function */
209046      void (*xDestroy)(void*);      /* Destructor function */
209047    } aBuiltin [] = {
209048      { "snippet",   0, fts5SnippetFunction, 0 },
209049      { "highlight", 0, fts5HighlightFunction, 0 },
209050      { "bm25",      0, fts5Bm25Function,    0 },
209051    };
209052    int rc = SQLITE_OK;             /* Return code */
209053    int i;                          /* To iterate through builtin functions */
209054  
209055    for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
209056      rc = pApi->xCreateFunction(pApi,
209057          aBuiltin[i].zFunc,
209058          aBuiltin[i].pUserData,
209059          aBuiltin[i].xFunc,
209060          aBuiltin[i].xDestroy
209061      );
209062    }
209063  
209064    return rc;
209065  }
209066  
209067  /*
209068  ** 2014 May 31
209069  **
209070  ** The author disclaims copyright to this source code.  In place of
209071  ** a legal notice, here is a blessing:
209072  **
209073  **    May you do good and not evil.
209074  **    May you find forgiveness for yourself and forgive others.
209075  **    May you share freely, never taking more than you give.
209076  **
209077  ******************************************************************************
209078  */
209079  
209080  
209081  
209082  /* #include "fts5Int.h" */
209083  
209084  static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
209085    if( (u32)pBuf->nSpace<nByte ){
209086      u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
209087      u8 *pNew;
209088      while( nNew<nByte ){
209089        nNew = nNew * 2;
209090      }
209091      pNew = sqlite3_realloc64(pBuf->p, nNew);
209092      if( pNew==0 ){
209093        *pRc = SQLITE_NOMEM;
209094        return 1;
209095      }else{
209096        pBuf->nSpace = nNew;
209097        pBuf->p = pNew;
209098      }
209099    }
209100    return 0;
209101  }
209102  
209103  
209104  /*
209105  ** Encode value iVal as an SQLite varint and append it to the buffer object
209106  ** pBuf. If an OOM error occurs, set the error code in p.
209107  */
209108  static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
209109    if( fts5BufferGrow(pRc, pBuf, 9) ) return;
209110    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
209111  }
209112  
209113  static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
209114    aBuf[0] = (iVal>>24) & 0x00FF;
209115    aBuf[1] = (iVal>>16) & 0x00FF;
209116    aBuf[2] = (iVal>> 8) & 0x00FF;
209117    aBuf[3] = (iVal>> 0) & 0x00FF;
209118  }
209119  
209120  static int sqlite3Fts5Get32(const u8 *aBuf){
209121    return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
209122  }
209123  
209124  /*
209125  ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set 
209126  ** the error code in p. If an error has already occurred when this function
209127  ** is called, it is a no-op.
209128  */
209129  static void sqlite3Fts5BufferAppendBlob(
209130    int *pRc,
209131    Fts5Buffer *pBuf, 
209132    u32 nData, 
209133    const u8 *pData
209134  ){
209135    assert_nc( *pRc || nData>=0 );
209136    if( nData ){
209137      if( fts5BufferGrow(pRc, pBuf, nData) ) return;
209138      memcpy(&pBuf->p[pBuf->n], pData, nData);
209139      pBuf->n += nData;
209140    }
209141  }
209142  
209143  /*
209144  ** Append the nul-terminated string zStr to the buffer pBuf. This function
209145  ** ensures that the byte following the buffer data is set to 0x00, even 
209146  ** though this byte is not included in the pBuf->n count.
209147  */
209148  static void sqlite3Fts5BufferAppendString(
209149    int *pRc,
209150    Fts5Buffer *pBuf, 
209151    const char *zStr
209152  ){
209153    int nStr = (int)strlen(zStr);
209154    sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
209155    pBuf->n--;
209156  }
209157  
209158  /*
209159  ** Argument zFmt is a printf() style format string. This function performs
209160  ** the printf() style processing, then appends the results to buffer pBuf.
209161  **
209162  ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte 
209163  ** following the buffer data is set to 0x00, even though this byte is not
209164  ** included in the pBuf->n count.
209165  */ 
209166  static void sqlite3Fts5BufferAppendPrintf(
209167    int *pRc,
209168    Fts5Buffer *pBuf, 
209169    char *zFmt, ...
209170  ){
209171    if( *pRc==SQLITE_OK ){
209172      char *zTmp;
209173      va_list ap;
209174      va_start(ap, zFmt);
209175      zTmp = sqlite3_vmprintf(zFmt, ap);
209176      va_end(ap);
209177  
209178      if( zTmp==0 ){
209179        *pRc = SQLITE_NOMEM;
209180      }else{
209181        sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
209182        sqlite3_free(zTmp);
209183      }
209184    }
209185  }
209186  
209187  static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
209188    char *zRet = 0;
209189    if( *pRc==SQLITE_OK ){
209190      va_list ap;
209191      va_start(ap, zFmt);
209192      zRet = sqlite3_vmprintf(zFmt, ap);
209193      va_end(ap);
209194      if( zRet==0 ){
209195        *pRc = SQLITE_NOMEM; 
209196      }
209197    }
209198    return zRet;
209199  }
209200   
209201  
209202  /*
209203  ** Free any buffer allocated by pBuf. Zero the structure before returning.
209204  */
209205  static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
209206    sqlite3_free(pBuf->p);
209207    memset(pBuf, 0, sizeof(Fts5Buffer));
209208  }
209209  
209210  /*
209211  ** Zero the contents of the buffer object. But do not free the associated 
209212  ** memory allocation.
209213  */
209214  static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
209215    pBuf->n = 0;
209216  }
209217  
209218  /*
209219  ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
209220  ** the error code in p. If an error has already occurred when this function
209221  ** is called, it is a no-op.
209222  */
209223  static void sqlite3Fts5BufferSet(
209224    int *pRc,
209225    Fts5Buffer *pBuf, 
209226    int nData, 
209227    const u8 *pData
209228  ){
209229    pBuf->n = 0;
209230    sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
209231  }
209232  
209233  static int sqlite3Fts5PoslistNext64(
209234    const u8 *a, int n,             /* Buffer containing poslist */
209235    int *pi,                        /* IN/OUT: Offset within a[] */
209236    i64 *piOff                      /* IN/OUT: Current offset */
209237  ){
209238    int i = *pi;
209239    if( i>=n ){
209240      /* EOF */
209241      *piOff = -1;
209242      return 1;  
209243    }else{
209244      i64 iOff = *piOff;
209245      int iVal;
209246      fts5FastGetVarint32(a, i, iVal);
209247      if( iVal==1 ){
209248        fts5FastGetVarint32(a, i, iVal);
209249        iOff = ((i64)iVal) << 32;
209250        fts5FastGetVarint32(a, i, iVal);
209251      }
209252      *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
209253      *pi = i;
209254      return 0;
209255    }
209256  }
209257  
209258  
209259  /*
209260  ** Advance the iterator object passed as the only argument. Return true
209261  ** if the iterator reaches EOF, or false otherwise.
209262  */
209263  static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
209264    if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
209265      pIter->bEof = 1;
209266    }
209267    return pIter->bEof;
209268  }
209269  
209270  static int sqlite3Fts5PoslistReaderInit(
209271    const u8 *a, int n,             /* Poslist buffer to iterate through */
209272    Fts5PoslistReader *pIter        /* Iterator object to initialize */
209273  ){
209274    memset(pIter, 0, sizeof(*pIter));
209275    pIter->a = a;
209276    pIter->n = n;
209277    sqlite3Fts5PoslistReaderNext(pIter);
209278    return pIter->bEof;
209279  }
209280  
209281  /*
209282  ** Append position iPos to the position list being accumulated in buffer
209283  ** pBuf, which must be already be large enough to hold the new data.
209284  ** The previous position written to this list is *piPrev. *piPrev is set
209285  ** to iPos before returning.
209286  */
209287  static void sqlite3Fts5PoslistSafeAppend(
209288    Fts5Buffer *pBuf, 
209289    i64 *piPrev, 
209290    i64 iPos
209291  ){
209292    static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
209293    if( (iPos & colmask) != (*piPrev & colmask) ){
209294      pBuf->p[pBuf->n++] = 1;
209295      pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
209296      *piPrev = (iPos & colmask);
209297    }
209298    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
209299    *piPrev = iPos;
209300  }
209301  
209302  static int sqlite3Fts5PoslistWriterAppend(
209303    Fts5Buffer *pBuf, 
209304    Fts5PoslistWriter *pWriter,
209305    i64 iPos
209306  ){
209307    int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
209308    if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
209309    sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
209310    return SQLITE_OK;
209311  }
209312  
209313  static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
209314    void *pRet = 0;
209315    if( *pRc==SQLITE_OK ){
209316      pRet = sqlite3_malloc64(nByte);
209317      if( pRet==0 ){
209318        if( nByte>0 ) *pRc = SQLITE_NOMEM;
209319      }else{
209320        memset(pRet, 0, nByte);
209321      }
209322    }
209323    return pRet;
209324  }
209325  
209326  /*
209327  ** Return a nul-terminated copy of the string indicated by pIn. If nIn
209328  ** is non-negative, then it is the length of the string in bytes. Otherwise,
209329  ** the length of the string is determined using strlen().
209330  **
209331  ** It is the responsibility of the caller to eventually free the returned
209332  ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. 
209333  */
209334  static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
209335    char *zRet = 0;
209336    if( *pRc==SQLITE_OK ){
209337      if( nIn<0 ){
209338        nIn = (int)strlen(pIn);
209339      }
209340      zRet = (char*)sqlite3_malloc(nIn+1);
209341      if( zRet ){
209342        memcpy(zRet, pIn, nIn);
209343        zRet[nIn] = '\0';
209344      }else{
209345        *pRc = SQLITE_NOMEM;
209346      }
209347    }
209348    return zRet;
209349  }
209350  
209351  
209352  /*
209353  ** Return true if character 't' may be part of an FTS5 bareword, or false
209354  ** otherwise. Characters that may be part of barewords:
209355  **
209356  **   * All non-ASCII characters,
209357  **   * The 52 upper and lower case ASCII characters, and
209358  **   * The 10 integer ASCII characters.
209359  **   * The underscore character "_" (0x5F).
209360  **   * The unicode "subsitute" character (0x1A).
209361  */
209362  static int sqlite3Fts5IsBareword(char t){
209363    u8 aBareword[128] = {
209364      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
209365      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
209366      0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
209367      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
209368      0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
209369      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
209370      0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
209371      1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
209372    };
209373  
209374    return (t & 0x80) || aBareword[(int)t];
209375  }
209376  
209377  
209378  /*************************************************************************
209379  */
209380  typedef struct Fts5TermsetEntry Fts5TermsetEntry;
209381  struct Fts5TermsetEntry {
209382    char *pTerm;
209383    int nTerm;
209384    int iIdx;                       /* Index (main or aPrefix[] entry) */
209385    Fts5TermsetEntry *pNext;
209386  };
209387  
209388  struct Fts5Termset {
209389    Fts5TermsetEntry *apHash[512];
209390  };
209391  
209392  static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
209393    int rc = SQLITE_OK;
209394    *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
209395    return rc;
209396  }
209397  
209398  static int sqlite3Fts5TermsetAdd(
209399    Fts5Termset *p, 
209400    int iIdx,
209401    const char *pTerm, int nTerm, 
209402    int *pbPresent
209403  ){
209404    int rc = SQLITE_OK;
209405    *pbPresent = 0;
209406    if( p ){
209407      int i;
209408      u32 hash = 13;
209409      Fts5TermsetEntry *pEntry;
209410  
209411      /* Calculate a hash value for this term. This is the same hash checksum
209412      ** used by the fts5_hash.c module. This is not important for correct
209413      ** operation of the module, but is necessary to ensure that some tests
209414      ** designed to produce hash table collisions really do work.  */
209415      for(i=nTerm-1; i>=0; i--){
209416        hash = (hash << 3) ^ hash ^ pTerm[i];
209417      }
209418      hash = (hash << 3) ^ hash ^ iIdx;
209419      hash = hash % ArraySize(p->apHash);
209420  
209421      for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
209422        if( pEntry->iIdx==iIdx 
209423            && pEntry->nTerm==nTerm 
209424            && memcmp(pEntry->pTerm, pTerm, nTerm)==0 
209425        ){
209426          *pbPresent = 1;
209427          break;
209428        }
209429      }
209430  
209431      if( pEntry==0 ){
209432        pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
209433        if( pEntry ){
209434          pEntry->pTerm = (char*)&pEntry[1];
209435          pEntry->nTerm = nTerm;
209436          pEntry->iIdx = iIdx;
209437          memcpy(pEntry->pTerm, pTerm, nTerm);
209438          pEntry->pNext = p->apHash[hash];
209439          p->apHash[hash] = pEntry;
209440        }
209441      }
209442    }
209443  
209444    return rc;
209445  }
209446  
209447  static void sqlite3Fts5TermsetFree(Fts5Termset *p){
209448    if( p ){
209449      u32 i;
209450      for(i=0; i<ArraySize(p->apHash); i++){
209451        Fts5TermsetEntry *pEntry = p->apHash[i];
209452        while( pEntry ){
209453          Fts5TermsetEntry *pDel = pEntry;
209454          pEntry = pEntry->pNext;
209455          sqlite3_free(pDel);
209456        }
209457      }
209458      sqlite3_free(p);
209459    }
209460  }
209461  
209462  /*
209463  ** 2014 Jun 09
209464  **
209465  ** The author disclaims copyright to this source code.  In place of
209466  ** a legal notice, here is a blessing:
209467  **
209468  **    May you do good and not evil.
209469  **    May you find forgiveness for yourself and forgive others.
209470  **    May you share freely, never taking more than you give.
209471  **
209472  ******************************************************************************
209473  **
209474  ** This is an SQLite module implementing full-text search.
209475  */
209476  
209477  
209478  /* #include "fts5Int.h" */
209479  
209480  #define FTS5_DEFAULT_PAGE_SIZE   4050
209481  #define FTS5_DEFAULT_AUTOMERGE      4
209482  #define FTS5_DEFAULT_USERMERGE      4
209483  #define FTS5_DEFAULT_CRISISMERGE   16
209484  #define FTS5_DEFAULT_HASHSIZE    (1024*1024)
209485  
209486  /* Maximum allowed page size */
209487  #define FTS5_MAX_PAGE_SIZE (128*1024)
209488  
209489  static int fts5_iswhitespace(char x){
209490    return (x==' ');
209491  }
209492  
209493  static int fts5_isopenquote(char x){
209494    return (x=='"' || x=='\'' || x=='[' || x=='`');
209495  }
209496  
209497  /*
209498  ** Argument pIn points to a character that is part of a nul-terminated 
209499  ** string. Return a pointer to the first character following *pIn in 
209500  ** the string that is not a white-space character.
209501  */
209502  static const char *fts5ConfigSkipWhitespace(const char *pIn){
209503    const char *p = pIn;
209504    if( p ){
209505      while( fts5_iswhitespace(*p) ){ p++; }
209506    }
209507    return p;
209508  }
209509  
209510  /*
209511  ** Argument pIn points to a character that is part of a nul-terminated 
209512  ** string. Return a pointer to the first character following *pIn in 
209513  ** the string that is not a "bareword" character.
209514  */
209515  static const char *fts5ConfigSkipBareword(const char *pIn){
209516    const char *p = pIn;
209517    while ( sqlite3Fts5IsBareword(*p) ) p++;
209518    if( p==pIn ) p = 0;
209519    return p;
209520  }
209521  
209522  static int fts5_isdigit(char a){
209523    return (a>='0' && a<='9');
209524  }
209525  
209526  
209527  
209528  static const char *fts5ConfigSkipLiteral(const char *pIn){
209529    const char *p = pIn;
209530    switch( *p ){
209531      case 'n': case 'N':
209532        if( sqlite3_strnicmp("null", p, 4)==0 ){
209533          p = &p[4];
209534        }else{
209535          p = 0;
209536        }
209537        break;
209538  
209539      case 'x': case 'X':
209540        p++;
209541        if( *p=='\'' ){
209542          p++;
209543          while( (*p>='a' && *p<='f') 
209544              || (*p>='A' && *p<='F') 
209545              || (*p>='0' && *p<='9') 
209546              ){
209547            p++;
209548          }
209549          if( *p=='\'' && 0==((p-pIn)%2) ){
209550            p++;
209551          }else{
209552            p = 0;
209553          }
209554        }else{
209555          p = 0;
209556        }
209557        break;
209558  
209559      case '\'':
209560        p++;
209561        while( p ){
209562          if( *p=='\'' ){
209563            p++;
209564            if( *p!='\'' ) break;
209565          }
209566          p++;
209567          if( *p==0 ) p = 0;
209568        }
209569        break;
209570  
209571      default:
209572        /* maybe a number */
209573        if( *p=='+' || *p=='-' ) p++;
209574        while( fts5_isdigit(*p) ) p++;
209575  
209576        /* At this point, if the literal was an integer, the parse is 
209577        ** finished. Or, if it is a floating point value, it may continue
209578        ** with either a decimal point or an 'E' character. */
209579        if( *p=='.' && fts5_isdigit(p[1]) ){
209580          p += 2;
209581          while( fts5_isdigit(*p) ) p++;
209582        }
209583        if( p==pIn ) p = 0;
209584  
209585        break;
209586    }
209587  
209588    return p;
209589  }
209590  
209591  /*
209592  ** The first character of the string pointed to by argument z is guaranteed
209593  ** to be an open-quote character (see function fts5_isopenquote()).
209594  **
209595  ** This function searches for the corresponding close-quote character within
209596  ** the string and, if found, dequotes the string in place and adds a new
209597  ** nul-terminator byte.
209598  **
209599  ** If the close-quote is found, the value returned is the byte offset of
209600  ** the character immediately following it. Or, if the close-quote is not 
209601  ** found, -1 is returned. If -1 is returned, the buffer is left in an 
209602  ** undefined state.
209603  */
209604  static int fts5Dequote(char *z){
209605    char q;
209606    int iIn = 1;
209607    int iOut = 0;
209608    q = z[0];
209609  
209610    /* Set stack variable q to the close-quote character */
209611    assert( q=='[' || q=='\'' || q=='"' || q=='`' );
209612    if( q=='[' ) q = ']';  
209613  
209614    while( ALWAYS(z[iIn]) ){
209615      if( z[iIn]==q ){
209616        if( z[iIn+1]!=q ){
209617          /* Character iIn was the close quote. */
209618          iIn++;
209619          break;
209620        }else{
209621          /* Character iIn and iIn+1 form an escaped quote character. Skip
209622          ** the input cursor past both and copy a single quote character 
209623          ** to the output buffer. */
209624          iIn += 2;
209625          z[iOut++] = q;
209626        }
209627      }else{
209628        z[iOut++] = z[iIn++];
209629      }
209630    }
209631  
209632    z[iOut] = '\0';
209633    return iIn;
209634  }
209635  
209636  /*
209637  ** Convert an SQL-style quoted string into a normal string by removing
209638  ** the quote characters.  The conversion is done in-place.  If the
209639  ** input does not begin with a quote character, then this routine
209640  ** is a no-op.
209641  **
209642  ** Examples:
209643  **
209644  **     "abc"   becomes   abc
209645  **     'xyz'   becomes   xyz
209646  **     [pqr]   becomes   pqr
209647  **     `mno`   becomes   mno
209648  */
209649  static void sqlite3Fts5Dequote(char *z){
209650    char quote;                     /* Quote character (if any ) */
209651  
209652    assert( 0==fts5_iswhitespace(z[0]) );
209653    quote = z[0];
209654    if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
209655      fts5Dequote(z);
209656    }
209657  }
209658  
209659  
209660  struct Fts5Enum {
209661    const char *zName;
209662    int eVal;
209663  };
209664  typedef struct Fts5Enum Fts5Enum;
209665  
209666  static int fts5ConfigSetEnum(
209667    const Fts5Enum *aEnum, 
209668    const char *zEnum, 
209669    int *peVal
209670  ){
209671    int nEnum = (int)strlen(zEnum);
209672    int i;
209673    int iVal = -1;
209674  
209675    for(i=0; aEnum[i].zName; i++){
209676      if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
209677        if( iVal>=0 ) return SQLITE_ERROR;
209678        iVal = aEnum[i].eVal;
209679      }
209680    }
209681  
209682    *peVal = iVal;
209683    return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
209684  }
209685  
209686  /*
209687  ** Parse a "special" CREATE VIRTUAL TABLE directive and update
209688  ** configuration object pConfig as appropriate.
209689  **
209690  ** If successful, object pConfig is updated and SQLITE_OK returned. If
209691  ** an error occurs, an SQLite error code is returned and an error message
209692  ** may be left in *pzErr. It is the responsibility of the caller to
209693  ** eventually free any such error message using sqlite3_free().
209694  */
209695  static int fts5ConfigParseSpecial(
209696    Fts5Global *pGlobal,
209697    Fts5Config *pConfig,            /* Configuration object to update */
209698    const char *zCmd,               /* Special command to parse */
209699    const char *zArg,               /* Argument to parse */
209700    char **pzErr                    /* OUT: Error message */
209701  ){
209702    int rc = SQLITE_OK;
209703    int nCmd = (int)strlen(zCmd);
209704    if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
209705      const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
209706      const char *p;
209707      int bFirst = 1;
209708      if( pConfig->aPrefix==0 ){
209709        pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
209710        if( rc ) return rc;
209711      }
209712  
209713      p = zArg;
209714      while( 1 ){
209715        int nPre = 0;
209716  
209717        while( p[0]==' ' ) p++;
209718        if( bFirst==0 && p[0]==',' ){
209719          p++;
209720          while( p[0]==' ' ) p++;
209721        }else if( p[0]=='\0' ){
209722          break;
209723        }
209724        if( p[0]<'0' || p[0]>'9' ){
209725          *pzErr = sqlite3_mprintf("malformed prefix=... directive");
209726          rc = SQLITE_ERROR;
209727          break;
209728        }
209729  
209730        if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
209731          *pzErr = sqlite3_mprintf(
209732              "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
209733          );
209734          rc = SQLITE_ERROR;
209735          break;
209736        }
209737  
209738        while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
209739          nPre = nPre*10 + (p[0] - '0');
209740          p++;
209741        }
209742  
209743        if( nPre<=0 || nPre>=1000 ){
209744          *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
209745          rc = SQLITE_ERROR;
209746          break;
209747        }
209748  
209749        pConfig->aPrefix[pConfig->nPrefix] = nPre;
209750        pConfig->nPrefix++;
209751        bFirst = 0;
209752      }
209753      assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
209754      return rc;
209755    }
209756  
209757    if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
209758      const char *p = (const char*)zArg;
209759      sqlite3_int64 nArg = strlen(zArg) + 1;
209760      char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
209761      char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
209762      char *pSpace = pDel;
209763  
209764      if( azArg && pSpace ){
209765        if( pConfig->pTok ){
209766          *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
209767          rc = SQLITE_ERROR;
209768        }else{
209769          for(nArg=0; p && *p; nArg++){
209770            const char *p2 = fts5ConfigSkipWhitespace(p);
209771            if( *p2=='\'' ){
209772              p = fts5ConfigSkipLiteral(p2);
209773            }else{
209774              p = fts5ConfigSkipBareword(p2);
209775            }
209776            if( p ){
209777              memcpy(pSpace, p2, p-p2);
209778              azArg[nArg] = pSpace;
209779              sqlite3Fts5Dequote(pSpace);
209780              pSpace += (p - p2) + 1;
209781              p = fts5ConfigSkipWhitespace(p);
209782            }
209783          }
209784          if( p==0 ){
209785            *pzErr = sqlite3_mprintf("parse error in tokenize directive");
209786            rc = SQLITE_ERROR;
209787          }else{
209788            rc = sqlite3Fts5GetTokenizer(pGlobal, 
209789                (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
209790                pzErr
209791            );
209792          }
209793        }
209794      }
209795  
209796      sqlite3_free(azArg);
209797      sqlite3_free(pDel);
209798      return rc;
209799    }
209800  
209801    if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
209802      if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
209803        *pzErr = sqlite3_mprintf("multiple content=... directives");
209804        rc = SQLITE_ERROR;
209805      }else{
209806        if( zArg[0] ){
209807          pConfig->eContent = FTS5_CONTENT_EXTERNAL;
209808          pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
209809        }else{
209810          pConfig->eContent = FTS5_CONTENT_NONE;
209811        }
209812      }
209813      return rc;
209814    }
209815  
209816    if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
209817      if( pConfig->zContentRowid ){
209818        *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
209819        rc = SQLITE_ERROR;
209820      }else{
209821        pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
209822      }
209823      return rc;
209824    }
209825  
209826    if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
209827      if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
209828        *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
209829        rc = SQLITE_ERROR;
209830      }else{
209831        pConfig->bColumnsize = (zArg[0]=='1');
209832      }
209833      return rc;
209834    }
209835  
209836    if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
209837      const Fts5Enum aDetail[] = {
209838        { "none", FTS5_DETAIL_NONE },
209839        { "full", FTS5_DETAIL_FULL },
209840        { "columns", FTS5_DETAIL_COLUMNS },
209841        { 0, 0 }
209842      };
209843  
209844      if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
209845        *pzErr = sqlite3_mprintf("malformed detail=... directive");
209846      }
209847      return rc;
209848    }
209849  
209850    *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
209851    return SQLITE_ERROR;
209852  }
209853  
209854  /*
209855  ** Allocate an instance of the default tokenizer ("simple") at 
209856  ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
209857  ** code if an error occurs.
209858  */
209859  static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
209860    assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
209861    return sqlite3Fts5GetTokenizer(
209862        pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
209863    );
209864  }
209865  
209866  /*
209867  ** Gobble up the first bareword or quoted word from the input buffer zIn.
209868  ** Return a pointer to the character immediately following the last in
209869  ** the gobbled word if successful, or a NULL pointer otherwise (failed
209870  ** to find close-quote character).
209871  **
209872  ** Before returning, set pzOut to point to a new buffer containing a
209873  ** nul-terminated, dequoted copy of the gobbled word. If the word was
209874  ** quoted, *pbQuoted is also set to 1 before returning.
209875  **
209876  ** If *pRc is other than SQLITE_OK when this function is called, it is
209877  ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
209878  ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
209879  ** set if a parse error (failed to find close quote) occurs.
209880  */
209881  static const char *fts5ConfigGobbleWord(
209882    int *pRc,                       /* IN/OUT: Error code */
209883    const char *zIn,                /* Buffer to gobble string/bareword from */
209884    char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
209885    int *pbQuoted                   /* OUT: Set to true if dequoting required */
209886  ){
209887    const char *zRet = 0;
209888  
209889    sqlite3_int64 nIn = strlen(zIn);
209890    char *zOut = sqlite3_malloc64(nIn+1);
209891  
209892    assert( *pRc==SQLITE_OK );
209893    *pbQuoted = 0;
209894    *pzOut = 0;
209895  
209896    if( zOut==0 ){
209897      *pRc = SQLITE_NOMEM;
209898    }else{
209899      memcpy(zOut, zIn, nIn+1);
209900      if( fts5_isopenquote(zOut[0]) ){
209901        int ii = fts5Dequote(zOut);
209902        zRet = &zIn[ii];
209903        *pbQuoted = 1;
209904      }else{
209905        zRet = fts5ConfigSkipBareword(zIn);
209906        if( zRet ){
209907          zOut[zRet-zIn] = '\0';
209908        }
209909      }
209910    }
209911  
209912    if( zRet==0 ){
209913      sqlite3_free(zOut);
209914    }else{
209915      *pzOut = zOut;
209916    }
209917  
209918    return zRet;
209919  }
209920  
209921  static int fts5ConfigParseColumn(
209922    Fts5Config *p, 
209923    char *zCol, 
209924    char *zArg, 
209925    char **pzErr
209926  ){
209927    int rc = SQLITE_OK;
209928    if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) 
209929     || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) 
209930    ){
209931      *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
209932      rc = SQLITE_ERROR;
209933    }else if( zArg ){
209934      if( 0==sqlite3_stricmp(zArg, "unindexed") ){
209935        p->abUnindexed[p->nCol] = 1;
209936      }else{
209937        *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
209938        rc = SQLITE_ERROR;
209939      }
209940    }
209941  
209942    p->azCol[p->nCol++] = zCol;
209943    return rc;
209944  }
209945  
209946  /*
209947  ** Populate the Fts5Config.zContentExprlist string.
209948  */
209949  static int fts5ConfigMakeExprlist(Fts5Config *p){
209950    int i;
209951    int rc = SQLITE_OK;
209952    Fts5Buffer buf = {0, 0, 0};
209953  
209954    sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
209955    if( p->eContent!=FTS5_CONTENT_NONE ){
209956      for(i=0; i<p->nCol; i++){
209957        if( p->eContent==FTS5_CONTENT_EXTERNAL ){
209958          sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
209959        }else{
209960          sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
209961        }
209962      }
209963    }
209964  
209965    assert( p->zContentExprlist==0 );
209966    p->zContentExprlist = (char*)buf.p;
209967    return rc;
209968  }
209969  
209970  /*
209971  ** Arguments nArg/azArg contain the string arguments passed to the xCreate
209972  ** or xConnect method of the virtual table. This function attempts to 
209973  ** allocate an instance of Fts5Config containing the results of parsing
209974  ** those arguments.
209975  **
209976  ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
209977  ** new Fts5Config object. If an error occurs, an SQLite error code is 
209978  ** returned, *ppOut is set to NULL and an error message may be left in
209979  ** *pzErr. It is the responsibility of the caller to eventually free any 
209980  ** such error message using sqlite3_free().
209981  */
209982  static int sqlite3Fts5ConfigParse(
209983    Fts5Global *pGlobal,
209984    sqlite3 *db,
209985    int nArg,                       /* Number of arguments */
209986    const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
209987    Fts5Config **ppOut,             /* OUT: Results of parse */
209988    char **pzErr                    /* OUT: Error message */
209989  ){
209990    int rc = SQLITE_OK;             /* Return code */
209991    Fts5Config *pRet;               /* New object to return */
209992    int i;
209993    sqlite3_int64 nByte;
209994  
209995    *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
209996    if( pRet==0 ) return SQLITE_NOMEM;
209997    memset(pRet, 0, sizeof(Fts5Config));
209998    pRet->db = db;
209999    pRet->iCookie = -1;
210000  
210001    nByte = nArg * (sizeof(char*) + sizeof(u8));
210002    pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
210003    pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
210004    pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
210005    pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
210006    pRet->bColumnsize = 1;
210007    pRet->eDetail = FTS5_DETAIL_FULL;
210008  #ifdef SQLITE_DEBUG
210009    pRet->bPrefixIndex = 1;
210010  #endif
210011    if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
210012      *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
210013      rc = SQLITE_ERROR;
210014    }
210015  
210016    for(i=3; rc==SQLITE_OK && i<nArg; i++){
210017      const char *zOrig = azArg[i];
210018      const char *z;
210019      char *zOne = 0;
210020      char *zTwo = 0;
210021      int bOption = 0;
210022      int bMustBeCol = 0;
210023  
210024      z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
210025      z = fts5ConfigSkipWhitespace(z);
210026      if( z && *z=='=' ){
210027        bOption = 1;
210028        z++;
210029        if( bMustBeCol ) z = 0;
210030      }
210031      z = fts5ConfigSkipWhitespace(z);
210032      if( z && z[0] ){
210033        int bDummy;
210034        z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
210035        if( z && z[0] ) z = 0;
210036      }
210037  
210038      if( rc==SQLITE_OK ){
210039        if( z==0 ){
210040          *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
210041          rc = SQLITE_ERROR;
210042        }else{
210043          if( bOption ){
210044            rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
210045          }else{
210046            rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
210047            zOne = 0;
210048          }
210049        }
210050      }
210051  
210052      sqlite3_free(zOne);
210053      sqlite3_free(zTwo);
210054    }
210055  
210056    /* If a tokenizer= option was successfully parsed, the tokenizer has
210057    ** already been allocated. Otherwise, allocate an instance of the default
210058    ** tokenizer (unicode61) now.  */
210059    if( rc==SQLITE_OK && pRet->pTok==0 ){
210060      rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
210061    }
210062  
210063    /* If no zContent option was specified, fill in the default values. */
210064    if( rc==SQLITE_OK && pRet->zContent==0 ){
210065      const char *zTail = 0;
210066      assert( pRet->eContent==FTS5_CONTENT_NORMAL 
210067           || pRet->eContent==FTS5_CONTENT_NONE 
210068      );
210069      if( pRet->eContent==FTS5_CONTENT_NORMAL ){
210070        zTail = "content";
210071      }else if( pRet->bColumnsize ){
210072        zTail = "docsize";
210073      }
210074  
210075      if( zTail ){
210076        pRet->zContent = sqlite3Fts5Mprintf(
210077            &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
210078        );
210079      }
210080    }
210081  
210082    if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
210083      pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
210084    }
210085  
210086    /* Formulate the zContentExprlist text */
210087    if( rc==SQLITE_OK ){
210088      rc = fts5ConfigMakeExprlist(pRet);
210089    }
210090  
210091    if( rc!=SQLITE_OK ){
210092      sqlite3Fts5ConfigFree(pRet);
210093      *ppOut = 0;
210094    }
210095    return rc;
210096  }
210097  
210098  /*
210099  ** Free the configuration object passed as the only argument.
210100  */
210101  static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
210102    if( pConfig ){
210103      int i;
210104      if( pConfig->pTok ){
210105        pConfig->pTokApi->xDelete(pConfig->pTok);
210106      }
210107      sqlite3_free(pConfig->zDb);
210108      sqlite3_free(pConfig->zName);
210109      for(i=0; i<pConfig->nCol; i++){
210110        sqlite3_free(pConfig->azCol[i]);
210111      }
210112      sqlite3_free(pConfig->azCol);
210113      sqlite3_free(pConfig->aPrefix);
210114      sqlite3_free(pConfig->zRank);
210115      sqlite3_free(pConfig->zRankArgs);
210116      sqlite3_free(pConfig->zContent);
210117      sqlite3_free(pConfig->zContentRowid);
210118      sqlite3_free(pConfig->zContentExprlist);
210119      sqlite3_free(pConfig);
210120    }
210121  }
210122  
210123  /*
210124  ** Call sqlite3_declare_vtab() based on the contents of the configuration
210125  ** object passed as the only argument. Return SQLITE_OK if successful, or
210126  ** an SQLite error code if an error occurs.
210127  */
210128  static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
210129    int i;
210130    int rc = SQLITE_OK;
210131    char *zSql;
210132  
210133    zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
210134    for(i=0; zSql && i<pConfig->nCol; i++){
210135      const char *zSep = (i==0?"":", ");
210136      zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
210137    }
210138    zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", 
210139        zSql, pConfig->zName, FTS5_RANK_NAME
210140    );
210141  
210142    assert( zSql || rc==SQLITE_NOMEM );
210143    if( zSql ){
210144      rc = sqlite3_declare_vtab(pConfig->db, zSql);
210145      sqlite3_free(zSql);
210146    }
210147    
210148    return rc;
210149  }
210150  
210151  /*
210152  ** Tokenize the text passed via the second and third arguments.
210153  **
210154  ** The callback is invoked once for each token in the input text. The
210155  ** arguments passed to it are, in order:
210156  **
210157  **     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
210158  **     const char *pToken  // Pointer to buffer containing token
210159  **     int nToken          // Size of token in bytes
210160  **     int iStart          // Byte offset of start of token within input text
210161  **     int iEnd            // Byte offset of end of token within input text
210162  **     int iPos            // Position of token in input (first token is 0)
210163  **
210164  ** If the callback returns a non-zero value the tokenization is abandoned
210165  ** and no further callbacks are issued. 
210166  **
210167  ** This function returns SQLITE_OK if successful or an SQLite error code
210168  ** if an error occurs. If the tokenization was abandoned early because
210169  ** the callback returned SQLITE_DONE, this is not an error and this function
210170  ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
210171  ** because the callback returned another non-zero value, it is assumed
210172  ** to be an SQLite error code and returned to the caller.
210173  */
210174  static int sqlite3Fts5Tokenize(
210175    Fts5Config *pConfig,            /* FTS5 Configuration object */
210176    int flags,                      /* FTS5_TOKENIZE_* flags */
210177    const char *pText, int nText,   /* Text to tokenize */
210178    void *pCtx,                     /* Context passed to xToken() */
210179    int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
210180  ){
210181    if( pText==0 ) return SQLITE_OK;
210182    return pConfig->pTokApi->xTokenize(
210183        pConfig->pTok, pCtx, flags, pText, nText, xToken
210184    );
210185  }
210186  
210187  /*
210188  ** Argument pIn points to the first character in what is expected to be
210189  ** a comma-separated list of SQL literals followed by a ')' character.
210190  ** If it actually is this, return a pointer to the ')'. Otherwise, return
210191  ** NULL to indicate a parse error.
210192  */
210193  static const char *fts5ConfigSkipArgs(const char *pIn){
210194    const char *p = pIn;
210195    
210196    while( 1 ){
210197      p = fts5ConfigSkipWhitespace(p);
210198      p = fts5ConfigSkipLiteral(p);
210199      p = fts5ConfigSkipWhitespace(p);
210200      if( p==0 || *p==')' ) break;
210201      if( *p!=',' ){
210202        p = 0;
210203        break;
210204      }
210205      p++;
210206    }
210207  
210208    return p;
210209  }
210210  
210211  /*
210212  ** Parameter zIn contains a rank() function specification. The format of 
210213  ** this is:
210214  **
210215  **   + Bareword (function name)
210216  **   + Open parenthesis - "("
210217  **   + Zero or more SQL literals in a comma separated list
210218  **   + Close parenthesis - ")"
210219  */
210220  static int sqlite3Fts5ConfigParseRank(
210221    const char *zIn,                /* Input string */
210222    char **pzRank,                  /* OUT: Rank function name */
210223    char **pzRankArgs               /* OUT: Rank function arguments */
210224  ){
210225    const char *p = zIn;
210226    const char *pRank;
210227    char *zRank = 0;
210228    char *zRankArgs = 0;
210229    int rc = SQLITE_OK;
210230  
210231    *pzRank = 0;
210232    *pzRankArgs = 0;
210233  
210234    if( p==0 ){
210235      rc = SQLITE_ERROR;
210236    }else{
210237      p = fts5ConfigSkipWhitespace(p);
210238      pRank = p;
210239      p = fts5ConfigSkipBareword(p);
210240  
210241      if( p ){
210242        zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
210243        if( zRank ) memcpy(zRank, pRank, p-pRank);
210244      }else{
210245        rc = SQLITE_ERROR;
210246      }
210247  
210248      if( rc==SQLITE_OK ){
210249        p = fts5ConfigSkipWhitespace(p);
210250        if( *p!='(' ) rc = SQLITE_ERROR;
210251        p++;
210252      }
210253      if( rc==SQLITE_OK ){
210254        const char *pArgs; 
210255        p = fts5ConfigSkipWhitespace(p);
210256        pArgs = p;
210257        if( *p!=')' ){
210258          p = fts5ConfigSkipArgs(p);
210259          if( p==0 ){
210260            rc = SQLITE_ERROR;
210261          }else{
210262            zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
210263            if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
210264          }
210265        }
210266      }
210267    }
210268  
210269    if( rc!=SQLITE_OK ){
210270      sqlite3_free(zRank);
210271      assert( zRankArgs==0 );
210272    }else{
210273      *pzRank = zRank;
210274      *pzRankArgs = zRankArgs;
210275    }
210276    return rc;
210277  }
210278  
210279  static int sqlite3Fts5ConfigSetValue(
210280    Fts5Config *pConfig, 
210281    const char *zKey, 
210282    sqlite3_value *pVal,
210283    int *pbBadkey
210284  ){
210285    int rc = SQLITE_OK;
210286  
210287    if( 0==sqlite3_stricmp(zKey, "pgsz") ){
210288      int pgsz = 0;
210289      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
210290        pgsz = sqlite3_value_int(pVal);
210291      }
210292      if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
210293        *pbBadkey = 1;
210294      }else{
210295        pConfig->pgsz = pgsz;
210296      }
210297    }
210298  
210299    else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
210300      int nHashSize = -1;
210301      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
210302        nHashSize = sqlite3_value_int(pVal);
210303      }
210304      if( nHashSize<=0 ){
210305        *pbBadkey = 1;
210306      }else{
210307        pConfig->nHashSize = nHashSize;
210308      }
210309    }
210310  
210311    else if( 0==sqlite3_stricmp(zKey, "automerge") ){
210312      int nAutomerge = -1;
210313      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
210314        nAutomerge = sqlite3_value_int(pVal);
210315      }
210316      if( nAutomerge<0 || nAutomerge>64 ){
210317        *pbBadkey = 1;
210318      }else{
210319        if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
210320        pConfig->nAutomerge = nAutomerge;
210321      }
210322    }
210323  
210324    else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
210325      int nUsermerge = -1;
210326      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
210327        nUsermerge = sqlite3_value_int(pVal);
210328      }
210329      if( nUsermerge<2 || nUsermerge>16 ){
210330        *pbBadkey = 1;
210331      }else{
210332        pConfig->nUsermerge = nUsermerge;
210333      }
210334    }
210335  
210336    else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
210337      int nCrisisMerge = -1;
210338      if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
210339        nCrisisMerge = sqlite3_value_int(pVal);
210340      }
210341      if( nCrisisMerge<0 ){
210342        *pbBadkey = 1;
210343      }else{
210344        if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
210345        pConfig->nCrisisMerge = nCrisisMerge;
210346      }
210347    }
210348  
210349    else if( 0==sqlite3_stricmp(zKey, "rank") ){
210350      const char *zIn = (const char*)sqlite3_value_text(pVal);
210351      char *zRank;
210352      char *zRankArgs;
210353      rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
210354      if( rc==SQLITE_OK ){
210355        sqlite3_free(pConfig->zRank);
210356        sqlite3_free(pConfig->zRankArgs);
210357        pConfig->zRank = zRank;
210358        pConfig->zRankArgs = zRankArgs;
210359      }else if( rc==SQLITE_ERROR ){
210360        rc = SQLITE_OK;
210361        *pbBadkey = 1;
210362      }
210363    }else{
210364      *pbBadkey = 1;
210365    }
210366    return rc;
210367  }
210368  
210369  /*
210370  ** Load the contents of the %_config table into memory.
210371  */
210372  static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
210373    const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
210374    char *zSql;
210375    sqlite3_stmt *p = 0;
210376    int rc = SQLITE_OK;
210377    int iVersion = 0;
210378  
210379    /* Set default values */
210380    pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
210381    pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
210382    pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
210383    pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
210384    pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
210385  
210386    zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
210387    if( zSql ){
210388      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
210389      sqlite3_free(zSql);
210390    }
210391  
210392    assert( rc==SQLITE_OK || p==0 );
210393    if( rc==SQLITE_OK ){
210394      while( SQLITE_ROW==sqlite3_step(p) ){
210395        const char *zK = (const char*)sqlite3_column_text(p, 0);
210396        sqlite3_value *pVal = sqlite3_column_value(p, 1);
210397        if( 0==sqlite3_stricmp(zK, "version") ){
210398          iVersion = sqlite3_value_int(pVal);
210399        }else{
210400          int bDummy = 0;
210401          sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
210402        }
210403      }
210404      rc = sqlite3_finalize(p);
210405    }
210406    
210407    if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
210408      rc = SQLITE_ERROR;
210409      if( pConfig->pzErrmsg ){
210410        assert( 0==*pConfig->pzErrmsg );
210411        *pConfig->pzErrmsg = sqlite3_mprintf(
210412            "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
210413            iVersion, FTS5_CURRENT_VERSION
210414        );
210415      }
210416    }
210417  
210418    if( rc==SQLITE_OK ){
210419      pConfig->iCookie = iCookie;
210420    }
210421    return rc;
210422  }
210423  
210424  /*
210425  ** 2014 May 31
210426  **
210427  ** The author disclaims copyright to this source code.  In place of
210428  ** a legal notice, here is a blessing:
210429  **
210430  **    May you do good and not evil.
210431  **    May you find forgiveness for yourself and forgive others.
210432  **    May you share freely, never taking more than you give.
210433  **
210434  ******************************************************************************
210435  **
210436  */
210437  
210438  
210439  
210440  /* #include "fts5Int.h" */
210441  /* #include "fts5parse.h" */
210442  
210443  /*
210444  ** All token types in the generated fts5parse.h file are greater than 0.
210445  */
210446  #define FTS5_EOF 0
210447  
210448  #define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
210449  
210450  typedef struct Fts5ExprTerm Fts5ExprTerm;
210451  
210452  /*
210453  ** Functions generated by lemon from fts5parse.y.
210454  */
210455  static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
210456  static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
210457  static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
210458  #ifndef NDEBUG
210459  /* #include <stdio.h> */
210460  static void sqlite3Fts5ParserTrace(FILE*, char*);
210461  #endif
210462  static int sqlite3Fts5ParserFallback(int);
210463  
210464  
210465  struct Fts5Expr {
210466    Fts5Index *pIndex;
210467    Fts5Config *pConfig;
210468    Fts5ExprNode *pRoot;
210469    int bDesc;                      /* Iterate in descending rowid order */
210470    int nPhrase;                    /* Number of phrases in expression */
210471    Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
210472  };
210473  
210474  /*
210475  ** eType:
210476  **   Expression node type. Always one of:
210477  **
210478  **       FTS5_AND                 (nChild, apChild valid)
210479  **       FTS5_OR                  (nChild, apChild valid)
210480  **       FTS5_NOT                 (nChild, apChild valid)
210481  **       FTS5_STRING              (pNear valid)
210482  **       FTS5_TERM                (pNear valid)
210483  */
210484  struct Fts5ExprNode {
210485    int eType;                      /* Node type */
210486    int bEof;                       /* True at EOF */
210487    int bNomatch;                   /* True if entry is not a match */
210488  
210489    /* Next method for this node. */
210490    int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
210491  
210492    i64 iRowid;                     /* Current rowid */
210493    Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
210494  
210495    /* Child nodes. For a NOT node, this array always contains 2 entries. For 
210496    ** AND or OR nodes, it contains 2 or more entries.  */
210497    int nChild;                     /* Number of child nodes */
210498    Fts5ExprNode *apChild[1];       /* Array of child nodes */
210499  };
210500  
210501  #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
210502  
210503  /*
210504  ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
210505  ** used as if it has the same signature as the xNext() methods themselves.
210506  */
210507  #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
210508  
210509  /*
210510  ** An instance of the following structure represents a single search term
210511  ** or term prefix.
210512  */
210513  struct Fts5ExprTerm {
210514    u8 bPrefix;                     /* True for a prefix term */
210515    u8 bFirst;                      /* True if token must be first in column */
210516    char *zTerm;                    /* nul-terminated term */
210517    Fts5IndexIter *pIter;           /* Iterator for this term */
210518    Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
210519  };
210520  
210521  /*
210522  ** A phrase. One or more terms that must appear in a contiguous sequence
210523  ** within a document for it to match.
210524  */
210525  struct Fts5ExprPhrase {
210526    Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
210527    Fts5Buffer poslist;             /* Current position list */
210528    int nTerm;                      /* Number of entries in aTerm[] */
210529    Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
210530  };
210531  
210532  /*
210533  ** One or more phrases that must appear within a certain token distance of
210534  ** each other within each matching document.
210535  */
210536  struct Fts5ExprNearset {
210537    int nNear;                      /* NEAR parameter */
210538    Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
210539    int nPhrase;                    /* Number of entries in aPhrase[] array */
210540    Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
210541  };
210542  
210543  
210544  /*
210545  ** Parse context.
210546  */
210547  struct Fts5Parse {
210548    Fts5Config *pConfig;
210549    char *zErr;
210550    int rc;
210551    int nPhrase;                    /* Size of apPhrase array */
210552    Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
210553    Fts5ExprNode *pExpr;            /* Result of a successful parse */
210554  };
210555  
210556  static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
210557    va_list ap;
210558    va_start(ap, zFmt);
210559    if( pParse->rc==SQLITE_OK ){
210560      pParse->zErr = sqlite3_vmprintf(zFmt, ap);
210561      pParse->rc = SQLITE_ERROR;
210562    }
210563    va_end(ap);
210564  }
210565  
210566  static int fts5ExprIsspace(char t){
210567    return t==' ' || t=='\t' || t=='\n' || t=='\r';
210568  }
210569  
210570  /*
210571  ** Read the first token from the nul-terminated string at *pz.
210572  */
210573  static int fts5ExprGetToken(
210574    Fts5Parse *pParse, 
210575    const char **pz,                /* IN/OUT: Pointer into buffer */
210576    Fts5Token *pToken
210577  ){
210578    const char *z = *pz;
210579    int tok;
210580  
210581    /* Skip past any whitespace */
210582    while( fts5ExprIsspace(*z) ) z++;
210583  
210584    pToken->p = z;
210585    pToken->n = 1;
210586    switch( *z ){
210587      case '(':  tok = FTS5_LP;    break;
210588      case ')':  tok = FTS5_RP;    break;
210589      case '{':  tok = FTS5_LCP;   break;
210590      case '}':  tok = FTS5_RCP;   break;
210591      case ':':  tok = FTS5_COLON; break;
210592      case ',':  tok = FTS5_COMMA; break;
210593      case '+':  tok = FTS5_PLUS;  break;
210594      case '*':  tok = FTS5_STAR;  break;
210595      case '-':  tok = FTS5_MINUS; break;
210596      case '^':  tok = FTS5_CARET; break;
210597      case '\0': tok = FTS5_EOF;   break;
210598  
210599      case '"': {
210600        const char *z2;
210601        tok = FTS5_STRING;
210602  
210603        for(z2=&z[1]; 1; z2++){
210604          if( z2[0]=='"' ){
210605            z2++;
210606            if( z2[0]!='"' ) break;
210607          }
210608          if( z2[0]=='\0' ){
210609            sqlite3Fts5ParseError(pParse, "unterminated string");
210610            return FTS5_EOF;
210611          }
210612        }
210613        pToken->n = (z2 - z);
210614        break;
210615      }
210616  
210617      default: {
210618        const char *z2;
210619        if( sqlite3Fts5IsBareword(z[0])==0 ){
210620          sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
210621          return FTS5_EOF;
210622        }
210623        tok = FTS5_STRING;
210624        for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
210625        pToken->n = (z2 - z);
210626        if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
210627        if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
210628        if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
210629        break;
210630      }
210631    }
210632  
210633    *pz = &pToken->p[pToken->n];
210634    return tok;
210635  }
210636  
210637  static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
210638  static void fts5ParseFree(void *p){ sqlite3_free(p); }
210639  
210640  static int sqlite3Fts5ExprNew(
210641    Fts5Config *pConfig,            /* FTS5 Configuration */
210642    int iCol,
210643    const char *zExpr,              /* Expression text */
210644    Fts5Expr **ppNew, 
210645    char **pzErr
210646  ){
210647    Fts5Parse sParse;
210648    Fts5Token token;
210649    const char *z = zExpr;
210650    int t;                          /* Next token type */
210651    void *pEngine;
210652    Fts5Expr *pNew;
210653  
210654    *ppNew = 0;
210655    *pzErr = 0;
210656    memset(&sParse, 0, sizeof(sParse));
210657    pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
210658    if( pEngine==0 ){ return SQLITE_NOMEM; }
210659    sParse.pConfig = pConfig;
210660  
210661    do {
210662      t = fts5ExprGetToken(&sParse, &z, &token);
210663      sqlite3Fts5Parser(pEngine, t, token, &sParse);
210664    }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
210665    sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
210666  
210667    /* If the LHS of the MATCH expression was a user column, apply the
210668    ** implicit column-filter.  */
210669    if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
210670      int n = sizeof(Fts5Colset);
210671      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
210672      if( pColset ){
210673        pColset->nCol = 1;
210674        pColset->aiCol[0] = iCol;
210675        sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
210676      }
210677    }
210678  
210679    assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
210680    if( sParse.rc==SQLITE_OK ){
210681      *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
210682      if( pNew==0 ){
210683        sParse.rc = SQLITE_NOMEM;
210684        sqlite3Fts5ParseNodeFree(sParse.pExpr);
210685      }else{
210686        if( !sParse.pExpr ){
210687          const int nByte = sizeof(Fts5ExprNode);
210688          pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
210689          if( pNew->pRoot ){
210690            pNew->pRoot->bEof = 1;
210691          }
210692        }else{
210693          pNew->pRoot = sParse.pExpr;
210694        }
210695        pNew->pIndex = 0;
210696        pNew->pConfig = pConfig;
210697        pNew->apExprPhrase = sParse.apPhrase;
210698        pNew->nPhrase = sParse.nPhrase;
210699        sParse.apPhrase = 0;
210700      }
210701    }else{
210702      sqlite3Fts5ParseNodeFree(sParse.pExpr);
210703    }
210704  
210705    sqlite3_free(sParse.apPhrase);
210706    *pzErr = sParse.zErr;
210707    return sParse.rc;
210708  }
210709  
210710  /*
210711  ** Free the expression node object passed as the only argument.
210712  */
210713  static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
210714    if( p ){
210715      int i;
210716      for(i=0; i<p->nChild; i++){
210717        sqlite3Fts5ParseNodeFree(p->apChild[i]);
210718      }
210719      sqlite3Fts5ParseNearsetFree(p->pNear);
210720      sqlite3_free(p);
210721    }
210722  }
210723  
210724  /*
210725  ** Free the expression object passed as the only argument.
210726  */
210727  static void sqlite3Fts5ExprFree(Fts5Expr *p){
210728    if( p ){
210729      sqlite3Fts5ParseNodeFree(p->pRoot);
210730      sqlite3_free(p->apExprPhrase);
210731      sqlite3_free(p);
210732    }
210733  }
210734  
210735  /*
210736  ** Argument pTerm must be a synonym iterator. Return the current rowid
210737  ** that it points to.
210738  */
210739  static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
210740    i64 iRet = 0;
210741    int bRetValid = 0;
210742    Fts5ExprTerm *p;
210743  
210744    assert( pTerm->pSynonym );
210745    assert( bDesc==0 || bDesc==1 );
210746    for(p=pTerm; p; p=p->pSynonym){
210747      if( 0==sqlite3Fts5IterEof(p->pIter) ){
210748        i64 iRowid = p->pIter->iRowid;
210749        if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
210750          iRet = iRowid;
210751          bRetValid = 1;
210752        }
210753      }
210754    }
210755  
210756    if( pbEof && bRetValid==0 ) *pbEof = 1;
210757    return iRet;
210758  }
210759  
210760  /*
210761  ** Argument pTerm must be a synonym iterator.
210762  */
210763  static int fts5ExprSynonymList(
210764    Fts5ExprTerm *pTerm, 
210765    i64 iRowid,
210766    Fts5Buffer *pBuf,               /* Use this buffer for space if required */
210767    u8 **pa, int *pn
210768  ){
210769    Fts5PoslistReader aStatic[4];
210770    Fts5PoslistReader *aIter = aStatic;
210771    int nIter = 0;
210772    int nAlloc = 4;
210773    int rc = SQLITE_OK;
210774    Fts5ExprTerm *p;
210775  
210776    assert( pTerm->pSynonym );
210777    for(p=pTerm; p; p=p->pSynonym){
210778      Fts5IndexIter *pIter = p->pIter;
210779      if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
210780        if( pIter->nData==0 ) continue;
210781        if( nIter==nAlloc ){
210782          sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
210783          Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
210784          if( aNew==0 ){
210785            rc = SQLITE_NOMEM;
210786            goto synonym_poslist_out;
210787          }
210788          memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
210789          nAlloc = nAlloc*2;
210790          if( aIter!=aStatic ) sqlite3_free(aIter);
210791          aIter = aNew;
210792        }
210793        sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
210794        assert( aIter[nIter].bEof==0 );
210795        nIter++;
210796      }
210797    }
210798  
210799    if( nIter==1 ){
210800      *pa = (u8*)aIter[0].a;
210801      *pn = aIter[0].n;
210802    }else{
210803      Fts5PoslistWriter writer = {0};
210804      i64 iPrev = -1;
210805      fts5BufferZero(pBuf);
210806      while( 1 ){
210807        int i;
210808        i64 iMin = FTS5_LARGEST_INT64;
210809        for(i=0; i<nIter; i++){
210810          if( aIter[i].bEof==0 ){
210811            if( aIter[i].iPos==iPrev ){
210812              if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
210813            }
210814            if( aIter[i].iPos<iMin ){
210815              iMin = aIter[i].iPos;
210816            }
210817          }
210818        }
210819        if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
210820        rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
210821        iPrev = iMin;
210822      }
210823      if( rc==SQLITE_OK ){
210824        *pa = pBuf->p;
210825        *pn = pBuf->n;
210826      }
210827    }
210828  
210829   synonym_poslist_out:
210830    if( aIter!=aStatic ) sqlite3_free(aIter);
210831    return rc;
210832  }
210833  
210834  
210835  /*
210836  ** All individual term iterators in pPhrase are guaranteed to be valid and
210837  ** pointing to the same rowid when this function is called. This function 
210838  ** checks if the current rowid really is a match, and if so populates
210839  ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
210840  ** is set to true if this is really a match, or false otherwise.
210841  **
210842  ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
210843  ** otherwise. It is not considered an error code if the current rowid is 
210844  ** not a match.
210845  */
210846  static int fts5ExprPhraseIsMatch(
210847    Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
210848    Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
210849    int *pbMatch                    /* OUT: Set to true if really a match */
210850  ){
210851    Fts5PoslistWriter writer = {0};
210852    Fts5PoslistReader aStatic[4];
210853    Fts5PoslistReader *aIter = aStatic;
210854    int i;
210855    int rc = SQLITE_OK;
210856    int bFirst = pPhrase->aTerm[0].bFirst;
210857    
210858    fts5BufferZero(&pPhrase->poslist);
210859  
210860    /* If the aStatic[] array is not large enough, allocate a large array
210861    ** using sqlite3_malloc(). This approach could be improved upon. */
210862    if( pPhrase->nTerm>ArraySize(aStatic) ){
210863      sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
210864      aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
210865      if( !aIter ) return SQLITE_NOMEM;
210866    }
210867    memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
210868  
210869    /* Initialize a term iterator for each term in the phrase */
210870    for(i=0; i<pPhrase->nTerm; i++){
210871      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
210872      int n = 0;
210873      int bFlag = 0;
210874      u8 *a = 0;
210875      if( pTerm->pSynonym ){
210876        Fts5Buffer buf = {0, 0, 0};
210877        rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
210878        if( rc ){
210879          sqlite3_free(a);
210880          goto ismatch_out;
210881        }
210882        if( a==buf.p ) bFlag = 1;
210883      }else{
210884        a = (u8*)pTerm->pIter->pData;
210885        n = pTerm->pIter->nData;
210886      }
210887      sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
210888      aIter[i].bFlag = (u8)bFlag;
210889      if( aIter[i].bEof ) goto ismatch_out;
210890    }
210891  
210892    while( 1 ){
210893      int bMatch;
210894      i64 iPos = aIter[0].iPos;
210895      do {
210896        bMatch = 1;
210897        for(i=0; i<pPhrase->nTerm; i++){
210898          Fts5PoslistReader *pPos = &aIter[i];
210899          i64 iAdj = iPos + i;
210900          if( pPos->iPos!=iAdj ){
210901            bMatch = 0;
210902            while( pPos->iPos<iAdj ){
210903              if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
210904            }
210905            if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
210906          }
210907        }
210908      }while( bMatch==0 );
210909  
210910      /* Append position iPos to the output */
210911      if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
210912        rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
210913        if( rc!=SQLITE_OK ) goto ismatch_out;
210914      }
210915  
210916      for(i=0; i<pPhrase->nTerm; i++){
210917        if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
210918      }
210919    }
210920  
210921   ismatch_out:
210922    *pbMatch = (pPhrase->poslist.n>0);
210923    for(i=0; i<pPhrase->nTerm; i++){
210924      if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
210925    }
210926    if( aIter!=aStatic ) sqlite3_free(aIter);
210927    return rc;
210928  }
210929  
210930  typedef struct Fts5LookaheadReader Fts5LookaheadReader;
210931  struct Fts5LookaheadReader {
210932    const u8 *a;                    /* Buffer containing position list */
210933    int n;                          /* Size of buffer a[] in bytes */
210934    int i;                          /* Current offset in position list */
210935    i64 iPos;                       /* Current position */
210936    i64 iLookahead;                 /* Next position */
210937  };
210938  
210939  #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
210940  
210941  static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
210942    p->iPos = p->iLookahead;
210943    if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
210944      p->iLookahead = FTS5_LOOKAHEAD_EOF;
210945    }
210946    return (p->iPos==FTS5_LOOKAHEAD_EOF);
210947  }
210948  
210949  static int fts5LookaheadReaderInit(
210950    const u8 *a, int n,             /* Buffer to read position list from */
210951    Fts5LookaheadReader *p          /* Iterator object to initialize */
210952  ){
210953    memset(p, 0, sizeof(Fts5LookaheadReader));
210954    p->a = a;
210955    p->n = n;
210956    fts5LookaheadReaderNext(p);
210957    return fts5LookaheadReaderNext(p);
210958  }
210959  
210960  typedef struct Fts5NearTrimmer Fts5NearTrimmer;
210961  struct Fts5NearTrimmer {
210962    Fts5LookaheadReader reader;     /* Input iterator */
210963    Fts5PoslistWriter writer;       /* Writer context */
210964    Fts5Buffer *pOut;               /* Output poslist */
210965  };
210966  
210967  /*
210968  ** The near-set object passed as the first argument contains more than
210969  ** one phrase. All phrases currently point to the same row. The
210970  ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
210971  ** tests if the current row contains instances of each phrase sufficiently
210972  ** close together to meet the NEAR constraint. Non-zero is returned if it
210973  ** does, or zero otherwise.
210974  **
210975  ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
210976  ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
210977  ** occurs within this function (*pRc) is set accordingly before returning.
210978  ** The return value is undefined in both these cases.
210979  ** 
210980  ** If no error occurs and non-zero (a match) is returned, the position-list
210981  ** of each phrase object is edited to contain only those entries that
210982  ** meet the constraint before returning.
210983  */
210984  static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
210985    Fts5NearTrimmer aStatic[4];
210986    Fts5NearTrimmer *a = aStatic;
210987    Fts5ExprPhrase **apPhrase = pNear->apPhrase;
210988  
210989    int i;
210990    int rc = *pRc;
210991    int bMatch;
210992  
210993    assert( pNear->nPhrase>1 );
210994  
210995    /* If the aStatic[] array is not large enough, allocate a large array
210996    ** using sqlite3_malloc(). This approach could be improved upon. */
210997    if( pNear->nPhrase>ArraySize(aStatic) ){
210998      sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
210999      a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
211000    }else{
211001      memset(aStatic, 0, sizeof(aStatic));
211002    }
211003    if( rc!=SQLITE_OK ){
211004      *pRc = rc;
211005      return 0;
211006    }
211007  
211008    /* Initialize a lookahead iterator for each phrase. After passing the
211009    ** buffer and buffer size to the lookaside-reader init function, zero
211010    ** the phrase poslist buffer. The new poslist for the phrase (containing
211011    ** the same entries as the original with some entries removed on account 
211012    ** of the NEAR constraint) is written over the original even as it is
211013    ** being read. This is safe as the entries for the new poslist are a
211014    ** subset of the old, so it is not possible for data yet to be read to
211015    ** be overwritten.  */
211016    for(i=0; i<pNear->nPhrase; i++){
211017      Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
211018      fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
211019      pPoslist->n = 0;
211020      a[i].pOut = pPoslist;
211021    }
211022  
211023    while( 1 ){
211024      int iAdv;
211025      i64 iMin;
211026      i64 iMax;
211027  
211028      /* This block advances the phrase iterators until they point to a set of
211029      ** entries that together comprise a match.  */
211030      iMax = a[0].reader.iPos;
211031      do {
211032        bMatch = 1;
211033        for(i=0; i<pNear->nPhrase; i++){
211034          Fts5LookaheadReader *pPos = &a[i].reader;
211035          iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
211036          if( pPos->iPos<iMin || pPos->iPos>iMax ){
211037            bMatch = 0;
211038            while( pPos->iPos<iMin ){
211039              if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
211040            }
211041            if( pPos->iPos>iMax ) iMax = pPos->iPos;
211042          }
211043        }
211044      }while( bMatch==0 );
211045  
211046      /* Add an entry to each output position list */
211047      for(i=0; i<pNear->nPhrase; i++){
211048        i64 iPos = a[i].reader.iPos;
211049        Fts5PoslistWriter *pWriter = &a[i].writer;
211050        if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
211051          sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
211052        }
211053      }
211054  
211055      iAdv = 0;
211056      iMin = a[0].reader.iLookahead;
211057      for(i=0; i<pNear->nPhrase; i++){
211058        if( a[i].reader.iLookahead < iMin ){
211059          iMin = a[i].reader.iLookahead;
211060          iAdv = i;
211061        }
211062      }
211063      if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
211064    }
211065  
211066    ismatch_out: {
211067      int bRet = a[0].pOut->n>0;
211068      *pRc = rc;
211069      if( a!=aStatic ) sqlite3_free(a);
211070      return bRet;
211071    }
211072  }
211073  
211074  /*
211075  ** Advance iterator pIter until it points to a value equal to or laster
211076  ** than the initial value of *piLast. If this means the iterator points
211077  ** to a value laster than *piLast, update *piLast to the new lastest value.
211078  **
211079  ** If the iterator reaches EOF, set *pbEof to true before returning. If
211080  ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
211081  ** are set, return a non-zero value. Otherwise, return zero.
211082  */
211083  static int fts5ExprAdvanceto(
211084    Fts5IndexIter *pIter,           /* Iterator to advance */
211085    int bDesc,                      /* True if iterator is "rowid DESC" */
211086    i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
211087    int *pRc,                       /* OUT: Error code */
211088    int *pbEof                      /* OUT: Set to true if EOF */
211089  ){
211090    i64 iLast = *piLast;
211091    i64 iRowid;
211092  
211093    iRowid = pIter->iRowid;
211094    if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
211095      int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
211096      if( rc || sqlite3Fts5IterEof(pIter) ){
211097        *pRc = rc;
211098        *pbEof = 1;
211099        return 1;
211100      }
211101      iRowid = pIter->iRowid;
211102      assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
211103    }
211104    *piLast = iRowid;
211105  
211106    return 0;
211107  }
211108  
211109  static int fts5ExprSynonymAdvanceto(
211110    Fts5ExprTerm *pTerm,            /* Term iterator to advance */
211111    int bDesc,                      /* True if iterator is "rowid DESC" */
211112    i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
211113    int *pRc                        /* OUT: Error code */
211114  ){
211115    int rc = SQLITE_OK;
211116    i64 iLast = *piLast;
211117    Fts5ExprTerm *p;
211118    int bEof = 0;
211119  
211120    for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
211121      if( sqlite3Fts5IterEof(p->pIter)==0 ){
211122        i64 iRowid = p->pIter->iRowid;
211123        if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
211124          rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
211125        }
211126      }
211127    }
211128  
211129    if( rc!=SQLITE_OK ){
211130      *pRc = rc;
211131      bEof = 1;
211132    }else{
211133      *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
211134    }
211135    return bEof;
211136  }
211137  
211138  
211139  static int fts5ExprNearTest(
211140    int *pRc,
211141    Fts5Expr *pExpr,                /* Expression that pNear is a part of */
211142    Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
211143  ){
211144    Fts5ExprNearset *pNear = pNode->pNear;
211145    int rc = *pRc;
211146  
211147    if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
211148      Fts5ExprTerm *pTerm;
211149      Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
211150      pPhrase->poslist.n = 0;
211151      for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
211152        Fts5IndexIter *pIter = pTerm->pIter;
211153        if( sqlite3Fts5IterEof(pIter)==0 ){
211154          if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
211155            pPhrase->poslist.n = 1;
211156          }
211157        }
211158      }
211159      return pPhrase->poslist.n;
211160    }else{
211161      int i;
211162  
211163      /* Check that each phrase in the nearset matches the current row.
211164      ** Populate the pPhrase->poslist buffers at the same time. If any
211165      ** phrase is not a match, break out of the loop early.  */
211166      for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
211167        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
211168        if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym 
211169         || pNear->pColset || pPhrase->aTerm[0].bFirst
211170        ){
211171          int bMatch = 0;
211172          rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
211173          if( bMatch==0 ) break;
211174        }else{
211175          Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
211176          fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
211177        }
211178      }
211179  
211180      *pRc = rc;
211181      if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
211182        return 1;
211183      }
211184      return 0;
211185    }
211186  }
211187  
211188  
211189  /*
211190  ** Initialize all term iterators in the pNear object. If any term is found
211191  ** to match no documents at all, return immediately without initializing any
211192  ** further iterators.
211193  **
211194  ** If an error occurs, return an SQLite error code. Otherwise, return
211195  ** SQLITE_OK. It is not considered an error if some term matches zero
211196  ** documents.
211197  */
211198  static int fts5ExprNearInitAll(
211199    Fts5Expr *pExpr,
211200    Fts5ExprNode *pNode
211201  ){
211202    Fts5ExprNearset *pNear = pNode->pNear;
211203    int i;
211204  
211205    assert( pNode->bNomatch==0 );
211206    for(i=0; i<pNear->nPhrase; i++){
211207      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
211208      if( pPhrase->nTerm==0 ){
211209        pNode->bEof = 1;
211210        return SQLITE_OK;
211211      }else{
211212        int j;
211213        for(j=0; j<pPhrase->nTerm; j++){
211214          Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
211215          Fts5ExprTerm *p;
211216          int bHit = 0;
211217  
211218          for(p=pTerm; p; p=p->pSynonym){
211219            int rc;
211220            if( p->pIter ){
211221              sqlite3Fts5IterClose(p->pIter);
211222              p->pIter = 0;
211223            }
211224            rc = sqlite3Fts5IndexQuery(
211225                pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
211226                (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
211227                (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
211228                pNear->pColset,
211229                &p->pIter
211230            );
211231            assert( (rc==SQLITE_OK)==(p->pIter!=0) );
211232            if( rc!=SQLITE_OK ) return rc;
211233            if( 0==sqlite3Fts5IterEof(p->pIter) ){
211234              bHit = 1;
211235            }
211236          }
211237  
211238          if( bHit==0 ){
211239            pNode->bEof = 1;
211240            return SQLITE_OK;
211241          }
211242        }
211243      }
211244    }
211245  
211246    pNode->bEof = 0;
211247    return SQLITE_OK;
211248  }
211249  
211250  /*
211251  ** If pExpr is an ASC iterator, this function returns a value with the
211252  ** same sign as:
211253  **
211254  **   (iLhs - iRhs)
211255  **
211256  ** Otherwise, if this is a DESC iterator, the opposite is returned:
211257  **
211258  **   (iRhs - iLhs)
211259  */
211260  static int fts5RowidCmp(
211261    Fts5Expr *pExpr,
211262    i64 iLhs,
211263    i64 iRhs
211264  ){
211265    assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
211266    if( pExpr->bDesc==0 ){
211267      if( iLhs<iRhs ) return -1;
211268      return (iLhs > iRhs);
211269    }else{
211270      if( iLhs>iRhs ) return -1;
211271      return (iLhs < iRhs);
211272    }
211273  }
211274  
211275  static void fts5ExprSetEof(Fts5ExprNode *pNode){
211276    int i;
211277    pNode->bEof = 1;
211278    pNode->bNomatch = 0;
211279    for(i=0; i<pNode->nChild; i++){
211280      fts5ExprSetEof(pNode->apChild[i]);
211281    }
211282  }
211283  
211284  static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
211285    if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
211286      Fts5ExprNearset *pNear = pNode->pNear;
211287      int i;
211288      for(i=0; i<pNear->nPhrase; i++){
211289        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
211290        pPhrase->poslist.n = 0;
211291      }
211292    }else{
211293      int i;
211294      for(i=0; i<pNode->nChild; i++){
211295        fts5ExprNodeZeroPoslist(pNode->apChild[i]);
211296      }
211297    }
211298  }
211299  
211300  
211301  
211302  /*
211303  ** Compare the values currently indicated by the two nodes as follows:
211304  **
211305  **    res = (*p1) - (*p2)
211306  **
211307  ** Nodes that point to values that come later in the iteration order are
211308  ** considered to be larger. Nodes at EOF are the largest of all.
211309  **
211310  ** This means that if the iteration order is ASC, then numerically larger
211311  ** rowids are considered larger. Or if it is the default DESC, numerically
211312  ** smaller rowids are larger.
211313  */
211314  static int fts5NodeCompare(
211315    Fts5Expr *pExpr,
211316    Fts5ExprNode *p1, 
211317    Fts5ExprNode *p2
211318  ){
211319    if( p2->bEof ) return -1;
211320    if( p1->bEof ) return +1;
211321    return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
211322  }
211323  
211324  /*
211325  ** All individual term iterators in pNear are guaranteed to be valid when
211326  ** this function is called. This function checks if all term iterators
211327  ** point to the same rowid, and if not, advances them until they do.
211328  ** If an EOF is reached before this happens, *pbEof is set to true before
211329  ** returning.
211330  **
211331  ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
211332  ** otherwise. It is not considered an error code if an iterator reaches
211333  ** EOF.
211334  */
211335  static int fts5ExprNodeTest_STRING(
211336    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
211337    Fts5ExprNode *pNode
211338  ){
211339    Fts5ExprNearset *pNear = pNode->pNear;
211340    Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
211341    int rc = SQLITE_OK;
211342    i64 iLast;                      /* Lastest rowid any iterator points to */
211343    int i, j;                       /* Phrase and token index, respectively */
211344    int bMatch;                     /* True if all terms are at the same rowid */
211345    const int bDesc = pExpr->bDesc;
211346  
211347    /* Check that this node should not be FTS5_TERM */
211348    assert( pNear->nPhrase>1 
211349         || pNear->apPhrase[0]->nTerm>1 
211350         || pNear->apPhrase[0]->aTerm[0].pSynonym
211351         || pNear->apPhrase[0]->aTerm[0].bFirst
211352    );
211353  
211354    /* Initialize iLast, the "lastest" rowid any iterator points to. If the
211355    ** iterator skips through rowids in the default ascending order, this means
211356    ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
211357    ** means the minimum rowid.  */
211358    if( pLeft->aTerm[0].pSynonym ){
211359      iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
211360    }else{
211361      iLast = pLeft->aTerm[0].pIter->iRowid;
211362    }
211363  
211364    do {
211365      bMatch = 1;
211366      for(i=0; i<pNear->nPhrase; i++){
211367        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
211368        for(j=0; j<pPhrase->nTerm; j++){
211369          Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
211370          if( pTerm->pSynonym ){
211371            i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
211372            if( iRowid==iLast ) continue;
211373            bMatch = 0;
211374            if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
211375              pNode->bNomatch = 0;
211376              pNode->bEof = 1;
211377              return rc;
211378            }
211379          }else{
211380            Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
211381            if( pIter->iRowid==iLast || pIter->bEof ) continue;
211382            bMatch = 0;
211383            if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
211384              return rc;
211385            }
211386          }
211387        }
211388      }
211389    }while( bMatch==0 );
211390  
211391    pNode->iRowid = iLast;
211392    pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
211393    assert( pNode->bEof==0 || pNode->bNomatch==0 );
211394  
211395    return rc;
211396  }
211397  
211398  /*
211399  ** Advance the first term iterator in the first phrase of pNear. Set output
211400  ** variable *pbEof to true if it reaches EOF or if an error occurs.
211401  **
211402  ** Return SQLITE_OK if successful, or an SQLite error code if an error
211403  ** occurs.
211404  */
211405  static int fts5ExprNodeNext_STRING(
211406    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
211407    Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
211408    int bFromValid,
211409    i64 iFrom 
211410  ){
211411    Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
211412    int rc = SQLITE_OK;
211413  
211414    pNode->bNomatch = 0;
211415    if( pTerm->pSynonym ){
211416      int bEof = 1;
211417      Fts5ExprTerm *p;
211418  
211419      /* Find the firstest rowid any synonym points to. */
211420      i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
211421  
211422      /* Advance each iterator that currently points to iRowid. Or, if iFrom
211423      ** is valid - each iterator that points to a rowid before iFrom.  */
211424      for(p=pTerm; p; p=p->pSynonym){
211425        if( sqlite3Fts5IterEof(p->pIter)==0 ){
211426          i64 ii = p->pIter->iRowid;
211427          if( ii==iRowid 
211428           || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) 
211429          ){
211430            if( bFromValid ){
211431              rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
211432            }else{
211433              rc = sqlite3Fts5IterNext(p->pIter);
211434            }
211435            if( rc!=SQLITE_OK ) break;
211436            if( sqlite3Fts5IterEof(p->pIter)==0 ){
211437              bEof = 0;
211438            }
211439          }else{
211440            bEof = 0;
211441          }
211442        }
211443      }
211444  
211445      /* Set the EOF flag if either all synonym iterators are at EOF or an
211446      ** error has occurred.  */
211447      pNode->bEof = (rc || bEof);
211448    }else{
211449      Fts5IndexIter *pIter = pTerm->pIter;
211450  
211451      assert( Fts5NodeIsString(pNode) );
211452      if( bFromValid ){
211453        rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
211454      }else{
211455        rc = sqlite3Fts5IterNext(pIter);
211456      }
211457  
211458      pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
211459    }
211460  
211461    if( pNode->bEof==0 ){
211462      assert( rc==SQLITE_OK );
211463      rc = fts5ExprNodeTest_STRING(pExpr, pNode);
211464    }
211465  
211466    return rc;
211467  }
211468  
211469  
211470  static int fts5ExprNodeTest_TERM(
211471    Fts5Expr *pExpr,                /* Expression that pNear is a part of */
211472    Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
211473  ){
211474    /* As this "NEAR" object is actually a single phrase that consists 
211475    ** of a single term only, grab pointers into the poslist managed by the
211476    ** fts5_index.c iterator object. This is much faster than synthesizing 
211477    ** a new poslist the way we have to for more complicated phrase or NEAR
211478    ** expressions.  */
211479    Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
211480    Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
211481  
211482    assert( pNode->eType==FTS5_TERM );
211483    assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
211484    assert( pPhrase->aTerm[0].pSynonym==0 );
211485  
211486    pPhrase->poslist.n = pIter->nData;
211487    if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
211488      pPhrase->poslist.p = (u8*)pIter->pData;
211489    }
211490    pNode->iRowid = pIter->iRowid;
211491    pNode->bNomatch = (pPhrase->poslist.n==0);
211492    return SQLITE_OK;
211493  }
211494  
211495  /*
211496  ** xNext() method for a node of type FTS5_TERM.
211497  */
211498  static int fts5ExprNodeNext_TERM(
211499    Fts5Expr *pExpr, 
211500    Fts5ExprNode *pNode,
211501    int bFromValid,
211502    i64 iFrom
211503  ){
211504    int rc;
211505    Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
211506  
211507    assert( pNode->bEof==0 );
211508    if( bFromValid ){
211509      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
211510    }else{
211511      rc = sqlite3Fts5IterNext(pIter);
211512    }
211513    if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
211514      rc = fts5ExprNodeTest_TERM(pExpr, pNode);
211515    }else{
211516      pNode->bEof = 1;
211517      pNode->bNomatch = 0;
211518    }
211519    return rc;
211520  }
211521  
211522  static void fts5ExprNodeTest_OR(
211523    Fts5Expr *pExpr,                /* Expression of which pNode is a part */
211524    Fts5ExprNode *pNode             /* Expression node to test */
211525  ){
211526    Fts5ExprNode *pNext = pNode->apChild[0];
211527    int i;
211528  
211529    for(i=1; i<pNode->nChild; i++){
211530      Fts5ExprNode *pChild = pNode->apChild[i];
211531      int cmp = fts5NodeCompare(pExpr, pNext, pChild);
211532      if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
211533        pNext = pChild;
211534      }
211535    }
211536    pNode->iRowid = pNext->iRowid;
211537    pNode->bEof = pNext->bEof;
211538    pNode->bNomatch = pNext->bNomatch;
211539  }
211540  
211541  static int fts5ExprNodeNext_OR(
211542    Fts5Expr *pExpr, 
211543    Fts5ExprNode *pNode,
211544    int bFromValid,
211545    i64 iFrom
211546  ){
211547    int i;
211548    i64 iLast = pNode->iRowid;
211549  
211550    for(i=0; i<pNode->nChild; i++){
211551      Fts5ExprNode *p1 = pNode->apChild[i];
211552      assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
211553      if( p1->bEof==0 ){
211554        if( (p1->iRowid==iLast) 
211555         || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
211556        ){
211557          int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
211558          if( rc!=SQLITE_OK ){
211559            pNode->bNomatch = 0;
211560            return rc;
211561          }
211562        }
211563      }
211564    }
211565  
211566    fts5ExprNodeTest_OR(pExpr, pNode);
211567    return SQLITE_OK;
211568  }
211569  
211570  /*
211571  ** Argument pNode is an FTS5_AND node.
211572  */
211573  static int fts5ExprNodeTest_AND(
211574    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
211575    Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
211576  ){
211577    int iChild;
211578    i64 iLast = pAnd->iRowid;
211579    int rc = SQLITE_OK;
211580    int bMatch;
211581  
211582    assert( pAnd->bEof==0 );
211583    do {
211584      pAnd->bNomatch = 0;
211585      bMatch = 1;
211586      for(iChild=0; iChild<pAnd->nChild; iChild++){
211587        Fts5ExprNode *pChild = pAnd->apChild[iChild];
211588        int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
211589        if( cmp>0 ){
211590          /* Advance pChild until it points to iLast or laster */
211591          rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
211592          if( rc!=SQLITE_OK ){
211593            pAnd->bNomatch = 0;
211594            return rc;
211595          }
211596        }
211597  
211598        /* If the child node is now at EOF, so is the parent AND node. Otherwise,
211599        ** the child node is guaranteed to have advanced at least as far as
211600        ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
211601        ** new lastest rowid seen so far.  */
211602        assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
211603        if( pChild->bEof ){
211604          fts5ExprSetEof(pAnd);
211605          bMatch = 1;
211606          break;
211607        }else if( iLast!=pChild->iRowid ){
211608          bMatch = 0;
211609          iLast = pChild->iRowid;
211610        }
211611  
211612        if( pChild->bNomatch ){
211613          pAnd->bNomatch = 1;
211614        }
211615      }
211616    }while( bMatch==0 );
211617  
211618    if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
211619      fts5ExprNodeZeroPoslist(pAnd);
211620    }
211621    pAnd->iRowid = iLast;
211622    return SQLITE_OK;
211623  }
211624  
211625  static int fts5ExprNodeNext_AND(
211626    Fts5Expr *pExpr, 
211627    Fts5ExprNode *pNode,
211628    int bFromValid,
211629    i64 iFrom
211630  ){
211631    int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
211632    if( rc==SQLITE_OK ){
211633      rc = fts5ExprNodeTest_AND(pExpr, pNode);
211634    }else{
211635      pNode->bNomatch = 0;
211636    }
211637    return rc;
211638  }
211639  
211640  static int fts5ExprNodeTest_NOT(
211641    Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
211642    Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
211643  ){
211644    int rc = SQLITE_OK;
211645    Fts5ExprNode *p1 = pNode->apChild[0];
211646    Fts5ExprNode *p2 = pNode->apChild[1];
211647    assert( pNode->nChild==2 );
211648  
211649    while( rc==SQLITE_OK && p1->bEof==0 ){
211650      int cmp = fts5NodeCompare(pExpr, p1, p2);
211651      if( cmp>0 ){
211652        rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
211653        cmp = fts5NodeCompare(pExpr, p1, p2);
211654      }
211655      assert( rc!=SQLITE_OK || cmp<=0 );
211656      if( cmp || p2->bNomatch ) break;
211657      rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
211658    }
211659    pNode->bEof = p1->bEof;
211660    pNode->bNomatch = p1->bNomatch;
211661    pNode->iRowid = p1->iRowid;
211662    if( p1->bEof ){
211663      fts5ExprNodeZeroPoslist(p2);
211664    }
211665    return rc;
211666  }
211667  
211668  static int fts5ExprNodeNext_NOT(
211669    Fts5Expr *pExpr, 
211670    Fts5ExprNode *pNode,
211671    int bFromValid,
211672    i64 iFrom
211673  ){
211674    int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
211675    if( rc==SQLITE_OK ){
211676      rc = fts5ExprNodeTest_NOT(pExpr, pNode);
211677    }
211678    if( rc!=SQLITE_OK ){
211679      pNode->bNomatch = 0;
211680    }
211681    return rc;
211682  }
211683  
211684  /*
211685  ** If pNode currently points to a match, this function returns SQLITE_OK
211686  ** without modifying it. Otherwise, pNode is advanced until it does point
211687  ** to a match or EOF is reached.
211688  */
211689  static int fts5ExprNodeTest(
211690    Fts5Expr *pExpr,                /* Expression of which pNode is a part */
211691    Fts5ExprNode *pNode             /* Expression node to test */
211692  ){
211693    int rc = SQLITE_OK;
211694    if( pNode->bEof==0 ){
211695      switch( pNode->eType ){
211696  
211697        case FTS5_STRING: {
211698          rc = fts5ExprNodeTest_STRING(pExpr, pNode);
211699          break;
211700        }
211701  
211702        case FTS5_TERM: {
211703          rc = fts5ExprNodeTest_TERM(pExpr, pNode);
211704          break;
211705        }
211706  
211707        case FTS5_AND: {
211708          rc = fts5ExprNodeTest_AND(pExpr, pNode);
211709          break;
211710        }
211711  
211712        case FTS5_OR: {
211713          fts5ExprNodeTest_OR(pExpr, pNode);
211714          break;
211715        }
211716  
211717        default: assert( pNode->eType==FTS5_NOT ); {
211718          rc = fts5ExprNodeTest_NOT(pExpr, pNode);
211719          break;
211720        }
211721      }
211722    }
211723    return rc;
211724  }
211725  
211726   
211727  /*
211728  ** Set node pNode, which is part of expression pExpr, to point to the first
211729  ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
211730  **
211731  ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
211732  ** It is not an error if there are no matches.
211733  */
211734  static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
211735    int rc = SQLITE_OK;
211736    pNode->bEof = 0;
211737    pNode->bNomatch = 0;
211738  
211739    if( Fts5NodeIsString(pNode) ){
211740      /* Initialize all term iterators in the NEAR object. */
211741      rc = fts5ExprNearInitAll(pExpr, pNode);
211742    }else if( pNode->xNext==0 ){
211743      pNode->bEof = 1;
211744    }else{
211745      int i;
211746      int nEof = 0;
211747      for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
211748        Fts5ExprNode *pChild = pNode->apChild[i];
211749        rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
211750        assert( pChild->bEof==0 || pChild->bEof==1 );
211751        nEof += pChild->bEof;
211752      }
211753      pNode->iRowid = pNode->apChild[0]->iRowid;
211754  
211755      switch( pNode->eType ){
211756        case FTS5_AND:
211757          if( nEof>0 ) fts5ExprSetEof(pNode);
211758          break;
211759  
211760        case FTS5_OR:
211761          if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
211762          break;
211763  
211764        default:
211765          assert( pNode->eType==FTS5_NOT );
211766          pNode->bEof = pNode->apChild[0]->bEof;
211767          break;
211768      }
211769    }
211770  
211771    if( rc==SQLITE_OK ){
211772      rc = fts5ExprNodeTest(pExpr, pNode);
211773    }
211774    return rc;
211775  }
211776  
211777  
211778  /*
211779  ** Begin iterating through the set of documents in index pIdx matched by
211780  ** the MATCH expression passed as the first argument. If the "bDesc" 
211781  ** parameter is passed a non-zero value, iteration is in descending rowid 
211782  ** order. Or, if it is zero, in ascending order.
211783  **
211784  ** If iterating in ascending rowid order (bDesc==0), the first document
211785  ** visited is that with the smallest rowid that is larger than or equal
211786  ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
211787  ** then the first document visited must have a rowid smaller than or
211788  ** equal to iFirst.
211789  **
211790  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
211791  ** is not considered an error if the query does not match any documents.
211792  */
211793  static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
211794    Fts5ExprNode *pRoot = p->pRoot;
211795    int rc;                         /* Return code */
211796  
211797    p->pIndex = pIdx;
211798    p->bDesc = bDesc;
211799    rc = fts5ExprNodeFirst(p, pRoot);
211800  
211801    /* If not at EOF but the current rowid occurs earlier than iFirst in
211802    ** the iteration order, move to document iFirst or later. */
211803    if( rc==SQLITE_OK 
211804     && 0==pRoot->bEof 
211805     && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 
211806    ){
211807      rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
211808    }
211809  
211810    /* If the iterator is not at a real match, skip forward until it is. */
211811    while( pRoot->bNomatch ){
211812      assert( pRoot->bEof==0 && rc==SQLITE_OK );
211813      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
211814    }
211815    return rc;
211816  }
211817  
211818  /*
211819  ** Move to the next document 
211820  **
211821  ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
211822  ** is not considered an error if the query does not match any documents.
211823  */
211824  static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
211825    int rc;
211826    Fts5ExprNode *pRoot = p->pRoot;
211827    assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
211828    do {
211829      rc = fts5ExprNodeNext(p, pRoot, 0, 0);
211830      assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
211831    }while( pRoot->bNomatch );
211832    if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
211833      pRoot->bEof = 1;
211834    }
211835    return rc;
211836  }
211837  
211838  static int sqlite3Fts5ExprEof(Fts5Expr *p){
211839    return p->pRoot->bEof;
211840  }
211841  
211842  static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
211843    return p->pRoot->iRowid;
211844  }
211845  
211846  static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
211847    int rc = SQLITE_OK;
211848    *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
211849    return rc;
211850  }
211851  
211852  /*
211853  ** Free the phrase object passed as the only argument.
211854  */
211855  static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
211856    if( pPhrase ){
211857      int i;
211858      for(i=0; i<pPhrase->nTerm; i++){
211859        Fts5ExprTerm *pSyn;
211860        Fts5ExprTerm *pNext;
211861        Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
211862        sqlite3_free(pTerm->zTerm);
211863        sqlite3Fts5IterClose(pTerm->pIter);
211864        for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
211865          pNext = pSyn->pSynonym;
211866          sqlite3Fts5IterClose(pSyn->pIter);
211867          fts5BufferFree((Fts5Buffer*)&pSyn[1]);
211868          sqlite3_free(pSyn);
211869        }
211870      }
211871      if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
211872      sqlite3_free(pPhrase);
211873    }
211874  }
211875  
211876  /*
211877  ** Set the "bFirst" flag on the first token of the phrase passed as the
211878  ** only argument.
211879  */
211880  static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
211881    if( pPhrase && pPhrase->nTerm ){
211882      pPhrase->aTerm[0].bFirst = 1;
211883    }
211884  }
211885  
211886  /*
211887  ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
211888  ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
211889  ** appended to it and the results returned.
211890  **
211891  ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
211892  ** NULL returned.
211893  */
211894  static Fts5ExprNearset *sqlite3Fts5ParseNearset(
211895    Fts5Parse *pParse,              /* Parse context */
211896    Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
211897    Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
211898  ){
211899    const int SZALLOC = 8;
211900    Fts5ExprNearset *pRet = 0;
211901  
211902    if( pParse->rc==SQLITE_OK ){
211903      if( pPhrase==0 ){
211904        return pNear;
211905      }
211906      if( pNear==0 ){
211907        sqlite3_int64 nByte;
211908        nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
211909        pRet = sqlite3_malloc64(nByte);
211910        if( pRet==0 ){
211911          pParse->rc = SQLITE_NOMEM;
211912        }else{
211913          memset(pRet, 0, nByte);
211914        }
211915      }else if( (pNear->nPhrase % SZALLOC)==0 ){
211916        int nNew = pNear->nPhrase + SZALLOC;
211917        sqlite3_int64 nByte;
211918  
211919        nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
211920        pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
211921        if( pRet==0 ){
211922          pParse->rc = SQLITE_NOMEM;
211923        }
211924      }else{
211925        pRet = pNear;
211926      }
211927    }
211928  
211929    if( pRet==0 ){
211930      assert( pParse->rc!=SQLITE_OK );
211931      sqlite3Fts5ParseNearsetFree(pNear);
211932      sqlite3Fts5ParsePhraseFree(pPhrase);
211933    }else{
211934      if( pRet->nPhrase>0 ){
211935        Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
211936        assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
211937        if( pPhrase->nTerm==0 ){
211938          fts5ExprPhraseFree(pPhrase);
211939          pRet->nPhrase--;
211940          pParse->nPhrase--;
211941          pPhrase = pLast;
211942        }else if( pLast->nTerm==0 ){
211943          fts5ExprPhraseFree(pLast);
211944          pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
211945          pParse->nPhrase--;
211946          pRet->nPhrase--;
211947        }
211948      }
211949      pRet->apPhrase[pRet->nPhrase++] = pPhrase;
211950    }
211951    return pRet;
211952  }
211953  
211954  typedef struct TokenCtx TokenCtx;
211955  struct TokenCtx {
211956    Fts5ExprPhrase *pPhrase;
211957    int rc;
211958  };
211959  
211960  /*
211961  ** Callback for tokenizing terms used by ParseTerm().
211962  */
211963  static int fts5ParseTokenize(
211964    void *pContext,                 /* Pointer to Fts5InsertCtx object */
211965    int tflags,                     /* Mask of FTS5_TOKEN_* flags */
211966    const char *pToken,             /* Buffer containing token */
211967    int nToken,                     /* Size of token in bytes */
211968    int iUnused1,                   /* Start offset of token */
211969    int iUnused2                    /* End offset of token */
211970  ){
211971    int rc = SQLITE_OK;
211972    const int SZALLOC = 8;
211973    TokenCtx *pCtx = (TokenCtx*)pContext;
211974    Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
211975  
211976    UNUSED_PARAM2(iUnused1, iUnused2);
211977  
211978    /* If an error has already occurred, this is a no-op */
211979    if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
211980    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
211981  
211982    if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
211983      Fts5ExprTerm *pSyn;
211984      sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
211985      pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
211986      if( pSyn==0 ){
211987        rc = SQLITE_NOMEM;
211988      }else{
211989        memset(pSyn, 0, nByte);
211990        pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
211991        memcpy(pSyn->zTerm, pToken, nToken);
211992        pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
211993        pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
211994      }
211995    }else{
211996      Fts5ExprTerm *pTerm;
211997      if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
211998        Fts5ExprPhrase *pNew;
211999        int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
212000  
212001        pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase, 
212002            sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
212003        );
212004        if( pNew==0 ){
212005          rc = SQLITE_NOMEM;
212006        }else{
212007          if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
212008          pCtx->pPhrase = pPhrase = pNew;
212009          pNew->nTerm = nNew - SZALLOC;
212010        }
212011      }
212012  
212013      if( rc==SQLITE_OK ){
212014        pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
212015        memset(pTerm, 0, sizeof(Fts5ExprTerm));
212016        pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
212017      }
212018    }
212019  
212020    pCtx->rc = rc;
212021    return rc;
212022  }
212023  
212024  
212025  /*
212026  ** Free the phrase object passed as the only argument.
212027  */
212028  static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
212029    fts5ExprPhraseFree(pPhrase);
212030  }
212031  
212032  /*
212033  ** Free the phrase object passed as the second argument.
212034  */
212035  static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
212036    if( pNear ){
212037      int i;
212038      for(i=0; i<pNear->nPhrase; i++){
212039        fts5ExprPhraseFree(pNear->apPhrase[i]);
212040      }
212041      sqlite3_free(pNear->pColset);
212042      sqlite3_free(pNear);
212043    }
212044  }
212045  
212046  static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
212047    assert( pParse->pExpr==0 );
212048    pParse->pExpr = p;
212049  }
212050  
212051  /*
212052  ** This function is called by the parser to process a string token. The
212053  ** string may or may not be quoted. In any case it is tokenized and a
212054  ** phrase object consisting of all tokens returned.
212055  */
212056  static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
212057    Fts5Parse *pParse,              /* Parse context */
212058    Fts5ExprPhrase *pAppend,        /* Phrase to append to */
212059    Fts5Token *pToken,              /* String to tokenize */
212060    int bPrefix                     /* True if there is a trailing "*" */
212061  ){
212062    Fts5Config *pConfig = pParse->pConfig;
212063    TokenCtx sCtx;                  /* Context object passed to callback */
212064    int rc;                         /* Tokenize return code */
212065    char *z = 0;
212066  
212067    memset(&sCtx, 0, sizeof(TokenCtx));
212068    sCtx.pPhrase = pAppend;
212069  
212070    rc = fts5ParseStringFromToken(pToken, &z);
212071    if( rc==SQLITE_OK ){
212072      int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
212073      int n;
212074      sqlite3Fts5Dequote(z);
212075      n = (int)strlen(z);
212076      rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
212077    }
212078    sqlite3_free(z);
212079    if( rc || (rc = sCtx.rc) ){
212080      pParse->rc = rc;
212081      fts5ExprPhraseFree(sCtx.pPhrase);
212082      sCtx.pPhrase = 0;
212083    }else{
212084  
212085      if( pAppend==0 ){
212086        if( (pParse->nPhrase % 8)==0 ){
212087          sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
212088          Fts5ExprPhrase **apNew;
212089          apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
212090          if( apNew==0 ){
212091            pParse->rc = SQLITE_NOMEM;
212092            fts5ExprPhraseFree(sCtx.pPhrase);
212093            return 0;
212094          }
212095          pParse->apPhrase = apNew;
212096        }
212097        pParse->nPhrase++;
212098      }
212099  
212100      if( sCtx.pPhrase==0 ){
212101        /* This happens when parsing a token or quoted phrase that contains
212102        ** no token characters at all. (e.g ... MATCH '""'). */
212103        sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
212104      }else if( sCtx.pPhrase->nTerm ){
212105        sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
212106      }
212107      pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
212108    }
212109  
212110    return sCtx.pPhrase;
212111  }
212112  
212113  /*
212114  ** Create a new FTS5 expression by cloning phrase iPhrase of the
212115  ** expression passed as the second argument.
212116  */
212117  static int sqlite3Fts5ExprClonePhrase(
212118    Fts5Expr *pExpr, 
212119    int iPhrase, 
212120    Fts5Expr **ppNew
212121  ){
212122    int rc = SQLITE_OK;             /* Return code */
212123    Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
212124    Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
212125    TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
212126  
212127    pOrig = pExpr->apExprPhrase[iPhrase];
212128    pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
212129    if( rc==SQLITE_OK ){
212130      pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, 
212131          sizeof(Fts5ExprPhrase*));
212132    }
212133    if( rc==SQLITE_OK ){
212134      pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, 
212135          sizeof(Fts5ExprNode));
212136    }
212137    if( rc==SQLITE_OK ){
212138      pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, 
212139          sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
212140    }
212141    if( rc==SQLITE_OK ){
212142      Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
212143      if( pColsetOrig ){
212144        sqlite3_int64 nByte;
212145        Fts5Colset *pColset;
212146        nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
212147        pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
212148        if( pColset ){ 
212149          memcpy(pColset, pColsetOrig, nByte);
212150        }
212151        pNew->pRoot->pNear->pColset = pColset;
212152      }
212153    }
212154  
212155    if( pOrig->nTerm ){
212156      int i;                          /* Used to iterate through phrase terms */
212157      for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
212158        int tflags = 0;
212159        Fts5ExprTerm *p;
212160        for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
212161          const char *zTerm = p->zTerm;
212162          rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
212163              0, 0);
212164          tflags = FTS5_TOKEN_COLOCATED;
212165        }
212166        if( rc==SQLITE_OK ){
212167          sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
212168          sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
212169        }
212170      }
212171    }else{
212172      /* This happens when parsing a token or quoted phrase that contains
212173      ** no token characters at all. (e.g ... MATCH '""'). */
212174      sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
212175    }
212176  
212177    if( rc==SQLITE_OK ){
212178      /* All the allocations succeeded. Put the expression object together. */
212179      pNew->pIndex = pExpr->pIndex;
212180      pNew->pConfig = pExpr->pConfig;
212181      pNew->nPhrase = 1;
212182      pNew->apExprPhrase[0] = sCtx.pPhrase;
212183      pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
212184      pNew->pRoot->pNear->nPhrase = 1;
212185      sCtx.pPhrase->pNode = pNew->pRoot;
212186  
212187      if( pOrig->nTerm==1 
212188       && pOrig->aTerm[0].pSynonym==0 
212189       && pOrig->aTerm[0].bFirst==0 
212190      ){
212191        pNew->pRoot->eType = FTS5_TERM;
212192        pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
212193      }else{
212194        pNew->pRoot->eType = FTS5_STRING;
212195        pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
212196      }
212197    }else{
212198      sqlite3Fts5ExprFree(pNew);
212199      fts5ExprPhraseFree(sCtx.pPhrase);
212200      pNew = 0;
212201    }
212202  
212203    *ppNew = pNew;
212204    return rc;
212205  }
212206  
212207  
212208  /*
212209  ** Token pTok has appeared in a MATCH expression where the NEAR operator
212210  ** is expected. If token pTok does not contain "NEAR", store an error
212211  ** in the pParse object.
212212  */
212213  static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
212214    if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
212215      sqlite3Fts5ParseError(
212216          pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
212217      );
212218    }
212219  }
212220  
212221  static void sqlite3Fts5ParseSetDistance(
212222    Fts5Parse *pParse, 
212223    Fts5ExprNearset *pNear,
212224    Fts5Token *p
212225  ){
212226    if( pNear ){
212227      int nNear = 0;
212228      int i;
212229      if( p->n ){
212230        for(i=0; i<p->n; i++){
212231          char c = (char)p->p[i];
212232          if( c<'0' || c>'9' ){
212233            sqlite3Fts5ParseError(
212234                pParse, "expected integer, got \"%.*s\"", p->n, p->p
212235                );
212236            return;
212237          }
212238          nNear = nNear * 10 + (p->p[i] - '0');
212239        }
212240      }else{
212241        nNear = FTS5_DEFAULT_NEARDIST;
212242      }
212243      pNear->nNear = nNear;
212244    }
212245  }
212246  
212247  /*
212248  ** The second argument passed to this function may be NULL, or it may be
212249  ** an existing Fts5Colset object. This function returns a pointer to
212250  ** a new colset object containing the contents of (p) with new value column
212251  ** number iCol appended. 
212252  **
212253  ** If an OOM error occurs, store an error code in pParse and return NULL.
212254  ** The old colset object (if any) is not freed in this case.
212255  */
212256  static Fts5Colset *fts5ParseColset(
212257    Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
212258    Fts5Colset *p,                  /* Existing colset object */
212259    int iCol                        /* New column to add to colset object */
212260  ){
212261    int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
212262    Fts5Colset *pNew;               /* New colset object to return */
212263  
212264    assert( pParse->rc==SQLITE_OK );
212265    assert( iCol>=0 && iCol<pParse->pConfig->nCol );
212266  
212267    pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
212268    if( pNew==0 ){
212269      pParse->rc = SQLITE_NOMEM;
212270    }else{
212271      int *aiCol = pNew->aiCol;
212272      int i, j;
212273      for(i=0; i<nCol; i++){
212274        if( aiCol[i]==iCol ) return pNew;
212275        if( aiCol[i]>iCol ) break;
212276      }
212277      for(j=nCol; j>i; j--){
212278        aiCol[j] = aiCol[j-1];
212279      }
212280      aiCol[i] = iCol;
212281      pNew->nCol = nCol+1;
212282  
212283  #ifndef NDEBUG
212284      /* Check that the array is in order and contains no duplicate entries. */
212285      for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
212286  #endif
212287    }
212288  
212289    return pNew;
212290  }
212291  
212292  /*
212293  ** Allocate and return an Fts5Colset object specifying the inverse of
212294  ** the colset passed as the second argument. Free the colset passed
212295  ** as the second argument before returning.
212296  */
212297  static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
212298    Fts5Colset *pRet;
212299    int nCol = pParse->pConfig->nCol;
212300  
212301    pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, 
212302        sizeof(Fts5Colset) + sizeof(int)*nCol
212303    );
212304    if( pRet ){
212305      int i;
212306      int iOld = 0;
212307      for(i=0; i<nCol; i++){
212308        if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
212309          pRet->aiCol[pRet->nCol++] = i;
212310        }else{
212311          iOld++;
212312        }
212313      }
212314    }
212315  
212316    sqlite3_free(p);
212317    return pRet;
212318  }
212319  
212320  static Fts5Colset *sqlite3Fts5ParseColset(
212321    Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
212322    Fts5Colset *pColset,            /* Existing colset object */
212323    Fts5Token *p
212324  ){
212325    Fts5Colset *pRet = 0;
212326    int iCol;
212327    char *z;                        /* Dequoted copy of token p */
212328  
212329    z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
212330    if( pParse->rc==SQLITE_OK ){
212331      Fts5Config *pConfig = pParse->pConfig;
212332      sqlite3Fts5Dequote(z);
212333      for(iCol=0; iCol<pConfig->nCol; iCol++){
212334        if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
212335      }
212336      if( iCol==pConfig->nCol ){
212337        sqlite3Fts5ParseError(pParse, "no such column: %s", z);
212338      }else{
212339        pRet = fts5ParseColset(pParse, pColset, iCol);
212340      }
212341      sqlite3_free(z);
212342    }
212343  
212344    if( pRet==0 ){
212345      assert( pParse->rc!=SQLITE_OK );
212346      sqlite3_free(pColset);
212347    }
212348  
212349    return pRet;
212350  }
212351  
212352  /*
212353  ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
212354  ** SQLITE_OK when this function is called, NULL is returned. 
212355  **
212356  ** Otherwise, a copy of (*pOrig) is made into memory obtained from
212357  ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
212358  ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
212359  */
212360  static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
212361    Fts5Colset *pRet;
212362    if( pOrig ){
212363      sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
212364      pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
212365      if( pRet ){ 
212366        memcpy(pRet, pOrig, nByte);
212367      }
212368    }else{
212369      pRet = 0;
212370    }
212371    return pRet;
212372  }
212373  
212374  /*
212375  ** Remove from colset pColset any columns that are not also in colset pMerge.
212376  */
212377  static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
212378    int iIn = 0;          /* Next input in pColset */
212379    int iMerge = 0;       /* Next input in pMerge */
212380    int iOut = 0;         /* Next output slot in pColset */
212381  
212382    while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
212383      int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
212384      if( iDiff==0 ){
212385        pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
212386        iMerge++;
212387        iIn++;
212388      }else if( iDiff>0 ){
212389        iMerge++;
212390      }else{
212391        iIn++;
212392      }
212393    }
212394    pColset->nCol = iOut;
212395  }
212396  
212397  /*
212398  ** Recursively apply colset pColset to expression node pNode and all of
212399  ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
212400  ** of pColset. This function may use the spare copy and set (*ppFree) to
212401  ** zero, or it may create copies of pColset using fts5CloneColset().
212402  */
212403  static void fts5ParseSetColset(
212404    Fts5Parse *pParse, 
212405    Fts5ExprNode *pNode, 
212406    Fts5Colset *pColset,
212407    Fts5Colset **ppFree
212408  ){
212409    if( pParse->rc==SQLITE_OK ){
212410      assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING 
212411           || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
212412           || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
212413      );
212414      if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
212415        Fts5ExprNearset *pNear = pNode->pNear;
212416        if( pNear->pColset ){
212417          fts5MergeColset(pNear->pColset, pColset);
212418          if( pNear->pColset->nCol==0 ){
212419            pNode->eType = FTS5_EOF;
212420            pNode->xNext = 0;
212421          }
212422        }else if( *ppFree ){
212423          pNear->pColset = pColset;
212424          *ppFree = 0;
212425        }else{
212426          pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
212427        }
212428      }else{
212429        int i;
212430        assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
212431        for(i=0; i<pNode->nChild; i++){
212432          fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
212433        }
212434      }
212435    }
212436  }
212437  
212438  /*
212439  ** Apply colset pColset to expression node pExpr and all of its descendents.
212440  */
212441  static void sqlite3Fts5ParseSetColset(
212442    Fts5Parse *pParse, 
212443    Fts5ExprNode *pExpr, 
212444    Fts5Colset *pColset 
212445  ){
212446    Fts5Colset *pFree = pColset;
212447    if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
212448      pParse->rc = SQLITE_ERROR;
212449      pParse->zErr = sqlite3_mprintf(
212450        "fts5: column queries are not supported (detail=none)"
212451      );
212452    }else{
212453      fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
212454    }
212455    sqlite3_free(pFree);
212456  }
212457  
212458  static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
212459    switch( pNode->eType ){
212460      case FTS5_STRING: {
212461        Fts5ExprNearset *pNear = pNode->pNear;
212462        if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 
212463         && pNear->apPhrase[0]->aTerm[0].pSynonym==0
212464         && pNear->apPhrase[0]->aTerm[0].bFirst==0
212465        ){
212466          pNode->eType = FTS5_TERM;
212467          pNode->xNext = fts5ExprNodeNext_TERM;
212468        }else{
212469          pNode->xNext = fts5ExprNodeNext_STRING;
212470        }
212471        break;
212472      };
212473  
212474      case FTS5_OR: {
212475        pNode->xNext = fts5ExprNodeNext_OR;
212476        break;
212477      };
212478  
212479      case FTS5_AND: {
212480        pNode->xNext = fts5ExprNodeNext_AND;
212481        break;
212482      };
212483  
212484      default: assert( pNode->eType==FTS5_NOT ); {
212485        pNode->xNext = fts5ExprNodeNext_NOT;
212486        break;
212487      };
212488    }
212489  }
212490  
212491  static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
212492    if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
212493      int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
212494      memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
212495      p->nChild += pSub->nChild;
212496      sqlite3_free(pSub);
212497    }else{
212498      p->apChild[p->nChild++] = pSub;
212499    }
212500  }
212501  
212502  /*
212503  ** Allocate and return a new expression object. If anything goes wrong (i.e.
212504  ** OOM error), leave an error code in pParse and return NULL.
212505  */
212506  static Fts5ExprNode *sqlite3Fts5ParseNode(
212507    Fts5Parse *pParse,              /* Parse context */
212508    int eType,                      /* FTS5_STRING, AND, OR or NOT */
212509    Fts5ExprNode *pLeft,            /* Left hand child expression */
212510    Fts5ExprNode *pRight,           /* Right hand child expression */
212511    Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
212512  ){
212513    Fts5ExprNode *pRet = 0;
212514  
212515    if( pParse->rc==SQLITE_OK ){
212516      int nChild = 0;               /* Number of children of returned node */
212517      sqlite3_int64 nByte;          /* Bytes of space to allocate for this node */
212518   
212519      assert( (eType!=FTS5_STRING && !pNear)
212520           || (eType==FTS5_STRING && !pLeft && !pRight)
212521      );
212522      if( eType==FTS5_STRING && pNear==0 ) return 0;
212523      if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
212524      if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
212525  
212526      if( eType==FTS5_NOT ){
212527        nChild = 2;
212528      }else if( eType==FTS5_AND || eType==FTS5_OR ){
212529        nChild = 2;
212530        if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
212531        if( pRight->eType==eType ) nChild += pRight->nChild-1;
212532      }
212533  
212534      nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
212535      pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
212536  
212537      if( pRet ){
212538        pRet->eType = eType;
212539        pRet->pNear = pNear;
212540        fts5ExprAssignXNext(pRet);
212541        if( eType==FTS5_STRING ){
212542          int iPhrase;
212543          for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
212544            pNear->apPhrase[iPhrase]->pNode = pRet;
212545            if( pNear->apPhrase[iPhrase]->nTerm==0 ){
212546              pRet->xNext = 0;
212547              pRet->eType = FTS5_EOF;
212548            }
212549          }
212550  
212551          if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
212552            Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
212553            if( pNear->nPhrase!=1 
212554             || pPhrase->nTerm>1
212555             || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
212556            ){
212557              assert( pParse->rc==SQLITE_OK );
212558              pParse->rc = SQLITE_ERROR;
212559              assert( pParse->zErr==0 );
212560              pParse->zErr = sqlite3_mprintf(
212561                  "fts5: %s queries are not supported (detail!=full)", 
212562                  pNear->nPhrase==1 ? "phrase": "NEAR"
212563                  );
212564              sqlite3_free(pRet);
212565              pRet = 0;
212566            }
212567          }
212568        }else{
212569          fts5ExprAddChildren(pRet, pLeft);
212570          fts5ExprAddChildren(pRet, pRight);
212571        }
212572      }
212573    }
212574  
212575    if( pRet==0 ){
212576      assert( pParse->rc!=SQLITE_OK );
212577      sqlite3Fts5ParseNodeFree(pLeft);
212578      sqlite3Fts5ParseNodeFree(pRight);
212579      sqlite3Fts5ParseNearsetFree(pNear);
212580    }
212581    return pRet;
212582  }
212583  
212584  static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
212585    Fts5Parse *pParse,              /* Parse context */
212586    Fts5ExprNode *pLeft,            /* Left hand child expression */
212587    Fts5ExprNode *pRight            /* Right hand child expression */
212588  ){
212589    Fts5ExprNode *pRet = 0;
212590    Fts5ExprNode *pPrev;
212591  
212592    if( pParse->rc ){
212593      sqlite3Fts5ParseNodeFree(pLeft);
212594      sqlite3Fts5ParseNodeFree(pRight);
212595    }else{
212596  
212597      assert( pLeft->eType==FTS5_STRING 
212598          || pLeft->eType==FTS5_TERM
212599          || pLeft->eType==FTS5_EOF
212600          || pLeft->eType==FTS5_AND
212601      );
212602      assert( pRight->eType==FTS5_STRING 
212603          || pRight->eType==FTS5_TERM 
212604          || pRight->eType==FTS5_EOF 
212605      );
212606  
212607      if( pLeft->eType==FTS5_AND ){
212608        pPrev = pLeft->apChild[pLeft->nChild-1];
212609      }else{
212610        pPrev = pLeft;
212611      }
212612      assert( pPrev->eType==FTS5_STRING 
212613          || pPrev->eType==FTS5_TERM 
212614          || pPrev->eType==FTS5_EOF 
212615          );
212616  
212617      if( pRight->eType==FTS5_EOF ){
212618        assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
212619        sqlite3Fts5ParseNodeFree(pRight);
212620        pRet = pLeft;
212621        pParse->nPhrase--;
212622      }
212623      else if( pPrev->eType==FTS5_EOF ){
212624        Fts5ExprPhrase **ap;
212625  
212626        if( pPrev==pLeft ){
212627          pRet = pRight;
212628        }else{
212629          pLeft->apChild[pLeft->nChild-1] = pRight;
212630          pRet = pLeft;
212631        }
212632  
212633        ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
212634        assert( ap[0]==pPrev->pNear->apPhrase[0] );
212635        memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
212636        pParse->nPhrase--;
212637  
212638        sqlite3Fts5ParseNodeFree(pPrev);
212639      }
212640      else{
212641        pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
212642      }
212643    }
212644  
212645    return pRet;
212646  }
212647  
212648  static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
212649    sqlite3_int64 nByte = 0;
212650    Fts5ExprTerm *p;
212651    char *zQuoted;
212652  
212653    /* Determine the maximum amount of space required. */
212654    for(p=pTerm; p; p=p->pSynonym){
212655      nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
212656    }
212657    zQuoted = sqlite3_malloc64(nByte);
212658  
212659    if( zQuoted ){
212660      int i = 0;
212661      for(p=pTerm; p; p=p->pSynonym){
212662        char *zIn = p->zTerm;
212663        zQuoted[i++] = '"';
212664        while( *zIn ){
212665          if( *zIn=='"' ) zQuoted[i++] = '"';
212666          zQuoted[i++] = *zIn++;
212667        }
212668        zQuoted[i++] = '"';
212669        if( p->pSynonym ) zQuoted[i++] = '|';
212670      }
212671      if( pTerm->bPrefix ){
212672        zQuoted[i++] = ' ';
212673        zQuoted[i++] = '*';
212674      }
212675      zQuoted[i++] = '\0';
212676    }
212677    return zQuoted;
212678  }
212679  
212680  static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
212681    char *zNew;
212682    va_list ap;
212683    va_start(ap, zFmt);
212684    zNew = sqlite3_vmprintf(zFmt, ap);
212685    va_end(ap);
212686    if( zApp && zNew ){
212687      char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
212688      sqlite3_free(zNew);
212689      zNew = zNew2;
212690    }
212691    sqlite3_free(zApp);
212692    return zNew;
212693  }
212694  
212695  /*
212696  ** Compose a tcl-readable representation of expression pExpr. Return a 
212697  ** pointer to a buffer containing that representation. It is the 
212698  ** responsibility of the caller to at some point free the buffer using 
212699  ** sqlite3_free().
212700  */
212701  static char *fts5ExprPrintTcl(
212702    Fts5Config *pConfig, 
212703    const char *zNearsetCmd,
212704    Fts5ExprNode *pExpr
212705  ){
212706    char *zRet = 0;
212707    if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
212708      Fts5ExprNearset *pNear = pExpr->pNear;
212709      int i; 
212710      int iTerm;
212711  
212712      zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
212713      if( zRet==0 ) return 0;
212714      if( pNear->pColset ){
212715        int *aiCol = pNear->pColset->aiCol;
212716        int nCol = pNear->pColset->nCol;
212717        if( nCol==1 ){
212718          zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
212719        }else{
212720          zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
212721          for(i=1; i<pNear->pColset->nCol; i++){
212722            zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
212723          }
212724          zRet = fts5PrintfAppend(zRet, "} ");
212725        }
212726        if( zRet==0 ) return 0;
212727      }
212728  
212729      if( pNear->nPhrase>1 ){
212730        zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
212731        if( zRet==0 ) return 0;
212732      }
212733  
212734      zRet = fts5PrintfAppend(zRet, "--");
212735      if( zRet==0 ) return 0;
212736  
212737      for(i=0; i<pNear->nPhrase; i++){
212738        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
212739  
212740        zRet = fts5PrintfAppend(zRet, " {");
212741        for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
212742          char *zTerm = pPhrase->aTerm[iTerm].zTerm;
212743          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
212744          if( pPhrase->aTerm[iTerm].bPrefix ){
212745            zRet = fts5PrintfAppend(zRet, "*");
212746          }
212747        }
212748  
212749        if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
212750        if( zRet==0 ) return 0;
212751      }
212752  
212753    }else{
212754      char const *zOp = 0;
212755      int i;
212756      switch( pExpr->eType ){
212757        case FTS5_AND: zOp = "AND"; break;
212758        case FTS5_NOT: zOp = "NOT"; break;
212759        default: 
212760          assert( pExpr->eType==FTS5_OR );
212761          zOp = "OR"; 
212762          break;
212763      }
212764  
212765      zRet = sqlite3_mprintf("%s", zOp);
212766      for(i=0; zRet && i<pExpr->nChild; i++){
212767        char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
212768        if( !z ){
212769          sqlite3_free(zRet);
212770          zRet = 0;
212771        }else{
212772          zRet = fts5PrintfAppend(zRet, " [%z]", z);
212773        }
212774      }
212775    }
212776  
212777    return zRet;
212778  }
212779  
212780  static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
212781    char *zRet = 0;
212782    if( pExpr->eType==0 ){
212783      return sqlite3_mprintf("\"\"");
212784    }else
212785    if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
212786      Fts5ExprNearset *pNear = pExpr->pNear;
212787      int i; 
212788      int iTerm;
212789  
212790      if( pNear->pColset ){
212791        int iCol = pNear->pColset->aiCol[0];
212792        zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
212793        if( zRet==0 ) return 0;
212794      }
212795  
212796      if( pNear->nPhrase>1 ){
212797        zRet = fts5PrintfAppend(zRet, "NEAR(");
212798        if( zRet==0 ) return 0;
212799      }
212800  
212801      for(i=0; i<pNear->nPhrase; i++){
212802        Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
212803        if( i!=0 ){
212804          zRet = fts5PrintfAppend(zRet, " ");
212805          if( zRet==0 ) return 0;
212806        }
212807        for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
212808          char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
212809          if( zTerm ){
212810            zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
212811            sqlite3_free(zTerm);
212812          }
212813          if( zTerm==0 || zRet==0 ){
212814            sqlite3_free(zRet);
212815            return 0;
212816          }
212817        }
212818      }
212819  
212820      if( pNear->nPhrase>1 ){
212821        zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
212822        if( zRet==0 ) return 0;
212823      }
212824  
212825    }else{
212826      char const *zOp = 0;
212827      int i;
212828  
212829      switch( pExpr->eType ){
212830        case FTS5_AND: zOp = " AND "; break;
212831        case FTS5_NOT: zOp = " NOT "; break;
212832        default:  
212833          assert( pExpr->eType==FTS5_OR );
212834          zOp = " OR "; 
212835          break;
212836      }
212837  
212838      for(i=0; i<pExpr->nChild; i++){
212839        char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
212840        if( z==0 ){
212841          sqlite3_free(zRet);
212842          zRet = 0;
212843        }else{
212844          int e = pExpr->apChild[i]->eType;
212845          int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
212846          zRet = fts5PrintfAppend(zRet, "%s%s%z%s", 
212847              (i==0 ? "" : zOp),
212848              (b?"(":""), z, (b?")":"")
212849          );
212850        }
212851        if( zRet==0 ) break;
212852      }
212853    }
212854  
212855    return zRet;
212856  }
212857  
212858  /*
212859  ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
212860  ** and fts5_expr_tcl() (bTcl!=0).
212861  */
212862  static void fts5ExprFunction(
212863    sqlite3_context *pCtx,          /* Function call context */
212864    int nArg,                       /* Number of args */
212865    sqlite3_value **apVal,          /* Function arguments */
212866    int bTcl
212867  ){
212868    Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
212869    sqlite3 *db = sqlite3_context_db_handle(pCtx);
212870    const char *zExpr = 0;
212871    char *zErr = 0;
212872    Fts5Expr *pExpr = 0;
212873    int rc;
212874    int i;
212875  
212876    const char **azConfig;          /* Array of arguments for Fts5Config */
212877    const char *zNearsetCmd = "nearset";
212878    int nConfig;                    /* Size of azConfig[] */
212879    Fts5Config *pConfig = 0;
212880    int iArg = 1;
212881  
212882    if( nArg<1 ){
212883      zErr = sqlite3_mprintf("wrong number of arguments to function %s",
212884          bTcl ? "fts5_expr_tcl" : "fts5_expr"
212885      );
212886      sqlite3_result_error(pCtx, zErr, -1);
212887      sqlite3_free(zErr);
212888      return;
212889    }
212890  
212891    if( bTcl && nArg>1 ){
212892      zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
212893      iArg = 2;
212894    }
212895  
212896    nConfig = 3 + (nArg-iArg);
212897    azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
212898    if( azConfig==0 ){
212899      sqlite3_result_error_nomem(pCtx);
212900      return;
212901    }
212902    azConfig[0] = 0;
212903    azConfig[1] = "main";
212904    azConfig[2] = "tbl";
212905    for(i=3; iArg<nArg; iArg++){
212906      azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
212907    }
212908  
212909    zExpr = (const char*)sqlite3_value_text(apVal[0]);
212910  
212911    rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
212912    if( rc==SQLITE_OK ){
212913      rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
212914    }
212915    if( rc==SQLITE_OK ){
212916      char *zText;
212917      if( pExpr->pRoot->xNext==0 ){
212918        zText = sqlite3_mprintf("");
212919      }else if( bTcl ){
212920        zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
212921      }else{
212922        zText = fts5ExprPrint(pConfig, pExpr->pRoot);
212923      }
212924      if( zText==0 ){
212925        rc = SQLITE_NOMEM;
212926      }else{
212927        sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
212928        sqlite3_free(zText);
212929      }
212930    }
212931  
212932    if( rc!=SQLITE_OK ){
212933      if( zErr ){
212934        sqlite3_result_error(pCtx, zErr, -1);
212935        sqlite3_free(zErr);
212936      }else{
212937        sqlite3_result_error_code(pCtx, rc);
212938      }
212939    }
212940    sqlite3_free((void *)azConfig);
212941    sqlite3Fts5ConfigFree(pConfig);
212942    sqlite3Fts5ExprFree(pExpr);
212943  }
212944  
212945  static void fts5ExprFunctionHr(
212946    sqlite3_context *pCtx,          /* Function call context */
212947    int nArg,                       /* Number of args */
212948    sqlite3_value **apVal           /* Function arguments */
212949  ){
212950    fts5ExprFunction(pCtx, nArg, apVal, 0);
212951  }
212952  static void fts5ExprFunctionTcl(
212953    sqlite3_context *pCtx,          /* Function call context */
212954    int nArg,                       /* Number of args */
212955    sqlite3_value **apVal           /* Function arguments */
212956  ){
212957    fts5ExprFunction(pCtx, nArg, apVal, 1);
212958  }
212959  
212960  /*
212961  ** The implementation of an SQLite user-defined-function that accepts a
212962  ** single integer as an argument. If the integer is an alpha-numeric 
212963  ** unicode code point, 1 is returned. Otherwise 0.
212964  */
212965  static void fts5ExprIsAlnum(
212966    sqlite3_context *pCtx,          /* Function call context */
212967    int nArg,                       /* Number of args */
212968    sqlite3_value **apVal           /* Function arguments */
212969  ){
212970    int iCode;
212971    u8 aArr[32];
212972    if( nArg!=1 ){
212973      sqlite3_result_error(pCtx, 
212974          "wrong number of arguments to function fts5_isalnum", -1
212975      );
212976      return;
212977    }
212978    memset(aArr, 0, sizeof(aArr));
212979    sqlite3Fts5UnicodeCatParse("L*", aArr);
212980    sqlite3Fts5UnicodeCatParse("N*", aArr);
212981    sqlite3Fts5UnicodeCatParse("Co", aArr);
212982    iCode = sqlite3_value_int(apVal[0]);
212983    sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
212984  }
212985  
212986  static void fts5ExprFold(
212987    sqlite3_context *pCtx,          /* Function call context */
212988    int nArg,                       /* Number of args */
212989    sqlite3_value **apVal           /* Function arguments */
212990  ){
212991    if( nArg!=1 && nArg!=2 ){
212992      sqlite3_result_error(pCtx, 
212993          "wrong number of arguments to function fts5_fold", -1
212994      );
212995    }else{
212996      int iCode;
212997      int bRemoveDiacritics = 0;
212998      iCode = sqlite3_value_int(apVal[0]);
212999      if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
213000      sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
213001    }
213002  }
213003  
213004  /*
213005  ** This is called during initialization to register the fts5_expr() scalar
213006  ** UDF with the SQLite handle passed as the only argument.
213007  */
213008  static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
213009    struct Fts5ExprFunc {
213010      const char *z;
213011      void (*x)(sqlite3_context*,int,sqlite3_value**);
213012    } aFunc[] = {
213013      { "fts5_expr",     fts5ExprFunctionHr },
213014      { "fts5_expr_tcl", fts5ExprFunctionTcl },
213015      { "fts5_isalnum",  fts5ExprIsAlnum },
213016      { "fts5_fold",     fts5ExprFold },
213017    };
213018    int i;
213019    int rc = SQLITE_OK;
213020    void *pCtx = (void*)pGlobal;
213021  
213022    for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
213023      struct Fts5ExprFunc *p = &aFunc[i];
213024      rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
213025    }
213026  
213027    /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
213028    ** sqlite3Fts5ParserFallback() are unused */
213029  #ifndef NDEBUG
213030    (void)sqlite3Fts5ParserTrace;
213031  #endif
213032    (void)sqlite3Fts5ParserFallback;
213033  
213034    return rc;
213035  }
213036  
213037  /*
213038  ** Return the number of phrases in expression pExpr.
213039  */
213040  static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
213041    return (pExpr ? pExpr->nPhrase : 0);
213042  }
213043  
213044  /*
213045  ** Return the number of terms in the iPhrase'th phrase in pExpr.
213046  */
213047  static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
213048    if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
213049    return pExpr->apExprPhrase[iPhrase]->nTerm;
213050  }
213051  
213052  /*
213053  ** This function is used to access the current position list for phrase
213054  ** iPhrase.
213055  */
213056  static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
213057    int nRet;
213058    Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
213059    Fts5ExprNode *pNode = pPhrase->pNode;
213060    if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
213061      *pa = pPhrase->poslist.p;
213062      nRet = pPhrase->poslist.n;
213063    }else{
213064      *pa = 0;
213065      nRet = 0;
213066    }
213067    return nRet;
213068  }
213069  
213070  struct Fts5PoslistPopulator {
213071    Fts5PoslistWriter writer;
213072    int bOk;                        /* True if ok to populate */
213073    int bMiss;
213074  };
213075  
213076  static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
213077    Fts5PoslistPopulator *pRet;
213078    pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
213079    if( pRet ){
213080      int i;
213081      memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
213082      for(i=0; i<pExpr->nPhrase; i++){
213083        Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
213084        Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
213085        assert( pExpr->apExprPhrase[i]->nTerm==1 );
213086        if( bLive && 
213087            (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
213088        ){
213089          pRet[i].bMiss = 1;
213090        }else{
213091          pBuf->n = 0;
213092        }
213093      }
213094    }
213095    return pRet;
213096  }
213097  
213098  struct Fts5ExprCtx {
213099    Fts5Expr *pExpr;
213100    Fts5PoslistPopulator *aPopulator;
213101    i64 iOff;
213102  };
213103  typedef struct Fts5ExprCtx Fts5ExprCtx;
213104  
213105  /*
213106  ** TODO: Make this more efficient!
213107  */
213108  static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
213109    int i;
213110    for(i=0; i<pColset->nCol; i++){
213111      if( pColset->aiCol[i]==iCol ) return 1;
213112    }
213113    return 0;
213114  }
213115  
213116  static int fts5ExprPopulatePoslistsCb(
213117    void *pCtx,                /* Copy of 2nd argument to xTokenize() */
213118    int tflags,                /* Mask of FTS5_TOKEN_* flags */
213119    const char *pToken,        /* Pointer to buffer containing token */
213120    int nToken,                /* Size of token in bytes */
213121    int iUnused1,              /* Byte offset of token within input text */
213122    int iUnused2               /* Byte offset of end of token within input text */
213123  ){
213124    Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
213125    Fts5Expr *pExpr = p->pExpr;
213126    int i;
213127  
213128    UNUSED_PARAM2(iUnused1, iUnused2);
213129  
213130    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
213131    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
213132    for(i=0; i<pExpr->nPhrase; i++){
213133      Fts5ExprTerm *pTerm;
213134      if( p->aPopulator[i].bOk==0 ) continue;
213135      for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
213136        int nTerm = (int)strlen(pTerm->zTerm);
213137        if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
213138         && memcmp(pTerm->zTerm, pToken, nTerm)==0
213139        ){
213140          int rc = sqlite3Fts5PoslistWriterAppend(
213141              &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
213142          );
213143          if( rc ) return rc;
213144          break;
213145        }
213146      }
213147    }
213148    return SQLITE_OK;
213149  }
213150  
213151  static int sqlite3Fts5ExprPopulatePoslists(
213152    Fts5Config *pConfig,
213153    Fts5Expr *pExpr, 
213154    Fts5PoslistPopulator *aPopulator,
213155    int iCol, 
213156    const char *z, int n
213157  ){
213158    int i;
213159    Fts5ExprCtx sCtx;
213160    sCtx.pExpr = pExpr;
213161    sCtx.aPopulator = aPopulator;
213162    sCtx.iOff = (((i64)iCol) << 32) - 1;
213163  
213164    for(i=0; i<pExpr->nPhrase; i++){
213165      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
213166      Fts5Colset *pColset = pNode->pNear->pColset;
213167      if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) 
213168       || aPopulator[i].bMiss
213169      ){
213170        aPopulator[i].bOk = 0;
213171      }else{
213172        aPopulator[i].bOk = 1;
213173      }
213174    }
213175  
213176    return sqlite3Fts5Tokenize(pConfig, 
213177        FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
213178    );
213179  }
213180  
213181  static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
213182    if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
213183      pNode->pNear->apPhrase[0]->poslist.n = 0;
213184    }else{
213185      int i;
213186      for(i=0; i<pNode->nChild; i++){
213187        fts5ExprClearPoslists(pNode->apChild[i]);
213188      }
213189    }
213190  }
213191  
213192  static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
213193    pNode->iRowid = iRowid;
213194    pNode->bEof = 0;
213195    switch( pNode->eType ){
213196      case FTS5_TERM:
213197      case FTS5_STRING:
213198        return (pNode->pNear->apPhrase[0]->poslist.n>0);
213199  
213200      case FTS5_AND: {
213201        int i;
213202        for(i=0; i<pNode->nChild; i++){
213203          if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
213204            fts5ExprClearPoslists(pNode);
213205            return 0;
213206          }
213207        }
213208        break;
213209      }
213210  
213211      case FTS5_OR: {
213212        int i;
213213        int bRet = 0;
213214        for(i=0; i<pNode->nChild; i++){
213215          if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
213216            bRet = 1;
213217          }
213218        }
213219        return bRet;
213220      }
213221  
213222      default: {
213223        assert( pNode->eType==FTS5_NOT );
213224        if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
213225            || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
213226          ){
213227          fts5ExprClearPoslists(pNode);
213228          return 0;
213229        }
213230        break;
213231      }
213232    }
213233    return 1;
213234  }
213235  
213236  static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
213237    fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
213238  }
213239  
213240  /*
213241  ** This function is only called for detail=columns tables. 
213242  */
213243  static int sqlite3Fts5ExprPhraseCollist(
213244    Fts5Expr *pExpr, 
213245    int iPhrase, 
213246    const u8 **ppCollist, 
213247    int *pnCollist
213248  ){
213249    Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
213250    Fts5ExprNode *pNode = pPhrase->pNode;
213251    int rc = SQLITE_OK;
213252  
213253    assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
213254    assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
213255  
213256    if( pNode->bEof==0 
213257     && pNode->iRowid==pExpr->pRoot->iRowid 
213258     && pPhrase->poslist.n>0
213259    ){
213260      Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
213261      if( pTerm->pSynonym ){
213262        Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
213263        rc = fts5ExprSynonymList(
213264            pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
213265        );
213266      }else{
213267        *ppCollist = pPhrase->aTerm[0].pIter->pData;
213268        *pnCollist = pPhrase->aTerm[0].pIter->nData;
213269      }
213270    }else{
213271      *ppCollist = 0;
213272      *pnCollist = 0;
213273    }
213274  
213275    return rc;
213276  }
213277  
213278  /*
213279  ** 2014 August 11
213280  **
213281  ** The author disclaims copyright to this source code.  In place of
213282  ** a legal notice, here is a blessing:
213283  **
213284  **    May you do good and not evil.
213285  **    May you find forgiveness for yourself and forgive others.
213286  **    May you share freely, never taking more than you give.
213287  **
213288  ******************************************************************************
213289  **
213290  */
213291  
213292  
213293  
213294  /* #include "fts5Int.h" */
213295  
213296  typedef struct Fts5HashEntry Fts5HashEntry;
213297  
213298  /*
213299  ** This file contains the implementation of an in-memory hash table used
213300  ** to accumuluate "term -> doclist" content before it is flused to a level-0
213301  ** segment.
213302  */
213303  
213304  
213305  struct Fts5Hash {
213306    int eDetail;                    /* Copy of Fts5Config.eDetail */
213307    int *pnByte;                    /* Pointer to bytes counter */
213308    int nEntry;                     /* Number of entries currently in hash */
213309    int nSlot;                      /* Size of aSlot[] array */
213310    Fts5HashEntry *pScan;           /* Current ordered scan item */
213311    Fts5HashEntry **aSlot;          /* Array of hash slots */
213312  };
213313  
213314  /*
213315  ** Each entry in the hash table is represented by an object of the 
213316  ** following type. Each object, its key (a nul-terminated string) and 
213317  ** its current data are stored in a single memory allocation. The 
213318  ** key immediately follows the object in memory. The position list
213319  ** data immediately follows the key data in memory.
213320  **
213321  ** The data that follows the key is in a similar, but not identical format
213322  ** to the doclist data stored in the database. It is:
213323  **
213324  **   * Rowid, as a varint
213325  **   * Position list, without 0x00 terminator.
213326  **   * Size of previous position list and rowid, as a 4 byte
213327  **     big-endian integer.
213328  **
213329  ** iRowidOff:
213330  **   Offset of last rowid written to data area. Relative to first byte of
213331  **   structure.
213332  **
213333  ** nData:
213334  **   Bytes of data written since iRowidOff.
213335  */
213336  struct Fts5HashEntry {
213337    Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
213338    Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
213339    
213340    int nAlloc;                     /* Total size of allocation */
213341    int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
213342    int nData;                      /* Total bytes of data (incl. structure) */
213343    int nKey;                       /* Length of key in bytes */
213344    u8 bDel;                        /* Set delete-flag @ iSzPoslist */
213345    u8 bContent;                    /* Set content-flag (detail=none mode) */
213346    i16 iCol;                       /* Column of last value written */
213347    int iPos;                       /* Position of last value written */
213348    i64 iRowid;                     /* Rowid of last value written */
213349  };
213350  
213351  /*
213352  ** Eqivalent to:
213353  **
213354  **   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
213355  */
213356  #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
213357  
213358  
213359  /*
213360  ** Allocate a new hash table.
213361  */
213362  static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
213363    int rc = SQLITE_OK;
213364    Fts5Hash *pNew;
213365  
213366    *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
213367    if( pNew==0 ){
213368      rc = SQLITE_NOMEM;
213369    }else{
213370      sqlite3_int64 nByte;
213371      memset(pNew, 0, sizeof(Fts5Hash));
213372      pNew->pnByte = pnByte;
213373      pNew->eDetail = pConfig->eDetail;
213374  
213375      pNew->nSlot = 1024;
213376      nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
213377      pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
213378      if( pNew->aSlot==0 ){
213379        sqlite3_free(pNew);
213380        *ppNew = 0;
213381        rc = SQLITE_NOMEM;
213382      }else{
213383        memset(pNew->aSlot, 0, nByte);
213384      }
213385    }
213386    return rc;
213387  }
213388  
213389  /*
213390  ** Free a hash table object.
213391  */
213392  static void sqlite3Fts5HashFree(Fts5Hash *pHash){
213393    if( pHash ){
213394      sqlite3Fts5HashClear(pHash);
213395      sqlite3_free(pHash->aSlot);
213396      sqlite3_free(pHash);
213397    }
213398  }
213399  
213400  /*
213401  ** Empty (but do not delete) a hash table.
213402  */
213403  static void sqlite3Fts5HashClear(Fts5Hash *pHash){
213404    int i;
213405    for(i=0; i<pHash->nSlot; i++){
213406      Fts5HashEntry *pNext;
213407      Fts5HashEntry *pSlot;
213408      for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
213409        pNext = pSlot->pHashNext;
213410        sqlite3_free(pSlot);
213411      }
213412    }
213413    memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
213414    pHash->nEntry = 0;
213415  }
213416  
213417  static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
213418    int i;
213419    unsigned int h = 13;
213420    for(i=n-1; i>=0; i--){
213421      h = (h << 3) ^ h ^ p[i];
213422    }
213423    return (h % nSlot);
213424  }
213425  
213426  static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
213427    int i;
213428    unsigned int h = 13;
213429    for(i=n-1; i>=0; i--){
213430      h = (h << 3) ^ h ^ p[i];
213431    }
213432    h = (h << 3) ^ h ^ b;
213433    return (h % nSlot);
213434  }
213435  
213436  /*
213437  ** Resize the hash table by doubling the number of slots.
213438  */
213439  static int fts5HashResize(Fts5Hash *pHash){
213440    int nNew = pHash->nSlot*2;
213441    int i;
213442    Fts5HashEntry **apNew;
213443    Fts5HashEntry **apOld = pHash->aSlot;
213444  
213445    apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
213446    if( !apNew ) return SQLITE_NOMEM;
213447    memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
213448  
213449    for(i=0; i<pHash->nSlot; i++){
213450      while( apOld[i] ){
213451        unsigned int iHash;
213452        Fts5HashEntry *p = apOld[i];
213453        apOld[i] = p->pHashNext;
213454        iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
213455                            (int)strlen(fts5EntryKey(p)));
213456        p->pHashNext = apNew[iHash];
213457        apNew[iHash] = p;
213458      }
213459    }
213460  
213461    sqlite3_free(apOld);
213462    pHash->nSlot = nNew;
213463    pHash->aSlot = apNew;
213464    return SQLITE_OK;
213465  }
213466  
213467  static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
213468    if( p->iSzPoslist ){
213469      u8 *pPtr = (u8*)p;
213470      if( pHash->eDetail==FTS5_DETAIL_NONE ){
213471        assert( p->nData==p->iSzPoslist );
213472        if( p->bDel ){
213473          pPtr[p->nData++] = 0x00;
213474          if( p->bContent ){
213475            pPtr[p->nData++] = 0x00;
213476          }
213477        }
213478      }else{
213479        int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
213480        int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
213481  
213482        assert( p->bDel==0 || p->bDel==1 );
213483        if( nPos<=127 ){
213484          pPtr[p->iSzPoslist] = (u8)nPos;
213485        }else{
213486          int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
213487          memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
213488          sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
213489          p->nData += (nByte-1);
213490        }
213491      }
213492  
213493      p->iSzPoslist = 0;
213494      p->bDel = 0;
213495      p->bContent = 0;
213496    }
213497  }
213498  
213499  /*
213500  ** Add an entry to the in-memory hash table. The key is the concatenation
213501  ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
213502  **
213503  **     (bByte || pToken) -> (iRowid,iCol,iPos)
213504  **
213505  ** Or, if iCol is negative, then the value is a delete marker.
213506  */
213507  static int sqlite3Fts5HashWrite(
213508    Fts5Hash *pHash,
213509    i64 iRowid,                     /* Rowid for this entry */
213510    int iCol,                       /* Column token appears in (-ve -> delete) */
213511    int iPos,                       /* Position of token within column */
213512    char bByte,                     /* First byte of token */
213513    const char *pToken, int nToken  /* Token to add or remove to or from index */
213514  ){
213515    unsigned int iHash;
213516    Fts5HashEntry *p;
213517    u8 *pPtr;
213518    int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
213519    int bNew;                       /* If non-delete entry should be written */
213520    
213521    bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
213522  
213523    /* Attempt to locate an existing hash entry */
213524    iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
213525    for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
213526      char *zKey = fts5EntryKey(p);
213527      if( zKey[0]==bByte 
213528       && p->nKey==nToken
213529       && memcmp(&zKey[1], pToken, nToken)==0 
213530      ){
213531        break;
213532      }
213533    }
213534  
213535    /* If an existing hash entry cannot be found, create a new one. */
213536    if( p==0 ){
213537      /* Figure out how much space to allocate */
213538      char *zKey;
213539      sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
213540      if( nByte<128 ) nByte = 128;
213541  
213542      /* Grow the Fts5Hash.aSlot[] array if necessary. */
213543      if( (pHash->nEntry*2)>=pHash->nSlot ){
213544        int rc = fts5HashResize(pHash);
213545        if( rc!=SQLITE_OK ) return rc;
213546        iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
213547      }
213548  
213549      /* Allocate new Fts5HashEntry and add it to the hash table. */
213550      p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
213551      if( !p ) return SQLITE_NOMEM;
213552      memset(p, 0, sizeof(Fts5HashEntry));
213553      p->nAlloc = nByte;
213554      zKey = fts5EntryKey(p);
213555      zKey[0] = bByte;
213556      memcpy(&zKey[1], pToken, nToken);
213557      assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
213558      p->nKey = nToken;
213559      zKey[nToken+1] = '\0';
213560      p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
213561      p->pHashNext = pHash->aSlot[iHash];
213562      pHash->aSlot[iHash] = p;
213563      pHash->nEntry++;
213564  
213565      /* Add the first rowid field to the hash-entry */
213566      p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
213567      p->iRowid = iRowid;
213568  
213569      p->iSzPoslist = p->nData;
213570      if( pHash->eDetail!=FTS5_DETAIL_NONE ){
213571        p->nData += 1;
213572        p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
213573      }
213574  
213575      nIncr += p->nData;
213576    }else{
213577  
213578      /* Appending to an existing hash-entry. Check that there is enough 
213579      ** space to append the largest possible new entry. Worst case scenario 
213580      ** is:
213581      **
213582      **     + 9 bytes for a new rowid,
213583      **     + 4 byte reserved for the "poslist size" varint.
213584      **     + 1 byte for a "new column" byte,
213585      **     + 3 bytes for a new column number (16-bit max) as a varint,
213586      **     + 5 bytes for the new position offset (32-bit max).
213587      */
213588      if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
213589        sqlite3_int64 nNew = p->nAlloc * 2;
213590        Fts5HashEntry *pNew;
213591        Fts5HashEntry **pp;
213592        pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
213593        if( pNew==0 ) return SQLITE_NOMEM;
213594        pNew->nAlloc = (int)nNew;
213595        for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
213596        *pp = pNew;
213597        p = pNew;
213598      }
213599      nIncr -= p->nData;
213600    }
213601    assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
213602  
213603    pPtr = (u8*)p;
213604  
213605    /* If this is a new rowid, append the 4-byte size field for the previous
213606    ** entry, and the new rowid for this entry.  */
213607    if( iRowid!=p->iRowid ){
213608      fts5HashAddPoslistSize(pHash, p);
213609      p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
213610      p->iRowid = iRowid;
213611      bNew = 1;
213612      p->iSzPoslist = p->nData;
213613      if( pHash->eDetail!=FTS5_DETAIL_NONE ){
213614        p->nData += 1;
213615        p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
213616        p->iPos = 0;
213617      }
213618    }
213619  
213620    if( iCol>=0 ){
213621      if( pHash->eDetail==FTS5_DETAIL_NONE ){
213622        p->bContent = 1;
213623      }else{
213624        /* Append a new column value, if necessary */
213625        assert( iCol>=p->iCol );
213626        if( iCol!=p->iCol ){
213627          if( pHash->eDetail==FTS5_DETAIL_FULL ){
213628            pPtr[p->nData++] = 0x01;
213629            p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
213630            p->iCol = (i16)iCol;
213631            p->iPos = 0;
213632          }else{
213633            bNew = 1;
213634            p->iCol = (i16)(iPos = iCol);
213635          }
213636        }
213637  
213638        /* Append the new position offset, if necessary */
213639        if( bNew ){
213640          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
213641          p->iPos = iPos;
213642        }
213643      }
213644    }else{
213645      /* This is a delete. Set the delete flag. */
213646      p->bDel = 1;
213647    }
213648  
213649    nIncr += p->nData;
213650    *pHash->pnByte += nIncr;
213651    return SQLITE_OK;
213652  }
213653  
213654  
213655  /*
213656  ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
213657  ** each sorted in key order. This function merges the two lists into a
213658  ** single list and returns a pointer to its first element.
213659  */
213660  static Fts5HashEntry *fts5HashEntryMerge(
213661    Fts5HashEntry *pLeft,
213662    Fts5HashEntry *pRight
213663  ){
213664    Fts5HashEntry *p1 = pLeft;
213665    Fts5HashEntry *p2 = pRight;
213666    Fts5HashEntry *pRet = 0;
213667    Fts5HashEntry **ppOut = &pRet;
213668  
213669    while( p1 || p2 ){
213670      if( p1==0 ){
213671        *ppOut = p2;
213672        p2 = 0;
213673      }else if( p2==0 ){
213674        *ppOut = p1;
213675        p1 = 0;
213676      }else{
213677        int i = 0;
213678        char *zKey1 = fts5EntryKey(p1);
213679        char *zKey2 = fts5EntryKey(p2);
213680        while( zKey1[i]==zKey2[i] ) i++;
213681  
213682        if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
213683          /* p2 is smaller */
213684          *ppOut = p2;
213685          ppOut = &p2->pScanNext;
213686          p2 = p2->pScanNext;
213687        }else{
213688          /* p1 is smaller */
213689          *ppOut = p1;
213690          ppOut = &p1->pScanNext;
213691          p1 = p1->pScanNext;
213692        }
213693        *ppOut = 0;
213694      }
213695    }
213696  
213697    return pRet;
213698  }
213699  
213700  /*
213701  ** Extract all tokens from hash table iHash and link them into a list
213702  ** in sorted order. The hash table is cleared before returning. It is
213703  ** the responsibility of the caller to free the elements of the returned
213704  ** list.
213705  */
213706  static int fts5HashEntrySort(
213707    Fts5Hash *pHash, 
213708    const char *pTerm, int nTerm,   /* Query prefix, if any */
213709    Fts5HashEntry **ppSorted
213710  ){
213711    const int nMergeSlot = 32;
213712    Fts5HashEntry **ap;
213713    Fts5HashEntry *pList;
213714    int iSlot;
213715    int i;
213716  
213717    *ppSorted = 0;
213718    ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
213719    if( !ap ) return SQLITE_NOMEM;
213720    memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
213721  
213722    for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
213723      Fts5HashEntry *pIter;
213724      for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
213725        if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
213726          Fts5HashEntry *pEntry = pIter;
213727          pEntry->pScanNext = 0;
213728          for(i=0; ap[i]; i++){
213729            pEntry = fts5HashEntryMerge(pEntry, ap[i]);
213730            ap[i] = 0;
213731          }
213732          ap[i] = pEntry;
213733        }
213734      }
213735    }
213736  
213737    pList = 0;
213738    for(i=0; i<nMergeSlot; i++){
213739      pList = fts5HashEntryMerge(pList, ap[i]);
213740    }
213741  
213742    pHash->nEntry = 0;
213743    sqlite3_free(ap);
213744    *ppSorted = pList;
213745    return SQLITE_OK;
213746  }
213747  
213748  /*
213749  ** Query the hash table for a doclist associated with term pTerm/nTerm.
213750  */
213751  static int sqlite3Fts5HashQuery(
213752    Fts5Hash *pHash,                /* Hash table to query */
213753    const char *pTerm, int nTerm,   /* Query term */
213754    const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
213755    int *pnDoclist                  /* OUT: Size of doclist in bytes */
213756  ){
213757    unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
213758    char *zKey = 0;
213759    Fts5HashEntry *p;
213760  
213761    for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
213762      zKey = fts5EntryKey(p);
213763      assert( p->nKey+1==(int)strlen(zKey) );
213764      if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;
213765    }
213766  
213767    if( p ){
213768      fts5HashAddPoslistSize(pHash, p);
213769      *ppDoclist = (const u8*)&zKey[nTerm+1];
213770      *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
213771    }else{
213772      *ppDoclist = 0;
213773      *pnDoclist = 0;
213774    }
213775  
213776    return SQLITE_OK;
213777  }
213778  
213779  static int sqlite3Fts5HashScanInit(
213780    Fts5Hash *p,                    /* Hash table to query */
213781    const char *pTerm, int nTerm    /* Query prefix */
213782  ){
213783    return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
213784  }
213785  
213786  static void sqlite3Fts5HashScanNext(Fts5Hash *p){
213787    assert( !sqlite3Fts5HashScanEof(p) );
213788    p->pScan = p->pScan->pScanNext;
213789  }
213790  
213791  static int sqlite3Fts5HashScanEof(Fts5Hash *p){
213792    return (p->pScan==0);
213793  }
213794  
213795  static void sqlite3Fts5HashScanEntry(
213796    Fts5Hash *pHash,
213797    const char **pzTerm,            /* OUT: term (nul-terminated) */
213798    const u8 **ppDoclist,           /* OUT: pointer to doclist */
213799    int *pnDoclist                  /* OUT: size of doclist in bytes */
213800  ){
213801    Fts5HashEntry *p;
213802    if( (p = pHash->pScan) ){
213803      char *zKey = fts5EntryKey(p);
213804      int nTerm = (int)strlen(zKey);
213805      fts5HashAddPoslistSize(pHash, p);
213806      *pzTerm = zKey;
213807      *ppDoclist = (const u8*)&zKey[nTerm+1];
213808      *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
213809    }else{
213810      *pzTerm = 0;
213811      *ppDoclist = 0;
213812      *pnDoclist = 0;
213813    }
213814  }
213815  
213816  /*
213817  ** 2014 May 31
213818  **
213819  ** The author disclaims copyright to this source code.  In place of
213820  ** a legal notice, here is a blessing:
213821  **
213822  **    May you do good and not evil.
213823  **    May you find forgiveness for yourself and forgive others.
213824  **    May you share freely, never taking more than you give.
213825  **
213826  ******************************************************************************
213827  **
213828  ** Low level access to the FTS index stored in the database file. The 
213829  ** routines in this file file implement all read and write access to the
213830  ** %_data table. Other parts of the system access this functionality via
213831  ** the interface defined in fts5Int.h.
213832  */
213833  
213834  
213835  /* #include "fts5Int.h" */
213836  
213837  /*
213838  ** Overview:
213839  **
213840  ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
213841  ** As well as the main term index, there may be up to 31 prefix indexes.
213842  ** The format is similar to FTS3/4, except that:
213843  **
213844  **   * all segment b-tree leaf data is stored in fixed size page records 
213845  **     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is 
213846  **     taken to ensure it is possible to iterate in either direction through 
213847  **     the entries in a doclist, or to seek to a specific entry within a 
213848  **     doclist, without loading it into memory.
213849  **
213850  **   * large doclists that span many pages have associated "doclist index"
213851  **     records that contain a copy of the first rowid on each page spanned by
213852  **     the doclist. This is used to speed up seek operations, and merges of
213853  **     large doclists with very small doclists.
213854  **
213855  **   * extra fields in the "structure record" record the state of ongoing
213856  **     incremental merge operations.
213857  **
213858  */
213859  
213860  
213861  #define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
213862  #define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
213863  
213864  #define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
213865  
213866  #define FTS5_MAIN_PREFIX '0'
213867  
213868  #if FTS5_MAX_PREFIX_INDEXES > 31
213869  # error "FTS5_MAX_PREFIX_INDEXES is too large"
213870  #endif
213871  
213872  /*
213873  ** Details:
213874  **
213875  ** The %_data table managed by this module,
213876  **
213877  **     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
213878  **
213879  ** , contains the following 5 types of records. See the comments surrounding
213880  ** the FTS5_*_ROWID macros below for a description of how %_data rowids are 
213881  ** assigned to each fo them.
213882  **
213883  ** 1. Structure Records:
213884  **
213885  **   The set of segments that make up an index - the index structure - are
213886  **   recorded in a single record within the %_data table. The record consists
213887  **   of a single 32-bit configuration cookie value followed by a list of 
213888  **   SQLite varints. If the FTS table features more than one index (because
213889  **   there are one or more prefix indexes), it is guaranteed that all share
213890  **   the same cookie value.
213891  **
213892  **   Immediately following the configuration cookie, the record begins with
213893  **   three varints:
213894  **
213895  **     + number of levels,
213896  **     + total number of segments on all levels,
213897  **     + value of write counter.
213898  **
213899  **   Then, for each level from 0 to nMax:
213900  **
213901  **     + number of input segments in ongoing merge.
213902  **     + total number of segments in level.
213903  **     + for each segment from oldest to newest:
213904  **         + segment id (always > 0)
213905  **         + first leaf page number (often 1, always greater than 0)
213906  **         + final leaf page number
213907  **
213908  ** 2. The Averages Record:
213909  **
213910  **   A single record within the %_data table. The data is a list of varints.
213911  **   The first value is the number of rows in the index. Then, for each column
213912  **   from left to right, the total number of tokens in the column for all
213913  **   rows of the table.
213914  **
213915  ** 3. Segment leaves:
213916  **
213917  **   TERM/DOCLIST FORMAT:
213918  **
213919  **     Most of each segment leaf is taken up by term/doclist data. The 
213920  **     general format of term/doclist, starting with the first term
213921  **     on the leaf page, is:
213922  **
213923  **         varint : size of first term
213924  **         blob:    first term data
213925  **         doclist: first doclist
213926  **         zero-or-more {
213927  **           varint:  number of bytes in common with previous term
213928  **           varint:  number of bytes of new term data (nNew)
213929  **           blob:    nNew bytes of new term data
213930  **           doclist: next doclist
213931  **         }
213932  **
213933  **     doclist format:
213934  **
213935  **         varint:  first rowid
213936  **         poslist: first poslist
213937  **         zero-or-more {
213938  **           varint:  rowid delta (always > 0)
213939  **           poslist: next poslist
213940  **         }
213941  **
213942  **     poslist format:
213943  **
213944  **         varint: size of poslist in bytes multiplied by 2, not including
213945  **                 this field. Plus 1 if this entry carries the "delete" flag.
213946  **         collist: collist for column 0
213947  **         zero-or-more {
213948  **           0x01 byte
213949  **           varint: column number (I)
213950  **           collist: collist for column I
213951  **         }
213952  **
213953  **     collist format:
213954  **
213955  **         varint: first offset + 2
213956  **         zero-or-more {
213957  **           varint: offset delta + 2
213958  **         }
213959  **
213960  **   PAGE FORMAT
213961  **
213962  **     Each leaf page begins with a 4-byte header containing 2 16-bit 
213963  **     unsigned integer fields in big-endian format. They are:
213964  **
213965  **       * The byte offset of the first rowid on the page, if it exists
213966  **         and occurs before the first term (otherwise 0).
213967  **
213968  **       * The byte offset of the start of the page footer. If the page
213969  **         footer is 0 bytes in size, then this field is the same as the
213970  **         size of the leaf page in bytes.
213971  **
213972  **     The page footer consists of a single varint for each term located
213973  **     on the page. Each varint is the byte offset of the current term
213974  **     within the page, delta-compressed against the previous value. In
213975  **     other words, the first varint in the footer is the byte offset of
213976  **     the first term, the second is the byte offset of the second less that
213977  **     of the first, and so on.
213978  **
213979  **     The term/doclist format described above is accurate if the entire
213980  **     term/doclist data fits on a single leaf page. If this is not the case,
213981  **     the format is changed in two ways:
213982  **
213983  **       + if the first rowid on a page occurs before the first term, it
213984  **         is stored as a literal value:
213985  **
213986  **             varint:  first rowid
213987  **
213988  **       + the first term on each page is stored in the same way as the
213989  **         very first term of the segment:
213990  **
213991  **             varint : size of first term
213992  **             blob:    first term data
213993  **
213994  ** 5. Segment doclist indexes:
213995  **
213996  **   Doclist indexes are themselves b-trees, however they usually consist of
213997  **   a single leaf record only. The format of each doclist index leaf page 
213998  **   is:
213999  **
214000  **     * Flags byte. Bits are:
214001  **         0x01: Clear if leaf is also the root page, otherwise set.
214002  **
214003  **     * Page number of fts index leaf page. As a varint.
214004  **
214005  **     * First rowid on page indicated by previous field. As a varint.
214006  **
214007  **     * A list of varints, one for each subsequent termless page. A 
214008  **       positive delta if the termless page contains at least one rowid, 
214009  **       or an 0x00 byte otherwise.
214010  **
214011  **   Internal doclist index nodes are:
214012  **
214013  **     * Flags byte. Bits are:
214014  **         0x01: Clear for root page, otherwise set.
214015  **
214016  **     * Page number of first child page. As a varint.
214017  **
214018  **     * Copy of first rowid on page indicated by previous field. As a varint.
214019  **
214020  **     * A list of delta-encoded varints - the first rowid on each subsequent
214021  **       child page. 
214022  **
214023  */
214024  
214025  /*
214026  ** Rowids for the averages and structure records in the %_data table.
214027  */
214028  #define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
214029  #define FTS5_STRUCTURE_ROWID   10    /* The structure record */
214030  
214031  /*
214032  ** Macros determining the rowids used by segment leaves and dlidx leaves
214033  ** and nodes. All nodes and leaves are stored in the %_data table with large
214034  ** positive rowids.
214035  **
214036  ** Each segment has a unique non-zero 16-bit id.
214037  **
214038  ** The rowid for each segment leaf is found by passing the segment id and 
214039  ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
214040  ** sequentially starting from 1.
214041  */
214042  #define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
214043  #define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
214044  #define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
214045  #define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
214046  
214047  #define fts5_dri(segid, dlidx, height, pgno) (                                 \
214048   ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
214049   ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
214050   ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
214051   ((i64)(pgno))                                                                 \
214052  )
214053  
214054  #define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
214055  #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
214056  
214057  /*
214058  ** Maximum segments permitted in a single index 
214059  */
214060  #define FTS5_MAX_SEGMENT 2000
214061  
214062  #ifdef SQLITE_DEBUG
214063  static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
214064  #endif
214065  
214066  
214067  /*
214068  ** Each time a blob is read from the %_data table, it is padded with this
214069  ** many zero bytes. This makes it easier to decode the various record formats
214070  ** without overreading if the records are corrupt.
214071  */
214072  #define FTS5_DATA_ZERO_PADDING 8
214073  #define FTS5_DATA_PADDING 20
214074  
214075  typedef struct Fts5Data Fts5Data;
214076  typedef struct Fts5DlidxIter Fts5DlidxIter;
214077  typedef struct Fts5DlidxLvl Fts5DlidxLvl;
214078  typedef struct Fts5DlidxWriter Fts5DlidxWriter;
214079  typedef struct Fts5Iter Fts5Iter;
214080  typedef struct Fts5PageWriter Fts5PageWriter;
214081  typedef struct Fts5SegIter Fts5SegIter;
214082  typedef struct Fts5DoclistIter Fts5DoclistIter;
214083  typedef struct Fts5SegWriter Fts5SegWriter;
214084  typedef struct Fts5Structure Fts5Structure;
214085  typedef struct Fts5StructureLevel Fts5StructureLevel;
214086  typedef struct Fts5StructureSegment Fts5StructureSegment;
214087  
214088  struct Fts5Data {
214089    u8 *p;                          /* Pointer to buffer containing record */
214090    int nn;                         /* Size of record in bytes */
214091    int szLeaf;                     /* Size of leaf without page-index */
214092  };
214093  
214094  /*
214095  ** One object per %_data table.
214096  */
214097  struct Fts5Index {
214098    Fts5Config *pConfig;            /* Virtual table configuration */
214099    char *zDataTbl;                 /* Name of %_data table */
214100    int nWorkUnit;                  /* Leaf pages in a "unit" of work */
214101  
214102    /*
214103    ** Variables related to the accumulation of tokens and doclists within the
214104    ** in-memory hash tables before they are flushed to disk.
214105    */
214106    Fts5Hash *pHash;                /* Hash table for in-memory data */
214107    int nPendingData;               /* Current bytes of pending data */
214108    i64 iWriteRowid;                /* Rowid for current doc being written */
214109    int bDelete;                    /* Current write is a delete */
214110  
214111    /* Error state. */
214112    int rc;                         /* Current error code */
214113  
214114    /* State used by the fts5DataXXX() functions. */
214115    sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
214116    sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
214117    sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
214118    sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
214119    sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
214120    sqlite3_stmt *pIdxSelect;
214121    int nRead;                      /* Total number of blocks read */
214122  
214123    sqlite3_stmt *pDataVersion;
214124    i64 iStructVersion;             /* data_version when pStruct read */
214125    Fts5Structure *pStruct;         /* Current db structure (or NULL) */
214126  };
214127  
214128  struct Fts5DoclistIter {
214129    u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
214130  
214131    /* Output variables. aPoslist==0 at EOF */
214132    i64 iRowid;
214133    u8 *aPoslist;
214134    int nPoslist;
214135    int nSize;
214136  };
214137  
214138  /*
214139  ** The contents of the "structure" record for each index are represented
214140  ** using an Fts5Structure record in memory. Which uses instances of the 
214141  ** other Fts5StructureXXX types as components.
214142  */
214143  struct Fts5StructureSegment {
214144    int iSegid;                     /* Segment id */
214145    int pgnoFirst;                  /* First leaf page number in segment */
214146    int pgnoLast;                   /* Last leaf page number in segment */
214147  };
214148  struct Fts5StructureLevel {
214149    int nMerge;                     /* Number of segments in incr-merge */
214150    int nSeg;                       /* Total number of segments on level */
214151    Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
214152  };
214153  struct Fts5Structure {
214154    int nRef;                       /* Object reference count */
214155    u64 nWriteCounter;              /* Total leaves written to level 0 */
214156    int nSegment;                   /* Total segments in this structure */
214157    int nLevel;                     /* Number of levels in this index */
214158    Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
214159  };
214160  
214161  /*
214162  ** An object of type Fts5SegWriter is used to write to segments.
214163  */
214164  struct Fts5PageWriter {
214165    int pgno;                       /* Page number for this page */
214166    int iPrevPgidx;                 /* Previous value written into pgidx */
214167    Fts5Buffer buf;                 /* Buffer containing leaf data */
214168    Fts5Buffer pgidx;               /* Buffer containing page-index */
214169    Fts5Buffer term;                /* Buffer containing previous term on page */
214170  };
214171  struct Fts5DlidxWriter {
214172    int pgno;                       /* Page number for this page */
214173    int bPrevValid;                 /* True if iPrev is valid */
214174    i64 iPrev;                      /* Previous rowid value written to page */
214175    Fts5Buffer buf;                 /* Buffer containing page data */
214176  };
214177  struct Fts5SegWriter {
214178    int iSegid;                     /* Segid to write to */
214179    Fts5PageWriter writer;          /* PageWriter object */
214180    i64 iPrevRowid;                 /* Previous rowid written to current leaf */
214181    u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
214182    u8 bFirstRowidInPage;           /* True if next rowid is first in page */
214183    /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
214184    u8 bFirstTermInPage;            /* True if next term will be first in leaf */
214185    int nLeafWritten;               /* Number of leaf pages written */
214186    int nEmpty;                     /* Number of contiguous term-less nodes */
214187  
214188    int nDlidx;                     /* Allocated size of aDlidx[] array */
214189    Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
214190  
214191    /* Values to insert into the %_idx table */
214192    Fts5Buffer btterm;              /* Next term to insert into %_idx table */
214193    int iBtPage;                    /* Page number corresponding to btterm */
214194  };
214195  
214196  typedef struct Fts5CResult Fts5CResult;
214197  struct Fts5CResult {
214198    u16 iFirst;                     /* aSeg[] index of firstest iterator */
214199    u8 bTermEq;                     /* True if the terms are equal */
214200  };
214201  
214202  /*
214203  ** Object for iterating through a single segment, visiting each term/rowid
214204  ** pair in the segment.
214205  **
214206  ** pSeg:
214207  **   The segment to iterate through.
214208  **
214209  ** iLeafPgno:
214210  **   Current leaf page number within segment.
214211  **
214212  ** iLeafOffset:
214213  **   Byte offset within the current leaf that is the first byte of the 
214214  **   position list data (one byte passed the position-list size field).
214215  **   rowid field of the current entry. Usually this is the size field of the
214216  **   position list data. The exception is if the rowid for the current entry 
214217  **   is the last thing on the leaf page.
214218  **
214219  ** pLeaf:
214220  **   Buffer containing current leaf page data. Set to NULL at EOF.
214221  **
214222  ** iTermLeafPgno, iTermLeafOffset:
214223  **   Leaf page number containing the last term read from the segment. And
214224  **   the offset immediately following the term data.
214225  **
214226  ** flags:
214227  **   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
214228  **
214229  **   FTS5_SEGITER_ONETERM:
214230  **     If set, set the iterator to point to EOF after the current doclist 
214231  **     has been exhausted. Do not proceed to the next term in the segment.
214232  **
214233  **   FTS5_SEGITER_REVERSE:
214234  **     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
214235  **     it is set, iterate through rowid in descending order instead of the
214236  **     default ascending order.
214237  **
214238  ** iRowidOffset/nRowidOffset/aRowidOffset:
214239  **     These are used if the FTS5_SEGITER_REVERSE flag is set.
214240  **
214241  **     For each rowid on the page corresponding to the current term, the
214242  **     corresponding aRowidOffset[] entry is set to the byte offset of the
214243  **     start of the "position-list-size" field within the page.
214244  **
214245  ** iTermIdx:
214246  **     Index of current term on iTermLeafPgno.
214247  */
214248  struct Fts5SegIter {
214249    Fts5StructureSegment *pSeg;     /* Segment to iterate through */
214250    int flags;                      /* Mask of configuration flags */
214251    int iLeafPgno;                  /* Current leaf page number */
214252    Fts5Data *pLeaf;                /* Current leaf data */
214253    Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
214254    int iLeafOffset;                /* Byte offset within current leaf */
214255  
214256    /* Next method */
214257    void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
214258  
214259    /* The page and offset from which the current term was read. The offset 
214260    ** is the offset of the first rowid in the current doclist.  */
214261    int iTermLeafPgno;
214262    int iTermLeafOffset;
214263  
214264    int iPgidxOff;                  /* Next offset in pgidx */
214265    int iEndofDoclist;
214266  
214267    /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
214268    int iRowidOffset;               /* Current entry in aRowidOffset[] */
214269    int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
214270    int *aRowidOffset;              /* Array of offset to rowid fields */
214271  
214272    Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
214273  
214274    /* Variables populated based on current entry. */
214275    Fts5Buffer term;                /* Current term */
214276    i64 iRowid;                     /* Current rowid */
214277    int nPos;                       /* Number of bytes in current position list */
214278    u8 bDel;                        /* True if the delete flag is set */
214279  };
214280  
214281  /*
214282  ** Argument is a pointer to an Fts5Data structure that contains a 
214283  ** leaf page.
214284  */
214285  #define ASSERT_SZLEAF_OK(x) assert( \
214286      (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
214287  )
214288  
214289  #define FTS5_SEGITER_ONETERM 0x01
214290  #define FTS5_SEGITER_REVERSE 0x02
214291  
214292  /* 
214293  ** Argument is a pointer to an Fts5Data structure that contains a leaf
214294  ** page. This macro evaluates to true if the leaf contains no terms, or
214295  ** false if it contains at least one term.
214296  */
214297  #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
214298  
214299  #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
214300  
214301  #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
214302  
214303  /*
214304  ** Object for iterating through the merged results of one or more segments,
214305  ** visiting each term/rowid pair in the merged data.
214306  **
214307  ** nSeg is always a power of two greater than or equal to the number of
214308  ** segments that this object is merging data from. Both the aSeg[] and
214309  ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
214310  ** with zeroed objects - these are handled as if they were iterators opened
214311  ** on empty segments.
214312  **
214313  ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
214314  ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the 
214315  ** comparison in this context is the index of the iterator that currently
214316  ** points to the smaller term/rowid combination. Iterators at EOF are
214317  ** considered to be greater than all other iterators.
214318  **
214319  ** aFirst[1] contains the index in aSeg[] of the iterator that points to
214320  ** the smallest key overall. aFirst[0] is unused. 
214321  **
214322  ** poslist:
214323  **   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
214324  **   There is no way to tell if this is populated or not.
214325  */
214326  struct Fts5Iter {
214327    Fts5IndexIter base;             /* Base class containing output vars */
214328  
214329    Fts5Index *pIndex;              /* Index that owns this iterator */
214330    Fts5Buffer poslist;             /* Buffer containing current poslist */
214331    Fts5Colset *pColset;            /* Restrict matches to these columns */
214332  
214333    /* Invoked to set output variables. */
214334    void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
214335  
214336    int nSeg;                       /* Size of aSeg[] array */
214337    int bRev;                       /* True to iterate in reverse order */
214338    u8 bSkipEmpty;                  /* True to skip deleted entries */
214339  
214340    i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
214341    Fts5CResult *aFirst;            /* Current merge state (see above) */
214342    Fts5SegIter aSeg[1];            /* Array of segment iterators */
214343  };
214344  
214345  
214346  /*
214347  ** An instance of the following type is used to iterate through the contents
214348  ** of a doclist-index record.
214349  **
214350  ** pData:
214351  **   Record containing the doclist-index data.
214352  **
214353  ** bEof:
214354  **   Set to true once iterator has reached EOF.
214355  **
214356  ** iOff:
214357  **   Set to the current offset within record pData.
214358  */
214359  struct Fts5DlidxLvl {
214360    Fts5Data *pData;              /* Data for current page of this level */
214361    int iOff;                     /* Current offset into pData */
214362    int bEof;                     /* At EOF already */
214363    int iFirstOff;                /* Used by reverse iterators */
214364  
214365    /* Output variables */
214366    int iLeafPgno;                /* Page number of current leaf page */
214367    i64 iRowid;                   /* First rowid on leaf iLeafPgno */
214368  };
214369  struct Fts5DlidxIter {
214370    int nLvl;
214371    int iSegid;
214372    Fts5DlidxLvl aLvl[1];
214373  };
214374  
214375  static void fts5PutU16(u8 *aOut, u16 iVal){
214376    aOut[0] = (iVal>>8);
214377    aOut[1] = (iVal&0xFF);
214378  }
214379  
214380  static u16 fts5GetU16(const u8 *aIn){
214381    return ((u16)aIn[0] << 8) + aIn[1];
214382  } 
214383  
214384  /*
214385  ** Allocate and return a buffer at least nByte bytes in size.
214386  **
214387  ** If an OOM error is encountered, return NULL and set the error code in
214388  ** the Fts5Index handle passed as the first argument.
214389  */
214390  static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
214391    return sqlite3Fts5MallocZero(&p->rc, nByte);
214392  }
214393  
214394  /*
214395  ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
214396  **
214397  ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
214398  ** +ve if pRight is smaller than pLeft. In other words:
214399  **
214400  **     res = *pLeft - *pRight
214401  */
214402  #ifdef SQLITE_DEBUG
214403  static int fts5BufferCompareBlob(
214404    Fts5Buffer *pLeft,              /* Left hand side of comparison */
214405    const u8 *pRight, int nRight    /* Right hand side of comparison */
214406  ){
214407    int nCmp = MIN(pLeft->n, nRight);
214408    int res = memcmp(pLeft->p, pRight, nCmp);
214409    return (res==0 ? (pLeft->n - nRight) : res);
214410  }
214411  #endif
214412  
214413  /*
214414  ** Compare the contents of the two buffers using memcmp(). If one buffer
214415  ** is a prefix of the other, it is considered the lesser.
214416  **
214417  ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
214418  ** +ve if pRight is smaller than pLeft. In other words:
214419  **
214420  **     res = *pLeft - *pRight
214421  */
214422  static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
214423    int nCmp = MIN(pLeft->n, pRight->n);
214424    int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
214425    return (res==0 ? (pLeft->n - pRight->n) : res);
214426  }
214427  
214428  static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
214429    int ret;
214430    fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
214431    return ret;
214432  }
214433  
214434  /*
214435  ** Close the read-only blob handle, if it is open.
214436  */
214437  static void fts5CloseReader(Fts5Index *p){
214438    if( p->pReader ){
214439      sqlite3_blob *pReader = p->pReader;
214440      p->pReader = 0;
214441      sqlite3_blob_close(pReader);
214442    }
214443  }
214444  
214445  /*
214446  ** Retrieve a record from the %_data table.
214447  **
214448  ** If an error occurs, NULL is returned and an error left in the 
214449  ** Fts5Index object.
214450  */
214451  static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
214452    Fts5Data *pRet = 0;
214453    if( p->rc==SQLITE_OK ){
214454      int rc = SQLITE_OK;
214455  
214456      if( p->pReader ){
214457        /* This call may return SQLITE_ABORT if there has been a savepoint
214458        ** rollback since it was last used. In this case a new blob handle
214459        ** is required.  */
214460        sqlite3_blob *pBlob = p->pReader;
214461        p->pReader = 0;
214462        rc = sqlite3_blob_reopen(pBlob, iRowid);
214463        assert( p->pReader==0 );
214464        p->pReader = pBlob;
214465        if( rc!=SQLITE_OK ){
214466          fts5CloseReader(p);
214467        }
214468        if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
214469      }
214470  
214471      /* If the blob handle is not open at this point, open it and seek 
214472      ** to the requested entry.  */
214473      if( p->pReader==0 && rc==SQLITE_OK ){
214474        Fts5Config *pConfig = p->pConfig;
214475        rc = sqlite3_blob_open(pConfig->db, 
214476            pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
214477        );
214478      }
214479  
214480      /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
214481      ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
214482      ** All the reasons those functions might return SQLITE_ERROR - missing
214483      ** table, missing row, non-blob/text in block column - indicate 
214484      ** backing store corruption.  */
214485      if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
214486  
214487      if( rc==SQLITE_OK ){
214488        u8 *aOut = 0;               /* Read blob data into this buffer */
214489        int nByte = sqlite3_blob_bytes(p->pReader);
214490        sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
214491        pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
214492        if( pRet ){
214493          pRet->nn = nByte;
214494          aOut = pRet->p = (u8*)&pRet[1];
214495        }else{
214496          rc = SQLITE_NOMEM;
214497        }
214498  
214499        if( rc==SQLITE_OK ){
214500          rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
214501        }
214502        if( rc!=SQLITE_OK ){
214503          sqlite3_free(pRet);
214504          pRet = 0;
214505        }else{
214506          /* TODO1: Fix this */
214507          pRet->p[nByte] = 0x00;
214508          pRet->szLeaf = fts5GetU16(&pRet->p[2]);
214509        }
214510      }
214511      p->rc = rc;
214512      p->nRead++;
214513    }
214514  
214515    assert( (pRet==0)==(p->rc!=SQLITE_OK) );
214516    return pRet;
214517  }
214518  
214519  /*
214520  ** Release a reference to data record returned by an earlier call to
214521  ** fts5DataRead().
214522  */
214523  static void fts5DataRelease(Fts5Data *pData){
214524    sqlite3_free(pData);
214525  }
214526  
214527  static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
214528    Fts5Data *pRet = fts5DataRead(p, iRowid);
214529    if( pRet ){
214530      if( pRet->szLeaf>pRet->nn ){
214531        p->rc = FTS5_CORRUPT;
214532        fts5DataRelease(pRet);
214533        pRet = 0;
214534      }
214535    }
214536    return pRet;
214537  }
214538  
214539  static int fts5IndexPrepareStmt(
214540    Fts5Index *p,
214541    sqlite3_stmt **ppStmt,
214542    char *zSql
214543  ){
214544    if( p->rc==SQLITE_OK ){
214545      if( zSql ){
214546        p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
214547            SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
214548            ppStmt, 0);
214549      }else{
214550        p->rc = SQLITE_NOMEM;
214551      }
214552    }
214553    sqlite3_free(zSql);
214554    return p->rc;
214555  }
214556  
214557  
214558  /*
214559  ** INSERT OR REPLACE a record into the %_data table.
214560  */
214561  static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
214562    if( p->rc!=SQLITE_OK ) return;
214563  
214564    if( p->pWriter==0 ){
214565      Fts5Config *pConfig = p->pConfig;
214566      fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
214567            "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", 
214568            pConfig->zDb, pConfig->zName
214569      ));
214570      if( p->rc ) return;
214571    }
214572  
214573    sqlite3_bind_int64(p->pWriter, 1, iRowid);
214574    sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
214575    sqlite3_step(p->pWriter);
214576    p->rc = sqlite3_reset(p->pWriter);
214577    sqlite3_bind_null(p->pWriter, 2);
214578  }
214579  
214580  /*
214581  ** Execute the following SQL:
214582  **
214583  **     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
214584  */
214585  static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
214586    if( p->rc!=SQLITE_OK ) return;
214587  
214588    if( p->pDeleter==0 ){
214589      Fts5Config *pConfig = p->pConfig;
214590      char *zSql = sqlite3_mprintf(
214591          "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", 
214592            pConfig->zDb, pConfig->zName
214593      );
214594      if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
214595    }
214596  
214597    sqlite3_bind_int64(p->pDeleter, 1, iFirst);
214598    sqlite3_bind_int64(p->pDeleter, 2, iLast);
214599    sqlite3_step(p->pDeleter);
214600    p->rc = sqlite3_reset(p->pDeleter);
214601  }
214602  
214603  /*
214604  ** Remove all records associated with segment iSegid.
214605  */
214606  static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
214607    i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
214608    i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
214609    fts5DataDelete(p, iFirst, iLast);
214610    if( p->pIdxDeleter==0 ){
214611      Fts5Config *pConfig = p->pConfig;
214612      fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
214613            "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
214614            pConfig->zDb, pConfig->zName
214615      ));
214616    }
214617    if( p->rc==SQLITE_OK ){
214618      sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
214619      sqlite3_step(p->pIdxDeleter);
214620      p->rc = sqlite3_reset(p->pIdxDeleter);
214621    }
214622  }
214623  
214624  /*
214625  ** Release a reference to an Fts5Structure object returned by an earlier 
214626  ** call to fts5StructureRead() or fts5StructureDecode().
214627  */
214628  static void fts5StructureRelease(Fts5Structure *pStruct){
214629    if( pStruct && 0>=(--pStruct->nRef) ){
214630      int i;
214631      assert( pStruct->nRef==0 );
214632      for(i=0; i<pStruct->nLevel; i++){
214633        sqlite3_free(pStruct->aLevel[i].aSeg);
214634      }
214635      sqlite3_free(pStruct);
214636    }
214637  }
214638  
214639  static void fts5StructureRef(Fts5Structure *pStruct){
214640    pStruct->nRef++;
214641  }
214642  
214643  /*
214644  ** Deserialize and return the structure record currently stored in serialized
214645  ** form within buffer pData/nData.
214646  **
214647  ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
214648  ** are over-allocated by one slot. This allows the structure contents
214649  ** to be more easily edited.
214650  **
214651  ** If an error occurs, *ppOut is set to NULL and an SQLite error code
214652  ** returned. Otherwise, *ppOut is set to point to the new object and
214653  ** SQLITE_OK returned.
214654  */
214655  static int fts5StructureDecode(
214656    const u8 *pData,                /* Buffer containing serialized structure */
214657    int nData,                      /* Size of buffer pData in bytes */
214658    int *piCookie,                  /* Configuration cookie value */
214659    Fts5Structure **ppOut           /* OUT: Deserialized object */
214660  ){
214661    int rc = SQLITE_OK;
214662    int i = 0;
214663    int iLvl;
214664    int nLevel = 0;
214665    int nSegment = 0;
214666    sqlite3_int64 nByte;            /* Bytes of space to allocate at pRet */
214667    Fts5Structure *pRet = 0;        /* Structure object to return */
214668  
214669    /* Grab the cookie value */
214670    if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
214671    i = 4;
214672  
214673    /* Read the total number of levels and segments from the start of the
214674    ** structure record.  */
214675    i += fts5GetVarint32(&pData[i], nLevel);
214676    i += fts5GetVarint32(&pData[i], nSegment);
214677    if( nLevel>FTS5_MAX_SEGMENT   || nLevel<0
214678     || nSegment>FTS5_MAX_SEGMENT || nSegment<0
214679    ){
214680      return FTS5_CORRUPT;
214681    }
214682    nByte = (
214683        sizeof(Fts5Structure) +                    /* Main structure */
214684        sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
214685    );
214686    pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
214687  
214688    if( pRet ){
214689      pRet->nRef = 1;
214690      pRet->nLevel = nLevel;
214691      pRet->nSegment = nSegment;
214692      i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
214693  
214694      for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
214695        Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
214696        int nTotal = 0;
214697        int iSeg;
214698  
214699        if( i>=nData ){
214700          rc = FTS5_CORRUPT;
214701        }else{
214702          i += fts5GetVarint32(&pData[i], pLvl->nMerge);
214703          i += fts5GetVarint32(&pData[i], nTotal);
214704          if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
214705          pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, 
214706              nTotal * sizeof(Fts5StructureSegment)
214707          );
214708          nSegment -= nTotal;
214709        }
214710  
214711        if( rc==SQLITE_OK ){
214712          pLvl->nSeg = nTotal;
214713          for(iSeg=0; iSeg<nTotal; iSeg++){
214714            Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
214715            if( i>=nData ){
214716              rc = FTS5_CORRUPT;
214717              break;
214718            }
214719            i += fts5GetVarint32(&pData[i], pSeg->iSegid);
214720            i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
214721            i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
214722            if( pSeg->pgnoLast<pSeg->pgnoFirst ){
214723              rc = FTS5_CORRUPT;
214724              break;
214725            }
214726          }
214727          if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
214728          if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
214729        }
214730      }
214731      if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
214732  
214733      if( rc!=SQLITE_OK ){
214734        fts5StructureRelease(pRet);
214735        pRet = 0;
214736      }
214737    }
214738  
214739    *ppOut = pRet;
214740    return rc;
214741  }
214742  
214743  /*
214744  **
214745  */
214746  static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
214747    if( *pRc==SQLITE_OK ){
214748      Fts5Structure *pStruct = *ppStruct;
214749      int nLevel = pStruct->nLevel;
214750      sqlite3_int64 nByte = (
214751          sizeof(Fts5Structure) +                  /* Main structure */
214752          sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
214753      );
214754  
214755      pStruct = sqlite3_realloc64(pStruct, nByte);
214756      if( pStruct ){
214757        memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
214758        pStruct->nLevel++;
214759        *ppStruct = pStruct;
214760      }else{
214761        *pRc = SQLITE_NOMEM;
214762      }
214763    }
214764  }
214765  
214766  /*
214767  ** Extend level iLvl so that there is room for at least nExtra more
214768  ** segments.
214769  */
214770  static void fts5StructureExtendLevel(
214771    int *pRc, 
214772    Fts5Structure *pStruct, 
214773    int iLvl, 
214774    int nExtra, 
214775    int bInsert
214776  ){
214777    if( *pRc==SQLITE_OK ){
214778      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
214779      Fts5StructureSegment *aNew;
214780      sqlite3_int64 nByte;
214781  
214782      nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
214783      aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
214784      if( aNew ){
214785        if( bInsert==0 ){
214786          memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
214787        }else{
214788          int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
214789          memmove(&aNew[nExtra], aNew, nMove);
214790          memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
214791        }
214792        pLvl->aSeg = aNew;
214793      }else{
214794        *pRc = SQLITE_NOMEM;
214795      }
214796    }
214797  }
214798  
214799  static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
214800    Fts5Structure *pRet = 0;
214801    Fts5Config *pConfig = p->pConfig;
214802    int iCookie;                    /* Configuration cookie */
214803    Fts5Data *pData;
214804  
214805    pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
214806    if( p->rc==SQLITE_OK ){
214807      /* TODO: Do we need this if the leaf-index is appended? Probably... */
214808      memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
214809      p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
214810      if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
214811        p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
214812      }
214813      fts5DataRelease(pData);
214814      if( p->rc!=SQLITE_OK ){
214815        fts5StructureRelease(pRet);
214816        pRet = 0;
214817      }
214818    }
214819  
214820    return pRet;
214821  }
214822  
214823  static i64 fts5IndexDataVersion(Fts5Index *p){
214824    i64 iVersion = 0;
214825  
214826    if( p->rc==SQLITE_OK ){
214827      if( p->pDataVersion==0 ){
214828        p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, 
214829            sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
214830            );
214831        if( p->rc ) return 0;
214832      }
214833  
214834      if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
214835        iVersion = sqlite3_column_int64(p->pDataVersion, 0);
214836      }
214837      p->rc = sqlite3_reset(p->pDataVersion);
214838    }
214839  
214840    return iVersion;
214841  }
214842  
214843  /*
214844  ** Read, deserialize and return the structure record.
214845  **
214846  ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
214847  ** are over-allocated as described for function fts5StructureDecode() 
214848  ** above.
214849  **
214850  ** If an error occurs, NULL is returned and an error code left in the
214851  ** Fts5Index handle. If an error has already occurred when this function
214852  ** is called, it is a no-op.
214853  */
214854  static Fts5Structure *fts5StructureRead(Fts5Index *p){
214855  
214856    if( p->pStruct==0 ){
214857      p->iStructVersion = fts5IndexDataVersion(p);
214858      if( p->rc==SQLITE_OK ){
214859        p->pStruct = fts5StructureReadUncached(p);
214860      }
214861    }
214862  
214863  #if 0
214864    else{
214865      Fts5Structure *pTest = fts5StructureReadUncached(p);
214866      if( pTest ){
214867        int i, j;
214868        assert_nc( p->pStruct->nSegment==pTest->nSegment );
214869        assert_nc( p->pStruct->nLevel==pTest->nLevel );
214870        for(i=0; i<pTest->nLevel; i++){
214871          assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
214872          assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
214873          for(j=0; j<pTest->aLevel[i].nSeg; j++){
214874            Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
214875            Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
214876            assert_nc( p1->iSegid==p2->iSegid );
214877            assert_nc( p1->pgnoFirst==p2->pgnoFirst );
214878            assert_nc( p1->pgnoLast==p2->pgnoLast );
214879          }
214880        }
214881        fts5StructureRelease(pTest);
214882      }
214883    }
214884  #endif
214885  
214886    if( p->rc!=SQLITE_OK ) return 0;
214887    assert( p->iStructVersion!=0 );
214888    assert( p->pStruct!=0 );
214889    fts5StructureRef(p->pStruct);
214890    return p->pStruct;
214891  }
214892  
214893  static void fts5StructureInvalidate(Fts5Index *p){
214894    if( p->pStruct ){
214895      fts5StructureRelease(p->pStruct);
214896      p->pStruct = 0;
214897    }
214898  }
214899  
214900  /*
214901  ** Return the total number of segments in index structure pStruct. This
214902  ** function is only ever used as part of assert() conditions.
214903  */
214904  #ifdef SQLITE_DEBUG
214905  static int fts5StructureCountSegments(Fts5Structure *pStruct){
214906    int nSegment = 0;               /* Total number of segments */
214907    if( pStruct ){
214908      int iLvl;                     /* Used to iterate through levels */
214909      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
214910        nSegment += pStruct->aLevel[iLvl].nSeg;
214911      }
214912    }
214913  
214914    return nSegment;
214915  }
214916  #endif
214917  
214918  #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
214919    assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
214920    memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
214921    (pBuf)->n += nBlob;                                      \
214922  }
214923  
214924  #define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
214925    (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
214926    assert( (pBuf)->nSpace>=(pBuf)->n );                          \
214927  }
214928  
214929  
214930  /*
214931  ** Serialize and store the "structure" record.
214932  **
214933  ** If an error occurs, leave an error code in the Fts5Index object. If an
214934  ** error has already occurred, this function is a no-op.
214935  */
214936  static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
214937    if( p->rc==SQLITE_OK ){
214938      Fts5Buffer buf;               /* Buffer to serialize record into */
214939      int iLvl;                     /* Used to iterate through levels */
214940      int iCookie;                  /* Cookie value to store */
214941  
214942      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
214943      memset(&buf, 0, sizeof(Fts5Buffer));
214944  
214945      /* Append the current configuration cookie */
214946      iCookie = p->pConfig->iCookie;
214947      if( iCookie<0 ) iCookie = 0;
214948  
214949      if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
214950        sqlite3Fts5Put32(buf.p, iCookie);
214951        buf.n = 4;
214952        fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
214953        fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
214954        fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
214955      }
214956  
214957      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
214958        int iSeg;                     /* Used to iterate through segments */
214959        Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
214960        fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
214961        fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
214962        assert( pLvl->nMerge<=pLvl->nSeg );
214963  
214964        for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
214965          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
214966          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
214967          fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
214968        }
214969      }
214970  
214971      fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
214972      fts5BufferFree(&buf);
214973    }
214974  }
214975  
214976  #if 0
214977  static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
214978  static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
214979    int rc = SQLITE_OK;
214980    Fts5Buffer buf;
214981    memset(&buf, 0, sizeof(buf));
214982    fts5DebugStructure(&rc, &buf, pStruct);
214983    fprintf(stdout, "%s: %s\n", zCaption, buf.p);
214984    fflush(stdout);
214985    fts5BufferFree(&buf);
214986  }
214987  #else
214988  # define fts5PrintStructure(x,y)
214989  #endif
214990  
214991  static int fts5SegmentSize(Fts5StructureSegment *pSeg){
214992    return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
214993  }
214994  
214995  /*
214996  ** Return a copy of index structure pStruct. Except, promote as many 
214997  ** segments as possible to level iPromote. If an OOM occurs, NULL is 
214998  ** returned.
214999  */
215000  static void fts5StructurePromoteTo(
215001    Fts5Index *p,
215002    int iPromote,
215003    int szPromote,
215004    Fts5Structure *pStruct
215005  ){
215006    int il, is;
215007    Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
215008  
215009    if( pOut->nMerge==0 ){
215010      for(il=iPromote+1; il<pStruct->nLevel; il++){
215011        Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
215012        if( pLvl->nMerge ) return;
215013        for(is=pLvl->nSeg-1; is>=0; is--){
215014          int sz = fts5SegmentSize(&pLvl->aSeg[is]);
215015          if( sz>szPromote ) return;
215016          fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
215017          if( p->rc ) return;
215018          memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
215019          pOut->nSeg++;
215020          pLvl->nSeg--;
215021        }
215022      }
215023    }
215024  }
215025  
215026  /*
215027  ** A new segment has just been written to level iLvl of index structure
215028  ** pStruct. This function determines if any segments should be promoted
215029  ** as a result. Segments are promoted in two scenarios:
215030  **
215031  **   a) If the segment just written is smaller than one or more segments
215032  **      within the previous populated level, it is promoted to the previous
215033  **      populated level.
215034  **
215035  **   b) If the segment just written is larger than the newest segment on
215036  **      the next populated level, then that segment, and any other adjacent
215037  **      segments that are also smaller than the one just written, are 
215038  **      promoted. 
215039  **
215040  ** If one or more segments are promoted, the structure object is updated
215041  ** to reflect this.
215042  */
215043  static void fts5StructurePromote(
215044    Fts5Index *p,                   /* FTS5 backend object */
215045    int iLvl,                       /* Index level just updated */
215046    Fts5Structure *pStruct          /* Index structure */
215047  ){
215048    if( p->rc==SQLITE_OK ){
215049      int iTst;
215050      int iPromote = -1;
215051      int szPromote = 0;            /* Promote anything this size or smaller */
215052      Fts5StructureSegment *pSeg;   /* Segment just written */
215053      int szSeg;                    /* Size of segment just written */
215054      int nSeg = pStruct->aLevel[iLvl].nSeg;
215055  
215056      if( nSeg==0 ) return;
215057      pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
215058      szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
215059  
215060      /* Check for condition (a) */
215061      for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
215062      if( iTst>=0 ){
215063        int i;
215064        int szMax = 0;
215065        Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
215066        assert( pTst->nMerge==0 );
215067        for(i=0; i<pTst->nSeg; i++){
215068          int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
215069          if( sz>szMax ) szMax = sz;
215070        }
215071        if( szMax>=szSeg ){
215072          /* Condition (a) is true. Promote the newest segment on level 
215073          ** iLvl to level iTst.  */
215074          iPromote = iTst;
215075          szPromote = szMax;
215076        }
215077      }
215078  
215079      /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
215080      ** is a no-op if it is not.  */
215081      if( iPromote<0 ){
215082        iPromote = iLvl;
215083        szPromote = szSeg;
215084      }
215085      fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
215086    }
215087  }
215088  
215089  
215090  /*
215091  ** Advance the iterator passed as the only argument. If the end of the 
215092  ** doclist-index page is reached, return non-zero.
215093  */
215094  static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
215095    Fts5Data *pData = pLvl->pData;
215096  
215097    if( pLvl->iOff==0 ){
215098      assert( pLvl->bEof==0 );
215099      pLvl->iOff = 1;
215100      pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
215101      pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
215102      pLvl->iFirstOff = pLvl->iOff;
215103    }else{
215104      int iOff;
215105      for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
215106        if( pData->p[iOff] ) break; 
215107      }
215108  
215109      if( iOff<pData->nn ){
215110        i64 iVal;
215111        pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
215112        iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
215113        pLvl->iRowid += iVal;
215114        pLvl->iOff = iOff;
215115      }else{
215116        pLvl->bEof = 1;
215117      }
215118    }
215119  
215120    return pLvl->bEof;
215121  }
215122  
215123  /*
215124  ** Advance the iterator passed as the only argument.
215125  */
215126  static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
215127    Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
215128  
215129    assert( iLvl<pIter->nLvl );
215130    if( fts5DlidxLvlNext(pLvl) ){
215131      if( (iLvl+1) < pIter->nLvl ){
215132        fts5DlidxIterNextR(p, pIter, iLvl+1);
215133        if( pLvl[1].bEof==0 ){
215134          fts5DataRelease(pLvl->pData);
215135          memset(pLvl, 0, sizeof(Fts5DlidxLvl));
215136          pLvl->pData = fts5DataRead(p, 
215137              FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
215138          );
215139          if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
215140        }
215141      }
215142    }
215143  
215144    return pIter->aLvl[0].bEof;
215145  }
215146  static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
215147    return fts5DlidxIterNextR(p, pIter, 0);
215148  }
215149  
215150  /*
215151  ** The iterator passed as the first argument has the following fields set
215152  ** as follows. This function sets up the rest of the iterator so that it
215153  ** points to the first rowid in the doclist-index.
215154  **
215155  **   pData:
215156  **     pointer to doclist-index record, 
215157  **
215158  ** When this function is called pIter->iLeafPgno is the page number the
215159  ** doclist is associated with (the one featuring the term).
215160  */
215161  static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
215162    int i;
215163    for(i=0; i<pIter->nLvl; i++){
215164      fts5DlidxLvlNext(&pIter->aLvl[i]);
215165    }
215166    return pIter->aLvl[0].bEof;
215167  }
215168  
215169  
215170  static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
215171    return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
215172  }
215173  
215174  static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
215175    int i;
215176  
215177    /* Advance each level to the last entry on the last page */
215178    for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
215179      Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
215180      while( fts5DlidxLvlNext(pLvl)==0 );
215181      pLvl->bEof = 0;
215182  
215183      if( i>0 ){
215184        Fts5DlidxLvl *pChild = &pLvl[-1];
215185        fts5DataRelease(pChild->pData);
215186        memset(pChild, 0, sizeof(Fts5DlidxLvl));
215187        pChild->pData = fts5DataRead(p, 
215188            FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
215189        );
215190      }
215191    }
215192  }
215193  
215194  /*
215195  ** Move the iterator passed as the only argument to the previous entry.
215196  */
215197  static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
215198    int iOff = pLvl->iOff;
215199  
215200    assert( pLvl->bEof==0 );
215201    if( iOff<=pLvl->iFirstOff ){
215202      pLvl->bEof = 1;
215203    }else{
215204      u8 *a = pLvl->pData->p;
215205      i64 iVal;
215206      int iLimit;
215207      int ii;
215208      int nZero = 0;
215209  
215210      /* Currently iOff points to the first byte of a varint. This block 
215211      ** decrements iOff until it points to the first byte of the previous 
215212      ** varint. Taking care not to read any memory locations that occur
215213      ** before the buffer in memory.  */
215214      iLimit = (iOff>9 ? iOff-9 : 0);
215215      for(iOff--; iOff>iLimit; iOff--){
215216        if( (a[iOff-1] & 0x80)==0 ) break;
215217      }
215218  
215219      fts5GetVarint(&a[iOff], (u64*)&iVal);
215220      pLvl->iRowid -= iVal;
215221      pLvl->iLeafPgno--;
215222  
215223      /* Skip backwards past any 0x00 varints. */
215224      for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
215225        nZero++;
215226      }
215227      if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
215228        /* The byte immediately before the last 0x00 byte has the 0x80 bit
215229        ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
215230        ** bytes before a[ii]. */
215231        int bZero = 0;              /* True if last 0x00 counts */
215232        if( (ii-8)>=pLvl->iFirstOff ){
215233          int j;
215234          for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
215235          bZero = (j>8);
215236        }
215237        if( bZero==0 ) nZero--;
215238      }
215239      pLvl->iLeafPgno -= nZero;
215240      pLvl->iOff = iOff - nZero;
215241    }
215242  
215243    return pLvl->bEof;
215244  }
215245  
215246  static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
215247    Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
215248  
215249    assert( iLvl<pIter->nLvl );
215250    if( fts5DlidxLvlPrev(pLvl) ){
215251      if( (iLvl+1) < pIter->nLvl ){
215252        fts5DlidxIterPrevR(p, pIter, iLvl+1);
215253        if( pLvl[1].bEof==0 ){
215254          fts5DataRelease(pLvl->pData);
215255          memset(pLvl, 0, sizeof(Fts5DlidxLvl));
215256          pLvl->pData = fts5DataRead(p, 
215257              FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
215258          );
215259          if( pLvl->pData ){
215260            while( fts5DlidxLvlNext(pLvl)==0 );
215261            pLvl->bEof = 0;
215262          }
215263        }
215264      }
215265    }
215266  
215267    return pIter->aLvl[0].bEof;
215268  }
215269  static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
215270    return fts5DlidxIterPrevR(p, pIter, 0);
215271  }
215272  
215273  /*
215274  ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
215275  */
215276  static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
215277    if( pIter ){
215278      int i;
215279      for(i=0; i<pIter->nLvl; i++){
215280        fts5DataRelease(pIter->aLvl[i].pData);
215281      }
215282      sqlite3_free(pIter);
215283    }
215284  }
215285  
215286  static Fts5DlidxIter *fts5DlidxIterInit(
215287    Fts5Index *p,                   /* Fts5 Backend to iterate within */
215288    int bRev,                       /* True for ORDER BY ASC */
215289    int iSegid,                     /* Segment id */
215290    int iLeafPg                     /* Leaf page number to load dlidx for */
215291  ){
215292    Fts5DlidxIter *pIter = 0;
215293    int i;
215294    int bDone = 0;
215295  
215296    for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
215297      sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
215298      Fts5DlidxIter *pNew;
215299  
215300      pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
215301      if( pNew==0 ){
215302        p->rc = SQLITE_NOMEM;
215303      }else{
215304        i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
215305        Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
215306        pIter = pNew;
215307        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
215308        pLvl->pData = fts5DataRead(p, iRowid);
215309        if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
215310          bDone = 1;
215311        }
215312        pIter->nLvl = i+1;
215313      }
215314    }
215315  
215316    if( p->rc==SQLITE_OK ){
215317      pIter->iSegid = iSegid;
215318      if( bRev==0 ){
215319        fts5DlidxIterFirst(pIter);
215320      }else{
215321        fts5DlidxIterLast(p, pIter);
215322      }
215323    }
215324  
215325    if( p->rc!=SQLITE_OK ){
215326      fts5DlidxIterFree(pIter);
215327      pIter = 0;
215328    }
215329  
215330    return pIter;
215331  }
215332  
215333  static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
215334    return pIter->aLvl[0].iRowid;
215335  }
215336  static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
215337    return pIter->aLvl[0].iLeafPgno;
215338  }
215339  
215340  /*
215341  ** Load the next leaf page into the segment iterator.
215342  */
215343  static void fts5SegIterNextPage(
215344    Fts5Index *p,                   /* FTS5 backend object */
215345    Fts5SegIter *pIter              /* Iterator to advance to next page */
215346  ){
215347    Fts5Data *pLeaf;
215348    Fts5StructureSegment *pSeg = pIter->pSeg;
215349    fts5DataRelease(pIter->pLeaf);
215350    pIter->iLeafPgno++;
215351    if( pIter->pNextLeaf ){
215352      pIter->pLeaf = pIter->pNextLeaf;
215353      pIter->pNextLeaf = 0;
215354    }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
215355      pIter->pLeaf = fts5LeafRead(p, 
215356          FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
215357      );
215358    }else{
215359      pIter->pLeaf = 0;
215360    }
215361    pLeaf = pIter->pLeaf;
215362  
215363    if( pLeaf ){
215364      pIter->iPgidxOff = pLeaf->szLeaf;
215365      if( fts5LeafIsTermless(pLeaf) ){
215366        pIter->iEndofDoclist = pLeaf->nn+1;
215367      }else{
215368        pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
215369            pIter->iEndofDoclist
215370        );
215371      }
215372    }
215373  }
215374  
215375  /*
215376  ** Argument p points to a buffer containing a varint to be interpreted as a
215377  ** position list size field. Read the varint and return the number of bytes
215378  ** read. Before returning, set *pnSz to the number of bytes in the position
215379  ** list, and *pbDel to true if the delete flag is set, or false otherwise.
215380  */
215381  static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
215382    int nSz;
215383    int n = 0;
215384    fts5FastGetVarint32(p, n, nSz);
215385    assert_nc( nSz>=0 );
215386    *pnSz = nSz/2;
215387    *pbDel = nSz & 0x0001;
215388    return n;
215389  }
215390  
215391  /*
215392  ** Fts5SegIter.iLeafOffset currently points to the first byte of a
215393  ** position-list size field. Read the value of the field and store it
215394  ** in the following variables:
215395  **
215396  **   Fts5SegIter.nPos
215397  **   Fts5SegIter.bDel
215398  **
215399  ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the 
215400  ** position list content (if any).
215401  */
215402  static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
215403    if( p->rc==SQLITE_OK ){
215404      int iOff = pIter->iLeafOffset;  /* Offset to read at */
215405      ASSERT_SZLEAF_OK(pIter->pLeaf);
215406      if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
215407        int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
215408        pIter->bDel = 0;
215409        pIter->nPos = 1;
215410        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
215411          pIter->bDel = 1;
215412          iOff++;
215413          if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
215414            pIter->nPos = 1;
215415            iOff++;
215416          }else{
215417            pIter->nPos = 0;
215418          }
215419        }
215420      }else{
215421        int nSz;
215422        fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
215423        pIter->bDel = (nSz & 0x0001);
215424        pIter->nPos = nSz>>1;
215425        assert_nc( pIter->nPos>=0 );
215426      }
215427      pIter->iLeafOffset = iOff;
215428    }
215429  }
215430  
215431  static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
215432    u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
215433    int iOff = pIter->iLeafOffset;
215434  
215435    ASSERT_SZLEAF_OK(pIter->pLeaf);
215436    if( iOff>=pIter->pLeaf->szLeaf ){
215437      fts5SegIterNextPage(p, pIter);
215438      if( pIter->pLeaf==0 ){
215439        if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
215440        return;
215441      }
215442      iOff = 4;
215443      a = pIter->pLeaf->p;
215444    }
215445    iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
215446    pIter->iLeafOffset = iOff;
215447  }
215448  
215449  /*
215450  ** Fts5SegIter.iLeafOffset currently points to the first byte of the 
215451  ** "nSuffix" field of a term. Function parameter nKeep contains the value
215452  ** of the "nPrefix" field (if there was one - it is passed 0 if this is
215453  ** the first term in the segment).
215454  **
215455  ** This function populates:
215456  **
215457  **   Fts5SegIter.term
215458  **   Fts5SegIter.rowid
215459  **
215460  ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
215461  ** the first position list. The position list belonging to document 
215462  ** (Fts5SegIter.iRowid).
215463  */
215464  static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
215465    u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
215466    int iOff = pIter->iLeafOffset;  /* Offset to read at */
215467    int nNew;                       /* Bytes of new data */
215468  
215469    iOff += fts5GetVarint32(&a[iOff], nNew);
215470    if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
215471      p->rc = FTS5_CORRUPT;
215472      return;
215473    }
215474    pIter->term.n = nKeep;
215475    fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
215476    assert( pIter->term.n<=pIter->term.nSpace );
215477    iOff += nNew;
215478    pIter->iTermLeafOffset = iOff;
215479    pIter->iTermLeafPgno = pIter->iLeafPgno;
215480    pIter->iLeafOffset = iOff;
215481  
215482    if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
215483      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
215484    }else{
215485      int nExtra;
215486      pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
215487      pIter->iEndofDoclist += nExtra;
215488    }
215489  
215490    fts5SegIterLoadRowid(p, pIter);
215491  }
215492  
215493  static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
215494  static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
215495  static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
215496  
215497  static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
215498    if( pIter->flags & FTS5_SEGITER_REVERSE ){
215499      pIter->xNext = fts5SegIterNext_Reverse;
215500    }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
215501      pIter->xNext = fts5SegIterNext_None;
215502    }else{
215503      pIter->xNext = fts5SegIterNext;
215504    }
215505  }
215506  
215507  /*
215508  ** Initialize the iterator object pIter to iterate through the entries in
215509  ** segment pSeg. The iterator is left pointing to the first entry when 
215510  ** this function returns.
215511  **
215512  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
215513  ** an error has already occurred when this function is called, it is a no-op.
215514  */
215515  static void fts5SegIterInit(
215516    Fts5Index *p,                   /* FTS index object */
215517    Fts5StructureSegment *pSeg,     /* Description of segment */
215518    Fts5SegIter *pIter              /* Object to populate */
215519  ){
215520    if( pSeg->pgnoFirst==0 ){
215521      /* This happens if the segment is being used as an input to an incremental
215522      ** merge and all data has already been "trimmed". See function
215523      ** fts5TrimSegments() for details. In this case leave the iterator empty.
215524      ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
215525      ** at EOF already. */
215526      assert( pIter->pLeaf==0 );
215527      return;
215528    }
215529  
215530    if( p->rc==SQLITE_OK ){
215531      memset(pIter, 0, sizeof(*pIter));
215532      fts5SegIterSetNext(p, pIter);
215533      pIter->pSeg = pSeg;
215534      pIter->iLeafPgno = pSeg->pgnoFirst-1;
215535      fts5SegIterNextPage(p, pIter);
215536    }
215537  
215538    if( p->rc==SQLITE_OK ){
215539      pIter->iLeafOffset = 4;
215540      assert_nc( pIter->pLeaf->nn>4 );
215541      assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
215542      pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
215543      fts5SegIterLoadTerm(p, pIter, 0);
215544      fts5SegIterLoadNPos(p, pIter);
215545    }
215546  }
215547  
215548  /*
215549  ** This function is only ever called on iterators created by calls to
215550  ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
215551  **
215552  ** The iterator is in an unusual state when this function is called: the
215553  ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
215554  ** the position-list size field for the first relevant rowid on the page.
215555  ** Fts5SegIter.rowid is set, but nPos and bDel are not.
215556  **
215557  ** This function advances the iterator so that it points to the last 
215558  ** relevant rowid on the page and, if necessary, initializes the 
215559  ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
215560  ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
215561  ** byte of the position list content associated with said rowid.
215562  */
215563  static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
215564    int eDetail = p->pConfig->eDetail;
215565    int n = pIter->pLeaf->szLeaf;
215566    int i = pIter->iLeafOffset;
215567    u8 *a = pIter->pLeaf->p;
215568    int iRowidOffset = 0;
215569  
215570    if( n>pIter->iEndofDoclist ){
215571      n = pIter->iEndofDoclist;
215572    }
215573  
215574    ASSERT_SZLEAF_OK(pIter->pLeaf);
215575    while( 1 ){
215576      i64 iDelta = 0;
215577  
215578      if( eDetail==FTS5_DETAIL_NONE ){
215579        /* todo */
215580        if( i<n && a[i]==0 ){
215581          i++;
215582          if( i<n && a[i]==0 ) i++;
215583        }
215584      }else{
215585        int nPos;
215586        int bDummy;
215587        i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
215588        i += nPos;
215589      }
215590      if( i>=n ) break;
215591      i += fts5GetVarint(&a[i], (u64*)&iDelta);
215592      pIter->iRowid += iDelta;
215593  
215594      /* If necessary, grow the pIter->aRowidOffset[] array. */
215595      if( iRowidOffset>=pIter->nRowidOffset ){
215596        int nNew = pIter->nRowidOffset + 8;
215597        int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
215598        if( aNew==0 ){
215599          p->rc = SQLITE_NOMEM;
215600          break;
215601        }
215602        pIter->aRowidOffset = aNew;
215603        pIter->nRowidOffset = nNew;
215604      }
215605  
215606      pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
215607      pIter->iLeafOffset = i;
215608    }
215609    pIter->iRowidOffset = iRowidOffset;
215610    fts5SegIterLoadNPos(p, pIter);
215611  }
215612  
215613  /*
215614  **
215615  */
215616  static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
215617    assert( pIter->flags & FTS5_SEGITER_REVERSE );
215618    assert( pIter->flags & FTS5_SEGITER_ONETERM );
215619  
215620    fts5DataRelease(pIter->pLeaf);
215621    pIter->pLeaf = 0;
215622    while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
215623      Fts5Data *pNew;
215624      pIter->iLeafPgno--;
215625      pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
215626            pIter->pSeg->iSegid, pIter->iLeafPgno
215627      ));
215628      if( pNew ){
215629        /* iTermLeafOffset may be equal to szLeaf if the term is the last
215630        ** thing on the page - i.e. the first rowid is on the following page.
215631        ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
215632        if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
215633          assert( pIter->pLeaf==0 );
215634          if( pIter->iTermLeafOffset<pNew->szLeaf ){
215635            pIter->pLeaf = pNew;
215636            pIter->iLeafOffset = pIter->iTermLeafOffset;
215637          }
215638        }else{
215639          int iRowidOff;
215640          iRowidOff = fts5LeafFirstRowidOff(pNew);
215641          if( iRowidOff ){
215642            pIter->pLeaf = pNew;
215643            pIter->iLeafOffset = iRowidOff;
215644          }
215645        }
215646  
215647        if( pIter->pLeaf ){
215648          u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
215649          pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
215650          break;
215651        }else{
215652          fts5DataRelease(pNew);
215653        }
215654      }
215655    }
215656  
215657    if( pIter->pLeaf ){
215658      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
215659      fts5SegIterReverseInitPage(p, pIter);
215660    }
215661  }
215662  
215663  /*
215664  ** Return true if the iterator passed as the second argument currently
215665  ** points to a delete marker. A delete marker is an entry with a 0 byte
215666  ** position-list.
215667  */
215668  static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
215669    Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
215670    return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
215671  }
215672  
215673  /*
215674  ** Advance iterator pIter to the next entry.
215675  **
215676  ** This version of fts5SegIterNext() is only used by reverse iterators.
215677  */
215678  static void fts5SegIterNext_Reverse(
215679    Fts5Index *p,                   /* FTS5 backend object */
215680    Fts5SegIter *pIter,             /* Iterator to advance */
215681    int *pbUnused                   /* Unused */
215682  ){
215683    assert( pIter->flags & FTS5_SEGITER_REVERSE );
215684    assert( pIter->pNextLeaf==0 );
215685    UNUSED_PARAM(pbUnused);
215686  
215687    if( pIter->iRowidOffset>0 ){
215688      u8 *a = pIter->pLeaf->p;
215689      int iOff;
215690      i64 iDelta;
215691  
215692      pIter->iRowidOffset--;
215693      pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
215694      fts5SegIterLoadNPos(p, pIter);
215695      iOff = pIter->iLeafOffset;
215696      if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
215697        iOff += pIter->nPos;
215698      }
215699      fts5GetVarint(&a[iOff], (u64*)&iDelta);
215700      pIter->iRowid -= iDelta;
215701    }else{
215702      fts5SegIterReverseNewPage(p, pIter);
215703    }
215704  }
215705  
215706  /*
215707  ** Advance iterator pIter to the next entry.
215708  **
215709  ** This version of fts5SegIterNext() is only used if detail=none and the
215710  ** iterator is not a reverse direction iterator.
215711  */
215712  static void fts5SegIterNext_None(
215713    Fts5Index *p,                   /* FTS5 backend object */
215714    Fts5SegIter *pIter,             /* Iterator to advance */
215715    int *pbNewTerm                  /* OUT: Set for new term */
215716  ){
215717    int iOff;
215718  
215719    assert( p->rc==SQLITE_OK );
215720    assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
215721    assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
215722  
215723    ASSERT_SZLEAF_OK(pIter->pLeaf);
215724    iOff = pIter->iLeafOffset;
215725  
215726    /* Next entry is on the next page */
215727    if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
215728      fts5SegIterNextPage(p, pIter);
215729      if( p->rc || pIter->pLeaf==0 ) return;
215730      pIter->iRowid = 0;
215731      iOff = 4;
215732    }
215733  
215734    if( iOff<pIter->iEndofDoclist ){
215735      /* Next entry is on the current page */
215736      i64 iDelta;
215737      iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
215738      pIter->iLeafOffset = iOff;
215739      pIter->iRowid += iDelta;
215740    }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
215741      if( pIter->pSeg ){
215742        int nKeep = 0;
215743        if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
215744          iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
215745        }
215746        pIter->iLeafOffset = iOff;
215747        fts5SegIterLoadTerm(p, pIter, nKeep);
215748      }else{
215749        const u8 *pList = 0;
215750        const char *zTerm = 0;
215751        int nList;
215752        sqlite3Fts5HashScanNext(p->pHash);
215753        sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
215754        if( pList==0 ) goto next_none_eof;
215755        pIter->pLeaf->p = (u8*)pList;
215756        pIter->pLeaf->nn = nList;
215757        pIter->pLeaf->szLeaf = nList;
215758        pIter->iEndofDoclist = nList;
215759        sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
215760        pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
215761      }
215762  
215763      if( pbNewTerm ) *pbNewTerm = 1;
215764    }else{
215765      goto next_none_eof;
215766    }
215767  
215768    fts5SegIterLoadNPos(p, pIter);
215769  
215770    return;
215771   next_none_eof:
215772    fts5DataRelease(pIter->pLeaf);
215773    pIter->pLeaf = 0;
215774  }
215775  
215776  
215777  /*
215778  ** Advance iterator pIter to the next entry. 
215779  **
215780  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It 
215781  ** is not considered an error if the iterator reaches EOF. If an error has 
215782  ** already occurred when this function is called, it is a no-op.
215783  */
215784  static void fts5SegIterNext(
215785    Fts5Index *p,                   /* FTS5 backend object */
215786    Fts5SegIter *pIter,             /* Iterator to advance */
215787    int *pbNewTerm                  /* OUT: Set for new term */
215788  ){
215789    Fts5Data *pLeaf = pIter->pLeaf;
215790    int iOff;
215791    int bNewTerm = 0;
215792    int nKeep = 0;
215793    u8 *a;
215794    int n;
215795  
215796    assert( pbNewTerm==0 || *pbNewTerm==0 );
215797    assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
215798  
215799    /* Search for the end of the position list within the current page. */
215800    a = pLeaf->p;
215801    n = pLeaf->szLeaf;
215802  
215803    ASSERT_SZLEAF_OK(pLeaf);
215804    iOff = pIter->iLeafOffset + pIter->nPos;
215805  
215806    if( iOff<n ){
215807      /* The next entry is on the current page. */
215808      assert_nc( iOff<=pIter->iEndofDoclist );
215809      if( iOff>=pIter->iEndofDoclist ){
215810        bNewTerm = 1;
215811        if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
215812          iOff += fts5GetVarint32(&a[iOff], nKeep);
215813        }
215814      }else{
215815        u64 iDelta;
215816        iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
215817        pIter->iRowid += iDelta;
215818        assert_nc( iDelta>0 );
215819      }
215820      pIter->iLeafOffset = iOff;
215821  
215822    }else if( pIter->pSeg==0 ){
215823      const u8 *pList = 0;
215824      const char *zTerm = 0;
215825      int nList = 0;
215826      assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
215827      if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
215828        sqlite3Fts5HashScanNext(p->pHash);
215829        sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
215830      }
215831      if( pList==0 ){
215832        fts5DataRelease(pIter->pLeaf);
215833        pIter->pLeaf = 0;
215834      }else{
215835        pIter->pLeaf->p = (u8*)pList;
215836        pIter->pLeaf->nn = nList;
215837        pIter->pLeaf->szLeaf = nList;
215838        pIter->iEndofDoclist = nList+1;
215839        sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
215840            (u8*)zTerm);
215841        pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
215842        *pbNewTerm = 1;
215843      }
215844    }else{
215845      iOff = 0;
215846      /* Next entry is not on the current page */
215847      while( iOff==0 ){
215848        fts5SegIterNextPage(p, pIter);
215849        pLeaf = pIter->pLeaf;
215850        if( pLeaf==0 ) break;
215851        ASSERT_SZLEAF_OK(pLeaf);
215852        if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
215853          iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
215854          pIter->iLeafOffset = iOff;
215855  
215856          if( pLeaf->nn>pLeaf->szLeaf ){
215857            pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
215858                &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
215859            );
215860          }
215861        }
215862        else if( pLeaf->nn>pLeaf->szLeaf ){
215863          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
215864              &pLeaf->p[pLeaf->szLeaf], iOff
215865          );
215866          pIter->iLeafOffset = iOff;
215867          pIter->iEndofDoclist = iOff;
215868          bNewTerm = 1;
215869        }
215870        assert_nc( iOff<pLeaf->szLeaf );
215871        if( iOff>pLeaf->szLeaf ){
215872          p->rc = FTS5_CORRUPT;
215873          return;
215874        }
215875      }
215876    }
215877  
215878    /* Check if the iterator is now at EOF. If so, return early. */
215879    if( pIter->pLeaf ){
215880      if( bNewTerm ){
215881        if( pIter->flags & FTS5_SEGITER_ONETERM ){
215882          fts5DataRelease(pIter->pLeaf);
215883          pIter->pLeaf = 0;
215884        }else{
215885          fts5SegIterLoadTerm(p, pIter, nKeep);
215886          fts5SegIterLoadNPos(p, pIter);
215887          if( pbNewTerm ) *pbNewTerm = 1;
215888        }
215889      }else{
215890        /* The following could be done by calling fts5SegIterLoadNPos(). But
215891        ** this block is particularly performance critical, so equivalent
215892        ** code is inlined. 
215893        **
215894        ** Later: Switched back to fts5SegIterLoadNPos() because it supports
215895        ** detail=none mode. Not ideal.
215896        */
215897        int nSz;
215898        assert( p->rc==SQLITE_OK );
215899        assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
215900        fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
215901        pIter->bDel = (nSz & 0x0001);
215902        pIter->nPos = nSz>>1;
215903        assert_nc( pIter->nPos>=0 );
215904      }
215905    }
215906  }
215907  
215908  #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
215909  
215910  #define fts5IndexSkipVarint(a, iOff) {            \
215911    int iEnd = iOff+9;                              \
215912    while( (a[iOff++] & 0x80) && iOff<iEnd );       \
215913  }
215914  
215915  /*
215916  ** Iterator pIter currently points to the first rowid in a doclist. This
215917  ** function sets the iterator up so that iterates in reverse order through
215918  ** the doclist.
215919  */
215920  static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
215921    Fts5DlidxIter *pDlidx = pIter->pDlidx;
215922    Fts5Data *pLast = 0;
215923    int pgnoLast = 0;
215924  
215925    if( pDlidx ){
215926      int iSegid = pIter->pSeg->iSegid;
215927      pgnoLast = fts5DlidxIterPgno(pDlidx);
215928      pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
215929    }else{
215930      Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
215931  
215932      /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
215933      ** position-list content for the current rowid. Back it up so that it
215934      ** points to the start of the position-list size field. */
215935      int iPoslist;
215936      if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
215937        iPoslist = pIter->iTermLeafOffset;
215938      }else{
215939        iPoslist = 4;
215940      }
215941      fts5IndexSkipVarint(pLeaf->p, iPoslist);
215942      pIter->iLeafOffset = iPoslist;
215943  
215944      /* If this condition is true then the largest rowid for the current
215945      ** term may not be stored on the current page. So search forward to
215946      ** see where said rowid really is.  */
215947      if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
215948        int pgno;
215949        Fts5StructureSegment *pSeg = pIter->pSeg;
215950  
215951        /* The last rowid in the doclist may not be on the current page. Search
215952        ** forward to find the page containing the last rowid.  */
215953        for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
215954          i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
215955          Fts5Data *pNew = fts5DataRead(p, iAbs);
215956          if( pNew ){
215957            int iRowid, bTermless;
215958            iRowid = fts5LeafFirstRowidOff(pNew);
215959            bTermless = fts5LeafIsTermless(pNew);
215960            if( iRowid ){
215961              SWAPVAL(Fts5Data*, pNew, pLast);
215962              pgnoLast = pgno;
215963            }
215964            fts5DataRelease(pNew);
215965            if( bTermless==0 ) break;
215966          }
215967        }
215968      }
215969    }
215970  
215971    /* If pLast is NULL at this point, then the last rowid for this doclist
215972    ** lies on the page currently indicated by the iterator. In this case 
215973    ** pIter->iLeafOffset is already set to point to the position-list size
215974    ** field associated with the first relevant rowid on the page.
215975    **
215976    ** Or, if pLast is non-NULL, then it is the page that contains the last
215977    ** rowid. In this case configure the iterator so that it points to the
215978    ** first rowid on this page.
215979    */
215980    if( pLast ){
215981      int iOff;
215982      fts5DataRelease(pIter->pLeaf);
215983      pIter->pLeaf = pLast;
215984      pIter->iLeafPgno = pgnoLast;
215985      iOff = fts5LeafFirstRowidOff(pLast);
215986      iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
215987      pIter->iLeafOffset = iOff;
215988  
215989      if( fts5LeafIsTermless(pLast) ){
215990        pIter->iEndofDoclist = pLast->nn+1;
215991      }else{
215992        pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
215993      }
215994  
215995    }
215996  
215997    fts5SegIterReverseInitPage(p, pIter);
215998  }
215999  
216000  /*
216001  ** Iterator pIter currently points to the first rowid of a doclist.
216002  ** There is a doclist-index associated with the final term on the current 
216003  ** page. If the current term is the last term on the page, load the 
216004  ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
216005  */
216006  static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
216007    int iSeg = pIter->pSeg->iSegid;
216008    int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
216009    Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
216010  
216011    assert( pIter->flags & FTS5_SEGITER_ONETERM );
216012    assert( pIter->pDlidx==0 );
216013  
216014    /* Check if the current doclist ends on this page. If it does, return
216015    ** early without loading the doclist-index (as it belongs to a different
216016    ** term. */
216017    if( pIter->iTermLeafPgno==pIter->iLeafPgno 
216018     && pIter->iEndofDoclist<pLeaf->szLeaf 
216019    ){
216020      return;
216021    }
216022  
216023    pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
216024  }
216025  
216026  /*
216027  ** The iterator object passed as the second argument currently contains
216028  ** no valid values except for the Fts5SegIter.pLeaf member variable. This
216029  ** function searches the leaf page for a term matching (pTerm/nTerm).
216030  **
216031  ** If the specified term is found on the page, then the iterator is left
216032  ** pointing to it. If argument bGe is zero and the term is not found,
216033  ** the iterator is left pointing at EOF.
216034  **
216035  ** If bGe is non-zero and the specified term is not found, then the
216036  ** iterator is left pointing to the smallest term in the segment that
216037  ** is larger than the specified term, even if this term is not on the
216038  ** current page.
216039  */
216040  static void fts5LeafSeek(
216041    Fts5Index *p,                   /* Leave any error code here */
216042    int bGe,                        /* True for a >= search */
216043    Fts5SegIter *pIter,             /* Iterator to seek */
216044    const u8 *pTerm, int nTerm      /* Term to search for */
216045  ){
216046    int iOff;
216047    const u8 *a = pIter->pLeaf->p;
216048    int szLeaf = pIter->pLeaf->szLeaf;
216049    int n = pIter->pLeaf->nn;
216050  
216051    u32 nMatch = 0;
216052    u32 nKeep = 0;
216053    u32 nNew = 0;
216054    u32 iTermOff;
216055    int iPgidx;                     /* Current offset in pgidx */
216056    int bEndOfPage = 0;
216057  
216058    assert( p->rc==SQLITE_OK );
216059  
216060    iPgidx = szLeaf;
216061    iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
216062    iOff = iTermOff;
216063    if( iOff>n ){
216064      p->rc = FTS5_CORRUPT;
216065      return;
216066    }
216067  
216068    while( 1 ){
216069  
216070      /* Figure out how many new bytes are in this term */
216071      fts5FastGetVarint32(a, iOff, nNew);
216072      if( nKeep<nMatch ){
216073        goto search_failed;
216074      }
216075  
216076      assert( nKeep>=nMatch );
216077      if( nKeep==nMatch ){
216078        u32 nCmp;
216079        u32 i;
216080        nCmp = (u32)MIN(nNew, nTerm-nMatch);
216081        for(i=0; i<nCmp; i++){
216082          if( a[iOff+i]!=pTerm[nMatch+i] ) break;
216083        }
216084        nMatch += i;
216085  
216086        if( (u32)nTerm==nMatch ){
216087          if( i==nNew ){
216088            goto search_success;
216089          }else{
216090            goto search_failed;
216091          }
216092        }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
216093          goto search_failed;
216094        }
216095      }
216096  
216097      if( iPgidx>=n ){
216098        bEndOfPage = 1;
216099        break;
216100      }
216101  
216102      iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
216103      iTermOff += nKeep;
216104      iOff = iTermOff;
216105  
216106      if( iOff>=n ){
216107        p->rc = FTS5_CORRUPT;
216108        return;
216109      }
216110  
216111      /* Read the nKeep field of the next term. */
216112      fts5FastGetVarint32(a, iOff, nKeep);
216113    }
216114  
216115   search_failed:
216116    if( bGe==0 ){
216117      fts5DataRelease(pIter->pLeaf);
216118      pIter->pLeaf = 0;
216119      return;
216120    }else if( bEndOfPage ){
216121      do {
216122        fts5SegIterNextPage(p, pIter);
216123        if( pIter->pLeaf==0 ) return;
216124        a = pIter->pLeaf->p;
216125        if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
216126          iPgidx = pIter->pLeaf->szLeaf;
216127          iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
216128          if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
216129            p->rc = FTS5_CORRUPT;
216130            return;
216131          }else{
216132            nKeep = 0;
216133            iTermOff = iOff;
216134            n = pIter->pLeaf->nn;
216135            iOff += fts5GetVarint32(&a[iOff], nNew);
216136            break;
216137          }
216138        }
216139      }while( 1 );
216140    }
216141  
216142   search_success:
216143    pIter->iLeafOffset = iOff + nNew;
216144    if( pIter->iLeafOffset>n || nNew<1 ){
216145      p->rc = FTS5_CORRUPT;
216146      return;
216147    }
216148    pIter->iTermLeafOffset = pIter->iLeafOffset;
216149    pIter->iTermLeafPgno = pIter->iLeafPgno;
216150  
216151    fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
216152    fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
216153  
216154    if( iPgidx>=n ){
216155      pIter->iEndofDoclist = pIter->pLeaf->nn+1;
216156    }else{
216157      int nExtra;
216158      iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
216159      pIter->iEndofDoclist = iTermOff + nExtra;
216160    }
216161    pIter->iPgidxOff = iPgidx;
216162  
216163    fts5SegIterLoadRowid(p, pIter);
216164    fts5SegIterLoadNPos(p, pIter);
216165  }
216166  
216167  static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
216168    if( p->pIdxSelect==0 ){
216169      Fts5Config *pConfig = p->pConfig;
216170      fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
216171            "SELECT pgno FROM '%q'.'%q_idx' WHERE "
216172            "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
216173            pConfig->zDb, pConfig->zName
216174      ));
216175    }
216176    return p->pIdxSelect;
216177  }
216178  
216179  /*
216180  ** Initialize the object pIter to point to term pTerm/nTerm within segment
216181  ** pSeg. If there is no such term in the index, the iterator is set to EOF.
216182  **
216183  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
216184  ** an error has already occurred when this function is called, it is a no-op.
216185  */
216186  static void fts5SegIterSeekInit(
216187    Fts5Index *p,                   /* FTS5 backend */
216188    const u8 *pTerm, int nTerm,     /* Term to seek to */
216189    int flags,                      /* Mask of FTS5INDEX_XXX flags */
216190    Fts5StructureSegment *pSeg,     /* Description of segment */
216191    Fts5SegIter *pIter              /* Object to populate */
216192  ){
216193    int iPg = 1;
216194    int bGe = (flags & FTS5INDEX_QUERY_SCAN);
216195    int bDlidx = 0;                 /* True if there is a doclist-index */
216196    sqlite3_stmt *pIdxSelect = 0;
216197  
216198    assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
216199    assert( pTerm && nTerm );
216200    memset(pIter, 0, sizeof(*pIter));
216201    pIter->pSeg = pSeg;
216202  
216203    /* This block sets stack variable iPg to the leaf page number that may
216204    ** contain term (pTerm/nTerm), if it is present in the segment. */
216205    pIdxSelect = fts5IdxSelectStmt(p);
216206    if( p->rc ) return;
216207    sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
216208    sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
216209    if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
216210      i64 val = sqlite3_column_int(pIdxSelect, 0);
216211      iPg = (int)(val>>1);
216212      bDlidx = (val & 0x0001);
216213    }
216214    p->rc = sqlite3_reset(pIdxSelect);
216215    sqlite3_bind_null(pIdxSelect, 2);
216216  
216217    if( iPg<pSeg->pgnoFirst ){
216218      iPg = pSeg->pgnoFirst;
216219      bDlidx = 0;
216220    }
216221  
216222    pIter->iLeafPgno = iPg - 1;
216223    fts5SegIterNextPage(p, pIter);
216224  
216225    if( pIter->pLeaf ){
216226      fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
216227    }
216228  
216229    if( p->rc==SQLITE_OK && bGe==0 ){
216230      pIter->flags |= FTS5_SEGITER_ONETERM;
216231      if( pIter->pLeaf ){
216232        if( flags & FTS5INDEX_QUERY_DESC ){
216233          pIter->flags |= FTS5_SEGITER_REVERSE;
216234        }
216235        if( bDlidx ){
216236          fts5SegIterLoadDlidx(p, pIter);
216237        }
216238        if( flags & FTS5INDEX_QUERY_DESC ){
216239          fts5SegIterReverse(p, pIter);
216240        }
216241      }
216242    }
216243  
216244    fts5SegIterSetNext(p, pIter);
216245  
216246    /* Either:
216247    **
216248    **   1) an error has occurred, or
216249    **   2) the iterator points to EOF, or
216250    **   3) the iterator points to an entry with term (pTerm/nTerm), or
216251    **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
216252    **      to an entry with a term greater than or equal to (pTerm/nTerm).
216253    */
216254    assert_nc( p->rc!=SQLITE_OK                                       /* 1 */
216255     || pIter->pLeaf==0                                               /* 2 */
216256     || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
216257     || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
216258    );
216259  }
216260  
216261  /*
216262  ** Initialize the object pIter to point to term pTerm/nTerm within the
216263  ** in-memory hash table. If there is no such term in the hash-table, the 
216264  ** iterator is set to EOF.
216265  **
216266  ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
216267  ** an error has already occurred when this function is called, it is a no-op.
216268  */
216269  static void fts5SegIterHashInit(
216270    Fts5Index *p,                   /* FTS5 backend */
216271    const u8 *pTerm, int nTerm,     /* Term to seek to */
216272    int flags,                      /* Mask of FTS5INDEX_XXX flags */
216273    Fts5SegIter *pIter              /* Object to populate */
216274  ){
216275    const u8 *pList = 0;
216276    int nList = 0;
216277    const u8 *z = 0;
216278    int n = 0;
216279  
216280    assert( p->pHash );
216281    assert( p->rc==SQLITE_OK );
216282  
216283    if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
216284      p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
216285      sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
216286      n = (z ? (int)strlen((const char*)z) : 0);
216287    }else{
216288      pIter->flags |= FTS5_SEGITER_ONETERM;
216289      sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
216290      z = pTerm;
216291      n = nTerm;
216292    }
216293  
216294    if( pList ){
216295      Fts5Data *pLeaf;
216296      sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
216297      pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
216298      if( pLeaf==0 ) return;
216299      pLeaf->p = (u8*)pList;
216300      pLeaf->nn = pLeaf->szLeaf = nList;
216301      pIter->pLeaf = pLeaf;
216302      pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
216303      pIter->iEndofDoclist = pLeaf->nn;
216304  
216305      if( flags & FTS5INDEX_QUERY_DESC ){
216306        pIter->flags |= FTS5_SEGITER_REVERSE;
216307        fts5SegIterReverseInitPage(p, pIter);
216308      }else{
216309        fts5SegIterLoadNPos(p, pIter);
216310      }
216311    }
216312  
216313    fts5SegIterSetNext(p, pIter);
216314  }
216315  
216316  /*
216317  ** Zero the iterator passed as the only argument.
216318  */
216319  static void fts5SegIterClear(Fts5SegIter *pIter){
216320    fts5BufferFree(&pIter->term);
216321    fts5DataRelease(pIter->pLeaf);
216322    fts5DataRelease(pIter->pNextLeaf);
216323    fts5DlidxIterFree(pIter->pDlidx);
216324    sqlite3_free(pIter->aRowidOffset);
216325    memset(pIter, 0, sizeof(Fts5SegIter));
216326  }
216327  
216328  #ifdef SQLITE_DEBUG
216329  
216330  /*
216331  ** This function is used as part of the big assert() procedure implemented by
216332  ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
216333  ** in *pRes is the correct result of comparing the current positions of the
216334  ** two iterators.
216335  */
216336  static void fts5AssertComparisonResult(
216337    Fts5Iter *pIter, 
216338    Fts5SegIter *p1,
216339    Fts5SegIter *p2,
216340    Fts5CResult *pRes
216341  ){
216342    int i1 = p1 - pIter->aSeg;
216343    int i2 = p2 - pIter->aSeg;
216344  
216345    if( p1->pLeaf || p2->pLeaf ){
216346      if( p1->pLeaf==0 ){
216347        assert( pRes->iFirst==i2 );
216348      }else if( p2->pLeaf==0 ){
216349        assert( pRes->iFirst==i1 );
216350      }else{
216351        int nMin = MIN(p1->term.n, p2->term.n);
216352        int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
216353        if( res==0 ) res = p1->term.n - p2->term.n;
216354  
216355        if( res==0 ){
216356          assert( pRes->bTermEq==1 );
216357          assert( p1->iRowid!=p2->iRowid );
216358          res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
216359        }else{
216360          assert( pRes->bTermEq==0 );
216361        }
216362  
216363        if( res<0 ){
216364          assert( pRes->iFirst==i1 );
216365        }else{
216366          assert( pRes->iFirst==i2 );
216367        }
216368      }
216369    }
216370  }
216371  
216372  /*
216373  ** This function is a no-op unless SQLITE_DEBUG is defined when this module
216374  ** is compiled. In that case, this function is essentially an assert() 
216375  ** statement used to verify that the contents of the pIter->aFirst[] array
216376  ** are correct.
216377  */
216378  static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
216379    if( p->rc==SQLITE_OK ){
216380      Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
216381      int i;
216382  
216383      assert( (pFirst->pLeaf==0)==pIter->base.bEof );
216384  
216385      /* Check that pIter->iSwitchRowid is set correctly. */
216386      for(i=0; i<pIter->nSeg; i++){
216387        Fts5SegIter *p1 = &pIter->aSeg[i];
216388        assert( p1==pFirst 
216389             || p1->pLeaf==0 
216390             || fts5BufferCompare(&pFirst->term, &p1->term) 
216391             || p1->iRowid==pIter->iSwitchRowid
216392             || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
216393        );
216394      }
216395  
216396      for(i=0; i<pIter->nSeg; i+=2){
216397        Fts5SegIter *p1 = &pIter->aSeg[i];
216398        Fts5SegIter *p2 = &pIter->aSeg[i+1];
216399        Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
216400        fts5AssertComparisonResult(pIter, p1, p2, pRes);
216401      }
216402  
216403      for(i=1; i<(pIter->nSeg / 2); i+=2){
216404        Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
216405        Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
216406        Fts5CResult *pRes = &pIter->aFirst[i];
216407        fts5AssertComparisonResult(pIter, p1, p2, pRes);
216408      }
216409    }
216410  }
216411  #else
216412  # define fts5AssertMultiIterSetup(x,y)
216413  #endif
216414  
216415  /*
216416  ** Do the comparison necessary to populate pIter->aFirst[iOut].
216417  **
216418  ** If the returned value is non-zero, then it is the index of an entry
216419  ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
216420  ** to a key that is a duplicate of another, higher priority, 
216421  ** segment-iterator in the pSeg->aSeg[] array.
216422  */
216423  static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
216424    int i1;                         /* Index of left-hand Fts5SegIter */
216425    int i2;                         /* Index of right-hand Fts5SegIter */
216426    int iRes;
216427    Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
216428    Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
216429    Fts5CResult *pRes = &pIter->aFirst[iOut];
216430  
216431    assert( iOut<pIter->nSeg && iOut>0 );
216432    assert( pIter->bRev==0 || pIter->bRev==1 );
216433  
216434    if( iOut>=(pIter->nSeg/2) ){
216435      i1 = (iOut - pIter->nSeg/2) * 2;
216436      i2 = i1 + 1;
216437    }else{
216438      i1 = pIter->aFirst[iOut*2].iFirst;
216439      i2 = pIter->aFirst[iOut*2+1].iFirst;
216440    }
216441    p1 = &pIter->aSeg[i1];
216442    p2 = &pIter->aSeg[i2];
216443  
216444    pRes->bTermEq = 0;
216445    if( p1->pLeaf==0 ){           /* If p1 is at EOF */
216446      iRes = i2;
216447    }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
216448      iRes = i1;
216449    }else{
216450      int res = fts5BufferCompare(&p1->term, &p2->term);
216451      if( res==0 ){
216452        assert( i2>i1 );
216453        assert( i2!=0 );
216454        pRes->bTermEq = 1;
216455        if( p1->iRowid==p2->iRowid ){
216456          p1->bDel = p2->bDel;
216457          return i2;
216458        }
216459        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
216460      }
216461      assert( res!=0 );
216462      if( res<0 ){
216463        iRes = i1;
216464      }else{
216465        iRes = i2;
216466      }
216467    }
216468  
216469    pRes->iFirst = (u16)iRes;
216470    return 0;
216471  }
216472  
216473  /*
216474  ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
216475  ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
216476  */
216477  static void fts5SegIterGotoPage(
216478    Fts5Index *p,                   /* FTS5 backend object */
216479    Fts5SegIter *pIter,             /* Iterator to advance */
216480    int iLeafPgno
216481  ){
216482    assert( iLeafPgno>pIter->iLeafPgno );
216483  
216484    if( iLeafPgno>pIter->pSeg->pgnoLast ){
216485      p->rc = FTS5_CORRUPT;
216486    }else{
216487      fts5DataRelease(pIter->pNextLeaf);
216488      pIter->pNextLeaf = 0;
216489      pIter->iLeafPgno = iLeafPgno-1;
216490      fts5SegIterNextPage(p, pIter);
216491      assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
216492  
216493      if( p->rc==SQLITE_OK ){
216494        int iOff;
216495        u8 *a = pIter->pLeaf->p;
216496        int n = pIter->pLeaf->szLeaf;
216497  
216498        iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
216499        if( iOff<4 || iOff>=n ){
216500          p->rc = FTS5_CORRUPT;
216501        }else{
216502          iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
216503          pIter->iLeafOffset = iOff;
216504          fts5SegIterLoadNPos(p, pIter);
216505        }
216506      }
216507    }
216508  }
216509  
216510  /*
216511  ** Advance the iterator passed as the second argument until it is at or 
216512  ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
216513  ** always advanced at least once.
216514  */
216515  static void fts5SegIterNextFrom(
216516    Fts5Index *p,                   /* FTS5 backend object */
216517    Fts5SegIter *pIter,             /* Iterator to advance */
216518    i64 iMatch                      /* Advance iterator at least this far */
216519  ){
216520    int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
216521    Fts5DlidxIter *pDlidx = pIter->pDlidx;
216522    int iLeafPgno = pIter->iLeafPgno;
216523    int bMove = 1;
216524  
216525    assert( pIter->flags & FTS5_SEGITER_ONETERM );
216526    assert( pIter->pDlidx );
216527    assert( pIter->pLeaf );
216528  
216529    if( bRev==0 ){
216530      while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
216531        iLeafPgno = fts5DlidxIterPgno(pDlidx);
216532        fts5DlidxIterNext(p, pDlidx);
216533      }
216534      assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
216535      if( iLeafPgno>pIter->iLeafPgno ){
216536        fts5SegIterGotoPage(p, pIter, iLeafPgno);
216537        bMove = 0;
216538      }
216539    }else{
216540      assert( pIter->pNextLeaf==0 );
216541      assert( iMatch<pIter->iRowid );
216542      while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
216543        fts5DlidxIterPrev(p, pDlidx);
216544      }
216545      iLeafPgno = fts5DlidxIterPgno(pDlidx);
216546  
216547      assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
216548  
216549      if( iLeafPgno<pIter->iLeafPgno ){
216550        pIter->iLeafPgno = iLeafPgno+1;
216551        fts5SegIterReverseNewPage(p, pIter);
216552        bMove = 0;
216553      }
216554    }
216555  
216556    do{
216557      if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
216558      if( pIter->pLeaf==0 ) break;
216559      if( bRev==0 && pIter->iRowid>=iMatch ) break;
216560      if( bRev!=0 && pIter->iRowid<=iMatch ) break;
216561      bMove = 1;
216562    }while( p->rc==SQLITE_OK );
216563  }
216564  
216565  
216566  /*
216567  ** Free the iterator object passed as the second argument.
216568  */
216569  static void fts5MultiIterFree(Fts5Iter *pIter){
216570    if( pIter ){
216571      int i;
216572      for(i=0; i<pIter->nSeg; i++){
216573        fts5SegIterClear(&pIter->aSeg[i]);
216574      }
216575      fts5BufferFree(&pIter->poslist);
216576      sqlite3_free(pIter);
216577    }
216578  }
216579  
216580  static void fts5MultiIterAdvanced(
216581    Fts5Index *p,                   /* FTS5 backend to iterate within */
216582    Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
216583    int iChanged,                   /* Index of sub-iterator just advanced */
216584    int iMinset                     /* Minimum entry in aFirst[] to set */
216585  ){
216586    int i;
216587    for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
216588      int iEq;
216589      if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
216590        Fts5SegIter *pSeg = &pIter->aSeg[iEq];
216591        assert( p->rc==SQLITE_OK );
216592        pSeg->xNext(p, pSeg, 0);
216593        i = pIter->nSeg + iEq;
216594      }
216595    }
216596  }
216597  
216598  /*
216599  ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
216600  ** points to the same term though - just a different rowid. This function
216601  ** attempts to update the contents of the pIter->aFirst[] accordingly.
216602  ** If it does so successfully, 0 is returned. Otherwise 1.
216603  **
216604  ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
216605  ** on the iterator instead. That function does the same as this one, except
216606  ** that it deals with more complicated cases as well.
216607  */ 
216608  static int fts5MultiIterAdvanceRowid(
216609    Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
216610    int iChanged,                   /* Index of sub-iterator just advanced */
216611    Fts5SegIter **ppFirst
216612  ){
216613    Fts5SegIter *pNew = &pIter->aSeg[iChanged];
216614  
216615    if( pNew->iRowid==pIter->iSwitchRowid
216616     || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
216617    ){
216618      int i;
216619      Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
216620      pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
216621      for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
216622        Fts5CResult *pRes = &pIter->aFirst[i];
216623  
216624        assert( pNew->pLeaf );
216625        assert( pRes->bTermEq==0 || pOther->pLeaf );
216626  
216627        if( pRes->bTermEq ){
216628          if( pNew->iRowid==pOther->iRowid ){
216629            return 1;
216630          }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
216631            pIter->iSwitchRowid = pOther->iRowid;
216632            pNew = pOther;
216633          }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
216634            pIter->iSwitchRowid = pOther->iRowid;
216635          }
216636        }
216637        pRes->iFirst = (u16)(pNew - pIter->aSeg);
216638        if( i==1 ) break;
216639  
216640        pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
216641      }
216642    }
216643  
216644    *ppFirst = pNew;
216645    return 0;
216646  }
216647  
216648  /*
216649  ** Set the pIter->bEof variable based on the state of the sub-iterators.
216650  */
216651  static void fts5MultiIterSetEof(Fts5Iter *pIter){
216652    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
216653    pIter->base.bEof = pSeg->pLeaf==0;
216654    pIter->iSwitchRowid = pSeg->iRowid;
216655  }
216656  
216657  /*
216658  ** Move the iterator to the next entry. 
216659  **
216660  ** If an error occurs, an error code is left in Fts5Index.rc. It is not 
216661  ** considered an error if the iterator reaches EOF, or if it is already at 
216662  ** EOF when this function is called.
216663  */
216664  static void fts5MultiIterNext(
216665    Fts5Index *p, 
216666    Fts5Iter *pIter,
216667    int bFrom,                      /* True if argument iFrom is valid */
216668    i64 iFrom                       /* Advance at least as far as this */
216669  ){
216670    int bUseFrom = bFrom;
216671    assert( pIter->base.bEof==0 );
216672    while( p->rc==SQLITE_OK ){
216673      int iFirst = pIter->aFirst[1].iFirst;
216674      int bNewTerm = 0;
216675      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
216676      assert( p->rc==SQLITE_OK );
216677      if( bUseFrom && pSeg->pDlidx ){
216678        fts5SegIterNextFrom(p, pSeg, iFrom);
216679      }else{
216680        pSeg->xNext(p, pSeg, &bNewTerm);
216681      }
216682  
216683      if( pSeg->pLeaf==0 || bNewTerm 
216684       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
216685      ){
216686        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
216687        fts5MultiIterSetEof(pIter);
216688        pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
216689        if( pSeg->pLeaf==0 ) return;
216690      }
216691  
216692      fts5AssertMultiIterSetup(p, pIter);
216693      assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
216694      if( pIter->bSkipEmpty==0 || pSeg->nPos ){
216695        pIter->xSetOutputs(pIter, pSeg);
216696        return;
216697      }
216698      bUseFrom = 0;
216699    }
216700  }
216701  
216702  static void fts5MultiIterNext2(
216703    Fts5Index *p, 
216704    Fts5Iter *pIter,
216705    int *pbNewTerm                  /* OUT: True if *might* be new term */
216706  ){
216707    assert( pIter->bSkipEmpty );
216708    if( p->rc==SQLITE_OK ){
216709      *pbNewTerm = 0;
216710      do{
216711        int iFirst = pIter->aFirst[1].iFirst;
216712        Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
216713        int bNewTerm = 0;
216714  
216715        assert( p->rc==SQLITE_OK );
216716        pSeg->xNext(p, pSeg, &bNewTerm);
216717        if( pSeg->pLeaf==0 || bNewTerm 
216718         || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
216719        ){
216720          fts5MultiIterAdvanced(p, pIter, iFirst, 1);
216721          fts5MultiIterSetEof(pIter);
216722          *pbNewTerm = 1;
216723        }
216724        fts5AssertMultiIterSetup(p, pIter);
216725  
216726      }while( fts5MultiIterIsEmpty(p, pIter) );
216727    }
216728  }
216729  
216730  static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
216731    UNUSED_PARAM2(pUnused1, pUnused2);
216732  }
216733  
216734  static Fts5Iter *fts5MultiIterAlloc(
216735    Fts5Index *p,                   /* FTS5 backend to iterate within */
216736    int nSeg
216737  ){
216738    Fts5Iter *pNew;
216739    int nSlot;                      /* Power of two >= nSeg */
216740  
216741    for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
216742    pNew = fts5IdxMalloc(p, 
216743        sizeof(Fts5Iter) +                  /* pNew */
216744        sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
216745        sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
216746    );
216747    if( pNew ){
216748      pNew->nSeg = nSlot;
216749      pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
216750      pNew->pIndex = p;
216751      pNew->xSetOutputs = fts5IterSetOutputs_Noop;
216752    }
216753    return pNew;
216754  }
216755  
216756  static void fts5PoslistCallback(
216757    Fts5Index *pUnused, 
216758    void *pContext, 
216759    const u8 *pChunk, int nChunk
216760  ){
216761    UNUSED_PARAM(pUnused);
216762    assert_nc( nChunk>=0 );
216763    if( nChunk>0 ){
216764      fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
216765    }
216766  }
216767  
216768  typedef struct PoslistCallbackCtx PoslistCallbackCtx;
216769  struct PoslistCallbackCtx {
216770    Fts5Buffer *pBuf;               /* Append to this buffer */
216771    Fts5Colset *pColset;            /* Restrict matches to this column */
216772    int eState;                     /* See above */
216773  };
216774  
216775  typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
216776  struct PoslistOffsetsCtx {
216777    Fts5Buffer *pBuf;               /* Append to this buffer */
216778    Fts5Colset *pColset;            /* Restrict matches to this column */
216779    int iRead;
216780    int iWrite;
216781  };
216782  
216783  /*
216784  ** TODO: Make this more efficient!
216785  */
216786  static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
216787    int i;
216788    for(i=0; i<pColset->nCol; i++){
216789      if( pColset->aiCol[i]==iCol ) return 1;
216790    }
216791    return 0;
216792  }
216793  
216794  static void fts5PoslistOffsetsCallback(
216795    Fts5Index *pUnused, 
216796    void *pContext, 
216797    const u8 *pChunk, int nChunk
216798  ){
216799    PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
216800    UNUSED_PARAM(pUnused);
216801    assert_nc( nChunk>=0 );
216802    if( nChunk>0 ){
216803      int i = 0;
216804      while( i<nChunk ){
216805        int iVal;
216806        i += fts5GetVarint32(&pChunk[i], iVal);
216807        iVal += pCtx->iRead - 2;
216808        pCtx->iRead = iVal;
216809        if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
216810          fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
216811          pCtx->iWrite = iVal;
216812        }
216813      }
216814    }
216815  }
216816  
216817  static void fts5PoslistFilterCallback(
216818    Fts5Index *pUnused,
216819    void *pContext, 
216820    const u8 *pChunk, int nChunk
216821  ){
216822    PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
216823    UNUSED_PARAM(pUnused);
216824    assert_nc( nChunk>=0 );
216825    if( nChunk>0 ){
216826      /* Search through to find the first varint with value 1. This is the
216827      ** start of the next columns hits. */
216828      int i = 0;
216829      int iStart = 0;
216830  
216831      if( pCtx->eState==2 ){
216832        int iCol;
216833        fts5FastGetVarint32(pChunk, i, iCol);
216834        if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
216835          pCtx->eState = 1;
216836          fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
216837        }else{
216838          pCtx->eState = 0;
216839        }
216840      }
216841  
216842      do {
216843        while( i<nChunk && pChunk[i]!=0x01 ){
216844          while( pChunk[i] & 0x80 ) i++;
216845          i++;
216846        }
216847        if( pCtx->eState ){
216848          fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
216849        }
216850        if( i<nChunk ){
216851          int iCol;
216852          iStart = i;
216853          i++;
216854          if( i>=nChunk ){
216855            pCtx->eState = 2;
216856          }else{
216857            fts5FastGetVarint32(pChunk, i, iCol);
216858            pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
216859            if( pCtx->eState ){
216860              fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
216861              iStart = i;
216862            }
216863          }
216864        }
216865      }while( i<nChunk );
216866    }
216867  }
216868  
216869  static void fts5ChunkIterate(
216870    Fts5Index *p,                   /* Index object */
216871    Fts5SegIter *pSeg,              /* Poslist of this iterator */
216872    void *pCtx,                     /* Context pointer for xChunk callback */
216873    void (*xChunk)(Fts5Index*, void*, const u8*, int)
216874  ){
216875    int nRem = pSeg->nPos;          /* Number of bytes still to come */
216876    Fts5Data *pData = 0;
216877    u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
216878    int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
216879    int pgno = pSeg->iLeafPgno;
216880    int pgnoSave = 0;
216881  
216882    /* This function does notmwork with detail=none databases. */
216883    assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
216884  
216885    if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
216886      pgnoSave = pgno+1;
216887    }
216888  
216889    while( 1 ){
216890      xChunk(p, pCtx, pChunk, nChunk);
216891      nRem -= nChunk;
216892      fts5DataRelease(pData);
216893      if( nRem<=0 ){
216894        break;
216895      }else{
216896        pgno++;
216897        pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
216898        if( pData==0 ) break;
216899        pChunk = &pData->p[4];
216900        nChunk = MIN(nRem, pData->szLeaf - 4);
216901        if( pgno==pgnoSave ){
216902          assert( pSeg->pNextLeaf==0 );
216903          pSeg->pNextLeaf = pData;
216904          pData = 0;
216905        }
216906      }
216907    }
216908  }
216909  
216910  /*
216911  ** Iterator pIter currently points to a valid entry (not EOF). This
216912  ** function appends the position list data for the current entry to
216913  ** buffer pBuf. It does not make a copy of the position-list size
216914  ** field.
216915  */
216916  static void fts5SegiterPoslist(
216917    Fts5Index *p,
216918    Fts5SegIter *pSeg,
216919    Fts5Colset *pColset,
216920    Fts5Buffer *pBuf
216921  ){
216922    if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
216923      memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
216924      if( pColset==0 ){
216925        fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
216926      }else{
216927        if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
216928          PoslistCallbackCtx sCtx;
216929          sCtx.pBuf = pBuf;
216930          sCtx.pColset = pColset;
216931          sCtx.eState = fts5IndexColsetTest(pColset, 0);
216932          assert( sCtx.eState==0 || sCtx.eState==1 );
216933          fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
216934        }else{
216935          PoslistOffsetsCtx sCtx;
216936          memset(&sCtx, 0, sizeof(sCtx));
216937          sCtx.pBuf = pBuf;
216938          sCtx.pColset = pColset;
216939          fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
216940        }
216941      }
216942    }
216943  }
216944  
216945  /*
216946  ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
216947  ** the position list contains entries for column iCol, then (*pa) is set
216948  ** to point to the sub-position-list for that column and the number of
216949  ** bytes in it returned. Or, if the argument position list does not
216950  ** contain any entries for column iCol, return 0.
216951  */
216952  static int fts5IndexExtractCol(
216953    const u8 **pa,                  /* IN/OUT: Pointer to poslist */
216954    int n,                          /* IN: Size of poslist in bytes */
216955    int iCol                        /* Column to extract from poslist */
216956  ){
216957    int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
216958    const u8 *p = *pa;
216959    const u8 *pEnd = &p[n];         /* One byte past end of position list */
216960  
216961    while( iCol>iCurrent ){
216962      /* Advance pointer p until it points to pEnd or an 0x01 byte that is
216963      ** not part of a varint. Note that it is not possible for a negative
216964      ** or extremely large varint to occur within an uncorrupted position 
216965      ** list. So the last byte of each varint may be assumed to have a clear
216966      ** 0x80 bit.  */
216967      while( *p!=0x01 ){
216968        while( *p++ & 0x80 );
216969        if( p>=pEnd ) return 0;
216970      }
216971      *pa = p++;
216972      iCurrent = *p++;
216973      if( iCurrent & 0x80 ){
216974        p--;
216975        p += fts5GetVarint32(p, iCurrent);
216976      }
216977    }
216978    if( iCol!=iCurrent ) return 0;
216979  
216980    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
216981    ** not part of a varint */
216982    while( p<pEnd && *p!=0x01 ){
216983      while( *p++ & 0x80 );
216984    }
216985  
216986    return p - (*pa);
216987  }
216988  
216989  static void fts5IndexExtractColset(
216990    int *pRc,
216991    Fts5Colset *pColset,            /* Colset to filter on */
216992    const u8 *pPos, int nPos,       /* Position list */
216993    Fts5Buffer *pBuf                /* Output buffer */
216994  ){
216995    if( *pRc==SQLITE_OK ){
216996      int i;
216997      fts5BufferZero(pBuf);
216998      for(i=0; i<pColset->nCol; i++){
216999        const u8 *pSub = pPos;
217000        int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
217001        if( nSub ){
217002          fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
217003        }
217004      }
217005    }
217006  }
217007  
217008  /*
217009  ** xSetOutputs callback used by detail=none tables.
217010  */
217011  static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
217012    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
217013    pIter->base.iRowid = pSeg->iRowid;
217014    pIter->base.nData = pSeg->nPos;
217015  }
217016  
217017  /*
217018  ** xSetOutputs callback used by detail=full and detail=col tables when no
217019  ** column filters are specified.
217020  */
217021  static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
217022    pIter->base.iRowid = pSeg->iRowid;
217023    pIter->base.nData = pSeg->nPos;
217024  
217025    assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
217026    assert( pIter->pColset==0 );
217027  
217028    if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
217029      /* All data is stored on the current page. Populate the output 
217030      ** variables to point into the body of the page object. */
217031      pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
217032    }else{
217033      /* The data is distributed over two or more pages. Copy it into the
217034      ** Fts5Iter.poslist buffer and then set the output pointer to point
217035      ** to this buffer.  */
217036      fts5BufferZero(&pIter->poslist);
217037      fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
217038      pIter->base.pData = pIter->poslist.p;
217039    }
217040  }
217041  
217042  /*
217043  ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
217044  ** against no columns at all).
217045  */
217046  static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
217047    UNUSED_PARAM(pSeg);
217048    pIter->base.nData = 0;
217049  }
217050  
217051  /*
217052  ** xSetOutputs callback used by detail=col when there is a column filter
217053  ** and there are 100 or more columns. Also called as a fallback from
217054  ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
217055  */
217056  static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
217057    fts5BufferZero(&pIter->poslist);
217058    fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
217059    pIter->base.iRowid = pSeg->iRowid;
217060    pIter->base.pData = pIter->poslist.p;
217061    pIter->base.nData = pIter->poslist.n;
217062  }
217063  
217064  /*
217065  ** xSetOutputs callback used when: 
217066  **
217067  **   * detail=col,
217068  **   * there is a column filter, and
217069  **   * the table contains 100 or fewer columns. 
217070  **
217071  ** The last point is to ensure all column numbers are stored as 
217072  ** single-byte varints.
217073  */
217074  static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
217075  
217076    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
217077    assert( pIter->pColset );
217078  
217079    if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
217080      fts5IterSetOutputs_Col(pIter, pSeg);
217081    }else{
217082      u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
217083      u8 *pEnd = (u8*)&a[pSeg->nPos]; 
217084      int iPrev = 0;
217085      int *aiCol = pIter->pColset->aiCol;
217086      int *aiColEnd = &aiCol[pIter->pColset->nCol];
217087  
217088      u8 *aOut = pIter->poslist.p;
217089      int iPrevOut = 0;
217090  
217091      pIter->base.iRowid = pSeg->iRowid;
217092  
217093      while( a<pEnd ){
217094        iPrev += (int)a++[0] - 2;
217095        while( *aiCol<iPrev ){
217096          aiCol++;
217097          if( aiCol==aiColEnd ) goto setoutputs_col_out;
217098        }
217099        if( *aiCol==iPrev ){
217100          *aOut++ = (u8)((iPrev - iPrevOut) + 2);
217101          iPrevOut = iPrev;
217102        }
217103      }
217104  
217105  setoutputs_col_out:
217106      pIter->base.pData = pIter->poslist.p;
217107      pIter->base.nData = aOut - pIter->poslist.p;
217108    }
217109  }
217110  
217111  /*
217112  ** xSetOutputs callback used by detail=full when there is a column filter.
217113  */
217114  static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
217115    Fts5Colset *pColset = pIter->pColset;
217116    pIter->base.iRowid = pSeg->iRowid;
217117  
217118    assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
217119    assert( pColset );
217120  
217121    if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
217122      /* All data is stored on the current page. Populate the output 
217123      ** variables to point into the body of the page object. */
217124      const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
217125      if( pColset->nCol==1 ){
217126        pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
217127        pIter->base.pData = a;
217128      }else{
217129        int *pRc = &pIter->pIndex->rc;
217130        fts5BufferZero(&pIter->poslist);
217131        fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
217132        pIter->base.pData = pIter->poslist.p;
217133        pIter->base.nData = pIter->poslist.n;
217134      }
217135    }else{
217136      /* The data is distributed over two or more pages. Copy it into the
217137      ** Fts5Iter.poslist buffer and then set the output pointer to point
217138      ** to this buffer.  */
217139      fts5BufferZero(&pIter->poslist);
217140      fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
217141      pIter->base.pData = pIter->poslist.p;
217142      pIter->base.nData = pIter->poslist.n;
217143    }
217144  }
217145  
217146  static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
217147    if( *pRc==SQLITE_OK ){
217148      Fts5Config *pConfig = pIter->pIndex->pConfig;
217149      if( pConfig->eDetail==FTS5_DETAIL_NONE ){
217150        pIter->xSetOutputs = fts5IterSetOutputs_None;
217151      }
217152  
217153      else if( pIter->pColset==0 ){
217154        pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
217155      }
217156  
217157      else if( pIter->pColset->nCol==0 ){
217158        pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
217159      }
217160  
217161      else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
217162        pIter->xSetOutputs = fts5IterSetOutputs_Full;
217163      }
217164  
217165      else{
217166        assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
217167        if( pConfig->nCol<=100 ){
217168          pIter->xSetOutputs = fts5IterSetOutputs_Col100;
217169          sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
217170        }else{
217171          pIter->xSetOutputs = fts5IterSetOutputs_Col;
217172        }
217173      }
217174    }
217175  }
217176  
217177  
217178  /*
217179  ** Allocate a new Fts5Iter object.
217180  **
217181  ** The new object will be used to iterate through data in structure pStruct.
217182  ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
217183  ** is zero or greater, data from the first nSegment segments on level iLevel
217184  ** is merged.
217185  **
217186  ** The iterator initially points to the first term/rowid entry in the 
217187  ** iterated data.
217188  */
217189  static void fts5MultiIterNew(
217190    Fts5Index *p,                   /* FTS5 backend to iterate within */
217191    Fts5Structure *pStruct,         /* Structure of specific index */
217192    int flags,                      /* FTS5INDEX_QUERY_XXX flags */
217193    Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
217194    const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
217195    int iLevel,                     /* Level to iterate (-1 for all) */
217196    int nSegment,                   /* Number of segments to merge (iLevel>=0) */
217197    Fts5Iter **ppOut                /* New object */
217198  ){
217199    int nSeg = 0;                   /* Number of segment-iters in use */
217200    int iIter = 0;                  /* */
217201    int iSeg;                       /* Used to iterate through segments */
217202    Fts5StructureLevel *pLvl;
217203    Fts5Iter *pNew;
217204  
217205    assert( (pTerm==0 && nTerm==0) || iLevel<0 );
217206  
217207    /* Allocate space for the new multi-seg-iterator. */
217208    if( p->rc==SQLITE_OK ){
217209      if( iLevel<0 ){
217210        assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
217211        nSeg = pStruct->nSegment;
217212        nSeg += (p->pHash ? 1 : 0);
217213      }else{
217214        nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
217215      }
217216    }
217217    *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
217218    if( pNew==0 ) return;
217219    pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
217220    pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
217221    pNew->pColset = pColset;
217222    if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
217223      fts5IterSetOutputCb(&p->rc, pNew);
217224    }
217225  
217226    /* Initialize each of the component segment iterators. */
217227    if( p->rc==SQLITE_OK ){
217228      if( iLevel<0 ){
217229        Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
217230        if( p->pHash ){
217231          /* Add a segment iterator for the current contents of the hash table. */
217232          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
217233          fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
217234        }
217235        for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
217236          for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
217237            Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
217238            Fts5SegIter *pIter = &pNew->aSeg[iIter++];
217239            if( pTerm==0 ){
217240              fts5SegIterInit(p, pSeg, pIter);
217241            }else{
217242              fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
217243            }
217244          }
217245        }
217246      }else{
217247        pLvl = &pStruct->aLevel[iLevel];
217248        for(iSeg=nSeg-1; iSeg>=0; iSeg--){
217249          fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
217250        }
217251      }
217252      assert( iIter==nSeg );
217253    }
217254  
217255    /* If the above was successful, each component iterators now points 
217256    ** to the first entry in its segment. In this case initialize the 
217257    ** aFirst[] array. Or, if an error has occurred, free the iterator
217258    ** object and set the output variable to NULL.  */
217259    if( p->rc==SQLITE_OK ){
217260      for(iIter=pNew->nSeg-1; iIter>0; iIter--){
217261        int iEq;
217262        if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
217263          Fts5SegIter *pSeg = &pNew->aSeg[iEq];
217264          if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
217265          fts5MultiIterAdvanced(p, pNew, iEq, iIter);
217266        }
217267      }
217268      fts5MultiIterSetEof(pNew);
217269      fts5AssertMultiIterSetup(p, pNew);
217270  
217271      if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
217272        fts5MultiIterNext(p, pNew, 0, 0);
217273      }else if( pNew->base.bEof==0 ){
217274        Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
217275        pNew->xSetOutputs(pNew, pSeg);
217276      }
217277  
217278    }else{
217279      fts5MultiIterFree(pNew);
217280      *ppOut = 0;
217281    }
217282  }
217283  
217284  /*
217285  ** Create an Fts5Iter that iterates through the doclist provided
217286  ** as the second argument.
217287  */
217288  static void fts5MultiIterNew2(
217289    Fts5Index *p,                   /* FTS5 backend to iterate within */
217290    Fts5Data *pData,                /* Doclist to iterate through */
217291    int bDesc,                      /* True for descending rowid order */
217292    Fts5Iter **ppOut                /* New object */
217293  ){
217294    Fts5Iter *pNew;
217295    pNew = fts5MultiIterAlloc(p, 2);
217296    if( pNew ){
217297      Fts5SegIter *pIter = &pNew->aSeg[1];
217298  
217299      pIter->flags = FTS5_SEGITER_ONETERM;
217300      if( pData->szLeaf>0 ){
217301        pIter->pLeaf = pData;
217302        pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
217303        pIter->iEndofDoclist = pData->nn;
217304        pNew->aFirst[1].iFirst = 1;
217305        if( bDesc ){
217306          pNew->bRev = 1;
217307          pIter->flags |= FTS5_SEGITER_REVERSE;
217308          fts5SegIterReverseInitPage(p, pIter);
217309        }else{
217310          fts5SegIterLoadNPos(p, pIter);
217311        }
217312        pData = 0;
217313      }else{
217314        pNew->base.bEof = 1;
217315      }
217316      fts5SegIterSetNext(p, pIter);
217317  
217318      *ppOut = pNew;
217319    }
217320  
217321    fts5DataRelease(pData);
217322  }
217323  
217324  /*
217325  ** Return true if the iterator is at EOF or if an error has occurred. 
217326  ** False otherwise.
217327  */
217328  static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
217329    assert( p->rc 
217330        || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof 
217331    );
217332    return (p->rc || pIter->base.bEof);
217333  }
217334  
217335  /*
217336  ** Return the rowid of the entry that the iterator currently points
217337  ** to. If the iterator points to EOF when this function is called the
217338  ** results are undefined.
217339  */
217340  static i64 fts5MultiIterRowid(Fts5Iter *pIter){
217341    assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
217342    return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
217343  }
217344  
217345  /*
217346  ** Move the iterator to the next entry at or following iMatch.
217347  */
217348  static void fts5MultiIterNextFrom(
217349    Fts5Index *p, 
217350    Fts5Iter *pIter, 
217351    i64 iMatch
217352  ){
217353    while( 1 ){
217354      i64 iRowid;
217355      fts5MultiIterNext(p, pIter, 1, iMatch);
217356      if( fts5MultiIterEof(p, pIter) ) break;
217357      iRowid = fts5MultiIterRowid(pIter);
217358      if( pIter->bRev==0 && iRowid>=iMatch ) break;
217359      if( pIter->bRev!=0 && iRowid<=iMatch ) break;
217360    }
217361  }
217362  
217363  /*
217364  ** Return a pointer to a buffer containing the term associated with the 
217365  ** entry that the iterator currently points to.
217366  */
217367  static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
217368    Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
217369    *pn = p->term.n;
217370    return p->term.p;
217371  }
217372  
217373  /*
217374  ** Allocate a new segment-id for the structure pStruct. The new segment
217375  ** id must be between 1 and 65335 inclusive, and must not be used by 
217376  ** any currently existing segment. If a free segment id cannot be found,
217377  ** SQLITE_FULL is returned.
217378  **
217379  ** If an error has already occurred, this function is a no-op. 0 is 
217380  ** returned in this case.
217381  */
217382  static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
217383    int iSegid = 0;
217384  
217385    if( p->rc==SQLITE_OK ){
217386      if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
217387        p->rc = SQLITE_FULL;
217388      }else{
217389        /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
217390        ** array is 63 elements, or 252 bytes, in size.  */
217391        u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
217392        int iLvl, iSeg;
217393        int i;
217394        u32 mask;
217395        memset(aUsed, 0, sizeof(aUsed));
217396        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
217397          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
217398            int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
217399            if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
217400              aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
217401            }
217402          }
217403        }
217404  
217405        for(i=0; aUsed[i]==0xFFFFFFFF; i++);
217406        mask = aUsed[i];
217407        for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
217408        iSegid += 1 + i*32;
217409  
217410  #ifdef SQLITE_DEBUG
217411        for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
217412          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
217413            assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
217414          }
217415        }
217416        assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
217417  
217418        {
217419          sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
217420          if( p->rc==SQLITE_OK ){
217421            u8 aBlob[2] = {0xff, 0xff};
217422            sqlite3_bind_int(pIdxSelect, 1, iSegid);
217423            sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
217424            assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
217425            p->rc = sqlite3_reset(pIdxSelect);
217426            sqlite3_bind_null(pIdxSelect, 2);
217427          }
217428        }
217429  #endif
217430      }
217431    }
217432  
217433    return iSegid;
217434  }
217435  
217436  /*
217437  ** Discard all data currently cached in the hash-tables.
217438  */
217439  static void fts5IndexDiscardData(Fts5Index *p){
217440    assert( p->pHash || p->nPendingData==0 );
217441    if( p->pHash ){
217442      sqlite3Fts5HashClear(p->pHash);
217443      p->nPendingData = 0;
217444    }
217445  }
217446  
217447  /*
217448  ** Return the size of the prefix, in bytes, that buffer 
217449  ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
217450  **
217451  ** Buffer (pNew/<length-unknown>) is guaranteed to be greater 
217452  ** than buffer (pOld/nOld).
217453  */
217454  static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
217455    int i;
217456    for(i=0; i<nOld; i++){
217457      if( pOld[i]!=pNew[i] ) break;
217458    }
217459    return i;
217460  }
217461  
217462  static void fts5WriteDlidxClear(
217463    Fts5Index *p, 
217464    Fts5SegWriter *pWriter,
217465    int bFlush                      /* If true, write dlidx to disk */
217466  ){
217467    int i;
217468    assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
217469    for(i=0; i<pWriter->nDlidx; i++){
217470      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
217471      if( pDlidx->buf.n==0 ) break;
217472      if( bFlush ){
217473        assert( pDlidx->pgno!=0 );
217474        fts5DataWrite(p, 
217475            FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
217476            pDlidx->buf.p, pDlidx->buf.n
217477        );
217478      }
217479      sqlite3Fts5BufferZero(&pDlidx->buf);
217480      pDlidx->bPrevValid = 0;
217481    }
217482  }
217483  
217484  /*
217485  ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
217486  ** Any new array elements are zeroed before returning.
217487  */
217488  static int fts5WriteDlidxGrow(
217489    Fts5Index *p,
217490    Fts5SegWriter *pWriter,
217491    int nLvl
217492  ){
217493    if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
217494      Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
217495          pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
217496      );
217497      if( aDlidx==0 ){
217498        p->rc = SQLITE_NOMEM;
217499      }else{
217500        int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
217501        memset(&aDlidx[pWriter->nDlidx], 0, nByte);
217502        pWriter->aDlidx = aDlidx;
217503        pWriter->nDlidx = nLvl;
217504      }
217505    }
217506    return p->rc;
217507  }
217508  
217509  /*
217510  ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
217511  ** enough, flush it to disk and return 1. Otherwise discard it and return
217512  ** zero.
217513  */
217514  static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
217515    int bFlag = 0;
217516  
217517    /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
217518    ** to the database, also write the doclist-index to disk.  */
217519    if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
217520      bFlag = 1;
217521    }
217522    fts5WriteDlidxClear(p, pWriter, bFlag);
217523    pWriter->nEmpty = 0;
217524    return bFlag;
217525  }
217526  
217527  /*
217528  ** This function is called whenever processing of the doclist for the 
217529  ** last term on leaf page (pWriter->iBtPage) is completed. 
217530  **
217531  ** The doclist-index for that term is currently stored in-memory within the
217532  ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
217533  ** writes it out to disk. Or, if it is too small to bother with, discards
217534  ** it.
217535  **
217536  ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
217537  */
217538  static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
217539    int bFlag;
217540  
217541    assert( pWriter->iBtPage || pWriter->nEmpty==0 );
217542    if( pWriter->iBtPage==0 ) return;
217543    bFlag = fts5WriteFlushDlidx(p, pWriter);
217544  
217545    if( p->rc==SQLITE_OK ){
217546      const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
217547      /* The following was already done in fts5WriteInit(): */
217548      /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
217549      sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
217550      sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
217551      sqlite3_step(p->pIdxWriter);
217552      p->rc = sqlite3_reset(p->pIdxWriter);
217553      sqlite3_bind_null(p->pIdxWriter, 2);
217554    }
217555    pWriter->iBtPage = 0;
217556  }
217557  
217558  /*
217559  ** This is called once for each leaf page except the first that contains
217560  ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
217561  ** is larger than all terms written to earlier leaves, and equal to or
217562  ** smaller than the first term on the new leaf.
217563  **
217564  ** If an error occurs, an error code is left in Fts5Index.rc. If an error
217565  ** has already occurred when this function is called, it is a no-op.
217566  */
217567  static void fts5WriteBtreeTerm(
217568    Fts5Index *p,                   /* FTS5 backend object */
217569    Fts5SegWriter *pWriter,         /* Writer object */
217570    int nTerm, const u8 *pTerm      /* First term on new page */
217571  ){
217572    fts5WriteFlushBtree(p, pWriter);
217573    if( p->rc==SQLITE_OK ){
217574      fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
217575      pWriter->iBtPage = pWriter->writer.pgno;
217576    }
217577  }
217578  
217579  /*
217580  ** This function is called when flushing a leaf page that contains no
217581  ** terms at all to disk.
217582  */
217583  static void fts5WriteBtreeNoTerm(
217584    Fts5Index *p,                   /* FTS5 backend object */
217585    Fts5SegWriter *pWriter          /* Writer object */
217586  ){
217587    /* If there were no rowids on the leaf page either and the doclist-index
217588    ** has already been started, append an 0x00 byte to it.  */
217589    if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
217590      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
217591      assert( pDlidx->bPrevValid );
217592      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
217593    }
217594  
217595    /* Increment the "number of sequential leaves without a term" counter. */
217596    pWriter->nEmpty++;
217597  }
217598  
217599  static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
217600    i64 iRowid;
217601    int iOff;
217602  
217603    iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
217604    fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
217605    return iRowid;
217606  }
217607  
217608  /*
217609  ** Rowid iRowid has just been appended to the current leaf page. It is the
217610  ** first on the page. This function appends an appropriate entry to the current
217611  ** doclist-index.
217612  */
217613  static void fts5WriteDlidxAppend(
217614    Fts5Index *p, 
217615    Fts5SegWriter *pWriter, 
217616    i64 iRowid
217617  ){
217618    int i;
217619    int bDone = 0;
217620  
217621    for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
217622      i64 iVal;
217623      Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
217624  
217625      if( pDlidx->buf.n>=p->pConfig->pgsz ){
217626        /* The current doclist-index page is full. Write it to disk and push
217627        ** a copy of iRowid (which will become the first rowid on the next
217628        ** doclist-index leaf page) up into the next level of the b-tree 
217629        ** hierarchy. If the node being flushed is currently the root node,
217630        ** also push its first rowid upwards. */
217631        pDlidx->buf.p[0] = 0x01;    /* Not the root node */
217632        fts5DataWrite(p, 
217633            FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
217634            pDlidx->buf.p, pDlidx->buf.n
217635        );
217636        fts5WriteDlidxGrow(p, pWriter, i+2);
217637        pDlidx = &pWriter->aDlidx[i];
217638        if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
217639          i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
217640  
217641          /* This was the root node. Push its first rowid up to the new root. */
217642          pDlidx[1].pgno = pDlidx->pgno;
217643          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
217644          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
217645          sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
217646          pDlidx[1].bPrevValid = 1;
217647          pDlidx[1].iPrev = iFirst;
217648        }
217649  
217650        sqlite3Fts5BufferZero(&pDlidx->buf);
217651        pDlidx->bPrevValid = 0;
217652        pDlidx->pgno++;
217653      }else{
217654        bDone = 1;
217655      }
217656  
217657      if( pDlidx->bPrevValid ){
217658        iVal = iRowid - pDlidx->iPrev;
217659      }else{
217660        i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
217661        assert( pDlidx->buf.n==0 );
217662        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
217663        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
217664        iVal = iRowid;
217665      }
217666  
217667      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
217668      pDlidx->bPrevValid = 1;
217669      pDlidx->iPrev = iRowid;
217670    }
217671  }
217672  
217673  static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
217674    static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
217675    Fts5PageWriter *pPage = &pWriter->writer;
217676    i64 iRowid;
217677  
217678    assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
217679  
217680    /* Set the szLeaf header field. */
217681    assert( 0==fts5GetU16(&pPage->buf.p[2]) );
217682    fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
217683  
217684    if( pWriter->bFirstTermInPage ){
217685      /* No term was written to this page. */
217686      assert( pPage->pgidx.n==0 );
217687      fts5WriteBtreeNoTerm(p, pWriter);
217688    }else{
217689      /* Append the pgidx to the page buffer. Set the szLeaf header field. */
217690      fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
217691    }
217692  
217693    /* Write the page out to disk */
217694    iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
217695    fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
217696  
217697    /* Initialize the next page. */
217698    fts5BufferZero(&pPage->buf);
217699    fts5BufferZero(&pPage->pgidx);
217700    fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
217701    pPage->iPrevPgidx = 0;
217702    pPage->pgno++;
217703  
217704    /* Increase the leaves written counter */
217705    pWriter->nLeafWritten++;
217706  
217707    /* The new leaf holds no terms or rowids */
217708    pWriter->bFirstTermInPage = 1;
217709    pWriter->bFirstRowidInPage = 1;
217710  }
217711  
217712  /*
217713  ** Append term pTerm/nTerm to the segment being written by the writer passed
217714  ** as the second argument.
217715  **
217716  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
217717  ** already occurred, this function is a no-op.
217718  */
217719  static void fts5WriteAppendTerm(
217720    Fts5Index *p, 
217721    Fts5SegWriter *pWriter,
217722    int nTerm, const u8 *pTerm 
217723  ){
217724    int nPrefix;                    /* Bytes of prefix compression for term */
217725    Fts5PageWriter *pPage = &pWriter->writer;
217726    Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
217727    int nMin = MIN(pPage->term.n, nTerm);
217728  
217729    assert( p->rc==SQLITE_OK );
217730    assert( pPage->buf.n>=4 );
217731    assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
217732  
217733    /* If the current leaf page is full, flush it to disk. */
217734    if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
217735      if( pPage->buf.n>4 ){
217736        fts5WriteFlushLeaf(p, pWriter);
217737        if( p->rc!=SQLITE_OK ) return;
217738      }
217739      fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
217740    }
217741    
217742    /* TODO1: Updating pgidx here. */
217743    pPgidx->n += sqlite3Fts5PutVarint(
217744        &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
217745    );
217746    pPage->iPrevPgidx = pPage->buf.n;
217747  #if 0
217748    fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
217749    pPgidx->n += 2;
217750  #endif
217751  
217752    if( pWriter->bFirstTermInPage ){
217753      nPrefix = 0;
217754      if( pPage->pgno!=1 ){
217755        /* This is the first term on a leaf that is not the leftmost leaf in
217756        ** the segment b-tree. In this case it is necessary to add a term to
217757        ** the b-tree hierarchy that is (a) larger than the largest term 
217758        ** already written to the segment and (b) smaller than or equal to
217759        ** this term. In other words, a prefix of (pTerm/nTerm) that is one
217760        ** byte longer than the longest prefix (pTerm/nTerm) shares with the
217761        ** previous term. 
217762        **
217763        ** Usually, the previous term is available in pPage->term. The exception
217764        ** is if this is the first term written in an incremental-merge step.
217765        ** In this case the previous term is not available, so just write a
217766        ** copy of (pTerm/nTerm) into the parent node. This is slightly
217767        ** inefficient, but still correct.  */
217768        int n = nTerm;
217769        if( pPage->term.n ){
217770          n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
217771        }
217772        fts5WriteBtreeTerm(p, pWriter, n, pTerm);
217773        if( p->rc!=SQLITE_OK ) return;
217774        pPage = &pWriter->writer;
217775      }
217776    }else{
217777      nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
217778      fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
217779    }
217780  
217781    /* Append the number of bytes of new data, then the term data itself
217782    ** to the page. */
217783    fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
217784    fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
217785  
217786    /* Update the Fts5PageWriter.term field. */
217787    fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
217788    pWriter->bFirstTermInPage = 0;
217789  
217790    pWriter->bFirstRowidInPage = 0;
217791    pWriter->bFirstRowidInDoclist = 1;
217792  
217793    assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
217794    pWriter->aDlidx[0].pgno = pPage->pgno;
217795  }
217796  
217797  /*
217798  ** Append a rowid and position-list size field to the writers output. 
217799  */
217800  static void fts5WriteAppendRowid(
217801    Fts5Index *p, 
217802    Fts5SegWriter *pWriter,
217803    i64 iRowid
217804  ){
217805    if( p->rc==SQLITE_OK ){
217806      Fts5PageWriter *pPage = &pWriter->writer;
217807  
217808      if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
217809        fts5WriteFlushLeaf(p, pWriter);
217810      }
217811  
217812      /* If this is to be the first rowid written to the page, set the 
217813      ** rowid-pointer in the page-header. Also append a value to the dlidx
217814      ** buffer, in case a doclist-index is required.  */
217815      if( pWriter->bFirstRowidInPage ){
217816        fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
217817        fts5WriteDlidxAppend(p, pWriter, iRowid);
217818      }
217819  
217820      /* Write the rowid. */
217821      if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
217822        fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
217823      }else{
217824        assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
217825        fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
217826      }
217827      pWriter->iPrevRowid = iRowid;
217828      pWriter->bFirstRowidInDoclist = 0;
217829      pWriter->bFirstRowidInPage = 0;
217830    }
217831  }
217832  
217833  static void fts5WriteAppendPoslistData(
217834    Fts5Index *p, 
217835    Fts5SegWriter *pWriter, 
217836    const u8 *aData, 
217837    int nData
217838  ){
217839    Fts5PageWriter *pPage = &pWriter->writer;
217840    const u8 *a = aData;
217841    int n = nData;
217842    
217843    assert( p->pConfig->pgsz>0 );
217844    while( p->rc==SQLITE_OK 
217845       && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz 
217846    ){
217847      int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
217848      int nCopy = 0;
217849      while( nCopy<nReq ){
217850        i64 dummy;
217851        nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
217852      }
217853      fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
217854      a += nCopy;
217855      n -= nCopy;
217856      fts5WriteFlushLeaf(p, pWriter);
217857    }
217858    if( n>0 ){
217859      fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
217860    }
217861  }
217862  
217863  /*
217864  ** Flush any data cached by the writer object to the database. Free any
217865  ** allocations associated with the writer.
217866  */
217867  static void fts5WriteFinish(
217868    Fts5Index *p, 
217869    Fts5SegWriter *pWriter,         /* Writer object */
217870    int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
217871  ){
217872    int i;
217873    Fts5PageWriter *pLeaf = &pWriter->writer;
217874    if( p->rc==SQLITE_OK ){
217875      assert( pLeaf->pgno>=1 );
217876      if( pLeaf->buf.n>4 ){
217877        fts5WriteFlushLeaf(p, pWriter);
217878      }
217879      *pnLeaf = pLeaf->pgno-1;
217880      if( pLeaf->pgno>1 ){
217881        fts5WriteFlushBtree(p, pWriter);
217882      }
217883    }
217884    fts5BufferFree(&pLeaf->term);
217885    fts5BufferFree(&pLeaf->buf);
217886    fts5BufferFree(&pLeaf->pgidx);
217887    fts5BufferFree(&pWriter->btterm);
217888  
217889    for(i=0; i<pWriter->nDlidx; i++){
217890      sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
217891    }
217892    sqlite3_free(pWriter->aDlidx);
217893  }
217894  
217895  static void fts5WriteInit(
217896    Fts5Index *p, 
217897    Fts5SegWriter *pWriter, 
217898    int iSegid
217899  ){
217900    const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
217901  
217902    memset(pWriter, 0, sizeof(Fts5SegWriter));
217903    pWriter->iSegid = iSegid;
217904  
217905    fts5WriteDlidxGrow(p, pWriter, 1);
217906    pWriter->writer.pgno = 1;
217907    pWriter->bFirstTermInPage = 1;
217908    pWriter->iBtPage = 1;
217909  
217910    assert( pWriter->writer.buf.n==0 );
217911    assert( pWriter->writer.pgidx.n==0 );
217912  
217913    /* Grow the two buffers to pgsz + padding bytes in size. */
217914    sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
217915    sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
217916  
217917    if( p->pIdxWriter==0 ){
217918      Fts5Config *pConfig = p->pConfig;
217919      fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
217920            "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", 
217921            pConfig->zDb, pConfig->zName
217922      ));
217923    }
217924  
217925    if( p->rc==SQLITE_OK ){
217926      /* Initialize the 4-byte leaf-page header to 0x00. */
217927      memset(pWriter->writer.buf.p, 0, 4);
217928      pWriter->writer.buf.n = 4;
217929  
217930      /* Bind the current output segment id to the index-writer. This is an
217931      ** optimization over binding the same value over and over as rows are
217932      ** inserted into %_idx by the current writer.  */
217933      sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
217934    }
217935  }
217936  
217937  /*
217938  ** Iterator pIter was used to iterate through the input segments of on an
217939  ** incremental merge operation. This function is called if the incremental
217940  ** merge step has finished but the input has not been completely exhausted.
217941  */
217942  static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
217943    int i;
217944    Fts5Buffer buf;
217945    memset(&buf, 0, sizeof(Fts5Buffer));
217946    for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
217947      Fts5SegIter *pSeg = &pIter->aSeg[i];
217948      if( pSeg->pSeg==0 ){
217949        /* no-op */
217950      }else if( pSeg->pLeaf==0 ){
217951        /* All keys from this input segment have been transfered to the output.
217952        ** Set both the first and last page-numbers to 0 to indicate that the
217953        ** segment is now empty. */
217954        pSeg->pSeg->pgnoLast = 0;
217955        pSeg->pSeg->pgnoFirst = 0;
217956      }else{
217957        int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
217958        i64 iLeafRowid;
217959        Fts5Data *pData;
217960        int iId = pSeg->pSeg->iSegid;
217961        u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
217962  
217963        iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
217964        pData = fts5LeafRead(p, iLeafRowid);
217965        if( pData ){
217966          if( iOff>pData->szLeaf ){
217967            /* This can occur if the pages that the segments occupy overlap - if
217968            ** a single page has been assigned to more than one segment. In
217969            ** this case a prior iteration of this loop may have corrupted the
217970            ** segment currently being trimmed.  */
217971            p->rc = FTS5_CORRUPT;
217972          }else{
217973            fts5BufferZero(&buf);
217974            fts5BufferGrow(&p->rc, &buf, pData->nn);
217975            fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
217976            fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
217977            fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
217978            fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
217979            if( p->rc==SQLITE_OK ){
217980              /* Set the szLeaf field */
217981              fts5PutU16(&buf.p[2], (u16)buf.n);
217982            }
217983  
217984            /* Set up the new page-index array */
217985            fts5BufferAppendVarint(&p->rc, &buf, 4);
217986            if( pSeg->iLeafPgno==pSeg->iTermLeafPgno 
217987                && pSeg->iEndofDoclist<pData->szLeaf 
217988              ){
217989              int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
217990              fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
217991              fts5BufferAppendBlob(&p->rc, &buf, 
217992                  pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
217993                  );
217994            }
217995  
217996            pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
217997            fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
217998            fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
217999          }
218000          fts5DataRelease(pData);
218001        }
218002      }
218003    }
218004    fts5BufferFree(&buf);
218005  }
218006  
218007  static void fts5MergeChunkCallback(
218008    Fts5Index *p, 
218009    void *pCtx, 
218010    const u8 *pChunk, int nChunk
218011  ){
218012    Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
218013    fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
218014  }
218015  
218016  /*
218017  **
218018  */
218019  static void fts5IndexMergeLevel(
218020    Fts5Index *p,                   /* FTS5 backend object */
218021    Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
218022    int iLvl,                       /* Level to read input from */
218023    int *pnRem                      /* Write up to this many output leaves */
218024  ){
218025    Fts5Structure *pStruct = *ppStruct;
218026    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
218027    Fts5StructureLevel *pLvlOut;
218028    Fts5Iter *pIter = 0;       /* Iterator to read input data */
218029    int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
218030    int nInput;                     /* Number of input segments */
218031    Fts5SegWriter writer;           /* Writer object */
218032    Fts5StructureSegment *pSeg;     /* Output segment */
218033    Fts5Buffer term;
218034    int bOldest;                    /* True if the output segment is the oldest */
218035    int eDetail = p->pConfig->eDetail;
218036    const int flags = FTS5INDEX_QUERY_NOOUTPUT;
218037    int bTermWritten = 0;           /* True if current term already output */
218038  
218039    assert( iLvl<pStruct->nLevel );
218040    assert( pLvl->nMerge<=pLvl->nSeg );
218041  
218042    memset(&writer, 0, sizeof(Fts5SegWriter));
218043    memset(&term, 0, sizeof(Fts5Buffer));
218044    if( pLvl->nMerge ){
218045      pLvlOut = &pStruct->aLevel[iLvl+1];
218046      assert( pLvlOut->nSeg>0 );
218047      nInput = pLvl->nMerge;
218048      pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
218049  
218050      fts5WriteInit(p, &writer, pSeg->iSegid);
218051      writer.writer.pgno = pSeg->pgnoLast+1;
218052      writer.iBtPage = 0;
218053    }else{
218054      int iSegid = fts5AllocateSegid(p, pStruct);
218055  
218056      /* Extend the Fts5Structure object as required to ensure the output
218057      ** segment exists. */
218058      if( iLvl==pStruct->nLevel-1 ){
218059        fts5StructureAddLevel(&p->rc, ppStruct);
218060        pStruct = *ppStruct;
218061      }
218062      fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
218063      if( p->rc ) return;
218064      pLvl = &pStruct->aLevel[iLvl];
218065      pLvlOut = &pStruct->aLevel[iLvl+1];
218066  
218067      fts5WriteInit(p, &writer, iSegid);
218068  
218069      /* Add the new segment to the output level */
218070      pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
218071      pLvlOut->nSeg++;
218072      pSeg->pgnoFirst = 1;
218073      pSeg->iSegid = iSegid;
218074      pStruct->nSegment++;
218075  
218076      /* Read input from all segments in the input level */
218077      nInput = pLvl->nSeg;
218078    }
218079    bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
218080  
218081    assert( iLvl>=0 );
218082    for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
218083        fts5MultiIterEof(p, pIter)==0;
218084        fts5MultiIterNext(p, pIter, 0, 0)
218085    ){
218086      Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
218087      int nPos;                     /* position-list size field value */
218088      int nTerm;
218089      const u8 *pTerm;
218090  
218091      pTerm = fts5MultiIterTerm(pIter, &nTerm);
218092      if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
218093        if( pnRem && writer.nLeafWritten>nRem ){
218094          break;
218095        }
218096        fts5BufferSet(&p->rc, &term, nTerm, pTerm);
218097        bTermWritten =0;
218098      }
218099  
218100      /* Check for key annihilation. */
218101      if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
218102  
218103      if( p->rc==SQLITE_OK && bTermWritten==0 ){
218104        /* This is a new term. Append a term to the output segment. */
218105        fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
218106        bTermWritten = 1;
218107      }
218108  
218109      /* Append the rowid to the output */
218110      /* WRITEPOSLISTSIZE */
218111      fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
218112  
218113      if( eDetail==FTS5_DETAIL_NONE ){
218114        if( pSegIter->bDel ){
218115          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
218116          if( pSegIter->nPos>0 ){
218117            fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
218118          }
218119        }
218120      }else{
218121        /* Append the position-list data to the output */
218122        nPos = pSegIter->nPos*2 + pSegIter->bDel;
218123        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
218124        fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
218125      }
218126    }
218127  
218128    /* Flush the last leaf page to disk. Set the output segment b-tree height
218129    ** and last leaf page number at the same time.  */
218130    fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
218131  
218132    if( fts5MultiIterEof(p, pIter) ){
218133      int i;
218134  
218135      /* Remove the redundant segments from the %_data table */
218136      for(i=0; i<nInput; i++){
218137        fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
218138      }
218139  
218140      /* Remove the redundant segments from the input level */
218141      if( pLvl->nSeg!=nInput ){
218142        int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
218143        memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
218144      }
218145      pStruct->nSegment -= nInput;
218146      pLvl->nSeg -= nInput;
218147      pLvl->nMerge = 0;
218148      if( pSeg->pgnoLast==0 ){
218149        pLvlOut->nSeg--;
218150        pStruct->nSegment--;
218151      }
218152    }else{
218153      assert( pSeg->pgnoLast>0 );
218154      fts5TrimSegments(p, pIter);
218155      pLvl->nMerge = nInput;
218156    }
218157  
218158    fts5MultiIterFree(pIter);
218159    fts5BufferFree(&term);
218160    if( pnRem ) *pnRem -= writer.nLeafWritten;
218161  }
218162  
218163  /*
218164  ** Do up to nPg pages of automerge work on the index.
218165  **
218166  ** Return true if any changes were actually made, or false otherwise.
218167  */
218168  static int fts5IndexMerge(
218169    Fts5Index *p,                   /* FTS5 backend object */
218170    Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
218171    int nPg,                        /* Pages of work to do */
218172    int nMin                        /* Minimum number of segments to merge */
218173  ){
218174    int nRem = nPg;
218175    int bRet = 0;
218176    Fts5Structure *pStruct = *ppStruct;
218177    while( nRem>0 && p->rc==SQLITE_OK ){
218178      int iLvl;                   /* To iterate through levels */
218179      int iBestLvl = 0;           /* Level offering the most input segments */
218180      int nBest = 0;              /* Number of input segments on best level */
218181  
218182      /* Set iBestLvl to the level to read input segments from. */
218183      assert( pStruct->nLevel>0 );
218184      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
218185        Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
218186        if( pLvl->nMerge ){
218187          if( pLvl->nMerge>nBest ){
218188            iBestLvl = iLvl;
218189            nBest = pLvl->nMerge;
218190          }
218191          break;
218192        }
218193        if( pLvl->nSeg>nBest ){
218194          nBest = pLvl->nSeg;
218195          iBestLvl = iLvl;
218196        }
218197      }
218198  
218199      /* If nBest is still 0, then the index must be empty. */
218200  #ifdef SQLITE_DEBUG
218201      for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
218202        assert( pStruct->aLevel[iLvl].nSeg==0 );
218203      }
218204  #endif
218205  
218206      if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
218207        break;
218208      }
218209      bRet = 1;
218210      fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
218211      if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
218212        fts5StructurePromote(p, iBestLvl+1, pStruct);
218213      }
218214    }
218215    *ppStruct = pStruct;
218216    return bRet;
218217  }
218218  
218219  /*
218220  ** A total of nLeaf leaf pages of data has just been flushed to a level-0
218221  ** segment. This function updates the write-counter accordingly and, if
218222  ** necessary, performs incremental merge work.
218223  **
218224  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
218225  ** already occurred, this function is a no-op.
218226  */
218227  static void fts5IndexAutomerge(
218228    Fts5Index *p,                   /* FTS5 backend object */
218229    Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
218230    int nLeaf                       /* Number of output leaves just written */
218231  ){
218232    if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
218233      Fts5Structure *pStruct = *ppStruct;
218234      u64 nWrite;                   /* Initial value of write-counter */
218235      int nWork;                    /* Number of work-quanta to perform */
218236      int nRem;                     /* Number of leaf pages left to write */
218237  
218238      /* Update the write-counter. While doing so, set nWork. */
218239      nWrite = pStruct->nWriteCounter;
218240      nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
218241      pStruct->nWriteCounter += nLeaf;
218242      nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
218243  
218244      fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
218245    }
218246  }
218247  
218248  static void fts5IndexCrisismerge(
218249    Fts5Index *p,                   /* FTS5 backend object */
218250    Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
218251  ){
218252    const int nCrisis = p->pConfig->nCrisisMerge;
218253    Fts5Structure *pStruct = *ppStruct;
218254    int iLvl = 0;
218255  
218256    assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
218257    while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
218258      fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
218259      assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
218260      fts5StructurePromote(p, iLvl+1, pStruct);
218261      iLvl++;
218262    }
218263    *ppStruct = pStruct;
218264  }
218265  
218266  static int fts5IndexReturn(Fts5Index *p){
218267    int rc = p->rc;
218268    p->rc = SQLITE_OK;
218269    return rc;
218270  }
218271  
218272  typedef struct Fts5FlushCtx Fts5FlushCtx;
218273  struct Fts5FlushCtx {
218274    Fts5Index *pIdx;
218275    Fts5SegWriter writer; 
218276  };
218277  
218278  /*
218279  ** Buffer aBuf[] contains a list of varints, all small enough to fit
218280  ** in a 32-bit integer. Return the size of the largest prefix of this 
218281  ** list nMax bytes or less in size.
218282  */
218283  static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
218284    int ret;
218285    u32 dummy;
218286    ret = fts5GetVarint32(aBuf, dummy);
218287    if( ret<nMax ){
218288      while( 1 ){
218289        int i = fts5GetVarint32(&aBuf[ret], dummy);
218290        if( (ret + i) > nMax ) break;
218291        ret += i;
218292      }
218293    }
218294    return ret;
218295  }
218296  
218297  /*
218298  ** Flush the contents of in-memory hash table iHash to a new level-0 
218299  ** segment on disk. Also update the corresponding structure record.
218300  **
218301  ** If an error occurs, set the Fts5Index.rc error code. If an error has 
218302  ** already occurred, this function is a no-op.
218303  */
218304  static void fts5FlushOneHash(Fts5Index *p){
218305    Fts5Hash *pHash = p->pHash;
218306    Fts5Structure *pStruct;
218307    int iSegid;
218308    int pgnoLast = 0;                 /* Last leaf page number in segment */
218309  
218310    /* Obtain a reference to the index structure and allocate a new segment-id
218311    ** for the new level-0 segment.  */
218312    pStruct = fts5StructureRead(p);
218313    iSegid = fts5AllocateSegid(p, pStruct);
218314    fts5StructureInvalidate(p);
218315  
218316    if( iSegid ){
218317      const int pgsz = p->pConfig->pgsz;
218318      int eDetail = p->pConfig->eDetail;
218319      Fts5StructureSegment *pSeg;   /* New segment within pStruct */
218320      Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
218321      Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
218322  
218323      Fts5SegWriter writer;
218324      fts5WriteInit(p, &writer, iSegid);
218325  
218326      pBuf = &writer.writer.buf;
218327      pPgidx = &writer.writer.pgidx;
218328  
218329      /* fts5WriteInit() should have initialized the buffers to (most likely)
218330      ** the maximum space required. */
218331      assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
218332      assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
218333  
218334      /* Begin scanning through hash table entries. This loop runs once for each
218335      ** term/doclist currently stored within the hash table. */
218336      if( p->rc==SQLITE_OK ){
218337        p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
218338      }
218339      while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
218340        const char *zTerm;          /* Buffer containing term */
218341        const u8 *pDoclist;         /* Pointer to doclist for this term */
218342        int nDoclist;               /* Size of doclist in bytes */
218343  
218344        /* Write the term for this entry to disk. */
218345        sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
218346        fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
218347        if( p->rc!=SQLITE_OK ) break;
218348  
218349        assert( writer.bFirstRowidInPage==0 );
218350        if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
218351          /* The entire doclist will fit on the current leaf. */
218352          fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
218353        }else{
218354          i64 iRowid = 0;
218355          i64 iDelta = 0;
218356          int iOff = 0;
218357  
218358          /* The entire doclist will not fit on this leaf. The following 
218359          ** loop iterates through the poslists that make up the current 
218360          ** doclist.  */
218361          while( p->rc==SQLITE_OK && iOff<nDoclist ){
218362            iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
218363            iRowid += iDelta;
218364            
218365            if( writer.bFirstRowidInPage ){
218366              fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
218367              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
218368              writer.bFirstRowidInPage = 0;
218369              fts5WriteDlidxAppend(p, &writer, iRowid);
218370              if( p->rc!=SQLITE_OK ) break;
218371            }else{
218372              pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
218373            }
218374            assert( pBuf->n<=pBuf->nSpace );
218375  
218376            if( eDetail==FTS5_DETAIL_NONE ){
218377              if( iOff<nDoclist && pDoclist[iOff]==0 ){
218378                pBuf->p[pBuf->n++] = 0;
218379                iOff++;
218380                if( iOff<nDoclist && pDoclist[iOff]==0 ){
218381                  pBuf->p[pBuf->n++] = 0;
218382                  iOff++;
218383                }
218384              }
218385              if( (pBuf->n + pPgidx->n)>=pgsz ){
218386                fts5WriteFlushLeaf(p, &writer);
218387              }
218388            }else{
218389              int bDummy;
218390              int nPos;
218391              int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
218392              nCopy += nPos;
218393              if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
218394                /* The entire poslist will fit on the current leaf. So copy
218395                ** it in one go. */
218396                fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
218397              }else{
218398                /* The entire poslist will not fit on this leaf. So it needs
218399                ** to be broken into sections. The only qualification being
218400                ** that each varint must be stored contiguously.  */
218401                const u8 *pPoslist = &pDoclist[iOff];
218402                int iPos = 0;
218403                while( p->rc==SQLITE_OK ){
218404                  int nSpace = pgsz - pBuf->n - pPgidx->n;
218405                  int n = 0;
218406                  if( (nCopy - iPos)<=nSpace ){
218407                    n = nCopy - iPos;
218408                  }else{
218409                    n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
218410                  }
218411                  assert( n>0 );
218412                  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
218413                  iPos += n;
218414                  if( (pBuf->n + pPgidx->n)>=pgsz ){
218415                    fts5WriteFlushLeaf(p, &writer);
218416                  }
218417                  if( iPos>=nCopy ) break;
218418                }
218419              }
218420              iOff += nCopy;
218421            }
218422          }
218423        }
218424  
218425        /* TODO2: Doclist terminator written here. */
218426        /* pBuf->p[pBuf->n++] = '\0'; */
218427        assert( pBuf->n<=pBuf->nSpace );
218428        if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
218429      }
218430      sqlite3Fts5HashClear(pHash);
218431      fts5WriteFinish(p, &writer, &pgnoLast);
218432  
218433      /* Update the Fts5Structure. It is written back to the database by the
218434      ** fts5StructureRelease() call below.  */
218435      if( pStruct->nLevel==0 ){
218436        fts5StructureAddLevel(&p->rc, &pStruct);
218437      }
218438      fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
218439      if( p->rc==SQLITE_OK ){
218440        pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
218441        pSeg->iSegid = iSegid;
218442        pSeg->pgnoFirst = 1;
218443        pSeg->pgnoLast = pgnoLast;
218444        pStruct->nSegment++;
218445      }
218446      fts5StructurePromote(p, 0, pStruct);
218447    }
218448  
218449    fts5IndexAutomerge(p, &pStruct, pgnoLast);
218450    fts5IndexCrisismerge(p, &pStruct);
218451    fts5StructureWrite(p, pStruct);
218452    fts5StructureRelease(pStruct);
218453  }
218454  
218455  /*
218456  ** Flush any data stored in the in-memory hash tables to the database.
218457  */
218458  static void fts5IndexFlush(Fts5Index *p){
218459    /* Unless it is empty, flush the hash table to disk */
218460    if( p->nPendingData ){
218461      assert( p->pHash );
218462      p->nPendingData = 0;
218463      fts5FlushOneHash(p);
218464    }
218465  }
218466  
218467  static Fts5Structure *fts5IndexOptimizeStruct(
218468    Fts5Index *p, 
218469    Fts5Structure *pStruct
218470  ){
218471    Fts5Structure *pNew = 0;
218472    sqlite3_int64 nByte = sizeof(Fts5Structure);
218473    int nSeg = pStruct->nSegment;
218474    int i;
218475  
218476    /* Figure out if this structure requires optimization. A structure does
218477    ** not require optimization if either:
218478    **
218479    **  + it consists of fewer than two segments, or 
218480    **  + all segments are on the same level, or
218481    **  + all segments except one are currently inputs to a merge operation.
218482    **
218483    ** In the first case, return NULL. In the second, increment the ref-count
218484    ** on *pStruct and return a copy of the pointer to it.
218485    */
218486    if( nSeg<2 ) return 0;
218487    for(i=0; i<pStruct->nLevel; i++){
218488      int nThis = pStruct->aLevel[i].nSeg;
218489      if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
218490        fts5StructureRef(pStruct);
218491        return pStruct;
218492      }
218493      assert( pStruct->aLevel[i].nMerge<=nThis );
218494    }
218495  
218496    nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
218497    pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
218498  
218499    if( pNew ){
218500      Fts5StructureLevel *pLvl;
218501      nByte = nSeg * sizeof(Fts5StructureSegment);
218502      pNew->nLevel = pStruct->nLevel+1;
218503      pNew->nRef = 1;
218504      pNew->nWriteCounter = pStruct->nWriteCounter;
218505      pLvl = &pNew->aLevel[pStruct->nLevel];
218506      pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
218507      if( pLvl->aSeg ){
218508        int iLvl, iSeg;
218509        int iSegOut = 0;
218510        /* Iterate through all segments, from oldest to newest. Add them to
218511        ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
218512        ** segment in the data structure.  */
218513        for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
218514          for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
218515            pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
218516            iSegOut++;
218517          }
218518        }
218519        pNew->nSegment = pLvl->nSeg = nSeg;
218520      }else{
218521        sqlite3_free(pNew);
218522        pNew = 0;
218523      }
218524    }
218525  
218526    return pNew;
218527  }
218528  
218529  static int sqlite3Fts5IndexOptimize(Fts5Index *p){
218530    Fts5Structure *pStruct;
218531    Fts5Structure *pNew = 0;
218532  
218533    assert( p->rc==SQLITE_OK );
218534    fts5IndexFlush(p);
218535    pStruct = fts5StructureRead(p);
218536    fts5StructureInvalidate(p);
218537  
218538    if( pStruct ){
218539      pNew = fts5IndexOptimizeStruct(p, pStruct);
218540    }
218541    fts5StructureRelease(pStruct);
218542  
218543    assert( pNew==0 || pNew->nSegment>0 );
218544    if( pNew ){
218545      int iLvl;
218546      for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
218547      while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
218548        int nRem = FTS5_OPT_WORK_UNIT;
218549        fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
218550      }
218551  
218552      fts5StructureWrite(p, pNew);
218553      fts5StructureRelease(pNew);
218554    }
218555  
218556    return fts5IndexReturn(p); 
218557  }
218558  
218559  /*
218560  ** This is called to implement the special "VALUES('merge', $nMerge)"
218561  ** INSERT command.
218562  */
218563  static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
218564    Fts5Structure *pStruct = fts5StructureRead(p);
218565    if( pStruct ){
218566      int nMin = p->pConfig->nUsermerge;
218567      fts5StructureInvalidate(p);
218568      if( nMerge<0 ){
218569        Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
218570        fts5StructureRelease(pStruct);
218571        pStruct = pNew;
218572        nMin = 2;
218573        nMerge = nMerge*-1;
218574      }
218575      if( pStruct && pStruct->nLevel ){
218576        if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
218577          fts5StructureWrite(p, pStruct);
218578        }
218579      }
218580      fts5StructureRelease(pStruct);
218581    }
218582    return fts5IndexReturn(p);
218583  }
218584  
218585  static void fts5AppendRowid(
218586    Fts5Index *p,
218587    i64 iDelta,
218588    Fts5Iter *pUnused,
218589    Fts5Buffer *pBuf
218590  ){
218591    UNUSED_PARAM(pUnused);
218592    fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
218593  }
218594  
218595  static void fts5AppendPoslist(
218596    Fts5Index *p,
218597    i64 iDelta,
218598    Fts5Iter *pMulti,
218599    Fts5Buffer *pBuf
218600  ){
218601    int nData = pMulti->base.nData;
218602    int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
218603    assert( nData>0 );
218604    if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
218605      fts5BufferSafeAppendVarint(pBuf, iDelta);
218606      fts5BufferSafeAppendVarint(pBuf, nData*2);
218607      fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
218608      memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
218609    }
218610  }
218611  
218612  
218613  static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
218614    u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
218615  
218616    assert( pIter->aPoslist );
218617    if( p>=pIter->aEof ){
218618      pIter->aPoslist = 0;
218619    }else{
218620      i64 iDelta;
218621  
218622      p += fts5GetVarint(p, (u64*)&iDelta);
218623      pIter->iRowid += iDelta;
218624  
218625      /* Read position list size */
218626      if( p[0] & 0x80 ){
218627        int nPos;
218628        pIter->nSize = fts5GetVarint32(p, nPos);
218629        pIter->nPoslist = (nPos>>1);
218630      }else{
218631        pIter->nPoslist = ((int)(p[0])) >> 1;
218632        pIter->nSize = 1;
218633      }
218634  
218635      pIter->aPoslist = p;
218636    }
218637  }
218638  
218639  static void fts5DoclistIterInit(
218640    Fts5Buffer *pBuf, 
218641    Fts5DoclistIter *pIter
218642  ){
218643    memset(pIter, 0, sizeof(*pIter));
218644    pIter->aPoslist = pBuf->p;
218645    pIter->aEof = &pBuf->p[pBuf->n];
218646    fts5DoclistIterNext(pIter);
218647  }
218648  
218649  #if 0
218650  /*
218651  ** Append a doclist to buffer pBuf.
218652  **
218653  ** This function assumes that space within the buffer has already been
218654  ** allocated.
218655  */
218656  static void fts5MergeAppendDocid(
218657    Fts5Buffer *pBuf,               /* Buffer to write to */
218658    i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
218659    i64 iRowid                      /* Rowid to append */
218660  ){
218661    assert( pBuf->n!=0 || (*piLastRowid)==0 );
218662    fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
218663    *piLastRowid = iRowid;
218664  }
218665  #endif
218666  
218667  #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
218668    assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
218669    fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
218670    (iLastRowid) = (iRowid);                                     \
218671  }
218672  
218673  /*
218674  ** Swap the contents of buffer *p1 with that of *p2.
218675  */
218676  static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
218677    Fts5Buffer tmp = *p1;
218678    *p1 = *p2;
218679    *p2 = tmp;
218680  }
218681  
218682  static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
218683    int i = *piOff;
218684    if( i>=pBuf->n ){
218685      *piOff = -1;
218686    }else{
218687      u64 iVal;
218688      *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
218689      *piRowid += iVal;
218690    }
218691  }
218692  
218693  /*
218694  ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
218695  ** In this case the buffers consist of a delta-encoded list of rowids only.
218696  */
218697  static void fts5MergeRowidLists(
218698    Fts5Index *p,                   /* FTS5 backend object */
218699    Fts5Buffer *p1,                 /* First list to merge */
218700    Fts5Buffer *p2                  /* Second list to merge */
218701  ){
218702    int i1 = 0;
218703    int i2 = 0;
218704    i64 iRowid1 = 0;
218705    i64 iRowid2 = 0;
218706    i64 iOut = 0;
218707  
218708    Fts5Buffer out;
218709    memset(&out, 0, sizeof(out));
218710    sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
218711    if( p->rc ) return;
218712  
218713    fts5NextRowid(p1, &i1, &iRowid1);
218714    fts5NextRowid(p2, &i2, &iRowid2);
218715    while( i1>=0 || i2>=0 ){
218716      if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
218717        assert( iOut==0 || iRowid1>iOut );
218718        fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
218719        iOut = iRowid1;
218720        fts5NextRowid(p1, &i1, &iRowid1);
218721      }else{
218722        assert( iOut==0 || iRowid2>iOut );
218723        fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
218724        iOut = iRowid2;
218725        if( i1>=0 && iRowid1==iRowid2 ){
218726          fts5NextRowid(p1, &i1, &iRowid1);
218727        }
218728        fts5NextRowid(p2, &i2, &iRowid2);
218729      }
218730    }
218731  
218732    fts5BufferSwap(&out, p1);
218733    fts5BufferFree(&out);
218734  }
218735  
218736  /*
218737  ** Buffers p1 and p2 contain doclists. This function merges the content
218738  ** of the two doclists together and sets buffer p1 to the result before
218739  ** returning.
218740  **
218741  ** If an error occurs, an error code is left in p->rc. If an error has
218742  ** already occurred, this function is a no-op.
218743  */
218744  static void fts5MergePrefixLists(
218745    Fts5Index *p,                   /* FTS5 backend object */
218746    Fts5Buffer *p1,                 /* First list to merge */
218747    Fts5Buffer *p2                  /* Second list to merge */
218748  ){
218749    if( p2->n ){
218750      i64 iLastRowid = 0;
218751      Fts5DoclistIter i1;
218752      Fts5DoclistIter i2;
218753      Fts5Buffer out = {0, 0, 0};
218754      Fts5Buffer tmp = {0, 0, 0};
218755  
218756      /* The maximum size of the output is equal to the sum of the two 
218757      ** input sizes + 1 varint (9 bytes). The extra varint is because if the
218758      ** first rowid in one input is a large negative number, and the first in
218759      ** the other a non-negative number, the delta for the non-negative
218760      ** number will be larger on disk than the literal integer value
218761      ** was.  */
218762      if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
218763      fts5DoclistIterInit(p1, &i1);
218764      fts5DoclistIterInit(p2, &i2);
218765  
218766      while( 1 ){
218767        if( i1.iRowid<i2.iRowid ){
218768          /* Copy entry from i1 */
218769          fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
218770          fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
218771          fts5DoclistIterNext(&i1);
218772          if( i1.aPoslist==0 ) break;
218773        }
218774        else if( i2.iRowid!=i1.iRowid ){
218775          /* Copy entry from i2 */
218776          fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
218777          fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
218778          fts5DoclistIterNext(&i2);
218779          if( i2.aPoslist==0 ) break;
218780        }
218781        else{
218782          /* Merge the two position lists. */ 
218783          i64 iPos1 = 0;
218784          i64 iPos2 = 0;
218785          int iOff1 = 0;
218786          int iOff2 = 0;
218787          u8 *a1 = &i1.aPoslist[i1.nSize];
218788          u8 *a2 = &i2.aPoslist[i2.nSize];
218789          int nCopy;
218790          u8 *aCopy;
218791  
218792          i64 iPrev = 0;
218793          Fts5PoslistWriter writer;
218794          memset(&writer, 0, sizeof(writer));
218795  
218796          fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
218797          fts5BufferZero(&tmp);
218798          sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
218799          if( p->rc ) break;
218800  
218801          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
218802          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
218803          assert( iPos1>=0 && iPos2>=0 );
218804  
218805          if( iPos1<iPos2 ){
218806            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
218807            sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
218808          }else{
218809            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
218810            sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
218811          }
218812  
218813          if( iPos1>=0 && iPos2>=0 ){
218814            while( 1 ){
218815              if( iPos1<iPos2 ){
218816                if( iPos1!=iPrev ){
218817                  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
218818                }
218819                sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
218820                if( iPos1<0 ) break;
218821              }else{
218822                assert_nc( iPos2!=iPrev );
218823                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
218824                sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
218825                if( iPos2<0 ) break;
218826              }
218827            }
218828          }
218829  
218830          if( iPos1>=0 ){
218831            if( iPos1!=iPrev ){
218832              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
218833            }
218834            aCopy = &a1[iOff1];
218835            nCopy = i1.nPoslist - iOff1;
218836          }else{
218837            assert( iPos2>=0 && iPos2!=iPrev );
218838            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
218839            aCopy = &a2[iOff2];
218840            nCopy = i2.nPoslist - iOff2;
218841          }
218842          if( nCopy>0 ){
218843            fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
218844          }
218845  
218846          /* WRITEPOSLISTSIZE */
218847          fts5BufferSafeAppendVarint(&out, tmp.n * 2);
218848          fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
218849          fts5DoclistIterNext(&i1);
218850          fts5DoclistIterNext(&i2);
218851          assert( out.n<=(p1->n+p2->n+9) );
218852          if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
218853        }
218854      }
218855  
218856      if( i1.aPoslist ){
218857        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
218858        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
218859      }
218860      else if( i2.aPoslist ){
218861        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
218862        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
218863      }
218864      assert( out.n<=(p1->n+p2->n+9) );
218865  
218866      fts5BufferSet(&p->rc, p1, out.n, out.p);
218867      fts5BufferFree(&tmp);
218868      fts5BufferFree(&out);
218869    }
218870  }
218871  
218872  static void fts5SetupPrefixIter(
218873    Fts5Index *p,                   /* Index to read from */
218874    int bDesc,                      /* True for "ORDER BY rowid DESC" */
218875    const u8 *pToken,               /* Buffer containing prefix to match */
218876    int nToken,                     /* Size of buffer pToken in bytes */
218877    Fts5Colset *pColset,            /* Restrict matches to these columns */
218878    Fts5Iter **ppIter          /* OUT: New iterator */
218879  ){
218880    Fts5Structure *pStruct;
218881    Fts5Buffer *aBuf;
218882    const int nBuf = 32;
218883  
218884    void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
218885    void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
218886    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
218887      xMerge = fts5MergeRowidLists;
218888      xAppend = fts5AppendRowid;
218889    }else{
218890      xMerge = fts5MergePrefixLists;
218891      xAppend = fts5AppendPoslist;
218892    }
218893  
218894    aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
218895    pStruct = fts5StructureRead(p);
218896  
218897    if( aBuf && pStruct ){
218898      const int flags = FTS5INDEX_QUERY_SCAN 
218899                      | FTS5INDEX_QUERY_SKIPEMPTY 
218900                      | FTS5INDEX_QUERY_NOOUTPUT;
218901      int i;
218902      i64 iLastRowid = 0;
218903      Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
218904      Fts5Data *pData;
218905      Fts5Buffer doclist;
218906      int bNewTerm = 1;
218907  
218908      memset(&doclist, 0, sizeof(doclist));
218909      fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
218910      fts5IterSetOutputCb(&p->rc, p1);
218911      for( /* no-op */ ;
218912          fts5MultiIterEof(p, p1)==0;
218913          fts5MultiIterNext2(p, p1, &bNewTerm)
218914      ){
218915        Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
218916        int nTerm = pSeg->term.n;
218917        const u8 *pTerm = pSeg->term.p;
218918        p1->xSetOutputs(p1, pSeg);
218919  
218920        assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
218921        if( bNewTerm ){
218922          if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
218923        }
218924  
218925        if( p1->base.nData==0 ) continue;
218926  
218927        if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
218928          for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
218929            assert( i<nBuf );
218930            if( aBuf[i].n==0 ){
218931              fts5BufferSwap(&doclist, &aBuf[i]);
218932              fts5BufferZero(&doclist);
218933            }else{
218934              xMerge(p, &doclist, &aBuf[i]);
218935              fts5BufferZero(&aBuf[i]);
218936            }
218937          }
218938          iLastRowid = 0;
218939        }
218940  
218941        xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
218942        iLastRowid = p1->base.iRowid;
218943      }
218944  
218945      for(i=0; i<nBuf; i++){
218946        if( p->rc==SQLITE_OK ){
218947          xMerge(p, &doclist, &aBuf[i]);
218948        }
218949        fts5BufferFree(&aBuf[i]);
218950      }
218951      fts5MultiIterFree(p1);
218952  
218953      pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);
218954      if( pData ){
218955        pData->p = (u8*)&pData[1];
218956        pData->nn = pData->szLeaf = doclist.n;
218957        if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
218958        fts5MultiIterNew2(p, pData, bDesc, ppIter);
218959      }
218960      fts5BufferFree(&doclist);
218961    }
218962  
218963    fts5StructureRelease(pStruct);
218964    sqlite3_free(aBuf);
218965  }
218966  
218967  
218968  /*
218969  ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
218970  ** to the document with rowid iRowid.
218971  */
218972  static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
218973    assert( p->rc==SQLITE_OK );
218974  
218975    /* Allocate the hash table if it has not already been allocated */
218976    if( p->pHash==0 ){
218977      p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
218978    }
218979  
218980    /* Flush the hash table to disk if required */
218981    if( iRowid<p->iWriteRowid 
218982     || (iRowid==p->iWriteRowid && p->bDelete==0)
218983     || (p->nPendingData > p->pConfig->nHashSize) 
218984    ){
218985      fts5IndexFlush(p);
218986    }
218987  
218988    p->iWriteRowid = iRowid;
218989    p->bDelete = bDelete;
218990    return fts5IndexReturn(p);
218991  }
218992  
218993  /*
218994  ** Commit data to disk.
218995  */
218996  static int sqlite3Fts5IndexSync(Fts5Index *p){
218997    assert( p->rc==SQLITE_OK );
218998    fts5IndexFlush(p);
218999    fts5CloseReader(p);
219000    return fts5IndexReturn(p);
219001  }
219002  
219003  /*
219004  ** Discard any data stored in the in-memory hash tables. Do not write it
219005  ** to the database. Additionally, assume that the contents of the %_data
219006  ** table may have changed on disk. So any in-memory caches of %_data 
219007  ** records must be invalidated.
219008  */
219009  static int sqlite3Fts5IndexRollback(Fts5Index *p){
219010    fts5CloseReader(p);
219011    fts5IndexDiscardData(p);
219012    fts5StructureInvalidate(p);
219013    /* assert( p->rc==SQLITE_OK ); */
219014    return SQLITE_OK;
219015  }
219016  
219017  /*
219018  ** The %_data table is completely empty when this function is called. This
219019  ** function populates it with the initial structure objects for each index,
219020  ** and the initial version of the "averages" record (a zero-byte blob).
219021  */
219022  static int sqlite3Fts5IndexReinit(Fts5Index *p){
219023    Fts5Structure s;
219024    fts5StructureInvalidate(p);
219025    memset(&s, 0, sizeof(Fts5Structure));
219026    fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
219027    fts5StructureWrite(p, &s);
219028    return fts5IndexReturn(p);
219029  }
219030  
219031  /*
219032  ** Open a new Fts5Index handle. If the bCreate argument is true, create
219033  ** and initialize the underlying %_data table.
219034  **
219035  ** If successful, set *pp to point to the new object and return SQLITE_OK.
219036  ** Otherwise, set *pp to NULL and return an SQLite error code.
219037  */
219038  static int sqlite3Fts5IndexOpen(
219039    Fts5Config *pConfig, 
219040    int bCreate, 
219041    Fts5Index **pp,
219042    char **pzErr
219043  ){
219044    int rc = SQLITE_OK;
219045    Fts5Index *p;                   /* New object */
219046  
219047    *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
219048    if( rc==SQLITE_OK ){
219049      p->pConfig = pConfig;
219050      p->nWorkUnit = FTS5_WORK_UNIT;
219051      p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
219052      if( p->zDataTbl && bCreate ){
219053        rc = sqlite3Fts5CreateTable(
219054            pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
219055        );
219056        if( rc==SQLITE_OK ){
219057          rc = sqlite3Fts5CreateTable(pConfig, "idx", 
219058              "segid, term, pgno, PRIMARY KEY(segid, term)", 
219059              1, pzErr
219060          );
219061        }
219062        if( rc==SQLITE_OK ){
219063          rc = sqlite3Fts5IndexReinit(p);
219064        }
219065      }
219066    }
219067  
219068    assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
219069    if( rc ){
219070      sqlite3Fts5IndexClose(p);
219071      *pp = 0;
219072    }
219073    return rc;
219074  }
219075  
219076  /*
219077  ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
219078  */
219079  static int sqlite3Fts5IndexClose(Fts5Index *p){
219080    int rc = SQLITE_OK;
219081    if( p ){
219082      assert( p->pReader==0 );
219083      fts5StructureInvalidate(p);
219084      sqlite3_finalize(p->pWriter);
219085      sqlite3_finalize(p->pDeleter);
219086      sqlite3_finalize(p->pIdxWriter);
219087      sqlite3_finalize(p->pIdxDeleter);
219088      sqlite3_finalize(p->pIdxSelect);
219089      sqlite3_finalize(p->pDataVersion);
219090      sqlite3Fts5HashFree(p->pHash);
219091      sqlite3_free(p->zDataTbl);
219092      sqlite3_free(p);
219093    }
219094    return rc;
219095  }
219096  
219097  /*
219098  ** Argument p points to a buffer containing utf-8 text that is n bytes in 
219099  ** size. Return the number of bytes in the nChar character prefix of the
219100  ** buffer, or 0 if there are less than nChar characters in total.
219101  */
219102  static int sqlite3Fts5IndexCharlenToBytelen(
219103    const char *p, 
219104    int nByte, 
219105    int nChar
219106  ){
219107    int n = 0;
219108    int i;
219109    for(i=0; i<nChar; i++){
219110      if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
219111      if( (unsigned char)p[n++]>=0xc0 ){
219112        while( (p[n] & 0xc0)==0x80 ){
219113          n++;
219114          if( n>=nByte ) break;
219115        }
219116      }
219117    }
219118    return n;
219119  }
219120  
219121  /*
219122  ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
219123  ** unicode characters in the string.
219124  */
219125  static int fts5IndexCharlen(const char *pIn, int nIn){
219126    int nChar = 0;            
219127    int i = 0;
219128    while( i<nIn ){
219129      if( (unsigned char)pIn[i++]>=0xc0 ){
219130        while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
219131      }
219132      nChar++;
219133    }
219134    return nChar;
219135  }
219136  
219137  /*
219138  ** Insert or remove data to or from the index. Each time a document is 
219139  ** added to or removed from the index, this function is called one or more
219140  ** times.
219141  **
219142  ** For an insert, it must be called once for each token in the new document.
219143  ** If the operation is a delete, it must be called (at least) once for each
219144  ** unique token in the document with an iCol value less than zero. The iPos
219145  ** argument is ignored for a delete.
219146  */
219147  static int sqlite3Fts5IndexWrite(
219148    Fts5Index *p,                   /* Index to write to */
219149    int iCol,                       /* Column token appears in (-ve -> delete) */
219150    int iPos,                       /* Position of token within column */
219151    const char *pToken, int nToken  /* Token to add or remove to or from index */
219152  ){
219153    int i;                          /* Used to iterate through indexes */
219154    int rc = SQLITE_OK;             /* Return code */
219155    Fts5Config *pConfig = p->pConfig;
219156  
219157    assert( p->rc==SQLITE_OK );
219158    assert( (iCol<0)==p->bDelete );
219159  
219160    /* Add the entry to the main terms index. */
219161    rc = sqlite3Fts5HashWrite(
219162        p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
219163    );
219164  
219165    for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
219166      const int nChar = pConfig->aPrefix[i];
219167      int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
219168      if( nByte ){
219169        rc = sqlite3Fts5HashWrite(p->pHash, 
219170            p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
219171            nByte
219172        );
219173      }
219174    }
219175  
219176    return rc;
219177  }
219178  
219179  /*
219180  ** Open a new iterator to iterate though all rowid that match the 
219181  ** specified token or token prefix.
219182  */
219183  static int sqlite3Fts5IndexQuery(
219184    Fts5Index *p,                   /* FTS index to query */
219185    const char *pToken, int nToken, /* Token (or prefix) to query for */
219186    int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
219187    Fts5Colset *pColset,            /* Match these columns only */
219188    Fts5IndexIter **ppIter          /* OUT: New iterator object */
219189  ){
219190    Fts5Config *pConfig = p->pConfig;
219191    Fts5Iter *pRet = 0;
219192    Fts5Buffer buf = {0, 0, 0};
219193  
219194    /* If the QUERY_SCAN flag is set, all other flags must be clear. */
219195    assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
219196  
219197    if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
219198      int iIdx = 0;                 /* Index to search */
219199      if( nToken ) memcpy(&buf.p[1], pToken, nToken);
219200  
219201      /* Figure out which index to search and set iIdx accordingly. If this
219202      ** is a prefix query for which there is no prefix index, set iIdx to
219203      ** greater than pConfig->nPrefix to indicate that the query will be
219204      ** satisfied by scanning multiple terms in the main index.
219205      **
219206      ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
219207      ** prefix-query. Instead of using a prefix-index (if one exists), 
219208      ** evaluate the prefix query using the main FTS index. This is used
219209      ** for internal sanity checking by the integrity-check in debug 
219210      ** mode only.  */
219211  #ifdef SQLITE_DEBUG
219212      if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
219213        assert( flags & FTS5INDEX_QUERY_PREFIX );
219214        iIdx = 1+pConfig->nPrefix;
219215      }else
219216  #endif
219217      if( flags & FTS5INDEX_QUERY_PREFIX ){
219218        int nChar = fts5IndexCharlen(pToken, nToken);
219219        for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
219220          if( pConfig->aPrefix[iIdx-1]==nChar ) break;
219221        }
219222      }
219223  
219224      if( iIdx<=pConfig->nPrefix ){
219225        /* Straight index lookup */
219226        Fts5Structure *pStruct = fts5StructureRead(p);
219227        buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
219228        if( pStruct ){
219229          fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, 
219230              pColset, buf.p, nToken+1, -1, 0, &pRet
219231          );
219232          fts5StructureRelease(pStruct);
219233        }
219234      }else{
219235        /* Scan multiple terms in the main index */
219236        int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
219237        buf.p[0] = FTS5_MAIN_PREFIX;
219238        fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
219239        assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
219240        fts5IterSetOutputCb(&p->rc, pRet);
219241        if( p->rc==SQLITE_OK ){
219242          Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
219243          if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
219244        }
219245      }
219246  
219247      if( p->rc ){
219248        sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
219249        pRet = 0;
219250        fts5CloseReader(p);
219251      }
219252  
219253      *ppIter = (Fts5IndexIter*)pRet;
219254      sqlite3Fts5BufferFree(&buf);
219255    }
219256    return fts5IndexReturn(p);
219257  }
219258  
219259  /*
219260  ** Return true if the iterator passed as the only argument is at EOF.
219261  */
219262  /*
219263  ** Move to the next matching rowid. 
219264  */
219265  static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
219266    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
219267    assert( pIter->pIndex->rc==SQLITE_OK );
219268    fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
219269    return fts5IndexReturn(pIter->pIndex);
219270  }
219271  
219272  /*
219273  ** Move to the next matching term/rowid. Used by the fts5vocab module.
219274  */
219275  static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
219276    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
219277    Fts5Index *p = pIter->pIndex;
219278  
219279    assert( pIter->pIndex->rc==SQLITE_OK );
219280  
219281    fts5MultiIterNext(p, pIter, 0, 0);
219282    if( p->rc==SQLITE_OK ){
219283      Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
219284      if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
219285        fts5DataRelease(pSeg->pLeaf);
219286        pSeg->pLeaf = 0;
219287        pIter->base.bEof = 1;
219288      }
219289    }
219290  
219291    return fts5IndexReturn(pIter->pIndex);
219292  }
219293  
219294  /*
219295  ** Move to the next matching rowid that occurs at or after iMatch. The
219296  ** definition of "at or after" depends on whether this iterator iterates
219297  ** in ascending or descending rowid order.
219298  */
219299  static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
219300    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
219301    fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
219302    return fts5IndexReturn(pIter->pIndex);
219303  }
219304  
219305  /*
219306  ** Return the current term.
219307  */
219308  static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
219309    int n;
219310    const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
219311    *pn = n-1;
219312    return &z[1];
219313  }
219314  
219315  /*
219316  ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
219317  */
219318  static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
219319    if( pIndexIter ){
219320      Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
219321      Fts5Index *pIndex = pIter->pIndex;
219322      fts5MultiIterFree(pIter);
219323      fts5CloseReader(pIndex);
219324    }
219325  }
219326  
219327  /*
219328  ** Read and decode the "averages" record from the database. 
219329  **
219330  ** Parameter anSize must point to an array of size nCol, where nCol is
219331  ** the number of user defined columns in the FTS table.
219332  */
219333  static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
219334    int nCol = p->pConfig->nCol;
219335    Fts5Data *pData;
219336  
219337    *pnRow = 0;
219338    memset(anSize, 0, sizeof(i64) * nCol);
219339    pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
219340    if( p->rc==SQLITE_OK && pData->nn ){
219341      int i = 0;
219342      int iCol;
219343      i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
219344      for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
219345        i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
219346      }
219347    }
219348  
219349    fts5DataRelease(pData);
219350    return fts5IndexReturn(p);
219351  }
219352  
219353  /*
219354  ** Replace the current "averages" record with the contents of the buffer 
219355  ** supplied as the second argument.
219356  */
219357  static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
219358    assert( p->rc==SQLITE_OK );
219359    fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
219360    return fts5IndexReturn(p);
219361  }
219362  
219363  /*
219364  ** Return the total number of blocks this module has read from the %_data
219365  ** table since it was created.
219366  */
219367  static int sqlite3Fts5IndexReads(Fts5Index *p){
219368    return p->nRead;
219369  }
219370  
219371  /*
219372  ** Set the 32-bit cookie value stored at the start of all structure 
219373  ** records to the value passed as the second argument.
219374  **
219375  ** Return SQLITE_OK if successful, or an SQLite error code if an error
219376  ** occurs.
219377  */
219378  static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
219379    int rc;                              /* Return code */
219380    Fts5Config *pConfig = p->pConfig;    /* Configuration object */
219381    u8 aCookie[4];                       /* Binary representation of iNew */
219382    sqlite3_blob *pBlob = 0;
219383  
219384    assert( p->rc==SQLITE_OK );
219385    sqlite3Fts5Put32(aCookie, iNew);
219386  
219387    rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, 
219388        "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
219389    );
219390    if( rc==SQLITE_OK ){
219391      sqlite3_blob_write(pBlob, aCookie, 4, 0);
219392      rc = sqlite3_blob_close(pBlob);
219393    }
219394  
219395    return rc;
219396  }
219397  
219398  static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
219399    Fts5Structure *pStruct;
219400    pStruct = fts5StructureRead(p);
219401    fts5StructureRelease(pStruct);
219402    return fts5IndexReturn(p);
219403  }
219404  
219405  
219406  /*************************************************************************
219407  **************************************************************************
219408  ** Below this point is the implementation of the integrity-check 
219409  ** functionality.
219410  */
219411  
219412  /*
219413  ** Return a simple checksum value based on the arguments.
219414  */
219415  static u64 sqlite3Fts5IndexEntryCksum(
219416    i64 iRowid, 
219417    int iCol, 
219418    int iPos, 
219419    int iIdx,
219420    const char *pTerm,
219421    int nTerm
219422  ){
219423    int i;
219424    u64 ret = iRowid;
219425    ret += (ret<<3) + iCol;
219426    ret += (ret<<3) + iPos;
219427    if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
219428    for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
219429    return ret;
219430  }
219431  
219432  #ifdef SQLITE_DEBUG
219433  /*
219434  ** This function is purely an internal test. It does not contribute to 
219435  ** FTS functionality, or even the integrity-check, in any way.
219436  **
219437  ** Instead, it tests that the same set of pgno/rowid combinations are 
219438  ** visited regardless of whether the doclist-index identified by parameters
219439  ** iSegid/iLeaf is iterated in forwards or reverse order.
219440  */
219441  static void fts5TestDlidxReverse(
219442    Fts5Index *p, 
219443    int iSegid,                     /* Segment id to load from */
219444    int iLeaf                       /* Load doclist-index for this leaf */
219445  ){
219446    Fts5DlidxIter *pDlidx = 0;
219447    u64 cksum1 = 13;
219448    u64 cksum2 = 13;
219449  
219450    for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
219451        fts5DlidxIterEof(p, pDlidx)==0;
219452        fts5DlidxIterNext(p, pDlidx)
219453    ){
219454      i64 iRowid = fts5DlidxIterRowid(pDlidx);
219455      int pgno = fts5DlidxIterPgno(pDlidx);
219456      assert( pgno>iLeaf );
219457      cksum1 += iRowid + ((i64)pgno<<32);
219458    }
219459    fts5DlidxIterFree(pDlidx);
219460    pDlidx = 0;
219461  
219462    for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
219463        fts5DlidxIterEof(p, pDlidx)==0;
219464        fts5DlidxIterPrev(p, pDlidx)
219465    ){
219466      i64 iRowid = fts5DlidxIterRowid(pDlidx);
219467      int pgno = fts5DlidxIterPgno(pDlidx);
219468      assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
219469      cksum2 += iRowid + ((i64)pgno<<32);
219470    }
219471    fts5DlidxIterFree(pDlidx);
219472    pDlidx = 0;
219473  
219474    if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
219475  }
219476  
219477  static int fts5QueryCksum(
219478    Fts5Index *p,                   /* Fts5 index object */
219479    int iIdx,
219480    const char *z,                  /* Index key to query for */
219481    int n,                          /* Size of index key in bytes */
219482    int flags,                      /* Flags for Fts5IndexQuery */
219483    u64 *pCksum                     /* IN/OUT: Checksum value */
219484  ){
219485    int eDetail = p->pConfig->eDetail;
219486    u64 cksum = *pCksum;
219487    Fts5IndexIter *pIter = 0;
219488    int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
219489  
219490    while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
219491      i64 rowid = pIter->iRowid;
219492  
219493      if( eDetail==FTS5_DETAIL_NONE ){
219494        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
219495      }else{
219496        Fts5PoslistReader sReader;
219497        for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
219498            sReader.bEof==0;
219499            sqlite3Fts5PoslistReaderNext(&sReader)
219500        ){
219501          int iCol = FTS5_POS2COLUMN(sReader.iPos);
219502          int iOff = FTS5_POS2OFFSET(sReader.iPos);
219503          cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
219504        }
219505      }
219506      if( rc==SQLITE_OK ){
219507        rc = sqlite3Fts5IterNext(pIter);
219508      }
219509    }
219510    sqlite3Fts5IterClose(pIter);
219511  
219512    *pCksum = cksum;
219513    return rc;
219514  }
219515  
219516  
219517  /*
219518  ** This function is also purely an internal test. It does not contribute to 
219519  ** FTS functionality, or even the integrity-check, in any way.
219520  */
219521  static void fts5TestTerm(
219522    Fts5Index *p, 
219523    Fts5Buffer *pPrev,              /* Previous term */
219524    const char *z, int n,           /* Possibly new term to test */
219525    u64 expected,
219526    u64 *pCksum
219527  ){
219528    int rc = p->rc;
219529    if( pPrev->n==0 ){
219530      fts5BufferSet(&rc, pPrev, n, (const u8*)z);
219531    }else
219532    if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
219533      u64 cksum3 = *pCksum;
219534      const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
219535      int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
219536      int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
219537      int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
219538      u64 ck1 = 0;
219539      u64 ck2 = 0;
219540  
219541      /* Check that the results returned for ASC and DESC queries are
219542      ** the same. If not, call this corruption.  */
219543      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
219544      if( rc==SQLITE_OK ){
219545        int f = flags|FTS5INDEX_QUERY_DESC;
219546        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
219547      }
219548      if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
219549  
219550      /* If this is a prefix query, check that the results returned if the
219551      ** the index is disabled are the same. In both ASC and DESC order. 
219552      **
219553      ** This check may only be performed if the hash table is empty. This
219554      ** is because the hash table only supports a single scan query at
219555      ** a time, and the multi-iter loop from which this function is called
219556      ** is already performing such a scan. */
219557      if( p->nPendingData==0 ){
219558        if( iIdx>0 && rc==SQLITE_OK ){
219559          int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
219560          ck2 = 0;
219561          rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
219562          if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
219563        }
219564        if( iIdx>0 && rc==SQLITE_OK ){
219565          int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
219566          ck2 = 0;
219567          rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
219568          if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
219569        }
219570      }
219571  
219572      cksum3 ^= ck1;
219573      fts5BufferSet(&rc, pPrev, n, (const u8*)z);
219574  
219575      if( rc==SQLITE_OK && cksum3!=expected ){
219576        rc = FTS5_CORRUPT;
219577      }
219578      *pCksum = cksum3;
219579    }
219580    p->rc = rc;
219581  }
219582   
219583  #else
219584  # define fts5TestDlidxReverse(x,y,z)
219585  # define fts5TestTerm(u,v,w,x,y,z)
219586  #endif
219587  
219588  /*
219589  ** Check that:
219590  **
219591  **   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
219592  **      contain zero terms.
219593  **   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
219594  **      contain zero rowids.
219595  */
219596  static void fts5IndexIntegrityCheckEmpty(
219597    Fts5Index *p,
219598    Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
219599    int iFirst,
219600    int iNoRowid,
219601    int iLast
219602  ){
219603    int i;
219604  
219605    /* Now check that the iter.nEmpty leaves following the current leaf
219606    ** (a) exist and (b) contain no terms. */
219607    for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
219608      Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
219609      if( pLeaf ){
219610        if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
219611        if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
219612      }
219613      fts5DataRelease(pLeaf);
219614    }
219615  }
219616  
219617  static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
219618    int iTermOff = 0;
219619    int ii;
219620  
219621    Fts5Buffer buf1 = {0,0,0};
219622    Fts5Buffer buf2 = {0,0,0};
219623  
219624    ii = pLeaf->szLeaf;
219625    while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
219626      int res;
219627      int iOff;
219628      int nIncr;
219629  
219630      ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
219631      iTermOff += nIncr;
219632      iOff = iTermOff;
219633  
219634      if( iOff>=pLeaf->szLeaf ){
219635        p->rc = FTS5_CORRUPT;
219636      }else if( iTermOff==nIncr ){
219637        int nByte;
219638        iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
219639        if( (iOff+nByte)>pLeaf->szLeaf ){
219640          p->rc = FTS5_CORRUPT;
219641        }else{
219642          fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
219643        }
219644      }else{
219645        int nKeep, nByte;
219646        iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
219647        iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
219648        if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
219649          p->rc = FTS5_CORRUPT;
219650        }else{
219651          buf1.n = nKeep;
219652          fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
219653        }
219654  
219655        if( p->rc==SQLITE_OK ){
219656          res = fts5BufferCompare(&buf1, &buf2);
219657          if( res<=0 ) p->rc = FTS5_CORRUPT;
219658        }
219659      }
219660      fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
219661    }
219662  
219663    fts5BufferFree(&buf1);
219664    fts5BufferFree(&buf2);
219665  }
219666  
219667  static void fts5IndexIntegrityCheckSegment(
219668    Fts5Index *p,                   /* FTS5 backend object */
219669    Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
219670  ){
219671    Fts5Config *pConfig = p->pConfig;
219672    sqlite3_stmt *pStmt = 0;
219673    int rc2;
219674    int iIdxPrevLeaf = pSeg->pgnoFirst-1;
219675    int iDlidxPrevLeaf = pSeg->pgnoLast;
219676  
219677    if( pSeg->pgnoFirst==0 ) return;
219678  
219679    fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
219680        "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
219681        pConfig->zDb, pConfig->zName, pSeg->iSegid
219682    ));
219683  
219684    /* Iterate through the b-tree hierarchy.  */
219685    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
219686      i64 iRow;                     /* Rowid for this leaf */
219687      Fts5Data *pLeaf;              /* Data for this leaf */
219688  
219689      int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
219690      const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
219691      int iIdxLeaf = sqlite3_column_int(pStmt, 2);
219692      int bIdxDlidx = sqlite3_column_int(pStmt, 3);
219693  
219694      /* If the leaf in question has already been trimmed from the segment, 
219695      ** ignore this b-tree entry. Otherwise, load it into memory. */
219696      if( iIdxLeaf<pSeg->pgnoFirst ) continue;
219697      iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
219698      pLeaf = fts5LeafRead(p, iRow);
219699      if( pLeaf==0 ) break;
219700  
219701      /* Check that the leaf contains at least one term, and that it is equal
219702      ** to or larger than the split-key in zIdxTerm.  Also check that if there
219703      ** is also a rowid pointer within the leaf page header, it points to a
219704      ** location before the term.  */
219705      if( pLeaf->nn<=pLeaf->szLeaf ){
219706        p->rc = FTS5_CORRUPT;
219707      }else{
219708        int iOff;                   /* Offset of first term on leaf */
219709        int iRowidOff;              /* Offset of first rowid on leaf */
219710        int nTerm;                  /* Size of term on leaf in bytes */
219711        int res;                    /* Comparison of term and split-key */
219712  
219713        iOff = fts5LeafFirstTermOff(pLeaf);
219714        iRowidOff = fts5LeafFirstRowidOff(pLeaf);
219715        if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
219716          p->rc = FTS5_CORRUPT;
219717        }else{
219718          iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
219719          res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
219720          if( res==0 ) res = nTerm - nIdxTerm;
219721          if( res<0 ) p->rc = FTS5_CORRUPT;
219722        }
219723  
219724        fts5IntegrityCheckPgidx(p, pLeaf);
219725      }
219726      fts5DataRelease(pLeaf);
219727      if( p->rc ) break;
219728  
219729      /* Now check that the iter.nEmpty leaves following the current leaf
219730      ** (a) exist and (b) contain no terms. */
219731      fts5IndexIntegrityCheckEmpty(
219732          p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
219733      );
219734      if( p->rc ) break;
219735  
219736      /* If there is a doclist-index, check that it looks right. */
219737      if( bIdxDlidx ){
219738        Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
219739        int iPrevLeaf = iIdxLeaf;
219740        int iSegid = pSeg->iSegid;
219741        int iPg = 0;
219742        i64 iKey;
219743  
219744        for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
219745            fts5DlidxIterEof(p, pDlidx)==0;
219746            fts5DlidxIterNext(p, pDlidx)
219747        ){
219748  
219749          /* Check any rowid-less pages that occur before the current leaf. */
219750          for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
219751            iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
219752            pLeaf = fts5DataRead(p, iKey);
219753            if( pLeaf ){
219754              if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
219755              fts5DataRelease(pLeaf);
219756            }
219757          }
219758          iPrevLeaf = fts5DlidxIterPgno(pDlidx);
219759  
219760          /* Check that the leaf page indicated by the iterator really does
219761          ** contain the rowid suggested by the same. */
219762          iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
219763          pLeaf = fts5DataRead(p, iKey);
219764          if( pLeaf ){
219765            i64 iRowid;
219766            int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
219767            ASSERT_SZLEAF_OK(pLeaf);
219768            if( iRowidOff>=pLeaf->szLeaf ){
219769              p->rc = FTS5_CORRUPT;
219770            }else{
219771              fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
219772              if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
219773            }
219774            fts5DataRelease(pLeaf);
219775          }
219776        }
219777  
219778        iDlidxPrevLeaf = iPg;
219779        fts5DlidxIterFree(pDlidx);
219780        fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
219781      }else{
219782        iDlidxPrevLeaf = pSeg->pgnoLast;
219783        /* TODO: Check there is no doclist index */
219784      }
219785  
219786      iIdxPrevLeaf = iIdxLeaf;
219787    }
219788  
219789    rc2 = sqlite3_finalize(pStmt);
219790    if( p->rc==SQLITE_OK ) p->rc = rc2;
219791  
219792    /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
219793  #if 0
219794    if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
219795      p->rc = FTS5_CORRUPT;
219796    }
219797  #endif
219798  }
219799  
219800  
219801  /*
219802  ** Run internal checks to ensure that the FTS index (a) is internally 
219803  ** consistent and (b) contains entries for which the XOR of the checksums
219804  ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
219805  **
219806  ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
219807  ** checksum does not match. Return SQLITE_OK if all checks pass without
219808  ** error, or some other SQLite error code if another error (e.g. OOM)
219809  ** occurs.
219810  */
219811  static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
219812    int eDetail = p->pConfig->eDetail;
219813    u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
219814    Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
219815    Fts5Iter *pIter;                /* Used to iterate through entire index */
219816    Fts5Structure *pStruct;         /* Index structure */
219817  
219818  #ifdef SQLITE_DEBUG
219819    /* Used by extra internal tests only run if NDEBUG is not defined */
219820    u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
219821    Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
219822  #endif
219823    const int flags = FTS5INDEX_QUERY_NOOUTPUT;
219824    
219825    /* Load the FTS index structure */
219826    pStruct = fts5StructureRead(p);
219827  
219828    /* Check that the internal nodes of each segment match the leaves */
219829    if( pStruct ){
219830      int iLvl, iSeg;
219831      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
219832        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
219833          Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
219834          fts5IndexIntegrityCheckSegment(p, pSeg);
219835        }
219836      }
219837    }
219838  
219839    /* The cksum argument passed to this function is a checksum calculated
219840    ** based on all expected entries in the FTS index (including prefix index
219841    ** entries). This block checks that a checksum calculated based on the
219842    ** actual contents of FTS index is identical.
219843    **
219844    ** Two versions of the same checksum are calculated. The first (stack
219845    ** variable cksum2) based on entries extracted from the full-text index
219846    ** while doing a linear scan of each individual index in turn. 
219847    **
219848    ** As each term visited by the linear scans, a separate query for the
219849    ** same term is performed. cksum3 is calculated based on the entries
219850    ** extracted by these queries.
219851    */
219852    for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
219853        fts5MultiIterEof(p, pIter)==0;
219854        fts5MultiIterNext(p, pIter, 0, 0)
219855    ){
219856      int n;                      /* Size of term in bytes */
219857      i64 iPos = 0;               /* Position read from poslist */
219858      int iOff = 0;               /* Offset within poslist */
219859      i64 iRowid = fts5MultiIterRowid(pIter);
219860      char *z = (char*)fts5MultiIterTerm(pIter, &n);
219861  
219862      /* If this is a new term, query for it. Update cksum3 with the results. */
219863      fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
219864  
219865      if( eDetail==FTS5_DETAIL_NONE ){
219866        if( 0==fts5MultiIterIsEmpty(p, pIter) ){
219867          cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
219868        }
219869      }else{
219870        poslist.n = 0;
219871        fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
219872        while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
219873          int iCol = FTS5_POS2COLUMN(iPos);
219874          int iTokOff = FTS5_POS2OFFSET(iPos);
219875          cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
219876        }
219877      }
219878    }
219879    fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
219880  
219881    fts5MultiIterFree(pIter);
219882    if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
219883  
219884    fts5StructureRelease(pStruct);
219885  #ifdef SQLITE_DEBUG
219886    fts5BufferFree(&term);
219887  #endif
219888    fts5BufferFree(&poslist);
219889    return fts5IndexReturn(p);
219890  }
219891  
219892  /*************************************************************************
219893  **************************************************************************
219894  ** Below this point is the implementation of the fts5_decode() scalar
219895  ** function only.
219896  */
219897  
219898  /*
219899  ** Decode a segment-data rowid from the %_data table. This function is
219900  ** the opposite of macro FTS5_SEGMENT_ROWID().
219901  */
219902  static void fts5DecodeRowid(
219903    i64 iRowid,                     /* Rowid from %_data table */
219904    int *piSegid,                   /* OUT: Segment id */
219905    int *pbDlidx,                   /* OUT: Dlidx flag */
219906    int *piHeight,                  /* OUT: Height */
219907    int *piPgno                     /* OUT: Page number */
219908  ){
219909    *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
219910    iRowid >>= FTS5_DATA_PAGE_B;
219911  
219912    *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
219913    iRowid >>= FTS5_DATA_HEIGHT_B;
219914  
219915    *pbDlidx = (int)(iRowid & 0x0001);
219916    iRowid >>= FTS5_DATA_DLI_B;
219917  
219918    *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
219919  }
219920  
219921  static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
219922    int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
219923    fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
219924  
219925    if( iSegid==0 ){
219926      if( iKey==FTS5_AVERAGES_ROWID ){
219927        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
219928      }else{
219929        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
219930      }
219931    }
219932    else{
219933      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
219934          bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
219935      );
219936    }
219937  }
219938  
219939  static void fts5DebugStructure(
219940    int *pRc,                       /* IN/OUT: error code */
219941    Fts5Buffer *pBuf,
219942    Fts5Structure *p
219943  ){
219944    int iLvl, iSeg;                 /* Iterate through levels, segments */
219945  
219946    for(iLvl=0; iLvl<p->nLevel; iLvl++){
219947      Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
219948      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, 
219949          " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
219950      );
219951      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
219952        Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
219953        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", 
219954            pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
219955        );
219956      }
219957      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
219958    }
219959  }
219960  
219961  /*
219962  ** This is part of the fts5_decode() debugging aid.
219963  **
219964  ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
219965  ** function appends a human-readable representation of the same object
219966  ** to the buffer passed as the second argument. 
219967  */
219968  static void fts5DecodeStructure(
219969    int *pRc,                       /* IN/OUT: error code */
219970    Fts5Buffer *pBuf,
219971    const u8 *pBlob, int nBlob
219972  ){
219973    int rc;                         /* Return code */
219974    Fts5Structure *p = 0;           /* Decoded structure object */
219975  
219976    rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
219977    if( rc!=SQLITE_OK ){
219978      *pRc = rc;
219979      return;
219980    }
219981  
219982    fts5DebugStructure(pRc, pBuf, p);
219983    fts5StructureRelease(p);
219984  }
219985  
219986  /*
219987  ** This is part of the fts5_decode() debugging aid.
219988  **
219989  ** Arguments pBlob/nBlob contain an "averages" record. This function 
219990  ** appends a human-readable representation of record to the buffer passed 
219991  ** as the second argument. 
219992  */
219993  static void fts5DecodeAverages(
219994    int *pRc,                       /* IN/OUT: error code */
219995    Fts5Buffer *pBuf,
219996    const u8 *pBlob, int nBlob
219997  ){
219998    int i = 0;
219999    const char *zSpace = "";
220000  
220001    while( i<nBlob ){
220002      u64 iVal;
220003      i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
220004      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
220005      zSpace = " ";
220006    }
220007  }
220008  
220009  /*
220010  ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
220011  ** each varint and append its string representation to buffer pBuf. Return
220012  ** after either the input buffer is exhausted or a 0 value is read.
220013  **
220014  ** The return value is the number of bytes read from the input buffer.
220015  */
220016  static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
220017    int iOff = 0;
220018    while( iOff<n ){
220019      int iVal;
220020      iOff += fts5GetVarint32(&a[iOff], iVal);
220021      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
220022    }
220023    return iOff;
220024  }
220025  
220026  /*
220027  ** The start of buffer (a/n) contains the start of a doclist. The doclist
220028  ** may or may not finish within the buffer. This function appends a text
220029  ** representation of the part of the doclist that is present to buffer
220030  ** pBuf. 
220031  **
220032  ** The return value is the number of bytes read from the input buffer.
220033  */
220034  static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
220035    i64 iDocid = 0;
220036    int iOff = 0;
220037  
220038    if( n>0 ){
220039      iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
220040      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
220041    }
220042    while( iOff<n ){
220043      int nPos;
220044      int bDel;
220045      iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
220046      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
220047      iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
220048      if( iOff<n ){
220049        i64 iDelta;
220050        iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
220051        iDocid += iDelta;
220052        sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
220053      }
220054    }
220055  
220056    return iOff;
220057  }
220058  
220059  /*
220060  ** This function is part of the fts5_decode() debugging function. It is 
220061  ** only ever used with detail=none tables.
220062  **
220063  ** Buffer (pData/nData) contains a doclist in the format used by detail=none
220064  ** tables. This function appends a human-readable version of that list to
220065  ** buffer pBuf.
220066  **
220067  ** If *pRc is other than SQLITE_OK when this function is called, it is a
220068  ** no-op. If an OOM or other error occurs within this function, *pRc is
220069  ** set to an SQLite error code before returning. The final state of buffer
220070  ** pBuf is undefined in this case.
220071  */
220072  static void fts5DecodeRowidList(
220073    int *pRc,                       /* IN/OUT: Error code */
220074    Fts5Buffer *pBuf,               /* Buffer to append text to */
220075    const u8 *pData, int nData      /* Data to decode list-of-rowids from */
220076  ){
220077    int i = 0;
220078    i64 iRowid = 0;
220079  
220080    while( i<nData ){
220081      const char *zApp = "";
220082      u64 iVal;
220083      i += sqlite3Fts5GetVarint(&pData[i], &iVal);
220084      iRowid += iVal;
220085  
220086      if( i<nData && pData[i]==0x00 ){
220087        i++;
220088        if( i<nData && pData[i]==0x00 ){
220089          i++;
220090          zApp = "+";
220091        }else{
220092          zApp = "*";
220093        }
220094      }
220095  
220096      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
220097    }
220098  }
220099  
220100  /*
220101  ** The implementation of user-defined scalar function fts5_decode().
220102  */
220103  static void fts5DecodeFunction(
220104    sqlite3_context *pCtx,          /* Function call context */
220105    int nArg,                       /* Number of args (always 2) */
220106    sqlite3_value **apVal           /* Function arguments */
220107  ){
220108    i64 iRowid;                     /* Rowid for record being decoded */
220109    int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
220110    const u8 *aBlob; int n;         /* Record to decode */
220111    u8 *a = 0;
220112    Fts5Buffer s;                   /* Build up text to return here */
220113    int rc = SQLITE_OK;             /* Return code */
220114    sqlite3_int64 nSpace = 0;
220115    int eDetailNone = (sqlite3_user_data(pCtx)!=0);
220116  
220117    assert( nArg==2 );
220118    UNUSED_PARAM(nArg);
220119    memset(&s, 0, sizeof(Fts5Buffer));
220120    iRowid = sqlite3_value_int64(apVal[0]);
220121  
220122    /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
220123    ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
220124    ** buffer overreads even if the record is corrupt.  */
220125    n = sqlite3_value_bytes(apVal[1]);
220126    aBlob = sqlite3_value_blob(apVal[1]);
220127    nSpace = n + FTS5_DATA_ZERO_PADDING;
220128    a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
220129    if( a==0 ) goto decode_out;
220130    if( n>0 ) memcpy(a, aBlob, n);
220131  
220132    fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
220133  
220134    fts5DebugRowid(&rc, &s, iRowid);
220135    if( bDlidx ){
220136      Fts5Data dlidx;
220137      Fts5DlidxLvl lvl;
220138  
220139      dlidx.p = a;
220140      dlidx.nn = n;
220141  
220142      memset(&lvl, 0, sizeof(Fts5DlidxLvl));
220143      lvl.pData = &dlidx;
220144      lvl.iLeafPgno = iPgno;
220145  
220146      for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
220147        sqlite3Fts5BufferAppendPrintf(&rc, &s, 
220148            " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
220149        );
220150      }
220151    }else if( iSegid==0 ){
220152      if( iRowid==FTS5_AVERAGES_ROWID ){
220153        fts5DecodeAverages(&rc, &s, a, n);
220154      }else{
220155        fts5DecodeStructure(&rc, &s, a, n);
220156      }
220157    }else if( eDetailNone ){
220158      Fts5Buffer term;              /* Current term read from page */
220159      int szLeaf;
220160      int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
220161      int iTermOff;
220162      int nKeep = 0;
220163      int iOff;
220164  
220165      memset(&term, 0, sizeof(Fts5Buffer));
220166  
220167      /* Decode any entries that occur before the first term. */
220168      if( szLeaf<n ){
220169        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
220170      }else{
220171        iTermOff = szLeaf;
220172      }
220173      fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
220174  
220175      iOff = iTermOff;
220176      while( iOff<szLeaf ){
220177        int nAppend;
220178  
220179        /* Read the term data for the next term*/
220180        iOff += fts5GetVarint32(&a[iOff], nAppend);
220181        term.n = nKeep;
220182        fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
220183        sqlite3Fts5BufferAppendPrintf(
220184            &rc, &s, " term=%.*s", term.n, (const char*)term.p
220185        );
220186        iOff += nAppend;
220187  
220188        /* Figure out where the doclist for this term ends */
220189        if( iPgidxOff<n ){
220190          int nIncr;
220191          iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
220192          iTermOff += nIncr;
220193        }else{
220194          iTermOff = szLeaf;
220195        }
220196  
220197        fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
220198        iOff = iTermOff;
220199        if( iOff<szLeaf ){
220200          iOff += fts5GetVarint32(&a[iOff], nKeep);
220201        }
220202      }
220203  
220204      fts5BufferFree(&term);
220205    }else{
220206      Fts5Buffer term;              /* Current term read from page */
220207      int szLeaf;                   /* Offset of pgidx in a[] */
220208      int iPgidxOff;
220209      int iPgidxPrev = 0;           /* Previous value read from pgidx */
220210      int iTermOff = 0;
220211      int iRowidOff = 0;
220212      int iOff;
220213      int nDoclist;
220214  
220215      memset(&term, 0, sizeof(Fts5Buffer));
220216  
220217      if( n<4 ){
220218        sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
220219        goto decode_out;
220220      }else{
220221        iRowidOff = fts5GetU16(&a[0]);
220222        iPgidxOff = szLeaf = fts5GetU16(&a[2]);
220223        if( iPgidxOff<n ){
220224          fts5GetVarint32(&a[iPgidxOff], iTermOff);
220225        }else if( iPgidxOff>n ){
220226          rc = FTS5_CORRUPT;
220227          goto decode_out;
220228        }
220229      }
220230  
220231      /* Decode the position list tail at the start of the page */
220232      if( iRowidOff!=0 ){
220233        iOff = iRowidOff;
220234      }else if( iTermOff!=0 ){
220235        iOff = iTermOff;
220236      }else{
220237        iOff = szLeaf;
220238      }
220239      if( iOff>n ){
220240        rc = FTS5_CORRUPT;
220241        goto decode_out;
220242      }
220243      fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
220244  
220245      /* Decode any more doclist data that appears on the page before the
220246      ** first term. */
220247      nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
220248      if( nDoclist+iOff>n ){
220249        rc = FTS5_CORRUPT;
220250        goto decode_out;
220251      }
220252      fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
220253  
220254      while( iPgidxOff<n && rc==SQLITE_OK ){
220255        int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
220256        int nByte;                            /* Bytes of data */
220257        int iEnd;
220258        
220259        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
220260        iPgidxPrev += nByte;
220261        iOff = iPgidxPrev;
220262  
220263        if( iPgidxOff<n ){
220264          fts5GetVarint32(&a[iPgidxOff], nByte);
220265          iEnd = iPgidxPrev + nByte;
220266        }else{
220267          iEnd = szLeaf;
220268        }
220269        if( iEnd>szLeaf ){
220270          rc = FTS5_CORRUPT;
220271          break;
220272        }
220273  
220274        if( bFirst==0 ){
220275          iOff += fts5GetVarint32(&a[iOff], nByte);
220276          if( nByte>term.n ){
220277            rc = FTS5_CORRUPT;
220278            break;
220279          }
220280          term.n = nByte;
220281        }
220282        iOff += fts5GetVarint32(&a[iOff], nByte);
220283        if( iOff+nByte>n ){
220284          rc = FTS5_CORRUPT;
220285          break;
220286        }
220287        fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
220288        iOff += nByte;
220289  
220290        sqlite3Fts5BufferAppendPrintf(
220291            &rc, &s, " term=%.*s", term.n, (const char*)term.p
220292        );
220293        iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
220294      }
220295  
220296      fts5BufferFree(&term);
220297    }
220298    
220299   decode_out:
220300    sqlite3_free(a);
220301    if( rc==SQLITE_OK ){
220302      sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
220303    }else{
220304      sqlite3_result_error_code(pCtx, rc);
220305    }
220306    fts5BufferFree(&s);
220307  }
220308  
220309  /*
220310  ** The implementation of user-defined scalar function fts5_rowid().
220311  */
220312  static void fts5RowidFunction(
220313    sqlite3_context *pCtx,          /* Function call context */
220314    int nArg,                       /* Number of args (always 2) */
220315    sqlite3_value **apVal           /* Function arguments */
220316  ){
220317    const char *zArg;
220318    if( nArg==0 ){
220319      sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
220320    }else{
220321      zArg = (const char*)sqlite3_value_text(apVal[0]);
220322      if( 0==sqlite3_stricmp(zArg, "segment") ){
220323        i64 iRowid;
220324        int segid, pgno;
220325        if( nArg!=3 ){
220326          sqlite3_result_error(pCtx, 
220327              "should be: fts5_rowid('segment', segid, pgno))", -1
220328          );
220329        }else{
220330          segid = sqlite3_value_int(apVal[1]);
220331          pgno = sqlite3_value_int(apVal[2]);
220332          iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
220333          sqlite3_result_int64(pCtx, iRowid);
220334        }
220335      }else{
220336        sqlite3_result_error(pCtx, 
220337          "first arg to fts5_rowid() must be 'segment'" , -1
220338        );
220339      }
220340    }
220341  }
220342  
220343  /*
220344  ** This is called as part of registering the FTS5 module with database
220345  ** connection db. It registers several user-defined scalar functions useful
220346  ** with FTS5.
220347  **
220348  ** If successful, SQLITE_OK is returned. If an error occurs, some other
220349  ** SQLite error code is returned instead.
220350  */
220351  static int sqlite3Fts5IndexInit(sqlite3 *db){
220352    int rc = sqlite3_create_function(
220353        db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
220354    );
220355  
220356    if( rc==SQLITE_OK ){
220357      rc = sqlite3_create_function(
220358          db, "fts5_decode_none", 2, 
220359          SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
220360      );
220361    }
220362  
220363    if( rc==SQLITE_OK ){
220364      rc = sqlite3_create_function(
220365          db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
220366      );
220367    }
220368    return rc;
220369  }
220370  
220371  
220372  static int sqlite3Fts5IndexReset(Fts5Index *p){
220373    assert( p->pStruct==0 || p->iStructVersion!=0 );
220374    if( fts5IndexDataVersion(p)!=p->iStructVersion ){
220375      fts5StructureInvalidate(p);
220376    }
220377    return fts5IndexReturn(p);
220378  }
220379  
220380  /*
220381  ** 2014 Jun 09
220382  **
220383  ** The author disclaims copyright to this source code.  In place of
220384  ** a legal notice, here is a blessing:
220385  **
220386  **    May you do good and not evil.
220387  **    May you find forgiveness for yourself and forgive others.
220388  **    May you share freely, never taking more than you give.
220389  **
220390  ******************************************************************************
220391  **
220392  ** This is an SQLite module implementing full-text search.
220393  */
220394  
220395  
220396  /* #include "fts5Int.h" */
220397  
220398  /*
220399  ** This variable is set to false when running tests for which the on disk
220400  ** structures should not be corrupt. Otherwise, true. If it is false, extra
220401  ** assert() conditions in the fts5 code are activated - conditions that are
220402  ** only true if it is guaranteed that the fts5 database is not corrupt.
220403  */
220404  SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
220405  
220406  
220407  typedef struct Fts5Auxdata Fts5Auxdata;
220408  typedef struct Fts5Auxiliary Fts5Auxiliary;
220409  typedef struct Fts5Cursor Fts5Cursor;
220410  typedef struct Fts5FullTable Fts5FullTable;
220411  typedef struct Fts5Sorter Fts5Sorter;
220412  typedef struct Fts5TokenizerModule Fts5TokenizerModule;
220413  
220414  /*
220415  ** NOTES ON TRANSACTIONS: 
220416  **
220417  ** SQLite invokes the following virtual table methods as transactions are 
220418  ** opened and closed by the user:
220419  **
220420  **     xBegin():    Start of a new transaction.
220421  **     xSync():     Initial part of two-phase commit.
220422  **     xCommit():   Final part of two-phase commit.
220423  **     xRollback(): Rollback the transaction.
220424  **
220425  ** Anything that is required as part of a commit that may fail is performed
220426  ** in the xSync() callback. Current versions of SQLite ignore any errors 
220427  ** returned by xCommit().
220428  **
220429  ** And as sub-transactions are opened/closed:
220430  **
220431  **     xSavepoint(int S):  Open savepoint S.
220432  **     xRelease(int S):    Commit and close savepoint S.
220433  **     xRollbackTo(int S): Rollback to start of savepoint S.
220434  **
220435  ** During a write-transaction the fts5_index.c module may cache some data 
220436  ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
220437  ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() 
220438  ** is called.
220439  **
220440  ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
220441  ** structure is used to record the current transaction state. This information
220442  ** is not required, but it is used in the assert() statements executed by
220443  ** function fts5CheckTransactionState() (see below).
220444  */
220445  struct Fts5TransactionState {
220446    int eState;                     /* 0==closed, 1==open, 2==synced */
220447    int iSavepoint;                 /* Number of open savepoints (0 -> none) */
220448  };
220449  
220450  /*
220451  ** A single object of this type is allocated when the FTS5 module is 
220452  ** registered with a database handle. It is used to store pointers to
220453  ** all registered FTS5 extensions - tokenizers and auxiliary functions.
220454  */
220455  struct Fts5Global {
220456    fts5_api api;                   /* User visible part of object (see fts5.h) */
220457    sqlite3 *db;                    /* Associated database connection */ 
220458    i64 iNextId;                    /* Used to allocate unique cursor ids */
220459    Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
220460    Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
220461    Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
220462    Fts5Cursor *pCsr;               /* First in list of all open cursors */
220463  };
220464  
220465  /*
220466  ** Each auxiliary function registered with the FTS5 module is represented
220467  ** by an object of the following type. All such objects are stored as part
220468  ** of the Fts5Global.pAux list.
220469  */
220470  struct Fts5Auxiliary {
220471    Fts5Global *pGlobal;            /* Global context for this function */
220472    char *zFunc;                    /* Function name (nul-terminated) */
220473    void *pUserData;                /* User-data pointer */
220474    fts5_extension_function xFunc;  /* Callback function */
220475    void (*xDestroy)(void*);        /* Destructor function */
220476    Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
220477  };
220478  
220479  /*
220480  ** Each tokenizer module registered with the FTS5 module is represented
220481  ** by an object of the following type. All such objects are stored as part
220482  ** of the Fts5Global.pTok list.
220483  */
220484  struct Fts5TokenizerModule {
220485    char *zName;                    /* Name of tokenizer */
220486    void *pUserData;                /* User pointer passed to xCreate() */
220487    fts5_tokenizer x;               /* Tokenizer functions */
220488    void (*xDestroy)(void*);        /* Destructor function */
220489    Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
220490  };
220491  
220492  struct Fts5FullTable {
220493    Fts5Table p;                    /* Public class members from fts5Int.h */
220494    Fts5Storage *pStorage;          /* Document store */
220495    Fts5Global *pGlobal;            /* Global (connection wide) data */
220496    Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
220497  #ifdef SQLITE_DEBUG
220498    struct Fts5TransactionState ts;
220499  #endif
220500  };
220501  
220502  struct Fts5MatchPhrase {
220503    Fts5Buffer *pPoslist;           /* Pointer to current poslist */
220504    int nTerm;                      /* Size of phrase in terms */
220505  };
220506  
220507  /*
220508  ** pStmt:
220509  **   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
220510  **
220511  ** aIdx[]:
220512  **   There is one entry in the aIdx[] array for each phrase in the query,
220513  **   the value of which is the offset within aPoslist[] following the last 
220514  **   byte of the position list for the corresponding phrase.
220515  */
220516  struct Fts5Sorter {
220517    sqlite3_stmt *pStmt;
220518    i64 iRowid;                     /* Current rowid */
220519    const u8 *aPoslist;             /* Position lists for current row */
220520    int nIdx;                       /* Number of entries in aIdx[] */
220521    int aIdx[1];                    /* Offsets into aPoslist for current row */
220522  };
220523  
220524  
220525  /*
220526  ** Virtual-table cursor object.
220527  **
220528  ** iSpecial:
220529  **   If this is a 'special' query (refer to function fts5SpecialMatch()), 
220530  **   then this variable contains the result of the query. 
220531  **
220532  ** iFirstRowid, iLastRowid:
220533  **   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
220534  **   cursor iterates in ascending order of rowids, iFirstRowid is the lower
220535  **   limit of rowids to return, and iLastRowid the upper. In other words, the
220536  **   WHERE clause in the user's query might have been:
220537  **
220538  **       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
220539  **
220540  **   If the cursor iterates in descending order of rowid, iFirstRowid
220541  **   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
220542  **   the lower.
220543  */
220544  struct Fts5Cursor {
220545    sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
220546    Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
220547    int *aColumnSize;               /* Values for xColumnSize() */
220548    i64 iCsrId;                     /* Cursor id */
220549  
220550    /* Zero from this point onwards on cursor reset */
220551    int ePlan;                      /* FTS5_PLAN_XXX value */
220552    int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
220553    i64 iFirstRowid;                /* Return no rowids earlier than this */
220554    i64 iLastRowid;                 /* Return no rowids later than this */
220555    sqlite3_stmt *pStmt;            /* Statement used to read %_content */
220556    Fts5Expr *pExpr;                /* Expression for MATCH queries */
220557    Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
220558    int csrflags;                   /* Mask of cursor flags (see below) */
220559    i64 iSpecial;                   /* Result of special query */
220560  
220561    /* "rank" function. Populated on demand from vtab.xColumn(). */
220562    char *zRank;                    /* Custom rank function */
220563    char *zRankArgs;                /* Custom rank function args */
220564    Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
220565    int nRankArg;                   /* Number of trailing arguments for rank() */
220566    sqlite3_value **apRankArg;      /* Array of trailing arguments */
220567    sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
220568  
220569    /* Auxiliary data storage */
220570    Fts5Auxiliary *pAux;            /* Currently executing extension function */
220571    Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
220572  
220573    /* Cache used by auxiliary functions xInst() and xInstCount() */
220574    Fts5PoslistReader *aInstIter;   /* One for each phrase */
220575    int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
220576    int nInstCount;                 /* Number of phrase instances */
220577    int *aInst;                     /* 3 integers per phrase instance */
220578  };
220579  
220580  /*
220581  ** Bits that make up the "idxNum" parameter passed indirectly by 
220582  ** xBestIndex() to xFilter().
220583  */
220584  #define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
220585  #define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
220586  #define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
220587  #define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
220588  #define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
220589  
220590  #define FTS5_BI_ORDER_RANK   0x0020
220591  #define FTS5_BI_ORDER_ROWID  0x0040
220592  #define FTS5_BI_ORDER_DESC   0x0080
220593  
220594  /*
220595  ** Values for Fts5Cursor.csrflags
220596  */
220597  #define FTS5CSR_EOF               0x01
220598  #define FTS5CSR_REQUIRE_CONTENT   0x02
220599  #define FTS5CSR_REQUIRE_DOCSIZE   0x04
220600  #define FTS5CSR_REQUIRE_INST      0x08
220601  #define FTS5CSR_FREE_ZRANK        0x10
220602  #define FTS5CSR_REQUIRE_RESEEK    0x20
220603  #define FTS5CSR_REQUIRE_POSLIST   0x40
220604  
220605  #define BitFlagAllTest(x,y) (((x) & (y))==(y))
220606  #define BitFlagTest(x,y)    (((x) & (y))!=0)
220607  
220608  
220609  /*
220610  ** Macros to Set(), Clear() and Test() cursor flags.
220611  */
220612  #define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
220613  #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
220614  #define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
220615  
220616  struct Fts5Auxdata {
220617    Fts5Auxiliary *pAux;            /* Extension to which this belongs */
220618    void *pPtr;                     /* Pointer value */
220619    void(*xDelete)(void*);          /* Destructor */
220620    Fts5Auxdata *pNext;             /* Next object in linked list */
220621  };
220622  
220623  #ifdef SQLITE_DEBUG
220624  #define FTS5_BEGIN      1
220625  #define FTS5_SYNC       2
220626  #define FTS5_COMMIT     3
220627  #define FTS5_ROLLBACK   4
220628  #define FTS5_SAVEPOINT  5
220629  #define FTS5_RELEASE    6
220630  #define FTS5_ROLLBACKTO 7
220631  static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
220632    switch( op ){
220633      case FTS5_BEGIN:
220634        assert( p->ts.eState==0 );
220635        p->ts.eState = 1;
220636        p->ts.iSavepoint = -1;
220637        break;
220638  
220639      case FTS5_SYNC:
220640        assert( p->ts.eState==1 );
220641        p->ts.eState = 2;
220642        break;
220643  
220644      case FTS5_COMMIT:
220645        assert( p->ts.eState==2 );
220646        p->ts.eState = 0;
220647        break;
220648  
220649      case FTS5_ROLLBACK:
220650        assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
220651        p->ts.eState = 0;
220652        break;
220653  
220654      case FTS5_SAVEPOINT:
220655        assert( p->ts.eState==1 );
220656        assert( iSavepoint>=0 );
220657        assert( iSavepoint>=p->ts.iSavepoint );
220658        p->ts.iSavepoint = iSavepoint;
220659        break;
220660        
220661      case FTS5_RELEASE:
220662        assert( p->ts.eState==1 );
220663        assert( iSavepoint>=0 );
220664        assert( iSavepoint<=p->ts.iSavepoint );
220665        p->ts.iSavepoint = iSavepoint-1;
220666        break;
220667  
220668      case FTS5_ROLLBACKTO:
220669        assert( p->ts.eState==1 );
220670        assert( iSavepoint>=-1 );
220671        assert( iSavepoint<=p->ts.iSavepoint );
220672        p->ts.iSavepoint = iSavepoint;
220673        break;
220674    }
220675  }
220676  #else
220677  # define fts5CheckTransactionState(x,y,z)
220678  #endif
220679  
220680  /*
220681  ** Return true if pTab is a contentless table.
220682  */
220683  static int fts5IsContentless(Fts5FullTable *pTab){
220684    return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
220685  }
220686  
220687  /*
220688  ** Delete a virtual table handle allocated by fts5InitVtab(). 
220689  */
220690  static void fts5FreeVtab(Fts5FullTable *pTab){
220691    if( pTab ){
220692      sqlite3Fts5IndexClose(pTab->p.pIndex);
220693      sqlite3Fts5StorageClose(pTab->pStorage);
220694      sqlite3Fts5ConfigFree(pTab->p.pConfig);
220695      sqlite3_free(pTab);
220696    }
220697  }
220698  
220699  /*
220700  ** The xDisconnect() virtual table method.
220701  */
220702  static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
220703    fts5FreeVtab((Fts5FullTable*)pVtab);
220704    return SQLITE_OK;
220705  }
220706  
220707  /*
220708  ** The xDestroy() virtual table method.
220709  */
220710  static int fts5DestroyMethod(sqlite3_vtab *pVtab){
220711    Fts5Table *pTab = (Fts5Table*)pVtab;
220712    int rc = sqlite3Fts5DropAll(pTab->pConfig);
220713    if( rc==SQLITE_OK ){
220714      fts5FreeVtab((Fts5FullTable*)pVtab);
220715    }
220716    return rc;
220717  }
220718  
220719  /*
220720  ** This function is the implementation of both the xConnect and xCreate
220721  ** methods of the FTS3 virtual table.
220722  **
220723  ** The argv[] array contains the following:
220724  **
220725  **   argv[0]   -> module name  ("fts5")
220726  **   argv[1]   -> database name
220727  **   argv[2]   -> table name
220728  **   argv[...] -> "column name" and other module argument fields.
220729  */
220730  static int fts5InitVtab(
220731    int bCreate,                    /* True for xCreate, false for xConnect */
220732    sqlite3 *db,                    /* The SQLite database connection */
220733    void *pAux,                     /* Hash table containing tokenizers */
220734    int argc,                       /* Number of elements in argv array */
220735    const char * const *argv,       /* xCreate/xConnect argument array */
220736    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
220737    char **pzErr                    /* Write any error message here */
220738  ){
220739    Fts5Global *pGlobal = (Fts5Global*)pAux;
220740    const char **azConfig = (const char**)argv;
220741    int rc = SQLITE_OK;             /* Return code */
220742    Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
220743    Fts5FullTable *pTab = 0;        /* New virtual table object */
220744  
220745    /* Allocate the new vtab object and parse the configuration */
220746    pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
220747    if( rc==SQLITE_OK ){
220748      rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
220749      assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
220750    }
220751    if( rc==SQLITE_OK ){
220752      pTab->p.pConfig = pConfig;
220753      pTab->pGlobal = pGlobal;
220754    }
220755  
220756    /* Open the index sub-system */
220757    if( rc==SQLITE_OK ){
220758      rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
220759    }
220760  
220761    /* Open the storage sub-system */
220762    if( rc==SQLITE_OK ){
220763      rc = sqlite3Fts5StorageOpen(
220764          pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
220765      );
220766    }
220767  
220768    /* Call sqlite3_declare_vtab() */
220769    if( rc==SQLITE_OK ){
220770      rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
220771    }
220772  
220773    /* Load the initial configuration */
220774    if( rc==SQLITE_OK ){
220775      assert( pConfig->pzErrmsg==0 );
220776      pConfig->pzErrmsg = pzErr;
220777      rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
220778      sqlite3Fts5IndexRollback(pTab->p.pIndex);
220779      pConfig->pzErrmsg = 0;
220780    }
220781  
220782    if( rc!=SQLITE_OK ){
220783      fts5FreeVtab(pTab);
220784      pTab = 0;
220785    }else if( bCreate ){
220786      fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
220787    }
220788    *ppVTab = (sqlite3_vtab*)pTab;
220789    return rc;
220790  }
220791  
220792  /*
220793  ** The xConnect() and xCreate() methods for the virtual table. All the
220794  ** work is done in function fts5InitVtab().
220795  */
220796  static int fts5ConnectMethod(
220797    sqlite3 *db,                    /* Database connection */
220798    void *pAux,                     /* Pointer to tokenizer hash table */
220799    int argc,                       /* Number of elements in argv array */
220800    const char * const *argv,       /* xCreate/xConnect argument array */
220801    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
220802    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
220803  ){
220804    return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
220805  }
220806  static int fts5CreateMethod(
220807    sqlite3 *db,                    /* Database connection */
220808    void *pAux,                     /* Pointer to tokenizer hash table */
220809    int argc,                       /* Number of elements in argv array */
220810    const char * const *argv,       /* xCreate/xConnect argument array */
220811    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
220812    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
220813  ){
220814    return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
220815  }
220816  
220817  /*
220818  ** The different query plans.
220819  */
220820  #define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
220821  #define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
220822  #define FTS5_PLAN_SPECIAL        3       /* An internal query */
220823  #define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
220824  #define FTS5_PLAN_SCAN           5       /* No usable constraint */
220825  #define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
220826  
220827  /*
220828  ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
220829  ** extension is currently being used by a version of SQLite too old to
220830  ** support index-info flags. In that case this function is a no-op.
220831  */
220832  static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
220833  #if SQLITE_VERSION_NUMBER>=3008012
220834  #ifndef SQLITE_CORE
220835    if( sqlite3_libversion_number()>=3008012 )
220836  #endif
220837    {
220838      pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
220839    }
220840  #endif
220841  }
220842  
220843  /*
220844  ** Implementation of the xBestIndex method for FTS5 tables. Within the 
220845  ** WHERE constraint, it searches for the following:
220846  **
220847  **   1. A MATCH constraint against the special column.
220848  **   2. A MATCH constraint against the "rank" column.
220849  **   3. An == constraint against the rowid column.
220850  **   4. A < or <= constraint against the rowid column.
220851  **   5. A > or >= constraint against the rowid column.
220852  **
220853  ** Within the ORDER BY, either:
220854  **
220855  **   5. ORDER BY rank [ASC|DESC]
220856  **   6. ORDER BY rowid [ASC|DESC]
220857  **
220858  ** Costs are assigned as follows:
220859  **
220860  **  a) If an unusable MATCH operator is present in the WHERE clause, the
220861  **     cost is unconditionally set to 1e50 (a really big number).
220862  **
220863  **  a) If a MATCH operator is present, the cost depends on the other
220864  **     constraints also present. As follows:
220865  **
220866  **       * No other constraints:         cost=1000.0
220867  **       * One rowid range constraint:   cost=750.0
220868  **       * Both rowid range constraints: cost=500.0
220869  **       * An == rowid constraint:       cost=100.0
220870  **
220871  **  b) Otherwise, if there is no MATCH:
220872  **
220873  **       * No other constraints:         cost=1000000.0
220874  **       * One rowid range constraint:   cost=750000.0
220875  **       * Both rowid range constraints: cost=250000.0
220876  **       * An == rowid constraint:       cost=10.0
220877  **
220878  ** Costs are not modified by the ORDER BY clause.
220879  */
220880  static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
220881    Fts5Table *pTab = (Fts5Table*)pVTab;
220882    Fts5Config *pConfig = pTab->pConfig;
220883    const int nCol = pConfig->nCol;
220884    int idxFlags = 0;               /* Parameter passed through to xFilter() */
220885    int bHasMatch;
220886    int iNext;
220887    int i;
220888  
220889    struct Constraint {
220890      int op;                       /* Mask against sqlite3_index_constraint.op */
220891      int fts5op;                   /* FTS5 mask for idxFlags */
220892      int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
220893      int omit;                     /* True to omit this if found */
220894      int iConsIndex;               /* Index in pInfo->aConstraint[] */
220895    } aConstraint[] = {
220896      {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
220897                                      FTS5_BI_MATCH,    1, 1, -1},
220898      {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
220899                                      FTS5_BI_RANK,     2, 1, -1},
220900      {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
220901      {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE, 
220902                                      FTS5_BI_ROWID_LE, 0, 0, -1},
220903      {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE, 
220904                                      FTS5_BI_ROWID_GE, 0, 0, -1},
220905    };
220906  
220907    int aColMap[3];
220908    aColMap[0] = -1;
220909    aColMap[1] = nCol;
220910    aColMap[2] = nCol+1;
220911  
220912    assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
220913    assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
220914    assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
220915    assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
220916    assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
220917  
220918    /* Set idxFlags flags for all WHERE clause terms that will be used. */
220919    for(i=0; i<pInfo->nConstraint; i++){
220920      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
220921      int iCol = p->iColumn;
220922  
220923      if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
220924       || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
220925      ){
220926        /* A MATCH operator or equivalent */
220927        if( p->usable ){
220928          idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
220929          aConstraint[0].iConsIndex = i;
220930        }else{
220931          /* As there exists an unusable MATCH constraint this is an 
220932          ** unusable plan. Set a prohibitively high cost. */
220933          pInfo->estimatedCost = 1e50;
220934          return SQLITE_OK;
220935        }
220936      }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
220937        int j;
220938        for(j=1; j<ArraySize(aConstraint); j++){
220939          struct Constraint *pC = &aConstraint[j];
220940          if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
220941            pC->iConsIndex = i;
220942            idxFlags |= pC->fts5op;
220943          }
220944        }
220945      }
220946    }
220947  
220948    /* Set idxFlags flags for the ORDER BY clause */
220949    if( pInfo->nOrderBy==1 ){
220950      int iSort = pInfo->aOrderBy[0].iColumn;
220951      if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
220952        idxFlags |= FTS5_BI_ORDER_RANK;
220953      }else if( iSort==-1 ){
220954        idxFlags |= FTS5_BI_ORDER_ROWID;
220955      }
220956      if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
220957        pInfo->orderByConsumed = 1;
220958        if( pInfo->aOrderBy[0].desc ){
220959          idxFlags |= FTS5_BI_ORDER_DESC;
220960        }
220961      }
220962    }
220963  
220964    /* Calculate the estimated cost based on the flags set in idxFlags. */
220965    bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
220966    if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
220967      pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
220968      if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
220969    }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
220970      pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
220971    }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
220972      pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
220973    }else{
220974      pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
220975    }
220976  
220977    /* Assign argvIndex values to each constraint in use. */
220978    iNext = 1;
220979    for(i=0; i<ArraySize(aConstraint); i++){
220980      struct Constraint *pC = &aConstraint[i];
220981      if( pC->iConsIndex>=0 ){
220982        pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
220983        pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
220984      }
220985    }
220986  
220987    pInfo->idxNum = idxFlags;
220988    return SQLITE_OK;
220989  }
220990  
220991  static int fts5NewTransaction(Fts5FullTable *pTab){
220992    Fts5Cursor *pCsr;
220993    for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
220994      if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
220995    }
220996    return sqlite3Fts5StorageReset(pTab->pStorage);
220997  }
220998  
220999  /*
221000  ** Implementation of xOpen method.
221001  */
221002  static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
221003    Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
221004    Fts5Config *pConfig = pTab->p.pConfig;
221005    Fts5Cursor *pCsr = 0;           /* New cursor object */
221006    sqlite3_int64 nByte;            /* Bytes of space to allocate */
221007    int rc;                         /* Return code */
221008  
221009    rc = fts5NewTransaction(pTab);
221010    if( rc==SQLITE_OK ){
221011      nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
221012      pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
221013      if( pCsr ){
221014        Fts5Global *pGlobal = pTab->pGlobal;
221015        memset(pCsr, 0, nByte);
221016        pCsr->aColumnSize = (int*)&pCsr[1];
221017        pCsr->pNext = pGlobal->pCsr;
221018        pGlobal->pCsr = pCsr;
221019        pCsr->iCsrId = ++pGlobal->iNextId;
221020      }else{
221021        rc = SQLITE_NOMEM;
221022      }
221023    }
221024    *ppCsr = (sqlite3_vtab_cursor*)pCsr;
221025    return rc;
221026  }
221027  
221028  static int fts5StmtType(Fts5Cursor *pCsr){
221029    if( pCsr->ePlan==FTS5_PLAN_SCAN ){
221030      return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
221031    }
221032    return FTS5_STMT_LOOKUP;
221033  }
221034  
221035  /*
221036  ** This function is called after the cursor passed as the only argument
221037  ** is moved to point at a different row. It clears all cached data 
221038  ** specific to the previous row stored by the cursor object.
221039  */
221040  static void fts5CsrNewrow(Fts5Cursor *pCsr){
221041    CsrFlagSet(pCsr, 
221042        FTS5CSR_REQUIRE_CONTENT 
221043      | FTS5CSR_REQUIRE_DOCSIZE 
221044      | FTS5CSR_REQUIRE_INST 
221045      | FTS5CSR_REQUIRE_POSLIST 
221046    );
221047  }
221048  
221049  static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
221050    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
221051    Fts5Auxdata *pData;
221052    Fts5Auxdata *pNext;
221053  
221054    sqlite3_free(pCsr->aInstIter);
221055    sqlite3_free(pCsr->aInst);
221056    if( pCsr->pStmt ){
221057      int eStmt = fts5StmtType(pCsr);
221058      sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
221059    }
221060    if( pCsr->pSorter ){
221061      Fts5Sorter *pSorter = pCsr->pSorter;
221062      sqlite3_finalize(pSorter->pStmt);
221063      sqlite3_free(pSorter);
221064    }
221065  
221066    if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
221067      sqlite3Fts5ExprFree(pCsr->pExpr);
221068    }
221069  
221070    for(pData=pCsr->pAuxdata; pData; pData=pNext){
221071      pNext = pData->pNext;
221072      if( pData->xDelete ) pData->xDelete(pData->pPtr);
221073      sqlite3_free(pData);
221074    }
221075  
221076    sqlite3_finalize(pCsr->pRankArgStmt);
221077    sqlite3_free(pCsr->apRankArg);
221078  
221079    if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
221080      sqlite3_free(pCsr->zRank);
221081      sqlite3_free(pCsr->zRankArgs);
221082    }
221083  
221084    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
221085  }
221086  
221087  
221088  /*
221089  ** Close the cursor.  For additional information see the documentation
221090  ** on the xClose method of the virtual table interface.
221091  */
221092  static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
221093    if( pCursor ){
221094      Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
221095      Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
221096      Fts5Cursor **pp;
221097  
221098      fts5FreeCursorComponents(pCsr);
221099      /* Remove the cursor from the Fts5Global.pCsr list */
221100      for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
221101      *pp = pCsr->pNext;
221102  
221103      sqlite3_free(pCsr);
221104    }
221105    return SQLITE_OK;
221106  }
221107  
221108  static int fts5SorterNext(Fts5Cursor *pCsr){
221109    Fts5Sorter *pSorter = pCsr->pSorter;
221110    int rc;
221111  
221112    rc = sqlite3_step(pSorter->pStmt);
221113    if( rc==SQLITE_DONE ){
221114      rc = SQLITE_OK;
221115      CsrFlagSet(pCsr, FTS5CSR_EOF);
221116    }else if( rc==SQLITE_ROW ){
221117      const u8 *a;
221118      const u8 *aBlob;
221119      int nBlob;
221120      int i;
221121      int iOff = 0;
221122      rc = SQLITE_OK;
221123  
221124      pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
221125      nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
221126      aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
221127  
221128      /* nBlob==0 in detail=none mode. */
221129      if( nBlob>0 ){
221130        for(i=0; i<(pSorter->nIdx-1); i++){
221131          int iVal;
221132          a += fts5GetVarint32(a, iVal);
221133          iOff += iVal;
221134          pSorter->aIdx[i] = iOff;
221135        }
221136        pSorter->aIdx[i] = &aBlob[nBlob] - a;
221137        pSorter->aPoslist = a;
221138      }
221139  
221140      fts5CsrNewrow(pCsr);
221141    }
221142  
221143    return rc;
221144  }
221145  
221146  
221147  /*
221148  ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors 
221149  ** open on table pTab.
221150  */
221151  static void fts5TripCursors(Fts5FullTable *pTab){
221152    Fts5Cursor *pCsr;
221153    for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
221154      if( pCsr->ePlan==FTS5_PLAN_MATCH
221155       && pCsr->base.pVtab==(sqlite3_vtab*)pTab 
221156      ){
221157        CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
221158      }
221159    }
221160  }
221161  
221162  /*
221163  ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
221164  ** argument, close and reopen all Fts5IndexIter iterators that the cursor 
221165  ** is using. Then attempt to move the cursor to a rowid equal to or laster
221166  ** (in the cursors sort order - ASC or DESC) than the current rowid. 
221167  **
221168  ** If the new rowid is not equal to the old, set output parameter *pbSkip
221169  ** to 1 before returning. Otherwise, leave it unchanged.
221170  **
221171  ** Return SQLITE_OK if successful or if no reseek was required, or an 
221172  ** error code if an error occurred.
221173  */
221174  static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
221175    int rc = SQLITE_OK;
221176    assert( *pbSkip==0 );
221177    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
221178      Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
221179      int bDesc = pCsr->bDesc;
221180      i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
221181  
221182      rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
221183      if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
221184        *pbSkip = 1;
221185      }
221186  
221187      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
221188      fts5CsrNewrow(pCsr);
221189      if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
221190        CsrFlagSet(pCsr, FTS5CSR_EOF);
221191        *pbSkip = 1;
221192      }
221193    }
221194    return rc;
221195  }
221196  
221197  
221198  /*
221199  ** Advance the cursor to the next row in the table that matches the 
221200  ** search criteria.
221201  **
221202  ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
221203  ** even if we reach end-of-file.  The fts5EofMethod() will be called
221204  ** subsequently to determine whether or not an EOF was hit.
221205  */
221206  static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
221207    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
221208    int rc;
221209  
221210    assert( (pCsr->ePlan<3)==
221211            (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) 
221212    );
221213    assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
221214  
221215    if( pCsr->ePlan<3 ){
221216      int bSkip = 0;
221217      if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
221218      rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
221219      CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
221220      fts5CsrNewrow(pCsr);
221221    }else{
221222      switch( pCsr->ePlan ){
221223        case FTS5_PLAN_SPECIAL: {
221224          CsrFlagSet(pCsr, FTS5CSR_EOF);
221225          rc = SQLITE_OK;
221226          break;
221227        }
221228    
221229        case FTS5_PLAN_SORTED_MATCH: {
221230          rc = fts5SorterNext(pCsr);
221231          break;
221232        }
221233    
221234        default:
221235          rc = sqlite3_step(pCsr->pStmt);
221236          if( rc!=SQLITE_ROW ){
221237            CsrFlagSet(pCsr, FTS5CSR_EOF);
221238            rc = sqlite3_reset(pCsr->pStmt);
221239          }else{
221240            rc = SQLITE_OK;
221241          }
221242          break;
221243      }
221244    }
221245    
221246    return rc;
221247  }
221248  
221249  
221250  static int fts5PrepareStatement(
221251    sqlite3_stmt **ppStmt,
221252    Fts5Config *pConfig, 
221253    const char *zFmt,
221254    ...
221255  ){
221256    sqlite3_stmt *pRet = 0;
221257    int rc;
221258    char *zSql;
221259    va_list ap;
221260  
221261    va_start(ap, zFmt);
221262    zSql = sqlite3_vmprintf(zFmt, ap);
221263    if( zSql==0 ){
221264      rc = SQLITE_NOMEM; 
221265    }else{
221266      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1, 
221267                              SQLITE_PREPARE_PERSISTENT, &pRet, 0);
221268      if( rc!=SQLITE_OK ){
221269        *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
221270      }
221271      sqlite3_free(zSql);
221272    }
221273  
221274    va_end(ap);
221275    *ppStmt = pRet;
221276    return rc;
221277  } 
221278  
221279  static int fts5CursorFirstSorted(
221280    Fts5FullTable *pTab, 
221281    Fts5Cursor *pCsr, 
221282    int bDesc
221283  ){
221284    Fts5Config *pConfig = pTab->p.pConfig;
221285    Fts5Sorter *pSorter;
221286    int nPhrase;
221287    sqlite3_int64 nByte;
221288    int rc;
221289    const char *zRank = pCsr->zRank;
221290    const char *zRankArgs = pCsr->zRankArgs;
221291    
221292    nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
221293    nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
221294    pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
221295    if( pSorter==0 ) return SQLITE_NOMEM;
221296    memset(pSorter, 0, nByte);
221297    pSorter->nIdx = nPhrase;
221298  
221299    /* TODO: It would be better to have some system for reusing statement
221300    ** handles here, rather than preparing a new one for each query. But that
221301    ** is not possible as SQLite reference counts the virtual table objects.
221302    ** And since the statement required here reads from this very virtual 
221303    ** table, saving it creates a circular reference.
221304    **
221305    ** If SQLite a built-in statement cache, this wouldn't be a problem. */
221306    rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
221307        "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
221308        pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
221309        (zRankArgs ? ", " : ""),
221310        (zRankArgs ? zRankArgs : ""),
221311        bDesc ? "DESC" : "ASC"
221312    );
221313  
221314    pCsr->pSorter = pSorter;
221315    if( rc==SQLITE_OK ){
221316      assert( pTab->pSortCsr==0 );
221317      pTab->pSortCsr = pCsr;
221318      rc = fts5SorterNext(pCsr);
221319      pTab->pSortCsr = 0;
221320    }
221321  
221322    if( rc!=SQLITE_OK ){
221323      sqlite3_finalize(pSorter->pStmt);
221324      sqlite3_free(pSorter);
221325      pCsr->pSorter = 0;
221326    }
221327  
221328    return rc;
221329  }
221330  
221331  static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
221332    int rc;
221333    Fts5Expr *pExpr = pCsr->pExpr;
221334    rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
221335    if( sqlite3Fts5ExprEof(pExpr) ){
221336      CsrFlagSet(pCsr, FTS5CSR_EOF);
221337    }
221338    fts5CsrNewrow(pCsr);
221339    return rc;
221340  }
221341  
221342  /*
221343  ** Process a "special" query. A special query is identified as one with a
221344  ** MATCH expression that begins with a '*' character. The remainder of
221345  ** the text passed to the MATCH operator are used as  the special query
221346  ** parameters.
221347  */
221348  static int fts5SpecialMatch(
221349    Fts5FullTable *pTab, 
221350    Fts5Cursor *pCsr, 
221351    const char *zQuery
221352  ){
221353    int rc = SQLITE_OK;             /* Return code */
221354    const char *z = zQuery;         /* Special query text */
221355    int n;                          /* Number of bytes in text at z */
221356  
221357    while( z[0]==' ' ) z++;
221358    for(n=0; z[n] && z[n]!=' '; n++);
221359  
221360    assert( pTab->p.base.zErrMsg==0 );
221361    pCsr->ePlan = FTS5_PLAN_SPECIAL;
221362  
221363    if( 0==sqlite3_strnicmp("reads", z, n) ){
221364      pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
221365    }
221366    else if( 0==sqlite3_strnicmp("id", z, n) ){
221367      pCsr->iSpecial = pCsr->iCsrId;
221368    }
221369    else{
221370      /* An unrecognized directive. Return an error message. */
221371      pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
221372      rc = SQLITE_ERROR;
221373    }
221374  
221375    return rc;
221376  }
221377  
221378  /*
221379  ** Search for an auxiliary function named zName that can be used with table
221380  ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
221381  ** structure. Otherwise, if no such function exists, return NULL.
221382  */
221383  static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
221384    Fts5Auxiliary *pAux;
221385  
221386    for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
221387      if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
221388    }
221389  
221390    /* No function of the specified name was found. Return 0. */
221391    return 0;
221392  }
221393  
221394  
221395  static int fts5FindRankFunction(Fts5Cursor *pCsr){
221396    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
221397    Fts5Config *pConfig = pTab->p.pConfig;
221398    int rc = SQLITE_OK;
221399    Fts5Auxiliary *pAux = 0;
221400    const char *zRank = pCsr->zRank;
221401    const char *zRankArgs = pCsr->zRankArgs;
221402  
221403    if( zRankArgs ){
221404      char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
221405      if( zSql ){
221406        sqlite3_stmt *pStmt = 0;
221407        rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
221408                                SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
221409        sqlite3_free(zSql);
221410        assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
221411        if( rc==SQLITE_OK ){
221412          if( SQLITE_ROW==sqlite3_step(pStmt) ){
221413            sqlite3_int64 nByte;
221414            pCsr->nRankArg = sqlite3_column_count(pStmt);
221415            nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
221416            pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
221417            if( rc==SQLITE_OK ){
221418              int i;
221419              for(i=0; i<pCsr->nRankArg; i++){
221420                pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
221421              }
221422            }
221423            pCsr->pRankArgStmt = pStmt;
221424          }else{
221425            rc = sqlite3_finalize(pStmt);
221426            assert( rc!=SQLITE_OK );
221427          }
221428        }
221429      }
221430    }
221431  
221432    if( rc==SQLITE_OK ){
221433      pAux = fts5FindAuxiliary(pTab, zRank);
221434      if( pAux==0 ){
221435        assert( pTab->p.base.zErrMsg==0 );
221436        pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
221437        rc = SQLITE_ERROR;
221438      }
221439    }
221440  
221441    pCsr->pRank = pAux;
221442    return rc;
221443  }
221444  
221445  
221446  static int fts5CursorParseRank(
221447    Fts5Config *pConfig,
221448    Fts5Cursor *pCsr, 
221449    sqlite3_value *pRank
221450  ){
221451    int rc = SQLITE_OK;
221452    if( pRank ){
221453      const char *z = (const char*)sqlite3_value_text(pRank);
221454      char *zRank = 0;
221455      char *zRankArgs = 0;
221456  
221457      if( z==0 ){
221458        if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
221459      }else{
221460        rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
221461      }
221462      if( rc==SQLITE_OK ){
221463        pCsr->zRank = zRank;
221464        pCsr->zRankArgs = zRankArgs;
221465        CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
221466      }else if( rc==SQLITE_ERROR ){
221467        pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
221468            "parse error in rank function: %s", z
221469        );
221470      }
221471    }else{
221472      if( pConfig->zRank ){
221473        pCsr->zRank = (char*)pConfig->zRank;
221474        pCsr->zRankArgs = (char*)pConfig->zRankArgs;
221475      }else{
221476        pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
221477        pCsr->zRankArgs = 0;
221478      }
221479    }
221480    return rc;
221481  }
221482  
221483  static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
221484    if( pVal ){
221485      int eType = sqlite3_value_numeric_type(pVal);
221486      if( eType==SQLITE_INTEGER ){
221487        return sqlite3_value_int64(pVal);
221488      }
221489    }
221490    return iDefault;
221491  }
221492  
221493  /*
221494  ** This is the xFilter interface for the virtual table.  See
221495  ** the virtual table xFilter method documentation for additional
221496  ** information.
221497  ** 
221498  ** There are three possible query strategies:
221499  **
221500  **   1. Full-text search using a MATCH operator.
221501  **   2. A by-rowid lookup.
221502  **   3. A full-table scan.
221503  */
221504  static int fts5FilterMethod(
221505    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
221506    int idxNum,                     /* Strategy index */
221507    const char *zUnused,            /* Unused */
221508    int nVal,                       /* Number of elements in apVal */
221509    sqlite3_value **apVal           /* Arguments for the indexing scheme */
221510  ){
221511    Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
221512    Fts5Config *pConfig = pTab->p.pConfig;
221513    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
221514    int rc = SQLITE_OK;             /* Error code */
221515    int iVal = 0;                   /* Counter for apVal[] */
221516    int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
221517    int bOrderByRank;               /* True if ORDER BY rank */
221518    sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
221519    sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
221520    sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
221521    sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
221522    sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
221523    int iCol;                       /* Column on LHS of MATCH operator */
221524    char **pzErrmsg = pConfig->pzErrmsg;
221525  
221526    UNUSED_PARAM(zUnused);
221527    UNUSED_PARAM(nVal);
221528  
221529    if( pCsr->ePlan ){
221530      fts5FreeCursorComponents(pCsr);
221531      memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
221532    }
221533  
221534    assert( pCsr->pStmt==0 );
221535    assert( pCsr->pExpr==0 );
221536    assert( pCsr->csrflags==0 );
221537    assert( pCsr->pRank==0 );
221538    assert( pCsr->zRank==0 );
221539    assert( pCsr->zRankArgs==0 );
221540  
221541    assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
221542    pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
221543  
221544    /* Decode the arguments passed through to this function.
221545    **
221546    ** Note: The following set of if(...) statements must be in the same
221547    ** order as the corresponding entries in the struct at the top of
221548    ** fts5BestIndexMethod().  */
221549    if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
221550    if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
221551    if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
221552    if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
221553    if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
221554    iCol = (idxNum>>16);
221555    assert( iCol>=0 && iCol<=pConfig->nCol );
221556    assert( iVal==nVal );
221557    bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
221558    pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
221559  
221560    /* Set the cursor upper and lower rowid limits. Only some strategies 
221561    ** actually use them. This is ok, as the xBestIndex() method leaves the
221562    ** sqlite3_index_constraint.omit flag clear for range constraints
221563    ** on the rowid field.  */
221564    if( pRowidEq ){
221565      pRowidLe = pRowidGe = pRowidEq;
221566    }
221567    if( bDesc ){
221568      pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
221569      pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
221570    }else{
221571      pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
221572      pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
221573    }
221574  
221575    if( pTab->pSortCsr ){
221576      /* If pSortCsr is non-NULL, then this call is being made as part of 
221577      ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
221578      ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
221579      ** return results to the user for this query. The current cursor 
221580      ** (pCursor) is used to execute the query issued by function 
221581      ** fts5CursorFirstSorted() above.  */
221582      assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
221583      assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
221584      assert( pCsr->iLastRowid==LARGEST_INT64 );
221585      assert( pCsr->iFirstRowid==SMALLEST_INT64 );
221586      if( pTab->pSortCsr->bDesc ){
221587        pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
221588        pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
221589      }else{
221590        pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
221591        pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
221592      }
221593      pCsr->ePlan = FTS5_PLAN_SOURCE;
221594      pCsr->pExpr = pTab->pSortCsr->pExpr;
221595      rc = fts5CursorFirst(pTab, pCsr, bDesc);
221596    }else if( pMatch ){
221597      const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
221598      if( zExpr==0 ) zExpr = "";
221599  
221600      rc = fts5CursorParseRank(pConfig, pCsr, pRank);
221601      if( rc==SQLITE_OK ){
221602        if( zExpr[0]=='*' ){
221603          /* The user has issued a query of the form "MATCH '*...'". This
221604          ** indicates that the MATCH expression is not a full text query,
221605          ** but a request for an internal parameter.  */
221606          rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
221607        }else{
221608          char **pzErr = &pTab->p.base.zErrMsg;
221609          rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
221610          if( rc==SQLITE_OK ){
221611            if( bOrderByRank ){
221612              pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
221613              rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
221614            }else{
221615              pCsr->ePlan = FTS5_PLAN_MATCH;
221616              rc = fts5CursorFirst(pTab, pCsr, bDesc);
221617            }
221618          }
221619        }
221620      }
221621    }else if( pConfig->zContent==0 ){
221622      *pConfig->pzErrmsg = sqlite3_mprintf(
221623          "%s: table does not support scanning", pConfig->zName
221624      );
221625      rc = SQLITE_ERROR;
221626    }else{
221627      /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
221628      ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
221629      pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
221630      rc = sqlite3Fts5StorageStmt(
221631          pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
221632      );
221633      if( rc==SQLITE_OK ){
221634        if( pCsr->ePlan==FTS5_PLAN_ROWID ){
221635          sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
221636        }else{
221637          sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
221638          sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
221639        }
221640        rc = fts5NextMethod(pCursor);
221641      }
221642    }
221643  
221644    pConfig->pzErrmsg = pzErrmsg;
221645    return rc;
221646  }
221647  
221648  /* 
221649  ** This is the xEof method of the virtual table. SQLite calls this 
221650  ** routine to find out if it has reached the end of a result set.
221651  */
221652  static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
221653    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
221654    return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
221655  }
221656  
221657  /*
221658  ** Return the rowid that the cursor currently points to.
221659  */
221660  static i64 fts5CursorRowid(Fts5Cursor *pCsr){
221661    assert( pCsr->ePlan==FTS5_PLAN_MATCH 
221662         || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH 
221663         || pCsr->ePlan==FTS5_PLAN_SOURCE 
221664    );
221665    if( pCsr->pSorter ){
221666      return pCsr->pSorter->iRowid;
221667    }else{
221668      return sqlite3Fts5ExprRowid(pCsr->pExpr);
221669    }
221670  }
221671  
221672  /* 
221673  ** This is the xRowid method. The SQLite core calls this routine to
221674  ** retrieve the rowid for the current row of the result set. fts5
221675  ** exposes %_content.rowid as the rowid for the virtual table. The
221676  ** rowid should be written to *pRowid.
221677  */
221678  static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
221679    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
221680    int ePlan = pCsr->ePlan;
221681    
221682    assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
221683    switch( ePlan ){
221684      case FTS5_PLAN_SPECIAL:
221685        *pRowid = 0;
221686        break;
221687  
221688      case FTS5_PLAN_SOURCE:
221689      case FTS5_PLAN_MATCH:
221690      case FTS5_PLAN_SORTED_MATCH:
221691        *pRowid = fts5CursorRowid(pCsr);
221692        break;
221693  
221694      default:
221695        *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
221696        break;
221697    }
221698  
221699    return SQLITE_OK;
221700  }
221701  
221702  /*
221703  ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
221704  ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
221705  **
221706  ** If argument bErrormsg is true and an error occurs, an error message may
221707  ** be left in sqlite3_vtab.zErrMsg.
221708  */
221709  static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
221710    int rc = SQLITE_OK;
221711  
221712    /* If the cursor does not yet have a statement handle, obtain one now. */ 
221713    if( pCsr->pStmt==0 ){
221714      Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
221715      int eStmt = fts5StmtType(pCsr);
221716      rc = sqlite3Fts5StorageStmt(
221717          pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
221718      );
221719      assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
221720      assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
221721    }
221722  
221723    if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
221724      assert( pCsr->pExpr );
221725      sqlite3_reset(pCsr->pStmt);
221726      sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
221727      rc = sqlite3_step(pCsr->pStmt);
221728      if( rc==SQLITE_ROW ){
221729        rc = SQLITE_OK;
221730        CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
221731      }else{
221732        rc = sqlite3_reset(pCsr->pStmt);
221733        if( rc==SQLITE_OK ){
221734          rc = FTS5_CORRUPT;
221735        }
221736      }
221737    }
221738    return rc;
221739  }
221740  
221741  static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
221742    va_list ap;                     /* ... printf arguments */
221743    va_start(ap, zFormat);
221744    assert( p->p.base.zErrMsg==0 );
221745    p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
221746    va_end(ap);
221747  }
221748  
221749  /*
221750  ** This function is called to handle an FTS INSERT command. In other words,
221751  ** an INSERT statement of the form:
221752  **
221753  **     INSERT INTO fts(fts) VALUES($pCmd)
221754  **     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
221755  **
221756  ** Argument pVal is the value assigned to column "fts" by the INSERT 
221757  ** statement. This function returns SQLITE_OK if successful, or an SQLite
221758  ** error code if an error occurs.
221759  **
221760  ** The commands implemented by this function are documented in the "Special
221761  ** INSERT Directives" section of the documentation. It should be updated if
221762  ** more commands are added to this function.
221763  */
221764  static int fts5SpecialInsert(
221765    Fts5FullTable *pTab,            /* Fts5 table object */
221766    const char *zCmd,               /* Text inserted into table-name column */
221767    sqlite3_value *pVal             /* Value inserted into rank column */
221768  ){
221769    Fts5Config *pConfig = pTab->p.pConfig;
221770    int rc = SQLITE_OK;
221771    int bError = 0;
221772  
221773    if( 0==sqlite3_stricmp("delete-all", zCmd) ){
221774      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
221775        fts5SetVtabError(pTab, 
221776            "'delete-all' may only be used with a "
221777            "contentless or external content fts5 table"
221778        );
221779        rc = SQLITE_ERROR;
221780      }else{
221781        rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
221782      }
221783    }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
221784      if( pConfig->eContent==FTS5_CONTENT_NONE ){
221785        fts5SetVtabError(pTab, 
221786            "'rebuild' may not be used with a contentless fts5 table"
221787        );
221788        rc = SQLITE_ERROR;
221789      }else{
221790        rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
221791      }
221792    }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
221793      rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
221794    }else if( 0==sqlite3_stricmp("merge", zCmd) ){
221795      int nMerge = sqlite3_value_int(pVal);
221796      rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
221797    }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
221798      rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
221799  #ifdef SQLITE_DEBUG
221800    }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
221801      pConfig->bPrefixIndex = sqlite3_value_int(pVal);
221802  #endif
221803    }else{
221804      rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
221805      if( rc==SQLITE_OK ){
221806        rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
221807      }
221808      if( rc==SQLITE_OK ){
221809        if( bError ){
221810          rc = SQLITE_ERROR;
221811        }else{
221812          rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
221813        }
221814      }
221815    }
221816    return rc;
221817  }
221818  
221819  static int fts5SpecialDelete(
221820    Fts5FullTable *pTab, 
221821    sqlite3_value **apVal
221822  ){
221823    int rc = SQLITE_OK;
221824    int eType1 = sqlite3_value_type(apVal[1]);
221825    if( eType1==SQLITE_INTEGER ){
221826      sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
221827      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
221828    }
221829    return rc;
221830  }
221831  
221832  static void fts5StorageInsert(
221833    int *pRc, 
221834    Fts5FullTable *pTab, 
221835    sqlite3_value **apVal, 
221836    i64 *piRowid
221837  ){
221838    int rc = *pRc;
221839    if( rc==SQLITE_OK ){
221840      rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
221841    }
221842    if( rc==SQLITE_OK ){
221843      rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
221844    }
221845    *pRc = rc;
221846  }
221847  
221848  /* 
221849  ** This function is the implementation of the xUpdate callback used by 
221850  ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
221851  ** inserted, updated or deleted.
221852  **
221853  ** A delete specifies a single argument - the rowid of the row to remove.
221854  ** 
221855  ** Update and insert operations pass:
221856  **
221857  **   1. The "old" rowid, or NULL.
221858  **   2. The "new" rowid.
221859  **   3. Values for each of the nCol matchable columns.
221860  **   4. Values for the two hidden columns (<tablename> and "rank").
221861  */
221862  static int fts5UpdateMethod(
221863    sqlite3_vtab *pVtab,            /* Virtual table handle */
221864    int nArg,                       /* Size of argument array */
221865    sqlite3_value **apVal,          /* Array of arguments */
221866    sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
221867  ){
221868    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
221869    Fts5Config *pConfig = pTab->p.pConfig;
221870    int eType0;                     /* value_type() of apVal[0] */
221871    int rc = SQLITE_OK;             /* Return code */
221872  
221873    /* A transaction must be open when this is called. */
221874    assert( pTab->ts.eState==1 );
221875  
221876    assert( pVtab->zErrMsg==0 );
221877    assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
221878    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER 
221879         || sqlite3_value_type(apVal[0])==SQLITE_NULL 
221880    );
221881    assert( pTab->p.pConfig->pzErrmsg==0 );
221882    pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
221883  
221884    /* Put any active cursors into REQUIRE_SEEK state. */
221885    fts5TripCursors(pTab);
221886  
221887    eType0 = sqlite3_value_type(apVal[0]);
221888    if( eType0==SQLITE_NULL 
221889     && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL 
221890    ){
221891      /* A "special" INSERT op. These are handled separately. */
221892      const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
221893      if( pConfig->eContent!=FTS5_CONTENT_NORMAL 
221894        && 0==sqlite3_stricmp("delete", z) 
221895      ){
221896        rc = fts5SpecialDelete(pTab, apVal);
221897      }else{
221898        rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
221899      }
221900    }else{
221901      /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
221902      ** any conflict on the rowid value must be detected before any 
221903      ** modifications are made to the database file. There are 4 cases:
221904      **
221905      **   1) DELETE
221906      **   2) UPDATE (rowid not modified)
221907      **   3) UPDATE (rowid modified)
221908      **   4) INSERT
221909      **
221910      ** Cases 3 and 4 may violate the rowid constraint.
221911      */
221912      int eConflict = SQLITE_ABORT;
221913      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
221914        eConflict = sqlite3_vtab_on_conflict(pConfig->db);
221915      }
221916  
221917      assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
221918      assert( nArg!=1 || eType0==SQLITE_INTEGER );
221919  
221920      /* Filter out attempts to run UPDATE or DELETE on contentless tables.
221921      ** This is not suported.  */
221922      if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
221923        pTab->p.base.zErrMsg = sqlite3_mprintf(
221924            "cannot %s contentless fts5 table: %s", 
221925            (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
221926        );
221927        rc = SQLITE_ERROR;
221928      }
221929  
221930      /* DELETE */
221931      else if( nArg==1 ){
221932        i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
221933        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
221934      }
221935  
221936      /* INSERT or UPDATE */
221937      else{
221938        int eType1 = sqlite3_value_numeric_type(apVal[1]);
221939  
221940        if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
221941          rc = SQLITE_MISMATCH;
221942        }
221943  
221944        else if( eType0!=SQLITE_INTEGER ){     
221945          /* If this is a REPLACE, first remove the current entry (if any) */
221946          if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
221947            i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
221948            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
221949          }
221950          fts5StorageInsert(&rc, pTab, apVal, pRowid);
221951        }
221952  
221953        /* UPDATE */
221954        else{
221955          i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
221956          i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
221957          if( eType1==SQLITE_INTEGER && iOld!=iNew ){
221958            if( eConflict==SQLITE_REPLACE ){
221959              rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
221960              if( rc==SQLITE_OK ){
221961                rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
221962              }
221963              fts5StorageInsert(&rc, pTab, apVal, pRowid);
221964            }else{
221965              rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
221966              if( rc==SQLITE_OK ){
221967                rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
221968              }
221969              if( rc==SQLITE_OK ){
221970                rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
221971              }
221972            }
221973          }else{
221974            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
221975            fts5StorageInsert(&rc, pTab, apVal, pRowid);
221976          }
221977        }
221978      }
221979    }
221980  
221981    pTab->p.pConfig->pzErrmsg = 0;
221982    return rc;
221983  }
221984  
221985  /*
221986  ** Implementation of xSync() method. 
221987  */
221988  static int fts5SyncMethod(sqlite3_vtab *pVtab){
221989    int rc;
221990    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
221991    fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
221992    pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
221993    fts5TripCursors(pTab);
221994    rc = sqlite3Fts5StorageSync(pTab->pStorage);
221995    pTab->p.pConfig->pzErrmsg = 0;
221996    return rc;
221997  }
221998  
221999  /*
222000  ** Implementation of xBegin() method. 
222001  */
222002  static int fts5BeginMethod(sqlite3_vtab *pVtab){
222003    fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
222004    fts5NewTransaction((Fts5FullTable*)pVtab);
222005    return SQLITE_OK;
222006  }
222007  
222008  /*
222009  ** Implementation of xCommit() method. This is a no-op. The contents of
222010  ** the pending-terms hash-table have already been flushed into the database
222011  ** by fts5SyncMethod().
222012  */
222013  static int fts5CommitMethod(sqlite3_vtab *pVtab){
222014    UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
222015    fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
222016    return SQLITE_OK;
222017  }
222018  
222019  /*
222020  ** Implementation of xRollback(). Discard the contents of the pending-terms
222021  ** hash-table. Any changes made to the database are reverted by SQLite.
222022  */
222023  static int fts5RollbackMethod(sqlite3_vtab *pVtab){
222024    int rc;
222025    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
222026    fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
222027    rc = sqlite3Fts5StorageRollback(pTab->pStorage);
222028    return rc;
222029  }
222030  
222031  static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
222032  
222033  static void *fts5ApiUserData(Fts5Context *pCtx){
222034    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222035    return pCsr->pAux->pUserData;
222036  }
222037  
222038  static int fts5ApiColumnCount(Fts5Context *pCtx){
222039    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222040    return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
222041  }
222042  
222043  static int fts5ApiColumnTotalSize(
222044    Fts5Context *pCtx, 
222045    int iCol, 
222046    sqlite3_int64 *pnToken
222047  ){
222048    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222049    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
222050    return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
222051  }
222052  
222053  static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
222054    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222055    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
222056    return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
222057  }
222058  
222059  static int fts5ApiTokenize(
222060    Fts5Context *pCtx, 
222061    const char *pText, int nText, 
222062    void *pUserData,
222063    int (*xToken)(void*, int, const char*, int, int, int)
222064  ){
222065    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222066    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
222067    return sqlite3Fts5Tokenize(
222068        pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
222069    );
222070  }
222071  
222072  static int fts5ApiPhraseCount(Fts5Context *pCtx){
222073    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222074    return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
222075  }
222076  
222077  static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
222078    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222079    return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
222080  }
222081  
222082  static int fts5ApiColumnText(
222083    Fts5Context *pCtx, 
222084    int iCol, 
222085    const char **pz, 
222086    int *pn
222087  ){
222088    int rc = SQLITE_OK;
222089    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222090    if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab)) 
222091     || pCsr->ePlan==FTS5_PLAN_SPECIAL 
222092    ){
222093      *pz = 0;
222094      *pn = 0;
222095    }else{
222096      rc = fts5SeekCursor(pCsr, 0);
222097      if( rc==SQLITE_OK ){
222098        *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
222099        *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
222100      }
222101    }
222102    return rc;
222103  }
222104  
222105  static int fts5CsrPoslist(
222106    Fts5Cursor *pCsr, 
222107    int iPhrase, 
222108    const u8 **pa,
222109    int *pn
222110  ){
222111    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
222112    int rc = SQLITE_OK;
222113    int bLive = (pCsr->pSorter==0);
222114  
222115    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
222116  
222117      if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
222118        Fts5PoslistPopulator *aPopulator;
222119        int i;
222120        aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
222121        if( aPopulator==0 ) rc = SQLITE_NOMEM;
222122        for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
222123          int n; const char *z;
222124          rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
222125          if( rc==SQLITE_OK ){
222126            rc = sqlite3Fts5ExprPopulatePoslists(
222127                pConfig, pCsr->pExpr, aPopulator, i, z, n
222128            );
222129          }
222130        }
222131        sqlite3_free(aPopulator);
222132  
222133        if( pCsr->pSorter ){
222134          sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
222135        }
222136      }
222137      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
222138    }
222139  
222140    if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
222141      Fts5Sorter *pSorter = pCsr->pSorter;
222142      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
222143      *pn = pSorter->aIdx[iPhrase] - i1;
222144      *pa = &pSorter->aPoslist[i1];
222145    }else{
222146      *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
222147    }
222148  
222149    return rc;
222150  }
222151  
222152  /*
222153  ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
222154  ** correctly for the current view. Return SQLITE_OK if successful, or an
222155  ** SQLite error code otherwise.
222156  */
222157  static int fts5CacheInstArray(Fts5Cursor *pCsr){
222158    int rc = SQLITE_OK;
222159    Fts5PoslistReader *aIter;       /* One iterator for each phrase */
222160    int nIter;                      /* Number of iterators/phrases */
222161    int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
222162    
222163    nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
222164    if( pCsr->aInstIter==0 ){
222165      sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
222166      pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
222167    }
222168    aIter = pCsr->aInstIter;
222169  
222170    if( aIter ){
222171      int nInst = 0;                /* Number instances seen so far */
222172      int i;
222173  
222174      /* Initialize all iterators */
222175      for(i=0; i<nIter && rc==SQLITE_OK; i++){
222176        const u8 *a;
222177        int n; 
222178        rc = fts5CsrPoslist(pCsr, i, &a, &n);
222179        if( rc==SQLITE_OK ){
222180          sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
222181        }
222182      }
222183  
222184      if( rc==SQLITE_OK ){
222185        while( 1 ){
222186          int *aInst;
222187          int iBest = -1;
222188          for(i=0; i<nIter; i++){
222189            if( (aIter[i].bEof==0) 
222190                && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) 
222191              ){
222192              iBest = i;
222193            }
222194          }
222195          if( iBest<0 ) break;
222196  
222197          nInst++;
222198          if( nInst>=pCsr->nInstAlloc ){
222199            pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
222200            aInst = (int*)sqlite3_realloc64(
222201                pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
222202                );
222203            if( aInst ){
222204              pCsr->aInst = aInst;
222205            }else{
222206              rc = SQLITE_NOMEM;
222207              break;
222208            }
222209          }
222210  
222211          aInst = &pCsr->aInst[3 * (nInst-1)];
222212          aInst[0] = iBest;
222213          aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
222214          aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
222215          if( aInst[1]<0 || aInst[1]>=nCol ){
222216            rc = FTS5_CORRUPT;
222217            break;
222218          }
222219          sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
222220        }
222221      }
222222  
222223      pCsr->nInstCount = nInst;
222224      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
222225    }
222226    return rc;
222227  }
222228  
222229  static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
222230    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222231    int rc = SQLITE_OK;
222232    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
222233     || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
222234      *pnInst = pCsr->nInstCount;
222235    }
222236    return rc;
222237  }
222238  
222239  static int fts5ApiInst(
222240    Fts5Context *pCtx, 
222241    int iIdx, 
222242    int *piPhrase, 
222243    int *piCol, 
222244    int *piOff
222245  ){
222246    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222247    int rc = SQLITE_OK;
222248    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
222249     || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) 
222250    ){
222251      if( iIdx<0 || iIdx>=pCsr->nInstCount ){
222252        rc = SQLITE_RANGE;
222253  #if 0
222254      }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
222255        *piPhrase = pCsr->aInst[iIdx*3];
222256        *piCol = pCsr->aInst[iIdx*3 + 2];
222257        *piOff = -1;
222258  #endif
222259      }else{
222260        *piPhrase = pCsr->aInst[iIdx*3];
222261        *piCol = pCsr->aInst[iIdx*3 + 1];
222262        *piOff = pCsr->aInst[iIdx*3 + 2];
222263      }
222264    }
222265    return rc;
222266  }
222267  
222268  static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
222269    return fts5CursorRowid((Fts5Cursor*)pCtx);
222270  }
222271  
222272  static int fts5ColumnSizeCb(
222273    void *pContext,                 /* Pointer to int */
222274    int tflags,
222275    const char *pUnused,            /* Buffer containing token */
222276    int nUnused,                    /* Size of token in bytes */
222277    int iUnused1,                   /* Start offset of token */
222278    int iUnused2                    /* End offset of token */
222279  ){
222280    int *pCnt = (int*)pContext;
222281    UNUSED_PARAM2(pUnused, nUnused);
222282    UNUSED_PARAM2(iUnused1, iUnused2);
222283    if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
222284      (*pCnt)++;
222285    }
222286    return SQLITE_OK;
222287  }
222288  
222289  static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
222290    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222291    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
222292    Fts5Config *pConfig = pTab->p.pConfig;
222293    int rc = SQLITE_OK;
222294  
222295    if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
222296      if( pConfig->bColumnsize ){
222297        i64 iRowid = fts5CursorRowid(pCsr);
222298        rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
222299      }else if( pConfig->zContent==0 ){
222300        int i;
222301        for(i=0; i<pConfig->nCol; i++){
222302          if( pConfig->abUnindexed[i]==0 ){
222303            pCsr->aColumnSize[i] = -1;
222304          }
222305        }
222306      }else{
222307        int i;
222308        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
222309          if( pConfig->abUnindexed[i]==0 ){
222310            const char *z; int n;
222311            void *p = (void*)(&pCsr->aColumnSize[i]);
222312            pCsr->aColumnSize[i] = 0;
222313            rc = fts5ApiColumnText(pCtx, i, &z, &n);
222314            if( rc==SQLITE_OK ){
222315              rc = sqlite3Fts5Tokenize(
222316                  pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
222317              );
222318            }
222319          }
222320        }
222321      }
222322      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
222323    }
222324    if( iCol<0 ){
222325      int i;
222326      *pnToken = 0;
222327      for(i=0; i<pConfig->nCol; i++){
222328        *pnToken += pCsr->aColumnSize[i];
222329      }
222330    }else if( iCol<pConfig->nCol ){
222331      *pnToken = pCsr->aColumnSize[iCol];
222332    }else{
222333      *pnToken = 0;
222334      rc = SQLITE_RANGE;
222335    }
222336    return rc;
222337  }
222338  
222339  /*
222340  ** Implementation of the xSetAuxdata() method.
222341  */
222342  static int fts5ApiSetAuxdata(
222343    Fts5Context *pCtx,              /* Fts5 context */
222344    void *pPtr,                     /* Pointer to save as auxdata */
222345    void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
222346  ){
222347    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222348    Fts5Auxdata *pData;
222349  
222350    /* Search through the cursors list of Fts5Auxdata objects for one that
222351    ** corresponds to the currently executing auxiliary function.  */
222352    for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
222353      if( pData->pAux==pCsr->pAux ) break;
222354    }
222355  
222356    if( pData ){
222357      if( pData->xDelete ){
222358        pData->xDelete(pData->pPtr);
222359      }
222360    }else{
222361      int rc = SQLITE_OK;
222362      pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
222363      if( pData==0 ){
222364        if( xDelete ) xDelete(pPtr);
222365        return rc;
222366      }
222367      pData->pAux = pCsr->pAux;
222368      pData->pNext = pCsr->pAuxdata;
222369      pCsr->pAuxdata = pData;
222370    }
222371  
222372    pData->xDelete = xDelete;
222373    pData->pPtr = pPtr;
222374    return SQLITE_OK;
222375  }
222376  
222377  static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
222378    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222379    Fts5Auxdata *pData;
222380    void *pRet = 0;
222381  
222382    for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
222383      if( pData->pAux==pCsr->pAux ) break;
222384    }
222385  
222386    if( pData ){
222387      pRet = pData->pPtr;
222388      if( bClear ){
222389        pData->pPtr = 0;
222390        pData->xDelete = 0;
222391      }
222392    }
222393  
222394    return pRet;
222395  }
222396  
222397  static void fts5ApiPhraseNext(
222398    Fts5Context *pUnused, 
222399    Fts5PhraseIter *pIter, 
222400    int *piCol, int *piOff
222401  ){
222402    UNUSED_PARAM(pUnused);
222403    if( pIter->a>=pIter->b ){
222404      *piCol = -1;
222405      *piOff = -1;
222406    }else{
222407      int iVal;
222408      pIter->a += fts5GetVarint32(pIter->a, iVal);
222409      if( iVal==1 ){
222410        pIter->a += fts5GetVarint32(pIter->a, iVal);
222411        *piCol = iVal;
222412        *piOff = 0;
222413        pIter->a += fts5GetVarint32(pIter->a, iVal);
222414      }
222415      *piOff += (iVal-2);
222416    }
222417  }
222418  
222419  static int fts5ApiPhraseFirst(
222420    Fts5Context *pCtx, 
222421    int iPhrase, 
222422    Fts5PhraseIter *pIter, 
222423    int *piCol, int *piOff
222424  ){
222425    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222426    int n;
222427    int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
222428    if( rc==SQLITE_OK ){
222429      pIter->b = &pIter->a[n];
222430      *piCol = 0;
222431      *piOff = 0;
222432      fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
222433    }
222434    return rc;
222435  }
222436  
222437  static void fts5ApiPhraseNextColumn(
222438    Fts5Context *pCtx, 
222439    Fts5PhraseIter *pIter, 
222440    int *piCol
222441  ){
222442    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222443    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
222444  
222445    if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
222446      if( pIter->a>=pIter->b ){
222447        *piCol = -1;
222448      }else{
222449        int iIncr;
222450        pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
222451        *piCol += (iIncr-2);
222452      }
222453    }else{
222454      while( 1 ){
222455        int dummy;
222456        if( pIter->a>=pIter->b ){
222457          *piCol = -1;
222458          return;
222459        }
222460        if( pIter->a[0]==0x01 ) break;
222461        pIter->a += fts5GetVarint32(pIter->a, dummy);
222462      }
222463      pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
222464    }
222465  }
222466  
222467  static int fts5ApiPhraseFirstColumn(
222468    Fts5Context *pCtx, 
222469    int iPhrase, 
222470    Fts5PhraseIter *pIter, 
222471    int *piCol
222472  ){
222473    int rc = SQLITE_OK;
222474    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222475    Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
222476  
222477    if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
222478      Fts5Sorter *pSorter = pCsr->pSorter;
222479      int n;
222480      if( pSorter ){
222481        int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
222482        n = pSorter->aIdx[iPhrase] - i1;
222483        pIter->a = &pSorter->aPoslist[i1];
222484      }else{
222485        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
222486      }
222487      if( rc==SQLITE_OK ){
222488        pIter->b = &pIter->a[n];
222489        *piCol = 0;
222490        fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
222491      }
222492    }else{
222493      int n;
222494      rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
222495      if( rc==SQLITE_OK ){
222496        pIter->b = &pIter->a[n];
222497        if( n<=0 ){
222498          *piCol = -1;
222499        }else if( pIter->a[0]==0x01 ){
222500          pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
222501        }else{
222502          *piCol = 0;
222503        }
222504      }
222505    }
222506  
222507    return rc;
222508  }
222509  
222510  
222511  static int fts5ApiQueryPhrase(Fts5Context*, int, void*, 
222512      int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
222513  );
222514  
222515  static const Fts5ExtensionApi sFts5Api = {
222516    2,                            /* iVersion */
222517    fts5ApiUserData,
222518    fts5ApiColumnCount,
222519    fts5ApiRowCount,
222520    fts5ApiColumnTotalSize,
222521    fts5ApiTokenize,
222522    fts5ApiPhraseCount,
222523    fts5ApiPhraseSize,
222524    fts5ApiInstCount,
222525    fts5ApiInst,
222526    fts5ApiRowid,
222527    fts5ApiColumnText,
222528    fts5ApiColumnSize,
222529    fts5ApiQueryPhrase,
222530    fts5ApiSetAuxdata,
222531    fts5ApiGetAuxdata,
222532    fts5ApiPhraseFirst,
222533    fts5ApiPhraseNext,
222534    fts5ApiPhraseFirstColumn,
222535    fts5ApiPhraseNextColumn,
222536  };
222537  
222538  /*
222539  ** Implementation of API function xQueryPhrase().
222540  */
222541  static int fts5ApiQueryPhrase(
222542    Fts5Context *pCtx, 
222543    int iPhrase, 
222544    void *pUserData,
222545    int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
222546  ){
222547    Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
222548    Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
222549    int rc;
222550    Fts5Cursor *pNew = 0;
222551  
222552    rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
222553    if( rc==SQLITE_OK ){
222554      pNew->ePlan = FTS5_PLAN_MATCH;
222555      pNew->iFirstRowid = SMALLEST_INT64;
222556      pNew->iLastRowid = LARGEST_INT64;
222557      pNew->base.pVtab = (sqlite3_vtab*)pTab;
222558      rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
222559    }
222560  
222561    if( rc==SQLITE_OK ){
222562      for(rc = fts5CursorFirst(pTab, pNew, 0);
222563          rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
222564          rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
222565      ){
222566        rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
222567        if( rc!=SQLITE_OK ){
222568          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
222569          break;
222570        }
222571      }
222572    }
222573  
222574    fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
222575    return rc;
222576  }
222577  
222578  static void fts5ApiInvoke(
222579    Fts5Auxiliary *pAux,
222580    Fts5Cursor *pCsr,
222581    sqlite3_context *context,
222582    int argc,
222583    sqlite3_value **argv
222584  ){
222585    assert( pCsr->pAux==0 );
222586    pCsr->pAux = pAux;
222587    pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
222588    pCsr->pAux = 0;
222589  }
222590  
222591  static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
222592    Fts5Cursor *pCsr;
222593    for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
222594      if( pCsr->iCsrId==iCsrId ) break;
222595    }
222596    return pCsr;
222597  }
222598  
222599  static void fts5ApiCallback(
222600    sqlite3_context *context,
222601    int argc,
222602    sqlite3_value **argv
222603  ){
222604  
222605    Fts5Auxiliary *pAux;
222606    Fts5Cursor *pCsr;
222607    i64 iCsrId;
222608  
222609    assert( argc>=1 );
222610    pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
222611    iCsrId = sqlite3_value_int64(argv[0]);
222612  
222613    pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
222614    if( pCsr==0 ){
222615      char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
222616      sqlite3_result_error(context, zErr, -1);
222617      sqlite3_free(zErr);
222618    }else{
222619      fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
222620    }
222621  }
222622  
222623  
222624  /*
222625  ** Given cursor id iId, return a pointer to the corresponding Fts5Table 
222626  ** object. Or NULL If the cursor id does not exist.
222627  */
222628  static Fts5Table *sqlite3Fts5TableFromCsrid(
222629    Fts5Global *pGlobal,            /* FTS5 global context for db handle */
222630    i64 iCsrId                      /* Id of cursor to find */
222631  ){
222632    Fts5Cursor *pCsr;
222633    pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
222634    if( pCsr ){
222635      return (Fts5Table*)pCsr->base.pVtab;
222636    }
222637    return 0;
222638  }
222639  
222640  /*
222641  ** Return a "position-list blob" corresponding to the current position of
222642  ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
222643  ** the current position-list for each phrase in the query associated with
222644  ** cursor pCsr.
222645  **
222646  ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
222647  ** the number of phrases in the query. Following the varints are the
222648  ** concatenated position lists for each phrase, in order.
222649  **
222650  ** The first varint (if it exists) contains the size of the position list
222651  ** for phrase 0. The second (same disclaimer) contains the size of position
222652  ** list 1. And so on. There is no size field for the final position list,
222653  ** as it can be derived from the total size of the blob.
222654  */
222655  static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
222656    int i;
222657    int rc = SQLITE_OK;
222658    int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
222659    Fts5Buffer val;
222660  
222661    memset(&val, 0, sizeof(Fts5Buffer));
222662    switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
222663      case FTS5_DETAIL_FULL:
222664  
222665        /* Append the varints */
222666        for(i=0; i<(nPhrase-1); i++){
222667          const u8 *dummy;
222668          int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
222669          sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
222670        }
222671  
222672        /* Append the position lists */
222673        for(i=0; i<nPhrase; i++){
222674          const u8 *pPoslist;
222675          int nPoslist;
222676          nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
222677          sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
222678        }
222679        break;
222680  
222681      case FTS5_DETAIL_COLUMNS:
222682  
222683        /* Append the varints */
222684        for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
222685          const u8 *dummy;
222686          int nByte;
222687          rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
222688          sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
222689        }
222690  
222691        /* Append the position lists */
222692        for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
222693          const u8 *pPoslist;
222694          int nPoslist;
222695          rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
222696          sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
222697        }
222698        break;
222699  
222700      default:
222701        break;
222702    }
222703  
222704    sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
222705    return rc;
222706  }
222707  
222708  /* 
222709  ** This is the xColumn method, called by SQLite to request a value from
222710  ** the row that the supplied cursor currently points to.
222711  */
222712  static int fts5ColumnMethod(
222713    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
222714    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
222715    int iCol                        /* Index of column to read value from */
222716  ){
222717    Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
222718    Fts5Config *pConfig = pTab->p.pConfig;
222719    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
222720    int rc = SQLITE_OK;
222721    
222722    assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
222723  
222724    if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
222725      if( iCol==pConfig->nCol ){
222726        sqlite3_result_int64(pCtx, pCsr->iSpecial);
222727      }
222728    }else
222729  
222730    if( iCol==pConfig->nCol ){
222731      /* User is requesting the value of the special column with the same name
222732      ** as the table. Return the cursor integer id number. This value is only
222733      ** useful in that it may be passed as the first argument to an FTS5
222734      ** auxiliary function.  */
222735      sqlite3_result_int64(pCtx, pCsr->iCsrId);
222736    }else if( iCol==pConfig->nCol+1 ){
222737  
222738      /* The value of the "rank" column. */
222739      if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
222740        fts5PoslistBlob(pCtx, pCsr);
222741      }else if( 
222742          pCsr->ePlan==FTS5_PLAN_MATCH
222743       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
222744      ){
222745        if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
222746          fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
222747        }
222748      }
222749    }else if( !fts5IsContentless(pTab) ){
222750      rc = fts5SeekCursor(pCsr, 1);
222751      if( rc==SQLITE_OK ){
222752        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
222753      }
222754    }
222755    return rc;
222756  }
222757  
222758  
222759  /*
222760  ** This routine implements the xFindFunction method for the FTS3
222761  ** virtual table.
222762  */
222763  static int fts5FindFunctionMethod(
222764    sqlite3_vtab *pVtab,            /* Virtual table handle */
222765    int nUnused,                    /* Number of SQL function arguments */
222766    const char *zName,              /* Name of SQL function */
222767    void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
222768    void **ppArg                    /* OUT: User data for *pxFunc */
222769  ){
222770    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
222771    Fts5Auxiliary *pAux;
222772  
222773    UNUSED_PARAM(nUnused);
222774    pAux = fts5FindAuxiliary(pTab, zName);
222775    if( pAux ){
222776      *pxFunc = fts5ApiCallback;
222777      *ppArg = (void*)pAux;
222778      return 1;
222779    }
222780  
222781    /* No function of the specified name was found. Return 0. */
222782    return 0;
222783  }
222784  
222785  /*
222786  ** Implementation of FTS5 xRename method. Rename an fts5 table.
222787  */
222788  static int fts5RenameMethod(
222789    sqlite3_vtab *pVtab,            /* Virtual table handle */
222790    const char *zName               /* New name of table */
222791  ){
222792    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
222793    return sqlite3Fts5StorageRename(pTab->pStorage, zName);
222794  }
222795  
222796  static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
222797    fts5TripCursors((Fts5FullTable*)pTab);
222798    return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
222799  }
222800  
222801  /*
222802  ** The xSavepoint() method.
222803  **
222804  ** Flush the contents of the pending-terms table to disk.
222805  */
222806  static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
222807    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
222808    fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
222809    return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
222810  }
222811  
222812  /*
222813  ** The xRelease() method.
222814  **
222815  ** This is a no-op.
222816  */
222817  static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
222818    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
222819    fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
222820    return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
222821  }
222822  
222823  /*
222824  ** The xRollbackTo() method.
222825  **
222826  ** Discard the contents of the pending terms table.
222827  */
222828  static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
222829    Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
222830    UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
222831    fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
222832    fts5TripCursors(pTab);
222833    return sqlite3Fts5StorageRollback(pTab->pStorage);
222834  }
222835  
222836  /*
222837  ** Register a new auxiliary function with global context pGlobal.
222838  */
222839  static int fts5CreateAux(
222840    fts5_api *pApi,                 /* Global context (one per db handle) */
222841    const char *zName,              /* Name of new function */
222842    void *pUserData,                /* User data for aux. function */
222843    fts5_extension_function xFunc,  /* Aux. function implementation */
222844    void(*xDestroy)(void*)          /* Destructor for pUserData */
222845  ){
222846    Fts5Global *pGlobal = (Fts5Global*)pApi;
222847    int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
222848    if( rc==SQLITE_OK ){
222849      Fts5Auxiliary *pAux;
222850      int nName;                      /* Size of zName in bytes, including \0 */
222851      int nByte;                      /* Bytes of space to allocate */
222852  
222853      nName = (int)strlen(zName) + 1;
222854      nByte = sizeof(Fts5Auxiliary) + nName;
222855      pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
222856      if( pAux ){
222857        memset(pAux, 0, nByte);
222858        pAux->zFunc = (char*)&pAux[1];
222859        memcpy(pAux->zFunc, zName, nName);
222860        pAux->pGlobal = pGlobal;
222861        pAux->pUserData = pUserData;
222862        pAux->xFunc = xFunc;
222863        pAux->xDestroy = xDestroy;
222864        pAux->pNext = pGlobal->pAux;
222865        pGlobal->pAux = pAux;
222866      }else{
222867        rc = SQLITE_NOMEM;
222868      }
222869    }
222870  
222871    return rc;
222872  }
222873  
222874  /*
222875  ** Register a new tokenizer. This is the implementation of the 
222876  ** fts5_api.xCreateTokenizer() method.
222877  */
222878  static int fts5CreateTokenizer(
222879    fts5_api *pApi,                 /* Global context (one per db handle) */
222880    const char *zName,              /* Name of new function */
222881    void *pUserData,                /* User data for aux. function */
222882    fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
222883    void(*xDestroy)(void*)          /* Destructor for pUserData */
222884  ){
222885    Fts5Global *pGlobal = (Fts5Global*)pApi;
222886    Fts5TokenizerModule *pNew;
222887    int nName;                      /* Size of zName and its \0 terminator */
222888    int nByte;                      /* Bytes of space to allocate */
222889    int rc = SQLITE_OK;
222890  
222891    nName = (int)strlen(zName) + 1;
222892    nByte = sizeof(Fts5TokenizerModule) + nName;
222893    pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
222894    if( pNew ){
222895      memset(pNew, 0, nByte);
222896      pNew->zName = (char*)&pNew[1];
222897      memcpy(pNew->zName, zName, nName);
222898      pNew->pUserData = pUserData;
222899      pNew->x = *pTokenizer;
222900      pNew->xDestroy = xDestroy;
222901      pNew->pNext = pGlobal->pTok;
222902      pGlobal->pTok = pNew;
222903      if( pNew->pNext==0 ){
222904        pGlobal->pDfltTok = pNew;
222905      }
222906    }else{
222907      rc = SQLITE_NOMEM;
222908    }
222909  
222910    return rc;
222911  }
222912  
222913  static Fts5TokenizerModule *fts5LocateTokenizer(
222914    Fts5Global *pGlobal, 
222915    const char *zName
222916  ){
222917    Fts5TokenizerModule *pMod = 0;
222918  
222919    if( zName==0 ){
222920      pMod = pGlobal->pDfltTok;
222921    }else{
222922      for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
222923        if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
222924      }
222925    }
222926  
222927    return pMod;
222928  }
222929  
222930  /*
222931  ** Find a tokenizer. This is the implementation of the 
222932  ** fts5_api.xFindTokenizer() method.
222933  */
222934  static int fts5FindTokenizer(
222935    fts5_api *pApi,                 /* Global context (one per db handle) */
222936    const char *zName,              /* Name of new function */
222937    void **ppUserData,
222938    fts5_tokenizer *pTokenizer      /* Populate this object */
222939  ){
222940    int rc = SQLITE_OK;
222941    Fts5TokenizerModule *pMod;
222942  
222943    pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
222944    if( pMod ){
222945      *pTokenizer = pMod->x;
222946      *ppUserData = pMod->pUserData;
222947    }else{
222948      memset(pTokenizer, 0, sizeof(fts5_tokenizer));
222949      rc = SQLITE_ERROR;
222950    }
222951  
222952    return rc;
222953  }
222954  
222955  static int sqlite3Fts5GetTokenizer(
222956    Fts5Global *pGlobal, 
222957    const char **azArg,
222958    int nArg,
222959    Fts5Tokenizer **ppTok,
222960    fts5_tokenizer **ppTokApi,
222961    char **pzErr
222962  ){
222963    Fts5TokenizerModule *pMod;
222964    int rc = SQLITE_OK;
222965  
222966    pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
222967    if( pMod==0 ){
222968      assert( nArg>0 );
222969      rc = SQLITE_ERROR;
222970      *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
222971    }else{
222972      rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
222973      *ppTokApi = &pMod->x;
222974      if( rc!=SQLITE_OK && pzErr ){
222975        *pzErr = sqlite3_mprintf("error in tokenizer constructor");
222976      }
222977    }
222978  
222979    if( rc!=SQLITE_OK ){
222980      *ppTokApi = 0;
222981      *ppTok = 0;
222982    }
222983  
222984    return rc;
222985  }
222986  
222987  static void fts5ModuleDestroy(void *pCtx){
222988    Fts5TokenizerModule *pTok, *pNextTok;
222989    Fts5Auxiliary *pAux, *pNextAux;
222990    Fts5Global *pGlobal = (Fts5Global*)pCtx;
222991  
222992    for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
222993      pNextAux = pAux->pNext;
222994      if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
222995      sqlite3_free(pAux);
222996    }
222997  
222998    for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
222999      pNextTok = pTok->pNext;
223000      if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
223001      sqlite3_free(pTok);
223002    }
223003  
223004    sqlite3_free(pGlobal);
223005  }
223006  
223007  static void fts5Fts5Func(
223008    sqlite3_context *pCtx,          /* Function call context */
223009    int nArg,                       /* Number of args */
223010    sqlite3_value **apArg           /* Function arguments */
223011  ){
223012    Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
223013    fts5_api **ppApi;
223014    UNUSED_PARAM(nArg);
223015    assert( nArg==1 );
223016    ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
223017    if( ppApi ) *ppApi = &pGlobal->api;
223018  }
223019  
223020  /*
223021  ** Implementation of fts5_source_id() function.
223022  */
223023  static void fts5SourceIdFunc(
223024    sqlite3_context *pCtx,          /* Function call context */
223025    int nArg,                       /* Number of args */
223026    sqlite3_value **apUnused        /* Function arguments */
223027  ){
223028    assert( nArg==0 );
223029    UNUSED_PARAM2(nArg, apUnused);
223030    sqlite3_result_text(pCtx, "fts5: 2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0f6d7", -1, SQLITE_TRANSIENT);
223031  }
223032  
223033  /*
223034  ** Return true if zName is the extension on one of the shadow tables used
223035  ** by this module.
223036  */
223037  static int fts5ShadowName(const char *zName){
223038    static const char *azName[] = {
223039      "config", "content", "data", "docsize", "idx"
223040    };
223041    unsigned int i;
223042    for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
223043      if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
223044    }
223045    return 0;
223046  }
223047  
223048  static int fts5Init(sqlite3 *db){
223049    static const sqlite3_module fts5Mod = {
223050      /* iVersion      */ 3,
223051      /* xCreate       */ fts5CreateMethod,
223052      /* xConnect      */ fts5ConnectMethod,
223053      /* xBestIndex    */ fts5BestIndexMethod,
223054      /* xDisconnect   */ fts5DisconnectMethod,
223055      /* xDestroy      */ fts5DestroyMethod,
223056      /* xOpen         */ fts5OpenMethod,
223057      /* xClose        */ fts5CloseMethod,
223058      /* xFilter       */ fts5FilterMethod,
223059      /* xNext         */ fts5NextMethod,
223060      /* xEof          */ fts5EofMethod,
223061      /* xColumn       */ fts5ColumnMethod,
223062      /* xRowid        */ fts5RowidMethod,
223063      /* xUpdate       */ fts5UpdateMethod,
223064      /* xBegin        */ fts5BeginMethod,
223065      /* xSync         */ fts5SyncMethod,
223066      /* xCommit       */ fts5CommitMethod,
223067      /* xRollback     */ fts5RollbackMethod,
223068      /* xFindFunction */ fts5FindFunctionMethod,
223069      /* xRename       */ fts5RenameMethod,
223070      /* xSavepoint    */ fts5SavepointMethod,
223071      /* xRelease      */ fts5ReleaseMethod,
223072      /* xRollbackTo   */ fts5RollbackToMethod,
223073      /* xShadowName   */ fts5ShadowName
223074    };
223075  
223076    int rc;
223077    Fts5Global *pGlobal = 0;
223078  
223079    pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
223080    if( pGlobal==0 ){
223081      rc = SQLITE_NOMEM;
223082    }else{
223083      void *p = (void*)pGlobal;
223084      memset(pGlobal, 0, sizeof(Fts5Global));
223085      pGlobal->db = db;
223086      pGlobal->api.iVersion = 2;
223087      pGlobal->api.xCreateFunction = fts5CreateAux;
223088      pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
223089      pGlobal->api.xFindTokenizer = fts5FindTokenizer;
223090      rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
223091      if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
223092      if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
223093      if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
223094      if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
223095      if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
223096      if( rc==SQLITE_OK ){
223097        rc = sqlite3_create_function(
223098            db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
223099        );
223100      }
223101      if( rc==SQLITE_OK ){
223102        rc = sqlite3_create_function(
223103            db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
223104        );
223105      }
223106    }
223107  
223108    /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
223109    ** fts5_test_mi.c is compiled and linked into the executable. And call
223110    ** its entry point to enable the matchinfo() demo.  */
223111  #ifdef SQLITE_FTS5_ENABLE_TEST_MI
223112    if( rc==SQLITE_OK ){
223113      extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
223114      rc = sqlite3Fts5TestRegisterMatchinfo(db);
223115    }
223116  #endif
223117  
223118    return rc;
223119  }
223120  
223121  /*
223122  ** The following functions are used to register the module with SQLite. If
223123  ** this module is being built as part of the SQLite core (SQLITE_CORE is
223124  ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
223125  **
223126  ** Or, if this module is being built as a loadable extension, 
223127  ** sqlite3Fts5Init() is omitted and the two standard entry points
223128  ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
223129  */
223130  #ifndef SQLITE_CORE
223131  #ifdef _WIN32
223132  __declspec(dllexport)
223133  #endif
223134  SQLITE_API int sqlite3_fts_init(
223135    sqlite3 *db,
223136    char **pzErrMsg,
223137    const sqlite3_api_routines *pApi
223138  ){
223139    SQLITE_EXTENSION_INIT2(pApi);
223140    (void)pzErrMsg;  /* Unused parameter */
223141    return fts5Init(db);
223142  }
223143  
223144  #ifdef _WIN32
223145  __declspec(dllexport)
223146  #endif
223147  SQLITE_API int sqlite3_fts5_init(
223148    sqlite3 *db,
223149    char **pzErrMsg,
223150    const sqlite3_api_routines *pApi
223151  ){
223152    SQLITE_EXTENSION_INIT2(pApi);
223153    (void)pzErrMsg;  /* Unused parameter */
223154    return fts5Init(db);
223155  }
223156  #else
223157  SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
223158    return fts5Init(db);
223159  }
223160  #endif
223161  
223162  /*
223163  ** 2014 May 31
223164  **
223165  ** The author disclaims copyright to this source code.  In place of
223166  ** a legal notice, here is a blessing:
223167  **
223168  **    May you do good and not evil.
223169  **    May you find forgiveness for yourself and forgive others.
223170  **    May you share freely, never taking more than you give.
223171  **
223172  ******************************************************************************
223173  **
223174  */
223175  
223176  
223177  
223178  /* #include "fts5Int.h" */
223179  
223180  struct Fts5Storage {
223181    Fts5Config *pConfig;
223182    Fts5Index *pIndex;
223183    int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
223184    i64 nTotalRow;                  /* Total number of rows in FTS table */
223185    i64 *aTotalSize;                /* Total sizes of each column */ 
223186    sqlite3_stmt *aStmt[11];
223187  };
223188  
223189  
223190  #if FTS5_STMT_SCAN_ASC!=0 
223191  # error "FTS5_STMT_SCAN_ASC mismatch" 
223192  #endif
223193  #if FTS5_STMT_SCAN_DESC!=1 
223194  # error "FTS5_STMT_SCAN_DESC mismatch" 
223195  #endif
223196  #if FTS5_STMT_LOOKUP!=2
223197  # error "FTS5_STMT_LOOKUP mismatch" 
223198  #endif
223199  
223200  #define FTS5_STMT_INSERT_CONTENT  3
223201  #define FTS5_STMT_REPLACE_CONTENT 4
223202  #define FTS5_STMT_DELETE_CONTENT  5
223203  #define FTS5_STMT_REPLACE_DOCSIZE  6
223204  #define FTS5_STMT_DELETE_DOCSIZE  7
223205  #define FTS5_STMT_LOOKUP_DOCSIZE  8
223206  #define FTS5_STMT_REPLACE_CONFIG 9
223207  #define FTS5_STMT_SCAN 10
223208  
223209  /*
223210  ** Prepare the two insert statements - Fts5Storage.pInsertContent and
223211  ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
223212  ** Return SQLITE_OK if successful, or an SQLite error code if an error
223213  ** occurs.
223214  */
223215  static int fts5StorageGetStmt(
223216    Fts5Storage *p,                 /* Storage handle */
223217    int eStmt,                      /* FTS5_STMT_XXX constant */
223218    sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
223219    char **pzErrMsg                 /* OUT: Error message (if any) */
223220  ){
223221    int rc = SQLITE_OK;
223222  
223223    /* If there is no %_docsize table, there should be no requests for 
223224    ** statements to operate on it.  */
223225    assert( p->pConfig->bColumnsize || (
223226          eStmt!=FTS5_STMT_REPLACE_DOCSIZE 
223227       && eStmt!=FTS5_STMT_DELETE_DOCSIZE 
223228       && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE 
223229    ));
223230  
223231    assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
223232    if( p->aStmt[eStmt]==0 ){
223233      const char *azStmt[] = {
223234        "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
223235        "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
223236        "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
223237  
223238        "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
223239        "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
223240        "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
223241        "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
223242        "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
223243  
223244        "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
223245  
223246        "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
223247        "SELECT %s FROM %s AS T",                         /* SCAN */
223248      };
223249      Fts5Config *pC = p->pConfig;
223250      char *zSql = 0;
223251  
223252      switch( eStmt ){
223253        case FTS5_STMT_SCAN:
223254          zSql = sqlite3_mprintf(azStmt[eStmt], 
223255              pC->zContentExprlist, pC->zContent
223256          );
223257          break;
223258  
223259        case FTS5_STMT_SCAN_ASC:
223260        case FTS5_STMT_SCAN_DESC:
223261          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, 
223262              pC->zContent, pC->zContentRowid, pC->zContentRowid,
223263              pC->zContentRowid
223264          );
223265          break;
223266  
223267        case FTS5_STMT_LOOKUP:
223268          zSql = sqlite3_mprintf(azStmt[eStmt], 
223269              pC->zContentExprlist, pC->zContent, pC->zContentRowid
223270          );
223271          break;
223272  
223273        case FTS5_STMT_INSERT_CONTENT: 
223274        case FTS5_STMT_REPLACE_CONTENT: {
223275          int nCol = pC->nCol + 1;
223276          char *zBind;
223277          int i;
223278  
223279          zBind = sqlite3_malloc64(1 + nCol*2);
223280          if( zBind ){
223281            for(i=0; i<nCol; i++){
223282              zBind[i*2] = '?';
223283              zBind[i*2 + 1] = ',';
223284            }
223285            zBind[i*2-1] = '\0';
223286            zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
223287            sqlite3_free(zBind);
223288          }
223289          break;
223290        }
223291  
223292        default:
223293          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
223294          break;
223295      }
223296  
223297      if( zSql==0 ){
223298        rc = SQLITE_NOMEM;
223299      }else{
223300        int f = SQLITE_PREPARE_PERSISTENT;
223301        if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
223302        rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
223303        sqlite3_free(zSql);
223304        if( rc!=SQLITE_OK && pzErrMsg ){
223305          *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
223306        }
223307      }
223308    }
223309  
223310    *ppStmt = p->aStmt[eStmt];
223311    sqlite3_reset(*ppStmt);
223312    return rc;
223313  }
223314  
223315  
223316  static int fts5ExecPrintf(
223317    sqlite3 *db,
223318    char **pzErr,
223319    const char *zFormat,
223320    ...
223321  ){
223322    int rc;
223323    va_list ap;                     /* ... printf arguments */
223324    char *zSql;
223325  
223326    va_start(ap, zFormat);
223327    zSql = sqlite3_vmprintf(zFormat, ap);
223328  
223329    if( zSql==0 ){
223330      rc = SQLITE_NOMEM;
223331    }else{
223332      rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
223333      sqlite3_free(zSql);
223334    }
223335  
223336    va_end(ap);
223337    return rc;
223338  }
223339  
223340  /*
223341  ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
223342  ** code otherwise.
223343  */
223344  static int sqlite3Fts5DropAll(Fts5Config *pConfig){
223345    int rc = fts5ExecPrintf(pConfig->db, 0, 
223346        "DROP TABLE IF EXISTS %Q.'%q_data';"
223347        "DROP TABLE IF EXISTS %Q.'%q_idx';"
223348        "DROP TABLE IF EXISTS %Q.'%q_config';",
223349        pConfig->zDb, pConfig->zName,
223350        pConfig->zDb, pConfig->zName,
223351        pConfig->zDb, pConfig->zName
223352    );
223353    if( rc==SQLITE_OK && pConfig->bColumnsize ){
223354      rc = fts5ExecPrintf(pConfig->db, 0, 
223355          "DROP TABLE IF EXISTS %Q.'%q_docsize';",
223356          pConfig->zDb, pConfig->zName
223357      );
223358    }
223359    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
223360      rc = fts5ExecPrintf(pConfig->db, 0, 
223361          "DROP TABLE IF EXISTS %Q.'%q_content';",
223362          pConfig->zDb, pConfig->zName
223363      );
223364    }
223365    return rc;
223366  }
223367  
223368  static void fts5StorageRenameOne(
223369    Fts5Config *pConfig,            /* Current FTS5 configuration */
223370    int *pRc,                       /* IN/OUT: Error code */
223371    const char *zTail,              /* Tail of table name e.g. "data", "config" */
223372    const char *zName               /* New name of FTS5 table */
223373  ){
223374    if( *pRc==SQLITE_OK ){
223375      *pRc = fts5ExecPrintf(pConfig->db, 0, 
223376          "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
223377          pConfig->zDb, pConfig->zName, zTail, zName, zTail
223378      );
223379    }
223380  }
223381  
223382  static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
223383    Fts5Config *pConfig = pStorage->pConfig;
223384    int rc = sqlite3Fts5StorageSync(pStorage);
223385  
223386    fts5StorageRenameOne(pConfig, &rc, "data", zName);
223387    fts5StorageRenameOne(pConfig, &rc, "idx", zName);
223388    fts5StorageRenameOne(pConfig, &rc, "config", zName);
223389    if( pConfig->bColumnsize ){
223390      fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
223391    }
223392    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
223393      fts5StorageRenameOne(pConfig, &rc, "content", zName);
223394    }
223395    return rc;
223396  }
223397  
223398  /*
223399  ** Create the shadow table named zPost, with definition zDefn. Return
223400  ** SQLITE_OK if successful, or an SQLite error code otherwise.
223401  */
223402  static int sqlite3Fts5CreateTable(
223403    Fts5Config *pConfig,            /* FTS5 configuration */
223404    const char *zPost,              /* Shadow table to create (e.g. "content") */
223405    const char *zDefn,              /* Columns etc. for shadow table */
223406    int bWithout,                   /* True for without rowid */
223407    char **pzErr                    /* OUT: Error message */
223408  ){
223409    int rc;
223410    char *zErr = 0;
223411  
223412    rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
223413        pConfig->zDb, pConfig->zName, zPost, zDefn, 
223414  #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
223415        bWithout?" WITHOUT ROWID":
223416  #endif
223417        ""
223418    );
223419    if( zErr ){
223420      *pzErr = sqlite3_mprintf(
223421          "fts5: error creating shadow table %q_%s: %s", 
223422          pConfig->zName, zPost, zErr
223423      );
223424      sqlite3_free(zErr);
223425    }
223426  
223427    return rc;
223428  }
223429  
223430  /*
223431  ** Open a new Fts5Index handle. If the bCreate argument is true, create
223432  ** and initialize the underlying tables 
223433  **
223434  ** If successful, set *pp to point to the new object and return SQLITE_OK.
223435  ** Otherwise, set *pp to NULL and return an SQLite error code.
223436  */
223437  static int sqlite3Fts5StorageOpen(
223438    Fts5Config *pConfig, 
223439    Fts5Index *pIndex, 
223440    int bCreate, 
223441    Fts5Storage **pp,
223442    char **pzErr                    /* OUT: Error message */
223443  ){
223444    int rc = SQLITE_OK;
223445    Fts5Storage *p;                 /* New object */
223446    sqlite3_int64 nByte;            /* Bytes of space to allocate */
223447  
223448    nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
223449          + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
223450    *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
223451    if( !p ) return SQLITE_NOMEM;
223452  
223453    memset(p, 0, nByte);
223454    p->aTotalSize = (i64*)&p[1];
223455    p->pConfig = pConfig;
223456    p->pIndex = pIndex;
223457  
223458    if( bCreate ){
223459      if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
223460        int nDefn = 32 + pConfig->nCol*10;
223461        char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
223462        if( zDefn==0 ){
223463          rc = SQLITE_NOMEM;
223464        }else{
223465          int i;
223466          int iOff;
223467          sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
223468          iOff = (int)strlen(zDefn);
223469          for(i=0; i<pConfig->nCol; i++){
223470            sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
223471            iOff += (int)strlen(&zDefn[iOff]);
223472          }
223473          rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
223474        }
223475        sqlite3_free(zDefn);
223476      }
223477  
223478      if( rc==SQLITE_OK && pConfig->bColumnsize ){
223479        rc = sqlite3Fts5CreateTable(
223480            pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
223481        );
223482      }
223483      if( rc==SQLITE_OK ){
223484        rc = sqlite3Fts5CreateTable(
223485            pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
223486        );
223487      }
223488      if( rc==SQLITE_OK ){
223489        rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
223490      }
223491    }
223492  
223493    if( rc ){
223494      sqlite3Fts5StorageClose(p);
223495      *pp = 0;
223496    }
223497    return rc;
223498  }
223499  
223500  /*
223501  ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
223502  */
223503  static int sqlite3Fts5StorageClose(Fts5Storage *p){
223504    int rc = SQLITE_OK;
223505    if( p ){
223506      int i;
223507  
223508      /* Finalize all SQL statements */
223509      for(i=0; i<ArraySize(p->aStmt); i++){
223510        sqlite3_finalize(p->aStmt[i]);
223511      }
223512  
223513      sqlite3_free(p);
223514    }
223515    return rc;
223516  }
223517  
223518  typedef struct Fts5InsertCtx Fts5InsertCtx;
223519  struct Fts5InsertCtx {
223520    Fts5Storage *pStorage;
223521    int iCol;
223522    int szCol;                      /* Size of column value in tokens */
223523  };
223524  
223525  /*
223526  ** Tokenization callback used when inserting tokens into the FTS index.
223527  */
223528  static int fts5StorageInsertCallback(
223529    void *pContext,                 /* Pointer to Fts5InsertCtx object */
223530    int tflags,
223531    const char *pToken,             /* Buffer containing token */
223532    int nToken,                     /* Size of token in bytes */
223533    int iUnused1,                   /* Start offset of token */
223534    int iUnused2                    /* End offset of token */
223535  ){
223536    Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
223537    Fts5Index *pIdx = pCtx->pStorage->pIndex;
223538    UNUSED_PARAM2(iUnused1, iUnused2);
223539    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
223540    if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
223541      pCtx->szCol++;
223542    }
223543    return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
223544  }
223545  
223546  /*
223547  ** If a row with rowid iDel is present in the %_content table, add the
223548  ** delete-markers to the FTS index necessary to delete it. Do not actually
223549  ** remove the %_content row at this time though.
223550  */
223551  static int fts5StorageDeleteFromIndex(
223552    Fts5Storage *p, 
223553    i64 iDel, 
223554    sqlite3_value **apVal
223555  ){
223556    Fts5Config *pConfig = p->pConfig;
223557    sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
223558    int rc;                         /* Return code */
223559    int rc2;                        /* sqlite3_reset() return code */
223560    int iCol;
223561    Fts5InsertCtx ctx;
223562  
223563    if( apVal==0 ){
223564      rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
223565      if( rc!=SQLITE_OK ) return rc;
223566      sqlite3_bind_int64(pSeek, 1, iDel);
223567      if( sqlite3_step(pSeek)!=SQLITE_ROW ){
223568        return sqlite3_reset(pSeek);
223569      }
223570    }
223571  
223572    ctx.pStorage = p;
223573    ctx.iCol = -1;
223574    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
223575    for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
223576      if( pConfig->abUnindexed[iCol-1]==0 ){
223577        const char *zText;
223578        int nText;
223579        if( pSeek ){
223580          zText = (const char*)sqlite3_column_text(pSeek, iCol);
223581          nText = sqlite3_column_bytes(pSeek, iCol);
223582        }else{
223583          zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
223584          nText = sqlite3_value_bytes(apVal[iCol-1]);
223585        }
223586        ctx.szCol = 0;
223587        rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, 
223588            zText, nText, (void*)&ctx, fts5StorageInsertCallback
223589        );
223590        p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
223591      }
223592    }
223593    p->nTotalRow--;
223594  
223595    rc2 = sqlite3_reset(pSeek);
223596    if( rc==SQLITE_OK ) rc = rc2;
223597    return rc;
223598  }
223599  
223600  
223601  /*
223602  ** Insert a record into the %_docsize table. Specifically, do:
223603  **
223604  **   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
223605  **
223606  ** If there is no %_docsize table (as happens if the columnsize=0 option
223607  ** is specified when the FTS5 table is created), this function is a no-op.
223608  */
223609  static int fts5StorageInsertDocsize(
223610    Fts5Storage *p,                 /* Storage module to write to */
223611    i64 iRowid,                     /* id value */
223612    Fts5Buffer *pBuf                /* sz value */
223613  ){
223614    int rc = SQLITE_OK;
223615    if( p->pConfig->bColumnsize ){
223616      sqlite3_stmt *pReplace = 0;
223617      rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
223618      if( rc==SQLITE_OK ){
223619        sqlite3_bind_int64(pReplace, 1, iRowid);
223620        sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
223621        sqlite3_step(pReplace);
223622        rc = sqlite3_reset(pReplace);
223623        sqlite3_bind_null(pReplace, 2);
223624      }
223625    }
223626    return rc;
223627  }
223628  
223629  /*
223630  ** Load the contents of the "averages" record from disk into the 
223631  ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
223632  ** argument bCache is true, set the p->bTotalsValid flag to indicate
223633  ** that the contents of aTotalSize[] and nTotalRow are valid until
223634  ** further notice.
223635  **
223636  ** Return SQLITE_OK if successful, or an SQLite error code if an error
223637  ** occurs.
223638  */
223639  static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
223640    int rc = SQLITE_OK;
223641    if( p->bTotalsValid==0 ){
223642      rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
223643      p->bTotalsValid = bCache;
223644    }
223645    return rc;
223646  }
223647  
223648  /*
223649  ** Store the current contents of the p->nTotalRow and p->aTotalSize[] 
223650  ** variables in the "averages" record on disk.
223651  **
223652  ** Return SQLITE_OK if successful, or an SQLite error code if an error
223653  ** occurs.
223654  */
223655  static int fts5StorageSaveTotals(Fts5Storage *p){
223656    int nCol = p->pConfig->nCol;
223657    int i;
223658    Fts5Buffer buf;
223659    int rc = SQLITE_OK;
223660    memset(&buf, 0, sizeof(buf));
223661  
223662    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
223663    for(i=0; i<nCol; i++){
223664      sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
223665    }
223666    if( rc==SQLITE_OK ){
223667      rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
223668    }
223669    sqlite3_free(buf.p);
223670  
223671    return rc;
223672  }
223673  
223674  /*
223675  ** Remove a row from the FTS table.
223676  */
223677  static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
223678    Fts5Config *pConfig = p->pConfig;
223679    int rc;
223680    sqlite3_stmt *pDel = 0;
223681  
223682    assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
223683    rc = fts5StorageLoadTotals(p, 1);
223684  
223685    /* Delete the index records */
223686    if( rc==SQLITE_OK ){
223687      rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
223688    }
223689  
223690    /* Delete the %_docsize record */
223691    if( rc==SQLITE_OK && pConfig->bColumnsize ){
223692      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
223693      if( rc==SQLITE_OK ){
223694        sqlite3_bind_int64(pDel, 1, iDel);
223695        sqlite3_step(pDel);
223696        rc = sqlite3_reset(pDel);
223697      }
223698    }
223699  
223700    /* Delete the %_content record */
223701    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
223702      if( rc==SQLITE_OK ){
223703        rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
223704      }
223705      if( rc==SQLITE_OK ){
223706        sqlite3_bind_int64(pDel, 1, iDel);
223707        sqlite3_step(pDel);
223708        rc = sqlite3_reset(pDel);
223709      }
223710    }
223711  
223712    return rc;
223713  }
223714  
223715  /*
223716  ** Delete all entries in the FTS5 index.
223717  */
223718  static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
223719    Fts5Config *pConfig = p->pConfig;
223720    int rc;
223721  
223722    /* Delete the contents of the %_data and %_docsize tables. */
223723    rc = fts5ExecPrintf(pConfig->db, 0,
223724        "DELETE FROM %Q.'%q_data';" 
223725        "DELETE FROM %Q.'%q_idx';",
223726        pConfig->zDb, pConfig->zName,
223727        pConfig->zDb, pConfig->zName
223728    );
223729    if( rc==SQLITE_OK && pConfig->bColumnsize ){
223730      rc = fts5ExecPrintf(pConfig->db, 0,
223731          "DELETE FROM %Q.'%q_docsize';",
223732          pConfig->zDb, pConfig->zName
223733      );
223734    }
223735  
223736    /* Reinitialize the %_data table. This call creates the initial structure
223737    ** and averages records.  */
223738    if( rc==SQLITE_OK ){
223739      rc = sqlite3Fts5IndexReinit(p->pIndex);
223740    }
223741    if( rc==SQLITE_OK ){
223742      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
223743    }
223744    return rc;
223745  }
223746  
223747  static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
223748    Fts5Buffer buf = {0,0,0};
223749    Fts5Config *pConfig = p->pConfig;
223750    sqlite3_stmt *pScan = 0;
223751    Fts5InsertCtx ctx;
223752    int rc, rc2;
223753  
223754    memset(&ctx, 0, sizeof(Fts5InsertCtx));
223755    ctx.pStorage = p;
223756    rc = sqlite3Fts5StorageDeleteAll(p);
223757    if( rc==SQLITE_OK ){
223758      rc = fts5StorageLoadTotals(p, 1);
223759    }
223760  
223761    if( rc==SQLITE_OK ){
223762      rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
223763    }
223764  
223765    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
223766      i64 iRowid = sqlite3_column_int64(pScan, 0);
223767  
223768      sqlite3Fts5BufferZero(&buf);
223769      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
223770      for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
223771        ctx.szCol = 0;
223772        if( pConfig->abUnindexed[ctx.iCol]==0 ){
223773          rc = sqlite3Fts5Tokenize(pConfig, 
223774              FTS5_TOKENIZE_DOCUMENT,
223775              (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
223776              sqlite3_column_bytes(pScan, ctx.iCol+1),
223777              (void*)&ctx,
223778              fts5StorageInsertCallback
223779          );
223780        }
223781        sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
223782        p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
223783      }
223784      p->nTotalRow++;
223785  
223786      if( rc==SQLITE_OK ){
223787        rc = fts5StorageInsertDocsize(p, iRowid, &buf);
223788      }
223789    }
223790    sqlite3_free(buf.p);
223791    rc2 = sqlite3_reset(pScan);
223792    if( rc==SQLITE_OK ) rc = rc2;
223793  
223794    /* Write the averages record */
223795    if( rc==SQLITE_OK ){
223796      rc = fts5StorageSaveTotals(p);
223797    }
223798    return rc;
223799  }
223800  
223801  static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
223802    return sqlite3Fts5IndexOptimize(p->pIndex);
223803  }
223804  
223805  static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
223806    return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
223807  }
223808  
223809  static int sqlite3Fts5StorageReset(Fts5Storage *p){
223810    return sqlite3Fts5IndexReset(p->pIndex);
223811  }
223812  
223813  /*
223814  ** Allocate a new rowid. This is used for "external content" tables when
223815  ** a NULL value is inserted into the rowid column. The new rowid is allocated
223816  ** by inserting a dummy row into the %_docsize table. The dummy will be
223817  ** overwritten later.
223818  **
223819  ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
223820  ** this case the user is required to provide a rowid explicitly.
223821  */
223822  static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
223823    int rc = SQLITE_MISMATCH;
223824    if( p->pConfig->bColumnsize ){
223825      sqlite3_stmt *pReplace = 0;
223826      rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
223827      if( rc==SQLITE_OK ){
223828        sqlite3_bind_null(pReplace, 1);
223829        sqlite3_bind_null(pReplace, 2);
223830        sqlite3_step(pReplace);
223831        rc = sqlite3_reset(pReplace);
223832      }
223833      if( rc==SQLITE_OK ){
223834        *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
223835      }
223836    }
223837    return rc;
223838  }
223839  
223840  /*
223841  ** Insert a new row into the FTS content table.
223842  */
223843  static int sqlite3Fts5StorageContentInsert(
223844    Fts5Storage *p, 
223845    sqlite3_value **apVal, 
223846    i64 *piRowid
223847  ){
223848    Fts5Config *pConfig = p->pConfig;
223849    int rc = SQLITE_OK;
223850  
223851    /* Insert the new row into the %_content table. */
223852    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
223853      if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
223854        *piRowid = sqlite3_value_int64(apVal[1]);
223855      }else{
223856        rc = fts5StorageNewRowid(p, piRowid);
223857      }
223858    }else{
223859      sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
223860      int i;                        /* Counter variable */
223861      rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
223862      for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
223863        rc = sqlite3_bind_value(pInsert, i, apVal[i]);
223864      }
223865      if( rc==SQLITE_OK ){
223866        sqlite3_step(pInsert);
223867        rc = sqlite3_reset(pInsert);
223868      }
223869      *piRowid = sqlite3_last_insert_rowid(pConfig->db);
223870    }
223871  
223872    return rc;
223873  }
223874  
223875  /*
223876  ** Insert new entries into the FTS index and %_docsize table.
223877  */
223878  static int sqlite3Fts5StorageIndexInsert(
223879    Fts5Storage *p, 
223880    sqlite3_value **apVal, 
223881    i64 iRowid
223882  ){
223883    Fts5Config *pConfig = p->pConfig;
223884    int rc = SQLITE_OK;             /* Return code */
223885    Fts5InsertCtx ctx;              /* Tokenization callback context object */
223886    Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
223887  
223888    memset(&buf, 0, sizeof(Fts5Buffer));
223889    ctx.pStorage = p;
223890    rc = fts5StorageLoadTotals(p, 1);
223891  
223892    if( rc==SQLITE_OK ){
223893      rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
223894    }
223895    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
223896      ctx.szCol = 0;
223897      if( pConfig->abUnindexed[ctx.iCol]==0 ){
223898        rc = sqlite3Fts5Tokenize(pConfig, 
223899            FTS5_TOKENIZE_DOCUMENT,
223900            (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
223901            sqlite3_value_bytes(apVal[ctx.iCol+2]),
223902            (void*)&ctx,
223903            fts5StorageInsertCallback
223904        );
223905      }
223906      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
223907      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
223908    }
223909    p->nTotalRow++;
223910  
223911    /* Write the %_docsize record */
223912    if( rc==SQLITE_OK ){
223913      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
223914    }
223915    sqlite3_free(buf.p);
223916  
223917    return rc;
223918  }
223919  
223920  static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
223921    Fts5Config *pConfig = p->pConfig;
223922    char *zSql;
223923    int rc;
223924  
223925    zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", 
223926        pConfig->zDb, pConfig->zName, zSuffix
223927    );
223928    if( zSql==0 ){
223929      rc = SQLITE_NOMEM;
223930    }else{
223931      sqlite3_stmt *pCnt = 0;
223932      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
223933      if( rc==SQLITE_OK ){
223934        if( SQLITE_ROW==sqlite3_step(pCnt) ){
223935          *pnRow = sqlite3_column_int64(pCnt, 0);
223936        }
223937        rc = sqlite3_finalize(pCnt);
223938      }
223939    }
223940  
223941    sqlite3_free(zSql);
223942    return rc;
223943  }
223944  
223945  /*
223946  ** Context object used by sqlite3Fts5StorageIntegrity().
223947  */
223948  typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
223949  struct Fts5IntegrityCtx {
223950    i64 iRowid;
223951    int iCol;
223952    int szCol;
223953    u64 cksum;
223954    Fts5Termset *pTermset;
223955    Fts5Config *pConfig;
223956  };
223957  
223958  
223959  /*
223960  ** Tokenization callback used by integrity check.
223961  */
223962  static int fts5StorageIntegrityCallback(
223963    void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
223964    int tflags,
223965    const char *pToken,             /* Buffer containing token */
223966    int nToken,                     /* Size of token in bytes */
223967    int iUnused1,                   /* Start offset of token */
223968    int iUnused2                    /* End offset of token */
223969  ){
223970    Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
223971    Fts5Termset *pTermset = pCtx->pTermset;
223972    int bPresent;
223973    int ii;
223974    int rc = SQLITE_OK;
223975    int iPos;
223976    int iCol;
223977  
223978    UNUSED_PARAM2(iUnused1, iUnused2);
223979    if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
223980  
223981    if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
223982      pCtx->szCol++;
223983    }
223984  
223985    switch( pCtx->pConfig->eDetail ){
223986      case FTS5_DETAIL_FULL:
223987        iPos = pCtx->szCol-1;
223988        iCol = pCtx->iCol;
223989        break;
223990  
223991      case FTS5_DETAIL_COLUMNS:
223992        iPos = pCtx->iCol;
223993        iCol = 0;
223994        break;
223995  
223996      default:
223997        assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
223998        iPos = 0;
223999        iCol = 0;
224000        break;
224001    }
224002  
224003    rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
224004    if( rc==SQLITE_OK && bPresent==0 ){
224005      pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
224006          pCtx->iRowid, iCol, iPos, 0, pToken, nToken
224007      );
224008    }
224009  
224010    for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
224011      const int nChar = pCtx->pConfig->aPrefix[ii];
224012      int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
224013      if( nByte ){
224014        rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
224015        if( bPresent==0 ){
224016          pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
224017              pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
224018          );
224019        }
224020      }
224021    }
224022  
224023    return rc;
224024  }
224025  
224026  /*
224027  ** Check that the contents of the FTS index match that of the %_content
224028  ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
224029  ** some other SQLite error code if an error occurs while attempting to
224030  ** determine this.
224031  */
224032  static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
224033    Fts5Config *pConfig = p->pConfig;
224034    int rc;                         /* Return code */
224035    int *aColSize;                  /* Array of size pConfig->nCol */
224036    i64 *aTotalSize;                /* Array of size pConfig->nCol */
224037    Fts5IntegrityCtx ctx;
224038    sqlite3_stmt *pScan;
224039  
224040    memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
224041    ctx.pConfig = p->pConfig;
224042    aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
224043    if( !aTotalSize ) return SQLITE_NOMEM;
224044    aColSize = (int*)&aTotalSize[pConfig->nCol];
224045    memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
224046  
224047    /* Generate the expected index checksum based on the contents of the
224048    ** %_content table. This block stores the checksum in ctx.cksum. */
224049    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
224050    if( rc==SQLITE_OK ){
224051      int rc2;
224052      while( SQLITE_ROW==sqlite3_step(pScan) ){
224053        int i;
224054        ctx.iRowid = sqlite3_column_int64(pScan, 0);
224055        ctx.szCol = 0;
224056        if( pConfig->bColumnsize ){
224057          rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
224058        }
224059        if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
224060          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
224061        }
224062        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
224063          if( pConfig->abUnindexed[i] ) continue;
224064          ctx.iCol = i;
224065          ctx.szCol = 0;
224066          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
224067            rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
224068          }
224069          if( rc==SQLITE_OK ){
224070            rc = sqlite3Fts5Tokenize(pConfig, 
224071                FTS5_TOKENIZE_DOCUMENT,
224072                (const char*)sqlite3_column_text(pScan, i+1),
224073                sqlite3_column_bytes(pScan, i+1),
224074                (void*)&ctx,
224075                fts5StorageIntegrityCallback
224076            );
224077          }
224078          if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
224079            rc = FTS5_CORRUPT;
224080          }
224081          aTotalSize[i] += ctx.szCol;
224082          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
224083            sqlite3Fts5TermsetFree(ctx.pTermset);
224084            ctx.pTermset = 0;
224085          }
224086        }
224087        sqlite3Fts5TermsetFree(ctx.pTermset);
224088        ctx.pTermset = 0;
224089  
224090        if( rc!=SQLITE_OK ) break;
224091      }
224092      rc2 = sqlite3_reset(pScan);
224093      if( rc==SQLITE_OK ) rc = rc2;
224094    }
224095  
224096    /* Test that the "totals" (sometimes called "averages") record looks Ok */
224097    if( rc==SQLITE_OK ){
224098      int i;
224099      rc = fts5StorageLoadTotals(p, 0);
224100      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
224101        if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
224102      }
224103    }
224104  
224105    /* Check that the %_docsize and %_content tables contain the expected
224106    ** number of rows.  */
224107    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
224108      i64 nRow = 0;
224109      rc = fts5StorageCount(p, "content", &nRow);
224110      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
224111    }
224112    if( rc==SQLITE_OK && pConfig->bColumnsize ){
224113      i64 nRow = 0;
224114      rc = fts5StorageCount(p, "docsize", &nRow);
224115      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
224116    }
224117  
224118    /* Pass the expected checksum down to the FTS index module. It will
224119    ** verify, amongst other things, that it matches the checksum generated by
224120    ** inspecting the index itself.  */
224121    if( rc==SQLITE_OK ){
224122      rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
224123    }
224124  
224125    sqlite3_free(aTotalSize);
224126    return rc;
224127  }
224128  
224129  /*
224130  ** Obtain an SQLite statement handle that may be used to read data from the
224131  ** %_content table.
224132  */
224133  static int sqlite3Fts5StorageStmt(
224134    Fts5Storage *p, 
224135    int eStmt, 
224136    sqlite3_stmt **pp, 
224137    char **pzErrMsg
224138  ){
224139    int rc;
224140    assert( eStmt==FTS5_STMT_SCAN_ASC 
224141         || eStmt==FTS5_STMT_SCAN_DESC
224142         || eStmt==FTS5_STMT_LOOKUP
224143    );
224144    rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
224145    if( rc==SQLITE_OK ){
224146      assert( p->aStmt[eStmt]==*pp );
224147      p->aStmt[eStmt] = 0;
224148    }
224149    return rc;
224150  }
224151  
224152  /*
224153  ** Release an SQLite statement handle obtained via an earlier call to
224154  ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
224155  ** must match that passed to the sqlite3Fts5StorageStmt() call.
224156  */
224157  static void sqlite3Fts5StorageStmtRelease(
224158    Fts5Storage *p, 
224159    int eStmt, 
224160    sqlite3_stmt *pStmt
224161  ){
224162    assert( eStmt==FTS5_STMT_SCAN_ASC
224163         || eStmt==FTS5_STMT_SCAN_DESC
224164         || eStmt==FTS5_STMT_LOOKUP
224165    );
224166    if( p->aStmt[eStmt]==0 ){
224167      sqlite3_reset(pStmt);
224168      p->aStmt[eStmt] = pStmt;
224169    }else{
224170      sqlite3_finalize(pStmt);
224171    }
224172  }
224173  
224174  static int fts5StorageDecodeSizeArray(
224175    int *aCol, int nCol,            /* Array to populate */
224176    const u8 *aBlob, int nBlob      /* Record to read varints from */
224177  ){
224178    int i;
224179    int iOff = 0;
224180    for(i=0; i<nCol; i++){
224181      if( iOff>=nBlob ) return 1;
224182      iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
224183    }
224184    return (iOff!=nBlob);
224185  }
224186  
224187  /*
224188  ** Argument aCol points to an array of integers containing one entry for
224189  ** each table column. This function reads the %_docsize record for the
224190  ** specified rowid and populates aCol[] with the results.
224191  **
224192  ** An SQLite error code is returned if an error occurs, or SQLITE_OK
224193  ** otherwise.
224194  */
224195  static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
224196    int nCol = p->pConfig->nCol;    /* Number of user columns in table */
224197    sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
224198    int rc;                         /* Return Code */
224199  
224200    assert( p->pConfig->bColumnsize );
224201    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
224202    if( rc==SQLITE_OK ){
224203      int bCorrupt = 1;
224204      sqlite3_bind_int64(pLookup, 1, iRowid);
224205      if( SQLITE_ROW==sqlite3_step(pLookup) ){
224206        const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
224207        int nBlob = sqlite3_column_bytes(pLookup, 0);
224208        if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
224209          bCorrupt = 0;
224210        }
224211      }
224212      rc = sqlite3_reset(pLookup);
224213      if( bCorrupt && rc==SQLITE_OK ){
224214        rc = FTS5_CORRUPT;
224215      }
224216    }
224217  
224218    return rc;
224219  }
224220  
224221  static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
224222    int rc = fts5StorageLoadTotals(p, 0);
224223    if( rc==SQLITE_OK ){
224224      *pnToken = 0;
224225      if( iCol<0 ){
224226        int i;
224227        for(i=0; i<p->pConfig->nCol; i++){
224228          *pnToken += p->aTotalSize[i];
224229        }
224230      }else if( iCol<p->pConfig->nCol ){
224231        *pnToken = p->aTotalSize[iCol];
224232      }else{
224233        rc = SQLITE_RANGE;
224234      }
224235    }
224236    return rc;
224237  }
224238  
224239  static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
224240    int rc = fts5StorageLoadTotals(p, 0);
224241    if( rc==SQLITE_OK ){
224242      /* nTotalRow being zero does not necessarily indicate a corrupt 
224243      ** database - it might be that the FTS5 table really does contain zero
224244      ** rows. However this function is only called from the xRowCount() API,
224245      ** and there is no way for that API to be invoked if the table contains
224246      ** no rows. Hence the FTS5_CORRUPT return.  */
224247      *pnRow = p->nTotalRow;
224248      if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
224249    }
224250    return rc;
224251  }
224252  
224253  /*
224254  ** Flush any data currently held in-memory to disk.
224255  */
224256  static int sqlite3Fts5StorageSync(Fts5Storage *p){
224257    int rc = SQLITE_OK;
224258    i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
224259    if( p->bTotalsValid ){
224260      rc = fts5StorageSaveTotals(p);
224261      p->bTotalsValid = 0;
224262    }
224263    if( rc==SQLITE_OK ){
224264      rc = sqlite3Fts5IndexSync(p->pIndex);
224265    }
224266    sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
224267    return rc;
224268  }
224269  
224270  static int sqlite3Fts5StorageRollback(Fts5Storage *p){
224271    p->bTotalsValid = 0;
224272    return sqlite3Fts5IndexRollback(p->pIndex);
224273  }
224274  
224275  static int sqlite3Fts5StorageConfigValue(
224276    Fts5Storage *p, 
224277    const char *z,
224278    sqlite3_value *pVal,
224279    int iVal
224280  ){
224281    sqlite3_stmt *pReplace = 0;
224282    int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
224283    if( rc==SQLITE_OK ){
224284      sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
224285      if( pVal ){
224286        sqlite3_bind_value(pReplace, 2, pVal);
224287      }else{
224288        sqlite3_bind_int(pReplace, 2, iVal);
224289      }
224290      sqlite3_step(pReplace);
224291      rc = sqlite3_reset(pReplace);
224292      sqlite3_bind_null(pReplace, 1);
224293    }
224294    if( rc==SQLITE_OK && pVal ){
224295      int iNew = p->pConfig->iCookie + 1;
224296      rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
224297      if( rc==SQLITE_OK ){
224298        p->pConfig->iCookie = iNew;
224299      }
224300    }
224301    return rc;
224302  }
224303  
224304  /*
224305  ** 2014 May 31
224306  **
224307  ** The author disclaims copyright to this source code.  In place of
224308  ** a legal notice, here is a blessing:
224309  **
224310  **    May you do good and not evil.
224311  **    May you find forgiveness for yourself and forgive others.
224312  **    May you share freely, never taking more than you give.
224313  **
224314  ******************************************************************************
224315  */
224316  
224317  
224318  /* #include "fts5Int.h" */
224319  
224320  /**************************************************************************
224321  ** Start of ascii tokenizer implementation.
224322  */
224323  
224324  /*
224325  ** For tokenizers with no "unicode" modifier, the set of token characters
224326  ** is the same as the set of ASCII range alphanumeric characters. 
224327  */
224328  static unsigned char aAsciiTokenChar[128] = {
224329    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
224330    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
224331    0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
224332    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
224333    0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
224334    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
224335    0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
224336    1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
224337  };
224338  
224339  typedef struct AsciiTokenizer AsciiTokenizer;
224340  struct AsciiTokenizer {
224341    unsigned char aTokenChar[128];
224342  };
224343  
224344  static void fts5AsciiAddExceptions(
224345    AsciiTokenizer *p, 
224346    const char *zArg, 
224347    int bTokenChars
224348  ){
224349    int i;
224350    for(i=0; zArg[i]; i++){
224351      if( (zArg[i] & 0x80)==0 ){
224352        p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
224353      }
224354    }
224355  }
224356  
224357  /*
224358  ** Delete a "ascii" tokenizer.
224359  */
224360  static void fts5AsciiDelete(Fts5Tokenizer *p){
224361    sqlite3_free(p);
224362  }
224363  
224364  /*
224365  ** Create an "ascii" tokenizer.
224366  */
224367  static int fts5AsciiCreate(
224368    void *pUnused, 
224369    const char **azArg, int nArg,
224370    Fts5Tokenizer **ppOut
224371  ){
224372    int rc = SQLITE_OK;
224373    AsciiTokenizer *p = 0;
224374    UNUSED_PARAM(pUnused);
224375    if( nArg%2 ){
224376      rc = SQLITE_ERROR;
224377    }else{
224378      p = sqlite3_malloc(sizeof(AsciiTokenizer));
224379      if( p==0 ){
224380        rc = SQLITE_NOMEM;
224381      }else{
224382        int i;
224383        memset(p, 0, sizeof(AsciiTokenizer));
224384        memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
224385        for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
224386          const char *zArg = azArg[i+1];
224387          if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
224388            fts5AsciiAddExceptions(p, zArg, 1);
224389          }else
224390          if( 0==sqlite3_stricmp(azArg[i], "separators") ){
224391            fts5AsciiAddExceptions(p, zArg, 0);
224392          }else{
224393            rc = SQLITE_ERROR;
224394          }
224395        }
224396        if( rc!=SQLITE_OK ){
224397          fts5AsciiDelete((Fts5Tokenizer*)p);
224398          p = 0;
224399        }
224400      }
224401    }
224402  
224403    *ppOut = (Fts5Tokenizer*)p;
224404    return rc;
224405  }
224406  
224407  
224408  static void asciiFold(char *aOut, const char *aIn, int nByte){
224409    int i;
224410    for(i=0; i<nByte; i++){
224411      char c = aIn[i];
224412      if( c>='A' && c<='Z' ) c += 32;
224413      aOut[i] = c;
224414    }
224415  }
224416  
224417  /*
224418  ** Tokenize some text using the ascii tokenizer.
224419  */
224420  static int fts5AsciiTokenize(
224421    Fts5Tokenizer *pTokenizer,
224422    void *pCtx,
224423    int iUnused,
224424    const char *pText, int nText,
224425    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
224426  ){
224427    AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
224428    int rc = SQLITE_OK;
224429    int ie;
224430    int is = 0;
224431  
224432    char aFold[64];
224433    int nFold = sizeof(aFold);
224434    char *pFold = aFold;
224435    unsigned char *a = p->aTokenChar;
224436  
224437    UNUSED_PARAM(iUnused);
224438  
224439    while( is<nText && rc==SQLITE_OK ){
224440      int nByte;
224441  
224442      /* Skip any leading divider characters. */
224443      while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
224444        is++;
224445      }
224446      if( is==nText ) break;
224447  
224448      /* Count the token characters */
224449      ie = is+1;
224450      while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
224451        ie++;
224452      }
224453  
224454      /* Fold to lower case */
224455      nByte = ie-is;
224456      if( nByte>nFold ){
224457        if( pFold!=aFold ) sqlite3_free(pFold);
224458        pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
224459        if( pFold==0 ){
224460          rc = SQLITE_NOMEM;
224461          break;
224462        }
224463        nFold = nByte*2;
224464      }
224465      asciiFold(pFold, &pText[is], nByte);
224466  
224467      /* Invoke the token callback */
224468      rc = xToken(pCtx, 0, pFold, nByte, is, ie);
224469      is = ie+1;
224470    }
224471    
224472    if( pFold!=aFold ) sqlite3_free(pFold);
224473    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
224474    return rc;
224475  }
224476  
224477  /**************************************************************************
224478  ** Start of unicode61 tokenizer implementation.
224479  */
224480  
224481  
224482  /*
224483  ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
224484  ** from the sqlite3 source file utf.c. If this file is compiled as part
224485  ** of the amalgamation, they are not required.
224486  */
224487  #ifndef SQLITE_AMALGAMATION
224488  
224489  static const unsigned char sqlite3Utf8Trans1[] = {
224490    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
224491    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
224492    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
224493    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
224494    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
224495    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
224496    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
224497    0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
224498  };
224499  
224500  #define READ_UTF8(zIn, zTerm, c)                           \
224501    c = *(zIn++);                                            \
224502    if( c>=0xc0 ){                                           \
224503      c = sqlite3Utf8Trans1[c-0xc0];                         \
224504      while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
224505        c = (c<<6) + (0x3f & *(zIn++));                      \
224506      }                                                      \
224507      if( c<0x80                                             \
224508          || (c&0xFFFFF800)==0xD800                          \
224509          || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
224510    }
224511  
224512  
224513  #define WRITE_UTF8(zOut, c) {                          \
224514    if( c<0x00080 ){                                     \
224515      *zOut++ = (unsigned char)(c&0xFF);                 \
224516    }                                                    \
224517    else if( c<0x00800 ){                                \
224518      *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
224519      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
224520    }                                                    \
224521    else if( c<0x10000 ){                                \
224522      *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
224523      *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
224524      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
224525    }else{                                               \
224526      *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
224527      *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
224528      *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
224529      *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
224530    }                                                    \
224531  }
224532  
224533  #endif /* ifndef SQLITE_AMALGAMATION */
224534  
224535  typedef struct Unicode61Tokenizer Unicode61Tokenizer;
224536  struct Unicode61Tokenizer {
224537    unsigned char aTokenChar[128];  /* ASCII range token characters */
224538    char *aFold;                    /* Buffer to fold text into */
224539    int nFold;                      /* Size of aFold[] in bytes */
224540    int eRemoveDiacritic;           /* True if remove_diacritics=1 is set */
224541    int nException;
224542    int *aiException;
224543  
224544    unsigned char aCategory[32];    /* True for token char categories */
224545  };
224546  
224547  /* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
224548  #define FTS5_REMOVE_DIACRITICS_NONE    0
224549  #define FTS5_REMOVE_DIACRITICS_SIMPLE  1
224550  #define FTS5_REMOVE_DIACRITICS_COMPLEX 2
224551  
224552  static int fts5UnicodeAddExceptions(
224553    Unicode61Tokenizer *p,          /* Tokenizer object */
224554    const char *z,                  /* Characters to treat as exceptions */
224555    int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
224556  ){
224557    int rc = SQLITE_OK;
224558    int n = (int)strlen(z);
224559    int *aNew;
224560  
224561    if( n>0 ){
224562      aNew = (int*)sqlite3_realloc64(p->aiException,
224563                                     (n+p->nException)*sizeof(int));
224564      if( aNew ){
224565        int nNew = p->nException;
224566        const unsigned char *zCsr = (const unsigned char*)z;
224567        const unsigned char *zTerm = (const unsigned char*)&z[n];
224568        while( zCsr<zTerm ){
224569          u32 iCode;
224570          int bToken;
224571          READ_UTF8(zCsr, zTerm, iCode);
224572          if( iCode<128 ){
224573            p->aTokenChar[iCode] = (unsigned char)bTokenChars;
224574          }else{
224575            bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
224576            assert( (bToken==0 || bToken==1) ); 
224577            assert( (bTokenChars==0 || bTokenChars==1) );
224578            if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
224579              int i;
224580              for(i=0; i<nNew; i++){
224581                if( (u32)aNew[i]>iCode ) break;
224582              }
224583              memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
224584              aNew[i] = iCode;
224585              nNew++;
224586            }
224587          }
224588        }
224589        p->aiException = aNew;
224590        p->nException = nNew;
224591      }else{
224592        rc = SQLITE_NOMEM;
224593      }
224594    }
224595  
224596    return rc;
224597  }
224598  
224599  /*
224600  ** Return true if the p->aiException[] array contains the value iCode.
224601  */
224602  static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
224603    if( p->nException>0 ){
224604      int *a = p->aiException;
224605      int iLo = 0;
224606      int iHi = p->nException-1;
224607  
224608      while( iHi>=iLo ){
224609        int iTest = (iHi + iLo) / 2;
224610        if( iCode==a[iTest] ){
224611          return 1;
224612        }else if( iCode>a[iTest] ){
224613          iLo = iTest+1;
224614        }else{
224615          iHi = iTest-1;
224616        }
224617      }
224618    }
224619  
224620    return 0;
224621  }
224622  
224623  /*
224624  ** Delete a "unicode61" tokenizer.
224625  */
224626  static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
224627    if( pTok ){
224628      Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
224629      sqlite3_free(p->aiException);
224630      sqlite3_free(p->aFold);
224631      sqlite3_free(p);
224632    }
224633    return;
224634  }
224635  
224636  static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
224637    const char *z = zCat;
224638  
224639    while( *z ){
224640      while( *z==' ' || *z=='\t' ) z++;
224641      if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
224642        return SQLITE_ERROR;
224643      }
224644      while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
224645    }
224646  
224647    sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
224648    return SQLITE_OK;
224649  }
224650  
224651  /*
224652  ** Create a "unicode61" tokenizer.
224653  */
224654  static int fts5UnicodeCreate(
224655    void *pUnused, 
224656    const char **azArg, int nArg,
224657    Fts5Tokenizer **ppOut
224658  ){
224659    int rc = SQLITE_OK;             /* Return code */
224660    Unicode61Tokenizer *p = 0;      /* New tokenizer object */ 
224661  
224662    UNUSED_PARAM(pUnused);
224663  
224664    if( nArg%2 ){
224665      rc = SQLITE_ERROR;
224666    }else{
224667      p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
224668      if( p ){
224669        const char *zCat = "L* N* Co";
224670        int i;
224671        memset(p, 0, sizeof(Unicode61Tokenizer));
224672  
224673        p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
224674        p->nFold = 64;
224675        p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
224676        if( p->aFold==0 ){
224677          rc = SQLITE_NOMEM;
224678        }
224679  
224680        /* Search for a "categories" argument */
224681        for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
224682          if( 0==sqlite3_stricmp(azArg[i], "categories") ){
224683            zCat = azArg[i+1];
224684          }
224685        }
224686  
224687        if( rc==SQLITE_OK ){
224688          rc = unicodeSetCategories(p, zCat);
224689        }
224690  
224691        for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
224692          const char *zArg = azArg[i+1];
224693          if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
224694            if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
224695              rc = SQLITE_ERROR;
224696            }else{
224697              p->eRemoveDiacritic = (zArg[0] - '0');
224698              assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
224699                   || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
224700                   || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
224701              );
224702            }
224703          }else
224704          if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
224705            rc = fts5UnicodeAddExceptions(p, zArg, 1);
224706          }else
224707          if( 0==sqlite3_stricmp(azArg[i], "separators") ){
224708            rc = fts5UnicodeAddExceptions(p, zArg, 0);
224709          }else
224710          if( 0==sqlite3_stricmp(azArg[i], "categories") ){
224711            /* no-op */
224712          }else{
224713            rc = SQLITE_ERROR;
224714          }
224715        }
224716  
224717      }else{
224718        rc = SQLITE_NOMEM;
224719      }
224720      if( rc!=SQLITE_OK ){
224721        fts5UnicodeDelete((Fts5Tokenizer*)p);
224722        p = 0;
224723      }
224724      *ppOut = (Fts5Tokenizer*)p;
224725    }
224726    return rc;
224727  }
224728  
224729  /*
224730  ** Return true if, for the purposes of tokenizing with the tokenizer
224731  ** passed as the first argument, codepoint iCode is considered a token 
224732  ** character (not a separator).
224733  */
224734  static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
224735    return (
224736      p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
224737      ^ fts5UnicodeIsException(p, iCode)
224738    );
224739  }
224740  
224741  static int fts5UnicodeTokenize(
224742    Fts5Tokenizer *pTokenizer,
224743    void *pCtx,
224744    int iUnused,
224745    const char *pText, int nText,
224746    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
224747  ){
224748    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
224749    int rc = SQLITE_OK;
224750    unsigned char *a = p->aTokenChar;
224751  
224752    unsigned char *zTerm = (unsigned char*)&pText[nText];
224753    unsigned char *zCsr = (unsigned char *)pText;
224754  
224755    /* Output buffer */
224756    char *aFold = p->aFold;
224757    int nFold = p->nFold;
224758    const char *pEnd = &aFold[nFold-6];
224759  
224760    UNUSED_PARAM(iUnused);
224761  
224762    /* Each iteration of this loop gobbles up a contiguous run of separators,
224763    ** then the next token.  */
224764    while( rc==SQLITE_OK ){
224765      u32 iCode;                    /* non-ASCII codepoint read from input */
224766      char *zOut = aFold;
224767      int is;
224768      int ie;
224769  
224770      /* Skip any separator characters. */
224771      while( 1 ){
224772        if( zCsr>=zTerm ) goto tokenize_done;
224773        if( *zCsr & 0x80 ) {
224774          /* A character outside of the ascii range. Skip past it if it is
224775          ** a separator character. Or break out of the loop if it is not. */
224776          is = zCsr - (unsigned char*)pText;
224777          READ_UTF8(zCsr, zTerm, iCode);
224778          if( fts5UnicodeIsAlnum(p, iCode) ){
224779            goto non_ascii_tokenchar;
224780          }
224781        }else{
224782          if( a[*zCsr] ){
224783            is = zCsr - (unsigned char*)pText;
224784            goto ascii_tokenchar;
224785          }
224786          zCsr++;
224787        }
224788      }
224789  
224790      /* Run through the tokenchars. Fold them into the output buffer along
224791      ** the way.  */
224792      while( zCsr<zTerm ){
224793  
224794        /* Grow the output buffer so that there is sufficient space to fit the
224795        ** largest possible utf-8 character.  */
224796        if( zOut>pEnd ){
224797          aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
224798          if( aFold==0 ){
224799            rc = SQLITE_NOMEM;
224800            goto tokenize_done;
224801          }
224802          zOut = &aFold[zOut - p->aFold];
224803          memcpy(aFold, p->aFold, nFold);
224804          sqlite3_free(p->aFold);
224805          p->aFold = aFold;
224806          p->nFold = nFold = nFold*2;
224807          pEnd = &aFold[nFold-6];
224808        }
224809  
224810        if( *zCsr & 0x80 ){
224811          /* An non-ascii-range character. Fold it into the output buffer if
224812          ** it is a token character, or break out of the loop if it is not. */
224813          READ_UTF8(zCsr, zTerm, iCode);
224814          if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
224815   non_ascii_tokenchar:
224816            iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
224817            if( iCode ) WRITE_UTF8(zOut, iCode);
224818          }else{
224819            break;
224820          }
224821        }else if( a[*zCsr]==0 ){
224822          /* An ascii-range separator character. End of token. */
224823          break; 
224824        }else{
224825   ascii_tokenchar:
224826          if( *zCsr>='A' && *zCsr<='Z' ){
224827            *zOut++ = *zCsr + 32;
224828          }else{
224829            *zOut++ = *zCsr;
224830          }
224831          zCsr++;
224832        }
224833        ie = zCsr - (unsigned char*)pText;
224834      }
224835  
224836      /* Invoke the token callback */
224837      rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); 
224838    }
224839    
224840   tokenize_done:
224841    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
224842    return rc;
224843  }
224844  
224845  /**************************************************************************
224846  ** Start of porter stemmer implementation.
224847  */
224848  
224849  /* Any tokens larger than this (in bytes) are passed through without
224850  ** stemming. */
224851  #define FTS5_PORTER_MAX_TOKEN 64
224852  
224853  typedef struct PorterTokenizer PorterTokenizer;
224854  struct PorterTokenizer {
224855    fts5_tokenizer tokenizer;       /* Parent tokenizer module */
224856    Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
224857    char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
224858  };
224859  
224860  /*
224861  ** Delete a "porter" tokenizer.
224862  */
224863  static void fts5PorterDelete(Fts5Tokenizer *pTok){
224864    if( pTok ){
224865      PorterTokenizer *p = (PorterTokenizer*)pTok;
224866      if( p->pTokenizer ){
224867        p->tokenizer.xDelete(p->pTokenizer);
224868      }
224869      sqlite3_free(p);
224870    }
224871  }
224872  
224873  /*
224874  ** Create a "porter" tokenizer.
224875  */
224876  static int fts5PorterCreate(
224877    void *pCtx, 
224878    const char **azArg, int nArg,
224879    Fts5Tokenizer **ppOut
224880  ){
224881    fts5_api *pApi = (fts5_api*)pCtx;
224882    int rc = SQLITE_OK;
224883    PorterTokenizer *pRet;
224884    void *pUserdata = 0;
224885    const char *zBase = "unicode61";
224886  
224887    if( nArg>0 ){
224888      zBase = azArg[0];
224889    }
224890  
224891    pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
224892    if( pRet ){
224893      memset(pRet, 0, sizeof(PorterTokenizer));
224894      rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
224895    }else{
224896      rc = SQLITE_NOMEM;
224897    }
224898    if( rc==SQLITE_OK ){
224899      int nArg2 = (nArg>0 ? nArg-1 : 0);
224900      const char **azArg2 = (nArg2 ? &azArg[1] : 0);
224901      rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
224902    }
224903  
224904    if( rc!=SQLITE_OK ){
224905      fts5PorterDelete((Fts5Tokenizer*)pRet);
224906      pRet = 0;
224907    }
224908    *ppOut = (Fts5Tokenizer*)pRet;
224909    return rc;
224910  }
224911  
224912  typedef struct PorterContext PorterContext;
224913  struct PorterContext {
224914    void *pCtx;
224915    int (*xToken)(void*, int, const char*, int, int, int);
224916    char *aBuf;
224917  };
224918  
224919  typedef struct PorterRule PorterRule;
224920  struct PorterRule {
224921    const char *zSuffix;
224922    int nSuffix;
224923    int (*xCond)(char *zStem, int nStem);
224924    const char *zOutput;
224925    int nOutput;
224926  };
224927  
224928  #if 0
224929  static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
224930    int ret = -1;
224931    int nBuf = *pnBuf;
224932    PorterRule *p;
224933  
224934    for(p=aRule; p->zSuffix; p++){
224935      assert( strlen(p->zSuffix)==p->nSuffix );
224936      assert( strlen(p->zOutput)==p->nOutput );
224937      if( nBuf<p->nSuffix ) continue;
224938      if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
224939    }
224940  
224941    if( p->zSuffix ){
224942      int nStem = nBuf - p->nSuffix;
224943      if( p->xCond==0 || p->xCond(aBuf, nStem) ){
224944        memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
224945        *pnBuf = nStem + p->nOutput;
224946        ret = p - aRule;
224947      }
224948    }
224949  
224950    return ret;
224951  }
224952  #endif
224953  
224954  static int fts5PorterIsVowel(char c, int bYIsVowel){
224955    return (
224956        c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
224957    );
224958  }
224959  
224960  static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
224961    int i;
224962    int bCons = bPrevCons;
224963  
224964    /* Scan for a vowel */
224965    for(i=0; i<nStem; i++){
224966      if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
224967    }
224968  
224969    /* Scan for a consonent */
224970    for(i++; i<nStem; i++){
224971      if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
224972    }
224973    return 0;
224974  }
224975  
224976  /* porter rule condition: (m > 0) */
224977  static int fts5Porter_MGt0(char *zStem, int nStem){
224978    return !!fts5PorterGobbleVC(zStem, nStem, 0);
224979  }
224980  
224981  /* porter rule condition: (m > 1) */
224982  static int fts5Porter_MGt1(char *zStem, int nStem){
224983    int n;
224984    n = fts5PorterGobbleVC(zStem, nStem, 0);
224985    if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
224986      return 1;
224987    }
224988    return 0;
224989  }
224990  
224991  /* porter rule condition: (m = 1) */
224992  static int fts5Porter_MEq1(char *zStem, int nStem){
224993    int n;
224994    n = fts5PorterGobbleVC(zStem, nStem, 0);
224995    if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
224996      return 1;
224997    }
224998    return 0;
224999  }
225000  
225001  /* porter rule condition: (*o) */
225002  static int fts5Porter_Ostar(char *zStem, int nStem){
225003    if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
225004      return 0;
225005    }else{
225006      int i;
225007      int mask = 0;
225008      int bCons = 0;
225009      for(i=0; i<nStem; i++){
225010        bCons = !fts5PorterIsVowel(zStem[i], bCons);
225011        assert( bCons==0 || bCons==1 );
225012        mask = (mask << 1) + bCons;
225013      }
225014      return ((mask & 0x0007)==0x0005);
225015    }
225016  }
225017  
225018  /* porter rule condition: (m > 1 and (*S or *T)) */
225019  static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
225020    assert( nStem>0 );
225021    return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') 
225022        && fts5Porter_MGt1(zStem, nStem);
225023  }
225024  
225025  /* porter rule condition: (*v*) */
225026  static int fts5Porter_Vowel(char *zStem, int nStem){
225027    int i;
225028    for(i=0; i<nStem; i++){
225029      if( fts5PorterIsVowel(zStem[i], i>0) ){
225030        return 1;
225031      }
225032    }
225033    return 0;
225034  }
225035  
225036  
225037  /**************************************************************************
225038  ***************************************************************************
225039  ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
225040  */
225041  
225042  static int fts5PorterStep4(char *aBuf, int *pnBuf){
225043    int ret = 0;
225044    int nBuf = *pnBuf;
225045    switch( aBuf[nBuf-2] ){
225046      
225047      case 'a': 
225048        if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
225049          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
225050            *pnBuf = nBuf - 2;
225051          }
225052        }
225053        break;
225054    
225055      case 'c': 
225056        if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
225057          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
225058            *pnBuf = nBuf - 4;
225059          }
225060        }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
225061          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
225062            *pnBuf = nBuf - 4;
225063          }
225064        }
225065        break;
225066    
225067      case 'e': 
225068        if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
225069          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
225070            *pnBuf = nBuf - 2;
225071          }
225072        }
225073        break;
225074    
225075      case 'i': 
225076        if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
225077          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
225078            *pnBuf = nBuf - 2;
225079          }
225080        }
225081        break;
225082    
225083      case 'l': 
225084        if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
225085          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
225086            *pnBuf = nBuf - 4;
225087          }
225088        }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
225089          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
225090            *pnBuf = nBuf - 4;
225091          }
225092        }
225093        break;
225094    
225095      case 'n': 
225096        if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
225097          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225098            *pnBuf = nBuf - 3;
225099          }
225100        }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
225101          if( fts5Porter_MGt1(aBuf, nBuf-5) ){
225102            *pnBuf = nBuf - 5;
225103          }
225104        }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
225105          if( fts5Porter_MGt1(aBuf, nBuf-4) ){
225106            *pnBuf = nBuf - 4;
225107          }
225108        }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
225109          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225110            *pnBuf = nBuf - 3;
225111          }
225112        }
225113        break;
225114    
225115      case 'o': 
225116        if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
225117          if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
225118            *pnBuf = nBuf - 3;
225119          }
225120        }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
225121          if( fts5Porter_MGt1(aBuf, nBuf-2) ){
225122            *pnBuf = nBuf - 2;
225123          }
225124        }
225125        break;
225126    
225127      case 's': 
225128        if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
225129          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225130            *pnBuf = nBuf - 3;
225131          }
225132        }
225133        break;
225134    
225135      case 't': 
225136        if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
225137          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225138            *pnBuf = nBuf - 3;
225139          }
225140        }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
225141          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225142            *pnBuf = nBuf - 3;
225143          }
225144        }
225145        break;
225146    
225147      case 'u': 
225148        if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
225149          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225150            *pnBuf = nBuf - 3;
225151          }
225152        }
225153        break;
225154    
225155      case 'v': 
225156        if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
225157          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225158            *pnBuf = nBuf - 3;
225159          }
225160        }
225161        break;
225162    
225163      case 'z': 
225164        if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
225165          if( fts5Porter_MGt1(aBuf, nBuf-3) ){
225166            *pnBuf = nBuf - 3;
225167          }
225168        }
225169        break;
225170    
225171    }
225172    return ret;
225173  }
225174    
225175  
225176  static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
225177    int ret = 0;
225178    int nBuf = *pnBuf;
225179    switch( aBuf[nBuf-2] ){
225180      
225181      case 'a': 
225182        if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
225183          memcpy(&aBuf[nBuf-2], "ate", 3);
225184          *pnBuf = nBuf - 2 + 3;
225185          ret = 1;
225186        }
225187        break;
225188    
225189      case 'b': 
225190        if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
225191          memcpy(&aBuf[nBuf-2], "ble", 3);
225192          *pnBuf = nBuf - 2 + 3;
225193          ret = 1;
225194        }
225195        break;
225196    
225197      case 'i': 
225198        if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
225199          memcpy(&aBuf[nBuf-2], "ize", 3);
225200          *pnBuf = nBuf - 2 + 3;
225201          ret = 1;
225202        }
225203        break;
225204    
225205    }
225206    return ret;
225207  }
225208    
225209  
225210  static int fts5PorterStep2(char *aBuf, int *pnBuf){
225211    int ret = 0;
225212    int nBuf = *pnBuf;
225213    switch( aBuf[nBuf-2] ){
225214      
225215      case 'a': 
225216        if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
225217          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
225218            memcpy(&aBuf[nBuf-7], "ate", 3);
225219            *pnBuf = nBuf - 7 + 3;
225220          }
225221        }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
225222          if( fts5Porter_MGt0(aBuf, nBuf-6) ){
225223            memcpy(&aBuf[nBuf-6], "tion", 4);
225224            *pnBuf = nBuf - 6 + 4;
225225          }
225226        }
225227        break;
225228    
225229      case 'c': 
225230        if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
225231          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225232            memcpy(&aBuf[nBuf-4], "ence", 4);
225233            *pnBuf = nBuf - 4 + 4;
225234          }
225235        }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
225236          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225237            memcpy(&aBuf[nBuf-4], "ance", 4);
225238            *pnBuf = nBuf - 4 + 4;
225239          }
225240        }
225241        break;
225242    
225243      case 'e': 
225244        if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
225245          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225246            memcpy(&aBuf[nBuf-4], "ize", 3);
225247            *pnBuf = nBuf - 4 + 3;
225248          }
225249        }
225250        break;
225251    
225252      case 'g': 
225253        if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
225254          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225255            memcpy(&aBuf[nBuf-4], "log", 3);
225256            *pnBuf = nBuf - 4 + 3;
225257          }
225258        }
225259        break;
225260    
225261      case 'l': 
225262        if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
225263          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
225264            memcpy(&aBuf[nBuf-3], "ble", 3);
225265            *pnBuf = nBuf - 3 + 3;
225266          }
225267        }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
225268          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225269            memcpy(&aBuf[nBuf-4], "al", 2);
225270            *pnBuf = nBuf - 4 + 2;
225271          }
225272        }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
225273          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225274            memcpy(&aBuf[nBuf-5], "ent", 3);
225275            *pnBuf = nBuf - 5 + 3;
225276          }
225277        }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
225278          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
225279            memcpy(&aBuf[nBuf-3], "e", 1);
225280            *pnBuf = nBuf - 3 + 1;
225281          }
225282        }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
225283          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225284            memcpy(&aBuf[nBuf-5], "ous", 3);
225285            *pnBuf = nBuf - 5 + 3;
225286          }
225287        }
225288        break;
225289    
225290      case 'o': 
225291        if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
225292          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
225293            memcpy(&aBuf[nBuf-7], "ize", 3);
225294            *pnBuf = nBuf - 7 + 3;
225295          }
225296        }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
225297          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225298            memcpy(&aBuf[nBuf-5], "ate", 3);
225299            *pnBuf = nBuf - 5 + 3;
225300          }
225301        }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
225302          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225303            memcpy(&aBuf[nBuf-4], "ate", 3);
225304            *pnBuf = nBuf - 4 + 3;
225305          }
225306        }
225307        break;
225308    
225309      case 's': 
225310        if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
225311          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225312            memcpy(&aBuf[nBuf-5], "al", 2);
225313            *pnBuf = nBuf - 5 + 2;
225314          }
225315        }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
225316          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
225317            memcpy(&aBuf[nBuf-7], "ive", 3);
225318            *pnBuf = nBuf - 7 + 3;
225319          }
225320        }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
225321          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
225322            memcpy(&aBuf[nBuf-7], "ful", 3);
225323            *pnBuf = nBuf - 7 + 3;
225324          }
225325        }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
225326          if( fts5Porter_MGt0(aBuf, nBuf-7) ){
225327            memcpy(&aBuf[nBuf-7], "ous", 3);
225328            *pnBuf = nBuf - 7 + 3;
225329          }
225330        }
225331        break;
225332    
225333      case 't': 
225334        if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
225335          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225336            memcpy(&aBuf[nBuf-5], "al", 2);
225337            *pnBuf = nBuf - 5 + 2;
225338          }
225339        }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
225340          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225341            memcpy(&aBuf[nBuf-5], "ive", 3);
225342            *pnBuf = nBuf - 5 + 3;
225343          }
225344        }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
225345          if( fts5Porter_MGt0(aBuf, nBuf-6) ){
225346            memcpy(&aBuf[nBuf-6], "ble", 3);
225347            *pnBuf = nBuf - 6 + 3;
225348          }
225349        }
225350        break;
225351    
225352    }
225353    return ret;
225354  }
225355    
225356  
225357  static int fts5PorterStep3(char *aBuf, int *pnBuf){
225358    int ret = 0;
225359    int nBuf = *pnBuf;
225360    switch( aBuf[nBuf-2] ){
225361      
225362      case 'a': 
225363        if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
225364          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225365            memcpy(&aBuf[nBuf-4], "ic", 2);
225366            *pnBuf = nBuf - 4 + 2;
225367          }
225368        }
225369        break;
225370    
225371      case 's': 
225372        if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
225373          if( fts5Porter_MGt0(aBuf, nBuf-4) ){
225374            *pnBuf = nBuf - 4;
225375          }
225376        }
225377        break;
225378    
225379      case 't': 
225380        if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
225381          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225382            memcpy(&aBuf[nBuf-5], "ic", 2);
225383            *pnBuf = nBuf - 5 + 2;
225384          }
225385        }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
225386          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225387            memcpy(&aBuf[nBuf-5], "ic", 2);
225388            *pnBuf = nBuf - 5 + 2;
225389          }
225390        }
225391        break;
225392    
225393      case 'u': 
225394        if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
225395          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
225396            *pnBuf = nBuf - 3;
225397          }
225398        }
225399        break;
225400    
225401      case 'v': 
225402        if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
225403          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225404            *pnBuf = nBuf - 5;
225405          }
225406        }
225407        break;
225408    
225409      case 'z': 
225410        if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
225411          if( fts5Porter_MGt0(aBuf, nBuf-5) ){
225412            memcpy(&aBuf[nBuf-5], "al", 2);
225413            *pnBuf = nBuf - 5 + 2;
225414          }
225415        }
225416        break;
225417    
225418    }
225419    return ret;
225420  }
225421    
225422  
225423  static int fts5PorterStep1B(char *aBuf, int *pnBuf){
225424    int ret = 0;
225425    int nBuf = *pnBuf;
225426    switch( aBuf[nBuf-2] ){
225427      
225428      case 'e': 
225429        if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
225430          if( fts5Porter_MGt0(aBuf, nBuf-3) ){
225431            memcpy(&aBuf[nBuf-3], "ee", 2);
225432            *pnBuf = nBuf - 3 + 2;
225433          }
225434        }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
225435          if( fts5Porter_Vowel(aBuf, nBuf-2) ){
225436            *pnBuf = nBuf - 2;
225437            ret = 1;
225438          }
225439        }
225440        break;
225441    
225442      case 'n': 
225443        if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
225444          if( fts5Porter_Vowel(aBuf, nBuf-3) ){
225445            *pnBuf = nBuf - 3;
225446            ret = 1;
225447          }
225448        }
225449        break;
225450    
225451    }
225452    return ret;
225453  }
225454    
225455  /* 
225456  ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
225457  ***************************************************************************
225458  **************************************************************************/
225459  
225460  static void fts5PorterStep1A(char *aBuf, int *pnBuf){
225461    int nBuf = *pnBuf;
225462    if( aBuf[nBuf-1]=='s' ){
225463      if( aBuf[nBuf-2]=='e' ){
225464        if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') 
225465         || (nBuf>3 && aBuf[nBuf-3]=='i' )
225466        ){
225467          *pnBuf = nBuf-2;
225468        }else{
225469          *pnBuf = nBuf-1;
225470        }
225471      }
225472      else if( aBuf[nBuf-2]!='s' ){
225473        *pnBuf = nBuf-1;
225474      }
225475    }
225476  }
225477  
225478  static int fts5PorterCb(
225479    void *pCtx, 
225480    int tflags,
225481    const char *pToken, 
225482    int nToken, 
225483    int iStart, 
225484    int iEnd
225485  ){
225486    PorterContext *p = (PorterContext*)pCtx;
225487  
225488    char *aBuf;
225489    int nBuf;
225490  
225491    if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
225492    aBuf = p->aBuf;
225493    nBuf = nToken;
225494    memcpy(aBuf, pToken, nBuf);
225495  
225496    /* Step 1. */
225497    fts5PorterStep1A(aBuf, &nBuf);
225498    if( fts5PorterStep1B(aBuf, &nBuf) ){
225499      if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
225500        char c = aBuf[nBuf-1];
225501        if( fts5PorterIsVowel(c, 0)==0 
225502         && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] 
225503        ){
225504          nBuf--;
225505        }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
225506          aBuf[nBuf++] = 'e';
225507        }
225508      }
225509    }
225510  
225511    /* Step 1C. */
225512    if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
225513      aBuf[nBuf-1] = 'i';
225514    }
225515  
225516    /* Steps 2 through 4. */
225517    fts5PorterStep2(aBuf, &nBuf);
225518    fts5PorterStep3(aBuf, &nBuf);
225519    fts5PorterStep4(aBuf, &nBuf);
225520  
225521    /* Step 5a. */
225522    assert( nBuf>0 );
225523    if( aBuf[nBuf-1]=='e' ){
225524      if( fts5Porter_MGt1(aBuf, nBuf-1) 
225525       || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
225526      ){
225527        nBuf--;
225528      }
225529    }
225530  
225531    /* Step 5b. */
225532    if( nBuf>1 && aBuf[nBuf-1]=='l' 
225533     && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) 
225534    ){
225535      nBuf--;
225536    }
225537  
225538    return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
225539  
225540   pass_through:
225541    return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
225542  }
225543  
225544  /*
225545  ** Tokenize using the porter tokenizer.
225546  */
225547  static int fts5PorterTokenize(
225548    Fts5Tokenizer *pTokenizer,
225549    void *pCtx,
225550    int flags,
225551    const char *pText, int nText,
225552    int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
225553  ){
225554    PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
225555    PorterContext sCtx;
225556    sCtx.xToken = xToken;
225557    sCtx.pCtx = pCtx;
225558    sCtx.aBuf = p->aBuf;
225559    return p->tokenizer.xTokenize(
225560        p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
225561    );
225562  }
225563  
225564  /*
225565  ** Register all built-in tokenizers with FTS5.
225566  */
225567  static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
225568    struct BuiltinTokenizer {
225569      const char *zName;
225570      fts5_tokenizer x;
225571    } aBuiltin[] = {
225572      { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
225573      { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
225574      { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
225575    };
225576    
225577    int rc = SQLITE_OK;             /* Return code */
225578    int i;                          /* To iterate through builtin functions */
225579  
225580    for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
225581      rc = pApi->xCreateTokenizer(pApi,
225582          aBuiltin[i].zName,
225583          (void*)pApi,
225584          &aBuiltin[i].x,
225585          0
225586      );
225587    }
225588  
225589    return rc;
225590  }
225591  
225592  /*
225593  ** 2012-05-25
225594  **
225595  ** The author disclaims copyright to this source code.  In place of
225596  ** a legal notice, here is a blessing:
225597  **
225598  **    May you do good and not evil.
225599  **    May you find forgiveness for yourself and forgive others.
225600  **    May you share freely, never taking more than you give.
225601  **
225602  ******************************************************************************
225603  */
225604  
225605  /*
225606  ** DO NOT EDIT THIS MACHINE GENERATED FILE.
225607  */
225608  
225609  
225610  /* #include <assert.h> */
225611  
225612  
225613  
225614  /*
225615  ** If the argument is a codepoint corresponding to a lowercase letter
225616  ** in the ASCII range with a diacritic added, return the codepoint
225617  ** of the ASCII letter only. For example, if passed 235 - "LATIN
225618  ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
225619  ** E"). The resuls of passing a codepoint that corresponds to an
225620  ** uppercase letter are undefined.
225621  */
225622  static int fts5_remove_diacritic(int c, int bComplex){
225623    unsigned short aDia[] = {
225624          0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
225625       2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
225626       2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
225627       2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
225628       3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, 
225629       3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, 
225630       4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, 
225631       4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, 
225632       6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, 
225633      61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, 
225634      61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, 
225635      61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, 
225636      62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, 
225637      62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, 
225638      62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, 
225639      63182, 63242, 63274, 63310, 63368, 63390, 
225640    };
225641  #define HIBIT ((unsigned char)0x80)
225642    unsigned char aChar[] = {
225643      '\0',      'a',       'c',       'e',       'i',       'n',       
225644      'o',       'u',       'y',       'y',       'a',       'c',       
225645      'd',       'e',       'e',       'g',       'h',       'i',       
225646      'j',       'k',       'l',       'n',       'o',       'r',       
225647      's',       't',       'u',       'u',       'w',       'y',       
225648      'z',       'o',       'u',       'a',       'i',       'o',       
225649      'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       
225650      'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       
225651      'e',       'i',       'o',       'r',       'u',       's',       
225652      't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       
225653      'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',      
225654      '\0',      '\0',      '\0',      '\0',      'a',       'b',       
225655      'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, 
225656      'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, 
225657      'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       
225658      'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       
225659      's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       
225660      'w',       'x',       'y',       'z',       'h',       't',       
225661      'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, 
225662      'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, 
225663      'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       
225664    };
225665  
225666    unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
225667    int iRes = 0;
225668    int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
225669    int iLo = 0;
225670    while( iHi>=iLo ){
225671      int iTest = (iHi + iLo) / 2;
225672      if( key >= aDia[iTest] ){
225673        iRes = iTest;
225674        iLo = iTest+1;
225675      }else{
225676        iHi = iTest-1;
225677      }
225678    }
225679    assert( key>=aDia[iRes] );
225680    if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
225681    return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
225682  }
225683  
225684  
225685  /*
225686  ** Return true if the argument interpreted as a unicode codepoint
225687  ** is a diacritical modifier character.
225688  */
225689  static int sqlite3Fts5UnicodeIsdiacritic(int c){
225690    unsigned int mask0 = 0x08029FDF;
225691    unsigned int mask1 = 0x000361F8;
225692    if( c<768 || c>817 ) return 0;
225693    return (c < 768+32) ?
225694        (mask0 & ((unsigned int)1 << (c-768))) :
225695        (mask1 & ((unsigned int)1 << (c-768-32)));
225696  }
225697  
225698  
225699  /*
225700  ** Interpret the argument as a unicode codepoint. If the codepoint
225701  ** is an upper case character that has a lower case equivalent,
225702  ** return the codepoint corresponding to the lower case version.
225703  ** Otherwise, return a copy of the argument.
225704  **
225705  ** The results are undefined if the value passed to this function
225706  ** is less than zero.
225707  */
225708  static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
225709    /* Each entry in the following array defines a rule for folding a range
225710    ** of codepoints to lower case. The rule applies to a range of nRange
225711    ** codepoints starting at codepoint iCode.
225712    **
225713    ** If the least significant bit in flags is clear, then the rule applies
225714    ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
225715    ** need to be folded). Or, if it is set, then the rule only applies to
225716    ** every second codepoint in the range, starting with codepoint C.
225717    **
225718    ** The 7 most significant bits in flags are an index into the aiOff[]
225719    ** array. If a specific codepoint C does require folding, then its lower
225720    ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
225721    **
225722    ** The contents of this array are generated by parsing the CaseFolding.txt
225723    ** file distributed as part of the "Unicode Character Database". See
225724    ** http://www.unicode.org for details.
225725    */
225726    static const struct TableEntry {
225727      unsigned short iCode;
225728      unsigned char flags;
225729      unsigned char nRange;
225730    } aEntry[] = {
225731      {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
225732      {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
225733      {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
225734      {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
225735      {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
225736      {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
225737      {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
225738      {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
225739      {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
225740      {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
225741      {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
225742      {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
225743      {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
225744      {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
225745      {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
225746      {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
225747      {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
225748      {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
225749      {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
225750      {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
225751      {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
225752      {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
225753      {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
225754      {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
225755      {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
225756      {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
225757      {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
225758      {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
225759      {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
225760      {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
225761      {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
225762      {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
225763      {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
225764      {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
225765      {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
225766      {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
225767      {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
225768      {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
225769      {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
225770      {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
225771      {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
225772      {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
225773      {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
225774      {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
225775      {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
225776      {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
225777      {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
225778      {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
225779      {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
225780      {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
225781      {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
225782      {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
225783      {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
225784      {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
225785      {65313, 14, 26},       
225786    };
225787    static const unsigned short aiOff[] = {
225788     1,     2,     8,     15,    16,    26,    28,    32,    
225789     37,    38,    40,    48,    63,    64,    69,    71,    
225790     79,    80,    116,   202,   203,   205,   206,   207,   
225791     209,   210,   211,   213,   214,   217,   218,   219,   
225792     775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
225793     54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
225794     57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
225795     65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
225796     65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
225797     65514, 65521, 65527, 65528, 65529, 
225798    };
225799  
225800    int ret = c;
225801  
225802    assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
225803  
225804    if( c<128 ){
225805      if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
225806    }else if( c<65536 ){
225807      const struct TableEntry *p;
225808      int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
225809      int iLo = 0;
225810      int iRes = -1;
225811  
225812      assert( c>aEntry[0].iCode );
225813      while( iHi>=iLo ){
225814        int iTest = (iHi + iLo) / 2;
225815        int cmp = (c - aEntry[iTest].iCode);
225816        if( cmp>=0 ){
225817          iRes = iTest;
225818          iLo = iTest+1;
225819        }else{
225820          iHi = iTest-1;
225821        }
225822      }
225823  
225824      assert( iRes>=0 && c>=aEntry[iRes].iCode );
225825      p = &aEntry[iRes];
225826      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
225827        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
225828        assert( ret>0 );
225829      }
225830  
225831      if( eRemoveDiacritic ){
225832        ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
225833      }
225834    }
225835    
225836    else if( c>=66560 && c<66600 ){
225837      ret = c + 40;
225838    }
225839  
225840    return ret;
225841  }
225842  
225843  
225844  static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){ 
225845    aArray[0] = 1;
225846    switch( zCat[0] ){
225847      case 'C':
225848            switch( zCat[1] ){
225849              case 'c': aArray[1] = 1; break;
225850              case 'f': aArray[2] = 1; break;
225851              case 'n': aArray[3] = 1; break;
225852              case 's': aArray[4] = 1; break;
225853              case 'o': aArray[31] = 1; break;
225854              case '*': 
225855                aArray[1] = 1;
225856                aArray[2] = 1;
225857                aArray[3] = 1;
225858                aArray[4] = 1;
225859                aArray[31] = 1;
225860                break;
225861              default: return 1;          }
225862            break;
225863  
225864      case 'L':
225865            switch( zCat[1] ){
225866              case 'l': aArray[5] = 1; break;
225867              case 'm': aArray[6] = 1; break;
225868              case 'o': aArray[7] = 1; break;
225869              case 't': aArray[8] = 1; break;
225870              case 'u': aArray[9] = 1; break;
225871              case 'C': aArray[30] = 1; break;
225872              case '*': 
225873                aArray[5] = 1;
225874                aArray[6] = 1;
225875                aArray[7] = 1;
225876                aArray[8] = 1;
225877                aArray[9] = 1;
225878                aArray[30] = 1;
225879                break;
225880              default: return 1;          }
225881            break;
225882  
225883      case 'M':
225884            switch( zCat[1] ){
225885              case 'c': aArray[10] = 1; break;
225886              case 'e': aArray[11] = 1; break;
225887              case 'n': aArray[12] = 1; break;
225888              case '*': 
225889                aArray[10] = 1;
225890                aArray[11] = 1;
225891                aArray[12] = 1;
225892                break;
225893              default: return 1;          }
225894            break;
225895  
225896      case 'N':
225897            switch( zCat[1] ){
225898              case 'd': aArray[13] = 1; break;
225899              case 'l': aArray[14] = 1; break;
225900              case 'o': aArray[15] = 1; break;
225901              case '*': 
225902                aArray[13] = 1;
225903                aArray[14] = 1;
225904                aArray[15] = 1;
225905                break;
225906              default: return 1;          }
225907            break;
225908  
225909      case 'P':
225910            switch( zCat[1] ){
225911              case 'c': aArray[16] = 1; break;
225912              case 'd': aArray[17] = 1; break;
225913              case 'e': aArray[18] = 1; break;
225914              case 'f': aArray[19] = 1; break;
225915              case 'i': aArray[20] = 1; break;
225916              case 'o': aArray[21] = 1; break;
225917              case 's': aArray[22] = 1; break;
225918              case '*': 
225919                aArray[16] = 1;
225920                aArray[17] = 1;
225921                aArray[18] = 1;
225922                aArray[19] = 1;
225923                aArray[20] = 1;
225924                aArray[21] = 1;
225925                aArray[22] = 1;
225926                break;
225927              default: return 1;          }
225928            break;
225929  
225930      case 'S':
225931            switch( zCat[1] ){
225932              case 'c': aArray[23] = 1; break;
225933              case 'k': aArray[24] = 1; break;
225934              case 'm': aArray[25] = 1; break;
225935              case 'o': aArray[26] = 1; break;
225936              case '*': 
225937                aArray[23] = 1;
225938                aArray[24] = 1;
225939                aArray[25] = 1;
225940                aArray[26] = 1;
225941                break;
225942              default: return 1;          }
225943            break;
225944  
225945      case 'Z':
225946            switch( zCat[1] ){
225947              case 'l': aArray[27] = 1; break;
225948              case 'p': aArray[28] = 1; break;
225949              case 's': aArray[29] = 1; break;
225950              case '*': 
225951                aArray[27] = 1;
225952                aArray[28] = 1;
225953                aArray[29] = 1;
225954                break;
225955              default: return 1;          }
225956            break;
225957  
225958    }
225959    return 0;
225960  }
225961  
225962  static u16 aFts5UnicodeBlock[] = {
225963      0,     1471,  1753,  1760,  1760,  1760,  1760,  1760,  1760,  1760,  
225964      1760,  1760,  1760,  1760,  1760,  1763,  1765,  
225965    };
225966  static u16 aFts5UnicodeMap[] = {
225967      0,     32,    33,    36,    37,    40,    41,    42,    43,    44,    
225968      45,    46,    48,    58,    60,    63,    65,    91,    92,    93,    
225969      94,    95,    96,    97,    123,   124,   125,   126,   127,   160,   
225970      161,   162,   166,   167,   168,   169,   170,   171,   172,   173,   
225971      174,   175,   176,   177,   178,   180,   181,   182,   184,   185,   
225972      186,   187,   188,   191,   192,   215,   216,   223,   247,   248,   
225973      256,   312,   313,   329,   330,   377,   383,   385,   387,   388,   
225974      391,   394,   396,   398,   402,   403,   405,   406,   409,   412,   
225975      414,   415,   417,   418,   423,   427,   428,   431,   434,   436,   
225976      437,   440,   442,   443,   444,   446,   448,   452,   453,   454,   
225977      455,   456,   457,   458,   459,   460,   461,   477,   478,   496,   
225978      497,   498,   499,   500,   503,   505,   506,   564,   570,   572,   
225979      573,   575,   577,   580,   583,   584,   592,   660,   661,   688,   
225980      706,   710,   722,   736,   741,   748,   749,   750,   751,   768,   
225981      880,   884,   885,   886,   890,   891,   894,   900,   902,   903,   
225982      904,   908,   910,   912,   913,   931,   940,   975,   977,   978,   
225983      981,   984,   1008,  1012,  1014,  1015,  1018,  1020,  1021,  1072,  
225984      1120,  1154,  1155,  1160,  1162,  1217,  1231,  1232,  1329,  1369,  
225985      1370,  1377,  1417,  1418,  1423,  1425,  1470,  1471,  1472,  1473,  
225986      1475,  1476,  1478,  1479,  1488,  1520,  1523,  1536,  1542,  1545,  
225987      1547,  1548,  1550,  1552,  1563,  1566,  1568,  1600,  1601,  1611,  
225988      1632,  1642,  1646,  1648,  1649,  1748,  1749,  1750,  1757,  1758,  
225989      1759,  1765,  1767,  1769,  1770,  1774,  1776,  1786,  1789,  1791,  
225990      1792,  1807,  1808,  1809,  1810,  1840,  1869,  1958,  1969,  1984,  
225991      1994,  2027,  2036,  2038,  2039,  2042,  2048,  2070,  2074,  2075,  
225992      2084,  2085,  2088,  2089,  2096,  2112,  2137,  2142,  2208,  2210,  
225993      2276,  2304,  2307,  2308,  2362,  2363,  2364,  2365,  2366,  2369,  
225994      2377,  2381,  2382,  2384,  2385,  2392,  2402,  2404,  2406,  2416,  
225995      2417,  2418,  2425,  2433,  2434,  2437,  2447,  2451,  2474,  2482,  
225996      2486,  2492,  2493,  2494,  2497,  2503,  2507,  2509,  2510,  2519,  
225997      2524,  2527,  2530,  2534,  2544,  2546,  2548,  2554,  2555,  2561,  
225998      2563,  2565,  2575,  2579,  2602,  2610,  2613,  2616,  2620,  2622,  
225999      2625,  2631,  2635,  2641,  2649,  2654,  2662,  2672,  2674,  2677,  
226000      2689,  2691,  2693,  2703,  2707,  2730,  2738,  2741,  2748,  2749,  
226001      2750,  2753,  2759,  2761,  2763,  2765,  2768,  2784,  2786,  2790,  
226002      2800,  2801,  2817,  2818,  2821,  2831,  2835,  2858,  2866,  2869,  
226003      2876,  2877,  2878,  2879,  2880,  2881,  2887,  2891,  2893,  2902,  
226004      2903,  2908,  2911,  2914,  2918,  2928,  2929,  2930,  2946,  2947,  
226005      2949,  2958,  2962,  2969,  2972,  2974,  2979,  2984,  2990,  3006,  
226006      3008,  3009,  3014,  3018,  3021,  3024,  3031,  3046,  3056,  3059,  
226007      3065,  3066,  3073,  3077,  3086,  3090,  3114,  3125,  3133,  3134,  
226008      3137,  3142,  3146,  3157,  3160,  3168,  3170,  3174,  3192,  3199,  
226009      3202,  3205,  3214,  3218,  3242,  3253,  3260,  3261,  3262,  3263,  
226010      3264,  3270,  3271,  3274,  3276,  3285,  3294,  3296,  3298,  3302,  
226011      3313,  3330,  3333,  3342,  3346,  3389,  3390,  3393,  3398,  3402,  
226012      3405,  3406,  3415,  3424,  3426,  3430,  3440,  3449,  3450,  3458,  
226013      3461,  3482,  3507,  3517,  3520,  3530,  3535,  3538,  3542,  3544,  
226014      3570,  3572,  3585,  3633,  3634,  3636,  3647,  3648,  3654,  3655,  
226015      3663,  3664,  3674,  3713,  3716,  3719,  3722,  3725,  3732,  3737,  
226016      3745,  3749,  3751,  3754,  3757,  3761,  3762,  3764,  3771,  3773,  
226017      3776,  3782,  3784,  3792,  3804,  3840,  3841,  3844,  3859,  3860,  
226018      3861,  3864,  3866,  3872,  3882,  3892,  3893,  3894,  3895,  3896,  
226019      3897,  3898,  3899,  3900,  3901,  3902,  3904,  3913,  3953,  3967,  
226020      3968,  3973,  3974,  3976,  3981,  3993,  4030,  4038,  4039,  4046,  
226021      4048,  4053,  4057,  4096,  4139,  4141,  4145,  4146,  4152,  4153,  
226022      4155,  4157,  4159,  4160,  4170,  4176,  4182,  4184,  4186,  4190,  
226023      4193,  4194,  4197,  4199,  4206,  4209,  4213,  4226,  4227,  4229,  
226024      4231,  4237,  4238,  4239,  4240,  4250,  4253,  4254,  4256,  4295,  
226025      4301,  4304,  4347,  4348,  4349,  4682,  4688,  4696,  4698,  4704,  
226026      4746,  4752,  4786,  4792,  4800,  4802,  4808,  4824,  4882,  4888,  
226027      4957,  4960,  4969,  4992,  5008,  5024,  5120,  5121,  5741,  5743,  
226028      5760,  5761,  5787,  5788,  5792,  5867,  5870,  5888,  5902,  5906,  
226029      5920,  5938,  5941,  5952,  5970,  5984,  5998,  6002,  6016,  6068,  
226030      6070,  6071,  6078,  6086,  6087,  6089,  6100,  6103,  6104,  6107,  
226031      6108,  6109,  6112,  6128,  6144,  6150,  6151,  6155,  6158,  6160,  
226032      6176,  6211,  6212,  6272,  6313,  6314,  6320,  6400,  6432,  6435,  
226033      6439,  6441,  6448,  6450,  6451,  6457,  6464,  6468,  6470,  6480,  
226034      6512,  6528,  6576,  6593,  6600,  6608,  6618,  6622,  6656,  6679,  
226035      6681,  6686,  6688,  6741,  6742,  6743,  6744,  6752,  6753,  6754,  
226036      6755,  6757,  6765,  6771,  6783,  6784,  6800,  6816,  6823,  6824,  
226037      6912,  6916,  6917,  6964,  6965,  6966,  6971,  6972,  6973,  6978,  
226038      6979,  6981,  6992,  7002,  7009,  7019,  7028,  7040,  7042,  7043,  
226039      7073,  7074,  7078,  7080,  7082,  7083,  7084,  7086,  7088,  7098,  
226040      7142,  7143,  7144,  7146,  7149,  7150,  7151,  7154,  7164,  7168,  
226041      7204,  7212,  7220,  7222,  7227,  7232,  7245,  7248,  7258,  7288,  
226042      7294,  7360,  7376,  7379,  7380,  7393,  7394,  7401,  7405,  7406,  
226043      7410,  7412,  7413,  7424,  7468,  7531,  7544,  7545,  7579,  7616,  
226044      7676,  7680,  7830,  7838,  7936,  7944,  7952,  7960,  7968,  7976,  
226045      7984,  7992,  8000,  8008,  8016,  8025,  8027,  8029,  8031,  8033,  
226046      8040,  8048,  8064,  8072,  8080,  8088,  8096,  8104,  8112,  8118,  
226047      8120,  8124,  8125,  8126,  8127,  8130,  8134,  8136,  8140,  8141,  
226048      8144,  8150,  8152,  8157,  8160,  8168,  8173,  8178,  8182,  8184,  
226049      8188,  8189,  8192,  8203,  8208,  8214,  8216,  8217,  8218,  8219,  
226050      8221,  8222,  8223,  8224,  8232,  8233,  8234,  8239,  8240,  8249,  
226051      8250,  8251,  8255,  8257,  8260,  8261,  8262,  8263,  8274,  8275,  
226052      8276,  8277,  8287,  8288,  8298,  8304,  8305,  8308,  8314,  8317,  
226053      8318,  8319,  8320,  8330,  8333,  8334,  8336,  8352,  8400,  8413,  
226054      8417,  8418,  8421,  8448,  8450,  8451,  8455,  8456,  8458,  8459,  
226055      8462,  8464,  8467,  8468,  8469,  8470,  8472,  8473,  8478,  8484,  
226056      8485,  8486,  8487,  8488,  8489,  8490,  8494,  8495,  8496,  8500,  
226057      8501,  8505,  8506,  8508,  8510,  8512,  8517,  8519,  8522,  8523,  
226058      8524,  8526,  8527,  8528,  8544,  8579,  8581,  8585,  8592,  8597,  
226059      8602,  8604,  8608,  8609,  8611,  8612,  8614,  8615,  8622,  8623,  
226060      8654,  8656,  8658,  8659,  8660,  8661,  8692,  8960,  8968,  8972,  
226061      8992,  8994,  9001,  9002,  9003,  9084,  9085,  9115,  9140,  9180,  
226062      9186,  9216,  9280,  9312,  9372,  9450,  9472,  9655,  9656,  9665,  
226063      9666,  9720,  9728,  9839,  9840,  9985,  10088, 10089, 10090, 10091, 
226064      10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, 
226065      10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217, 
226066      10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627, 
226067      10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637, 
226068      10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647, 
226069      10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750, 
226070      11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365, 
226071      11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393, 
226072      11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520, 
226073      11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696, 
226074      11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780, 
226075      11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800, 
226076      11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812, 
226077      11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904, 
226078      11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296, 
226079      12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306, 
226080      12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317, 
226081      12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347, 
226082      12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449, 
226083      12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736, 
226084      12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938, 
226085      12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981, 
226086      40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528, 
226087      42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624, 
226088      42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800, 
226089      42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912, 
226090      43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043, 
226091      43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136, 
226092      43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264, 
226093      43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395, 
226094      43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472, 
226095      43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588, 
226096      43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643, 
226097      43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713, 
226098      43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762, 
226099      43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003, 
226100      44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203, 
226101      55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112, 
226102      64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320, 
226103      64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020, 
226104      65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075, 
226105      65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086, 
226106      65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097, 
226107      65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118, 
226108      65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279, 
226109      65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294, 
226110      65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343, 
226111      65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378, 
226112      65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490, 
226113      65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529, 
226114      65532, 0,     13,    40,    60,    63,    80,    128,   256,   263,   
226115      311,   320,   373,   377,   394,   400,   464,   509,   640,   672,   
226116      768,   800,   816,   833,   834,   842,   896,   927,   928,   968,   
226117      976,   977,   1024,  1064,  1104,  1184,  2048,  2056,  2058,  2103,  
226118      2108,  2111,  2135,  2136,  2304,  2326,  2335,  2336,  2367,  2432,  
226119      2494,  2560,  2561,  2565,  2572,  2576,  2581,  2585,  2616,  2623,  
226120      2624,  2640,  2656,  2685,  2687,  2816,  2873,  2880,  2904,  2912,  
226121      2936,  3072,  3680,  4096,  4097,  4098,  4099,  4152,  4167,  4178,  
226122      4198,  4224,  4226,  4227,  4272,  4275,  4279,  4281,  4283,  4285,  
226123      4286,  4304,  4336,  4352,  4355,  4391,  4396,  4397,  4406,  4416,  
226124      4480,  4482,  4483,  4531,  4534,  4543,  4545,  4549,  4560,  5760,  
226125      5803,  5804,  5805,  5806,  5808,  5814,  5815,  5824,  8192,  9216,  
226126      9328,  12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248, 
226127      53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637, 
226128      53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298, 
226129      54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441, 
226130      54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541, 
226131      54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662, 
226132      54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922, 
226133      54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062, 
226134      55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178, 
226135      55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961, 
226136      60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003, 
226137      61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028, 
226138      61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099, 
226139      61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744, 
226140      61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368, 
226141      62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971, 
226142      63045, 63104, 63232, 0,     42710, 42752, 46900, 46912, 47133, 63488, 
226143      1,     32,    256,   0,     65533, 
226144    };
226145  static u16 aFts5UnicodeData[] = {
226146      1025,  61,    117,   55,    117,   54,    50,    53,    57,    53,    
226147      49,    85,    333,   85,    121,   85,    841,   54,    53,    50,    
226148      56,    48,    56,    837,   54,    57,    50,    57,    1057,  61,    
226149      53,    151,   58,    53,    56,    58,    39,    52,    57,    34,    
226150      58,    56,    58,    57,    79,    56,    37,    85,    56,    47,    
226151      39,    51,    111,   53,    745,   57,    233,   773,   57,    261,   
226152      1822,  37,    542,   37,    1534,  222,   69,    73,    37,    126,   
226153      126,   73,    69,    137,   37,    73,    37,    105,   101,   73,    
226154      37,    73,    37,    190,   158,   37,    126,   126,   73,    37,    
226155      126,   94,    37,    39,    94,    69,    135,   41,    40,    37,    
226156      41,    40,    37,    41,    40,    37,    542,   37,    606,   37,    
226157      41,    40,    37,    126,   73,    37,    1886,  197,   73,    37,    
226158      73,    69,    126,   105,   37,    286,   2181,  39,    869,   582,   
226159      152,   390,   472,   166,   248,   38,    56,    38,    568,   3596,  
226160      158,   38,    56,    94,    38,    101,   53,    88,    41,    53,    
226161      105,   41,    73,    37,    553,   297,   1125,  94,    37,    105,   
226162      101,   798,   133,   94,    57,    126,   94,    37,    1641,  1541,  
226163      1118,  58,    172,   75,    1790,  478,   37,    2846,  1225,  38,    
226164      213,   1253,  53,    49,    55,    1452,  49,    44,    53,    76,    
226165      53,    76,    53,    44,    871,   103,   85,    162,   121,   85,    
226166      55,    85,    90,    364,   53,    85,    1031,  38,    327,   684,   
226167      333,   149,   71,    44,    3175,  53,    39,    236,   34,    58,    
226168      204,   70,    76,    58,    140,   71,    333,   103,   90,    39,    
226169      469,   34,    39,    44,    967,   876,   2855,  364,   39,    333,   
226170      1063,  300,   70,    58,    117,   38,    711,   140,   38,    300,   
226171      38,    108,   38,    172,   501,   807,   108,   53,    39,    359,   
226172      876,   108,   42,    1735,  44,    42,    44,    39,    106,   268,   
226173      138,   44,    74,    39,    236,   327,   76,    85,    333,   53,    
226174      38,    199,   231,   44,    74,    263,   71,    711,   231,   39,    
226175      135,   44,    39,    106,   140,   74,    74,    44,    39,    42,    
226176      71,    103,   76,    333,   71,    87,    207,   58,    55,    76,    
226177      42,    199,   71,    711,   231,   71,    71,    71,    44,    106,   
226178      76,    76,    108,   44,    135,   39,    333,   76,    103,   44,    
226179      76,    42,    295,   103,   711,   231,   71,    167,   44,    39,    
226180      106,   172,   76,    42,    74,    44,    39,    71,    76,    333,   
226181      53,    55,    44,    74,    263,   71,    711,   231,   71,    167,   
226182      44,    39,    42,    44,    42,    140,   74,    74,    44,    44,    
226183      42,    71,    103,   76,    333,   58,    39,    207,   44,    39,    
226184      199,   103,   135,   71,    39,    71,    71,    103,   391,   74,    
226185      44,    74,    106,   106,   44,    39,    42,    333,   111,   218,   
226186      55,    58,    106,   263,   103,   743,   327,   167,   39,    108,   
226187      138,   108,   140,   76,    71,    71,    76,    333,   239,   58,    
226188      74,    263,   103,   743,   327,   167,   44,    39,    42,    44,    
226189      170,   44,    74,    74,    76,    74,    39,    71,    76,    333,   
226190      71,    74,    263,   103,   1319,  39,    106,   140,   106,   106,   
226191      44,    39,    42,    71,    76,    333,   207,   58,    199,   74,    
226192      583,   775,   295,   39,    231,   44,    106,   108,   44,    266,   
226193      74,    53,    1543,  44,    71,    236,   55,    199,   38,    268,   
226194      53,    333,   85,    71,    39,    71,    39,    39,    135,   231,   
226195      103,   39,    39,    71,    135,   44,    71,    204,   76,    39,    
226196      167,   38,    204,   333,   135,   39,    122,   501,   58,    53,    
226197      122,   76,    218,   333,   335,   58,    44,    58,    44,    58,    
226198      44,    54,    50,    54,    50,    74,    263,   1159,  460,   42,    
226199      172,   53,    76,    167,   364,   1164,  282,   44,    218,   90,    
226200      181,   154,   85,    1383,  74,    140,   42,    204,   42,    76,    
226201      74,    76,    39,    333,   213,   199,   74,    76,    135,   108,   
226202      39,    106,   71,    234,   103,   140,   423,   44,    74,    76,    
226203      202,   44,    39,    42,    333,   106,   44,    90,    1225,  41,    
226204      41,    1383,  53,    38,    10631, 135,   231,   39,    135,   1319,  
226205      135,   1063,  135,   231,   39,    135,   487,   1831,  135,   2151,  
226206      108,   309,   655,   519,   346,   2727,  49,    19847, 85,    551,   
226207      61,    839,   54,    50,    2407,  117,   110,   423,   135,   108,   
226208      583,   108,   85,    583,   76,    423,   103,   76,    1671,  76,    
226209      42,    236,   266,   44,    74,    364,   117,   38,    117,   55,    
226210      39,    44,    333,   335,   213,   49,    149,   108,   61,    333,   
226211      1127,  38,    1671,  1319,  44,    39,    2247,  935,   108,   138,   
226212      76,    106,   74,    44,    202,   108,   58,    85,    333,   967,   
226213      167,   1415,  554,   231,   74,    333,   47,    1114,  743,   76,    
226214      106,   85,    1703,  42,    44,    42,    236,   44,    42,    44,    
226215      74,    268,   202,   332,   44,    333,   333,   245,   38,    213,   
226216      140,   42,    1511,  44,    42,    172,   42,    44,    170,   44,    
226217      74,    231,   333,   245,   346,   300,   314,   76,    42,    967,   
226218      42,    140,   74,    76,    42,    44,    74,    71,    333,   1415,  
226219      44,    42,    76,    106,   44,    42,    108,   74,    149,   1159,  
226220      266,   268,   74,    76,    181,   333,   103,   333,   967,   198,   
226221      85,    277,   108,   53,    428,   42,    236,   135,   44,    135,   
226222      74,    44,    71,    1413,  2022,  421,   38,    1093,  1190,  1260,  
226223      140,   4830,  261,   3166,  261,   265,   197,   201,   261,   265,   
226224      261,   265,   197,   201,   261,   41,    41,    41,    94,    229,   
226225      265,   453,   261,   264,   261,   264,   261,   264,   165,   69,    
226226      137,   40,    56,    37,    120,   101,   69,    137,   40,    120,   
226227      133,   69,    137,   120,   261,   169,   120,   101,   69,    137,   
226228      40,    88,    381,   162,   209,   85,    52,    51,    54,    84,    
226229      51,    54,    52,    277,   59,    60,    162,   61,    309,   52,    
226230      51,    149,   80,    117,   57,    54,    50,    373,   57,    53,    
226231      48,    341,   61,    162,   194,   47,    38,    207,   121,   54,    
226232      50,    38,    335,   121,   54,    50,    422,   855,   428,   139,   
226233      44,    107,   396,   90,    41,    154,   41,    90,    37,    105,   
226234      69,    105,   37,    58,    41,    90,    57,    169,   218,   41,    
226235      58,    41,    58,    41,    58,    137,   58,    37,    137,   37,    
226236      135,   37,    90,    69,    73,    185,   94,    101,   58,    57,    
226237      90,    37,    58,    527,   1134,  94,    142,   47,    185,   186,   
226238      89,    154,   57,    90,    57,    90,    57,    250,   57,    1018,  
226239      89,    90,    57,    58,    57,    1018,  8601,  282,   153,   666,   
226240      89,    250,   54,    50,    2618,  57,    986,   825,   1306,  217,   
226241      602,   1274,  378,   1935,  2522,  719,   5882,  57,    314,   57,    
226242      1754,  281,   3578,  57,    4634,  3322,  54,    50,    54,    50,    
226243      54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    
226244      975,   1434,  185,   54,    50,    1017,  54,    50,    54,    50,    
226245      54,    50,    54,    50,    54,    50,    537,   8218,  4217,  54,    
226246      50,    54,    50,    54,    50,    54,    50,    54,    50,    54,    
226247      50,    54,    50,    54,    50,    54,    50,    54,    50,    54,    
226248      50,    2041,  54,    50,    54,    50,    1049,  54,    50,    8281,  
226249      1562,  697,   90,    217,   346,   1513,  1509,  126,   73,    69,    
226250      254,   105,   37,    94,    37,    94,    165,   70,    105,   37,    
226251      3166,  37,    218,   158,   108,   94,    149,   47,    85,    1221,  
226252      37,    37,    1799,  38,    53,    44,    743,   231,   231,   231,   
226253      231,   231,   231,   231,   231,   1036,  85,    52,    51,    52,    
226254      51,    117,   52,    51,    53,    52,    51,    309,   49,    85,    
226255      49,    53,    52,    51,    85,    52,    51,    54,    50,    54,    
226256      50,    54,    50,    54,    50,    181,   38,    341,   81,    858,   
226257      2874,  6874,  410,   61,    117,   58,    38,    39,    46,    54,    
226258      50,    54,    50,    54,    50,    54,    50,    54,    50,    90,    
226259      54,    50,    54,    50,    54,    50,    54,    50,    49,    54,    
226260      82,    58,    302,   140,   74,    49,    166,   90,    110,   38,    
226261      39,    53,    90,    2759,  76,    88,    70,    39,    49,    2887,  
226262      53,    102,   39,    1319,  3015,  90,    143,   346,   871,   1178,  
226263      519,   1018,  335,   986,   271,   58,    495,   1050,  335,   1274,  
226264      495,   2042,  8218,  39,    39,    2074,  39,    39,    679,   38,    
226265      36583, 1786,  1287,  198,   85,    8583,  38,    117,   519,   333,   
226266      71,    1502,  39,    44,    107,   53,    332,   53,    38,    798,   
226267      44,    2247,  334,   76,    213,   760,   294,   88,    478,   69,    
226268      2014,  38,    261,   190,   350,   38,    88,    158,   158,   382,   
226269      70,    37,    231,   44,    103,   44,    135,   44,    743,   74,    
226270      76,    42,    154,   207,   90,    55,    58,    1671,  149,   74,    
226271      1607,  522,   44,    85,    333,   588,   199,   117,   39,    333,   
226272      903,   268,   85,    743,   364,   74,    53,    935,   108,   42,    
226273      1511,  44,    74,    140,   74,    44,    138,   437,   38,    333,   
226274      85,    1319,  204,   74,    76,    74,    76,    103,   44,    263,   
226275      44,    42,    333,   149,   519,   38,    199,   122,   39,    42,    
226276      1543,  44,    39,    108,   71,    76,    167,   76,    39,    44,    
226277      39,    71,    38,    85,    359,   42,    76,    74,    85,    39,    
226278      70,    42,    44,    199,   199,   199,   231,   231,   1127,  74,    
226279      44,    74,    44,    74,    53,    42,    44,    333,   39,    39,    
226280      743,   1575,  36,    68,    68,    36,    63,    63,    11719, 3399,  
226281      229,   165,   39,    44,    327,   57,    423,   167,   39,    71,    
226282      71,    3463,  536,   11623, 54,    50,    2055,  1735,  391,   55,    
226283      58,    524,   245,   54,    50,    53,    236,   53,    81,    80,    
226284      54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    
226285      54,    50,    54,    50,    54,    50,    85,    54,    50,    149,   
226286      112,   117,   149,   49,    54,    50,    54,    50,    54,    50,    
226287      117,   57,    49,    121,   53,    55,    85,    167,   4327,  34,    
226288      117,   55,    117,   54,    50,    53,    57,    53,    49,    85,    
226289      333,   85,    121,   85,    841,   54,    53,    50,    56,    48,    
226290      56,    837,   54,    57,    50,    57,    54,    50,    53,    54,    
226291      50,    85,    327,   38,    1447,  70,    999,   199,   199,   199,   
226292      103,   87,    57,    56,    58,    87,    58,    153,   90,    98,    
226293      90,    391,   839,   615,   71,    487,   455,   3943,  117,   1455,  
226294      314,   1710,  143,   570,   47,    410,   1466,  44,    935,   1575,  
226295      999,   143,   551,   46,    263,   46,    967,   53,    1159,  263,   
226296      53,    174,   1289,  1285,  2503,  333,   199,   39,    1415,  71,    
226297      39,    743,   53,    271,   711,   207,   53,    839,   53,    1799,  
226298      71,    39,    108,   76,    140,   135,   103,   871,   108,   44,    
226299      271,   309,   935,   79,    53,    1735,  245,   711,   271,   615,   
226300      271,   2343,  1007,  42,    44,    42,    1703,  492,   245,   655,   
226301      333,   76,    42,    1447,  106,   140,   74,    76,    85,    34,    
226302      149,   807,   333,   108,   1159,  172,   42,    268,   333,   149,   
226303      76,    42,    1543,  106,   300,   74,    135,   149,   333,   1383,  
226304      44,    42,    44,    74,    204,   42,    44,    333,   28135, 3182,  
226305      149,   34279, 18215, 2215,  39,    1482,  140,   422,   71,    7898,  
226306      1274,  1946,  74,    108,   122,   202,   258,   268,   90,    236,   
226307      986,   140,   1562,  2138,  108,   58,    2810,  591,   841,   837,   
226308      841,   229,   581,   841,   837,   41,    73,    41,    73,    137,   
226309      265,   133,   37,    229,   357,   841,   837,   73,    137,   265,   
226310      233,   837,   73,    137,   169,   41,    233,   837,   841,   837,   
226311      841,   837,   841,   837,   841,   837,   841,   837,   841,   901,   
226312      809,   57,    805,   57,    197,   809,   57,    805,   57,    197,   
226313      809,   57,    805,   57,    197,   809,   57,    805,   57,    197,   
226314      809,   57,    805,   57,    197,   94,    1613,  135,   871,   71,    
226315      39,    39,    327,   135,   39,    39,    39,    39,    39,    39,    
226316      103,   71,    39,    39,    39,    39,    39,    39,    71,    39,    
226317      135,   231,   135,   135,   39,    327,   551,   103,   167,   551,   
226318      89,    1434,  3226,  506,   474,   506,   506,   367,   1018,  1946,  
226319      1402,  954,   1402,  314,   90,    1082,  218,   2266,  666,   1210,  
226320      186,   570,   2042,  58,    5850,  154,   2010,  154,   794,   2266,  
226321      378,   2266,  3738,  39,    39,    39,    39,    39,    39,    17351, 
226322      34,    3074,  7692,  63,    63,    
226323    };
226324  
226325  static int sqlite3Fts5UnicodeCategory(u32 iCode) { 
226326    int iRes = -1;
226327    int iHi;
226328    int iLo;
226329    int ret;
226330    u16 iKey;
226331  
226332    if( iCode>=(1<<20) ){
226333      return 0;
226334    }
226335    iLo = aFts5UnicodeBlock[(iCode>>16)];
226336    iHi = aFts5UnicodeBlock[1+(iCode>>16)];
226337    iKey = (iCode & 0xFFFF);
226338    while( iHi>iLo ){
226339      int iTest = (iHi + iLo) / 2;
226340      assert( iTest>=iLo && iTest<iHi );
226341      if( iKey>=aFts5UnicodeMap[iTest] ){
226342        iRes = iTest;
226343        iLo = iTest+1;
226344      }else{
226345        iHi = iTest;
226346      }
226347    }
226348  
226349    if( iRes<0 ) return 0;
226350    if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
226351    ret = aFts5UnicodeData[iRes] & 0x1F;
226352    if( ret!=30 ) return ret;
226353    return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
226354  }
226355  
226356  static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
226357    int i = 0;
226358    int iTbl = 0;
226359    while( i<128 ){
226360      int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
226361      int n = (aFts5UnicodeData[iTbl] >> 5) + i;
226362      for(; i<128 && i<n; i++){
226363        aAscii[i] = bToken;
226364      }
226365      iTbl++;
226366    }
226367  }
226368  
226369  /*
226370  ** 2015 May 30
226371  **
226372  ** The author disclaims copyright to this source code.  In place of
226373  ** a legal notice, here is a blessing:
226374  **
226375  **    May you do good and not evil.
226376  **    May you find forgiveness for yourself and forgive others.
226377  **    May you share freely, never taking more than you give.
226378  **
226379  ******************************************************************************
226380  **
226381  ** Routines for varint serialization and deserialization.
226382  */
226383  
226384  
226385  /* #include "fts5Int.h" */
226386  
226387  /*
226388  ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
226389  ** Except, this version does handle the single byte case that the core
226390  ** version depends on being handled before its function is called.
226391  */
226392  static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
226393    u32 a,b;
226394  
226395    /* The 1-byte case. Overwhelmingly the most common. */
226396    a = *p;
226397    /* a: p0 (unmasked) */
226398    if (!(a&0x80))
226399    {
226400      /* Values between 0 and 127 */
226401      *v = a;
226402      return 1;
226403    }
226404  
226405    /* The 2-byte case */
226406    p++;
226407    b = *p;
226408    /* b: p1 (unmasked) */
226409    if (!(b&0x80))
226410    {
226411      /* Values between 128 and 16383 */
226412      a &= 0x7f;
226413      a = a<<7;
226414      *v = a | b;
226415      return 2;
226416    }
226417  
226418    /* The 3-byte case */
226419    p++;
226420    a = a<<14;
226421    a |= *p;
226422    /* a: p0<<14 | p2 (unmasked) */
226423    if (!(a&0x80))
226424    {
226425      /* Values between 16384 and 2097151 */
226426      a &= (0x7f<<14)|(0x7f);
226427      b &= 0x7f;
226428      b = b<<7;
226429      *v = a | b;
226430      return 3;
226431    }
226432  
226433    /* A 32-bit varint is used to store size information in btrees.
226434    ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
226435    ** A 3-byte varint is sufficient, for example, to record the size
226436    ** of a 1048569-byte BLOB or string.
226437    **
226438    ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
226439    ** rare larger cases can be handled by the slower 64-bit varint
226440    ** routine.
226441    */
226442    {
226443      u64 v64;
226444      u8 n;
226445      p -= 2;
226446      n = sqlite3Fts5GetVarint(p, &v64);
226447      *v = ((u32)v64) & 0x7FFFFFFF;
226448      assert( n>3 && n<=9 );
226449      return n;
226450    }
226451  }
226452  
226453  
226454  /*
226455  ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
226456  ** are defined here rather than simply putting the constant expressions
226457  ** inline in order to work around bugs in the RVT compiler.
226458  **
226459  ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
226460  **
226461  ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
226462  */
226463  #define SLOT_2_0     0x001fc07f
226464  #define SLOT_4_2_0   0xf01fc07f
226465  
226466  /*
226467  ** Read a 64-bit variable-length integer from memory starting at p[0].
226468  ** Return the number of bytes read.  The value is stored in *v.
226469  */
226470  static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
226471    u32 a,b,s;
226472  
226473    a = *p;
226474    /* a: p0 (unmasked) */
226475    if (!(a&0x80))
226476    {
226477      *v = a;
226478      return 1;
226479    }
226480  
226481    p++;
226482    b = *p;
226483    /* b: p1 (unmasked) */
226484    if (!(b&0x80))
226485    {
226486      a &= 0x7f;
226487      a = a<<7;
226488      a |= b;
226489      *v = a;
226490      return 2;
226491    }
226492  
226493    /* Verify that constants are precomputed correctly */
226494    assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
226495    assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
226496  
226497    p++;
226498    a = a<<14;
226499    a |= *p;
226500    /* a: p0<<14 | p2 (unmasked) */
226501    if (!(a&0x80))
226502    {
226503      a &= SLOT_2_0;
226504      b &= 0x7f;
226505      b = b<<7;
226506      a |= b;
226507      *v = a;
226508      return 3;
226509    }
226510  
226511    /* CSE1 from below */
226512    a &= SLOT_2_0;
226513    p++;
226514    b = b<<14;
226515    b |= *p;
226516    /* b: p1<<14 | p3 (unmasked) */
226517    if (!(b&0x80))
226518    {
226519      b &= SLOT_2_0;
226520      /* moved CSE1 up */
226521      /* a &= (0x7f<<14)|(0x7f); */
226522      a = a<<7;
226523      a |= b;
226524      *v = a;
226525      return 4;
226526    }
226527  
226528    /* a: p0<<14 | p2 (masked) */
226529    /* b: p1<<14 | p3 (unmasked) */
226530    /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
226531    /* moved CSE1 up */
226532    /* a &= (0x7f<<14)|(0x7f); */
226533    b &= SLOT_2_0;
226534    s = a;
226535    /* s: p0<<14 | p2 (masked) */
226536  
226537    p++;
226538    a = a<<14;
226539    a |= *p;
226540    /* a: p0<<28 | p2<<14 | p4 (unmasked) */
226541    if (!(a&0x80))
226542    {
226543      /* we can skip these cause they were (effectively) done above in calc'ing s */
226544      /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
226545      /* b &= (0x7f<<14)|(0x7f); */
226546      b = b<<7;
226547      a |= b;
226548      s = s>>18;
226549      *v = ((u64)s)<<32 | a;
226550      return 5;
226551    }
226552  
226553    /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
226554    s = s<<7;
226555    s |= b;
226556    /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
226557  
226558    p++;
226559    b = b<<14;
226560    b |= *p;
226561    /* b: p1<<28 | p3<<14 | p5 (unmasked) */
226562    if (!(b&0x80))
226563    {
226564      /* we can skip this cause it was (effectively) done above in calc'ing s */
226565      /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
226566      a &= SLOT_2_0;
226567      a = a<<7;
226568      a |= b;
226569      s = s>>18;
226570      *v = ((u64)s)<<32 | a;
226571      return 6;
226572    }
226573  
226574    p++;
226575    a = a<<14;
226576    a |= *p;
226577    /* a: p2<<28 | p4<<14 | p6 (unmasked) */
226578    if (!(a&0x80))
226579    {
226580      a &= SLOT_4_2_0;
226581      b &= SLOT_2_0;
226582      b = b<<7;
226583      a |= b;
226584      s = s>>11;
226585      *v = ((u64)s)<<32 | a;
226586      return 7;
226587    }
226588  
226589    /* CSE2 from below */
226590    a &= SLOT_2_0;
226591    p++;
226592    b = b<<14;
226593    b |= *p;
226594    /* b: p3<<28 | p5<<14 | p7 (unmasked) */
226595    if (!(b&0x80))
226596    {
226597      b &= SLOT_4_2_0;
226598      /* moved CSE2 up */
226599      /* a &= (0x7f<<14)|(0x7f); */
226600      a = a<<7;
226601      a |= b;
226602      s = s>>4;
226603      *v = ((u64)s)<<32 | a;
226604      return 8;
226605    }
226606  
226607    p++;
226608    a = a<<15;
226609    a |= *p;
226610    /* a: p4<<29 | p6<<15 | p8 (unmasked) */
226611  
226612    /* moved CSE2 up */
226613    /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
226614    b &= SLOT_2_0;
226615    b = b<<8;
226616    a |= b;
226617  
226618    s = s<<4;
226619    b = p[-4];
226620    b &= 0x7f;
226621    b = b>>3;
226622    s |= b;
226623  
226624    *v = ((u64)s)<<32 | a;
226625  
226626    return 9;
226627  }
226628  
226629  /*
226630  ** The variable-length integer encoding is as follows:
226631  **
226632  ** KEY:
226633  **         A = 0xxxxxxx    7 bits of data and one flag bit
226634  **         B = 1xxxxxxx    7 bits of data and one flag bit
226635  **         C = xxxxxxxx    8 bits of data
226636  **
226637  **  7 bits - A
226638  ** 14 bits - BA
226639  ** 21 bits - BBA
226640  ** 28 bits - BBBA
226641  ** 35 bits - BBBBA
226642  ** 42 bits - BBBBBA
226643  ** 49 bits - BBBBBBA
226644  ** 56 bits - BBBBBBBA
226645  ** 64 bits - BBBBBBBBC
226646  */
226647  
226648  #ifdef SQLITE_NOINLINE
226649  # define FTS5_NOINLINE SQLITE_NOINLINE
226650  #else
226651  # define FTS5_NOINLINE
226652  #endif
226653  
226654  /*
226655  ** Write a 64-bit variable-length integer to memory starting at p[0].
226656  ** The length of data write will be between 1 and 9 bytes.  The number
226657  ** of bytes written is returned.
226658  **
226659  ** A variable-length integer consists of the lower 7 bits of each byte
226660  ** for all bytes that have the 8th bit set and one byte with the 8th
226661  ** bit clear.  Except, if we get to the 9th byte, it stores the full
226662  ** 8 bits and is the last byte.
226663  */
226664  static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
226665    int i, j, n;
226666    u8 buf[10];
226667    if( v & (((u64)0xff000000)<<32) ){
226668      p[8] = (u8)v;
226669      v >>= 8;
226670      for(i=7; i>=0; i--){
226671        p[i] = (u8)((v & 0x7f) | 0x80);
226672        v >>= 7;
226673      }
226674      return 9;
226675    }    
226676    n = 0;
226677    do{
226678      buf[n++] = (u8)((v & 0x7f) | 0x80);
226679      v >>= 7;
226680    }while( v!=0 );
226681    buf[0] &= 0x7f;
226682    assert( n<=9 );
226683    for(i=0, j=n-1; j>=0; j--, i++){
226684      p[i] = buf[j];
226685    }
226686    return n;
226687  }
226688  
226689  static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
226690    if( v<=0x7f ){
226691      p[0] = v&0x7f;
226692      return 1;
226693    }
226694    if( v<=0x3fff ){
226695      p[0] = ((v>>7)&0x7f)|0x80;
226696      p[1] = v&0x7f;
226697      return 2;
226698    }
226699    return fts5PutVarint64(p,v);
226700  }
226701  
226702  
226703  static int sqlite3Fts5GetVarintLen(u32 iVal){
226704  #if 0
226705    if( iVal<(1 << 7 ) ) return 1;
226706  #endif
226707    assert( iVal>=(1 << 7) );
226708    if( iVal<(1 << 14) ) return 2;
226709    if( iVal<(1 << 21) ) return 3;
226710    if( iVal<(1 << 28) ) return 4;
226711    return 5;
226712  }
226713  
226714  /*
226715  ** 2015 May 08
226716  **
226717  ** The author disclaims copyright to this source code.  In place of
226718  ** a legal notice, here is a blessing:
226719  **
226720  **    May you do good and not evil.
226721  **    May you find forgiveness for yourself and forgive others.
226722  **    May you share freely, never taking more than you give.
226723  **
226724  ******************************************************************************
226725  **
226726  ** This is an SQLite virtual table module implementing direct access to an
226727  ** existing FTS5 index. The module may create several different types of 
226728  ** tables:
226729  **
226730  ** col:
226731  **     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
226732  **
226733  **   One row for each term/column combination. The value of $doc is set to
226734  **   the number of fts5 rows that contain at least one instance of term
226735  **   $term within column $col. Field $cnt is set to the total number of 
226736  **   instances of term $term in column $col (in any row of the fts5 table). 
226737  **
226738  ** row:
226739  **     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
226740  **
226741  **   One row for each term in the database. The value of $doc is set to
226742  **   the number of fts5 rows that contain at least one instance of term
226743  **   $term. Field $cnt is set to the total number of instances of term 
226744  **   $term in the database.
226745  **
226746  ** instance:
226747  **     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
226748  **
226749  **   One row for each term instance in the database. 
226750  */
226751  
226752  
226753  /* #include "fts5Int.h" */
226754  
226755  
226756  typedef struct Fts5VocabTable Fts5VocabTable;
226757  typedef struct Fts5VocabCursor Fts5VocabCursor;
226758  
226759  struct Fts5VocabTable {
226760    sqlite3_vtab base;
226761    char *zFts5Tbl;                 /* Name of fts5 table */
226762    char *zFts5Db;                  /* Db containing fts5 table */
226763    sqlite3 *db;                    /* Database handle */
226764    Fts5Global *pGlobal;            /* FTS5 global object for this database */
226765    int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */
226766  };
226767  
226768  struct Fts5VocabCursor {
226769    sqlite3_vtab_cursor base;
226770    sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
226771    Fts5Table *pFts5;               /* Associated FTS5 table */
226772  
226773    int bEof;                       /* True if this cursor is at EOF */
226774    Fts5IndexIter *pIter;           /* Term/rowid iterator object */
226775  
226776    int nLeTerm;                    /* Size of zLeTerm in bytes */
226777    char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
226778  
226779    /* These are used by 'col' tables only */
226780    int iCol;
226781    i64 *aCnt;
226782    i64 *aDoc;
226783  
226784    /* Output values used by all tables. */
226785    i64 rowid;                      /* This table's current rowid value */
226786    Fts5Buffer term;                /* Current value of 'term' column */
226787  
226788    /* Output values Used by 'instance' tables only */
226789    i64 iInstPos;
226790    int iInstOff;
226791  };
226792  
226793  #define FTS5_VOCAB_COL      0
226794  #define FTS5_VOCAB_ROW      1
226795  #define FTS5_VOCAB_INSTANCE 2
226796  
226797  #define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
226798  #define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
226799  #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
226800  
226801  /*
226802  ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
226803  */
226804  #define FTS5_VOCAB_TERM_EQ 0x01
226805  #define FTS5_VOCAB_TERM_GE 0x02
226806  #define FTS5_VOCAB_TERM_LE 0x04
226807  
226808  
226809  /*
226810  ** Translate a string containing an fts5vocab table type to an 
226811  ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
226812  ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
226813  ** and return SQLITE_ERROR.
226814  */
226815  static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
226816    int rc = SQLITE_OK;
226817    char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
226818    if( rc==SQLITE_OK ){
226819      sqlite3Fts5Dequote(zCopy);
226820      if( sqlite3_stricmp(zCopy, "col")==0 ){
226821        *peType = FTS5_VOCAB_COL;
226822      }else
226823  
226824      if( sqlite3_stricmp(zCopy, "row")==0 ){
226825        *peType = FTS5_VOCAB_ROW;
226826      }else
226827      if( sqlite3_stricmp(zCopy, "instance")==0 ){
226828        *peType = FTS5_VOCAB_INSTANCE;
226829      }else
226830      {
226831        *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
226832        rc = SQLITE_ERROR;
226833      }
226834      sqlite3_free(zCopy);
226835    }
226836  
226837    return rc;
226838  }
226839  
226840  
226841  /*
226842  ** The xDisconnect() virtual table method.
226843  */
226844  static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
226845    Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
226846    sqlite3_free(pTab);
226847    return SQLITE_OK;
226848  }
226849  
226850  /*
226851  ** The xDestroy() virtual table method.
226852  */
226853  static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
226854    Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
226855    sqlite3_free(pTab);
226856    return SQLITE_OK;
226857  }
226858  
226859  /*
226860  ** This function is the implementation of both the xConnect and xCreate
226861  ** methods of the FTS3 virtual table.
226862  **
226863  ** The argv[] array contains the following:
226864  **
226865  **   argv[0]   -> module name  ("fts5vocab")
226866  **   argv[1]   -> database name
226867  **   argv[2]   -> table name
226868  **
226869  ** then:
226870  **
226871  **   argv[3]   -> name of fts5 table
226872  **   argv[4]   -> type of fts5vocab table
226873  **
226874  ** or, for tables in the TEMP schema only.
226875  **
226876  **   argv[3]   -> name of fts5 tables database
226877  **   argv[4]   -> name of fts5 table
226878  **   argv[5]   -> type of fts5vocab table
226879  */
226880  static int fts5VocabInitVtab(
226881    sqlite3 *db,                    /* The SQLite database connection */
226882    void *pAux,                     /* Pointer to Fts5Global object */
226883    int argc,                       /* Number of elements in argv array */
226884    const char * const *argv,       /* xCreate/xConnect argument array */
226885    sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
226886    char **pzErr                    /* Write any error message here */
226887  ){
226888    const char *azSchema[] = { 
226889      "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")", 
226890      "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")",
226891      "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
226892    };
226893  
226894    Fts5VocabTable *pRet = 0;
226895    int rc = SQLITE_OK;             /* Return code */
226896    int bDb;
226897  
226898    bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
226899  
226900    if( argc!=5 && bDb==0 ){
226901      *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
226902      rc = SQLITE_ERROR;
226903    }else{
226904      int nByte;                      /* Bytes of space to allocate */
226905      const char *zDb = bDb ? argv[3] : argv[1];
226906      const char *zTab = bDb ? argv[4] : argv[3];
226907      const char *zType = bDb ? argv[5] : argv[4];
226908      int nDb = (int)strlen(zDb)+1; 
226909      int nTab = (int)strlen(zTab)+1;
226910      int eType = 0;
226911      
226912      rc = fts5VocabTableType(zType, pzErr, &eType);
226913      if( rc==SQLITE_OK ){
226914        assert( eType>=0 && eType<ArraySize(azSchema) );
226915        rc = sqlite3_declare_vtab(db, azSchema[eType]);
226916      }
226917  
226918      nByte = sizeof(Fts5VocabTable) + nDb + nTab;
226919      pRet = sqlite3Fts5MallocZero(&rc, nByte);
226920      if( pRet ){
226921        pRet->pGlobal = (Fts5Global*)pAux;
226922        pRet->eType = eType;
226923        pRet->db = db;
226924        pRet->zFts5Tbl = (char*)&pRet[1];
226925        pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
226926        memcpy(pRet->zFts5Tbl, zTab, nTab);
226927        memcpy(pRet->zFts5Db, zDb, nDb);
226928        sqlite3Fts5Dequote(pRet->zFts5Tbl);
226929        sqlite3Fts5Dequote(pRet->zFts5Db);
226930      }
226931    }
226932  
226933    *ppVTab = (sqlite3_vtab*)pRet;
226934    return rc;
226935  }
226936  
226937  
226938  /*
226939  ** The xConnect() and xCreate() methods for the virtual table. All the
226940  ** work is done in function fts5VocabInitVtab().
226941  */
226942  static int fts5VocabConnectMethod(
226943    sqlite3 *db,                    /* Database connection */
226944    void *pAux,                     /* Pointer to tokenizer hash table */
226945    int argc,                       /* Number of elements in argv array */
226946    const char * const *argv,       /* xCreate/xConnect argument array */
226947    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
226948    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
226949  ){
226950    return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
226951  }
226952  static int fts5VocabCreateMethod(
226953    sqlite3 *db,                    /* Database connection */
226954    void *pAux,                     /* Pointer to tokenizer hash table */
226955    int argc,                       /* Number of elements in argv array */
226956    const char * const *argv,       /* xCreate/xConnect argument array */
226957    sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
226958    char **pzErr                    /* OUT: sqlite3_malloc'd error message */
226959  ){
226960    return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
226961  }
226962  
226963  /* 
226964  ** Implementation of the xBestIndex method.
226965  **
226966  ** Only constraints of the form:
226967  **
226968  **     term <= ?
226969  **     term == ?
226970  **     term >= ?
226971  **
226972  ** are interpreted. Less-than and less-than-or-equal are treated 
226973  ** identically, as are greater-than and greater-than-or-equal.
226974  */
226975  static int fts5VocabBestIndexMethod(
226976    sqlite3_vtab *pUnused,
226977    sqlite3_index_info *pInfo
226978  ){
226979    int i;
226980    int iTermEq = -1;
226981    int iTermGe = -1;
226982    int iTermLe = -1;
226983    int idxNum = 0;
226984    int nArg = 0;
226985  
226986    UNUSED_PARAM(pUnused);
226987  
226988    for(i=0; i<pInfo->nConstraint; i++){
226989      struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
226990      if( p->usable==0 ) continue;
226991      if( p->iColumn==0 ){          /* term column */
226992        if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
226993        if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
226994        if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
226995        if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
226996        if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
226997      }
226998    }
226999  
227000    if( iTermEq>=0 ){
227001      idxNum |= FTS5_VOCAB_TERM_EQ;
227002      pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
227003      pInfo->estimatedCost = 100;
227004    }else{
227005      pInfo->estimatedCost = 1000000;
227006      if( iTermGe>=0 ){
227007        idxNum |= FTS5_VOCAB_TERM_GE;
227008        pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
227009        pInfo->estimatedCost = pInfo->estimatedCost / 2;
227010      }
227011      if( iTermLe>=0 ){
227012        idxNum |= FTS5_VOCAB_TERM_LE;
227013        pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
227014        pInfo->estimatedCost = pInfo->estimatedCost / 2;
227015      }
227016    }
227017  
227018    /* This virtual table always delivers results in ascending order of
227019    ** the "term" column (column 0). So if the user has requested this
227020    ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
227021    ** sqlite3_index_info.orderByConsumed flag to tell the core the results
227022    ** are already in sorted order.  */
227023    if( pInfo->nOrderBy==1 
227024     && pInfo->aOrderBy[0].iColumn==0 
227025     && pInfo->aOrderBy[0].desc==0
227026    ){
227027      pInfo->orderByConsumed = 1;
227028    }
227029  
227030    pInfo->idxNum = idxNum;
227031    return SQLITE_OK;
227032  }
227033  
227034  /*
227035  ** Implementation of xOpen method.
227036  */
227037  static int fts5VocabOpenMethod(
227038    sqlite3_vtab *pVTab, 
227039    sqlite3_vtab_cursor **ppCsr
227040  ){
227041    Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
227042    Fts5Table *pFts5 = 0;
227043    Fts5VocabCursor *pCsr = 0;
227044    int rc = SQLITE_OK;
227045    sqlite3_stmt *pStmt = 0;
227046    char *zSql = 0;
227047  
227048    zSql = sqlite3Fts5Mprintf(&rc,
227049        "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
227050        pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
227051    );
227052    if( zSql ){
227053      rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
227054    }
227055    sqlite3_free(zSql);
227056    assert( rc==SQLITE_OK || pStmt==0 );
227057    if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
227058  
227059    if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
227060      i64 iId = sqlite3_column_int64(pStmt, 0);
227061      pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
227062    }
227063  
227064    if( rc==SQLITE_OK ){
227065      if( pFts5==0 ){
227066        rc = sqlite3_finalize(pStmt);
227067        pStmt = 0;
227068        if( rc==SQLITE_OK ){
227069          pVTab->zErrMsg = sqlite3_mprintf(
227070              "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
227071              );
227072          rc = SQLITE_ERROR;
227073        }
227074      }else{
227075        rc = sqlite3Fts5FlushToDisk(pFts5);
227076      }
227077    }
227078  
227079    if( rc==SQLITE_OK ){
227080      int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
227081      pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
227082    }
227083  
227084    if( pCsr ){
227085      pCsr->pFts5 = pFts5;
227086      pCsr->pStmt = pStmt;
227087      pCsr->aCnt = (i64*)&pCsr[1];
227088      pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
227089    }else{
227090      sqlite3_finalize(pStmt);
227091    }
227092  
227093    *ppCsr = (sqlite3_vtab_cursor*)pCsr;
227094    return rc;
227095  }
227096  
227097  static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
227098    pCsr->rowid = 0;
227099    sqlite3Fts5IterClose(pCsr->pIter);
227100    pCsr->pIter = 0;
227101    sqlite3_free(pCsr->zLeTerm);
227102    pCsr->nLeTerm = -1;
227103    pCsr->zLeTerm = 0;
227104    pCsr->bEof = 0;
227105  }
227106  
227107  /*
227108  ** Close the cursor.  For additional information see the documentation
227109  ** on the xClose method of the virtual table interface.
227110  */
227111  static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
227112    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227113    fts5VocabResetCursor(pCsr);
227114    sqlite3Fts5BufferFree(&pCsr->term);
227115    sqlite3_finalize(pCsr->pStmt);
227116    sqlite3_free(pCsr);
227117    return SQLITE_OK;
227118  }
227119  
227120  static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
227121    int rc = SQLITE_OK;
227122    
227123    if( sqlite3Fts5IterEof(pCsr->pIter) ){
227124      pCsr->bEof = 1;
227125    }else{
227126      const char *zTerm;
227127      int nTerm;
227128      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
227129      if( pCsr->nLeTerm>=0 ){
227130        int nCmp = MIN(nTerm, pCsr->nLeTerm);
227131        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
227132        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
227133          pCsr->bEof = 1;
227134        }
227135      }
227136  
227137      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
227138    }
227139    return rc;
227140  }
227141  
227142  static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
227143    int eDetail = pCsr->pFts5->pConfig->eDetail;
227144    int rc = SQLITE_OK;
227145    Fts5IndexIter *pIter = pCsr->pIter;
227146    i64 *pp = &pCsr->iInstPos;
227147    int *po = &pCsr->iInstOff;
227148    
227149    assert( sqlite3Fts5IterEof(pIter)==0 );
227150    assert( pCsr->bEof==0 );
227151    while( eDetail==FTS5_DETAIL_NONE
227152        || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp) 
227153    ){
227154      pCsr->iInstPos = 0;
227155      pCsr->iInstOff = 0;
227156  
227157      rc = sqlite3Fts5IterNextScan(pCsr->pIter);
227158      if( rc==SQLITE_OK ){
227159        rc = fts5VocabInstanceNewTerm(pCsr);
227160        if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
227161      }
227162      if( rc ){
227163        pCsr->bEof = 1;
227164        break;
227165      }
227166    }
227167  
227168    return rc;
227169  }
227170  
227171  /*
227172  ** Advance the cursor to the next row in the table.
227173  */
227174  static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
227175    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227176    Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
227177    int rc = SQLITE_OK;
227178    int nCol = pCsr->pFts5->pConfig->nCol;
227179  
227180    pCsr->rowid++;
227181  
227182    if( pTab->eType==FTS5_VOCAB_INSTANCE ){
227183      return fts5VocabInstanceNext(pCsr);
227184    }
227185  
227186    if( pTab->eType==FTS5_VOCAB_COL ){
227187      for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
227188        if( pCsr->aDoc[pCsr->iCol] ) break;
227189      }
227190    }
227191  
227192    if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
227193      if( sqlite3Fts5IterEof(pCsr->pIter) ){
227194        pCsr->bEof = 1;
227195      }else{
227196        const char *zTerm;
227197        int nTerm;
227198  
227199        zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
227200        assert( nTerm>=0 );
227201        if( pCsr->nLeTerm>=0 ){
227202          int nCmp = MIN(nTerm, pCsr->nLeTerm);
227203          int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
227204          if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
227205            pCsr->bEof = 1;
227206            return SQLITE_OK;
227207          }
227208        }
227209  
227210        sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
227211        memset(pCsr->aCnt, 0, nCol * sizeof(i64));
227212        memset(pCsr->aDoc, 0, nCol * sizeof(i64));
227213        pCsr->iCol = 0;
227214  
227215        assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
227216        while( rc==SQLITE_OK ){
227217          int eDetail = pCsr->pFts5->pConfig->eDetail;
227218          const u8 *pPos; int nPos;   /* Position list */
227219          i64 iPos = 0;               /* 64-bit position read from poslist */
227220          int iOff = 0;               /* Current offset within position list */
227221  
227222          pPos = pCsr->pIter->pData;
227223          nPos = pCsr->pIter->nData;
227224  
227225          switch( pTab->eType ){
227226            case FTS5_VOCAB_ROW:
227227              if( eDetail==FTS5_DETAIL_FULL ){
227228                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
227229                  pCsr->aCnt[0]++;
227230                }
227231              }
227232              pCsr->aDoc[0]++;
227233              break;
227234  
227235            case FTS5_VOCAB_COL:
227236              if( eDetail==FTS5_DETAIL_FULL ){
227237                int iCol = -1;
227238                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
227239                  int ii = FTS5_POS2COLUMN(iPos);
227240                  if( iCol!=ii ){
227241                    if( ii>=nCol ){
227242                      rc = FTS5_CORRUPT;
227243                      break;
227244                    }
227245                    pCsr->aDoc[ii]++;
227246                    iCol = ii;
227247                  }
227248                  pCsr->aCnt[ii]++;
227249                }
227250              }else if( eDetail==FTS5_DETAIL_COLUMNS ){
227251                while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
227252                  assert_nc( iPos>=0 && iPos<nCol );
227253                  if( iPos>=nCol ){
227254                    rc = FTS5_CORRUPT;
227255                    break;
227256                  }
227257                  pCsr->aDoc[iPos]++;
227258                }
227259              }else{
227260                assert( eDetail==FTS5_DETAIL_NONE );
227261                pCsr->aDoc[0]++;
227262              }
227263              break;
227264  
227265            default:
227266              assert( pTab->eType==FTS5_VOCAB_INSTANCE );
227267              break;
227268          }
227269  
227270          if( rc==SQLITE_OK ){
227271            rc = sqlite3Fts5IterNextScan(pCsr->pIter);
227272          }
227273          if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
227274  
227275          if( rc==SQLITE_OK ){
227276            zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
227277            if( nTerm!=pCsr->term.n 
227278            || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm)) 
227279            ){
227280              break;
227281            }
227282            if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
227283          }
227284        }
227285      }
227286    }
227287  
227288    if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
227289      while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
227290      assert( pCsr->iCol<pCsr->pFts5->pConfig->nCol );
227291    }
227292    return rc;
227293  }
227294  
227295  /*
227296  ** This is the xFilter implementation for the virtual table.
227297  */
227298  static int fts5VocabFilterMethod(
227299    sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
227300    int idxNum,                     /* Strategy index */
227301    const char *zUnused,            /* Unused */
227302    int nUnused,                    /* Number of elements in apVal */
227303    sqlite3_value **apVal           /* Arguments for the indexing scheme */
227304  ){
227305    Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
227306    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227307    int eType = pTab->eType;
227308    int rc = SQLITE_OK;
227309  
227310    int iVal = 0;
227311    int f = FTS5INDEX_QUERY_SCAN;
227312    const char *zTerm = 0;
227313    int nTerm = 0;
227314  
227315    sqlite3_value *pEq = 0;
227316    sqlite3_value *pGe = 0;
227317    sqlite3_value *pLe = 0;
227318  
227319    UNUSED_PARAM2(zUnused, nUnused);
227320  
227321    fts5VocabResetCursor(pCsr);
227322    if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
227323    if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
227324    if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
227325  
227326    if( pEq ){
227327      zTerm = (const char *)sqlite3_value_text(pEq);
227328      nTerm = sqlite3_value_bytes(pEq);
227329      f = 0;
227330    }else{
227331      if( pGe ){
227332        zTerm = (const char *)sqlite3_value_text(pGe);
227333        nTerm = sqlite3_value_bytes(pGe);
227334      }
227335      if( pLe ){
227336        const char *zCopy = (const char *)sqlite3_value_text(pLe);
227337        if( zCopy==0 ) zCopy = "";
227338        pCsr->nLeTerm = sqlite3_value_bytes(pLe);
227339        pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
227340        if( pCsr->zLeTerm==0 ){
227341          rc = SQLITE_NOMEM;
227342        }else{
227343          memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
227344        }
227345      }
227346    }
227347  
227348    if( rc==SQLITE_OK ){
227349      Fts5Index *pIndex = pCsr->pFts5->pIndex;
227350      rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
227351    }
227352    if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
227353      rc = fts5VocabInstanceNewTerm(pCsr);
227354    }
227355    if( rc==SQLITE_OK && !pCsr->bEof 
227356     && (eType!=FTS5_VOCAB_INSTANCE 
227357      || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
227358    ){
227359      rc = fts5VocabNextMethod(pCursor);
227360    }
227361  
227362    return rc;
227363  }
227364  
227365  /* 
227366  ** This is the xEof method of the virtual table. SQLite calls this 
227367  ** routine to find out if it has reached the end of a result set.
227368  */
227369  static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
227370    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227371    return pCsr->bEof;
227372  }
227373  
227374  static int fts5VocabColumnMethod(
227375    sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
227376    sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
227377    int iCol                        /* Index of column to read value from */
227378  ){
227379    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227380    int eDetail = pCsr->pFts5->pConfig->eDetail;
227381    int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
227382    i64 iVal = 0;
227383  
227384    if( iCol==0 ){
227385      sqlite3_result_text(
227386          pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
227387      );
227388    }else if( eType==FTS5_VOCAB_COL ){
227389      assert( iCol==1 || iCol==2 || iCol==3 );
227390      if( iCol==1 ){
227391        if( eDetail!=FTS5_DETAIL_NONE ){
227392          const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
227393          sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
227394        }
227395      }else if( iCol==2 ){
227396        iVal = pCsr->aDoc[pCsr->iCol];
227397      }else{
227398        iVal = pCsr->aCnt[pCsr->iCol];
227399      }
227400    }else if( eType==FTS5_VOCAB_ROW ){
227401      assert( iCol==1 || iCol==2 );
227402      if( iCol==1 ){
227403        iVal = pCsr->aDoc[0];
227404      }else{
227405        iVal = pCsr->aCnt[0];
227406      }
227407    }else{
227408      assert( eType==FTS5_VOCAB_INSTANCE );
227409      switch( iCol ){
227410        case 1:
227411          sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
227412          break;
227413        case 2: {
227414          int ii = -1;
227415          if( eDetail==FTS5_DETAIL_FULL ){
227416            ii = FTS5_POS2COLUMN(pCsr->iInstPos);
227417          }else if( eDetail==FTS5_DETAIL_COLUMNS ){
227418            ii = (int)pCsr->iInstPos;
227419          }
227420          if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
227421            const char *z = pCsr->pFts5->pConfig->azCol[ii];
227422            sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
227423          }
227424          break;
227425        }
227426        default: {
227427          assert( iCol==3 );
227428          if( eDetail==FTS5_DETAIL_FULL ){
227429            int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
227430            sqlite3_result_int(pCtx, ii);
227431          }
227432          break;
227433        }
227434      }
227435    }
227436  
227437    if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
227438    return SQLITE_OK;
227439  }
227440  
227441  /* 
227442  ** This is the xRowid method. The SQLite core calls this routine to
227443  ** retrieve the rowid for the current row of the result set. The
227444  ** rowid should be written to *pRowid.
227445  */
227446  static int fts5VocabRowidMethod(
227447    sqlite3_vtab_cursor *pCursor, 
227448    sqlite_int64 *pRowid
227449  ){
227450    Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
227451    *pRowid = pCsr->rowid;
227452    return SQLITE_OK;
227453  }
227454  
227455  static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
227456    static const sqlite3_module fts5Vocab = {
227457      /* iVersion      */ 2,
227458      /* xCreate       */ fts5VocabCreateMethod,
227459      /* xConnect      */ fts5VocabConnectMethod,
227460      /* xBestIndex    */ fts5VocabBestIndexMethod,
227461      /* xDisconnect   */ fts5VocabDisconnectMethod,
227462      /* xDestroy      */ fts5VocabDestroyMethod,
227463      /* xOpen         */ fts5VocabOpenMethod,
227464      /* xClose        */ fts5VocabCloseMethod,
227465      /* xFilter       */ fts5VocabFilterMethod,
227466      /* xNext         */ fts5VocabNextMethod,
227467      /* xEof          */ fts5VocabEofMethod,
227468      /* xColumn       */ fts5VocabColumnMethod,
227469      /* xRowid        */ fts5VocabRowidMethod,
227470      /* xUpdate       */ 0,
227471      /* xBegin        */ 0,
227472      /* xSync         */ 0,
227473      /* xCommit       */ 0,
227474      /* xRollback     */ 0,
227475      /* xFindFunction */ 0,
227476      /* xRename       */ 0,
227477      /* xSavepoint    */ 0,
227478      /* xRelease      */ 0,
227479      /* xRollbackTo   */ 0,
227480      /* xShadowName   */ 0
227481    };
227482    void *p = (void*)pGlobal;
227483  
227484    return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
227485  }
227486  
227487  
227488      
227489  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
227490  
227491  /************** End of fts5.c ************************************************/
227492  /************** Begin file stmt.c ********************************************/
227493  /*
227494  ** 2017-05-31
227495  **
227496  ** The author disclaims copyright to this source code.  In place of
227497  ** a legal notice, here is a blessing:
227498  **
227499  **    May you do good and not evil.
227500  **    May you find forgiveness for yourself and forgive others.
227501  **    May you share freely, never taking more than you give.
227502  **
227503  *************************************************************************
227504  **
227505  ** This file demonstrates an eponymous virtual table that returns information
227506  ** about all prepared statements for the database connection.
227507  **
227508  ** Usage example:
227509  **
227510  **     .load ./stmt
227511  **     .mode line
227512  **     .header on
227513  **     SELECT * FROM stmt;
227514  */
227515  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
227516  #if !defined(SQLITEINT_H)
227517  /* #include "sqlite3ext.h" */
227518  #endif
227519  SQLITE_EXTENSION_INIT1
227520  /* #include <assert.h> */
227521  /* #include <string.h> */
227522  
227523  #ifndef SQLITE_OMIT_VIRTUALTABLE
227524  
227525  /* stmt_vtab is a subclass of sqlite3_vtab which will
227526  ** serve as the underlying representation of a stmt virtual table
227527  */
227528  typedef struct stmt_vtab stmt_vtab;
227529  struct stmt_vtab {
227530    sqlite3_vtab base;  /* Base class - must be first */
227531    sqlite3 *db;        /* Database connection for this stmt vtab */
227532  };
227533  
227534  /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
227535  ** serve as the underlying representation of a cursor that scans
227536  ** over rows of the result
227537  */
227538  typedef struct stmt_cursor stmt_cursor;
227539  struct stmt_cursor {
227540    sqlite3_vtab_cursor base;  /* Base class - must be first */
227541    sqlite3 *db;               /* Database connection for this cursor */
227542    sqlite3_stmt *pStmt;       /* Statement cursor is currently pointing at */
227543    sqlite3_int64 iRowid;      /* The rowid */
227544  };
227545  
227546  /*
227547  ** The stmtConnect() method is invoked to create a new
227548  ** stmt_vtab that describes the stmt virtual table.
227549  **
227550  ** Think of this routine as the constructor for stmt_vtab objects.
227551  **
227552  ** All this routine needs to do is:
227553  **
227554  **    (1) Allocate the stmt_vtab object and initialize all fields.
227555  **
227556  **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
227557  **        result set of queries against stmt will look like.
227558  */
227559  static int stmtConnect(
227560    sqlite3 *db,
227561    void *pAux,
227562    int argc, const char *const*argv,
227563    sqlite3_vtab **ppVtab,
227564    char **pzErr
227565  ){
227566    stmt_vtab *pNew;
227567    int rc;
227568  
227569  /* Column numbers */
227570  #define STMT_COLUMN_SQL     0   /* SQL for the statement */
227571  #define STMT_COLUMN_NCOL    1   /* Number of result columns */
227572  #define STMT_COLUMN_RO      2   /* True if read-only */
227573  #define STMT_COLUMN_BUSY    3   /* True if currently busy */
227574  #define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
227575  #define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */
227576  #define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */
227577  #define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */
227578  #define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */
227579  #define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */
227580  #define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */
227581  
227582  
227583    rc = sqlite3_declare_vtab(db,
227584       "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
227585                      "reprep,run,mem)");
227586    if( rc==SQLITE_OK ){
227587      pNew = sqlite3_malloc( sizeof(*pNew) );
227588      *ppVtab = (sqlite3_vtab*)pNew;
227589      if( pNew==0 ) return SQLITE_NOMEM;
227590      memset(pNew, 0, sizeof(*pNew));
227591      pNew->db = db;
227592    }
227593    return rc;
227594  }
227595  
227596  /*
227597  ** This method is the destructor for stmt_cursor objects.
227598  */
227599  static int stmtDisconnect(sqlite3_vtab *pVtab){
227600    sqlite3_free(pVtab);
227601    return SQLITE_OK;
227602  }
227603  
227604  /*
227605  ** Constructor for a new stmt_cursor object.
227606  */
227607  static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
227608    stmt_cursor *pCur;
227609    pCur = sqlite3_malloc( sizeof(*pCur) );
227610    if( pCur==0 ) return SQLITE_NOMEM;
227611    memset(pCur, 0, sizeof(*pCur));
227612    pCur->db = ((stmt_vtab*)p)->db;
227613    *ppCursor = &pCur->base;
227614    return SQLITE_OK;
227615  }
227616  
227617  /*
227618  ** Destructor for a stmt_cursor.
227619  */
227620  static int stmtClose(sqlite3_vtab_cursor *cur){
227621    sqlite3_free(cur);
227622    return SQLITE_OK;
227623  }
227624  
227625  
227626  /*
227627  ** Advance a stmt_cursor to its next row of output.
227628  */
227629  static int stmtNext(sqlite3_vtab_cursor *cur){
227630    stmt_cursor *pCur = (stmt_cursor*)cur;
227631    pCur->iRowid++;
227632    pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
227633    return SQLITE_OK;
227634  }
227635  
227636  /*
227637  ** Return values of columns for the row at which the stmt_cursor
227638  ** is currently pointing.
227639  */
227640  static int stmtColumn(
227641    sqlite3_vtab_cursor *cur,   /* The cursor */
227642    sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
227643    int i                       /* Which column to return */
227644  ){
227645    stmt_cursor *pCur = (stmt_cursor*)cur;
227646    switch( i ){
227647      case STMT_COLUMN_SQL: {
227648        sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
227649        break;
227650      }
227651      case STMT_COLUMN_NCOL: {
227652        sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
227653        break;
227654      }
227655      case STMT_COLUMN_RO: {
227656        sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
227657        break;
227658      }
227659      case STMT_COLUMN_BUSY: {
227660        sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
227661        break;
227662      }
227663      case STMT_COLUMN_MEM: {
227664        i = SQLITE_STMTSTATUS_MEMUSED + 
227665              STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
227666        /* Fall thru */
227667      }
227668      case STMT_COLUMN_NSCAN:
227669      case STMT_COLUMN_NSORT:
227670      case STMT_COLUMN_NAIDX:
227671      case STMT_COLUMN_NSTEP:
227672      case STMT_COLUMN_REPREP:
227673      case STMT_COLUMN_RUN: {
227674        sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
227675                        i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
227676        break;
227677      }
227678    }
227679    return SQLITE_OK;
227680  }
227681  
227682  /*
227683  ** Return the rowid for the current row.  In this implementation, the
227684  ** rowid is the same as the output value.
227685  */
227686  static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
227687    stmt_cursor *pCur = (stmt_cursor*)cur;
227688    *pRowid = pCur->iRowid;
227689    return SQLITE_OK;
227690  }
227691  
227692  /*
227693  ** Return TRUE if the cursor has been moved off of the last
227694  ** row of output.
227695  */
227696  static int stmtEof(sqlite3_vtab_cursor *cur){
227697    stmt_cursor *pCur = (stmt_cursor*)cur;
227698    return pCur->pStmt==0;
227699  }
227700  
227701  /*
227702  ** This method is called to "rewind" the stmt_cursor object back
227703  ** to the first row of output.  This method is always called at least
227704  ** once prior to any call to stmtColumn() or stmtRowid() or 
227705  ** stmtEof().
227706  */
227707  static int stmtFilter(
227708    sqlite3_vtab_cursor *pVtabCursor, 
227709    int idxNum, const char *idxStr,
227710    int argc, sqlite3_value **argv
227711  ){
227712    stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
227713    pCur->pStmt = 0;
227714    pCur->iRowid = 0;
227715    return stmtNext(pVtabCursor);
227716  }
227717  
227718  /*
227719  ** SQLite will invoke this method one or more times while planning a query
227720  ** that uses the stmt virtual table.  This routine needs to create
227721  ** a query plan for each invocation and compute an estimated cost for that
227722  ** plan.
227723  */
227724  static int stmtBestIndex(
227725    sqlite3_vtab *tab,
227726    sqlite3_index_info *pIdxInfo
227727  ){
227728    pIdxInfo->estimatedCost = (double)500;
227729    pIdxInfo->estimatedRows = 500;
227730    return SQLITE_OK;
227731  }
227732  
227733  /*
227734  ** This following structure defines all the methods for the 
227735  ** stmt virtual table.
227736  */
227737  static sqlite3_module stmtModule = {
227738    0,                         /* iVersion */
227739    0,                         /* xCreate */
227740    stmtConnect,               /* xConnect */
227741    stmtBestIndex,             /* xBestIndex */
227742    stmtDisconnect,            /* xDisconnect */
227743    0,                         /* xDestroy */
227744    stmtOpen,                  /* xOpen - open a cursor */
227745    stmtClose,                 /* xClose - close a cursor */
227746    stmtFilter,                /* xFilter - configure scan constraints */
227747    stmtNext,                  /* xNext - advance a cursor */
227748    stmtEof,                   /* xEof - check for end of scan */
227749    stmtColumn,                /* xColumn - read data */
227750    stmtRowid,                 /* xRowid - read data */
227751    0,                         /* xUpdate */
227752    0,                         /* xBegin */
227753    0,                         /* xSync */
227754    0,                         /* xCommit */
227755    0,                         /* xRollback */
227756    0,                         /* xFindMethod */
227757    0,                         /* xRename */
227758    0,                         /* xSavepoint */
227759    0,                         /* xRelease */
227760    0,                         /* xRollbackTo */
227761    0,                         /* xShadowName */
227762  };
227763  
227764  #endif /* SQLITE_OMIT_VIRTUALTABLE */
227765  
227766  SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
227767    int rc = SQLITE_OK;
227768  #ifndef SQLITE_OMIT_VIRTUALTABLE
227769    rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
227770  #endif
227771    return rc;
227772  }
227773  
227774  #ifndef SQLITE_CORE
227775  #ifdef _WIN32
227776  __declspec(dllexport)
227777  #endif
227778  SQLITE_API int sqlite3_stmt_init(
227779    sqlite3 *db, 
227780    char **pzErrMsg, 
227781    const sqlite3_api_routines *pApi
227782  ){
227783    int rc = SQLITE_OK;
227784    SQLITE_EXTENSION_INIT2(pApi);
227785  #ifndef SQLITE_OMIT_VIRTUALTABLE
227786    rc = sqlite3StmtVtabInit(db);
227787  #endif
227788    return rc;
227789  }
227790  #endif /* SQLITE_CORE */
227791  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
227792  
227793  /************** End of stmt.c ************************************************/
227794  #if __LINE__!=221831
227795  #undef SQLITE_SOURCE_ID
227796  #define SQLITE_SOURCE_ID      "2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0alt2"
227797  #endif
227798  /* Return the source-id for this library */
227799  SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
227800  /************************** End of sqlite3.c ******************************/
227801  
227802  
227803  
227804  /*****************************************************************************/
227805  /*** BRANCHING SUPPORT *******************************************************/
227806  /*****************************************************************************/
227807  
227808  /*
227809  ** Returns the Btree from the given db connection and db index
227810  */
227811  SQLITE_PRIVATE Btree * getBtreeFromiDb(sqlite3 *db, int iDb) {
227812    if( !db || iDb<0 || iDb>db->nDb ) return NULL;
227813    return db->aDb[iDb].pBt;
227814  }
227815  
227816  /*
227817  ** Returns the pager associated with a Btree
227818  */
227819  SQLITE_PRIVATE Pager * getPagerFromBtree(Btree *pBtree) {
227820    if( !pBtree || !pBtree->pBt ) return NULL;
227821    return pBtree->pBt->pPager;
227822  }
227823  
227824  /*
227825  ** Returns the Pager from the given db connection and db index
227826  */
227827  SQLITE_PRIVATE Pager * getPagerFromiDb(sqlite3 *db, int iDb) {
227828    Btree *pBtree = getBtreeFromiDb(db, iDb);
227829    return getPagerFromBtree(pBtree);
227830  }
227831  
227832  /****************************************************************************/
227833  
227834  SQLITE_PRIVATE int getDbFromName(sqlite3 *db, const char *name) {
227835    int i;
227836    if( db==NULL || db->magic!=SQLITE_MAGIC_OPEN || db->aDb==NULL ) return -1;
227837    if( name==NULL || name[0]=='\0' ) name = "main";
227838    for (i=0; i < db->nDb; i++) {
227839      if( sqlite3StrICmp(db->aDb[i].zDbSName, name)==0 ){
227840        return i;
227841      }
227842    }
227843    return -1;
227844  }
227845  
227846  /****************************************************************************/
227847  
227848  SQLITE_PRIVATE Btree * getBtree(sqlite3 *db, const char *name) {
227849    int nDb = getDbFromName(db,name);
227850    if( nDb<0 ) return NULL;
227851    return db->aDb[nDb].pBt;
227852  }
227853  
227854  /****************************************************************************/
227855  
227856  SQLITE_PRIVATE Pager * getPager(sqlite3 *db, const char *name) {
227857    Btree *p = getBtree(db, name);
227858    if( p==NULL || p->pBt==NULL ) return NULL;
227859      return p->pBt->pPager;
227860  }
227861  
227862  /****************************************************************************/
227863  
227864  #ifdef UNUSED_FUNCTION
227865  SQLITE_PRIVATE void jsonAppendInt(JsonString *p, int value){
227866    char buf[64];
227867    sqlite3_snprintf(sizeof(buf), buf, "%d", value);
227868    jsonAppendRaw(p, buf, strlen(buf));
227869  }
227870  
227871  SQLITE_PRIVATE void jsonAppendU32(JsonString *p, u32 value){
227872    char buf[64];
227873    sqlite3_snprintf(sizeof(buf), buf, "%u", value);
227874    jsonAppendRaw(p, buf, strlen(buf));
227875  }
227876  #endif
227877  
227878  SQLITE_PRIVATE void jsonAppendU64(JsonString *p, u64 value){
227879    char buf[64];
227880    sqlite3_snprintf(sizeof(buf), buf, "%llu", value);
227881    jsonAppendRaw(p, buf, strlen(buf));
227882  }
227883  
227884  /*
227885  ** PRAGMA commands -----------------------------------------------------------
227886  */
227887  
227888  SQLITE_PRIVATE char * pragma_get_branch_list(lmdb *lmdb){
227889    JsonString jx;
227890    int i;
227891  
227892    jsonInit(&jx, NULL);
227893    jsonAppendChar(&jx, '[');
227894  
227895    for( i=1; i <= lmdb->num_branches; i++ ){
227896      if( lmdb->branches[i].visible ){
227897        char *value = lmdb->branches[i].name;
227898        if( i>1 ) jsonAppendSeparator(&jx);
227899        jsonAppendString(&jx, value, strlen(value));
227900      }
227901    }
227902  
227903    jsonAppendChar(&jx, ']');
227904    jsonAppendChar(&jx, 0);  /* null terminator */
227905  
227906    if( jx.bStatic ){
227907      jx.zBuf = sqlite3_strdup(jx.zBuf);
227908    }
227909    return jx.zBuf;
227910  }
227911  
227912  /*
227913  
227914  {
227915  source_branch: "new-feat",
227916  source_commit: 7,
227917  total_commits: 15;
227918  this_branch_commits: 8    (15 - 7)  maybe not needed
227919  }
227920  
227921  for the master branch:
227922  
227923  {
227924  total_commits: 15;
227925  }
227926  
227927  */
227928  SQLITE_PRIVATE char * pragma_get_branch_info(sqlite3 *db, int iDb, char *name){
227929    Btree *pBtree = getBtreeFromiDb(db, iDb);
227930    Pager *pPager = getPagerFromBtree(pBtree);
227931    branch_info *branch;
227932    lmdb *lmdb;
227933    JsonString jx;
227934    char *value;
227935    int id;
227936  
227937    BRANCHTRACE("pragma_get_branch_info: %s", name);
227938  
227939    if( !pPager || !pPager->lmdb ) return NULL;
227940    lmdb = pPager->lmdb;
227941  
227942    /* if the db is being accessed by many db connections */
227943    if( !lmdb->singleConnection ){
227944      /* check if the db was modified in another db connection */
227945      sqlite3BranchCheckReloadDb(pPager, 0);
227946    }
227947  
227948    id = sqlite3BranchFind(lmdb, name);
227949    if( id<=0 ) return NULL;
227950    branch = &lmdb->branches[id];
227951  
227952    jsonInit(&jx, NULL);
227953    jsonAppendChar(&jx, '{');
227954    jsonAppendChar(&jx, '\n');
227955  
227956    if( branch->source_branch > 0 ){
227957      value = "source_branch";
227958      jsonAppendString(&jx, value, strlen(value));
227959      jsonAppendRaw(&jx, ": ", 2);
227960      value = lmdb->branches[branch->source_branch].name;
227961      jsonAppendString(&jx, value, strlen(value));
227962  
227963      jsonAppendSeparator(&jx);
227964      jsonAppendChar(&jx, '\n');
227965  
227966      value = "source_commit";
227967      jsonAppendString(&jx, value, strlen(value));
227968      jsonAppendRaw(&jx, ": ", 2);
227969      jsonAppendU64(&jx, branch->source_commit);
227970  
227971      jsonAppendSeparator(&jx);
227972      jsonAppendChar(&jx, '\n');
227973    }
227974  
227975    value = "total_commits";
227976    jsonAppendString(&jx, value, strlen(value));
227977    jsonAppendRaw(&jx, ": ", 2);
227978    jsonAppendU64(&jx, branch->last_commit);
227979  
227980    jsonAppendChar(&jx, '\n');
227981    jsonAppendChar(&jx, '}');
227982    jsonAppendChar(&jx, 0);  /* null terminator */
227983  
227984    if( jx.bStatic ){
227985      jx.zBuf = sqlite3_strdup(jx.zBuf);
227986    }
227987    return jx.zBuf;
227988  }
227989  
227990  /*****************************************************************************/
227991  
227992  SQLITE_PRIVATE int enable_branching(sqlite3 *db, const char *name, int useSingleConnection) {
227993    Btree *p = getBtree(db,name);
227994    Pager *pPager = getPager(db,name);
227995    BtShared *pBt;
227996    int nReserve;
227997  
227998    if( !p || !pPager ) return SQLITE_ERROR;
227999    pBt = p->pBt;
228000  
228001    pPager->useBranches = 1;
228002    pPager->journalMode = PAGER_JOURNALMODE_BRANCHES;
228003    if( pPager->lmdb )
228004      pPager->lmdb->singleConnection = useSingleConnection;
228005  
228006    /* set the reserved space on the pages */
228007    nReserve = LMDB_PAGE_RESERVED_SPACE;
228008    if( pBt->pageSize - pBt->usableSize != nReserve ){
228009      db->nextPagesize = pPager->pageSize;  //LMDB_PAGE_SIZE;
228010      return sqlite3BtreeSetPageSize(p,db->nextPagesize,nReserve,0);
228011    }
228012    return SQLITE_OK;
228013  
228014  }
228015  
228016  /*****************************************************************************/
228017  
228018  SQLITE_PRIVATE int process_branch_uri(sqlite3 *db, const char *name, const char *uri) {
228019    char *zActive, *zConn;
228020    int useSingleConnection=0;
228021    int rc=SQLITE_OK;
228022  
228023    zActive = (char*) sqlite3_uri_parameter(uri, "branches");
228024    zConn   = (char*) sqlite3_uri_parameter(uri, "single_connection");
228025  
228026    if( zActive && strcmp(zActive,"on")==0 ){
228027      BRANCHTRACE("BRANCHES: ON");
228028      if( zConn && strcmp(zConn,"true")==0 ) useSingleConnection = 1;
228029      rc = enable_branching(db, name, useSingleConnection);
228030    }
228031  
228032    return rc;
228033  
228034  }